Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ea73c3414 | ||
|
|
b20e514c90 | ||
|
|
fccca5b459 | ||
|
|
a47756795c | ||
|
|
9b2174a097 | ||
|
|
dc7b46aa38 | ||
|
|
a7df502219 | ||
|
|
9b9a1722cd | ||
|
|
8f37ded71e | ||
|
|
eac16ad8a7 | ||
|
|
518a9662a7 | ||
|
|
0edbf60b2e | ||
|
|
bc3a560830 | ||
|
|
c0b921c109 | ||
|
|
e89980f7a0 | ||
|
|
9238c6694b | ||
|
|
d436b064c3 | ||
|
|
b86582e606 | ||
|
|
0c6bf3ec2b | ||
|
|
2fb519a373 | ||
|
|
f64ac4e326 | ||
|
|
0ec8029f17 | ||
|
|
4d86aa8d31 | ||
|
|
5ca465f203 | ||
|
|
f16067d6d0 | ||
|
|
116989a091 | ||
|
|
b171818df5 | ||
|
|
ebea992b10 | ||
|
|
fb1a1c9bb0 | ||
|
|
49e2dab2a6 | ||
|
|
e0e749510a | ||
|
|
a81b3733fa | ||
|
|
4eaddc2d75 | ||
|
|
9ffa1efc26 | ||
|
|
4b533f035a | ||
|
|
b9ad4e1d71 | ||
|
|
aca103cb96 | ||
|
|
c50f8861a4 | ||
|
|
5d4ba73771 | ||
|
|
340eacf527 | ||
|
|
00b55c9cca | ||
|
|
804466aad8 | ||
|
|
d1ee3bbd30 | ||
|
|
7dcda8554e | ||
|
|
6cadcb9a5a | ||
|
|
f47af8024f | ||
|
|
4a4c0eb520 | ||
|
|
05b881d79e | ||
|
|
80e0f43529 | ||
|
|
39753d7784 | ||
|
|
f95e9d491c | ||
|
|
780a19900b | ||
|
|
7e9997cc06 | ||
|
|
8c162969ff | ||
|
|
51c373501a | ||
|
|
9db08dba1a | ||
|
|
49e3fcfb20 | ||
|
|
450668f5e6 | ||
|
|
8804a16ad9 | ||
|
|
d9d0672072 | ||
|
|
a328db687d | ||
|
|
915ee73f95 | ||
|
|
df6388a86d | ||
|
|
695afd7c3e | ||
|
|
049b5a9495 | ||
|
|
43c917a070 | ||
|
|
84737a7407 | ||
|
|
d6d837e6f6 | ||
|
|
443bbc866c | ||
|
|
e17e2d908e | ||
|
|
a0c729374f | ||
|
|
b36311e276 | ||
|
|
9608077b90 | ||
|
|
9ab71bf730 | ||
|
|
52c89bf0c7 | ||
|
|
a799fc1490 | ||
|
|
c366dd1187 | ||
|
|
0d78ad3f54 | ||
|
|
de9f4d311a | ||
|
|
67e4e8f31e | ||
|
|
958dab1ddd | ||
|
|
694d5041bd | ||
|
|
7f3ea4ae6d | ||
|
|
ae0afa65d9 | ||
|
|
72812447fd | ||
|
|
eaa25cd29e | ||
|
|
fd7d5016a8 | ||
|
|
028e8b6553 | ||
|
|
7ce0475b3f | ||
|
|
9564fde04d | ||
|
|
632ec9ee13 | ||
|
|
4d9af4a193 | ||
|
|
e5f0aa59f4 | ||
|
|
ea4d1eabc2 | ||
|
|
108d04f901 | ||
|
|
713232bd62 | ||
|
|
e83e85fe64 | ||
|
|
e5a1656644 | ||
|
|
e24e5fe6e8 | ||
|
|
194dd0035b | ||
|
|
c3629255ea | ||
|
|
345a0db49b | ||
|
|
5276bce060 | ||
|
|
0abbda1160 | ||
|
|
97c74859c0 | ||
|
|
4d5c6459fe | ||
|
|
c835d5c570 | ||
|
|
59872daf52 | ||
|
|
3bd3935042 | ||
|
|
77a6912ade | ||
|
|
4b83aaed61 | ||
|
|
7268188e40 | ||
|
|
8503c92f3a | ||
|
|
069d836dea | ||
|
|
95384a4a92 | ||
|
|
9b82ca663b | ||
|
|
f5633a29cb | ||
|
|
766cd94788 | ||
|
|
b6d287a299 | ||
|
|
4c25236070 | ||
|
|
c1224cb612 | ||
|
|
5036639aa1 | ||
|
|
9593ca0f54 | ||
|
|
b441287d54 | ||
|
|
9b82d29037 | ||
|
|
0f270366aa | ||
|
|
12b8fb34c6 | ||
|
|
774346d503 | ||
|
|
b97e1f4bc6 | ||
|
|
4b2395a8d2 | ||
|
|
1337bcb7de | ||
|
|
b8f08d54c8 | ||
|
|
24399f1d70 | ||
|
|
e6db4de711 | ||
|
|
adff6021fc | ||
|
|
75004375df | ||
|
|
75de616527 | ||
|
|
f5158fd3e4 | ||
|
|
ed4c21a68f | ||
|
|
f35ca1778a | ||
|
|
21b2b57d28 | ||
|
|
67dc45819e | ||
|
|
ff212d594c | ||
|
|
353df30ff8 | ||
|
|
4f8435d0e2 | ||
|
|
389a853560 | ||
|
|
c437be349e | ||
|
|
488966d771 | ||
|
|
00095ae627 | ||
|
|
ffbe78f74a | ||
|
|
7e9a79486e | ||
|
|
4191d4d5f5 | ||
|
|
29c1166eca | ||
|
|
bf78055b69 | ||
|
|
550e3b104c | ||
|
|
cf9ea8a83b | ||
|
|
5efae86fcf | ||
|
|
70c55442f3 | ||
|
|
9288256a5e | ||
|
|
e5bd162a01 | ||
|
|
cef1ad493c | ||
|
|
add16885fe | ||
|
|
ab3b3731b7 | ||
|
|
0c4932d740 | ||
|
|
fe8619d56d | ||
|
|
376ea79ff6 | ||
|
|
dc6d1eb6ac | ||
|
|
532e135406 | ||
|
|
7ae0d63a7f | ||
|
|
c759bcd30e | ||
|
|
0bad419150 | ||
|
|
facc292443 | ||
|
|
7554de7d72 | ||
|
|
1bc66e33fd | ||
|
|
976aac32c5 | ||
|
|
3634f49a48 | ||
|
|
1156362c3c | ||
|
|
60528ffe53 | ||
|
|
f28480ffbe | ||
|
|
8e784d8125 | ||
|
|
3489535750 | ||
|
|
5e268cd8f4 | ||
|
|
454f449c41 | ||
|
|
517e650942 | ||
|
|
21e299942b | ||
|
|
bde3bc537f | ||
|
|
719ffa0a24 | ||
|
|
8fa4dd50e7 | ||
|
|
3462d49516 | ||
|
|
7ef991aa67 | ||
|
|
4d758b2aca | ||
|
|
27f4108cf9 | ||
|
|
e1f4ec79dd | ||
|
|
76e9e683c4 | ||
|
|
7c8b45a24a | ||
|
|
1c8bbae1f0 | ||
|
|
25b72c3d76 | ||
|
|
f65dc4ac32 | ||
|
|
e59332b514 | ||
|
|
6cbf9af662 | ||
|
|
5acfa14475 | ||
|
|
698251796f | ||
|
|
a007e110ac | ||
|
|
7cf043e3c3 | ||
|
|
949e6bc868 | ||
|
|
62abd872ee | ||
|
|
0d68217dda | ||
|
|
ee5f50db83 | ||
|
|
36e709d7a6 | ||
|
|
b26d4dd1a7 | ||
|
|
8f9a0c44da | ||
|
|
5ff67edaef |
No files matched your search
@@ -5,6 +5,9 @@ VITE_DB_KEY=
|
||||
# Set to true/1/yes/on for local development. Default is disabled.
|
||||
VITE_AUTO_LOGIN=false
|
||||
|
||||
# Show the scheduled report debug notification test action. Default is disabled.
|
||||
VITE_SCHEDULED_REPORT_DEBUG=false
|
||||
|
||||
# AI API Configuration (Optional, can be entered in UI)
|
||||
# 注意:发布版本不再自动读取以下环境变量。
|
||||
# 如果你只是本地开发想用默认值,可以在自己机器的 .env.local 里填,
|
||||
|
||||
@@ -15,6 +15,9 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# 版本漂移检查需要与基准分支比较 SKILL.md,浅克隆拿不到基准。
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
@@ -25,16 +28,10 @@ jobs:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: services/wechat-connector/go.mod
|
||||
cache-dependency-path: services/wechat-connector/go.sum
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
run: pnpm install
|
||||
|
||||
- name: Install Playwright Chromium
|
||||
if: runner.os == 'macOS'
|
||||
run: pnpm exec playwright install chromium
|
||||
|
||||
- name: Type check
|
||||
@@ -52,8 +49,8 @@ jobs:
|
||||
- name: Skill installation instruction tests
|
||||
run: pnpm test:skill-install
|
||||
|
||||
- name: WeChat connector tests
|
||||
run: pnpm test:wechat-connector
|
||||
- name: Reader Skill version drift check
|
||||
run: pnpm check:skill-version
|
||||
|
||||
- name: Build Electron test application
|
||||
run: pnpm test:e2e:build
|
||||
@@ -64,6 +61,8 @@ jobs:
|
||||
WXE_E2E_CLOSE_DELAY_MS: 0
|
||||
|
||||
- name: Platform visual regression
|
||||
# GitHub-hosted Windows 无法稳定容纳项目统一的 1400×800 Electron 窗口,Windows visual regression 改由可控 Windows 桌面环境执行。
|
||||
if: matrix.os != 'windows-latest'
|
||||
run: pnpm exec playwright test tests/e2e/visual.spec.ts
|
||||
env:
|
||||
WXE_E2E_CLOSE_DELAY_MS: 0
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
node_modules
|
||||
*.tsbuildinfo
|
||||
electron.vite.config.[0-9]*.mjs
|
||||
dist
|
||||
out
|
||||
.env
|
||||
@@ -9,19 +10,47 @@ out
|
||||
coverage/
|
||||
playwright-report/
|
||||
test-results/
|
||||
resources/connectors/wechat/
|
||||
resources/connectors/wechat-personal/
|
||||
resources/runtime/darwin-arm64
|
||||
.native-runtime-source
|
||||
.omc
|
||||
.codex/
|
||||
services/share-card-worker/.wrangler/
|
||||
services/share-card-worker/wrangler.local.jsonc
|
||||
skills-lock.json
|
||||
docs/design/
|
||||
docs/ui-redesign-plan.md
|
||||
docs/ui-redesign-spec.md
|
||||
AGENTS.md
|
||||
*__screenshots__
|
||||
|
||||
/AGENTS.md
|
||||
/CLAUDE.md
|
||||
/.claude/
|
||||
/.workbuddy/
|
||||
/.ai-local/
|
||||
|
||||
findings.md
|
||||
progress.md
|
||||
task_plan.md
|
||||
.agents
|
||||
*__screenshots__
|
||||
|
||||
*tm-wcdb-config-helper*
|
||||
*libtmlicense*
|
||||
debug-originals
|
||||
/build/mac-staging/
|
||||
|
||||
# 去水印脚本与群聊机器人核心引擎
|
||||
/examples/extensions/douyin-sender/scripts/douyin.py
|
||||
/examples/extensions/group-chat-bot/lib/
|
||||
/examples/extensions/group-chat-bot/tests/
|
||||
|
||||
# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
|
||||
/build/extension-templates/
|
||||
|
||||
# 诊断产物与数据库快照(含密钥派生脚本、消息正文、zstd blob)——严禁入库
|
||||
/dump*.js
|
||||
/dump*.cjs
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.zst
|
||||
/snapshot/
|
||||
/blobs/
|
||||
/database-keys/
|
||||
|
||||
.dev-verify/
|
||||
@@ -0,0 +1,112 @@
|
||||
# 参与贡献
|
||||
|
||||
> 这份文档同时写给人和 AI Agent。文末有给 Agent 的英文硬性规则。
|
||||
> 如果你只是想把 TraceMemo 跑起来,看[第一次使用](./docs/user-guide/getting-started.md)就够了。
|
||||
|
||||
## 一句话规则
|
||||
|
||||
**从 `develop` 拉分支,把 PR 提给 `develop`。**
|
||||
|
||||
## 为什么不是 main
|
||||
|
||||
| 分支 | 是什么 | 接受 PR 吗 |
|
||||
| --------- | ------------------------------------------------------- | -------------- |
|
||||
| `main` | 稳定版。只在发版时更新,对应 GitHub Releases 里的安装包 | 不接受 |
|
||||
| `develop` | 开发主线。所有改动先进这里,**随下一个版本一起发布** | 唯一的目标分支 |
|
||||
|
||||
指向 `main` 的 PR、或者不是基于 `develop` 拉出来的分支,会被直接关闭。不是不欢迎贡献,而是因为冲突合并 提交落后较多等原因
|
||||
|
||||
## 提 PR 的完整流程
|
||||
|
||||
```bash
|
||||
# 1. 基于 develop 拉分支(不要基于 main)
|
||||
git fetch origin
|
||||
git checkout -b feat/your-change origin/develop
|
||||
|
||||
# 2. 改代码,只改与本任务相关的文件
|
||||
|
||||
# 3. 自检
|
||||
pnpm install # 需要 Node 22 与 pnpm 7.33.7
|
||||
pnpm typecheck
|
||||
pnpm test:unit # 再按改动范围补跑 component / integration
|
||||
|
||||
# 4. 提交
|
||||
git commit -m "feat: 一句话说明改了什么"
|
||||
|
||||
# 5. 提 PR,目标分支必须是 develop
|
||||
gh pr create --base develop --head feat/your-change
|
||||
```
|
||||
|
||||
## 提交信息
|
||||
|
||||
默认**只写一行标题**:类型前缀 + 一句话说明。
|
||||
|
||||
```
|
||||
feat: 新增本地查询能力
|
||||
fix: 修复查询工具时间契约
|
||||
docs: 整理开发文档
|
||||
```
|
||||
|
||||
确实包含多个功能点时,标题之后每个功能点各写一行纯文本 —— 不要用列表符号,也不要写
|
||||
「设置侧:」「测试:」这类分节标题:
|
||||
|
||||
```
|
||||
feat: 统一手动发送入口为文字转语音
|
||||
移除普通文本、图片和本地语音的手动发送入口
|
||||
保留文字转语音的生成、试听和发送能力
|
||||
```
|
||||
|
||||
不要在提交信息里堆文件名清单、测试结果或实现过程叙述,那些属于 PR 描述。
|
||||
|
||||
## 分支命名
|
||||
|
||||
`feat/…`、`fix/…`、`docs/…`、`refactor/…`,后面接简短的英文或拼音描述。
|
||||
|
||||
## PR 前自检
|
||||
|
||||
| 你的改动 | 至少跑这些 |
|
||||
| -------------------------- | ----------------------------------------------------------------- |
|
||||
| 一般代码 / 服务 / 工具函数 | `pnpm typecheck` + 相关 `pnpm test:unit` |
|
||||
| 界面 / 交互 | `pnpm typecheck` + 相关 `pnpm test:component`,或针对该功能的 E2E |
|
||||
| preload / IPC 契约 | `pnpm typecheck` + 相关 contract 测试或 `pnpm test:integration` |
|
||||
| 只改文档 | 不需要跑测试 |
|
||||
|
||||
全部测试命令见 `package.json` 的 `scripts`;本地开发环境的说明见[开发概览](./docs/development/overview.md)。
|
||||
|
||||
## 请不要提交这些东西
|
||||
|
||||
- **构建产物**:`out/`、`dist/`、`build/` 下的二进制、`node_modules/`、`test-results/`、`playwright-report/`
|
||||
- **真实数据**:微信聊天内容、真实的 wxid / 群名 / 联系人名、聊天截图
|
||||
- **密钥**:API Key、Token、数据库密钥、图片解密密钥
|
||||
- **本机绝对路径**:`/Users/…`、`C:\Users\…`
|
||||
|
||||
测试用的假数据请用一眼能看出是合成的命名,例如 `fixture-group`、`wxid_fixture_member`。
|
||||
|
||||
## 合入之后
|
||||
|
||||
PR 合进 `develop` 不会立刻出现在下载页,它随**下一个版本**发布。想提前用上,可以自行从
|
||||
`develop` 构建。
|
||||
|
||||
## 如果你是 AI Agent
|
||||
|
||||
请按顺序执行,不要凭直觉选分支:
|
||||
|
||||
1. **基线**:`git fetch origin && git checkout -b <branch> origin/develop`。永远不要基于 `main`。
|
||||
2. **PR 目标**:`gh pr create --base develop`。无法确定时默认 `develop`;任何情况下都不要把
|
||||
`main` 当 PR 目标。
|
||||
3. **改动范围**:只改与本任务相关的文件。不要顺手格式化、重排 import、升级依赖。
|
||||
4. **提交前**:跑 `pnpm typecheck` 和与本次改动相关的测试(见上表)。
|
||||
5. **提交信息**:一行标题,`type: 描述`。不要写文件清单、测试输出或过程叙述。
|
||||
6. **PR 描述**:说明改了什么、为什么改、怎么验证的;关联 Issue 用 `closes #123`。
|
||||
7. **禁止**:真实聊天数据、密钥、Token、本机绝对路径、构建产物。
|
||||
|
||||
### Hard rules for AI agents (English)
|
||||
|
||||
- Base branch: `origin/develop`. Never branch off `main`.
|
||||
- Open pull requests with base branch `develop`. PRs targeting `main` are closed without review.
|
||||
- One PR = one logical change. No drive-by reformatting, import reordering, or dependency upgrades.
|
||||
- Before opening a PR, run `pnpm typecheck` plus the tests relevant to your change.
|
||||
- Commit subject: a single line, `type: summary`. No file lists, no test logs, no process narration.
|
||||
- Never commit build output (`out/`, `dist/`, `test-results/`, `playwright-report/`), real WeChat
|
||||
data, keys, tokens, or absolute local paths.
|
||||
- Changes merged into `develop` ship with the next release.
|
||||
@@ -4,12 +4,9 @@
|
||||
<img src="./build/icon.png" width="120" alt="TraceMemo Logo" />
|
||||
</p>
|
||||
|
||||
<h2 align="center">把微信聊过的事,找回来、问清楚、留下来</h2>
|
||||
<h2 align="center">把微信里的信息,记住、理解、监控,并在需要时行动</h2>
|
||||
|
||||
<p align="center">
|
||||
本地优先的微信聊天记录工作台:查看、搜索、提问、总结和导出<br />
|
||||
查看聊天 · 找回信息 · AI 问答 · 微信群聊总结 · 语音转写 · 导出 · 微信机器人 · Agent 接入
|
||||
</p>
|
||||
<p align="center">本地优先的微信数据、AI 分析与自动化工作台</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/github/stars/Wxw-Gu/TraceMemo?style=for-the-badge" alt="GitHub stars" />
|
||||
@@ -23,61 +20,79 @@
|
||||
<a href="./docs/user-guide/getting-started.md"><b>第一次使用</b></a>
|
||||
·
|
||||
<a href="./docs/README.md"><b>完整文档</b></a>
|
||||
·
|
||||
<a href="./docs/concepts/how-it-works.md"><b>TraceMemo 如何工作</b></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="./public/software-1.png" alt="TraceMemo 主界面" />
|
||||
<img src="./public/日报.png" alt="TraceMemo 日报" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="./public/机器人.png" alt="TraceMemo 微信机器人" />
|
||||
<img src="./public/自动化.png" alt="TraceMemo 自动化" />
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## TraceMemo(迹忆)是什么
|
||||
|
||||
TraceMemo(迹忆)是一款**本地优先、可追溯的 AI 微信知识与分析工作台**。
|
||||
|
||||
TraceMemo 原名 **WechatExplorer**,是一次从“微信聊天记录探索工具”向“可追溯的本地 AI 知识工作台”演进后的正式品牌升级。
|
||||
|
||||
它可以帮你浏览、搜索和整理微信历史,也可以让 AI 帮你找回聊过的内容,并回到原始消息核对答案。
|
||||
|
||||
你可以直接浏览聊天,也可以用自然语言提问:
|
||||
|
||||
> “上个月我们讨论过哪些发布问题?”
|
||||
>
|
||||
> “张三之前发过的项目地址在哪里?”
|
||||
>
|
||||
> “技术交流群今天有哪些结论和待办?”
|
||||
|
||||
它和普通聊天记录查看器最大的不同,是 AI 不只是告诉你答案,还会告诉你答案来自哪里。
|
||||
|
||||
你可以看到答案参考了哪些内容、来自哪个会话和时间,再回到原始消息确认它有没有理解错。
|
||||
|
||||
TraceMemo 不提供任何微信聊天数据,也不鼓励收集、上传、出售、共享或未经授权处理他人的聊天记录。使用 TraceMemo 时,请确保你对所处理的数据具有合法的访问和使用权限,并自行承担相应的数据安全与合规责任。
|
||||
|
||||
---
|
||||
|
||||
## 为什么叫 TraceMemo(迹忆)
|
||||
## 🎨 社区日报模板
|
||||
|
||||
<details>
|
||||
`Trace` 代表聊天记录留下的痕迹、可以追溯的信息来源、AI 搜索过程,以及从结果回到原始聊天上下文并核对证据的能力。
|
||||
TraceMemo 日报除了内置版式,也支持从社区模板市场安装更多样式。社区模板与默认日报读取同一份真实日报数据,只改变展示方式,适合手机长图分享、桌面归档、团队复盘等不同场景。
|
||||
|
||||
`Memo` 代表记忆、知识沉淀和长期保存:让聊天中产生的信息逐渐形成个人知识。
|
||||
<p align="center">
|
||||
<a href="https://github.com/Wxw-Gu/TraceMemo-Templates"><b>浏览 TraceMemo 模板社区</b></a>
|
||||
·
|
||||
<a href="https://github.com/Wxw-Gu/TraceMemo-Templates/tree/main/skills/tracememo-template-contributor"><b>用 AI 制作并投稿模板</b></a>
|
||||
</p>
|
||||
|
||||
“迹忆”可以理解为“留下痕迹的记忆”。
|
||||
在 TraceMemo 中打开:
|
||||
|
||||
TraceMemo 不是单纯查看微信聊天记录的工具,而是希望让聊天中产生的信息留下痕迹,并能够被再次找到、理解、验证和沉淀。
|
||||
**日报 → 社区模板市场**
|
||||
|
||||
> **品牌说明**
|
||||
>
|
||||
> TraceMemo(迹忆)原名 WechatExplorer。WechatExplorer 最初是一个用于查看和探索微信聊天记录的工具。随着本地搜索、AI 问答、来源追溯、知识库、日报、语音转写和 Agent 能力逐渐形成,项目已经从单纯的聊天记录查看器发展为本地 AI 知识与分析工作台,因此在 v2.2.0 正式更名为 TraceMemo(迹忆)。
|
||||
即可查看、预览、安装和切换已发布的社区模板。
|
||||
|
||||
</details>
|
||||
如果你有一张喜欢的日报长图、网页或前端项目,也可以把它交给 Codex、ChatGPT 或其他能够读取 GitHub 仓库的 AI,并让它读取 [TraceMemo Template Contributor Skill](https://github.com/Wxw-Gu/TraceMemo-Templates/tree/main/skills/tracememo-template-contributor)。AI 可以帮助你完成模板转换、真实预览,并在你确认满意后向 [TraceMemo-Templates](https://github.com/Wxw-Gu/TraceMemo-Templates) 提交 Pull Request。
|
||||
|
||||
模板通过审核并正式发布后,其他 TraceMemo 用户即可在模板市场中安装使用。
|
||||
|
||||
---
|
||||
|
||||
## TraceMemo 是什么
|
||||
|
||||
TraceMemo(迹忆)原名 **WechatExplorer** 是一款本地优先的微信数据、AI 分析与自动化工作台,把聊天变成可浏览、可搜索、可理解、可追溯的信息。
|
||||
|
||||
先用档案找原话,再按需要使用 AI Search、日报、监控或 Agent。普通浏览、搜索和导出不需要 AI。
|
||||
|
||||
## 核心能力
|
||||
|
||||
- 💬 **聊天档案与搜索**:浏览会话,按关键词、备注、昵称或 wxid 查找消息。
|
||||
- 🔍 **AI Search / 问问微信**:用自然语言找回模糊记忆,并查看来源。
|
||||
- 🧠 **本地知识库**:在本机建立索引,让跨会话、跨时间的查询更稳定。
|
||||
- 🖼️ **图片文字索引**:在本机识别微信图片里的文字(截图、公告、报价图),识别结果可以在搜索和「问问微信」里被检索。识别全程不联网,原始图片不会因为本地识别而上传。
|
||||
- 📊 **群聊日报**:生成今日、昨日或近 7 天的群聊总结,可保存为 HTML 与 PNG。
|
||||
- 🗣️ **群发言统计**:统计群成员的发言量和沉默成员,看清一个群里谁在说、谁一直没说。
|
||||
- 👀 **退群监控**:用成员快照对比记录群成员退出事件,支持多群与事件历史。
|
||||
- ⚙️ **自动化**:把上面几步按规则串起来——定时生成并发送日报、成员退群时发送通知;能发到哪里取决于当前的发送能力。
|
||||
- 🔊 **文字转语音**:把文字生成语音,试听后发送到当前会话。
|
||||
- 🤖 **Agent Hub**:在微信里向本机 TraceMemo 提问。
|
||||
- 🔌 **外部 Agent / Local HTTP API**:让 Codex 等外部 Agent 查询本机微信历史。
|
||||
|
||||
## 💻 平台支持
|
||||
|
||||
TraceMemo 2.5.1 支持:
|
||||
|
||||
- **Windows x64**
|
||||
- **macOS Apple Silicon(M 系列 / arm64)**
|
||||
- **macOS Intel(x64)**
|
||||
|
||||
Windows 与 macOS 均支持微信本地数据库连接与数据库 Key 获取。
|
||||
|
||||
### 关于“发送能力”
|
||||
|
||||
浏览、搜索、日报生成、导出、知识库和图片文字索引都不需要额外的发送组件。只有**把内容真正发回微信**这一步——自动发送日报、退群通知、把语音发到会话——依赖本机发送能力:
|
||||
|
||||
发送能力未就绪、未绑定或发送失败时,报告本身仍会正常生成并保存在本机,执行记录会显示为“已生成,但未发送”或“已生成,发送失败”,可以稍后重试。
|
||||
|
||||
## 项目缘起
|
||||
|
||||
<details>
|
||||
@@ -88,11 +103,11 @@ TraceMemo 最早叫 **WechatExplorer**。
|
||||
|
||||
第一个版本完成后,项目搁置了一段时间。后来重新捡起来,我还是想继续做群聊日报,但微信已经更新到 4.x,原来的微信 3.0 数据解析方案不再适用。
|
||||
|
||||
为了支持微信 4.x,我开始重新研究数据访问。这部分工作得到了 **WeFlow** 很大的帮助。TraceMemo 目前的微信 4.x 数据连接能力,参考并使用了 **WeFlow 历史版本中的相关实现和思路**,包括数据库密钥获取、图片解密等底层能力。
|
||||
为了支持微信 4.x,我开始重新研究数据访问。这部分工作最初得到了 **WeFlow** 很大的帮助。早期 TraceMemo 曾参考 WeFlow 历史版本中的实现和思路,借此解决了数据库消息、密钥获取等微信 4.x 数据访问问题。
|
||||
|
||||
> **没有 WeFlow,就没有今天的 TraceMemo。**
|
||||
随着项目继续发展,我逐步把这部分底层能力从原有实现中抽离,并重新实现了一套独立的数据访问兼容层。目前会继续保持与 WeFlow 历史接口和行为的兼容,以减少上层业务迁移成本。
|
||||
|
||||
WeFlow 帮我跨过了微信 4.x 数据访问这道门槛,我才有机会继续做后面的事情:让聊天记录可以被搜索、理解和总结,也让 AI 给出的答案能够回到原始消息核对。
|
||||
也就是说,**WeFlow 是 TraceMemo 进入微信 数据访问领域的重要起点。没有 WeFlow,就没有今天的 TraceMemo。**
|
||||
|
||||
在此基础上,项目陆续加入了:
|
||||
|
||||
@@ -105,12 +120,15 @@ WeFlow 帮我跨过了微信 4.x 数据访问这道门槛,我才有机会继
|
||||
- Reader Skill
|
||||
- Agent 接入
|
||||
- 多种聊天记录导出能力
|
||||
- 退群监控
|
||||
- 文字转语音
|
||||
- 持续监控自动化能力
|
||||
|
||||
群聊日报后来被一些人看到,项目也开始有了 Star、Fork、使用反馈和功能建议。说实话,我一开始没想到,这个原本只给自己用的小工具,会得到这么多人的关注。
|
||||
|
||||
这些关注和反馈让我决定认真把项目继续做下去。WechatExplorer 就这样一步一步变成了今天的 **TraceMemo(迹忆)**。
|
||||
|
||||
感谢 WeFlow,也感谢每一位使用、关注和反馈过 TraceMemo 的人。
|
||||
感谢每一位使用、关注和反馈过的人。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -124,298 +142,57 @@ WeFlow 帮我跨过了微信 4.x 数据访问这道门槛,我才有机会继
|
||||
|
||||
## 从你的任务开始
|
||||
|
||||
| 我现在想做什么 | 在应用里打开 | 需要准备什么 |
|
||||
| ----------------------------------------- | ------------------------------------------------------------------- | ------------------------------------ |
|
||||
| 找一句记得原文或关键词的聊天 | [档案](./docs/user-guide/chat-archive.md) | 连接微信数据,不需要 AI |
|
||||
| 找一件记得大意、但不知道在哪聊过的事 | [问问微信](./docs/user-guide/ai-search.md) | 配置 AI 服务,并选择会话和时间范围 |
|
||||
| 让长期、跨群聊查找更稳定 | [问问微信 → 本地知识库](./docs/user-guide/knowledge.md) | 主动建立本地索引;不会自动创建 |
|
||||
| 快速了解一个群今天、昨天或近 7 天聊了什么 | [日报](./docs/user-guide/report.md) | 选择群聊并配置 AI 服务 |
|
||||
| 把群聊日报生成微信分享卡片(实验性) | [微信分享卡片](./docs/deployment/experimental-wechat-share-card.md) | 自备 Cloudflare、域名和微信测试号 |
|
||||
| 把微信语音变成可搜索的文字 | [设置 → 语音转文字](./docs/user-guide/voice.md) | 准备本地语音模型 |
|
||||
| 把聊天保存成 HTML、Markdown、CSV 或 JSON | [导出](./docs/user-guide/export.md) | 选择聊天、时间和格式,不需要 AI |
|
||||
| 尽量保留之后捕获到的撤回消息 | [设置 → 防撤回](./docs/user-guide/recall-protection.md) | 默认关闭;开启前先了解写入和性能边界 |
|
||||
| 直接在微信里向 TraceMemo 提问 | [微信机器人](./docs/agent/agent-hub.md) | 扫码连接机器人;总结类任务需要 AI |
|
||||
| 让 Codex 等外部 Agent 查询微信历史 | [外部 Agent](./docs/agent/overview.md) | 安装 Reader Skill 并配置本机 Token |
|
||||
|
||||
---
|
||||
|
||||
## 最核心的三个能力
|
||||
|
||||
### 生成群聊日报
|
||||
|
||||
选择群聊和时间范围后,可以让 AI 把聊天整理成报告,并保存为 HTML 与 PNG 长图。
|
||||
|
||||
报告包含:
|
||||
|
||||
- 热点
|
||||
- 重要消息
|
||||
- 资源
|
||||
- 问答
|
||||
- 待办
|
||||
- 未解决事项
|
||||
- 活跃统计
|
||||
- 图片精选
|
||||
|
||||
具体内容取决于消息、媒体是否可读以及模型能力。
|
||||
详细说明:[生成群聊日报](./docs/user-guide/report.md)
|
||||
|
||||
</details>
|
||||
|
||||
### AI 帮你找回聊过的内容
|
||||
|
||||
打开“问问微信”,选择搜索范围和时间,然后像提问一样描述你想找的内容。
|
||||
|
||||
TraceMemo 会先在本机查找候选消息,再把整理后的少量来源交给你配置的 AI 模型生成回答。
|
||||
|
||||
你可以查看答案参考了哪些聊天、来自哪个人和时间,并从来源标记跳回原始消息核对;“查看检索详情”还会展示本次查找经历了哪些阶段。
|
||||
|
||||
<p align="center">
|
||||
<img src="./public/问一问.png" alt="问问微信与聊天来源" />
|
||||
</p>
|
||||
|
||||
详细说明:[使用 AI 查找聊天信息](./docs/user-guide/ai-search.md)
|
||||
|
||||
### 直接在微信里问你的历史聊天
|
||||
|
||||
打开应用中的“Agent”入口(页面标题为“Agent Hub”,对应微信机器人功能),扫码连接一个微信机器人账号。
|
||||
|
||||
例如,你可以直接给机器人发送:
|
||||
|
||||
- “最近 5 个会话”
|
||||
- “张三最近和我聊了什么”
|
||||
- “总结今天的技术交流群”
|
||||
|
||||
TraceMemo 会在本机读取已连接的聊天数据并把结果回复到微信。
|
||||
|
||||
这个入口不要求另外安装 Codex、Claude Code 等外部 Agent。
|
||||
|
||||
当前主要处理文字消息,不支持群发、定时任务或通用自主操作微信;总结和自然语言理解需要先配置 AI 服务。
|
||||
|
||||
详细步骤和能力边界见[在微信里向 TraceMemo 提问](./docs/agent/agent-hub.md)。
|
||||
|
||||
---
|
||||
|
||||
## 其他能力
|
||||
|
||||
### 本地知识库
|
||||
|
||||
<details>
|
||||
“问问微信”里的“本地知识库”会为当前微信账号建立一份留在本机的可检索资料。
|
||||
|
||||
它把聊天文本、附件信息和已有语音转写整理起来,让跨会话、跨时间查找更稳定。
|
||||
|
||||
它只在用户主动建立后工作,可以同步、查看占用并清理;清理不会删除微信原始数据库。
|
||||
|
||||
详细说明:[本地知识库](./docs/user-guide/knowledge.md)
|
||||
|
||||
</details>
|
||||
|
||||
### 实验性:生成微信分享卡片
|
||||
|
||||
<details>
|
||||
TraceMemo 可以把群聊日报长图上传到你自己部署的 Cloudflare Worker 和 R2,并生成可在微信中分享的临时网页、二维码及卡片信息。
|
||||
|
||||
该功能需要自备 Cloudflare 账号、域名和微信测试号,目前不属于开箱即用的稳定功能。
|
||||
|
||||
<p align="center">
|
||||
<img src="./public/微信卡片分享.png" alt="微信卡片分享效果示例" />
|
||||
</p>
|
||||
|
||||
详细说明:[实验性微信分享卡片](./docs/deployment/experimental-wechat-share-card.md)。
|
||||
|
||||
不熟悉命令行的用户,可以把[自动部署 Skill](./docs/skill/setup-wechat-share-card/SKILL.md)直接交给 Codex 或 Claude Code。
|
||||
|
||||
</details>
|
||||
|
||||
### 转写微信语音
|
||||
|
||||
<details>
|
||||
TraceMemo 支持在本机转写单条或批量微信语音,结果可以参与本地知识库检索和 HTML 导出。
|
||||
|
||||
转写本身不要求把语音文件发送给在线 AI;随后用于 AI 问答或日报时,文字会按对应功能的规则处理。
|
||||
|
||||
详细说明:[语音转文字](./docs/user-guide/voice.md)
|
||||
|
||||
</details>
|
||||
|
||||
### 导出长期可用的聊天档案
|
||||
|
||||
<details>
|
||||
支持 HTML、CSV、JSON 和 Markdown。
|
||||
|
||||
HTML 可携带媒体、头像和可选语音转写,支持最多五个会话合并,也可以压缩为 ZIP;增量合并、媒体资源和 ZIP 只适用于 HTML,其他格式主要保留文本内容。
|
||||
|
||||
详细说明:[导出聊天](./docs/user-guide/export.md)
|
||||
|
||||
</details>
|
||||
|
||||
### 在外部 Agent 中查询微信历史
|
||||
|
||||
<details>
|
||||
通过 Reader Skill 和本机 Local HTTP API,Codex、Claude Code、OpenClaw 等外部 Agent 可以按需查询联系人、群聊和聊天记录。
|
||||
|
||||
这和微信机器人是两条不同路径:
|
||||
|
||||
- **微信机器人**:收到消息后在微信中回复。
|
||||
- **外部 Agent**:主动查询历史。
|
||||
|
||||
安装和技术说明请看[Agent 接入概览](./docs/agent/overview.md)与[Local HTTP API](./docs/agent/api.md)。
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 它如何工作
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[本机微信数据] --> B[TraceMemo 读取与解析]
|
||||
B --> C[聊天档案]
|
||||
B --> D[本地知识库与搜索]
|
||||
D --> E[筛选相关聊天来源]
|
||||
E --> F[用户配置的 AI 模型]
|
||||
F --> G[带来源的回答]
|
||||
B --> H[整理日报输入]
|
||||
H --> F
|
||||
B --> I[聊天导出]
|
||||
B --> J[Local HTTP API]
|
||||
J --> K[外部 Agent]
|
||||
L[微信机器人消息] --> M[Agent Hub]
|
||||
M --> B
|
||||
M --> F
|
||||
```
|
||||
|
||||
- 微信数据库读取、聊天解析、知识库索引和离线语音识别在本机完成。
|
||||
- 普通浏览、普通搜索和导出不要求配置 AI 服务。
|
||||
- 使用“问问微信”、群聊日报或图片理解等 AI 功能时,完成任务所需的内容可能发送到你选择的模型服务;具体发送范围和确认方式以对应功能页面为准。
|
||||
- “问问微信”会先在本机缩小范围,不会默认把整个微信数据库作为一次模型请求发送。
|
||||
|
||||
完整边界见:[数据、隐私与安全](./docs/user-guide/privacy.md)
|
||||
|
||||
---
|
||||
|
||||
## 支持平台与安装包
|
||||
|
||||
| 平台 | 处理器架构 | Releases 安装包 |
|
||||
| ------- | ------------------------------ | --------------- |
|
||||
| Windows | x64 | `-setup.exe` |
|
||||
| macOS | Apple Silicon(M 系列、arm64) | `.dmg` |
|
||||
|
||||
当前版本不支持 Intel 芯片的 Mac。
|
||||
|
||||
当前代码面向微信 4.x 数据结构。实际连接结果仍会受到微信客户端版本、账号数据状态和系统权限影响;macOS 首次连接可能需要按页面提示完成额外授权。
|
||||
|
||||
---
|
||||
| 想做什么 | 使用入口 |
|
||||
| ---------------------------------- | ----------------------------- |
|
||||
| 找记得原文或关键词的消息 | 档案搜索 |
|
||||
| 找记得大意、但不知道在哪聊过的内容 | 问问微信(AI Search) |
|
||||
| 找到截图、公告图里写过的文字 | 问问微信 → 图片文字索引 |
|
||||
| 长期跨群查询历史 | 本地知识库 |
|
||||
| 了解一个群今天或近 7 天聊了什么 | 日报 |
|
||||
| 看群里谁最活跃、谁一直没说话 | 档案 → 群聊 → 群发言统计 |
|
||||
| 持续关注群成员退出 | 退群监控 |
|
||||
| 按计划自动生成并发送群聊日报 | 自动化 |
|
||||
| 成员退群时自动发一条通知 | 自动化 → 退群通知 |
|
||||
| 把文字生成微信语音 | 文字转语音 |
|
||||
| 在微信里向本机 TraceMemo 提问 | Agent Hub |
|
||||
| 让 Codex 等工具查询微信历史 | Reader Skill / Local HTTP API |
|
||||
| 把聊天保存成文件 | 导出 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 从 [GitHub Releases](https://github.com/Wxw-Gu/TraceMemo/releases) 下载安装包。
|
||||
2. 启动 TraceMemo,按照“第一次使用”页面选择微信数据目录。
|
||||
3. 第一次使用请先点击“开始连接”,按页面提示准备连接组件并获取数据库密钥;只有已经有密钥的高级用户才需要“手动连接”。
|
||||
4. 连接成功后打开“档案”,确认联系人和聊天消息已经出现。
|
||||
5. 先在“档案”里搜索一句你记得的原话;这一步不需要 AI。
|
||||
6. 需要 AI 问答或日报时,在“设置 → AI 模型”添加并测试 AI 服务,再打开“问问微信”或“日报”。
|
||||
7. 想直接在微信里提问时,打开“Agent”扫码连接微信机器人;想让 Codex 等外部 Agent 查询时,再进入“API”。
|
||||
1. 从 [GitHub Releases](https://github.com/Wxw-Gu/TraceMemo/releases) 下载对应平台的安装包。
|
||||
2. 启动应用,按“第一次使用”页面选择微信数据目录并完成连接。
|
||||
3. 打开“档案”,确认联系人和消息已加载后开始搜索。
|
||||
4. 需要 AI 时,在“设置 → AI 模型”添加并测试 Provider。
|
||||
|
||||
Windows 安装后无法启动时,请先安装 [Microsoft Visual C++ x64 运行库](https://aka.ms/vc14/vc_redist.x64.exe)。
|
||||
|
||||
当前完整测试过的微信客户端为 Windows `4.1.9.57` 和 macOS `4.1.8.100`;下载地址与连接要求见[第一次使用](./docs/user-guide/getting-started.md)。
|
||||
|
||||
从 WechatExplorer v2.1.9 升级时,TraceMemo v2.2.0 会在首次启动检测旧设置、Knowledge、Token、AI Provider 和 Agent 数据,并在用户确认后复制到新的 TraceMemo 数据目录。
|
||||
|
||||
迁移不会覆盖已有 TraceMemo 数据,也不会删除旧目录;详情见 [v2.2.0 正式品牌身份与安全升级迁移](./docs/agent/release-notes-v2.2.0.md)。
|
||||
|
||||
如果 macOS 页面提示处理 SIP,请先阅读对应说明。具体步骤和限制见[第一次使用](./docs/user-guide/getting-started.md)。
|
||||
|
||||
完整步骤:[第一次使用 TraceMemo](./docs/user-guide/getting-started.md)
|
||||
|
||||
---
|
||||
|
||||
## 配置 AI
|
||||
|
||||
需要 AI 问答、群聊日报或图片理解时,在“设置 → AI 模型”添加并测试一个服务。
|
||||
|
||||
应用支持云端服务、Ollama 等本地服务和自定义接口;具体服务商的配置、计费和数据规则由服务商决定。
|
||||
|
||||
使用本地服务可以减少数据离开电脑的路径,但本地服务的日志和配置仍由你自己负责。
|
||||
|
||||
开发者和 Agent 用户可以从[Agent 接入概览](./docs/agent/overview.md)开始,再按需要查看[Local HTTP API](./docs/agent/api.md)与[API 安全](./docs/agent/api-security.md)。
|
||||
|
||||
---
|
||||
详细步骤见[第一次使用 TraceMemo](./docs/user-guide/getting-started.md)。
|
||||
|
||||
## 文档
|
||||
|
||||
- [文档首页](./docs/README.md)
|
||||
- [第一次使用](./docs/user-guide/getting-started.md)
|
||||
- [聊天档案与搜索](./docs/user-guide/chat-archive.md)
|
||||
- [AI 查找聊天信息](./docs/user-guide/ai-search.md)
|
||||
- [本地知识库](./docs/user-guide/knowledge.md)
|
||||
- [群聊日报](./docs/user-guide/report.md)
|
||||
- [实验性微信分享卡片](./docs/deployment/experimental-wechat-share-card.md)
|
||||
- [微信分享卡片自动部署 Skill](./docs/skill/setup-wechat-share-card/SKILL.md)
|
||||
- [语音转文字](./docs/user-guide/voice.md)
|
||||
- [导出聊天](./docs/user-guide/export.md)
|
||||
- [防撤回](./docs/user-guide/recall-protection.md)
|
||||
- [数据、隐私与安全](./docs/user-guide/privacy.md)
|
||||
- [Agent 接入](./docs/agent/overview.md)
|
||||
- [微信机器人与 Agent Hub](./docs/agent/agent-hub.md)
|
||||
- [Local HTTP API](./docs/agent/api.md)
|
||||
- [开发与测试](./docs/development/overview.md)
|
||||
- [用户指南](./docs/README.md#档案与搜索)
|
||||
- [AI / Knowledge](./docs/README.md#ai-与知识库)
|
||||
- [日报与自动化](./docs/README.md#日报与自动化)
|
||||
- [Agent / API](./docs/README.md#agent--api)
|
||||
- [开发文档](./docs/development/overview.md)
|
||||
- [隐私与安全](./docs/user-guide/privacy.md)
|
||||
|
||||
---
|
||||
完整目录由[文档首页](./docs/README.md)维护。
|
||||
|
||||
## 本地开发
|
||||
## 支持平台
|
||||
|
||||
需要 Node.js、pnpm 7+、对应平台的 Electron/native 构建环境,以及 Go(用于微信连接器)。
|
||||
| 平台 | 架构 | 微信连接 | 安装包 |
|
||||
| ------- | ------------------------------ | ------------------------------------- | ------------------------------- |
|
||||
| Windows | x64 | 支持微信 4.x | `tracememo-<version>-setup.exe` |
|
||||
| macOS | Apple Silicon(M 系列、arm64) | 自动获取数据库 Key,已适配微信 4.1.13 | `tracememo-<version>-arm64.dmg` |
|
||||
| macOS | Intel(x64) | 自动获取数据库 Key,已适配微信 4.1.13 | `tracememo-<version>-x64.dmg` |
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
## 参与贡献
|
||||
|
||||
常用检查:
|
||||
稳定版在 `main`,只在发版时更新;所有改动都先进 `develop`,随**下一个版本**一起发布。
|
||||
|
||||
```bash
|
||||
pnpm typecheck
|
||||
pnpm test:unit
|
||||
pnpm test:component
|
||||
pnpm test:integration
|
||||
pnpm test:e2e:build
|
||||
```
|
||||
**提 PR 请基于 `develop` 拉新分支,并把 PR 的目标分支设为 `develop`** —— 指向 `main` 的 PR 会被直接关闭。
|
||||
|
||||
完整说明:[开发、测试与构建](./docs/development/overview.md)
|
||||
|
||||
---
|
||||
|
||||
## 支持与反馈
|
||||
|
||||
遇到问题时,先查看[常见问题与排查](./docs/user-guide/troubleshooting.md)。
|
||||
|
||||
提交 Issue 时请提供:
|
||||
|
||||
- 操作系统
|
||||
- 微信版本
|
||||
- TraceMemo 版本
|
||||
- 复现步骤
|
||||
- 已遮挡敏感信息的截图
|
||||
|
||||
请仅处理你有权访问的数据,并遵守适用的法律法规、组织政策和微信使用规则。
|
||||
|
||||
数据库读取、解密、自动化和机器人能力都可能受平台版本与账号环境影响。
|
||||
|
||||
---
|
||||
|
||||
## 许可说明
|
||||
|
||||
TraceMemo 当前暂未提供独立的项目 `LICENSE` 文件。
|
||||
|
||||
TraceMemo 允许个人使用、学习、修改、二次开发和 Fork,也欢迎基于项目进行非商业用途的再开发和分享。
|
||||
|
||||
**但未经项目维护者书面许可,禁止将 TraceMemo 本身或基于 TraceMemo 的衍生版本用于商业用途,包括但不限于商业软件、付费服务、商业产品、SaaS 服务或其他直接或间接的商业活动。**
|
||||
|
||||
仓库中的第三方组件以及参考项目均遵循各自适用的许可证和使用条款。TraceMemo 对第三方项目的参考、使用或集成,并不意味着这些第三方项目的代码或许可证发生变化。涉及第三方代码的部分,请以对应项目的许可证和授权范围为准。
|
||||
|
||||
---
|
||||
分支流程、提交信息风格、PR 前自检,以及**给 AI Agent 的硬性规则**,都在[参与贡献指南](./CONTRIBUTING.md)。
|
||||
|
||||
## 致谢
|
||||
|
||||
@@ -423,14 +200,14 @@ TraceMemo 的诞生离不开开源社区中许多优秀项目的工作。
|
||||
|
||||
### 特别感谢 WeFlow
|
||||
|
||||
TraceMemo 在支持微信 4.x 时,参考并使用了 **[WeFlow](https://github.com/hicccc77/WeFlow)** 历史版本中的相关实现和思路,包括数据库密钥获取、图片解密等底层能力。
|
||||
TraceMemo 在早期适配微信 4.x 时,曾参考 **[WeFlow](https://github.com/hicccc77/WeFlow)** 历史版本中的相关实现和思路,包括数据库访问、密钥获取等底层能力。
|
||||
|
||||
特别感谢作者 **hicccc77** 的理解和包容。项目与 WeFlow 的具体关系见[项目缘起](#项目缘起)。
|
||||
特别感谢作者 **[hicccc77](https://github.com/hicccc77)**。项目与 WeFlow 的具体关系见[项目缘起](#项目缘起)。
|
||||
|
||||
### 其他参考项目
|
||||
|
||||
- **[WechatMessageExplorer](https://github.com/svcvit/WechatMessageExplorer)**
|
||||
- 提供了数据库解析相关思路。
|
||||
- 提供了数据解析相关思路。
|
||||
|
||||
- **[chatlog](https://github.com/sjzar/chatlog)**
|
||||
- 提供了数据处理方面的参考。
|
||||
@@ -443,7 +220,7 @@ TraceMemo 在支持微信 4.x 时,参考并使用了 **[WeFlow](https://github
|
||||
|
||||
这个项目起初只是一个一时兴起的项目,所以它大概也不会有一份特别严肃的产品路线图。
|
||||
|
||||
我可能会按照自己的兴趣继续折腾,也可能突然加入一些奇奇怪怪、但觉得有意思的功能—— 比如让AI给某个好友, 某个群发一个语音条(逗逗群友) 或者定时生成群聊日报并做成微信卡片。
|
||||
我可能会按照自己的兴趣继续折腾,也可能突然加入一些奇奇怪怪、但觉得有意思的功能
|
||||
|
||||
也因此,这个项目随时可能继续折腾,也可能因为其他事情暂时搁置。如果你有想要的功能,可以提Issue;如果觉得现有实现不符合你的需求,也欢迎直接 Fork 后自己改。
|
||||
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
!include "LogicLib.nsh"
|
||||
!include "getProcessInfo.nsh"
|
||||
|
||||
Var tmSelfPid
|
||||
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
Var tmTempRedirected
|
||||
Var tmOrigTemp
|
||||
Var tmOrigTmp
|
||||
Var tmAltTempDir
|
||||
Var tmOldInstDir
|
||||
Var tmOldDrive
|
||||
Var tmTempDrive
|
||||
!endif
|
||||
|
||||
!macro TM_FIND_PROCESS _FILE _ERR
|
||||
!ifdef INSTALL_MODE_PER_ALL_USERS
|
||||
${nsProcess::FindProcess} "${_FILE}" ${_ERR}
|
||||
!else
|
||||
nsExec::Exec `"$SYSDIR\cmd.exe" /c tasklist /FI "USERNAME eq %USERNAME%" /FI "IMAGENAME eq ${_FILE}" /FO csv | "$SYSDIR\find.exe" /I "${_FILE}"`
|
||||
Pop ${_ERR}
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro TM_TASKKILL_SOFT _FILE _PID
|
||||
!ifdef INSTALL_MODE_PER_ALL_USERS
|
||||
nsExec::Exec `taskkill /im "${_FILE}" /fi "PID ne ${_PID}"`
|
||||
!else
|
||||
nsExec::Exec `"$SYSDIR\cmd.exe" /c taskkill /im "${_FILE}" /fi "PID ne ${_PID}" /fi "USERNAME eq %USERNAME%"`
|
||||
!endif
|
||||
Pop $R9
|
||||
!macroend
|
||||
|
||||
!macro TM_TASKKILL_FORCE_TREE _FILE _PID
|
||||
!ifdef INSTALL_MODE_PER_ALL_USERS
|
||||
nsExec::Exec `taskkill /f /t /im "${_FILE}" /fi "PID ne ${_PID}"`
|
||||
!else
|
||||
nsExec::Exec `"$SYSDIR\cmd.exe" /c taskkill /f /t /im "${_FILE}" /fi "PID ne ${_PID}" /fi "USERNAME eq %USERNAME%"`
|
||||
!endif
|
||||
Pop $R9
|
||||
!macroend
|
||||
|
||||
!macro customHeader
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
; 旧版卸载器在 --updated 模式下会把文件 Rename 到 %TEMP% 下的 $PLUGINSDIR\old-install。
|
||||
; 若旧版装在非系统盘,把子进程继承的 TEMP/TMP 暂指同盘符可写目录,避免跨卷 Rename 必败。
|
||||
Function tmPrepareCrossDriveUpdateTemp
|
||||
Push $0
|
||||
Push $1
|
||||
|
||||
StrCpy $tmTempRedirected "0"
|
||||
StrCpy $tmAltTempDir ""
|
||||
StrCpy $tmOldInstDir ""
|
||||
|
||||
ReadRegStr $tmOldInstDir SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${if} $tmOldInstDir == ""
|
||||
ReadRegStr $tmOldInstDir HKEY_CURRENT_USER "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${endIf}
|
||||
${if} $tmOldInstDir == ""
|
||||
StrCpy $tmOldInstDir "$INSTDIR"
|
||||
${endIf}
|
||||
|
||||
StrCpy $tmOldDrive $tmOldInstDir 2
|
||||
StrCpy $tmTempDrive $TEMP 2
|
||||
${if} $tmOldDrive == ""
|
||||
${orIf} $tmTempDrive == ""
|
||||
${orIf} $tmOldDrive == $tmTempDrive
|
||||
Goto tm_temp_done
|
||||
${endIf}
|
||||
|
||||
StrCpy $0 $tmOldInstDir 1 -1
|
||||
${if} $0 == "\"
|
||||
StrCpy $tmOldInstDir $tmOldInstDir -1
|
||||
${endIf}
|
||||
|
||||
StrCpy $tmAltTempDir "$tmOldInstDir._tm_upd_tmp"
|
||||
CreateDirectory "$tmAltTempDir"
|
||||
ClearErrors
|
||||
FileOpen $1 "$tmAltTempDir\.probe" w
|
||||
${if} ${Errors}
|
||||
StrCpy $tmAltTempDir "$tmOldDrive\.tracememo_upd_tmp"
|
||||
CreateDirectory "$tmAltTempDir"
|
||||
ClearErrors
|
||||
FileOpen $1 "$tmAltTempDir\.probe" w
|
||||
${if} ${Errors}
|
||||
StrCpy $tmAltTempDir ""
|
||||
Goto tm_temp_done
|
||||
${endIf}
|
||||
${endIf}
|
||||
FileClose $1
|
||||
Delete "$tmAltTempDir\.probe"
|
||||
|
||||
ReadEnvStr $tmOrigTemp "TEMP"
|
||||
ReadEnvStr $tmOrigTmp "TMP"
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TEMP", w "$tmAltTempDir") i.r0'
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TMP", w "$tmAltTempDir") i.r0'
|
||||
StrCpy $tmTempRedirected "1"
|
||||
|
||||
tm_temp_done:
|
||||
Pop $1
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
|
||||
Function tmRestoreCrossDriveUpdateTemp
|
||||
Push $0
|
||||
${if} $tmTempRedirected == "1"
|
||||
${if} $tmOrigTemp != ""
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TEMP", w "$tmOrigTemp") i.r0'
|
||||
${endIf}
|
||||
${if} $tmOrigTmp != ""
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TMP", w "$tmOrigTmp") i.r0'
|
||||
${endIf}
|
||||
${if} $tmAltTempDir != ""
|
||||
RMDir /r "$tmAltTempDir"
|
||||
${endIf}
|
||||
StrCpy $tmTempRedirected "0"
|
||||
${endIf}
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
!else
|
||||
Var /GLOBAL tmOldBackupRoot
|
||||
|
||||
Function un.tmAtomicMoveToBackup
|
||||
Exch $R0
|
||||
Push $R1
|
||||
Push $R2
|
||||
Push $R3
|
||||
|
||||
StrCpy $R3 "$INSTDIR$R0\*.*"
|
||||
FindFirst $R1 $R2 $R3
|
||||
|
||||
tm_move_loop:
|
||||
StrCmp $R2 "" tm_move_break
|
||||
StrCmp $R2 "." tm_move_continue
|
||||
StrCmp $R2 ".." tm_move_continue
|
||||
|
||||
IfFileExists "$INSTDIR$R0\$R2\*.*" tm_move_is_dir tm_move_is_file
|
||||
|
||||
tm_move_is_dir:
|
||||
CreateDirectory "$tmOldBackupRoot$R0\$R2"
|
||||
Push "$R0\$R2"
|
||||
Call un.tmAtomicMoveToBackup
|
||||
Pop $R3
|
||||
${if} $R3 != 0
|
||||
Goto tm_move_done
|
||||
${endIf}
|
||||
Goto tm_move_continue
|
||||
|
||||
tm_move_is_file:
|
||||
ClearErrors
|
||||
Rename "$INSTDIR$R0\$R2" "$tmOldBackupRoot$R0\$R2"
|
||||
StrCmp "$R0\$R2" "\${UNINSTALL_FILENAME}" 0 +2
|
||||
ClearErrors
|
||||
StrCmp "$R0\$R2" "${UNINSTALL_FILENAME}" 0 +2
|
||||
ClearErrors
|
||||
|
||||
IfErrors 0 +3
|
||||
StrCpy $R3 "$INSTDIR$R0\$R2"
|
||||
Goto tm_move_done
|
||||
|
||||
tm_move_continue:
|
||||
FindNext $R1 $R2
|
||||
Goto tm_move_loop
|
||||
|
||||
tm_move_break:
|
||||
StrCpy $R3 0
|
||||
|
||||
tm_move_done:
|
||||
FindClose $R1
|
||||
StrCpy $R0 $R3
|
||||
Pop $R3
|
||||
Pop $R2
|
||||
Pop $R1
|
||||
Exch $R0
|
||||
FunctionEnd
|
||||
|
||||
Function un.tmRestoreFromBackup
|
||||
Exch $R0
|
||||
Push $R1
|
||||
Push $R2
|
||||
Push $R3
|
||||
|
||||
StrCpy $R3 "$tmOldBackupRoot$R0\*.*"
|
||||
FindFirst $R1 $R2 $R3
|
||||
|
||||
tm_restore_loop:
|
||||
StrCmp $R2 "" tm_restore_break
|
||||
StrCmp $R2 "." tm_restore_continue
|
||||
StrCmp $R2 ".." tm_restore_continue
|
||||
|
||||
IfFileExists "$tmOldBackupRoot$R0\$R2\*.*" tm_restore_is_dir tm_restore_is_file
|
||||
|
||||
tm_restore_is_dir:
|
||||
CreateDirectory "$INSTDIR$R0\$R2"
|
||||
Push "$R0\$R2"
|
||||
Call un.tmRestoreFromBackup
|
||||
Pop $R3
|
||||
Goto tm_restore_continue
|
||||
|
||||
tm_restore_is_file:
|
||||
Rename "$tmOldBackupRoot$R0\$R2" "$INSTDIR$R0\$R2"
|
||||
|
||||
tm_restore_continue:
|
||||
FindNext $R1 $R2
|
||||
Goto tm_restore_loop
|
||||
|
||||
tm_restore_break:
|
||||
StrCpy $R0 0
|
||||
FindClose $R1
|
||||
Pop $R3
|
||||
Pop $R2
|
||||
Pop $R1
|
||||
Exch $R0
|
||||
FunctionEnd
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro customCheckAppRunning
|
||||
${GetProcessInfo} 0 $tmSelfPid $1 $2 $3 $4
|
||||
${if} $3 != "${APP_EXECUTABLE_FILENAME}"
|
||||
${if} ${isUpdated}
|
||||
Sleep 500
|
||||
${endIf}
|
||||
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 == 0
|
||||
${if} ${isUpdated}
|
||||
Sleep 1000
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 != 0
|
||||
Goto tm_app_not_running
|
||||
${endIf}
|
||||
Goto tm_do_stop_process
|
||||
${endIf}
|
||||
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(appRunning)" /SD IDOK IDOK tm_do_stop_process
|
||||
Quit
|
||||
|
||||
tm_do_stop_process:
|
||||
DetailPrint `Closing running "${PRODUCT_NAME}"...`
|
||||
!insertmacro TM_TASKKILL_SOFT "${APP_EXECUTABLE_FILENAME}" $tmSelfPid
|
||||
Sleep 500
|
||||
|
||||
StrCpy $R1 0
|
||||
|
||||
tm_stop_loop:
|
||||
IntOp $R1 $R1 + 1
|
||||
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 == 0
|
||||
Sleep 1000
|
||||
!insertmacro TM_TASKKILL_FORCE_TREE "${APP_EXECUTABLE_FILENAME}" $tmSelfPid
|
||||
Sleep 500
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 == 0
|
||||
DetailPrint `Waiting for "${PRODUCT_NAME}" to close.`
|
||||
Sleep 1500
|
||||
${else}
|
||||
Goto tm_app_not_running
|
||||
${endIf}
|
||||
${else}
|
||||
Goto tm_app_not_running
|
||||
${endIf}
|
||||
|
||||
${if} $R1 > 1
|
||||
MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "$(appCannotBeClosed)" /SD IDCANCEL IDRETRY tm_stop_loop
|
||||
Quit
|
||||
${else}
|
||||
Goto tm_stop_loop
|
||||
${endIf}
|
||||
|
||||
tm_app_not_running:
|
||||
${endIf}
|
||||
${endIf}
|
||||
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
Call tmPrepareCrossDriveUpdateTemp
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
!macro customInstall
|
||||
Call tmRestoreCrossDriveUpdateTemp
|
||||
!macroend
|
||||
!endif
|
||||
|
||||
!ifdef BUILD_UNINSTALLER
|
||||
; 同盘符沿用原生 $PLUGINSDIR\old-install,跨盘符改用同卷旁路目录避免 Rename 必败。
|
||||
!macro customRemoveFiles
|
||||
${if} ${isUpdated}
|
||||
StrCpy $0 $INSTDIR 2
|
||||
StrCpy $1 $PLUGINSDIR 2
|
||||
${if} $0 == $1
|
||||
CreateDirectory "$PLUGINSDIR\old-install"
|
||||
Push ""
|
||||
Call un.atomicRMDir
|
||||
Pop $R0
|
||||
${if} $R0 != 0
|
||||
DetailPrint "File is busy, aborting: $R0"
|
||||
Push ""
|
||||
Call un.restoreFiles
|
||||
Pop $R0
|
||||
Abort `Can't rename "$INSTDIR" to "$PLUGINSDIR\old-install".`
|
||||
${endIf}
|
||||
${else}
|
||||
StrCpy $2 $INSTDIR
|
||||
StrCpy $3 $2 1 -1
|
||||
${if} $3 == "\"
|
||||
StrCpy $2 $2 -1
|
||||
${endIf}
|
||||
StrCpy $tmOldBackupRoot "$2._tm_old"
|
||||
RMDir /r "$tmOldBackupRoot"
|
||||
CreateDirectory "$tmOldBackupRoot"
|
||||
|
||||
ClearErrors
|
||||
FileOpen $4 "$tmOldBackupRoot\.probe" w
|
||||
${ifNot} ${Errors}
|
||||
FileClose $4
|
||||
Delete "$tmOldBackupRoot\.probe"
|
||||
Push ""
|
||||
Call un.tmAtomicMoveToBackup
|
||||
Pop $R0
|
||||
${if} $R0 != 0
|
||||
DetailPrint "File is busy, aborting: $R0"
|
||||
Push ""
|
||||
Call un.tmRestoreFromBackup
|
||||
Pop $R0
|
||||
RMDir /r "$tmOldBackupRoot"
|
||||
Abort `Can't rename "$INSTDIR" to "$tmOldBackupRoot".`
|
||||
${endIf}
|
||||
RMDir /r "$tmOldBackupRoot"
|
||||
${else}
|
||||
; 父目录不可写时检测主程序是否被锁,未锁再清理安装目录。
|
||||
${if} ${FileExists} "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
|
||||
ClearErrors
|
||||
Rename "$INSTDIR\${APP_EXECUTABLE_FILENAME}" "$INSTDIR\${APP_EXECUTABLE_FILENAME}.tm_bak"
|
||||
${if} ${Errors}
|
||||
Abort `File is busy: "$INSTDIR\${APP_EXECUTABLE_FILENAME}".`
|
||||
${endIf}
|
||||
Rename "$INSTDIR\${APP_EXECUTABLE_FILENAME}.tm_bak" "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
|
||||
${endIf}
|
||||
${endIf}
|
||||
${endIf}
|
||||
${endIf}
|
||||
|
||||
RMDir /r $INSTDIR
|
||||
!macroend
|
||||
!endif
|
||||
@@ -1,64 +1,74 @@
|
||||
# TraceMemo 文档
|
||||
|
||||
TraceMemo 的文档按“你想完成什么”组织,而不是按源码模块组织。
|
||||
文档按产品任务和使用场景组织。需要集成或开发时,再看 Agent、概念和开发文档。
|
||||
|
||||
## 从这里开始
|
||||
## 档案与搜索
|
||||
|
||||
- [第一次使用](./user-guide/getting-started.md):安装、连接微信、完成第一次搜索和提问。
|
||||
- [查看和搜索聊天](./user-guide/chat-archive.md):找原话、回看上下文、处理媒体。
|
||||
- [用 AI 查找聊天信息](./user-guide/ai-search.md):理解普通搜索和 AI Search 的区别,并核对答案来源。
|
||||
- [第一次使用](./user-guide/getting-started.md):安装、连接微信并完成第一次搜索。
|
||||
- [Intel Mac 获取微信密钥](./user-guide/intel-mac-key.md):按页面检查结果准备环境并获取密钥。
|
||||
- [聊天档案与搜索](./user-guide/chat-archive.md):浏览联系人和群聊,按关键词、备注、昵称、微信号或 wxid 查找消息;也包含档案中的文字转语音入口,以及群聊里的「群发言统计」。
|
||||
|
||||
## 你可以完成的任务
|
||||
## AI 与知识库
|
||||
|
||||
- [建立本地知识库](./user-guide/knowledge.md)
|
||||
- [生成群聊日报和总结](./user-guide/report.md)
|
||||
- [实验性:自托管微信分享卡片](./deployment/experimental-wechat-share-card.md)
|
||||
- [交给 Agent 自动部署微信分享卡片](./skill/setup-wechat-share-card/SKILL.md)
|
||||
- [语音转文字](./user-guide/voice.md)
|
||||
- [导出聊天档案](./user-guide/export.md)
|
||||
- [防撤回](./user-guide/recall-protection.md)
|
||||
- [在微信里向 TraceMemo 提问](./agent/agent-hub.md)
|
||||
- [数据、隐私与安全](./user-guide/privacy.md)
|
||||
- [常见问题与排查](./user-guide/troubleshooting.md)
|
||||
- [AI Search / 问问微信](./user-guide/ai-search.md):用自然语言找回记得大意、但不知道在哪个会话里的内容,并查看 Evidence、Citation 和 Search Trace。
|
||||
- [本地知识库](./user-guide/knowledge.md):主动建立本地索引,提升跨会话、跨时间查询的稳定性;也包括在本机识别图片文字、让截图和公告图变得可搜索的「图片文字索引」。
|
||||
- [如何核对 AI 的回答来源](./concepts/answer-sources.md):从来源回到原始消息,检查上下文和覆盖范围。
|
||||
- [从微信数据到回答、日报和导出](./concepts/how-it-works.md):了解哪些步骤在本机完成,哪些 AI 功能可能调用 Provider。
|
||||
|
||||
## 如果你想了解 AI 为什么这样回答
|
||||
## 日报与自动化
|
||||
|
||||
- [如何核对 AI 的回答来源](./concepts/answer-sources.md):用用户语言解释依据、来源标记和查找过程。
|
||||
- [从微信数据到回答、日报和导出](./concepts/how-it-works.md):了解哪些步骤在本机完成,哪些步骤可能调用 Provider。
|
||||
- [群聊日报](./user-guide/report.md):手动生成今日、昨日或近 7 天的群聊报告,也可以在「自动化」里创建定时日报。
|
||||
- 「自动化」按三类规则执行:**@我生成日报**、**定时日报**、**退群通知**。定时日报会依次生成报告、保存 Report History,再按当前微信发送能力尝试通知;发送失败时可复用已有 PNG 重试。
|
||||
- 自动发送和监控动作通过统一执行边界,并保留执行记录;简要说明见[产品工作方式](./concepts/how-it-works.md#动作执行与审计)。
|
||||
|
||||
## 微信机器人和外部 Agent
|
||||
## 退群监控
|
||||
|
||||
TraceMemo 有两种不同的接入方式。微信机器人是普通用户可以直接使用的产品能力;Reader Skill 和 Local HTTP API 面向已经在使用 Codex、Claude Code、OpenClaw 等外部 Agent 的用户。
|
||||
退群监控会比较当前成员与上一份有效快照,记录成员退出事件。它支持多群、Last Good Snapshot 和事件历史;监控关闭期间的变化不会在重新开启后补报。成员退出同时是「自动化 → 退群通知」的触发条件。工作方式见[产品工作方式](./concepts/how-it-works.md#退群监控)。
|
||||
|
||||
| 你想做什么 | 应该看哪里 |
|
||||
| --------------------------------------------------------------------- | -------------------------------------------------------------------------- |
|
||||
| 在微信里给机器人发消息,让本机读取数据、生成总结并回复 | [Agent Hub](./agent/agent-hub.md) |
|
||||
| 在 Codex、Claude Code、OpenClaw 等外部 Agent 中主动查询过去的微信数据 | [Reader Skill](./agent/reader-skill.md) + [Local HTTP API](./agent/api.md) |
|
||||
## 语音能力
|
||||
|
||||
### 在微信里提问
|
||||
- [语音转文字](./user-guide/voice.md):在本机转写微信语音,结果可用于搜索、Knowledge 和导出。
|
||||
- [聊天档案与搜索](./user-guide/chat-archive.md#文字转语音):把文字生成微信语音,试听后发送到当前联系人或群聊;实际发送依赖本机发送能力。
|
||||
|
||||
打开应用一级导航中的“Agent”,进入“Agent Hub”后扫码登录微信机器人。机器人收到文字消息后,可以查询最近会话、读取联系人聊天、生成群聊总结图片或总结群成员发言,并把结果回复给发消息的人。它需要本地微信数据库已经连接;依赖 AI 的任务还需要配置 AI 服务。
|
||||
## Agent / API
|
||||
|
||||
- [Agent Hub](./agent/agent-hub.md):连接机器人、查看运行状态和了解实时交互边界。
|
||||
Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP API 让外部 Agent 主动查询历史数据。
|
||||
|
||||
### 让外部 Agent 查询历史微信
|
||||
- [Agent 接入概览](./agent/overview.md)
|
||||
- [Agent Hub](./agent/agent-hub.md)
|
||||
- [Reader Skill](./agent/reader-skill.md)
|
||||
- [Local HTTP API](./agent/api.md)
|
||||
- [API 安全](./agent/api-security.md)
|
||||
|
||||
连接 Reader Skill 后,你可以询问:
|
||||
## 导出与隐私
|
||||
|
||||
> “总结今天技术交流群讨论了什么。”
|
||||
> “过去一周有没有人提到这个项目?”
|
||||
- [导出聊天](./user-guide/export.md):导出 HTML、Markdown、CSV 或 JSON 档案。
|
||||
- [数据、隐私与安全](./user-guide/privacy.md):本地处理、Provider、媒体和 Token 的数据边界。
|
||||
- [常见问题与排查](./user-guide/troubleshooting.md):按安装、连接、AI、媒体和 Agent 现象排查。
|
||||
- [macOS 更新27后读不到微信数据](./user-guide/macos27-permission-recovery.md):升级 macOS 或更新应用后失去微信数据访问权限的恢复步骤。
|
||||
|
||||
- [Agent 接入概览](./agent/overview.md):先选择适合你的接入方式。
|
||||
- [Reader Skill](./agent/reader-skill.md):安装并让外部 Agent 按需读取聊天。
|
||||
- [Local HTTP API](./agent/api.md):完整端点和请求示例。
|
||||
- [API 安全](./agent/api-security.md):Bearer Token、CORS、轮换和边界。
|
||||
## 开发文档
|
||||
|
||||
## 开发与平台
|
||||
|
||||
- [macOS 数据访问说明](./platform/macos.md)
|
||||
- [开发、测试与构建](./development/overview.md)
|
||||
- [克隆 TraceMemo 后开发自己的扩展](./extensions/clone-and-customize.md)
|
||||
- [扩展 API 参考](./extensions/api-reference.md)
|
||||
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
|
||||
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
|
||||
- [企业微信插件会话只读验收](./development/wecom-enterprise-acceptance.md)
|
||||
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
|
||||
- [本地启动排障](./development/local-startup-troubleshooting.md)
|
||||
- [v2.2.0 正式品牌身份与安全升级迁移](./agent/release-notes-v2.2.0.md)
|
||||
- [v2.1.9 API 鉴权迁移说明](./agent/release-notes-v2.1.9.md)
|
||||
- [macOS 数据访问说明](./platform/macos.md)
|
||||
- [关闭 SIP 教程](./mac-disable-sip.md)
|
||||
|
||||
当前工作区版本:**2.2.0**。文档只描述当前代码已经实现的能力;版本兼容性、AI Provider 行为和媒体读取结果可能随系统、微信客户端和服务商变化。
|
||||
## 实验性功能与第三方
|
||||
|
||||
- [实验性:自托管微信分享卡片](./deployment/experimental-wechat-share-card.md)
|
||||
- [微信分享卡片自动部署 Skill](./skill/setup-wechat-share-card/SKILL.md)
|
||||
- [TraceMemo Reader Skill 文件](./skill/tracememo-reader/SKILL.md)
|
||||
|
||||
## 版本说明
|
||||
|
||||
- [v2.2.0 品牌与安全迁移](./agent/release-notes-v2.2.0.md)
|
||||
- [v2.1.9 API 鉴权迁移](./agent/release-notes-v2.1.9.md)
|
||||
|
||||
文档按当前 develop 已实现的能力维护,不在首页固定写死版本号。版本兼容性、AI Provider 行为和媒体读取结果可能随系统、微信客户端和服务商变化。
|
||||
@@ -21,14 +21,15 @@ Agent Hub 是 TraceMemo 内置的微信机器人入口,也是应用一级导
|
||||
- “帮我看看最近跟某人聊了些什么。”
|
||||
- “生成产品交流群今天的群聊总结图片。”
|
||||
|
||||
当前已实现的实时任务包括:
|
||||
Hub 把入站文字分成两类处理。
|
||||
|
||||
- 查看最近会话(数量限制为 1–20);
|
||||
- 查询你和某位联系人的近期聊天;
|
||||
- 用已配置的 AI 总结你和某位联系人近 7 天的聊天;
|
||||
- 生成今天、昨天或近 7 天的群聊总结图片;
|
||||
- 总结指定群成员在群里的近期发言;
|
||||
- 对不需要读取聊天的普通文字请求返回简短 AI 回复。
|
||||
**确定性的快捷动作**(不经过模型,命中就执行):
|
||||
|
||||
- 查看最近会话:数量限制为 1–20;
|
||||
- 生成群聊总结图片:今天、昨天或近 7 天(需要同时提到“群”和“图片 / 长图 / 日报 / 报告”);
|
||||
- 分析某个群成员的近期发言:可以指定“今天 / 昨天 / 最近 N 天”。
|
||||
|
||||
**其余问题**交给本机的 Query Agent:它和桌面端“问问微信”使用的是同一个实现,可以按需读取联系人、会话和时间范围来回答,必要时调用你在“设置 → AI 模型”里配置的 AI。例如“帮我看看最近跟某人聊了些什么”“上个月讨论过的项目地址在哪里”。
|
||||
|
||||
任务完成后,回复会发送回触发这次请求的微信用户。群聊总结会先发送进度提示,完成后发送图片。
|
||||
|
||||
@@ -56,12 +57,12 @@ Agent Hub 页面会记录系统、Agent Hub 和微信连接器日志。日志支
|
||||
|
||||
## 安全与边界
|
||||
|
||||
- Hub 使用本机通信,不把数据库直接暴露到公网;
|
||||
- Hub 在主进程内运行,不开放本地监听端口;它不会把数据库暴露到公网;
|
||||
- 机器人账号和个人微信账号是不同的登录边界,请确认你连接的是正确账号;
|
||||
- 机器人回复会发送给当前发消息的人;开发者 API 另有受保护的测试发送入口,使用前必须确认接收者;
|
||||
- Hub 生成群聊总结时仍可能调用你配置的 AI Provider;
|
||||
- 当前实时自然语言入口主要处理文字消息。底层连接器可以接收图片、语音、文件和视频,但 Agent Hub 尚未为这些媒体提供同等的实时意图处理;
|
||||
- 当前没有实现群发、广播、定时任务或通用自主操作微信;
|
||||
- Hub 理解请求或生成总结时,会调用你在“设置 → AI 模型”配置的 Provider;
|
||||
- 当前实时入口只处理文字消息。连接器会归一化收到的消息条目,但 Agent Hub 只把文本条目当作意图处理,尚未为图片、语音、文件和视频提供同等能力;
|
||||
- 当前没有实现群发、广播、定时任务或通用自主操作微信(定时日报属于「自动化」,不是 Agent Hub);
|
||||
- 本页面的“Agent Hub 状态”可以通过 Local HTTP API 查询,但不要把它误认为外部 Agent 的实时消息订阅接口或 MCP Server。
|
||||
|
||||
## 无法连接时
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
|
||||
TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑上的 API Center、Reader Skill、CLI 和 Agent,不是公网网关,也不是带用户账户和细粒度权限 Scope 的服务。
|
||||
|
||||
它同时包含**写入型**端点:生成报告并渲染 PNG(`/report`)、通过已连接机器人发送微信消息(`/agent/send`)、创建/修改/删除/启停定时日报任务并触发立即执行(`/scheduled-reports*`)。因此这个 Token 相当于本机敏感凭据,而不是一个只读查询键。
|
||||
|
||||
## Bearer Token
|
||||
|
||||
新 Agent 配置使用 `TRACEMEMO_API_TOKEN`。v2.2.0 仍兼容读取历史变量 `WECHATEXPLORER_API_TOKEN`,优先级为新变量高于旧变量。
|
||||
新 Agent 配置使用 `TRACEMEMO_API_TOKEN`。历史变量名 `WECHATEXPLORER_API_TOKEN` 仍被兼容读取,优先级为新变量高于旧变量;当前没有设定旧变量名的移除时间,新配置不要再使用它。
|
||||
|
||||
- `/api/v1/health` 是公开健康检查;
|
||||
- 其他所有端点都要求 `Authorization: Bearer <TOKEN>`;
|
||||
@@ -14,7 +16,8 @@ TraceMemo 的本地 API 默认监听 `127.0.0.1:6131`。它面向同一台电脑
|
||||
- Token 由 Electron `safeStorage` 加密保存在用户数据目录的 `local-api-token.bin`;
|
||||
- 文件权限设置为 `0600`;
|
||||
- 在“API Center”中可以显示、复制和重新生成;
|
||||
- 重新生成后旧 Token 立即失效。
|
||||
- 重新生成后旧 Token 立即失效;
|
||||
- 服务端只认这个 Token,**不接受用环境变量覆盖**——Agent 一侧的环境变量只是把 Token 交给 Agent 自己的方式,不是鉴权来源。
|
||||
|
||||
应用不会自动把 Token 写入 Codex、Claude Code、OpenClaw 或其他 Agent 配置。请把它放进 Agent 自己的本地 secret/environment,例如:
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
- API 前缀:`/api/v1`
|
||||
- 默认只监听 loopback;不要把它当作公网服务。
|
||||
- `/api/v1/health` 无需 Token;其他端点需要 `Authorization: Bearer <TOKEN>`。
|
||||
- 请求体使用 JSON;响应为 JSON。
|
||||
- 请求体使用 JSON,单个请求体最大 `1 MiB`;超限返回 `413`。
|
||||
- 错误响应包含 `requestId`,响应头包含 `X-Request-Id`。客户端可传入 1-128 位的 `[A-Za-z0-9._:-]` 标识,否则服务端会生成 UUID。
|
||||
- 不支持的 HTTP method 返回 `405` 和 `Allow` 响应头。
|
||||
|
||||
## 最小请求
|
||||
|
||||
@@ -24,31 +26,257 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||
|
||||
不要把 Token 放入 URL、Skill 文件、仓库或命令历史可被共享的脚本中。
|
||||
|
||||
新配置必须优先使用 `TRACEMEMO_API_TOKEN`。已安装的旧 Reader Skill 可在 v2.2.0 兼容期内继续读取 `WECHATEXPLORER_API_TOKEN`;如果两个变量都存在,以新变量为准。
|
||||
新配置必须优先使用 `TRACEMEMO_API_TOKEN`。应用生成的安装指令仍会提示:尚未升级的旧配置可以继续读取 `WECHATEXPLORER_API_TOKEN`,但新配置必须使用新变量名;如果两个变量都存在,以新变量为准。当前没有设定旧变量名的移除时间。
|
||||
|
||||
Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:Agent 侧的环境变量只是把 Token 传给 Agent 自己的方式,不是服务端的鉴权来源。
|
||||
|
||||
## 端点
|
||||
|
||||
| 方法 | 路径 | 作用 | 参数/请求体 |
|
||||
| ---- | ---------------------------- | -------------------------------------- | --------------------------------------------------------------- |
|
||||
| GET | `/api/v1/health` | 服务与数据库健康状态 | 无 |
|
||||
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
|
||||
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
|
||||
| GET | `/api/v1/chatroom` | 群聊列表 | `keyword` |
|
||||
| GET | `/api/v1/recent_chat` | 最近会话 | `limit`,默认 50 |
|
||||
| GET | `/api/v1/chatlog` | 指定会话的聊天记录 | 必填 `talker`;可选 `time` 或 `startTime`/`endTime` |
|
||||
| GET | `/api/v1/media/{messageId}` | 获取图片消息的二进制资源 | 使用 `/chatlog` 返回的图片消息 `id` |
|
||||
| GET | `/api/v1/group_snapshot` | 群成员快照 | 必填 `md5` |
|
||||
| GET | `/api/v1/resolve` | 将昵称、wxid 或 md5 解析为会话 | 必填 `q` |
|
||||
| POST | `/api/v1/report` | 将结构化日报渲染为 HTML 与 PNG | `GroupReportExportRequest` JSON |
|
||||
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
|
||||
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
|
||||
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
|
||||
| 方法 | 路径 | 作用 | 参数/请求体 |
|
||||
| ------ | --------------------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------- |
|
||||
| GET | `/api/v1/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` |
|
||||
| GET | `/api/v1/recent_chat` | 最近会话 | `limit`,默认 50 |
|
||||
| GET | `/api/v1/chatlog` | 指定会话的聊天记录 | 必填 `talker`;可选 `time` 或 `startTime`/`endTime` |
|
||||
| GET | `/api/v1/media/{mediaId}` | 获取图片消息的二进制资源 | 原样使用 `/chatlog` 返回的 `media.url`,不要用消息 `id` 拼接 |
|
||||
| GET | `/api/v1/group_snapshot` | 群成员快照 | 必填 `md5` |
|
||||
| GET | `/api/v1/resolve` | 将昵称、wxid 或 md5 解析为会话 | 必填 `q` |
|
||||
| POST | `/api/v1/report` | 将结构化日报渲染为 HTML 与 PNG | `GroupReportExportRequest` JSON |
|
||||
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
|
||||
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
|
||||
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
|
||||
| POST | `/api/v1/wechat/send` | 用本机微信账号把消息发给别人 | `{ "to": "wxid 或 filehelper", "type": "text\|image\|voice", "text": "..." }` |
|
||||
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信发送能力状态 | 无 |
|
||||
| GET | `/api/v1/scheduled-reports` | 定时日报任务列表 | 无 |
|
||||
| POST | `/api/v1/scheduled-reports` | 创建定时日报任务 | `ScheduledReportApiCreateRequest` JSON |
|
||||
| GET | `/api/v1/scheduled-reports/{id}` | 查询单个定时日报任务 | 无 |
|
||||
| PATCH | `/api/v1/scheduled-reports/{id}` | 修改定时日报任务 | `ScheduledReportApiUpdateRequest` JSON |
|
||||
| DELETE | `/api/v1/scheduled-reports/{id}` | 删除定时日报任务 | 无 |
|
||||
| POST | `/api/v1/scheduled-reports/{id}/enable` | 启用定时日报任务 | 无 |
|
||||
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停定时日报任务 | 无 |
|
||||
| POST | `/api/v1/scheduled-reports/{id}/run` | 立即执行一次并返回 execution | 无 |
|
||||
| GET | `/api/v1/scheduled-reports/{id}/executions` | 查询某个任务的执行记录 | 无 |
|
||||
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 兼容占位路由;当前返回 `501 not_supported` | 无 |
|
||||
| GET | `/api/v1/capabilities` | TraceMemo 应用能力和可用状态 | 无 |
|
||||
| GET | `/api/v1/automations` | 自动化规则列表 | 可选 `type`、`enabled` |
|
||||
| POST | `/api/v1/automations` | 创建默认停用的自动化规则 | Automation draft JSON |
|
||||
| POST | `/api/v1/automations/validate` | 校验规则,不保存、不执行 | Automation draft JSON |
|
||||
| GET | `/api/v1/automations/{id}` | 查询单条自动化规则 | 无 |
|
||||
| PATCH | `/api/v1/automations/{id}` | 更新规则配置 | 可变配置字段 JSON |
|
||||
| DELETE | `/api/v1/automations/{id}` | 删除自定义规则 | 系统内置规则受保护 |
|
||||
| POST | `/api/v1/automations/{id}/enable` | 校验并启用规则 | 无 |
|
||||
| POST | `/api/v1/automations/{id}/disable` | 停用规则 | 无 |
|
||||
| GET | `/api/v1/automations/executions` | 查询自动化执行记录 | `ruleId`、`status`、`since`、`until`、`limit` |
|
||||
| GET | `/api/v1/monitors/group-exits` | 查看退群监控状态 | 无 |
|
||||
| PATCH | `/api/v1/monitors/group-exits` | 配置监控群范围或启停 | `enabled`、`monitoredConversationIds` |
|
||||
| GET | `/api/v1/monitors/group-exits/events` | 查询退群事件历史 | `conversationId`、`since`、`until`、`limit` |
|
||||
| GET | `/api/v1/groups/{conversationId}/member-stats` | 查询群成员活跃统计 | 必填 `conversationId`、`start`、`end` |
|
||||
|
||||
`/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。
|
||||
|
||||
## 发送消息 API
|
||||
|
||||
两个发送端点走**完全不同的通道**,用途也不同,不要混用。
|
||||
|
||||
| | `POST /api/v1/wechat/send` | `POST /api/v1/agent/send` |
|
||||
| --- | --- | --- |
|
||||
| 通道 | 本机微信(macOS native runtime / Windows hook) | Agent Hub 机器人(iLink) |
|
||||
| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 |
|
||||
| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) |
|
||||
| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` |
|
||||
| 内容类型 | `text` / `image` / `voice` / `file`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
|
||||
| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` |
|
||||
|
||||
### 本地发送:`POST /api/v1/wechat/send`
|
||||
|
||||
用你正在登录的微信账号发消息。**这是唯一能把消息发给别人(而不是发给机器人自己)的端点。**
|
||||
|
||||
```bash
|
||||
: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
|
||||
curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
|
||||
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"to":"filehelper","type":"text","text":"来自 Agent 的一条消息"}'
|
||||
|
||||
# 发送本地文件(macOS / Windows 均走本机发送能力)
|
||||
curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
|
||||
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"to":"filehelper","type":"file","filePath":"/abs/path/report.pdf","fileName":"周报.pdf"}'
|
||||
```
|
||||
|
||||
请求体:
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid |
|
||||
| `type` | 否 | `text`(默认)/ `image` / `voice` / `file` |
|
||||
| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 |
|
||||
| `filePath` | `type=image\|voice\|file` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络文件时先落盘 |
|
||||
| `fileName` | 否 | 仅 `type=file`:接收方看到的文件名。macOS 会透传;Windows 当前由 runtime 使用 `filePath` 的 basename,`fileName` 可能被忽略 |
|
||||
| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 |
|
||||
| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 |
|
||||
|
||||
发送前会先校验当前发送能力(等价于 `GET /api/v1/wechat-personal/send-capability`):`ready=false` 时直接返回 `503`,不会进入投递;`capabilities[type]=false` 时返回 `503 SEND_NOT_READY`。
|
||||
|
||||
> **没有 3 秒节流。** 自动化规则(定时日报、退群通知)之间共享 3 秒发送间隔,但本端点属于手动发送,**不受该队列约束**:连续调用会连续投递。Agent 需要自行控制频率,不要用它循环刷消息。
|
||||
|
||||
响应:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"status": "sent",
|
||||
"actionId": "5f0c…",
|
||||
"recipient": { "type": "contact", "id": "filehelper" },
|
||||
"contentType": "text",
|
||||
"durationMs": 842
|
||||
}
|
||||
```
|
||||
|
||||
| HTTP | `errorCode` | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `400` | `INVALID_REQUEST` / `INVALID_RECIPIENT` | 字段缺失、`text` 超长、`filePath` 不存在 |
|
||||
| `403` | `POLICY_BLOCKED` / `ACTION_NOT_ALLOWED` / `RECIPIENT_SCOPE_VIOLATION` | 发送策略拒绝 |
|
||||
| `502` | `SEND_FAILED` | 已进入投递,底层发送失败(看 `error`) |
|
||||
| `503` | `SEND_CAPABILITY_UNAVAILABLE` | 微信未启动 / 未绑定 / 未初始化 |
|
||||
| `503` | `SEND_NOT_READY` | 能力在,但不支持该内容类型(例如语音 hook 未就绪) |
|
||||
| `503` | `UNSUPPORTED_PLATFORM` | 非 macOS / Windows |
|
||||
| `500` | `INTERNAL_ERROR` | 网关执行抛出未预期异常 |
|
||||
|
||||
> **`status: "sent"` 只代表投递成功,不等于消息已写入本地数据库。** TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不会写入。因此不要用 `/api/v1/chatlog` 回查自己刚发的消息来判断是否发送成功 —— 查不到是正常现象;也**不要**因为本地库没有就重发,那会产生真实的重复消息。需要人工确认时,让对方用手机微信或另一个账号查看会话。
|
||||
|
||||
每一次发送都会写入 `actions/wechat-actions.json` 审计记录(`origin` 为 `http_api`),可在 Send Log 中核对。这份记录证明的是「调用过并成功投递」,**不能**证明对方已收到或本地库已落库。
|
||||
|
||||
### 机器人通知:`POST /api/v1/agent/send`
|
||||
|
||||
走已扫码的 Agent Hub 连接器,给**自己**发一条测试消息,用于确认机器人链路是否通畅。它不适合「通知某人」这类场景 —— 那要用上面的 `/api/v1/wechat/send`。
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:6131/api/v1/agent/send \
|
||||
-H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"to":"<你的 wxid>","text":"connector ok"}'
|
||||
```
|
||||
|
||||
`to` 省略时回落到当前登录账号自己。`media_url` 可传 URL。连接器离线返回 `503`,凭证过期返回 `401`。
|
||||
|
||||
## Application Capabilities
|
||||
|
||||
`GET /api/v1/capabilities` 描述 TraceMemo 应用级能力和当前运行环境;`GET /api/v1/query/capabilities` 只描述结构化 Query primitive,两者不是同一份目录。应用能力使用 `supported` 和 `available` 分开表示“代码支持”与“当前可用”;运行时原因使用稳定的简短 code,不返回 Token、数据库路径、微信密钥或 sender 诊断路径。
|
||||
|
||||
响应包含应用版本、数据库 readiness、Query、Automation、退群监控、群统计,以及个人微信/iLink 的能力状态。`groupExitMonitor.operations` 当前声明 `read_state`、`configure_scope`、`enable`、`disable`、`list_events`;`groupStats.operations` 当前声明 `member_stats`。能力声明不会触发监控扫描或群统计查询。
|
||||
|
||||
```bash
|
||||
: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
|
||||
BASE="http://127.0.0.1:6131/api/v1"
|
||||
AUTH="Authorization: Bearer $TRACEMEMO_API_TOKEN"
|
||||
curl -H "$AUTH" "$BASE/capabilities"
|
||||
```
|
||||
|
||||
## Group Exit Monitor API
|
||||
|
||||
退群监控只负责“监测哪些群、发现了哪些退群事实”。退群后是否通知、通知到哪里以及通知模板,仍由 `leave_notification` Automation singleton 负责;修改监控范围不会隐式修改该 Automation。
|
||||
|
||||
### 查看和配置监控
|
||||
|
||||
```bash
|
||||
curl -H "$AUTH" "$BASE/monitors/group-exits"
|
||||
|
||||
curl -X PATCH -H "$AUTH" -H 'Content-Type: application/json' \
|
||||
"$BASE/monitors/group-exits" \
|
||||
-d '{"enabled":true,"monitoredConversationIds":["123@chatroom"]}'
|
||||
```
|
||||
|
||||
`monitoredConversationIds` 只接受当前联系人列表中精确存在的群 `roomId`(例如 `xxx@chatroom`),不接受群名、md5、个人联系人、重复或空 ID。请求至少提供 `enabled` 或 `monitoredConversationIds` 其中一个;传空数组表示清空监控范围。服务会先校验全部群,再执行一次原子配置。PATCH 返回最终完整状态。
|
||||
|
||||
状态中的 `eventCount` 是持久化退群事件总数,`lastCheckedAt`/`lastReadAt` 为空时返回 `null`。GET 不会调用 `checkNow()`,也不会触发通知发送。
|
||||
|
||||
### 查询退群事件
|
||||
|
||||
```bash
|
||||
curl -G -H "$AUTH" "$BASE/monitors/group-exits/events" \
|
||||
--data-urlencode 'conversationId=123@chatroom' \
|
||||
--data-urlencode 'since=2026-10-01T00:00:00+07:00' \
|
||||
--data-urlencode 'until=2026-10-02T23:59:59+07:00' \
|
||||
--data-urlencode 'limit=50'
|
||||
```
|
||||
|
||||
时间参数必须是带 offset 的 ISO-8601;默认 `limit=50`,最大 200。事件按 `detectedAt` 升序返回。事件 DTO 使用 `eventId`、稳定的 `conversationId` 和 `memberId`,并把时间输出为 ISO-8601;当前整体已读状态不会伪造成 event-level `read` 字段。当前未开放 clear events、markRead 或 checkNow HTTP 路由。
|
||||
|
||||
一个典型 Agent 工作流是:先通过 `/resolve` 或 `/contact` 找到稳定群 ID,再 PATCH monitor scope;如需通知,再单独 PATCH `leave_notification` Automation,调用 `/automations/validate`,最后启用规则。
|
||||
|
||||
## Group Member Stats API
|
||||
|
||||
```bash
|
||||
curl -G -H "$AUTH" "$BASE/groups/123%40chatroom/member-stats" \
|
||||
--data-urlencode 'start=2026-09-01T00:00:00+07:00' \
|
||||
--data-urlencode 'end=2026-10-01T00:00:00+07:00'
|
||||
```
|
||||
|
||||
`conversationId` 必须是当前联系人列表中精确存在的群 `roomId`;不存在返回 `NOT_FOUND`,个人联系人返回 `NOT_GROUP_CONVERSATION`。`start` 和 `end` 必须同时提供,且使用带 offset 的 ISO-8601,`start` 不能晚于 `end`。HTTP adapter 只负责把稳定群 ID 解析为内部 md5 并调用现有 `GroupStatsService`,不会在 HTTP 层重新统计消息。
|
||||
|
||||
响应中的 `activeMembers` 和 `silentMembers` 都只描述当前成员名单;成员使用 `memberId`,活跃成员的 `lastMessageAt` 和 `range` 时间均为 ISO-8601。`freshness`、`complete`、`limitations` 必须原样保留,`unattributedMessages` 与 `excludedSystemMessages` 用于诊断,`firstMessageAt` 没有消息时为 `null`。当前成员统计不等于完整历史成员统计,`limitations` 表达的退群成员或未归档时段不能从文本中推导成额外的 `formerMembers`,也不会伪造 `totalMessageCount`。
|
||||
|
||||
## Automation API
|
||||
|
||||
`/api/v1/automations*` 是 Automation 的 canonical HTTP API,读写唯一的 `AutomationRuleStore`。它支持当前真实规则类型:`daily_report`、`scheduled_report`、`leave_notification`。本 API 不提供立即执行、重试或清理执行记录。
|
||||
|
||||
旧 `/api/v1/scheduled-reports*` 保持兼容,不设移除日期;它是面向旧 DTO 的受限 compatibility API,不是第二份存储,也不能表示所有新的定时日报目标和配置。新的 Agent 集成应使用 `/automations`。
|
||||
|
||||
创建和校验规则时 `enabled` 只能缺省或为 `false`。创建成功后必须调用 `/automations/{id}/enable` 才会启用。启用会重新校验当前规则;数据库未就绪、目标无法解析或配置无效时不会启用。`PATCH` 只接受规则配置字段,不可改 `ruleType`、`id`、创建/更新时间或 `enabled`;启停必须使用独立 endpoint。未知字段和未知枚举会被拒绝。
|
||||
|
||||
会话范围优先传 `wxid`、`roomId`(如 `xxx@chatroom`)或 canonical conversation ID。唯一匹配的联系人名可被解析为稳定 ID;重名会返回 `ambiguous_contact`,不会猜测。`daily_report.conditions.conversationIds` 在对外 API 中使用稳定 ID,Store 内部仍沿用既有 md5 口径。
|
||||
|
||||
校验请求不落盘、不发消息,也不执行规则。`valid: false` 时查看 `issues`;有效时 `normalized` 是经 ID 解析后的草稿,`effects` 描述启用后的动作,定时日报另外返回按本机时区计算的 `nextRunAt`。
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "产品群每日日报",
|
||||
"ruleType": "scheduled_report",
|
||||
"scheduledReport": {
|
||||
"schedule": { "time": "20:00" },
|
||||
"report": {
|
||||
"sourceConversationId": "wxid_product@chatroom",
|
||||
"range": "today",
|
||||
"messageTypes": ["text", "image"],
|
||||
"templateId": "v1",
|
||||
"memberNameMode": "groupNickname",
|
||||
"timeoutSeconds": 300
|
||||
},
|
||||
"target": { "type": "file_transfer" },
|
||||
"postfixText": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
执行历史只读,默认最多返回 50 条,`limit` 范围是 1-200。`since` 和 `until` 接受带时区的 ISO-8601 时间;execution 本身最多留存 200 条。`running` 记录的 `finishedAt` 为 `null`。
|
||||
|
||||
新 Agent API 的错误格式:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "VALIDATION_FAILED",
|
||||
"message": "自动化规则校验失败",
|
||||
"details": []
|
||||
},
|
||||
"requestId": "..."
|
||||
}
|
||||
```
|
||||
|
||||
常见错误码包括 `UNAUTHORIZED`、`METHOD_NOT_ALLOWED`、`PAYLOAD_TOO_LARGE`、`INVALID_ARGUMENT`、`NOT_FOUND`、`NOT_GROUP_CONVERSATION`、`DATABASE_NOT_READY`、`VALIDATION_FAILED`、`SINGLETON_RULE`、`PROTECTED_RULE` 和 `PERSISTENCE_FAILED`。`leave_notification` 是固定单例:可读取、修改和启停,但不能创建第二条或删除。内置 `@我生成日报` 同样不能通过 HTTP 删除。
|
||||
|
||||
### 这些端点与实时机器人有什么关系
|
||||
|
||||
- `/api/v1/agent/status` 只用于查询 Agent Hub、微信连接器和数据库状态;
|
||||
- `/api/v1/agent/group-report` 由外部 Agent 或脚本主动请求生成群聊总结图片;
|
||||
- `/api/v1/agent/send` 是受 Bearer Token 保护的开发者/测试发送入口,用于通过已经连接的机器人发送文字或本地图片;它不是任意群发能力,也不是实时消息订阅接口;
|
||||
- `/api/v1/scheduled-reports*` 会**写入**应用状态:创建、修改、删除、启停定时日报任务,以及立刻执行一次。加上 `/report` 和 `/agent/send`,这个 API 并非只读接口——拿到 Token 就能改配置、生成报告并发送微信消息,请按本机敏感凭据对待;
|
||||
- `POST /api/v1/scheduled-reports/{id}/run` 与定时触发共用同一条链路:读取群聊 → 生成报告 → 保存 Report History → 尝试发送;
|
||||
- 当前 API 没有对外暴露实时入站 webhook。微信消息由应用内部的 Agent Hub 和微信连接器接收、处理和回复。
|
||||
|
||||
## 时间查询
|
||||
@@ -83,11 +311,13 @@ curl -H "$AUTH" "$BASE/chatlog?talker=技术交流群&time=2026-08-07"
|
||||
## 响应与错误
|
||||
|
||||
- `200`:请求成功;
|
||||
- `201`:定时日报任务创建成功;
|
||||
- `401`:缺少、错误或已失效的 Bearer Token;
|
||||
- `400`:参数或 JSON 请求体无效;
|
||||
- `422`:媒体 `messageId` 无效,或目标消息不是可读取的图片;
|
||||
- `422`:媒体标识格式错误,或目标消息不是可读取的图片(`NOT_IMAGE`);
|
||||
- `403`:浏览器 Origin 不在允许的 loopback 列表;
|
||||
- `404`:端点、会话或群聊不存在;
|
||||
- `409`:定时日报任务重复(`error === "duplicate"`,响应里会带回已存在的任务),或群聊名称匹配到多个目标(`ambiguous_contact`);
|
||||
- `404`:端点、会话或群聊不存在;媒体标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。媒体请求遇到此状态时,先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在;
|
||||
- `503`:数据库或 Agent Hub 尚未就绪;
|
||||
- `500`:服务端处理或报告渲染失败。
|
||||
|
||||
@@ -102,13 +332,196 @@ curl -H "$AUTH" "$BASE/chatlog?talker=技术交流群&time=2026-08-07"
|
||||
"media": {
|
||||
"type": "image",
|
||||
"available": true,
|
||||
"url": "/api/v1/media/msg_xxx"
|
||||
"url": "/api/v1/media/image%3A0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
当用户要求查看或理解图片时,使用 `media.url` 获取 `image/jpeg`、`image/png` 等真实二进制;不要根据 `[图片]` 猜测内容,也不要向 API 传入本地路径。
|
||||
|
||||
`media.url` 包含当前数据库连接内的独立媒体标识,不等同于消息 `id`。不同会话的消息 `id` 可能重复,调用方应原样使用返回的地址,不自行拼接或解析。重启、重连或切换账号后须重新读取 `/chatlog` 获取新地址;旧的纯消息 ID 地址仅在无歧义时兼容。`available` 只表示消息带有图片定位信息,不保证本地图片文件仍存在或可以解密。
|
||||
|
||||
## 与 MCP 的关系
|
||||
|
||||
当前实现没有把 `6131` 暴露为 MCP Server。需要在 Agent 中使用时,请安装随应用提供的 Reader Skill,并让 Skill 通过普通 HTTP 请求调用本 API。
|
||||
|
||||
## LLM-friendly Query Tool API
|
||||
|
||||
这些端点提供稳定的结构化 Query primitive,不接收自然语言问题,也不会调用 AI。它们与现有 API 共用端口、Bearer Token、loopback 和 CORS 安全策略。
|
||||
|
||||
```bash
|
||||
BASE="http://127.0.0.1:6131/api/v1"
|
||||
AUTH="Authorization: Bearer ${TRACEMEMO_API_TOKEN:-$WECHATEXPLORER_API_TOKEN}"
|
||||
|
||||
# 能力目录
|
||||
curl -H "$AUTH" "$BASE/query/capabilities"
|
||||
|
||||
# BOBO 的第一条真实互动
|
||||
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/messages" \
|
||||
-d '{"target":{"query":"BOBO"},"timeRange":{"kind":"all"},"direction":"any","order":"asc","limit":1,"excludeSystem":true}'
|
||||
|
||||
# 上个月 BOBO 发来的文件
|
||||
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/messages" \
|
||||
-d '{"target":{"query":"BOBO"},"timeRange":{"kind":"previous_month"},"direction":"from_target","messageTypes":["file"],"order":"desc","limit":1}'
|
||||
|
||||
# 受限语义关键词检索(最多 4 个 variants)
|
||||
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/search" \
|
||||
-d '{"target":{"query":"BOBO"},"timeRange":{"kind":"all"},"query":"答应之后给我或者帮我完成某件事情","variants":["我给你","我发你","弄好给你"],"limit":20}'
|
||||
|
||||
# 按会话和时间范围提取可供总结的证据
|
||||
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/conversation-overview" \
|
||||
-d '{"target":{"query":"BOBO"},"timeRange":{"kind":"previous_month"}}'
|
||||
```
|
||||
|
||||
`query/messages` 的 `messageRef` 是服务端生成的不透明引用,可直接传给 `query/message-context` 获取前后文;不要自行构造 wxid、md5 或数据库路径。
|
||||
|
||||
每条消息都会返回 `messageType`(`text`、`image`、`voice`、`video`、`file`、`link`、`sticker`、`system` 或 `other`)。非文本消息不会伪造 `text`;可识别的图片、视频、贴纸和文件会返回不含密钥或本地路径的 `attachment` 元数据。
|
||||
|
||||
`conversation-overview` 同时返回 `sourceCoverage` 与 `selection`:前者描述时间范围内源消息是否完整及 `sourceMessageCount`,后者描述从源消息中选出的 Evidence 数量及是否抽样。`evidence` 最终按 `timestamp` 升序返回,`messageRef` 是唯一推荐的消息引用。
|
||||
`conversation-overview` 另有一个 `origin` 字段:`wcdb` 表示这次证据直接来自本机聊天数据库(会话概览的事实来源),`knowledge` 表示来自本地索引。
|
||||
|
||||
### 搜索范围(scope)
|
||||
|
||||
`query/messages`、`query/search`、`query/message-context` 和 `query/conversation-overview` 都接受一个可选的 `scope`,用来把检索限制在一个确定的语料边界内:
|
||||
|
||||
| scope | 含义 |
|
||||
| ----------------------------------------- | -------------------------------------------------------------------- |
|
||||
| `{"kind":"all"}` | 所有可读会话(默认;省略 `scope` 等价于此) |
|
||||
| `{"kind":"groups"}` | 只搜群聊语料,**且包含群成员实际发送的消息**(不是群名称或群元数据) |
|
||||
| `{"kind":"contact","conversationId":"…"}` | 只搜该一对一会话 |
|
||||
| `{"kind":"current","conversationId":"…"}` | 只搜指定的那个会话(单聊或群聊) |
|
||||
|
||||
`conversationId` 是会话标识,可用 `/api/v1/resolve` 或 `/api/v1/contact` 得到。`scope` 一旦给出就是**权威边界**:`target` 落在范围之外会被拒绝(`status: "invalid_tool_arguments"`、`constraint: "target_outside_scope"`),不会静默扩大范围;范围里包含多个会话时,`query/messages` 与 `query/conversation-overview` 必须显式指定 `target`(`constraint: "target_required_for_scope"`)。
|
||||
|
||||
响应会回显实际生效的边界:
|
||||
|
||||
```json
|
||||
{ "scope": { "kind": "groups", "conversationCount": 243 } }
|
||||
```
|
||||
|
||||
跨会话检索时,`evidence` 的每一项都会带上它所属的会话,便于把结果归属到具体群 / 联系人与具体成员:
|
||||
|
||||
```json
|
||||
{
|
||||
"messageRef": "…",
|
||||
"conversationName": "某个群",
|
||||
"conversationType": "group",
|
||||
"sender": "某成员",
|
||||
"timestamp": 1789099069000,
|
||||
"text": "…"
|
||||
}
|
||||
```
|
||||
|
||||
### 索引新鲜度(freshness)
|
||||
|
||||
`query/search` 依赖本地索引,而本地索引是异步建立的派生数据,可能落后于聊天数据库。因此它的响应会显式给出覆盖口径:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| ------------------- | ------------------------------------------------------------------- |
|
||||
| `indexLatestAt` | 索引目前覆盖到的源数据时间(epoch ms),`null` 表示无法判定 |
|
||||
| `sourceLatestAt` | 聊天数据库里最新的活跃时间(epoch ms),`null` 表示无法判定 |
|
||||
| `coverage.state` | `complete` 只在索引确实覆盖了所请求的时间范围时出现 |
|
||||
| `freshness.catchUp` | 本次为追赶索引做了什么:`none` / `reused` / `completed` / `pending` |
|
||||
|
||||
调用方**必须**把 `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.4.0`);
|
||||
- `/api/v1/health` 的 `skill.version` 回报当前应用内置的版本;
|
||||
- 两者不一致,就说明 Agent 手里那份已经过期,接口契约可能已经变化。
|
||||
|
||||
### 检查更新
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:6131/api/v1/health
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"ready": true,
|
||||
"service": "TraceMemo Reader",
|
||||
"version": "2.5.1",
|
||||
"skill": { "name": "tracememo-reader", "version": "1.4.0", "available": true },
|
||||
"timestamp": "2026-10-13T08:43:52.863Z"
|
||||
}
|
||||
```
|
||||
|
||||
注意区分两个版本号:`version` 是应用版本,`skill.version` 才是 Reader Skill 的版本。Skill 文件读不到时 `available` 为 `false`、`skill.version` 为 `null`,此时 health 仍然返回 `200`——外部 Agent 靠它做自检,这个接口不允许因为 Skill 缺失而失败。
|
||||
|
||||
### 拉取最新 Skill
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "tracememo-reader",
|
||||
"version": "1.4.0",
|
||||
"contentHash": "<sha256 hex>",
|
||||
"modifiedAt": "2026-10-13T08:37:30.000Z",
|
||||
"markdown": "---\nname: tracememo-reader\nversion: 1.4.0\n…"
|
||||
}
|
||||
```
|
||||
|
||||
`markdown` 就是可以直接落盘的 SKILL.md 全文,`contentHash` 是它的 SHA-256,可用来核对写入结果。响应**不包含**任何本地文件路径。`503 skill_unavailable` 表示应用侧也没找到 Skill 文件,需要重新安装 TraceMemo。
|
||||
|
||||
### Agent 侧的自检义务
|
||||
|
||||
`docs/skill/tracememo-reader/SKILL.md` 中的「版本自检」要求 Agent 在每次会话开始时比对一次版本:不一致就停止读取数据并提醒用户重新安装;用户同意后,Agent 可以直接调用上面的接口自助覆盖本地文件,不需要用户重新复制安装指令。
|
||||
|
||||
修改 `SKILL.md` 内容时必须同步提升 `version`。CI 中的 `pnpm check:skill-version` 会在"只改文档、不升版本"时失败,避免再次出现"文档改了两轮、版本号纹丝不动"的情况。
|
||||
@@ -8,7 +8,7 @@ Reader Skill 是一份给 Agent 的操作说明。安装后,Codex、Claude Cod
|
||||
|
||||
Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不负责二维码登录、监听微信实时消息、接收机器人消息或管理 Agent Hub。想让机器人收到微信消息后处理并回复,请阅读[Agent Hub](./agent-hub.md)。
|
||||
|
||||
正式 Reader Skill 名称和目录是 `tracememo-reader`,新安装使用 `TRACEMEMO_API_TOKEN`。已安装的旧 `wechatexplorer-reader` 可在 v2.2.0 兼容期内继续使用旧变量。
|
||||
正式 Reader Skill 名称和目录是 `tracememo-reader`,新安装使用 `TRACEMEMO_API_TOKEN`。已安装的旧 `wechatexplorer-reader` 仍可继续使用旧变量 `WECHATEXPLORER_API_TOKEN`(当前没有设定移除时间),但新安装请使用新名称与新变量名。
|
||||
|
||||
## 推荐安装流程
|
||||
|
||||
@@ -26,6 +26,21 @@ Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不
|
||||
|
||||
TraceMemo 不会自动把 Token 写进 Agent 配置。重新生成 Token 后,必须同步更新 Agent 环境。
|
||||
|
||||
## 更新已安装的 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 的读取顺序
|
||||
|
||||
当用户使用“今天”“昨天”“本周”等相对时间时:
|
||||
@@ -53,8 +68,14 @@ Reader Skill 可以指导 Agent 使用:
|
||||
- 指定会话、日期或时间戳范围的聊天记录;
|
||||
- 群成员快照;
|
||||
- 结构化日报渲染和按群聊生成总结图片;
|
||||
- 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认;
|
||||
- 个人微信发送能力状态查询(`/wechat-personal/send-capability`);
|
||||
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`、`voice-transcribe`;
|
||||
- 自身版本查询(`/skill/tracememo-reader`),用于判断是否需要更新;
|
||||
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
|
||||
|
||||
注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。
|
||||
|
||||
端点、参数、错误码和鉴权细节以[Local HTTP API](./api.md)为准。Skill 文件保持短小,避免在多个文档中复制会变化的完整响应 schema。
|
||||
|
||||
## 隐私边界
|
||||
|
||||
@@ -28,12 +28,12 @@ AI 回答后,你可以继续查看它参考了哪些聊天内容、这些内
|
||||
|
||||
来源覆盖受时间范围、会话范围、索引状态和可读媒体影响。例如:
|
||||
|
||||
- Knowledge 正在同步时,新的分析会被暂停;
|
||||
- Knowledge 还没追到最新时,跨会话检索只覆盖到索引当前的时间点,答案会标注这个范围;
|
||||
- 语音没有转写时,AI 可能只能看到消息类型;
|
||||
- 图片无法读取或未启用图片理解时,AI 不应声称知道图片内容;
|
||||
- 你只选择了一个群,答案不会自动代表所有聊天。
|
||||
|
||||
看到“可能遗漏”或“部分覆盖”时,扩大范围、先完成同步或检查原始媒体后再问。
|
||||
Knowledge 在后台同步时**不会**暂停分析:你仍然可以提问,只是答案基于当前已可用的覆盖范围。看到“可能遗漏”或“部分覆盖”时,扩大范围、等同步追上或检查原始媒体后再问。
|
||||
|
||||
## 这不是事实保证
|
||||
|
||||
|
||||
@@ -4,34 +4,91 @@
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[本机微信数据] --> B[读取与解析]
|
||||
B --> C[聊天档案与普通搜索]
|
||||
B --> D[本地知识索引]
|
||||
D --> E[筛选相关消息]
|
||||
E --> F[用户配置的 AI Provider]
|
||||
F --> G[回答与可核对来源]
|
||||
B --> H[聊天导出]
|
||||
B --> I[整理日报输入]
|
||||
I --> F
|
||||
F --> J[本地保存 HTML 与 PNG]
|
||||
B --> K[Local HTTP API]
|
||||
K --> L[外部 Agent]
|
||||
M[微信机器人消息] --> N[Agent Hub]
|
||||
N --> B
|
||||
N --> F
|
||||
WX["本机微信数据"] --> PARSE["读取与解析"]
|
||||
|
||||
PARSE --> ARCHIVE["聊天档案与普通搜索"]
|
||||
PARSE --> EXPORT["聊天导出"]
|
||||
|
||||
PARSE --> IDX["本机索引"]
|
||||
IDX --> TEXTIDX["聊天记录索引"]
|
||||
IDX --> IMGIDX["图片文字索引(本机识别)"]
|
||||
|
||||
TEXTIDX --> UNDERSTAND["Understand:AI Search / 问问微信"]
|
||||
IMGIDX --> UNDERSTAND
|
||||
UNDERSTAND --> PROVIDER["你配置的 AI Provider"]
|
||||
PROVIDER --> ANSWER["回答与可核对来源"]
|
||||
|
||||
PARSE --> REPORTINPUT["整理日报输入"]
|
||||
REPORTINPUT --> PROVIDER
|
||||
PROVIDER --> REPORTFILE["本机保存 HTML 与 PNG"]
|
||||
|
||||
PARSE --> MONITOR["Monitor:退群监控 / 成员快照"]
|
||||
MONITOR --> RULE["自动化规则"]
|
||||
REPORTFILE --> RULE
|
||||
RULE --> POLICY["Policy"]
|
||||
POLICY --> GATEWAY["Action Gateway"]
|
||||
GATEWAY --> CAP["本机发送能力"]
|
||||
CAP --> AUDIT["执行记录与审计"]
|
||||
|
||||
PARSE --> API["Local HTTP API"]
|
||||
API --> EXTAGENT["外部 Agent / Reader Skill"]
|
||||
BOT["微信机器人消息"] --> HUB["Agent Hub"]
|
||||
HUB --> PARSE
|
||||
HUB --> PROVIDER
|
||||
```
|
||||
|
||||
## Remember → 图片文字 → Understand → Monitor → Act
|
||||
|
||||
TraceMemo 的工作方式可以概括为:
|
||||
|
||||
```text
|
||||
Remember → 图片文字 → Understand → Monitor → Act
|
||||
```
|
||||
|
||||
- **Remember**:读取并解析本机微信数据,建立聊天档案、普通搜索和导出。
|
||||
- **图片文字**:在本机识别图片里的文字,把截图、公告、报价图也变成可检索的内容。这一步不联网。
|
||||
- **Understand**:Knowledge、AI Search / 问问微信、群聊日报。需要模型时,只把完成这次任务所需的受控上下文交给 Provider。
|
||||
- **Monitor**:用成员快照对比发现群成员变化,产出成员退出事件。
|
||||
- **Act**:自动化规则把前面的步骤串起来(定时日报、退群通知);动作经过统一执行边界,并留下执行记录。
|
||||
|
||||
回答和动作结果都应能回到来源或记录核对。
|
||||
|
||||
## 退群监控
|
||||
|
||||
退群监控使用成员快照判断变化:
|
||||
|
||||
```text
|
||||
Current Membership → Snapshot Diff → Member Event
|
||||
```
|
||||
|
||||
上一份有效快照(Last Good Snapshot)不会被不完整读取覆盖,因此重启后仍可继续监控通知。监控关闭期间发生的变化,不会在重新开启后补报。
|
||||
|
||||
成员退出事件同时是「自动化」里「退群通知」规则的触发条件。
|
||||
|
||||
## 动作执行与审计
|
||||
|
||||
自动发送和监控动作经过统一边界:
|
||||
|
||||
```text
|
||||
Feature → Policy → Gateway → Capability → Execution → Audit
|
||||
```
|
||||
|
||||
Policy blocked 表示策略不允许,Capability unavailable 表示当前发送能力不可用,Send failed 表示已经尝试但执行失败。Action Audit / Logs 会保留执行结果;定时日报即使发送失败,也会保留已生成的报告记录。
|
||||
|
||||
这些动作统一由「自动化」管理,当前有三类规则:**@我生成日报**、**定时日报**、**退群通知**。发送目标支持当前群聊、文件传输助手、自己、指定好友,不是任意群发。
|
||||
|
||||
## 哪些步骤在本机
|
||||
|
||||
- 微信数据库读取与解析;
|
||||
- 聊天档案浏览和普通搜索;
|
||||
- Knowledge 索引与增量同步;
|
||||
- 图片文字索引:识别图片中的文字完全在本机进行,原始图片不会因为本地识别而上传;
|
||||
- 离线语音转写;
|
||||
- 聊天导出文件、日报 HTML/PNG 和本地历史记录的保存。
|
||||
|
||||
## 哪些步骤可能调用外部服务
|
||||
|
||||
当你主动使用 AI Search、群聊日报或图片理解时,应用会把完成任务所需的受控问题和上下文发送给你配置的 Provider。它不会因为打开软件就自动上传完整数据库。
|
||||
当你主动使用 AI Search、群聊日报或图片理解时,应用会把完成任务所需的受控问题和上下文发送给你配置的 Provider。它不会因为打开软件就自动上传完整数据库,本机 OCR、离线语音转写和普通搜索也不会触发外发。
|
||||
|
||||
Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生成总结调用已配置的 Provider。Reader Skill 调用的是本机 API;外部 Agent 是否把读取结果继续交给云端模型,取决于外部 Agent 自己的配置。
|
||||
|
||||
@@ -39,13 +96,15 @@ Agent Hub 收到微信机器人的文字后,也可能为了理解请求或生
|
||||
|
||||
## 产品名词和用户任务的对应关系
|
||||
|
||||
| 用户想做什么 | 产品中可能看到的名称 |
|
||||
| ------------------------ | ---------------------------- |
|
||||
| 让 AI 找相关聊天 | AI Search、Retrieval |
|
||||
| 让答案能回到原消息 | Evidence、Citation |
|
||||
| 查看 AI 查找过程 | Search Trace |
|
||||
| 让跨会话查找更稳定 | Knowledge、FTS 索引 |
|
||||
| 让外部 Agent 读取聊天 | Reader Skill、Local HTTP API |
|
||||
| 让微信机器人调用本机能力 | Agent Hub |
|
||||
| 用户想做什么 | 产品中可能看到的名称 |
|
||||
| ------------------------------ | ---------------------------- |
|
||||
| 让 AI 找相关聊天 | AI Search、Retrieval |
|
||||
| 让答案能回到原消息 | Evidence、Citation |
|
||||
| 查看 AI 查找过程 | Search Trace |
|
||||
| 让跨会话查找更稳定 | Knowledge、FTS 索引 |
|
||||
| 搜到截图、公告图里写过的文字 | 图片文字索引、本机 OCR |
|
||||
| 让日报、退群通知按规则自动执行 | 自动化、Policy、执行记录 |
|
||||
| 让外部 Agent 读取聊天 | Reader Skill、Local HTTP API |
|
||||
| 让微信机器人调用本机能力 | Agent Hub |
|
||||
|
||||
先按任务使用,再在需要排查或开发集成时阅读术语。
|
||||
@@ -0,0 +1,308 @@
|
||||
# TraceMemo Local HTTP API / Agent API 能力审计
|
||||
|
||||
本报告基于当前代码、文档、IPC、Renderer 调用和相关测试做静态审计,对应当前发布应用版本 `2.5.0`;不连接真实微信数据库,也不修改生产代码、API Center 或测试。
|
||||
|
||||
主要代码入口:[http-server.ts](../../src/main/http-server.ts)、[automation-rule-store.ts](../../src/main/services/automation-rule-store.ts)、[group-exit-monitor-service.ts](../../src/main/services/group-exit-monitor-service.ts)、[group-stats-service.ts](../../src/main/services/group-stats-service.ts)、[api.md](../agent/api.md)。
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
当前 HTTP 层声明了 **30 个 Method + Path 模板**:15 个 GET、12 个 POST、1 个 PATCH、1 个 DELETE、1 个 HEAD。共享 `LOCAL_API_ENDPOINTS` 定义 **14 个测试项**,但 Renderer 的 `API_ENDPOINTS` 实际只展示 **12 项**;个人微信能力和 `GET /scheduled-reports` 虽有共享定义,界面没有展示。界面也没有结构化 Query、媒体读取、定时日报写操作、退群监控、群统计、Automation 通用资源或执行日志查询。
|
||||
|
||||
当前不缺成熟的 Query primitive:结构化读取消息、Knowledge 搜索、消息前后文、会话概览和图片 OCR 搜索已经有 HTTP 契约。真正的能力缺口集中在 **监控配置、自动化规则通用管理、群员统计、执行历史、全局能力发现、发送状态和报告历史**。
|
||||
|
||||
几个影响后续设计的代码事实:
|
||||
|
||||
1. 定时日报已迁入 `AutomationRuleStore`。当前 `/scheduled-reports` 是旧 HTTP 契约的兼容投影,不是第二份活动规则存储;但它只表达“生成后发回来源群”,其他当前合法目标不会出现在该兼容 API 列表中。
|
||||
2. 退群监控只负责监测范围、快照和事件历史;退群后如何通知由唯一的 `leave_notification` Automation 规则负责。二者应分别建资源。
|
||||
3. 群统计 Service 足以提供活跃成员、当前沉默成员、时间范围、新鲜度和限制说明;它没有结构化的 former member 列表,也没有覆盖所有发言者的群总消息数。
|
||||
4. 现有微信 Action Gateway 有策略、审计和幂等骨架,但策略目前主要校验收件人,以及 Automation purpose allowlist;手动用户 purpose 默认可放行。它只发个人微信,现有 `/agent/send` 则走 iLink 的 `WechatSendGateway`。两者不能直接视为统一的 Agent 安全边界。
|
||||
5. HTTP 静态 GET handler 大多没有 method guard;对这些路径发 POST、PATCH 或 DELETE 仍会执行读处理。Automation store 的规则落盘失败会记录日志,但仍将内存中的规则返回为成功。
|
||||
|
||||
建议先做应用级能力发现、退群监控资源、严格校验后的 Automation CRUD/执行查询;发送和“立即执行”放到有 dry-run、明确确认、幂等键和 Action 审计的后续阶段。
|
||||
|
||||
## 2. Current API Inventory
|
||||
|
||||
以下按 `http-server.ts` 的路由分派和动态 route factory 盘点。静态读路由的 `Method` 是当前文档和产品语义的预期方法;实际接受方法的差异见本节末尾。
|
||||
|
||||
| Method | Path | 能力 | Read/Write/Execute | Service | API Center | 文档 | Agent 价值 |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| GET | `/api/v1/health` | HTTP 与数据库 ready 状态;唯一免 Token 路径 | Read | `isReady()` | 是 | 是 | 高:连通性 |
|
||||
| GET | `/api/v1/current_time` | 本机时间、时区、日期 | Read | JavaScript `Date` | 是 | 是 | 中:相对日期换算 |
|
||||
| GET | `/api/v1/contact` | 联系人和群列表;`filter`、`type`;使用异步 hydration | Read | `chat-service.listContactsAsync` | 是 | 是 | 高:标识发现与 resolve 前置 |
|
||||
| GET | `/api/v1/chatroom` | 群聊列表;`keyword`;使用异步 hydration | Read | `chat-service.listContactsAsync` | 是 | 是 | 高:群标识发现 |
|
||||
| GET | `/api/v1/recent_chat` | 最近会话;`limit` 默认 50 | Read | `chat-service.listRecentChat` | 是 | 是 | 高:导航/摘要 |
|
||||
| GET | `/api/v1/chatlog` | 按 talker 和时间读取原始消息;移除 `contentData.aeskey` | Read | `chat-service.listMessages`、`resolveMd5` | 是 | 是 | 高,但旧式、未做结构化分页 |
|
||||
| GET | `/api/v1/group_snapshot` | 群成员快照;必填 `md5` | Read | `chat-service.getGroupSnapshot` | 是 | 是 | 高:成员身份解析 |
|
||||
| GET | `/api/v1/resolve` | 昵称、wxid、md5 解析为会话 | Read | `chat-service.resolveMd5` | 是 | 是 | 高;新资源宜返回稳定 ID 和歧义候选 |
|
||||
| POST | `/api/v1/report` | 接收完整结构化日报并导出 HTML/PNG;当前拒绝外部 `templateRef` | Write:本地文件 | `group-report-service.exportGroupReport` | 是 | 是 | 低/中:低层渲染契约,Agent 须先拼完整结构 |
|
||||
| POST | `/api/v1/agent/group-report` | 读群消息、调用 AI 生成群总结、导出 HTML/PNG | Execute:AI/本地文件 | `agent-group-report-service.generateAgentGroupReport` | 是 | 是 | 高但有模型费用/数据出站;结果不等同于报告历史记录 |
|
||||
| GET | `/api/v1/agent/status` | Agent Hub、connector、数据 API、数据库状态 | Read | `agentHubService.getStatus` | 是 | 是 | 中:只覆盖 Agent Hub,不是应用总能力 |
|
||||
| POST | `/api/v1/agent/send` | 通过 Agent Hub 连接器发送文字或媒体 | Execute:微信发送 | `agentHubService.testSend` → `WechatSendGateway`/iLink | 是 | 是 | 高但 R2;是测试入口,不含统一 Action policy/幂等确认 |
|
||||
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信 text/image/voice 能力状态 | Read | `PersonalWechatCapabilityService`,由 `ScheduledReportApiService` 包装 | 否(共享定义有,界面未展示) | 是 | 高但只代表 personal,不代表 iLink |
|
||||
| GET | `/api/v1/scheduled-reports` | 列出旧 DTO 可表达的定时日报规则 | Read | `ScheduledReportApiService.list` → 规则投影 | 否(共享定义有,界面未展示) | 是 | 高但不完整:仅 `source_chat` 目标 |
|
||||
| POST | `/api/v1/scheduled-reports` | 创建旧型定时日报,来源群即发送目标 | Write:规则配置 | `ScheduledReportApiService.create` → `AutomationRuleStore` | 否 | 是 | 高;功能受旧 DTO 限制 |
|
||||
| GET | `/api/v1/scheduled-reports/{id}` | 单条旧型日报规则投影 | Read | `ScheduledReportApiService.get` → `AutomationRuleStore` | 否 | 是 | 中/高:只支持兼容投影规则 |
|
||||
| PATCH | `/api/v1/scheduled-reports/{id}` | 修改旧型日报规则 | Write:规则配置 | `ScheduledReportApiService.update` → `AutomationRuleStore` | 否 | 是 | 高但只能改旧字段/目标 |
|
||||
| DELETE | `/api/v1/scheduled-reports/{id}` | 删除旧型日报规则 | Write:删除配置 | `ScheduledReportApiService.delete` → `AutomationRuleStore` | 否 | 是 | 中;新 API 应标 R3 并防护系统规则 |
|
||||
| POST | `/api/v1/scheduled-reports/{id}/enable` | 启用规则 | Write:配置/未来执行 | `ScheduledReportApiService.setEnabled` → `AutomationRuleStore` | 否 | 是 | 高;启用后未来可能发送微信 |
|
||||
| POST | `/api/v1/scheduled-reports/{id}/disable` | 暂停规则 | Write:配置 | `ScheduledReportApiService.setEnabled` → `AutomationRuleStore` | 否 | 是 | 高 |
|
||||
| POST | `/api/v1/scheduled-reports/{id}/run` | 手动触发完整日报规则 | Execute:可能调用 AI、保存历史、发微信 | `ScheduledReportService.runScheduledReportNow` → `AutomationService` | 否 | 是 | 高但 R2;当前无 HTTP 幂等键/确认 |
|
||||
| GET | `/api/v1/scheduled-reports/{id}/executions` | 旧型 execution 历史和新 Automation execution 投影 | Read | `ScheduledReportService.listExecutions` | 否 | 是 | 高但旧响应模型/有限留存 |
|
||||
| POST | `/api/v1/scheduled-reports/executions/{executionId}/retry-send` | 旧文档称复用 PNG 重发 | Execute 路由存在但当前固定 `501 not_supported` | `ScheduledReportApiService.retrySend` | 否 | **路径有,语义已失效** | 无:不能重发 |
|
||||
| GET | `/api/v1/media/{mediaId}` | 读取消息关联的图片二进制 | Read | `http-media-service.readImageMedia` | 否 | 是 | 高:图像证据 |
|
||||
| HEAD | `/api/v1/media/{mediaId}` | 图片资源存在性/响应头 | Read | `http-media-service.readImageMedia` | 否 | 否 | 低/中 |
|
||||
| GET | `/api/v1/query/capabilities` | Query Tool 支持的结构化操作、范围和上限 | Read | `LocalQueryApiService.capabilities` | 否 | 是(独立章节) | 高,但不是 TraceMemo 应用能力清单 |
|
||||
| POST | `/api/v1/query/messages` | 单会话、范围、时间、方向、类型等确定性消息读取 | Read | `LocalQueryApiService.messages` | 否 | 是 | 高:推荐 Query primitive |
|
||||
| POST | `/api/v1/query/search` | Knowledge 关键词检索,返回覆盖、新鲜度和 OCR 命中 | Read | `LocalQueryApiService.search` + `KnowledgeSearchService` | 否 | 是 | 高:必须读取 coverage/freshness |
|
||||
| POST | `/api/v1/query/message-context` | 通过 opaque `messageRef` 读取前后文 | Read | `LocalQueryApiService.context` | 否 | 是 | 高:稳定消息引用 |
|
||||
| POST | `/api/v1/query/conversation-overview` | 单会话范围的概览证据和 source coverage | Read | `LocalQueryApiService.overview` | 否 | 是 | 高:broad summary |
|
||||
|
||||
路由来源:[http-server.ts](../../src/main/http-server.ts#L212)、scheduled/query/media route factory(同文件 L404-L670)。总数是代码中声明的业务方法模板,不代表静态 handler 都正确拒绝其他动词:`/health`、`/current_time`、`/contact`、`/chatroom`、`/recent_chat`、`/chatlog`、`/group_snapshot`、`/resolve`、`/agent/status` 没有检查 `req.method`。这些路径携带错误动词仍会走同一 handler;特别是 `POST /health` 也绕过 Token 检查,因为鉴权例外按 pathname 判断。新/旧路由都应 fail closed 并对不支持的方法返回 405。
|
||||
|
||||
全局 `OPTIONS` 在路由和鉴权前处理;媒体额外支持 HEAD。非 health 路径要求 `Authorization: Bearer …`,但 `readBody` 没有大小上限。路由外层目前没有统一请求 schema、统一错误 envelope 或 request id。
|
||||
|
||||
## 3. Internal Capability Inventory
|
||||
|
||||
这里按产品能力追 Service → IPC/Renderer → HTTP → 外部 Agent,而不是按当前 API 名字扩展。
|
||||
|
||||
| 业务域 | 已有能力及实现 | IPC / Renderer | HTTP 现状 | Agent 结论 |
|
||||
|---|---|---|---|---|
|
||||
| Chat / Contact | 联系人、群聊、最近会话、解析、历史消息、群快照、消息周边上下文、媒体定位;`contact-resolution-service` 可精确匹配别名并返回歧义候选 | `db:getContacts`、`db:getGroupSnapshot`、消息查询/around 等,Chat/Contact/档案 UI | 旧 Reader routes + `/query/*` + 图片 `/media/{id}` | 已有 Read API 基础完整。新配置应使用 `m_nsUsrName` 对应的 wxid/roomId 等稳定 ID,不应把昵称当长期键 |
|
||||
| Query / Knowledge | `messages`、`search`、`message-context`、`conversation-overview`;Knowledge 索引覆盖/新鲜度;Image OCR 可进入 Knowledge 搜索和证据 | `knowledge:search/getStatus/startIndex/cancelIndex`、AI Search UI、`LocalQueryToolExecutor` | 四个 Query 操作均已 HTTP 化;`query/capabilities` 只描述 Query Tool | 没有需要重做的基础 Query primitive。缺的是统一应用 capability/status、更多外层筛选和 API Center 展示 |
|
||||
| Group Analytics | 活跃/沉默当前成员、每人 messageCount/lastMessageTime、窗口时间、memberCount、unattributed/system 消息、firstMessageTime、freshness/complete/limitations;索引未新鲜时最多等待 2 秒并如实降级 | `group-stats:getMemberStats`;聊天页群统计 UI | 无 | P1 候选。当前 query 要求群 `userMd5` + epoch 毫秒。former sender 只以限制文案给出数量,没有 formerMembers 数组/结构化计数;没有覆盖 former sender 的群总消息数字段,需扩 DTO 后再承诺 |
|
||||
| Group Exit Monitor | enabled/running/nativeMonitor 状态、监控 roomId 集合、lastChecked、unread、事件历史;每次回传最多 500 条,但完整事件历史 append-only 长期保存;可立即 check、改范围、启停、筛事件、清历史、mark read | `group-exit-monitor:*`;`GroupExitMonitorWorkspace` | 无 | P0。拆成 monitor state/config、events、check。`checkNow` 可能发现事件并触发自动通知,不是纯读操作;重启监控会重建快照基线,暂停期成员变化不会补报 |
|
||||
| Automation | 实际规则类型:`daily_report`、`scheduled_report`、`leave_notification`。`daily_report` 是现有消息触发条件/动作链,不是任意流程引擎;退群通知为固定 ID singleton。规则 CRUD、enable、执行记录读写均已有 Service/Store | `automation:*`;AutomationWorkspace 有规则、日志、定时执行、启停、删除和状态 UI | 没有通用 Automation API;仅 scheduled-report 兼容映射 | P0。使用 typed rule union;不要把内部任意 draft 原样开放。规则创建当前缺省 enabled=true,未知值会被归一化成默认;需 HTTP 严格校验,先 disabled + validate,再显式 enable |
|
||||
| WeChat Send / Action | `WechatSendGateway` 有 personal/iLink transport resolution、text/image/voice/file 统一类型及 Send Log;`WechatActionGateway` 做 capability preflight、Automation purpose allowlist、Action audit、幂等和 Automation 3 秒间隔 | `wechat-personal:send`、`sendGeneratedTtsVoice`、`wechat-action-log:list`、Agent Hub connector 相关 IPC/UI | `/agent/send` 只走 Agent Hub/iLink 测试发送;个人 capability 有独立 GET;两类日志没有 HTTP | 分 transport 公布 capability;R2 send 通过经审计的业务门面,不直接暴露底层 gateway。现有 Action Gateway 还不是普适安全策略:`triggerType=user` 不按 purpose 限制;普通 `/agent/send` 没传 idempotency key,也没有 Action audit |
|
||||
| Agent Hub | status、connector login/reconnect/disconnect、notification recipient/send、logs、conversation list/detail/clear、入站 inbox retry | `agent-hub:*`;Agent Hub UI | 仅 `/agent/status` 和 `/agent/send`;无 conversation/log HTTP | status 有只读价值。对话记录包含完整收发正文;inbox 包含 context token/raw items。Connector 生命周期、登录 QR/验证码、收件箱和通知 recipient 应保持 internal |
|
||||
| Reports / Templates | 手动 report render/export;AI group report;本地 Report History list/save/update template/delete;内置/已安装模板和市场 catalog/install/uninstall | `report:*`、`report-template:*`、`report-template-market:*`;Reports 与 Template Market UI | `/report` 低层 export,`/agent/group-report` AI 生成;没有 history/template API | P1:只读 Report History 元数据/资产可分离设计。现有 `listGeneratedReports` 会读取每张 PNG 为 base64,并返回结构快照和本机绝对路径,不可原样直出。模板目录可读列入 P2;安装/卸载涉及网络与本地包写入,不宜第一批开放 |
|
||||
| Recall Archive | 后台监听撤回变化,最多按会话存归档消息/撤回记录;chat-service 将 archive merge 到历史读结果 | 没有独立 CRUD IPC;设置开关和消息渲染 | 没有独立 archive API;旧 `/chatlog` 可能随底层消息返回 `recalled` 标记;Query DTO 未声明 recalled 字段 | 不开放原始 archive 管理。后续 Query 应明确返回 `recalled`/来源,避免把已撤回归档当普通消息证据 |
|
||||
| OCR / Image Insight | System OCR 本地识别;image-text-index status/count/start/pause/resume/cancel/clear/repair;Image Insight 读/解密图片并可调用 AI Provider | `system-ocr:*`、`image-text-index:*`、`image:*` IPC;Search/Report UI | OCR 派生文本可通过 `/query/search` 得到;索引管理、单图 AI 分析无 HTTP | 已有搜索能力可用。状态可纳入 capability/status;索引删除、key/decoder 配置、任意图像 AI 分析涉及成本、私密图片和索引破坏,不列第一批 |
|
||||
| 系统 / 数据 / 其他 | account discovery、DB key 管理、数据库 connect/root 重开、设置写入、cache summary/clear、app update、voice/TTS、export/import、Reader Skill 本地安装信息 | 多组 IPC;Settings、Cache、Export、Update、Voice UI | 无相应 HTTP API | 只读脱敏运行状态可按需求列 P2;DB key/root、通用 settings patch、cache 清理、任意文件路径、更新安装、TTS synthesis 等保持 internal |
|
||||
|
||||
### A. Chat / Contact 与 ID 语义
|
||||
|
||||
- `/contact`、`/chatroom` 改用 `listContactsAsync`,因为 macOS Session 可能只有原始 wxid/chatroom id,需要 hydrate 显示名;`ScheduledReportApiService` 却使用同步 `listContacts()` 解析群名。稳定 `talker` 可直接解析,但名称输入在需要 hydration 的运行时可能失败/退化。这是可复用 adapter 应统一异步解析的理由。
|
||||
- ID 现在不是一个口径:旧 Query 的 `scope.conversationId`/`target` 解析为 `Contact.md5`;`group-stats` 传 `userMd5`;监控用 `roomId`(`xxx@chatroom`);新的 scheduled automation 用 `sourceConversationId`(wxid/roomId);老 HTTP 路由混用昵称、wxid、md5。保持已有 Reader 契约不动,新 API facade 应统一对外 canonical `conversationId`(底层当前联系人的稳定 username/wxid 或 roomId),并在 main adapter 转为服务所需 md5。名称只做 resolve,不持久化到规则。
|
||||
- `chatlog` 时间边界是 Unix 秒,Query `absolute` 内部也是秒,而 group stats IPC 是 epoch 毫秒;新 Agent 资源建议用带时区 ISO-8601 输入/输出,并在 facade 单点转换。
|
||||
- `/query/messages` 有 200 上限,`messageRef` 是 opaque 稳定引用;图片 OCR 文字和 Coverage 分开呈现。`/chatlog` 则支持旧 talker/time 风格但读取结果没有同等结构边界;作为兼容 Reader 保留,不作为新 Agent 配置/分析的默认接口。
|
||||
|
||||
### B. Group Exit Monitor 与 Leave Notification
|
||||
|
||||
`GroupExitMonitorService` 的真实 IPC 有 `getState`、`setEnabled`、`setGroups`、`checkNow`、`listEvents`、`clearEvents`、`markRead`。事件是群成员差异事实,包含 roomId、member wxid/name、previous/current count、detectedAt;monitor state 中 `events` 只是最近 500 条快照,`totalEventCount` 对应完整内存历史。
|
||||
|
||||
`AutomationService.handleGroupExit` 只处理 `BUILTIN_LEAVE_NOTIFICATION_RULE_ID` 对应的 singleton 规则。规则另有 `notifyScope` / `notifyRoomIds` 二次范围、target、template。Agent 配“监控 A/B/C”需改 monitor 范围;配置通知目标/通知哪些被监控群则另改这条 leave notification automation。两者不能合并为 `/monitors/{id}/notify`。
|
||||
|
||||
### C. Automation 与 Scheduled Report
|
||||
|
||||
`AutomationRuleStore` 的真实方法有 `listRules/getRule/createRule/updateRule/saveLeaveNotificationRule/deleteRule/setRuleEnabled`;`AutomationExecutionLogService` 提供 `list/record/clear/countSince`。执行日志最多留存 200 条,clear 属于破坏性操作。规则在 `{userData}/automation/rules.json` 中 JSON 持久化。
|
||||
|
||||
`scheduled-report-service.ts` 的调度来源是 `automationRuleStore.listRules()`,执行交给 `AutomationService.executeScheduledRule()`,execution 从 Automation Log 投影。迁移后的旧 `tasks.json`/`executions.json` 是只读历史存档。旧 HTTP API 通过 `ScheduledReportApiService` 转换旧 DTO;创建、修改、删除、启停最终也是读写 `AutomationRuleStore`。所以正确方案是保留兼容 facade,并建立 Automation canonical API,不要继续增加第二个 scheduled-report store。
|
||||
|
||||
旧 facade 的限制:只列/操作可投影为 `target.type === 'wechat_group'`、且目标等于来源群的规则。如今 scheduled automation 支持 source_chat/self/file_transfer/contact,故通过新 UI 创建为文件传输助手或联系人目标的规则,会从旧 `/scheduled-reports` 列表隐藏。旧 API 输入 schema 也不能表示完整 scheduled config(成员名、消息类型、模板、timeout、postfix 等)。
|
||||
|
||||
写 API 前还需处理 `AutomationRuleStore` 的归一化和持久化契约:未知 ruleType 会降成 `daily_report`,大部分错误枚举会静默落安全默认;缺省 enabled 是 true;`persist()` catch 写盘错误后只记 warning,Store 仍返回创建/更新后的对象。HTTP adapter 必须先 strict validate,且 Store 需要可观察的持久化结果,不能把内存态冒充成功。
|
||||
|
||||
### D. Group Analytics 确认项
|
||||
|
||||
`GroupStatsService.getMemberStats` 已有可直接复用的核心计算;接口具体有:
|
||||
|
||||
- 当前群成员:`memberCount`、`activeMembers`、`silentMembers`、各活跃成员 `messageCount`/`lastMessageTime`;
|
||||
- 查询窗口:`startTime`、`endTime`(epoch ms)、`firstMessageTime`;
|
||||
- 数据完整性:`freshness = fresh|stale|unknown`、`complete`、`limitations`;
|
||||
- 诊断:`unattributedMessages`、`excludedSystemMessages`。
|
||||
|
||||
成员名单是当前成员集合;知识库统计的 sender 不在当前集合时被排除,只在 `limitations` 中增加“另有 N 位窗口内发言者已不在当前群成员名单”。Service 不返回其身份/每人消息数,也没有 `totalMessageCount`。若 Agent 需要“前成员榜”或全群消息数,需要先扩展 Service/shared type;不能由 API adapter 从 limitation 文案反解析。
|
||||
|
||||
## 4. API / Docs / API Center Drift
|
||||
|
||||
| 项目 | 代码事实 | 漂移/影响 |
|
||||
|---|---|---|
|
||||
| HTTP、共享定义与界面列表 | HTTP 有 30 个 method/path 模板;`LOCAL_API_ENDPOINTS` 定义 14 项,Renderer `API_ENDPOINTS` 实际展示 12 项 | 16 个 HTTP 操作模板没有共享定义;另有 2 个已定义项(个人微信能力、定时日报列表)没有展示。界面仅呈现 12/30 项,不能作为完整 API catalog |
|
||||
| Scheduled Report 展示 | 共享定义只有 `GET /scheduled-reports`;该项本身也未进入 Renderer 列表 | POST 和 task action 不显示,GET 列表也不显示;Agent 在 API Center 里无法发现这组 API |
|
||||
| WeChat Capability 展示 | 共享定义有 `GET /wechat-personal/send-capability`;Renderer 列表未包含它 | API Center 看不到个人微信发送能力状态,用户可能误把 Agent Hub 状态当成完整发送能力 |
|
||||
| Query 展示 | Query 文档在 `api.md` 的独立 LLM-friendly 章节,Service/HTTP 实现完整 | API Center 看不到;用户可能误认为 Reader API 仍只有旧 chatlog |
|
||||
| Media 方法 | `/media/{mediaId}` 支持 GET、HEAD | 文档仅列 GET;API Center 都未列 |
|
||||
| Retry Send | 文档表称 retry-send“复用已有 PNG 重试发送” | `ScheduledReportApiService.retrySend()` 当前无条件抛 `501 not_supported`;integration/unit tests 也未覆盖 retry 路由的这项现状 |
|
||||
| Scheduled Report 完整性 | 旧 facade 只 project `source_chat` | UI 可保存的其他 scheduled target 会从旧 API list/get 隐藏;不是两份存储,但旧 API 不是 Automation API 的完整别名 |
|
||||
| Health 版本 | `/health` 固定返回 `version: "1.0.0"` | 与当前 package version `2.5.0` 不同,Agent 无法据此判断应用版本 |
|
||||
| HTTP 动词 | 九个静态 GET 语义路由无 method guard | POST/PATCH/DELETE 等也可能调用读取逻辑;`/health` 任意 method 均免 Token。测试目前未锁定统一 405 契约 |
|
||||
| 请求/错误 schema | JSON parsing 和错误形状分散:通用 `sendError`、ScheduledReport 专用 error、Query status body、业务自身 result | Agent 要写多套解析逻辑;共享 API schema 和统一错误 code 不存在 |
|
||||
| 命名 | `/contact`、`/chatroom`、`/recent_chat`、`/group_snapshot` 与 `/scheduled-reports`、`/query/*`、`/agent/*`、`/wechat-personal/*` 并存 | snake_case 旧路径、资源路径和“Agent 为业务 owner”的命名混杂;新接口不能继续沿用此漂移 |
|
||||
|
||||
文档 [api.md](../agent/api.md#L35) 基本列出当前 HTTP 路径,Query 在后续单独说明;除 HEAD 外没有发现漏写的当前业务路径,但 retry-send 的成功语义过期。API Center 的来源是单独的 [local-api-test.ts](../../src/shared/local-api-test.ts) 和 [apiEndpoints.ts](../../src/renderer/src/features/api-center/model/apiEndpoints.ts),没有从 HTTP route/schema 派生。测试现有 `local-api-auth` 覆盖鉴权、媒体、部分 Query 和 Agent send;`scheduled-report-api` 覆盖旧生命周期;`local-api-contact-search` 覆盖 hydrate。它们没有自动比对 HTTP route、文档、Catalog 三者,也没有覆盖全部 method guard 和 retry-send。
|
||||
|
||||
## 5. Candidate API Matrix
|
||||
|
||||
风险按本任务口径:R0 只读;R1 本地配置/应用状态修改;R2 微信发送、AI/provider 调用等外部副作用;R3 删除或清空不可轻易恢复的数据。R1 不代表没有后续行为:enable 一条定时规则会武装未来的 R2 执行。
|
||||
|
||||
| Capability | 当前实现 | 当前 API | 建议 | Agent 用例 | Risk | Priority |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 联系人/群/会话 resolve | Chat Service + Contact Resolution | 有旧 routes;Query 内 resolve | 保留旧路由;新 resource 返回稳定 ID、歧义候选 | 查找群并取得 roomId | R0 | P0(复用) |
|
||||
| 结构化消息/搜索/上下文/概览 | LocalQueryApiService + Knowledge | `/query/*` | 保持契约;加 route schema/catalog,后续可升级稳定 ID | 查聊天、关键词/OCR、补上下文 | R0 | P0(复用) |
|
||||
| 应用 capability discovery | 各 Service 能回答局部状态 | 无;`query/capabilities` 仅 Query Tools | 新 `GET /capabilities`,区分 supported/available/reason/operations | 发现自动化、监控、统计、发送 transport | R0 | P0 |
|
||||
| Group Exit Monitor 状态/范围 | GroupExitMonitorService | 仅 IPC | GET state + PATCH enabled/roomIds | 查看监控、监控/停止一个群 | R0/R1 | P0 |
|
||||
| Group Exit events | Monitor JSONL + listEvents | 仅 IPC | GET 带 stable roomId/time/cursor/limit | 最近 7 天谁退群 | R0 | P0 |
|
||||
| 手动检查退群 | checkNow 会扫描并触发事件 handler | 仅 IPC | 有外部通知时按 R2 操作开放,先 validate effects + confirm | 立即检查一次 | R2 | P1 |
|
||||
| Automation 规则 CRUD | AutomationRuleStore | 通用 IPC;HTTP 仅旧 scheduled facade | typed union CRUD;create disabled;validate 再 enable;保护 singleton/system rules | 创建、列出、修改、暂停自动化 | R1/R3(delete) | P0 |
|
||||
| Automation validation/dry-run | 现有编辑器 preview 分散;无通用 validator API | 无 | `POST /automations/validate`;不落盘、不发送 | 确认群、目标、模板、下次运行和能力 | R0 | P0 |
|
||||
| Automation execution history | AutomationExecutionLogService,最多 200 条 | schedule 专属旧投影 | 规范化 Automation execution 读接口;清日志不开放第一批 | 查看失败、按 rule 过滤 | R0/R3(clear) | P0 |
|
||||
| Group member stats | GroupStatsService | 仅 IPC | 按稳定 group ID + ISO window 读统计;先补 former/total 语义 | 近 30 天活跃榜 | R0 | P1 |
|
||||
| WeChat capability | personal capability service;Agent Hub status | personal GET + Agent status | 新全局 capability 含 personal/iLink 和内容能力;旧路由保留 | 检查发送当前是否可用 | R0 | P0 |
|
||||
| 手动微信发送 | WechatSendGateway + Action Gateway | `/agent/send` iLink test send | 新 send command 经受限 Action facade,强制 stable recipient、confirm、idempotency | 文件助手测试消息 | R2 | P1 |
|
||||
| Send Log / Action audit | Send Log 500 条;Action audit 500 条;IPC action-log | 无 HTTP | 分层只读分页,preview 脱敏;按 executionId/requestId 关联 | 查最近发送失败、审计规则动作 | R0 | P1 |
|
||||
| Agent Hub status | AgentHubService.getStatus | `/agent/status` + IPC | 保留 alias,新资源名归 `/agent-hub/status`,与 app capabilities 分开 | 查 Hub/connector online | R0 | P1(复用) |
|
||||
| Agent Hub 对话内容 | Conversation Store,最多 50 会话×500 条 | 仅 IPC | 默认为 Internal;若产品确认需要,另做显式 opt-in、分页/时间过滤 | 查看机器人与某人的对话 | R0(高隐私) | 不建议第一批 |
|
||||
| AI 群日报 | AgentGroupReportService + export | `/agent/group-report` | 保留兼容;未来先 validate model/range/group/data egress,再异步 job | 生成临时总结图片 | R2(provider/本地文件) | P1 |
|
||||
| 日报历史 | ReportHistory Service,IPC CRUD | 无 | 分页 metadata DTO;图片 asset 单独下载;不返回 base64/路径/完整 snapshot | 昨天生成过哪些日报 | R0 | P1 |
|
||||
| 模板列表 | Template Service + market catalog | 仅 IPC | 仅已安装模板只读列表列 P2 | 有哪些日报模板 | R0 | P2 |
|
||||
| 模板安装/删除/历史改版 | Template Service/Market + Report History | 仅 IPC | 不开放通用 HTML/路径写入;将来单独授权且保留校验 | 安装或修改模板 | R1/R3 | Maybe/P2 |
|
||||
| Recall archive 查询 | 内部 archive merge 到历史消息 | 无独立 API | 不单独开放磁盘 Archive;给 Query 增 `recalled` 来源标记 | 找被撤回消息 | R0(敏感/语义风险) | P2 |
|
||||
| Image OCR index 操作 | image-text-index service | IPC(含 clear/repair) | coverage 状态可汇入 capabilities/status;不让 Agent 操作 clear/reset | 查 OCR 覆盖 | R0/R1/R3 | P2 |
|
||||
| AI image insight | ImageInsightService 读/解密图片并调 vision provider | IPC | 不暴露任意 hash/message AI 分析,除非有成本/隐私授权 | 理解群图片 | R2 | 不建议第一批 |
|
||||
| DB key、根目录、settings、cache | 多个设置/DB/cache Service | IPC/UI | 禁止通用 settings patch / 文件路径 / DB key API;只加白名单状态字段 | 修改本机数据库、安全设置 | R1/R3 | 不建议开放 |
|
||||
| Connector 生命周期/inbox | AgentHubService + WechatInboundInbox | 仅 IPC/内部 | connector 登录、验证码、QR、inbox、context token 不对 Agent 暴露 | 重连或直接拿入站 token | R1/R2 | 不建议开放 |
|
||||
|
||||
## 6. P0 Recommendation
|
||||
|
||||
第一批目标是“让 Agent 能配置和核验 TraceMemo,但不意外发消息”。建议只包括:
|
||||
|
||||
1. `GET /api/v1/capabilities`:应用级 capability,不与现有 `/query/capabilities` 合并。返回版本、DB/readiness、supported vs available、不可用原因和依赖;发送分 personal/iLink 与 text/image/voice 能力。
|
||||
2. Group Exit Monitor:读取状态、显式配置 monitored roomIds、读取历史事件。`PATCH` 只接 canonical 群 ID,拒绝不存在/非群 ID;修改范围响应明确显示后台 baseline/check 状态。`check` 先列 P1,因为它可能启动退群通知发送。
|
||||
3. Automation typed CRUD:列/读规则、创建 disabled 规则、更新、显式启停、执行历史读取。Leave Notification 仍使用固定 singleton id,不允许创建重复规则;拒绝未知字段/未知 enum,而不是靠 `normalizeRuleDraft` 静默修正。
|
||||
4. `POST /automations/validate`:验证目标群、稳定通知 recipient、模板变量、report/template 配置、send capability 和 nextRunAt;只返回 plan,不落盘、不发送。
|
||||
5. 运行状态与错误契约:一致的 405、最大 body、请求 ID、错误 envelope;这是任何新 Agent 写接口前的 foundation,不是大规模权限系统。
|
||||
|
||||
Agent 实现示例(概念流程):
|
||||
|
||||
- “监控 A/B/C 退群”:resolve 三个群为 roomId → validate scope → PATCH monitor group IDs。
|
||||
- “A 群有人退出就通知文件助手”:读取 monitor scope 和 singleton leave rule → validate 类型/notify scope/target → 更新规则但保持 disabled → 用户/Agent 明确 enable。监控与 leave-notification 是两份正交配置。
|
||||
- “每天 20:00 生成产品群日报”:resolve sourceConversationId → validate scheduled rule(包含 target/transport/模板/时区/next run)→ 创建 disabled → 显式 enable。旧 `/scheduled-reports` 无法表达所有当前 config,不承担新 Agent CRUD。
|
||||
- “昨天哪些自动化失败”:读 automation executions,按本机 timezone/UTC offset 和 status 查询,不清理日志。
|
||||
|
||||
## 7. Proposed Resource Model
|
||||
|
||||
采用业务 capability 资源,HTTP server 只负责 transport、auth、body、统一错误;每个 domain route 调用独立的 main-process API facade/Service adapter。Facade 复用当前 Service/Store,不把 UI IPC 当 HTTP RPC 转发层。
|
||||
|
||||
| Resource | 职责 | 现有路径的处理 |
|
||||
|---|---|---|
|
||||
| `system` | health、版本、应用级 capabilities、运行状态 | `/health` 保留;新增 `/capabilities`;`query/capabilities` 不改语义 |
|
||||
| `contacts` / `groups` | 稳定 ID 列表、resolve、群成员快照/统计 | `/contact`、`/chatroom`、`/resolve`、`/group_snapshot` 保留兼容 |
|
||||
| `query` | 消息/搜索/上下文/概览证据 | 现有 `/query/*` 保持;query ID 口径升级需兼容 reader skill |
|
||||
| `monitors` | 退群监控范围、启停、事件、显式 check | 新 `/monitors/group-exits`,与通知规则分离 |
|
||||
| `automations` | 规则 typed CRUD、validate、启停和运行 | 新 `/automations` 是 canonical HTTP resource;底层仍由 `AutomationRuleStore` 存储 |
|
||||
| `executions` | 跨 Automation/Action/Send 的只读运行视图 | 新 `/executions` read model,不合并各自写存储 |
|
||||
| `wechat` | transport capabilities、受控 send command、Send Log/Action audit | `/agent/send` 与 `/wechat-personal/send-capability` 保留兼容 |
|
||||
| `reports` | report history 元数据/asset;installed templates read-only | `/report` 与 `/agent/group-report` 保留为不同兼容操作 |
|
||||
| `agent-hub` | Hub/connector 状态;conversation API 默认 internal | `/agent/status` 保留 alias,不复用 app capability |
|
||||
| `developer` | 高级 raw request tester 与诊断 | API Center 的 tester;不作为 Agent 业务 API |
|
||||
|
||||
共享资源原则:新 API 输入以 stable id 为主、名字只用于 resolve;所有写请求 strict validate;时间对新资源用 offset ISO-8601;分页使用 `limit` + `cursor`;成功/失败使用一个 typed envelope;不直接返回 app userData path、token、context token、AES key 或原始 transport payload。
|
||||
|
||||
## 8. Safety Model
|
||||
|
||||
### 当前边界
|
||||
|
||||
- 默认监听 `127.0.0.1:6131`,但 host/port 由设置和 `api:start` 调用传入,API Center 会警告非 loopback。CORS 只允许 loopback Origin,但不带 Origin 的 curl/Agent 请求仍可用 Token;CORS 不是本地进程授权边界。
|
||||
- `/health` 公开,其余 endpoint 共用单一 Bearer Token。Token 为 32 random bytes、safeStorage 加密存储并设 `0600`,没有 read/config/send scope。拿到 token 即可读取聊天,也能建/删/启停规则、立即发送。
|
||||
- HTTP `/agent/send` 的消息进入 `WechatSendGateway`,因此有低层 Send Log;但没有 `WechatActionGateway` 的业务 Action audit/策略决策,也没有调用方 Idempotency-Key。Personal capability 路由只报告个人微信状态。
|
||||
- `WechatActionGateway` 的请求包含 `purpose`、`triggerType`、recipient、content、`idempotencyKey`、`executionId`;Automation trigger 有 purpose allowlist,sender capability 会先检查,审计记录会保存 content preview/hash。当前 `evaluateWechatActionPolicy` 对 `triggerType=user` 不做 purpose allowlist,`shouldUseAiPolicy` 固定 false;幂等只对显式 key 或历史特定 scheduled request 生效。它目前只发个人微信,不能直接替换 iLink send。
|
||||
- Action Audit 和 Send Log 各自上限 500;Automation Execution Log 上限 200。三类日志粒度不同,不是重复的同一事实。
|
||||
|
||||
### 分级建议
|
||||
|
||||
| 风险 | 操作 | 建议控制 |
|
||||
|---|---|---|
|
||||
| R0 | 查询聊天/成员/事件/状态/统计/日志/报告元数据 | 保留本地 Token;响应明确 scope、coverage、freshness、隐私字段 |
|
||||
| R1 | 修改监控群、Automation 配置、启停、模板设置 | typed validation、dry-run plan、显示持久化成功;enable 需确认它武装未来发送 |
|
||||
| R2 | 微信发送、立即执行日报/退群通知 check、调用 AI Provider 生成报告 | 明确 recipient 和内容/规则;`Idempotency-Key` 必填;统一 Action policy + Action audit + Send Log;重复请求回放原结果;返回发送状态 |
|
||||
| R3 | 清理退群事件、删除 report、清空执行/发送/Action 日志、清 cache/index、删规则 | 初始不开放;如以后开放,独立权限、预览计数、可恢复备份/本地确认,不接受批量 wildcard |
|
||||
|
||||
现有 Bearer Token 不足以支撑“查询、配置、发送、清理”都对一个不受信 Agent 开放。近期不必造完整账户系统,但应先修路由 method/body/validation,提供默认只读或 disabled 配置工作流;后续可加入多个 named token + scope(`read`, `configure`, `send`, `destructive`),R2 请求确认和 durable idempotency。风险分类也需承认本地 artifact write(如 `/report` 导出)不是配置本身,可先按 R1 local-write 处理。
|
||||
|
||||
## 9. Compatibility Plan
|
||||
|
||||
1. 不 rename/remove 任何现有 route。Reader Skill 依赖旧 contacts/chatlog/media 路径;新 structured query 已经是更合适的 Agent query,但两者并行。
|
||||
2. 新 `/automations` 读写同一 `AutomationRuleStore`。旧 `/scheduled-reports*` 改为明确标注 Deprecated 的 compatibility adapter;维持现有 request/response shape 和 source_chat 子集,不维护第二个任务存储。响应可加 `Deprecation` header/文档说明,未定 sunset 前不返回 breaking error。
|
||||
3. `/scheduled-reports` 的投影不能假装覆盖所有 scheduled automation。旧 list/get 只反映 source_chat;新 clients 必须迁到 `/automations?type=scheduled_report`。旧 `retry-send` 保留返回 501,文档明确废弃;不能伪造已发送成功。
|
||||
4. `/agent/send` 继续表示现有 iLink/Agent Hub 测试发送。新 `/wechat/send` 必须先明确 transport/recipient schema,再通过能统一 personal+iLink 的受控 Action facade;如果不能保留旧发送语义,就将旧路径作为 adapter 而不是简单 alias。
|
||||
5. `/wechat-personal/send-capability` 保持 personal-only 兼容 view;新全局 capability 返回 transport map。应用能力 `/capabilities` 和 Query Tool 的 `/query/capabilities` 各自有清晰不同的契约。
|
||||
6. 同一 shared contract/catalog 应供 HTTP 验证、API Center、文档和 route contract tests 使用;把实际路由、文档和 API Center 三者 drift 变成测试失败,而不是发布后人工发现。
|
||||
|
||||
## 10. Proposed Phase Plan
|
||||
|
||||
### Phase A — HTTP Contract / Facade
|
||||
|
||||
给现有 routes 加明确 method guard、body size limit、严格 shared request schema、统一错误 envelope/request id;补 `AutomationRuleStore` 写盘成功/失败结果;建立稳定 conversation ID adapter 和 route contract tests。保留 raw Node HTTP,不需要为第一阶段换 web framework。
|
||||
|
||||
### Phase B — Read + Validation P0
|
||||
|
||||
增加应用 `/capabilities`、monitor state/events、automation rules/executions 读取、`/automations/validate`、group stats adapter。monitor `check` 因可能触发 notification 暂留 P1 或先加 side-effect confirmation。把新资源路径、schema、风险元数据接进 EndpointCatalog/生成文档。
|
||||
|
||||
### Phase C — Automation Configuration
|
||||
|
||||
开放 disabled create、PATCH、启停和 DELETE 防护;退群通知专用 singleton upsert 接入同一规则资源;scheduled report 使用真实完整 config;旧 scheduled API 只做 compatibility projection。先做 dry-run 再允许 enable。
|
||||
|
||||
### Phase D — Side Effects / Execution Read Model
|
||||
|
||||
扩展一层统一 `Action` facade 支持 iLink + personal transports,并有 per-purpose policy、recipient allowlist/validation、确认语义、强幂等、Action audit 到 Send Log correlation。再开放 send/check/run;按需增加 `/executions` read projection,不合并底层日志存储。
|
||||
|
||||
### Phase E — API Center
|
||||
|
||||
Overview、Query、Monitors、Automations、WeChat Actions、Reports、Developer 分区;按业务任务做 schema-aware 表单/效果预览,Raw Request Tester 留在 Developer。展示 Token scope/host 范围/transport capability,而不只是固定 URL 测试器。
|
||||
|
||||
## 11. Concrete Endpoint Proposal
|
||||
|
||||
下表是下一阶段建议契约,不表示当前已实现。新写 API 应统一错误:`{"error":{"code":"...","message":"...","details":{...}},"requestId":"..."}`。时间使用带 offset 的 ISO-8601;接口只接受 stable IDs。
|
||||
|
||||
| Method | Path | Request → Response | Risk | Underlying Service |
|
||||
|---|---|---|---|---|
|
||||
| GET | `/api/v1/capabilities` | 无 → app version/readiness + `query`,`groups.memberStats`,`groupExitMonitor`,`automations`、每种 `wechat.transport/content` 的 `supported/available/reason` | R0 | 新薄 facade 汇总 LocalQuery、GroupStats、Monitor、AutomationStore、personal capability、AgentHub status |
|
||||
| GET | `/api/v1/monitors/group-exits` | 无 → `{enabled,running,monitoredConversationIds,lastCheckedAt,eventCount}` | R0 | `GroupExitMonitorService.getState` |
|
||||
| PATCH | `/api/v1/monitors/group-exits` | `{enabled?,monitoredConversationIds?}` → 保存后的 state;监控 ID 必须 resolve 到现有群 | R1 | `setEnabled` / `setMonitoredRoomIds` |
|
||||
| GET | `/api/v1/monitors/group-exits/events?conversationId=&since=&until=&limit=&cursor=` | ISO 时间和稳定群 ID → `{events,nextCursor}`,事件显式 `eventId`、group/member、counts、detectedAt | R0 | `GroupExitMonitorService.listEvents`;为无 cursor 的现有 list 加稳定分页 adapter |
|
||||
| POST | `/api/v1/monitors/group-exits/check` | `{confirmSideEffects:true}` + `Idempotency-Key` → checkedAt、新事件数、notification execution refs | R2 | `checkNow`;因检查可发现事件并调用 leave-notification Automation,不应标成纯读 |
|
||||
| GET | `/api/v1/automations?type=&enabled=` | 无 → typed rules page;包括 singleton leave rule | R0 | `AutomationRuleStore.listRules` |
|
||||
| POST | `/api/v1/automations` | typed `AutomationRuleDraft`,create 默认 `enabled:false` → `{rule}` | R1 | `AutomationRuleStore.createRule`(需先强化 strict validation/persist result) |
|
||||
| GET | `/api/v1/automations/{ruleId}` | 无 → `{rule}` | R0 | `AutomationRuleStore.getRule` |
|
||||
| PATCH | `/api/v1/automations/{ruleId}` | typed partial config → `{rule}`;`ruleType` 不可变 | R1 | `AutomationRuleStore.updateRule` |
|
||||
| DELETE | `/api/v1/automations/{ruleId}` | 无 → `{deletedId}`;默认拒绝 builtin/system singleton 删除 | R3 | `AutomationRuleStore.deleteRule` + protected-id policy |
|
||||
| POST | `/api/v1/automations/validate` | typed draft → `{valid,normalizedDraft,issues,effects,resolvedTargets,nextRunAt,capabilities,validationId}`;不保存、不发送 | R0 | 新 validator adapter:contact resolve、template validator、capability services、schedule pure functions |
|
||||
| POST | `/api/v1/automations/{ruleId}/enable` | `{validationId,confirmFutureEffects:true}` → `{rule}`;validation hash 必须匹配当前规则 | R1(武装未来 R2) | `AutomationRuleStore.setRuleEnabled` + validator |
|
||||
| POST | `/api/v1/automations/{ruleId}/disable` | 无 → `{rule}` | R1 | `AutomationRuleStore.setRuleEnabled` |
|
||||
| POST | `/api/v1/automations/{ruleId}/run` | `{confirmSideEffects:true}` + `Idempotency-Key` → `{execution}` | R2 | `AutomationService.executeScheduledRule`;只对具有 `run` 语义的 rule type 开放 |
|
||||
| GET | `/api/v1/automations/executions?ruleId=&status=&trigger=&since=&until=&limit=&cursor=` | 无 → `{executions,nextCursor}` | R0 | `AutomationExecutionLogService.list`;需加 timestamp/filter/cursor adapter |
|
||||
| GET | `/api/v1/groups/{conversationId}/member-stats?start=&end=` | ISO 时间窗口 → active/silent/counts/freshness/complete/limitations;未来要 former members 则先扩 shared result | R0 | `GroupStatsService.getMemberStats`;adapter 把 canonical roomId 转 md5 |
|
||||
| GET | `/api/v1/wechat/capabilities` | 无 → personal/iLink 分 transport 状态与内容能力 | R0 | `PersonalWechatCapabilityService` + `WechatSendGateway.hasIlinkSender`/Agent Hub connector health |
|
||||
| POST | `/api/v1/wechat/send` | `{recipient:{type,id},content:{type:"text",text},confirm:true}` + 必填 `Idempotency-Key` → `{actionId,status,transport,sendLogRef}` | R2 | 扩展后的 `WechatActionGateway`/统一 Action facade;不得裸调 `WechatSendGateway.send` |
|
||||
| GET | `/api/v1/wechat/send-logs?status=&since=&limit=&cursor=` | 无 → 只读、脱敏 Send Log page | R0 | `WechatSendGateway.listSendLog` / `WechatSendLogService.list` |
|
||||
| GET | `/api/v1/wechat/action-logs?executionId=&status=&since=&limit=&cursor=` | 无 → 业务 Action 审计 page;preview 默认截短/可省略 | R0 | `WechatActionLogService.list` / `WechatActionGateway.listAuditRecords` |
|
||||
| GET | `/api/v1/executions?source=&status=&since=&until=&limit=&cursor=` | 无 → 统一只读 projection,每项保留 source/executionId/trigger/action/status/error/times/correlation IDs | R0 | 组合 `AutomationExecutionLogService`、Action audit、Send Log;不合并其存储 |
|
||||
| GET | `/api/v1/reports/history?groupId=&since=&until=&limit=&cursor=` | 无 → 仅元数据分页,不带 `generatedImage`、本地绝对路径或完整 report snapshot | R0 | `listGeneratedReports` 经 summary adapter,最好先让 Service 支持 metadata-only |
|
||||
| GET | `/api/v1/reports/history/{reportId}/image` | 无 → PNG binary | R0 | Report History 的 file resolver;仅按内部 report id 解析,不接收任意路径 |
|
||||
| GET | `/api/v1/report-templates` | 无 → 已安装模板的 stable id/name/version/available 列表 | R0 | `reportTemplateService.list` |
|
||||
| GET | `/api/v1/agent-hub/status` | 无 → hub/connector/dataApi/dbReady 的脱敏状态 | R0 | `AgentHubService.getStatus`;`/api/v1/agent/status` 保留 alias |
|
||||
|
||||
`POST /wechat/send` 建议先只开放 text + 明确目标;image path/url、voice 和 file 类型各自扩大本机文件/外传风险,需独立 validation/permission,不从现有任意 `msg` 输入自动继承。
|
||||
|
||||
## 12. Do Not Expose
|
||||
|
||||
- 任意数据库 key、图片 AES key、微信登录凭据、iLink `context_token`/bot token、inbound inbox raw items;这些是密钥或未处理消息,不是业务 API。
|
||||
- 通用 `settings:set`、任意 `dbRoot`、数据库 disconnect/reopen、cache 全清、Knowledge/OCR 索引 clear/reset;配置或 destructive blast radius 远高于 Agent automation 管理需求。
|
||||
- Agent Hub QR/login/verify-code/reconnect/disconnect/connector lifecycle。它会影响进程状态/账户登录,也会暴露登录材料。
|
||||
- `WechatInboundInbox` pending/clear/complete/recordFailure 等队列控制。它是 at-least-once 消息交付内部机制,外部 ack 会破坏不丢消息语义。
|
||||
- Agent Hub 完整对话正文默认不暴露。若明确产品需要,独立设计用户授权、最小时间窗口、分页、清理和脱敏;现有 Conversation Store 为本机完整收发留档。
|
||||
- 任意本地 file path、path traversal 类导出/报告资产操作;不要把 IPC 的 file chooser、reveal、delete path 形状直接变 HTTP 参数。
|
||||
- 单图 AI insight/任意 Vision analyze、批量 TTS synthesis、AI Provider 配置/测试和 app update download/install;它们具有费用、敏感图片/文本上传或应用安装影响。
|
||||
- 清除退群、Automation、发送/Action、报告历史或批量发送接口作为 P0。清理类不是“管理配置”的必要前提,应使用 R3 独立权限及本地可恢复流程。
|
||||
- 通用“任意 Automation DAG/任意脚本/任意 purpose”的创建。当前实现只有明确的三类规则和固定动作,不是 workflow engine;扩展功能应有显式 ruleType/schema,而不是暴露内存对象。
|
||||
|
||||
## 13. Open Questions
|
||||
|
||||
以下属于产品边界选择,无法只从代码决定:
|
||||
|
||||
1. 新 Agent API 是否允许同时操作个人微信和 Agent Hub/iLink,还是第一版限定一个 transport?现有 capability 与 send endpoint 分属两套连接状态。
|
||||
2. Agent 是否默认只拿只读 scope;配置和 R2 send 是否要求独立 token/用户确认?当前只有单一 Bearer Token。
|
||||
3. 多账号是否属于本阶段?当前 Query/GroupExit 绑定当前活动数据库账号,Agent Hub 有自己的 connector accountId;没有统一 account-scoped API model。
|
||||
4. Agent Hub 完整对话是否要作为 API capability?它含完整消息正文,和从微信数据库按 query 搜历史是不同隐私边界。
|
||||
|
||||
真实微信 runtime 可用性、平台 hydration 和 transport 能力需在后续实现集成测试中验证;静态代码审计无法替代真实数据库/微信连接的运行时验证。
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
执行 `pnpm dev` 后,以下状态同时满足,说明本地开发环境已经可用:
|
||||
|
||||
- 控制台显示连接器已生成,例如 `resources/connectors/wechat/win32-x64/wechat-connector.exe`;
|
||||
- Electron 窗口已打开,或 `http://localhost:5173/` 返回 HTTP `200`;
|
||||
- 控制台显示 Local HTTP API 正在监听 `http://127.0.0.1:6131`。
|
||||
|
||||
@@ -22,41 +21,28 @@ WCDB_DEBUG_LOGS=1 pnpm dev
|
||||
|
||||
开启后会输出 `GETMSG-xxx` 请求耗时和 native `WCDB-EXPLAIN` 执行计划,不记录聊天正文。取消该环境变量或设为 `0` 即可关闭。
|
||||
|
||||
## Go 命令找不到
|
||||
|
||||
如果 `pnpm dev` 在构建微信连接器时出现 `spawnSync go ENOENT`,先执行:
|
||||
|
||||
```bash
|
||||
go version
|
||||
```
|
||||
|
||||
命令不可用表示当前终端的 `PATH` 没有找到 Go。Windows 默认安装位置是 `C:\Program Files\Go\bin`。确认 Go 已安装并把该目录加入系统 `PATH` 后,关闭并重新打开终端或 IDE,再重新执行 `go version` 和 `pnpm dev`。
|
||||
|
||||
如果 Go 刚完成安装,已经打开的终端不会自动继承新的环境变量;重开终端是必要步骤。不要绕过连接器构建直接启动 `electron-vite dev`,否则 Agent Hub 的微信连接器不会生成。
|
||||
|
||||
## Electron 二进制缺失或下载失败
|
||||
|
||||
`electron-vite dev` 报 `Electron uninstall`,或 Electron 安装器报 `fetch failed`,通常表示 `node_modules/electron/dist` 中的 Electron 二进制缺失或下载未完成。这不是应用业务代码的启动错误。
|
||||
|
||||
项目的 [`.npmrc`](../../.npmrc) 已设置:
|
||||
**先看根因,别急着删 `node_modules` 重装。** `electron@43` 的 npm 包**不再声明 `postinstall`**(其 `package.json` 里 `scripts` 是空对象),下载改为「首次 `require('electron')` 时的懒加载」。因此:
|
||||
|
||||
```ini
|
||||
electron_mirror=https://npmmirror.com/mirrors/electron/
|
||||
```
|
||||
- `package.json` 里的 `pnpm.onlyBuiltDependencies: ["electron"]` 对它不起作用——上游没有脚本可执行,pnpm 无从下手;
|
||||
- `pnpm install` 跑完不会有任何二进制被下载,**只重装依赖解决不了这个问题**。
|
||||
|
||||
pnpm 会把该值传给 Electron 安装器,令其从镜像下载与 `package.json` 锁定版本匹配的二进制文件,避免默认 GitHub 下载源在受限网络中不可访问。
|
||||
项目已自动兜住这条路径:`scripts/ensure-electron-binary.cjs` 挂在 `postinstall` 与 `predev` 上,校验 `path.txt` 指向的可执行文件是否真的存在(只有 `path.txt` 而没有 `dist/` 同样算没装好),缺失时就地补下载。它读取 `.npmrc` 的 `electron_mirror`(当前为 `https://npmmirror.com/mirrors/electron/`),失败后再兜底重试一次该镜像。
|
||||
|
||||
依赖安装被中断或 Electron 目录不完整时,删除不完整的 `node_modules` 后重新安装:
|
||||
正常情况下你不需要做任何事。只有当自动步骤没有执行时(例如安装时带了 `--ignore-scripts`),才需要手动补一次:
|
||||
|
||||
```bash
|
||||
pnpm install --frozen-lockfile
|
||||
node scripts/ensure-electron-binary.cjs
|
||||
```
|
||||
|
||||
单次安装需要使用其他镜像时,可以临时覆盖项目默认值。PowerShell 示例:
|
||||
要换用别的镜像时,显式设置环境变量(优先于 `.npmrc`)。PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
$env:ELECTRON_MIRROR = 'https://your-electron-mirror.example/'
|
||||
pnpm install --frozen-lockfile
|
||||
node scripts/ensure-electron-binary.cjs
|
||||
```
|
||||
|
||||
该环境变量只影响当前终端,不会改写仓库中的 `.npmrc`。镜像地址必须保留末尾的 `/`,并提供与 Electron 版本对应的目录结构。
|
||||
@@ -69,4 +55,4 @@ Vite 在某些 Windows 环境中只监听 IPv6 本机回环地址 `::1`。这时
|
||||
|
||||
## 仍无法启动时
|
||||
|
||||
保留首次错误的完整输出,并同时记录操作系统、Node.js、pnpm 和 Go 版本,以及 `pnpm install --frozen-lockfile` 与 `pnpm dev` 的执行结果。不要提交数据库密钥、AI API Key、微信数据路径或聊天内容。
|
||||
保留首次错误的完整输出,并同时记录操作系统、Node.js 与 pnpm 版本,以及 `pnpm install --frozen-lockfile` 与 `pnpm dev` 的执行结果。不要提交数据库密钥、AI API Key、微信数据路径或聊天内容。
|
||||
@@ -0,0 +1,28 @@
|
||||
# macOS 版本发送能力二次开发
|
||||
|
||||
如果你已经拥有 TraceMemo 发送能力授权,并希望基于源码进行二次开发,请联系授权人获取开发环境所需的发送能力组件包。
|
||||
|
||||
## 1. 安装发送能力组件
|
||||
|
||||
获取组件包后,将以下文件放到项目对应目录:
|
||||
|
||||
| 组件 | 放入目录 |
|
||||
| ----------------------- | --------------------------------- |
|
||||
| `tm-wechat-host` | `resources/runtime/darwin-arm64/` |
|
||||
| `libtmwechat.dylib` | `resources/runtime/darwin-arm64/` |
|
||||
| `runtime-manifest.json` | `resources/runtime/darwin-arm64/` |
|
||||
| `libwcdb_api.dylib` | `resources/wcdb/macos/arm64/` |
|
||||
| `libWCDB.dylib` | `resources/wcdb/macos/arm64/` |
|
||||
| `tm-wcdb-config-helper` | `resources/wcdb/macos/arm64/` |
|
||||
| `libtmlicense.dylib` | `resources/wcdb/macos/arm64/` |
|
||||
|
||||
完成后,为以下两个文件添加执行权限:
|
||||
|
||||
```bash
|
||||
chmod 755 resources/runtime/darwin-arm64/tm-wechat-host
|
||||
chmod 755 resources/wcdb/macos/arm64/tm-wcdb-config-helper
|
||||
```
|
||||
|
||||
完成配置后,启动 TraceMemo 开发环境,在「设置 → 微信发送」中查看发送能力与授权状态。
|
||||
|
||||
**注意:** 发送能力组件不包含授权。开发环境仍需使用有效的设备授权才能绑定微信和发送消息。
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
- Electron + React + TypeScript;
|
||||
- pnpm 7+;
|
||||
- Go(构建微信连接器);
|
||||
- 平台对应的 Electron/native 构建环境。
|
||||
|
||||
产品文档的事实来源优先级是:当前源码 → 当前 UI/Renderer → 测试 → package/config → README/docs → 历史资料。功能、API、版本、隐私和兼容性变更时,不要只改 README。
|
||||
@@ -18,7 +17,7 @@ pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
本地依赖安装、Go 环境和 Electron 二进制下载异常,请查看[本地启动排障](./local-startup-troubleshooting.md)。
|
||||
本地依赖安装与 Electron 二进制下载异常,请查看[本地启动排障](./local-startup-troubleshooting.md)。
|
||||
|
||||
常用检查:
|
||||
|
||||
@@ -30,21 +29,28 @@ pnpm test:integration
|
||||
pnpm test:e2e:build
|
||||
```
|
||||
|
||||
完整测试入口 `pnpm test` 还会运行 Skill 安装指令、微信连接器、构建和 Playwright 测试;需要对应平台环境。
|
||||
完整测试入口 `pnpm test` 还会运行 Skill 安装指令、构建和 Playwright 测试;需要对应平台环境。
|
||||
|
||||
## 代码变更对应文档
|
||||
|
||||
| 代码区域 | 需要同步检查的文档 |
|
||||
| --------------------------------------------------------- | ---------------------------------------------------------- |
|
||||
| `src/shared/ai-search.ts`、AI Search pipeline | `user-guide/ai-search.md`、`concepts/answer-sources.md` |
|
||||
| `src/shared/knowledge.ts`、`src/main/knowledge/` | `user-guide/knowledge.md`、`concepts/how-it-works.md` |
|
||||
| `src/shared/voice-recognition.ts` | `user-guide/voice.md` |
|
||||
| `src/shared/group-report.ts`、报告 UI | `user-guide/report.md`、API/Agent 文档 |
|
||||
| `src/shared/export.ts`、导出服务/UI | `user-guide/export.md` |
|
||||
| `src/main/services/recall-archive-service.ts`、防撤回设置 | `user-guide/recall-protection.md`、`user-guide/privacy.md` |
|
||||
| `src/shared/local-api-test.ts`、`src/main/http-server.ts` | `agent/api.md`、`api-security.md`、打包 Skill |
|
||||
| Agent Hub service/UI | `agent/agent-hub.md`、`user-guide/privacy.md` |
|
||||
| 设置导航、连接页面 | `user-guide/getting-started.md`、`docs/README.md` |
|
||||
| 代码区域 | 需要同步检查的文档 |
|
||||
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
|
||||
| `src/shared/ai-search.ts`、AI Search pipeline | `user-guide/ai-search.md`、`concepts/answer-sources.md` |
|
||||
| `src/shared/knowledge.ts`、`src/main/knowledge/` | `user-guide/knowledge.md`、`concepts/how-it-works.md` |
|
||||
| `src/shared/voice-recognition.ts` | `user-guide/voice.md` |
|
||||
| `src/shared/group-report.ts`、报告 UI | `user-guide/report.md`、API/Agent 文档 |
|
||||
| `src/shared/export.ts`、导出服务/UI | `user-guide/export.md` |
|
||||
| `src/main/services/system-ocr-service.ts`、`image-text-index-service.ts` | `user-guide/knowledge.md`、`concepts/how-it-works.md`、`user-guide/privacy.md` |
|
||||
| `src/main/services/image-insight-service.ts`、AI Provider | `user-guide/report.md`、`user-guide/privacy.md` |
|
||||
| `src/shared/automation.ts`、自动化服务与执行网关 | `user-guide/report.md`、`concepts/how-it-works.md`、`docs/README.md` |
|
||||
| `src/shared/local-api-test.ts`、`src/main/http-server.ts` | `agent/api.md`、`api-security.md`、打包 Skill |
|
||||
| Agent Hub service/UI | `agent/agent-hub.md`、`user-guide/privacy.md` |
|
||||
| 设置导航、连接页面 | `user-guide/getting-started.md`、`docs/README.md` |
|
||||
|
||||
两条容易被写错的边界:
|
||||
|
||||
- **防撤回已下线**(`src/main/services/recall-archive-service.ts` 保留但不再启动):设置入口隐藏,`recallProtectionEnabled` 在所有读写路径上被强制收敛为 `false`。不要把它写回用户指南。
|
||||
- **图片文字索引(本机 OCR)与图片理解(需要 Provider)是两条不同的路径**:前者写入本地索引、能被搜索,且不联网;后者只在日报和设置里的模型检测中使用。改其中一条时不要把另一条的隐私口径带过去。
|
||||
|
||||
## 文档检查
|
||||
|
||||
@@ -52,7 +58,10 @@ pnpm test:e2e:build
|
||||
|
||||
```bash
|
||||
git diff --check
|
||||
rg -n "v2\.1\.7|TraceMemo|迹忆|mcpServers|无鉴权" README.md docs --glob '*.md' --glob '!DOCUMENTATION_AUDIT.md' --glob '!development/overview.md'
|
||||
# 过时版本号、旧品牌名、旧结构叙述、MCP 误解
|
||||
rg -n "v2\.1\.7|2\.4\.0|v2\.2\.0 兼容期|无鉴权|mcpServers" README.md docs --glob '*.md' --glob '!development/overview.md'
|
||||
# 不存在的产品结构(定时日报已并入自动化)
|
||||
rg -n "日报 → 定时日报|Monitor / Automation" README.md docs --glob '*.md'
|
||||
```
|
||||
|
||||
历史迁移说明可以出现旧版本号;正式使用指南不要把过时版本写成当前版本。负向澄清“6131 不是 MCP Server”可以保留,以防用户照抄错误配置。
|
||||
历史迁移说明可以出现旧版本号;正式使用指南不要把过时版本写成当前版本。负向澄清“6131 不是 MCP Server”可以保留,以防用户照抄错误配置。发版前额外确认 `README.md` 里的版本号与 `package.json` 的 `version` 一致。
|
||||
@@ -0,0 +1,84 @@
|
||||
# Query Agent POC
|
||||
|
||||
这是独立的开发测试入口,不会修改生产“问问微信”执行链。
|
||||
|
||||
先启动 TraceMemo,并在 API Center 开启 Local HTTP API。然后在仓库根目录运行:
|
||||
|
||||
```bash
|
||||
pnpm poc:query-agent "我和BOBO第一次聊了什么"
|
||||
```
|
||||
|
||||
## 两个入口
|
||||
|
||||
| 命令 | 行为 | 何时用 |
|
||||
| --- | --- | --- |
|
||||
| `pnpm poc:query-agent "问题"` | 先执行完整构建,再运行 | 首次运行,或刚改过代码 |
|
||||
| `pnpm poc:query-agent:run "问题"` | 直接运行已有构建,**不构建** | 连续迭代测试 |
|
||||
|
||||
`poc:query-agent:run` 在构建产物不存在时会明确提示先运行 `pnpm poc:query-agent`,**不会自动构建**。
|
||||
|
||||
注意:`poc:query-agent` 内部走的是完整 `electron-vite build`(main + preload + renderer),
|
||||
即使 POC 只需要一个 main entry。连续测试请使用 `poc:query-agent:run` 以免每次都重建整个 renderer。
|
||||
|
||||
## 传参
|
||||
|
||||
参数按原样转发给入口,可以被 `--` 分隔(`pnpm run` 惯例):
|
||||
|
||||
```bash
|
||||
pnpm poc:query-agent -- "BOBO上个月有没有给我发过文件"
|
||||
pnpm poc:query-agent:run "BOBO上个月有没有给我发过文件"
|
||||
```
|
||||
|
||||
入口只会移除参数列表**开头**的一个独立 `--`;问题正文中的 `--` 会原样保留。
|
||||
|
||||
## Provider
|
||||
|
||||
POC 使用设置页当前默认 AI Provider、模型、Base URL 和安全存储中的 API Key。Local Query API 仍使用现有 Bearer Token;POC 输出不会打印 Token、API Key、数据库路径或内部消息 ID。
|
||||
|
||||
## 输出
|
||||
|
||||
**stdout 是 JSON**(`poc:query-agent` 会在它前面混入构建日志,`poc:query-agent:run` 只多两行 pnpm 横幅)。
|
||||
需要机器解析时用 `--silent` 拿到纯 JSON:
|
||||
|
||||
```bash
|
||||
pnpm --silent poc:query-agent:run "我和BOBO第一次聊了什么" > result.json
|
||||
```
|
||||
|
||||
JSON 字段:
|
||||
|
||||
- `question`、`provider`、`model`
|
||||
- `modelCallCount`、`toolCallCount`
|
||||
- `modelDurationsMs`(每次模型调用耗时,含失败的那次)
|
||||
- `modelDiagnostics`(每次模型调用的请求级诊断:HTTP status、content-type、是否返回 HTML、是否超时、耗时)
|
||||
- `firstModelMs`、`toolTotalMs`、`finalModelMs`、`totalMs`
|
||||
- 每次工具调用的名称、脱敏参数、耗时、状态和结果数量
|
||||
- 最终 `answer` 或错误信息
|
||||
|
||||
**stderr 是人类可读摘要**(不参与 JSON 解析):
|
||||
|
||||
```text
|
||||
[Timing]
|
||||
Model #1 1315 ms
|
||||
TM Tools(1) 623 ms
|
||||
Model #2 1598 ms
|
||||
------------------------
|
||||
Total 3545 ms
|
||||
Model total 2913 ms (82.2%)
|
||||
TM tool total 623 ms (17.6%)
|
||||
|
||||
[Provider]
|
||||
provider DeepSeek
|
||||
model DeepSeek Chat
|
||||
host api.deepseek.com
|
||||
model calls 2
|
||||
tool calls 1
|
||||
attempt #1 elapsedMs=1298 status=200 contentType=application/json
|
||||
attempt #2 elapsedMs=1571 status=200 contentType=application/json
|
||||
```
|
||||
|
||||
`elapsedMs` 是 TTFB(收到响应头),`modelDurationsMs` 是整次调用(含读 body);502 时两者接近,
|
||||
说明等待发生在上游网关,不是本地读 body 慢。诊断只记录 host,不记录完整 URL 或任何凭据。非 2xx 响应会先记录 status / content-type / elapsedMs,再返回安全错误(例如“模型服务返回了网页而不是 JSON(HTTP 502 Bad Gateway)”),不会把 HTML 正文丢给 JSON 解析器。
|
||||
|
||||
## 约束
|
||||
|
||||
工具调用最多 5 次,只允许 `query_messages`、`search_messages`、`message_context`、`conversation_overview`。未配置 AI Provider、Local Query API 未启动或当前 Provider 协议不支持 tools 时,POC 会直接返回错误,不会回退到另一套模型配置。
|
||||
@@ -0,0 +1,171 @@
|
||||
# 界面开发规范:按钮与主题色
|
||||
|
||||
这份规范回答一件事:**为什么同一个产品里,有的按钮是主题色,有的还是浏览器默认的黑白方角。**
|
||||
|
||||
先看一个真实案例 —— 同一屏里的两组按钮:
|
||||
|
||||
```
|
||||
主界面:「更新图片文字索引」 ← 主题色(正确)
|
||||
弹窗里:「取消」「开始索引」 ← 浏览器默认样式(错误)
|
||||
```
|
||||
|
||||
两者渲染出来完全不同,用户会以为是两个不同的产品。根因不是"设计没定颜色",
|
||||
而是**组件在导出时把样式丢了**。下面写清楚怎么避免。
|
||||
|
||||
---
|
||||
|
||||
## 1. 永远不要写裸 `<button>`
|
||||
|
||||
任何可点的按钮都必须来自 `components/ui/button`:
|
||||
|
||||
```tsx
|
||||
import { Button } from '../ui'
|
||||
|
||||
<Button variant="outline" onClick={handleCancel}>取消</Button>
|
||||
```
|
||||
|
||||
**唯一的例外**:结构性控件(导航项、Tab、列表行、图标热区)——它们有自己
|
||||
成套的布局样式,用原生 `<button>` 是合理的,但**必须**带 `className`,
|
||||
且样式写在对应的 `.scss` 里,不要在 JSX 里临时拼颜色。
|
||||
|
||||
```tsx
|
||||
// 可以:结构性控件,样式来自 .scss
|
||||
<button type="button" role="tab" className={active ? 'active' : ''} onClick={...}>
|
||||
今日日报
|
||||
</button>
|
||||
```
|
||||
|
||||
**判据**:如果这个按钮在别的界面也会以同样形态出现("取消"、"保存"、"删除"),
|
||||
它就该是 `Button`;如果它只在某一个位置有意义(侧栏导航项),才考虑原生。
|
||||
|
||||
---
|
||||
|
||||
## 2. 三种角色,只有三个默认变体
|
||||
|
||||
`Button` 提供 6 个变体,但**日常只用其中 3 个**:
|
||||
|
||||
| 角色 | `variant` | 长什么样 | 用在哪 |
|
||||
| --- | --- | --- | --- |
|
||||
| 主要 | `default` | 主题色实底 | 这一步用户唯一该做的事 |
|
||||
| 次要 | `outline` / `ghost` | 描边 / 无底色 | 取消、返回、并列的辅助操作 |
|
||||
| 危险 | `destructive` | 红色实底 | 删除、清空、不可恢复的操作 |
|
||||
|
||||
另外两个(`secondary` / `link`)按需用;`link` 只用于正文里的行内跳转。
|
||||
|
||||
**一条硬约束:同一个界面(或同一个弹窗)里,`default` 最多出现一次。**
|
||||
两个主题色实底按钮并排,等于没有主次。
|
||||
|
||||
---
|
||||
|
||||
## 3. 弹窗按钮:组件已经带样式了,不要再包一层
|
||||
|
||||
`AlertDialogCancel` 和 `AlertDialogAction` **自带**按钮样式(分别是 `outline`
|
||||
和 `default`),直接写文字即可:
|
||||
|
||||
```tsx
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleStart}>开始索引</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
```
|
||||
|
||||
**不要**再套一层 `Button`:
|
||||
|
||||
```tsx
|
||||
// 反面写法:外层已经有样式了,再包一层只会产生重复类名
|
||||
<AlertDialogCancel asChild>
|
||||
<Button variant="outline">取消</Button>
|
||||
</AlertDialogCancel>
|
||||
```
|
||||
|
||||
需要危险动作时,用 `className` 覆盖(`cn` 走 tailwind-merge,同族类后者生效):
|
||||
|
||||
```tsx
|
||||
<AlertDialogAction className="bg-destructive text-destructive-foreground">
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 颜色只能用语义 token,禁止硬编码
|
||||
|
||||
颜色全部走 Tailwind 的语义类,它们背后是 `--tm-*` 变量,换主题时自动跟随:
|
||||
|
||||
```
|
||||
背景 bg-primary / bg-surface / bg-accent / bg-destructive
|
||||
文字 text-foreground / text-primary-foreground / text-muted-foreground
|
||||
描边 border-border / border-border-subtle / border-disabled-border
|
||||
```
|
||||
|
||||
```tsx
|
||||
// 对
|
||||
<Button className="bg-primary text-primary-foreground">保存</Button>
|
||||
|
||||
// 错 —— 换主题时这行不会跟着变
|
||||
<Button className="bg-[#247a63] text-white">保存</Button>
|
||||
```
|
||||
|
||||
**判据**:JSX 里出现 `#` 开头的颜色、`rgb(...)`、或 Tailwind 的调色板名
|
||||
(`bg-green-600`、`text-slate-500`)—— 都是漏用 semantic token 的信号。
|
||||
|
||||
---
|
||||
|
||||
## 5. 「默认样式」的三个常见来源
|
||||
|
||||
排查界面里冒出来的黑白方角按钮时,按这个顺序找:
|
||||
|
||||
**① 组件导出时把样式丢了。** 最常见。把 Radix 的 primitive 原样导出:
|
||||
|
||||
```tsx
|
||||
// 错:渲染出来就是浏览器默认按钮
|
||||
const AlertDialogCancel = AlertDialogPrimitive.Cancel
|
||||
```
|
||||
|
||||
正确做法是 `forwardRef` 包一层,挂上 `buttonVariants`:
|
||||
|
||||
```tsx
|
||||
const AlertDialogCancel = React.forwardRef<...>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(buttonVariants({ variant: 'outline' }), className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
```
|
||||
|
||||
**判据**:`components/ui/` 里凡是导出 Radix primitive 的地方,都要确认它是
|
||||
"样式化的封装"还是"原样透传"。原样透传只对布局容器(`Root` / `Portal` /
|
||||
`Group`)成立,对**可点元素**(`Close` / `Action` / `Cancel` / `Item`)不成立。
|
||||
|
||||
**② `asChild` 里重复包了一层。** 外层已经带样式、子元素又带一次,虽然因为
|
||||
同族类后生效而不会出错,但会产生冗余类名。**能去掉一层就去掉。**
|
||||
|
||||
**③ 原生 `<button>` 忘写 `className`。** 见第 1 节的例外条款 —— 结构性控件也必须
|
||||
有样式来源。
|
||||
|
||||
---
|
||||
|
||||
## 6. 提交前检查清单
|
||||
|
||||
- [ ] 新增的可点元素来自 `Button`,不是裸 `<button>`
|
||||
- [ ] 同一界面里 `default` 变体不超过一个
|
||||
- [ ] 危险操作走 `destructive`,不是红色硬编码
|
||||
- [ ] 弹窗按钮没有重复包 `Button`
|
||||
- [ ] JSX 里没有 `#` 开头的颜色、没有 Tailwind 调色板名
|
||||
- [ ] `components/ui/` 里新导出的可点 primitive 已经挂上 `buttonVariants`
|
||||
- [ ] 组件测试覆盖到按钮的可见性与点击行为(testid 用 `xxx-yyy` 连字符命名)
|
||||
|
||||
---
|
||||
|
||||
## 7. 一个反面案例的复盘
|
||||
|
||||
弹窗里的「取消 / 开始索引」显示成浏览器默认样式,原因就是第 5 节第 ① 条:
|
||||
`alert-dialog.tsx` 把 `Cancel` / `Action` 两个 primitive 原样导出了。
|
||||
|
||||
修复是给它们各加一个 `forwardRef` 封装,挂上 `buttonVariants`。**组件本身没坏**,
|
||||
所有调用方一行不用改,样式自动生效 —— 这正是把样式收在 `components/ui/` 里的价值:
|
||||
**修一处,全产品对齐。**
|
||||
|
||||
如果你发现某个地方的按钮"没跟上主题",先别去改那个界面 ——
|
||||
**先看它用的组件是不是漏了样式。**
|
||||
@@ -0,0 +1,92 @@
|
||||
# 微信系统消息(sysmsg)解析与格式兼容
|
||||
|
||||
微信的「系统消息」(入群、撤回、成员变动等)以 XML(`<sysmsg>`)存放在消息内容里,
|
||||
但**同一类提示的 XML 结构会随客户端版本变化**。本文说明 TraceMemo 的解析方式,
|
||||
以及在遇到新格式时应当怎么扩展。
|
||||
|
||||
## 两类格式
|
||||
|
||||
### 旧格式:正文直接放在 `<plain>`
|
||||
|
||||
```xml
|
||||
<sysmsg type="delchatroommember">
|
||||
<delchatroommember>
|
||||
<plain><![CDATA["成员昵称"通过扫描你分享的二维码加入群聊]]></plain>
|
||||
<text><![CDATA["成员昵称"通过扫描你分享的二维码加入群聊]]></text>
|
||||
<link>
|
||||
<scene>qrcode</scene>
|
||||
<text><![CDATA[撤销]]></text>
|
||||
</link>
|
||||
</delchatroommember>
|
||||
</sysmsg>
|
||||
```
|
||||
|
||||
解析:命中 `delchatroommember`,直接取 `<plain>`。
|
||||
|
||||
### 新格式:正文在 `<template>`,用 `$名称$` 引用 link
|
||||
|
||||
```xml
|
||||
<sysmsg type="sysmsgtemplate">
|
||||
<sysmsgtemplate>
|
||||
<content_template type="tmpl_type_profilewithrevokeqrcode">
|
||||
<plain><![CDATA[]]></plain>
|
||||
<template><![CDATA["$adder$"通过扫描你分享的二维码加入群聊 $revoke$]]></template>
|
||||
<link_list>
|
||||
<link name="adder" type="link_profile">
|
||||
<memberlist><member>
|
||||
<username><![CDATA[wxid_xxxxxxxx]]></username>
|
||||
<nickname><![CDATA[成员昵称]]></nickname>
|
||||
</member></memberlist>
|
||||
</link>
|
||||
<link name="revoke" type="link_revoke_qrcode" hidden="1">
|
||||
<title><![CDATA[撤销]]></title>
|
||||
</link>
|
||||
</link_list>
|
||||
</content_template>
|
||||
</sysmsgtemplate>
|
||||
</sysmsg>
|
||||
```
|
||||
|
||||
三个要点:
|
||||
|
||||
- `<plain>` 变成**空 CDATA**,正文挪进 `<template>`;
|
||||
- 正文里的 `$名称$` 是占位符,按 `<link_list>` 中 `link[name]` 回填;
|
||||
- `hidden="1"` 的 link 在微信里是**可点击按钮**,纯文本展示时应省略其文案。
|
||||
|
||||
## 解析流程
|
||||
|
||||
`src/main/message-parser.ts` 的 `parseSystemMessage()` 按以下顺序尝试:
|
||||
|
||||
| 顺序 | 分支 | 处理对象 |
|
||||
| --- | --- | --- |
|
||||
| 1 | `extractRecallMessage` | `<revokemsg>` 撤回通知 |
|
||||
| 2 | `extractSysmsgTemplateText` | `<sysmsgtemplate>` 模板消息 |
|
||||
| 3 | `extractDelChatroomMemberText` | `<delchatroommember>` 成员变动 |
|
||||
| 4 | 通用提取(`plain` → `text` → `title`),再退回 `fallbackSystemText` | 其余未覆盖类型 |
|
||||
|
||||
第 4 步之前会先调用 `stripSysmsgLinkList()` 剥掉 `<link_list>`。
|
||||
|
||||
## 为什么必须显式处理新格式
|
||||
|
||||
通用提取链只在第 1~3 步全部落空时才执行,而新格式恰好让它落空:
|
||||
`<plain>` 是空 CDATA,又没有 `<text>`,于是取到 `<title>` ——
|
||||
那是 `hidden="1"` 按钮的标题。**结果是整条系统消息只剩一个按钮文案**,
|
||||
例如把「某某通过扫描你分享的二维码加入群聊」显示成「撤销」。
|
||||
|
||||
因此三处约束缺一不可:
|
||||
|
||||
1. 模板分支必须排在通用提取之前;
|
||||
2. 占位符回填必须尊重 `hidden="1"`;
|
||||
3. 通用提取前先剥 `<link_list>`,作为未知类型的防护。
|
||||
|
||||
## 新增一类系统消息时
|
||||
|
||||
1. 从真实消息中取出 `content`(`<sysmsg>` 原文),确认 `type` 与承载正文的标签;
|
||||
2. 在 `parseSystemMessage()` 里加一个**早于通用提取**的分支;
|
||||
3. 补 `tests/unit/message-parser.test.ts` 用例,**新旧两版各一条**,防止回归;
|
||||
4. 文档与代码注释只写结构,不粘贴真实会话内容、昵称、wxid 或二维码链接。
|
||||
|
||||
## 相关位置
|
||||
|
||||
- 解析实现:`src/main/message-parser.ts`
|
||||
- 单元测试:`tests/unit/message-parser.test.ts`
|
||||
@@ -0,0 +1,134 @@
|
||||
# 企业微信插件会话:只读验收报告
|
||||
|
||||
本文记录 Mac 微信 4.x 企业微信插件会话(群 `*@qy_g`、单聊 `*@qy_u`)在 TraceMemo 中的
|
||||
真实数据验收结果,用于回答 review 中「需要真实环境证据」的那一项。
|
||||
|
||||
结论先行:**会话列表、群名、群成员、消息、发送者、图片六条链路在真实库上都已跑通**,
|
||||
且全程只读;报告中所有会话 id、群名、成员名、消息正文均以 sha256 前缀代替,不含原文。
|
||||
|
||||
## 验收环境
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| 客户端 | Mac 微信 4.x(企业微信插件会话已存在) |
|
||||
| 账号规模 | 5521 个会话,其中企业会话 7 个 = 5 个 `@qy_g` 群 + 2 个 `@qy_u` 单聊 |
|
||||
| 消息库 | `db_storage`(会话/消息)+ `bizchat/bizchat.db`(企业群名与成员) |
|
||||
| 运行方式 | 以只读模式(`TRACEMEMO_READ_ONLY=1`)直接调用主进程的 `Wcdb4Client` / `chat-service` |
|
||||
| 数据隔离 | 数据库目录用 APFS clone(写时复制)复制后再读;媒体目录只做 `existsSync`/`readFileSync` |
|
||||
|
||||
### 只读是怎么保证的
|
||||
|
||||
1. 数据库侧:`src/main/wcdb4-client.ts` 中不存在 `writeFileSync` / `mkdirSync` / `renameSync` /
|
||||
`unlinkSync` 等写调用,所有 SQL 都是 `SELECT`;验收时读的是 clone 出来的副本。
|
||||
2. 媒体侧:只读取 `msg/attach/<session md5>/<YYYY-MM>/Img|Thumb` 下的 `.dat` 文件,
|
||||
不写回、不删除、不改名。
|
||||
3. 密钥:数据库密钥与图片 AES 密钥从本机已有的安全存储中取出后仅用于本次进程内解密,
|
||||
不落盘、不进入任何报告或提交。
|
||||
|
||||
## 六条链路的实测结果
|
||||
|
||||
### 1. 会话列表与群名(冷启动顺序无关)
|
||||
|
||||
`getSessions()` 是同步路径,会在异步 hydration 之前返回;旧实现只读 `displayNameCache`,
|
||||
冷启动第一次取群名时缓存为空,就会把 `ww...@qy_g` 原样当群名显示。现在的
|
||||
`resolveSessionNickname()` 统一走「企业群名 → 缓存 → 会话昵称 → username」,
|
||||
并且 `getEnterpriseGroupName()` 在缓存未命中时同步查一次 `bizchat.chat_group.chat_name`。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 冷启动同步列表里 5 个企业群是否用 raw id 当群名 | 0/5(全部已解析) |
|
||||
| 2 个企业单聊 | 保持自身昵称(单聊本无群名,符合预期) |
|
||||
| 异步 `getSessionsAsync({hydrateDisplayNames:true})` 之后 | 5 个群名与冷启动完全一致 |
|
||||
| `getGroupNamesAsync()`(退群提示/自动化取群名) | 5/5 企业群在列,名字与会话列表一致 |
|
||||
|
||||
### 2. 联系人列表(群列表与群日报的群名来源)
|
||||
|
||||
群日报的 `groupName` 取 `contact.m_nsNickName`,并过滤内部标识符
|
||||
(`src/renderer/src/utils/group-report-facts.ts:114`)。用真实的 `listContactsAsync()` 复核:
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 7 个企业会话是否都出现在联系人列表 | 7/7 |
|
||||
| `type` 判定 | 5 个 `group`(`@qy_g`)、2 个 `user`(`@qy_u`) |
|
||||
| 群名能否通过 `isInternalIdentifier` 过滤(即日报不显示「未命名会话」) | 7/7 |
|
||||
|
||||
### 3. 群成员(失败与空列表已区分)
|
||||
|
||||
`getEnterpriseGroupMembers(Async)` 现在返回 `Wcdb4GroupMember[] | null`:
|
||||
读不到(缺 native 入口、非 `@qy_g`、查询抛错)返回 `null`,只有 `user_list` 真正为空才返回 `[]`。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 5 个企业群的群快照 | 5/5 可解析 |
|
||||
| 群名与同步通道一致 | 5/5 |
|
||||
| 成员数 | 每群 2 人 |
|
||||
| 成员显示名(`user_info.user_name`) | 2/2 每群都解析到非 id 名称 |
|
||||
|
||||
### 4. 消息数量与发送者
|
||||
|
||||
90 天窗口,每会话最多 500 条:
|
||||
|
||||
| 会话 | 消息数 | 发送者已解析 | 不同发送者 |
|
||||
| --- | --- | --- | --- |
|
||||
| 企业群 A | 350 | 350/350 | 2 |
|
||||
| 企业群 B | 500 | 500/500 | 1 |
|
||||
| 企业群 C | 379 | 379/379 | 1 |
|
||||
| 企业群 D | 369 | 369/369 | 2 |
|
||||
| 企业群 E | 61 | 61/61 | 1 |
|
||||
| 企业单聊 1 | 10 | 10/10 | 2 |
|
||||
| 企业单聊 2 | 3 | 3/3 | 1 |
|
||||
|
||||
所有会话的发送者解析率均为 100%:企业消息的 `source` 是 zstd 压缩的
|
||||
`enterprise_info` XML,`parseEnterpriseSource()` 从中取 `sender` / `nickname` / `bizchat_id`。
|
||||
|
||||
### 5. 图片
|
||||
|
||||
企业图片的 `message_content` 里**没有 md5**(只有 `aeskey` / `encryver` / CDN 地址等属性),
|
||||
所以不能用普通消息的 md5 路线定位文件。实际链路是:`packed_info_data` → `parseImageDatNameFromRow()`
|
||||
解出 32 位 datName → 在 `msg/attach/<session md5>/<YYYY-MM>/Img` 命中 `.dat` → 用图片 AES 密钥解密。
|
||||
|
||||
| 会话 | 图片数 | 抽样 | 定位到文件 | 解密成功 | 格式 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 企业群 A | 188 | 5 | 5/5 | 5/5 | JPEG / PNG |
|
||||
| 企业群 B | 316 | 5 | 5/5 | 5/5 | JPEG |
|
||||
| 企业群 C | 184 | 5 | 5/5 | 5/5 | JPEG |
|
||||
| 企业群 D | 184 | 5 | 5/5 | 5/5 | JPEG / PNG |
|
||||
| 企业群 E | 0 | — | — | — | 该群 90 天内只有文字 |
|
||||
| 企业单聊 1 | 1 | 1 | 1/1 | 1/1 | PNG |
|
||||
| 企业单聊 2 | 0 | — | — | — | — |
|
||||
|
||||
解密结果按文件头判定(`FF D8 FF` / `89 50 4E 47`),不是「解出非空 buffer」就算通过。
|
||||
|
||||
### 6. 企业群的成员批量读取与退群监控
|
||||
|
||||
native 的 `wcdb_get_group_members_batch` **只认 `@chatroom`**。实测:
|
||||
|
||||
- 只请求 3 个普通群 → 正常返回,成员数 500 / 412 / 488;
|
||||
- 只请求 5 个企业群 → 整批失败(nativeCode `-2001`);
|
||||
- 混合请求 3 个普通群 + 5 个企业群 → **整批失败**,普通群的结果也一起丢掉。
|
||||
|
||||
因此在 `chat-service.getGroupMemberIdsBatchAsync()` 里按通道分流:普通群仍走一次 native 批量,
|
||||
企业群逐个走 bizchat 成员通道,最后按调用方请求顺序合并。修复后同一批 8 个会话返回 8 条结果
|
||||
(普通群 500 / 412 / 488,企业群各 2),不再互相拖累。
|
||||
|
||||
退群监控侧(`src/main/services/group-exit-monitor-service.ts`):
|
||||
|
||||
- `normalizeRoomIds()`(:914)与 `normalizeSnapshots()`(:951)都要求 `@chatroom`,
|
||||
所以 `@qy_g` 永远进不了 `monitoredRoomIds`,也不会被写进持久化快照;
|
||||
- 只有「微信内退群提示」开着时,`@qy_g` 才会经 `getGroupNamesAsync()` 进入检测范围;
|
||||
- 此时成员读取失败(`null`)会得到 `membersValid === false`,`applyCurrentMemberships()`
|
||||
直接 `continue`,不会把「读不到」当成「全员退群」。
|
||||
|
||||
## 复现方式(不含任何密钥)
|
||||
|
||||
1. 以只读模式启动主进程,指向 clone 出来的 `db_storage`;
|
||||
2. 调 `getSessions()` 看冷启动群名,再调 `getSessionsAsync({hydrateDisplayNames:true})` 比对;
|
||||
3. 调 `listContactsAsync()` / `getGroupNamesAsync()` / `getGroupSnapshotAsync()` 复核群名与成员;
|
||||
4. 调 `getMessages()` 统计消息数、发送者解析率与图片数;
|
||||
5. 对图片样本调 `parseImageDatNameFromRow()` + `ImageDecryptService.findImageFileAsync()` + `decryptImage()`;
|
||||
6. 调 `getGroupMemberIdsBatchAsync()` 混合普通群与企业群,确认不再整批失败。
|
||||
|
||||
## 隐私说明
|
||||
|
||||
- 本文只出现 sha256 前缀、计数与布尔判定,不含 wxid、群名、成员名、消息正文、文件路径或密钥;
|
||||
- 验收脚本与原始 JSON 均为本机临时产物,不在仓库内,也不会进入提交历史。
|
||||
@@ -0,0 +1,195 @@
|
||||
# 扩展 API 参考(v1)
|
||||
|
||||
## manifest.json
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `manifestVersion` | 是 | 固定 `1` |
|
||||
| `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 |
|
||||
| `name` | 是 | 展示名,≤ 64 字 |
|
||||
| `version` | 是 | `x.y.z`(可带 prerelease) |
|
||||
| `apiVersion` | 是 | 必须为 `1`(向后兼容所有 v1 扩展) |
|
||||
| `minAppVersion` | 否 | 低于该版本拒绝安装 |
|
||||
| `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) |
|
||||
| `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 |
|
||||
| `entrypoints.page` | 二选一 | 页面 HTML 相对路径 |
|
||||
| `entrypoints.background` | 二选一 | 后台入口相对路径 |
|
||||
| `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 |
|
||||
| `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` |
|
||||
| `contributions.navigation` | 否 | `{ label, icon?, pageId?, order? }`,供用户「固定到一级菜单」;`icon` 仅支持内置安全图标集 `spark / bot / digest / bell / media / puzzle / compass / message` |
|
||||
| `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background |
|
||||
|
||||
路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名;
|
||||
安装时还会用 realpath 复核入口仍在扩展目录内。
|
||||
|
||||
## 权限
|
||||
|
||||
| 权限 | 风险 | 能力 |
|
||||
| --- | --- | --- |
|
||||
| `messages.subscribe` | 高 | 接收 `message.received` |
|
||||
| `messages.query` | 高 | `tm.messages.query`(支持游标分页与类型过滤) |
|
||||
| `media.read` | 高 | `tm.media.readImage` / `readVoice` / `readVideo`(按需解密并写入扩展私有缓存目录) |
|
||||
| `media.ocr` | 中 | `tm.media.ocrImage`(纯本地系统 OCR,优先复用既有索引缓存) |
|
||||
| `media.transcribe` | 中 | `tm.media.transcribeVoice`(复用 `VoiceTranscriptionGateway` 与转写缓存) |
|
||||
| `contacts.list` | 中 | 配置页读取群列表(`contacts.listGroups`),不含聊天内容 |
|
||||
| `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` |
|
||||
| `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` |
|
||||
| `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video |
|
||||
| `wechat.send.voice` | 高 | `tm.wechat.send({ type: 'voice' })`,支持传入 `text` 用宿主 TTS 音色合成发送或传入音频 `path` |
|
||||
| `ai.chat` | 中 | `tm.ai.chat` |
|
||||
| `ai.vision` | 中 | `tm.media.analyzeImage` / `tm.ai.analyzeImage`(复用已配置的视觉 AI Provider) |
|
||||
| `render.html` | 低 | `tm.render.htmlToImage`(离线隔离渲染静态 HTML/CSS 为 PNG 长图) |
|
||||
| `notifications.create` | 中 | `tm.notifications.create`(写入扩展通知中心与未读角标) |
|
||||
| `storage` | 低 | `tm.storage.*` 与页面存储 |
|
||||
| `automation.action` | 中 | `tm.automation.registerAction` |
|
||||
| `secrets` | 中 | `tm.secrets.*`(经系统安全存储加密保存私有凭据) |
|
||||
|
||||
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。所有权限均由主进程独立校验,不依赖 SDK 侧检查。
|
||||
|
||||
## 后台 API
|
||||
|
||||
### tm.extension
|
||||
|
||||
- `id: string`
|
||||
- `dataDir: string`(扩展私有数据目录,媒体与渲染产物落盘于此)
|
||||
- `permissions: string[]`(当前已授予)
|
||||
|
||||
### tm.events
|
||||
|
||||
- `on('message.received', handler): () => void`
|
||||
- `off('message.received', handler): void`
|
||||
|
||||
事件字段见 `TraceMemoMessageEvent`:`eventId / messageRef / accountId / conversationId / messageId / senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
|
||||
其中 `messageRef` 与 `tm.messages.query` 返回的 `messageRef` 格式完全统一,包含账号、会话与消息身份隔离校验。
|
||||
|
||||
### tm.messages.query
|
||||
|
||||
```ts
|
||||
await tm.messages.query({
|
||||
conversationId,
|
||||
startTime?,
|
||||
endTime?,
|
||||
limit?,
|
||||
cursor?,
|
||||
order?, // 'asc' | 'desc';省略时保持 v1 默认最新一页语义并支持向更早历史续页
|
||||
types? // 如 ['text', 'image', 'voice']
|
||||
})
|
||||
// → { messages: [{ messageId, messageRef, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }], nextCursor?, hasMore }
|
||||
```
|
||||
|
||||
- 时间参数是 **epoch 毫秒**;默认最近 24 小时,单次最大 35 天,`limit` 上限 500。
|
||||
- 游标以 `(timestamp, messageId)` 为确定性边界,同时间戳多条消息分页不遗漏、不重复。
|
||||
- 数据库未连接时抛 `DATABASE_NOT_READY`。
|
||||
|
||||
### tm.media(扩展媒体 Gateway)
|
||||
|
||||
```ts
|
||||
// 按需读取媒体副本(写入扩展私有目录,不暴露原始微信数据库路径与密钥)
|
||||
await tm.media.readImage({ messageRef, quality?: 'original' | 'thumbnail' })
|
||||
await tm.media.readVoice({ messageRef })
|
||||
await tm.media.readVideo({ messageRef })
|
||||
|
||||
// 本地 OCR / 语音转写 / AI 图片理解(自动复用主程序缓存与并发限制)
|
||||
await tm.media.ocrImage({ messageRef, language?, force? })
|
||||
await tm.media.transcribeVoice({ messageRef, force?, waitMs? })
|
||||
await tm.media.analyzeImage({ messageRef, prompt?, force? })
|
||||
|
||||
// 批量按需处理(单次最多 20 项,并发上限 4,单项失败隔离返回)
|
||||
await tm.media.batch({
|
||||
concurrency: 2,
|
||||
items: [
|
||||
{ op: 'ocrImage', messageRef: imgRef },
|
||||
{ op: 'transcribeVoice', messageRef: voiceRef }
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
- 跨账号 `messageRef` 触发 `ACCOUNT_MISMATCH`;消息类型不匹配触发 `MEDIA_UNSUPPORTED`;缺失文件触发 `MEDIA_NOT_FOUND`;并发满载触发 `CONCURRENCY_LIMITED`。
|
||||
- `tm.ai.analyzeImage` 是 `tm.media.analyzeImage` 的等价别名,均要求 `ai.vision` 权限。
|
||||
|
||||
### tm.render.htmlToImage
|
||||
|
||||
```ts
|
||||
await tm.render.htmlToImage({
|
||||
html: '<main><h1>晨报</h1></main>',
|
||||
css: 'main { padding: 20px; }',
|
||||
fileName: 'morning-2026-12-01.png', // 可选,仅接受安全相对路径
|
||||
width: 460,
|
||||
maxHeight: 16000,
|
||||
backgroundColor: '#ffffff',
|
||||
timeoutMs: 20000
|
||||
})
|
||||
// → { path, previewUrl, width, height, pixelWidth, pixelHeight, deviceScaleFactor, bytes, mimeType: 'image/png', sha256 }
|
||||
```
|
||||
|
||||
- 与官方群聊日报共用同一 `HtmlRenderService` 离线渲染引擎。
|
||||
- 仅接受静态 HTML/CSS:自动拦截 `<script>`、`<iframe>`、内联事件、`javascript:`、`srcset`/`xlink:href` 与外链资源,独立窗口 + 临时 Session + 严格 CSP,输出至 `<dataDir>/rendered/`;生成路径可直接交给 `tm.wechat.send({ type: 'image', to, path })`,`previewUrl`(`tm-extension://<extensionId>/_data/rendered/...`)可直接用于扩展沙箱页面 `<img>` 预览。
|
||||
|
||||
### tm.notifications
|
||||
|
||||
```ts
|
||||
await tm.notifications.create({
|
||||
title: '今日晨报已生成',
|
||||
body: '覆盖 3 个群聊,共提炼 5 条重点',
|
||||
level: 'success', // 'info' | 'success' | 'warning' | 'error'
|
||||
dedupeKey: 'morning-2026-12-01',
|
||||
pageId: 'digest'
|
||||
})
|
||||
// → { id, deduped, createdAt }
|
||||
|
||||
const ownItems = await tm.notifications.list()
|
||||
const { changed } = await tm.notifications.markRead({ id: ownItems[0]?.id })
|
||||
```
|
||||
|
||||
- 由宿主持久化管理;同扩展相同 `dedupeKey` 仅更新内容不重复累加未读数,并受滑动窗口防刷屏限频保护(超限抛 `CONCURRENCY_LIMITED`)。
|
||||
- `list` 与 `markRead` 强绑定调用方 `extensionId`,只能读写本扩展自己的通知。
|
||||
- 已固定到一级菜单的扩展在固定入口显示独立未读角标;未固定扩展聚合到「扩展」导航的未读角标,与红色 `!` 发送能力异常提示严格区分。
|
||||
- 停用扩展拒绝写入新通知(`EXTENSION_DISABLED`);卸载扩展自动清理其全部通知状态。
|
||||
|
||||
### tm.wechat.send
|
||||
|
||||
```ts
|
||||
await tm.wechat.send({ to, text, at?, dedupeKey? })
|
||||
await tm.wechat.send({ type: 'image', to, path: '/abs/path/cover.png', dedupeKey? })
|
||||
await tm.wechat.send({ type: 'video', to, path: '/abs/path/clip.mp4', dedupeKey? })
|
||||
await tm.wechat.send({ type: 'voice', to, text: '你好呀', voiceId?, dedupeKey? })
|
||||
// → { actionId, status: 'sent' }
|
||||
```
|
||||
|
||||
按顺序检查:权限 → 参数 → manifest 会话范围 → 频率 → 本机发送能力 → Pro 授权校验 → Action Gateway。任何一步不通过都抛带错误码的异常。
|
||||
|
||||
### tm.ai.chat / tm.storage / tm.secrets / tm.automation / tm.capabilities / tm.log
|
||||
|
||||
- `tm.ai.chat(messages)`:调用 TraceMemo 已配置的 AI Provider,不暴露 API Key。
|
||||
- `tm.storage.{get,set,remove,list}`:键 `[A-Za-z0-9._-]{1,64}`,单值 ≤ 256KB,总量 ≤ 1MB。
|
||||
- `tm.secrets.{get,set,delete,has}`:系统安全存储加密凭据。
|
||||
- `tm.automation.registerAction({ id, title, description?, inputSchema?, handler })`:注册自动化动作。
|
||||
- `tm.page.onRequest(method, handler)`:注册页面到同扩展后台的受限请求处理器(响应 ≤ 64KB 纯 JSON)。
|
||||
- `tm.capabilities.get()`:返回只读环境能力快照。
|
||||
- `tm.log.{info,warn,error}`:写入扩展日志(最多保留 200 条,单行 ≤ 500 字)。
|
||||
|
||||
## 错误码
|
||||
|
||||
| 码 | 含义 |
|
||||
| --- | --- |
|
||||
| `EXTENSION_NOT_FOUND` | 扩展不存在 / 已卸载 |
|
||||
| `EXTENSION_DISABLED` | 扩展未启用 |
|
||||
| `EXTENSION_INCOMPATIBLE` | apiVersion 或 minAppVersion 不满足 |
|
||||
| `EXTENSION_INVALID_MANIFEST` | manifest 不合法 |
|
||||
| `EXTENSION_INVALID_PATH` | 入口或输出路径越界 |
|
||||
| `EXTENSION_HOST_UNAVAILABLE` | 后台进程未运行 |
|
||||
| `PERMISSION_DENIED` | 未授予权限或超出声明范围 |
|
||||
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备或未配置 |
|
||||
| `LICENSE_REQUIRED` | 无有效 Pro 授权 |
|
||||
| `DATABASE_NOT_READY` | 微信数据库未连接 |
|
||||
| `SEND_NOT_SUPPORTED` | 当前平台或内容类型不支持 |
|
||||
| `MEDIA_NOT_FOUND` | 找不到消息对应的本地媒体文件 |
|
||||
| `MEDIA_UNSUPPORTED` | 该消息类型不支持所请求的媒体操作 |
|
||||
| `ACCOUNT_MISMATCH` | `messageRef` 不属于当前已连接账号 |
|
||||
| `CONCURRENCY_LIMITED` | 媒体解析或渲染并发达到上限 |
|
||||
| `RENDER_FAILED` | 离线 HTML 渲染失败 |
|
||||
| `ACTION_TIMEOUT` | 处理超时 |
|
||||
| `ACTION_FAILED` | 执行失败 |
|
||||
| `RATE_LIMITED` | 触发频率限制 |
|
||||
| `INVALID_REQUEST` | 参数非法或恶意输入被拒绝 |
|
||||
| `STORAGE_LIMIT_EXCEEDED` | 存储或产出文件体积超限 |
|
||||
@@ -0,0 +1,69 @@
|
||||
# 扩展中心架构
|
||||
|
||||
## 目标
|
||||
|
||||
将二次开发能力以稳定、可演进的 SDK 暴露给扩展,同时复用 TraceMemo 主程序既有的消息监听、媒体解密、语音转写、系统 OCR、视觉模型、HTML 离线渲染与发送网关,不维护第二套平行实现。
|
||||
|
||||
## 分层
|
||||
|
||||
```text
|
||||
TraceMemo Core(Electron 主进程 / 渲染层)
|
||||
│
|
||||
ExtensionManager ─── ExtensionRegistry(启用状态 / 授权集合)
|
||||
│ ExtensionInstaller(目录 / ZIP 安装,原子替换)
|
||||
│ ExtensionNavigationStore(固定到一级菜单的状态与排序)
|
||||
│ ExtensionNotificationStore(通知持久化、去重与未读汇总)
|
||||
│ ExtensionLogStore / ExtensionActionRegistry / ExtensionEventBus
|
||||
│
|
||||
ExtensionHost(每个扩展一个独立 Node 子进程)
|
||||
│ require(background/index.js),注入 tm
|
||||
│
|
||||
tm.* ── 白名单 RPC(主进程独立权限校验)──▶ 宿主能力
|
||||
├─ storage / secrets → extensions-data/<id> / safeStorage
|
||||
├─ messages.query → chat-service(游标分页 + 统一 messageRef)
|
||||
├─ media.* → ExtensionMediaGateway
|
||||
│ ├─ ImageDecryptService / VoiceService / VideoAssetService
|
||||
│ ├─ SystemOcrService + imageTextIndexService 缓存
|
||||
│ ├─ VoiceTranscriptionGateway
|
||||
│ └─ ImageInsightService / AIProviderService
|
||||
├─ render.htmlToImage → HtmlRenderService(与官方群聊日报共用)
|
||||
├─ notifications → ExtensionNotificationStore → 一级导航角标 & 通知中心
|
||||
├─ wechat.send → ExtensionSendGateway → WechatActionGateway
|
||||
├─ ai.chat / vision → AIProviderService
|
||||
└─ capabilities → 只读快照
|
||||
```
|
||||
|
||||
## 目录与宿主状态
|
||||
|
||||
```text
|
||||
<userData>/
|
||||
extensions/<id>/ 扩展代码(manifest.json / ui / background)
|
||||
extensions-data/<id>/ 扩展私有数据
|
||||
storage.json JSON 键值存储
|
||||
media-cache/{images,voices,videos}/ 按需解密的媒体副本缓存
|
||||
rendered/ tm.render.htmlToImage 生成的 PNG 长图
|
||||
extensions-state/ 宿主管理状态
|
||||
registry.json 启用状态与已授予权限
|
||||
pinned-navigation.json 用户固定到一级导航的扩展顺序
|
||||
notifications.json 扩展通知中心持久化记录
|
||||
logs/<id>.jsonl 运行日志
|
||||
extensions-staging/ 安装临时目录
|
||||
```
|
||||
|
||||
## 统一 messageRef 与按需媒体流水线
|
||||
|
||||
- 实时事件 `ExtensionMessageEvent` 与历史查询 `ExtensionQueriedMessage` 输出同一套 `tmref1_*` 编码的 `messageRef`,内含 `accountId / conversationId / messageId / localId? / timestamp?`。
|
||||
- 扩展通过 `messageRef` 按需请求媒体与派生解析;`ExtensionMediaGateway` 强制校验当前账号一致、权限充足、并发与超时上限,并将文件副本隔离写入该扩展自己的 `extensions-data/<id>/media-cache/`。
|
||||
- 本地 OCR、语音转写与图片视觉理解优先复用主程序已有缓存,避免重复解密或重复调用模型。
|
||||
|
||||
## 通用 HTML 渲染服务
|
||||
|
||||
- `src/main/services/html-render-service.ts` 统一承接官方群聊日报截图(`group-report-service.ts`)与扩展 `tm.render.htmlToImage`。
|
||||
- 每次渲染创建独立隐藏 `BrowserWindow` 与临时 `Session` 分区,限制网络请求仅放行目标 HTML 文件,校验静态 HTML 与输出尺寸/体积/并发/超时,并在 `finally` 中保证销毁窗口并删除临时文件。
|
||||
|
||||
## 动态一级导航与通知聚合
|
||||
|
||||
- 扩展可在 `manifest.json` 声明 `contributions.navigation`(安全内置图标 + 标签 + 默认页);用户在扩展详情页主动选择「固定到一级菜单 / 取消固定 / 上移 / 下移」。
|
||||
- 固定入口渲染在左侧一级导航「设置」上方,点击直接复用同一个 `ExtensionPageHost` 打开扩展页面,不新建第二套页面容器。
|
||||
- 已固定扩展的未读通知显示在对应固定入口角标;未固定扩展的未读通知聚合到「扩展」导航的蓝色数字角标,与红色 `!` 发送能力异常提示严格区分。
|
||||
- 卸载扩展时宿主自动清理其固定导航项与全部通知记录。
|
||||
@@ -0,0 +1,170 @@
|
||||
# 克隆 TraceMemo 后开发自己的扩展
|
||||
|
||||
本指南说明如何从 TraceMemo 示例开始,编写、安装和调试自己的扩展。扩展代码与 TraceMemo 主程序分开维护;通常只需要写一个扩展目录,不必改 TraceMemo 的业务源码。
|
||||
|
||||
本文适用于包含 Extension Center v1 的 TraceMemo 版本,扩展 API 版本为 `1`。较早的源码或安装包如果还没有左侧「扩展」入口,需要先使用包含 Extension Center 的分支或版本。
|
||||
|
||||
## 1. 克隆并启动 TraceMemo
|
||||
|
||||
先按项目开发文档准备 Node.js 与 pnpm,然后克隆源码、安装依赖并启动开发版:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Wxw-Gu/TraceMemo.git
|
||||
cd TraceMemo
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
`pnpm dev` 启动的是 TraceMemo 开发版。扩展安装后会复制到应用的用户数据目录;修改源码目录里的文件不会自动同步到已安装副本,每次改完都要重新安装同一扩展目录。
|
||||
|
||||
## 2. 从示例创建扩展
|
||||
|
||||
建议先复制示例,再按功能删改文件:
|
||||
|
||||
```bash
|
||||
cp -R examples/extensions/keyword-bot ../my-tracememo-extension
|
||||
```
|
||||
|
||||
`keyword-bot` 带有规则、匹配与发送逻辑;如果只是做最小扩展,保留 `manifest.json`、`ui/` 与 `storage` 用法,删除 `lib/`、规则 UI 以及 `background` 里的匹配/发送代码即可。
|
||||
|
||||
目录通常如下:
|
||||
|
||||
```text
|
||||
my-tracememo-extension/
|
||||
manifest.json 扩展身份、入口和权限声明
|
||||
background/index.js 可选;后台逻辑,运行于独立 Node 子进程
|
||||
ui/ 可选;扩展页面,运行于 sandbox iframe
|
||||
index.html
|
||||
app.js
|
||||
style.css
|
||||
```
|
||||
|
||||
最小扩展只要求有一个页面或后台入口。可先从 `keyword-bot` 保留 `manifest.json`、页面桥与 `storage` 用法,再把 `manifest.json` 中的 `id`、`name`、`description`、`author` 改成自己的信息;`id` 是反向域名格式,例如 `com.example.my-helper`,必须唯一,不能使用 `com.tracememo.`、`tracememo.` 或 `tm.` 前缀。版本采用 `x.y.z` 格式。
|
||||
|
||||
示例中的页面脚本也有一个 `EXTENSION_ID` 常量,使用页面桥时要将它改成 manifest 中完全相同的 id。稳定 id 很重要:相同 id 的升级会保留该扩展的配置;换 id 则会被视为另一个扩展。
|
||||
|
||||
典型 manifest:
|
||||
|
||||
```json
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.my-helper",
|
||||
"name": "我的扩展",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "我的 TraceMemo 扩展",
|
||||
"permissions": ["storage"],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [{ "id": "settings", "title": "设置" }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`minAppVersion` 是最低应用版本,可按扩展实际依赖调整。入口路径必须是扩展目录内的安全相对路径;安装器会检查 manifest 和入口文件。
|
||||
|
||||
## 3. 编写后台逻辑
|
||||
|
||||
后台入口导出 `activate(tm)`。TraceMemo 会在扩展启用时启动独立 Node 子进程,并注入 `tm` API:
|
||||
|
||||
```js
|
||||
module.exports = function activate(tm) {
|
||||
tm.log.info(`扩展已启动:${tm.extension.id}`)
|
||||
|
||||
tm.events.on('message.received', async (event) => {
|
||||
if (event.isSelf || !event.mentionsMe || !event.text) return
|
||||
|
||||
await tm.wechat.send({
|
||||
to: event.conversationId,
|
||||
text: '收到,我来处理。',
|
||||
dedupeKey: event.eventId
|
||||
})
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
上面这个例子需要在 manifest 中声明 `messages.subscribe`、`wechat.send.text`,并声明消息订阅范围:
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": ["messages.subscribe", "wechat.send.text", "storage"],
|
||||
"subscriptions": {
|
||||
"messageTypes": ["text"],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": true,
|
||||
"includeSelf": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
按需申请权限,不要为了省事把所有权限都加上。高、中风险权限会在启用时要求用户确认;没有获得相应授权的 API 会返回权限错误。微信发送仍经过 TraceMemo 的权限、范围、频率、发送能力和授权校验。
|
||||
|
||||
可用 API 包括 `tm.events`、有界的 `tm.messages.query`、`tm.wechat.send`、`tm.ai.chat`、`tm.storage`、`tm.automation.registerAction`、`tm.capabilities.get` 和 `tm.log`。字段、限制与错误码见[扩展 API 参考](./api-reference.md)。仓库的 `packages/extension-sdk/index.d.ts` 只提供类型定义,不是运行时依赖;运行时的 `tm` 由 TraceMemo 注入。
|
||||
|
||||
## 4. 编写扩展页面
|
||||
|
||||
页面在 sandbox iframe 中运行,不能访问 `window.api`、Node 或 Electron。需要调用宿主白名单功能时,通过 `postMessage` 页面桥通信。可参考 `examples/extensions/keyword-bot/ui/app.js` 里的 `callHost()` 与消息处理,并更新其中的扩展 id。页面桥目前允许存储读写、能力查询、群列表查询(需 `contacts.list`)和扩展信息查询;页面不能直接读取聊天消息、调用 AI 或发送微信。
|
||||
|
||||
后台逻辑使用 `tm.storage`;页面则通过页面桥的 `storage.get` / `storage.set` 等方法访问同一扩展的私有存储。
|
||||
|
||||
## 5. 在 TraceMemo 中安装和调试
|
||||
|
||||
1. 在开发版或已支持扩展的 TraceMemo 中打开左侧「扩展」。
|
||||
2. 选择「安装目录」,指向 `my-tracememo-extension`。也可以将扩展文件打成 ZIP;`manifest.json` 必须位于 ZIP 根目录,然后选择「安装 ZIP」。
|
||||
3. 安装完成后,选中扩展并点「启用」。检查权限清单,只确认扩展功能确实需要的权限。
|
||||
4. 有页面入口时点「打开页面」;检查配置是否读写正常。后台运行日志可在扩展详情页查看。
|
||||
5. 修改源码后重新安装同一个目录,以更新已安装副本;如后台进程仍未刷新,再停用后重新启用。页面资源更新后重新打开或刷新扩展页面。
|
||||
|
||||
同一 `id` 重新安装会更新扩展代码并保留已授予权限、启用状态和扩展存储。卸载默认保留数据;需要清理时再明确选择删除数据。
|
||||
|
||||
## 6. 编写和运行测试
|
||||
|
||||
纯 JavaScript 扩展可用 Node 内置检查器与测试运行器,不需要把扩展依赖装进 TraceMemo:
|
||||
|
||||
```bash
|
||||
node --check ../my-tracememo-extension/background/index.js
|
||||
node --test ../my-tracememo-extension/tests/*.test.mjs
|
||||
```
|
||||
|
||||
若扩展放在 TraceMemo 仓库的 `examples/extensions/` 下,也可以参照示例的测试命令,例如:
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
|
||||
```
|
||||
|
||||
改动 TraceMemo 扩展宿主、SDK 契约或示例校验时,再运行对应的 TraceMemo 测试:
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run --config vitest.unit.config.ts tests/unit/extension-manifest.test.ts tests/unit/extension-installer.test.ts tests/unit/extension-host.test.ts
|
||||
pnpm typecheck
|
||||
```
|
||||
|
||||
## 7. 自动化动作
|
||||
|
||||
扩展可以在 manifest 中用 `contributions.automationActions` 声明动作,并申请 `automation.action`;后台通过 `tm.automation.registerAction()` 注册实现。动作返回的 `reply` 由 TraceMemo 宿主经统一 Gateway 发送,扩展不应自行绕过 Gateway。
|
||||
|
||||
当前版本可以在扩展详情页查看动作是否已注册;自动化规则编辑器尚未提供选择扩展动作的入口,因此目前不能通过界面把这些扩展动作配置到规则中。相关执行接口已在宿主侧实现,界面入口开放后再按产品文档配置。
|
||||
|
||||
## 8. 安全与发布前检查
|
||||
|
||||
扩展后台虽然运行在独立进程,但这**不是操作系统级沙箱**。它是任意 Node.js 代码,拥有运行 TraceMemo 用户的文件与网络权限。只安装自己编写或信任来源的扩展,不要把不可信扩展当成受隔离代码。
|
||||
|
||||
发布前至少确认:
|
||||
|
||||
- manifest id 唯一、版本递增、权限最小化,所有入口文件都在扩展目录内;
|
||||
- 页面只使用受支持的 postMessage 白名单,不假设能访问 Electron API;
|
||||
- 消息回调处理异常并使用稳定的 `dedupeKey`;
|
||||
- 单元测试覆盖纯逻辑,人工验证安装、启用、停用、重装和配置保留;
|
||||
- README 说明扩展行为、权限用途、外部依赖与可能发送的内容。
|
||||
|
||||
## 相关资料
|
||||
|
||||
- [扩展开发入门与 API 用法](./getting-started.md)
|
||||
- [扩展 API 参考](./api-reference.md)
|
||||
- [扩展中心架构](./architecture.md)
|
||||
- [扩展安全模型](./security.md)
|
||||
- [可安装示例](../../examples/extensions/README.md)
|
||||
@@ -0,0 +1,91 @@
|
||||
# 扩展开发入门
|
||||
|
||||
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页提供第二阶段新增能力与基础 API 的快速上手。
|
||||
|
||||
## 1. 官方模板一览
|
||||
|
||||
在 TraceMemo 左侧点击「扩展」→「官方模板」可一键安装以下示例:
|
||||
|
||||
| 模板 | 演示能力 |
|
||||
| --- | --- |
|
||||
| `keyword-bot` | 消息事件订阅、关键词回复、Gateway 发送、自动化动作 |
|
||||
| `group-chat-bot` | 多套群聊人格、长短期记忆、文字/语音回复、按需图片 OCR/视觉与语音转写 |
|
||||
| `morning-digest` | 分页消息查询、批量媒体解析、AI 总结、离线 HTML 长图渲染、扩展通知、一级导航固定与可选微信发送 |
|
||||
| `douyin-sender` | 外部 Python 脚本协作、视频下载与发送 |
|
||||
|
||||
## 2. 最小扩展与固定到一级菜单
|
||||
|
||||
```json
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.my-extension",
|
||||
"name": "我的扩展",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.7.0",
|
||||
"permissions": ["storage", "notifications.create"],
|
||||
"entrypoints": { "page": "ui/index.html", "background": "background/index.js" },
|
||||
"contributions": {
|
||||
"pages": [{ "id": "main", "title": "我的扩展" }],
|
||||
"navigation": { "label": "我的工具", "icon": "spark", "pageId": "main" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
用户在扩展详情页点击「固定到一级菜单」后,该入口会出现在左侧「设置」上方;点击可直接打开扩展页面。
|
||||
|
||||
## 3. 按需分页读取消息与解析图片/语音
|
||||
|
||||
```js
|
||||
module.exports = function activate(tm) {
|
||||
tm.page.onRequest('runDigest', async ({ conversationId }) => {
|
||||
const endTime = Date.now()
|
||||
const startTime = endTime - 24 * 60 * 60 * 1000
|
||||
const messages = []
|
||||
let cursor
|
||||
|
||||
do {
|
||||
const page = await tm.messages.query({
|
||||
conversationId,
|
||||
startTime,
|
||||
endTime,
|
||||
order: 'asc',
|
||||
limit: 100,
|
||||
cursor
|
||||
})
|
||||
messages.push(...page.messages)
|
||||
cursor = page.nextCursor
|
||||
if (!page.hasMore) break
|
||||
} while (cursor)
|
||||
|
||||
const items = messages
|
||||
.filter((m) => m.type === 'image' || m.type === 'voice')
|
||||
.slice(-6)
|
||||
.map((m) => ({
|
||||
op: m.type === 'image' ? 'ocrImage' : 'transcribeVoice',
|
||||
messageRef: m.messageRef
|
||||
}))
|
||||
|
||||
const media = items.length ? await tm.media.batch({ items, concurrency: 2 }) : { results: [] }
|
||||
const rendered = await tm.render.htmlToImage({
|
||||
html: `<main><h1>今日速览</h1><p>共 ${messages.length} 条消息</p></main>`,
|
||||
css: 'main{padding:24px;font-family:-apple-system,sans-serif;}',
|
||||
width: 460
|
||||
})
|
||||
await tm.notifications.create({
|
||||
title: '今日速览已生成',
|
||||
body: `分析 ${messages.length} 条消息,解析 ${media.results.length} 条媒体`,
|
||||
level: 'success',
|
||||
dedupeKey: `digest-${new Date().toISOString().slice(0, 10)}`,
|
||||
pageId: 'main'
|
||||
})
|
||||
return { count: messages.length, imagePath: rendered.path }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## 4. 开发调试与安全约定
|
||||
|
||||
- 后台进程属于受信任本地代码;涉及敏感权限(读取消息/媒体、发微信、写通知)均由主进程独立校验,请按最小权限原则声明。
|
||||
- 涉及微信发送的扩展默认应关闭自动发送,先通过离线渲染与预览确认内容后再由用户手动触发测试发送。
|
||||
- 修改源码后可通过「二次开发 → 链接本地项目 + 重载」快速验证,无需反复重新打包安装。
|
||||
@@ -0,0 +1,44 @@
|
||||
# 扩展安全模型
|
||||
|
||||
## 信任分级与进程边界
|
||||
|
||||
| 类型 | 说明 | 支持状态 |
|
||||
| --- | --- | --- |
|
||||
| 声明式 UI 扩展 | 仅页面,经 `postMessage` 白名单访问存储与能力查询 | 支持 |
|
||||
| 受信任本地代码扩展 | 后台为独立 Node 子进程(`ELECTRON_RUN_AS_NODE`),具备当前系统用户的 Node 权限 | 支持(安装即视为受信任本地代码) |
|
||||
|
||||
**明确边界:独立 Node 子进程属于受信任本地代码,不构成强安全沙箱。** 我们不夸大进程隔离的安全性——子进程未受操作系统级 sandbox(如 seatbelt / AppContainer)约束。宿主边界保护的是 **TraceMemo 内部敏感资产与受控网关**:
|
||||
|
||||
- 扩展无法获取微信数据库句柄、数据库解密密钥、图片 AES/XOR 密钥、AI/TTS API Key 明文或原生发送 Runtime 句柄;
|
||||
- 扩展不能 `require` 主进程模块,也不能伪造宿主可信字段(`origin` / `purpose` / `triggerType` / 幂等键);
|
||||
- 扩展的后台代码崩溃、死循环或挂死不会拖垮主进程(具备启动超时、调用超时、退避重启与连续崩溃熔断)。
|
||||
|
||||
## 主进程独立权限校验
|
||||
|
||||
子进程 SDK 侧的 `requirePermission` 仅用于提前给出可读错误提示;**所有 RPC 方法在主进程 `ExtensionHost`、`ExtensionManager`、`ExtensionMediaGateway` 与 `ExtensionSendGateway` 均独立校验权限、启用状态与暂停状态**,绝不信任子进程上报的数据。
|
||||
|
||||
## 媒体 Gateway 安全与隔离
|
||||
|
||||
- **账号身份与签名防伪造**:实时事件与历史查询签发的 `messageRef` 均由主进程附加运行期 HMAC-SHA256 签名与账号世代标识;未签名伪造、篡改、跨账号(`ACCOUNT_MISMATCH`)或账号切换前的旧引用一律拒绝;若扩展声明了 `subscriptions.conversationIds`,查询与媒体读取同样强制校验会话范围(`PERMISSION_DENIED`)。
|
||||
- **跨扩展与跨账号缓存隔离**:图片、语音、视频副本严格落盘到 `<extensions-data>/<extensionId>/media-cache/<accountHash>/`,写入前经 `isPathInside` 与 `realpath` 双重校验,绝不返回微信原始目录或数据库路径。
|
||||
- **错误脱敏**:底层异常中的本地绝对路径与密钥键名在返回扩展前自动脱敏。
|
||||
- **资源保护**:全局并发上限、单扩展并发上限、单次批量项数上限(≤ 20)及单项超时(`ACTION_TIMEOUT`)防止扩展拖垮本地 OCR、语音转写队列或主进程 I/O。
|
||||
|
||||
## 离线 HTML 渲染安全
|
||||
|
||||
- 扩展调用 `tm.render.htmlToImage` 仅允许静态 HTML/CSS:入口即拒绝 `<script>`、`<iframe>`、`<object>`、`<embed>`、`<meta http-equiv="refresh">`、内联事件(`on*=`)、`javascript:` 协议及任何 `http(s)/ws/ftp/file` 外链。
|
||||
- 渲染窗口强制 `sandbox: true`、`contextIsolation: true`、`nodeIntegration: false`、独立随机 `partition`、`will-navigate` 拦截、弹窗拒绝、严格响应头 CSP(`default-src 'none'; script-src 'none'; img-src data:; style-src 'unsafe-inline'`)与 `webRequest.onBeforeRequest` 单文件白名单。
|
||||
- 强制限制 HTML 体积、输出宽高、PNG 体积、渲染并发数与执行超时;无论成功或失败都在 `finally` 中销毁窗口、注销过滤器并删除临时 HTML 文件。
|
||||
- 输出文件名经 `isSafeRelativeEntryPath`、`isPathInside` 与 `realpath` 校验,杜绝 `../` 路径穿越与符号链接逃逸。
|
||||
|
||||
## 发送与授权安全
|
||||
|
||||
- 所有扩展发送(文本、图片、视频、语音)均经 `ExtensionSendGateway` → `WechatActionGateway` → `WechatSendGateway`,不可绕过 Pro entitlement、频率限制、会话范围与 Action Audit。
|
||||
- 真实微信测试默认禁止自动发送;官方模板(如「AI 晨报」)默认关闭自动发送微信开关,仅在用户人工确认并显式开启或点击测试发送时才调用发送链路。
|
||||
|
||||
## 页面、导航与通知安全
|
||||
|
||||
- 扩展页面运行在 `tm-extension://<id>/<path>` 自定义协议与 `sandbox="allow-scripts"` iframe 中,固定到一级导航后仍复用同一个 `ExtensionPageHost`,不暴露 `window.api` 或 Node。
|
||||
- 扩展私有媒体预览仅开放 `tm-extension://<id>/_data/{rendered,media-cache}/` 白名单媒体扩展名(图片/音频/视频),禁止访问 `storage.json`、其他目录、符号链接与脚本/HTML 类型,不向扩展页面开放本地文件系统。
|
||||
- `contributions.navigation.icon` 仅允许预定义安全图标枚举,不加载扩展提供的原始 SVG 到主进程/主界面 DOM。
|
||||
- 停用扩展拒绝写入新通知;单扩展通知受滑动窗口限频保护防刷屏;卸载扩展自动清理固定导航项与通知持久化状态。
|
||||
@@ -1,5 +1,62 @@
|
||||
# macOS 数据访问说明(兼容入口)
|
||||
# macOS 关闭 SIP 教程
|
||||
|
||||
完整内容已移到[macOS 数据访问与系统权限](./platform/macos.md)。
|
||||
SIP(System Integrity Protection,系统完整性保护)是 macOS 的系统安全机制。关闭 SIP 会降低系统安全性,只建议在确实需要读取或调试本地微信数据时临时关闭;操作完成后,建议重新开启。
|
||||
|
||||
保留此文件是为了兼容应用内已经发布的帮助链接。请不要把“关闭 SIP”当作默认安装步骤;只有当当前连接页面明确要求时才处理,并在完成后恢复系统安全设置。
|
||||
> 只在连接页面明确提示需要关闭 SIP 时才处理。首次连接失败时,先确认微信版本、账号目录和登录时机,再按本文操作。关闭 SIP 不是 TraceMemo 的常规安装步骤,也不应长期保持关闭。
|
||||
|
||||
## 准备
|
||||
|
||||
- 一台 Mac 电脑,Intel 芯片和 Apple Silicon 芯片均可。
|
||||
- 需要进入 macOS 恢复模式。
|
||||
- 请先保存正在编辑的文件,并预留一次重启时间。
|
||||
|
||||
## 关闭 SIP
|
||||
|
||||
### Intel Mac
|
||||
|
||||
1. 关机。
|
||||
2. 按下开机键后,立刻按住 `Command + R`。
|
||||
3. 保持按住,直到进入 macOS 恢复模式。
|
||||
|
||||
### Apple Silicon Mac(M1/M2/M3/M4/M5)
|
||||
|
||||
1. 关机。
|
||||
2. 长按开机键不放。
|
||||
3. 直到出现启动选项界面后松开。
|
||||
4. 选择"选项",进入 macOS 恢复模式。
|
||||
|
||||
### 在恢复模式中执行命令
|
||||
|
||||
1. 进入恢复模式后,点击顶部菜单栏的 **Utilities(实用工具)**。
|
||||
2. 选择 **Terminal(终端)**。
|
||||
3. 在终端中输入:
|
||||
|
||||
```bash
|
||||
csrutil disable
|
||||
```
|
||||
|
||||
4. 按回车执行。
|
||||
5. 看到关闭成功提示后,重启电脑。
|
||||
|
||||
## 确认是否生效
|
||||
|
||||
重启回到正常桌面后,打开"终端",执行:
|
||||
|
||||
```bash
|
||||
csrutil status
|
||||
```
|
||||
|
||||
看到 `System Integrity Protection status: disabled.` 才算关闭成功。
|
||||
|
||||
若仍显示 `enabled`,说明没有生效。常见原因是没在恢复模式里执行,或系统刚做过大版本更新——
|
||||
macOS 大版本更新会把 SIP 重置回开启状态,此前关过也会失效,需要重新按上面的步骤操作。
|
||||
|
||||
## 重新开启 SIP
|
||||
|
||||
拿到数据库密钥后,建议重新进入恢复模式,在终端中执行:
|
||||
|
||||
```bash
|
||||
csrutil enable
|
||||
```
|
||||
|
||||
然后重启电脑,恢复系统安全设置。
|
||||
@@ -8,11 +8,44 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信
|
||||
|
||||
1. 先启动 TraceMemo,阅读连接页面显示的当前前置条件。
|
||||
2. 确认微信数据目录指向当前账号。
|
||||
3. 只在页面明确要求时处理系统授权或 SIP;按页面提示完成密钥获取后,恢复你平时使用的安全设置。
|
||||
3. 只在页面明确要求时处理系统授权或 SIP;关闭 SIP 的具体步骤见[关闭 SIP 教程](../mac-disable-sip.md),按页面提示完成密钥获取后,恢复你平时使用的安全设置。
|
||||
4. 返回应用重新检测账号、数据库和图片资源状态。
|
||||
|
||||
不要直接复制网上针对其他微信版本的命令。系统授权失败时,记录 macOS 版本、微信版本和页面错误,再按[排障文档](../user-guide/troubleshooting.md#连接微信失败)处理。
|
||||
|
||||
## 提示「无法读取微信数据库」时
|
||||
|
||||
**这是故障恢复步骤,不是安装前置条件。** 能正常连接的用户不需要做任何权限设置。
|
||||
|
||||
如果你在连接页看到「最近验证结果:无法读取微信数据库」(错误码 `DATABASE_PERMISSION_DENIED`),并且已经确认微信数据目录**实际存在**(例如在终端里能列出 `db_storage/session/session.db`),那说明是 **TraceMemo 这个进程**读不到,而不是文件缺失。
|
||||
|
||||
微信数据放在另一个应用的沙盒容器里,macOS 会对这种跨应用访问单独做校验。先看「完全磁盘访问权限」里 TraceMemo 的状态,再按情况处理:
|
||||
|
||||
- **不在列表里,或开关是关的**:按下面的步骤授权。
|
||||
- **开关已经是开的,但仍然读不到**:这不是「没授权」,而是旧授权记录对不上当前版本的应用,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](../user-guide/macos27-permission-recovery.md)。
|
||||
|
||||
首次授权的步骤:
|
||||
|
||||
1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||
2. 找到 **TraceMemo**,打开开关
|
||||
3. **重新启动 TraceMemo**(该授权只在进程下次启动时生效)
|
||||
4. 回到连接页重试
|
||||
|
||||
### 为什么终端能读、TraceMemo 读不了
|
||||
|
||||
macOS 的隐私权限按**应用进程的身份**判定,而不是按文件系统的用户身份。同一个用户在终端里能读到文件内容,不代表 TraceMemo 进程也有权限 —— 两者走的是不同的授权判定。所以「终端能读」不能用来排除权限问题。
|
||||
|
||||
### 不要做的事
|
||||
|
||||
上面这条路径**只涉及给 TraceMemo 授权**。以下做法都不需要,而且有风险:
|
||||
|
||||
- 关闭 SIP
|
||||
- `chmod` / `chown` 整个微信目录
|
||||
- 用 `sudo` 启动 TraceMemo
|
||||
- 修改微信数据库文件权限
|
||||
|
||||
「无法读取微信数据库」与 SIP 不是同一个问题;改动微信数据目录的权限还可能影响微信自身的正常运行。
|
||||
|
||||
## SIP 风险
|
||||
|
||||
关闭 System Integrity Protection 会降低 macOS 对系统文件和进程的保护。它不是日常使用 TraceMemo 的功能开关,也不应长期保持关闭。只有在你理解风险、确认页面要求且完成必要操作时才处理;完成后按 Apple 官方方式重新启用。
|
||||
@@ -23,5 +56,39 @@ TraceMemo 需要读取微信本地数据。macOS 会根据系统版本、微信
|
||||
|
||||
## Intel 与 Apple Silicon
|
||||
|
||||
从 Releases 选择与 Mac 处理器匹配的构建。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
|
||||
TraceMemo 同时支持两种 Mac 架构:
|
||||
|
||||
- **Apple Silicon(M 系列、`arm64`)**
|
||||
- **Intel Mac(`x64`)**
|
||||
|
||||
从 Releases 下载与你 Mac 处理器匹配的构建:
|
||||
|
||||
- Apple Silicon:`tracememo-<版本号>-arm64.dmg`
|
||||
- Intel:`tracememo-<版本号>-x64.dmg`
|
||||
|
||||
两种架构都可以通过应用内的连接流程自动获取微信数据库密钥。首次连接时,TraceMemo 会按**当前运行的这个版本**进入对应流程,按连接页面提示操作即可。
|
||||
|
||||
### 提示「Intel Mac 自动获取」,但电脑是 Apple 芯片
|
||||
|
||||
如果在 M 系列 Mac 上看到「Intel Mac 自动获取」,或页面要求准备 Intel 连接环境,多数是**正在运行 Intel(x64)版 TraceMemo**。macOS 允许 Intel 版应用在 Apple 芯片上通过 Rosetta 运行,应用本身不会报错,但会如实把自己识别成 Intel 版本,于是走了 Intel 的密钥获取方式。
|
||||
|
||||
判断当前跑的是哪个版本:
|
||||
|
||||
- 打开「活动监视器」,选中 TraceMemo,看「种类」一列 —— 显示「Apple」是 arm64 版,显示「Intel」是 x64 版;
|
||||
- 或点连接页的「复制脱敏诊断摘要」,看「处理器架构」和「硬件架构」两行。
|
||||
|
||||
**启动方式不会改变架构。** Finder、Dock、桌面文件夹、`open` 命令打开的都是同一个 `.app`。但如果电脑上存在多个 TraceMemo 副本(例如「应用程序」里一个、下载文件夹里一个),不同入口可能打开不同副本,表现出来就像「有时是 Intel、有时不是」。列出所有副本及架构:
|
||||
|
||||
```bash
|
||||
mdfind "kMDItemCFBundleIdentifier == 'com.tracememo.app'" | while read -r p; do
|
||||
[ -f "$p/Contents/MacOS/TraceMemo" ] && printf '%s -> ' "$p" && file -b "$p/Contents/MacOS/TraceMemo"
|
||||
done
|
||||
```
|
||||
|
||||
输出里带 `arm64` 的是 Apple 芯片版,带 `x86_64` 的是 Intel 版。
|
||||
|
||||
解决办法是从 [Releases](https://github.com/Wxw-Gu/TraceMemo/releases) 下载文件名带 `arm64` 的包,替换现有应用后重启。已保存的数据库密钥和连接配置不需要重新设置。
|
||||
|
||||
这与[提示「无法读取微信数据库」](#提示无法读取微信数据库时)不是同一个问题:那边是系统授权失效,这里是装错了版本。两种情况的处理方式不同,都不需要关闭 SIP。
|
||||
|
||||
Apple Silicon 和 Intel 已适配微信 macOS `4.1.13`。不同架构、微信版本和系统授权状态可能导致连接结果不同;文档不对所有组合做兼容性保证。
|
||||
@@ -1,10 +1,13 @@
|
||||
---
|
||||
name: tracememo-reader
|
||||
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
||||
version: 1.4.1
|
||||
description: 本机微信聊天记录的读取入口(TraceMemo 本地 HTTP API,默认 http://127.0.0.1:6131/api/v1)。凡是「看微信内容」的请求都必须先走本 Skill:某个群或某人今天聊了什么、刚刚聊了啥、最近消息、谁说了什么、总结聊天、翻历史记录、撤回的消息、图片内容、语音转文字、查找联系人或群聊、群成员、生成群聊总结、定时日报、给好友或群发微信消息、查看发送记录、查看未读。本 Skill 已处理鉴权、撤回归档、图片媒体、语音转写与压缩编码解码,当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
||||
---
|
||||
|
||||
# TraceMemo Reader
|
||||
|
||||
> **加载到本文件,说明通道选对了。** 只要问题涉及「读本机微信聊天内容」——某个群或某人今天聊了什么、刚刚聊了啥、最近消息、撤回、图片、语音、联系人、日报——本 Skill 就是第一顺位。
|
||||
|
||||
你是一个通过本机 TraceMemo 读取微信历史的 Agent。先确认用户已经在 TraceMemo 中完成数据库连接,再按需调用 API;不要假设数据库已就绪,也不要声称读取了没有调用过的消息。
|
||||
|
||||
## 连接信息
|
||||
@@ -17,6 +20,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`,确认服务和数据库状态。
|
||||
@@ -27,21 +59,143 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
|
||||
## 端点速查
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| ---- | --------------------- | ------------------------------------------------- |
|
||||
| GET | `/health` | 健康和数据库状态 |
|
||||
| GET | `/current_time` | 本机时间与时区 |
|
||||
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
|
||||
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
|
||||
| GET | `/recent_chat` | 最近会话;可传 `limit` |
|
||||
| GET | `/chatlog` | 会话消息;必填 `talker`,可传 `time` 或时间戳范围 |
|
||||
| GET | `/media/{messageId}` | 获取图片消息的真实图片二进制资源 |
|
||||
| GET | `/group_snapshot` | 群成员快照;必填 `md5` |
|
||||
| GET | `/resolve` | 昵称、wxid、md5 解析;必填 `q` |
|
||||
| POST | `/report` | 将已有日报结构渲染为 HTML/PNG |
|
||||
| GET | `/agent/status` | Agent Hub、连接器和数据库状态 |
|
||||
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
|
||||
| POST | `/agent/send` | 已连接机器人发送测试 |
|
||||
| 方法 | 路径 | 用途 |
|
||||
| ------ | ------------------------------------------------------- | ------------------------------------------------- |
|
||||
| GET | `/health` | 健康和数据库状态 + 当前 Skill 版本 |
|
||||
| GET | `/skill/tracememo-reader` | 当前 SKILL.md 全文与版本号(自助更新用) |
|
||||
| GET | `/current_time` | 本机时间与时区 |
|
||||
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
|
||||
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
|
||||
| GET | `/recent_chat` | 最近会话;可传 `limit` |
|
||||
| GET | `/chatlog` | 会话消息;必填 `talker`,可传 `time` 或时间戳范围 |
|
||||
| GET | `/media/{mediaId}` | 按消息返回的 `media.url` 获取图片二进制资源 |
|
||||
| GET | `/group_snapshot` | 群成员快照;必填 `md5` |
|
||||
| GET | `/resolve` | 昵称、wxid、md5 解析;必填 `q` |
|
||||
| POST | `/query/messages` | 按目标与时间范围取消息(结构化,不调用 AI) |
|
||||
| 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` | 个人微信发送能力状态(文字 / 图片 / 语音) |
|
||||
| POST | `/wechat/send` | 用本机微信账号发消息给他人(文字/图片/语音) |
|
||||
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
|
||||
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
|
||||
| POST | `/scheduled-reports` | 创建定时日报任务 |
|
||||
| PATCH | `/scheduled-reports/:id` | 修改定时日报任务 |
|
||||
| DELETE | `/scheduled-reports/:id` | 删除定时日报任务(执行前必须获得用户确认) |
|
||||
| POST | `/scheduled-reports/:id/enable` | 启用定时日报任务 |
|
||||
| POST | `/scheduled-reports/:id/disable` | 暂停定时日报任务 |
|
||||
| POST | `/scheduled-reports/:id/run` | 立即执行一次并返回 execution |
|
||||
| GET | `/scheduled-reports/:id/executions` | 查询执行记录 |
|
||||
| POST | `/scheduled-reports/executions/:executionId/retry-send` | 复用已有 PNG 重试发送 |
|
||||
| POST | `/report` | 将已有日报结构渲染为 HTML/PNG |
|
||||
| GET | `/agent/status` | Agent Hub、连接器和数据库状态 |
|
||||
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
|
||||
| POST | `/agent/send` | 已连接机器人发送测试(文字或本地图片) |
|
||||
|
||||
这个 API **不只是只读的**:`/report` 会渲染并写文件,`/wechat/send` 会以用户本人的微信账号把消息真的发给别人,`/agent/send` 会通过机器人发出消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE`、`/wechat/send` 与 `/agent/send` 尤其需要用户明确确认。
|
||||
|
||||
## 发送微信消息
|
||||
|
||||
两个发送端点的**身份和通道完全不同**,不要混用:
|
||||
|
||||
| | `/wechat/send` | `/agent/send` |
|
||||
| -------- | ------------------------------ | -------------------------------- |
|
||||
| 发送身份 | 用户本机正在登录的微信账号 | 已扫码接入的 TraceMemo 机器人 |
|
||||
| 收件人 | 好友 / 群 / 文件传输助手 | 一般是自己,用于测试连接器连通性 |
|
||||
| 前置条件 | 本机微信已启动,发送能力 ready | Agent Hub 连接器 online |
|
||||
|
||||
用户说“发消息给某人 / 某个群 / 文件传输助手”时,**只能用 `/wechat/send`**。`/agent/send` 不是用来通知别人的。
|
||||
|
||||
### 调用前必须做
|
||||
|
||||
1. 调用 `GET /wechat-personal/send-capability`,只有 `capability.ready === true` 且 `capability.capabilities[type] === true` 才继续。否则停下来说明需要先在 TraceMemo「设置 → 发送能力」里完成绑定,**不要**直接调用再解释失败。
|
||||
2. 通过 `/resolve` 把用户说的昵称换成 wxid;`to` 只接受 wxid、`xxx@chatroom` 群 id,或 `filehelper`。**不要猜 wxid,也不要把昵称直接写进 `to`。**
|
||||
3. 把「发给谁 + 发什么」复述给用户并得到确认后再发。这是不可撤回的外部操作。
|
||||
|
||||
### 请求
|
||||
|
||||
```json
|
||||
{ "to": "wxid_xxx", "type": "text", "text": "消息内容", "idempotencyKey": "可选" }
|
||||
```
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
| ---------------- | ------------------ | ------------------------------------------------------------------- |
|
||||
| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 |
|
||||
| `type` | 否 | `text`(默认)/ `image` / `voice` / `file` |
|
||||
| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 |
|
||||
| `filePath` | `type=image/voice/file` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
|
||||
| `fileName` | 否 | 仅 `type=file`:macOS 透传名称;Windows 当前可能忽略,按路径 basename 发送 |
|
||||
| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 |
|
||||
|
||||
几个必须遵守的限制:
|
||||
|
||||
- **超过 2000 字符不要硬发**。先告诉用户内容过长,征得同意后再拆成多条依次发送;不要静默截断。
|
||||
- **媒体只收本地文件**。用户给的是聊天里的图片时,先用 `/chatlog` 拿到 `media.url` 下载成临时文件,再把该路径传给 `filePath`;网络图片同样需要先落盘。不要试图传 URL。
|
||||
- **本端点没有节流**。automation 的 3 秒间隔对它不生效,连续调用就会连续投递。单个任务里连续发送超过 3 条前,先和用户确认节奏。
|
||||
|
||||
### 结果
|
||||
|
||||
成功返回 `success: true`、`status: "sent"`、`actionId`。失败时读 `errorCode`:
|
||||
|
||||
- `400 INVALID_REQUEST` / `INVALID_RECIPIENT`:字段不合法,按 `error` 里的说明修正;
|
||||
- `403 POLICY_BLOCKED`:被发送策略拒绝,如实告知用户;
|
||||
- `502 SEND_FAILED`:已进入投递但微信侧失败,不要说成“已发送”;
|
||||
- `503 SEND_CAPABILITY_UNAVAILABLE` / `SEND_NOT_READY`:能力未就绪,引导用户去绑定;
|
||||
- `503 UNSUPPORTED_PLATFORM`:当前系统不支持。
|
||||
|
||||
只有 `status === "sent"` 才能告诉用户发送成功。不要凭 `actionId` 或 HTTP 200 之外的任何信息推断结果。
|
||||
|
||||
### 发送成功后不要用 `/chatlog` 自证
|
||||
|
||||
`status: "sent"` 只表示消息已经交给微信完成投递,**不代表它会出现在本地聊天数据库里**。TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不写入。
|
||||
|
||||
因此:
|
||||
|
||||
- **不要**用 `/chatlog` 查自己刚发出的那条消息来确认发送成功。查不到是正常现象,不等于发送失败。
|
||||
- **不要**因为本地库没有这条消息就重发 —— 那会产生真实的重复消息。
|
||||
- 需要人工确认时,请用户用**手机微信**或**另一个微信号**查看该会话;这是唯一可靠的确认方式。
|
||||
- Send Log 与 `actions/wechat-actions.json` 记录的是 TraceMemo 自己的发送动作与结果,能证明“调用过并成功投递”,**不能**证明对方收到或本地库已落库。不要把它们混为一谈。
|
||||
|
||||
## 定时日报管理
|
||||
|
||||
定时日报由 TraceMemo 自己持久化和调度。Agent 只负责理解自然语言、解析群聊和时间,再调用上述 API;不要创建 cron、维护任务文件、计算下一次执行时间或自行发送微信。
|
||||
|
||||
### 创建任务
|
||||
|
||||
用户提出“每天早上 9 点给技术交流群发昨天的日报”时,按以下顺序执行:
|
||||
|
||||
1. 调用 `/health`,确认 TraceMemo 和数据库可用。
|
||||
2. 调用 `/wechat-personal/send-capability`,只有 `capability.status === "ready"` 且 `capability.capabilities.image === true` 才允许继续。
|
||||
3. 用户使用“今天”“昨天”等相对日期时调用 `/current_time`;日报任务的 `schedule.time` 使用 TraceMemo 本机时区的 `HH:mm`,不要转成 UTC。
|
||||
4. 调用 `/chatroom` 或 `/contact?type=group` 查找群聊。名称匹配多个结果时,必须把候选项展示给用户并要求选择;不能猜测。
|
||||
5. 使用唯一群聊的 `talker` 创建:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "技术交流群 · 每日日报",
|
||||
"group": { "talker": "xxx@chatroom", "name": "技术交流群" },
|
||||
"schedule": { "type": "daily", "time": "09:00" },
|
||||
"reportRange": "yesterday",
|
||||
"target": { "type": "wechat_group", "talker": "xxx@chatroom" },
|
||||
"enabled": true
|
||||
}
|
||||
```
|
||||
|
||||
如果 API 返回 `409` 且 `error === "duplicate"`,告诉用户相同任务已经存在,不要再次创建。能力状态不是 `ready` 时(`unsupported`、`unconfigured`、`needs_binding`、`initializing` 或 `error`),直接说明需要先在 TraceMemo 的“设置 → 发送能力”里完成个人微信绑定和能力检测,不要继续创建任务。
|
||||
|
||||
### 查看、修改和执行
|
||||
|
||||
- “我现在有哪些定时日报”调用 `GET /scheduled-reports`,使用返回的 `tasks` 展示任务名称、群聊、每天的时间、范围、目标和启停状态。
|
||||
- 修改前先查询列表并确认唯一任务,再调用 `PATCH /scheduled-reports/:id`。只提交需要修改的字段,例如 `{"schedule":{"type":"daily","time":"10:00"}}`。
|
||||
- 暂停调用 `/scheduled-reports/:id/disable`,恢复调用 `/scheduled-reports/:id/enable`。
|
||||
- “现在执行一次”调用 `/scheduled-reports/:id/run`,不要改用 `/agent/group-report` 后自行发送微信;该接口和定时执行共用同一条链路。
|
||||
- 查询执行结果调用 `/scheduled-reports/:id/executions`,根据 `status`、`startedAt`、`finishedAt`、`message` 和 `error` 向用户解释结果。
|
||||
|
||||
### 删除确认
|
||||
|
||||
删除是不可逆操作。收到删除请求后,先用任务列表找到唯一任务,向用户展示任务名称、时间、日报范围和发送目标并明确询问确认;只有用户明确确认后,才调用 `DELETE /scheduled-reports/:id`。
|
||||
|
||||
## 时间与上下文规则
|
||||
|
||||
@@ -53,12 +207,27 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
- 根据多条消息整理出的总结;
|
||||
- 没有来源支持的推断。
|
||||
|
||||
## 结构化查询(query/\*)
|
||||
|
||||
需要按目标 + 时间范围稳定取数时,优先使用 `query/*`,而不是自己拼 `chatlog`:
|
||||
|
||||
- `query/messages`:按 `target`、`timeRange`、`direction`、`messageTypes` 取消息;
|
||||
- `query/search`:受限语义关键词检索,依赖本地索引;
|
||||
- `query/message-context`:用返回的 `messageRef` 取前后文;
|
||||
- `query/conversation-overview`:按会话与时间范围提取可总结的证据。
|
||||
- `query/voice-transcribe`:把指定语音消息的 `messageRef` 转成文字。
|
||||
|
||||
两个要点:
|
||||
|
||||
- `messageRef` 是服务端生成的不透明引用,**不要**自行构造 wxid、md5 或数据库路径;
|
||||
- `query/search` 依赖异步建立的本地索引。`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说“这段范围暂时无法确认”,**不能**下“没有找到”的结论。
|
||||
|
||||
## 媒体消息
|
||||
|
||||
当 `/chatlog` 返回图片消息时:
|
||||
|
||||
1. 如果用户只是询问图片消息是否存在,不需要获取图片。
|
||||
2. 如果用户要求查看、识别、理解或分析图片,使用该消息 `media.url`(`/media/{messageId}`)获取真实图片。
|
||||
2. 如果用户要求查看、识别、理解或分析图片,原样使用该消息 `media.url` 获取真实图片;不要用消息 `id` 自行拼接。媒体标识按数据库连接隔离,重启、重连或切换账号后须重新读取 `/chatlog` 获取地址。
|
||||
3. 不要根据 `[图片]`、消息文本或文件名猜测图片内容。
|
||||
4. 获取成功后,将图片交给当前 Agent 的视觉能力。
|
||||
5. 如果图片获取失败,明确说明无法读取图片。
|
||||
@@ -71,11 +240,23 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
|
||||
1. 调用 `/health`;必要时调用 `/current_time`。
|
||||
2. 调用 `/resolve`,再调用 `/chatlog` 找到 `type` 为图片的消息。
|
||||
3. 调用 `/media/{messageId}`,将返回的图片交给 Vision。
|
||||
3. 请求该消息的 `media.url`,将返回的图片交给 Vision。
|
||||
4. 必要时读取图片消息前后若干条消息,结合聊天上下文回答。
|
||||
|
||||
不要只根据 `[图片]` 猜测内容,不要把一次 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 的数据策略。
|
||||
@@ -83,8 +264,8 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
## 常见错误
|
||||
|
||||
- `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。
|
||||
- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。
|
||||
- `404`:先用 `/resolve` 确认会话标识。
|
||||
- `422`:`messageId` 无效,或消息不是可读取的图片。
|
||||
- `503`:用户还没有完成数据库连接或对应服务未就绪。
|
||||
- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。注意 `/wechat/send` 的 `403 POLICY_BLOCKED` 是被发送策略拒绝,含义不同。
|
||||
- `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。
|
||||
- `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。
|
||||
- `503`:用户还没有完成数据库连接或对应服务未就绪。发送端点返回 `503` 时先查 `/wechat-personal/send-capability`,不要反复重试。
|
||||
- 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2026 yincongcyincong
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,28 +0,0 @@
|
||||
# wechat_chatter / OneBot 第三方组件说明
|
||||
|
||||
TraceMemo 的 macOS 个人微信发送功能会按需使用以下第三方组件:
|
||||
|
||||
- 项目:`yincongcyincong/wechat_chatter`
|
||||
- 上游仓库:https://github.com/yincongcyincong/wechat_chatter
|
||||
- 当前运行时版本:`v0.0.18`
|
||||
- 运行时文件:`onebot_mac_arm64.tar.gz`
|
||||
- 许可证:GNU General Public License version 3(GPL-3.0)
|
||||
- 上游版权:Copyright (C) 2026 yincongcyincong
|
||||
- TraceMemo 修改日期:2026-08-17
|
||||
|
||||
## 集成方式
|
||||
|
||||
OneBot 运行时不会随 TraceMemo 安装包一起分发。用户启用该实验性功能时,TraceMemo 会从上述上游项目的 GitHub Release 按需下载运行时,并将其安装到应用的用户数据目录。
|
||||
|
||||
运行时作为独立进程启动,TraceMemo 通过本机 HTTP 接口与其通信。
|
||||
|
||||
## 本地修改
|
||||
|
||||
为适配连续发送、图片上传 Hook 状态检测以及微信核心模块基址定位,TraceMemo 会在用户设备上对上游 `onebot/script.js` 应用兼容性补丁。补丁逻辑位于:
|
||||
|
||||
- `scripts/prepare-wechat-chatter-runtime.cjs`
|
||||
- `src/main/services/personal-wechat-runtime-manager.ts`
|
||||
|
||||
补丁中源自或修改自上游 `script.js` 的部分,以及补丁应用后产生的修改版 `script.js`,继续按照 GPL-3.0 提供。本说明只针对该第三方组件及相关修改,不用于声明 TraceMemo 仓库其他部分的许可证。
|
||||
|
||||
GPL-3.0 的完整文本见本目录下的 `LICENSE`。
|
||||
@@ -41,6 +41,19 @@
|
||||
|
||||
你可以点击来源回到档案中的原始消息。产品内部将这些信息称为 Evidence、Citation 和 Search Trace,用户可以把它们理解为“依据、来源标记和查找过程”。详见[如何核对 AI 的回答来源](../concepts/answer-sources.md)。
|
||||
|
||||
## 查找过程和跳回原消息
|
||||
|
||||
查找过程中,界面依次显示真实阶段:**理解问题 → 查找相关聊天 → 整理证据 → 生成回答**。跨会话、大范围检索更慢时,副提示会写明“正在搜索较大范围的聊天记录…”。阶段只在真正进入下一步时前进,不使用定时器或百分比伪造进度。
|
||||
|
||||
查找结束后,界面给出耗时拆解:**总耗时**,以及其中分别花在 **AI 生成** 和 **本地查询** 上的时间。这样你能判断慢在哪——是模型在写答案,还是本机还在翻聊天记录。
|
||||
|
||||
点击来源卡片的 **“跳转到原聊天”** 会真的打开对应会话并定位到那条消息:
|
||||
|
||||
- 群聊来源打开的是那个群,而不是群里某个联系人;
|
||||
- 会加载该消息前后的上下文,并滚动到它、短暂高亮;
|
||||
- 只加载目标消息附近的一段,不会把整个会话历史全部读出来;
|
||||
- 如果这条消息已经不在本地(例如已被删除),界面会明确说明“已打开对应会话,但暂时无法定位原消息”,不会假装跳转成功。
|
||||
|
||||
## 什么时候不要直接相信答案
|
||||
|
||||
- 来源很少,或时间范围与问题不一致;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## 选择要看的会话
|
||||
|
||||
左侧会话列表可以浏览联系人、群聊、折叠群聊和公众号等已读取到的会话。选中会话后,右侧显示消息时间线;滚动到较早位置可以继续加载历史。
|
||||
左侧会话列表可以浏览已读取到的联系人、群聊和公众号。选中会话后,右侧显示消息时间线;滚动到较早位置可以继续加载历史。
|
||||
|
||||
如果你从 AI 回答的来源进入档案,应用会自动切换到对应会话并尽量定位到消息时间。
|
||||
|
||||
@@ -19,6 +19,22 @@
|
||||
|
||||
关键词搜索速度快、结果直观,但它不会理解“意思相近但没有相同词”的问题。
|
||||
|
||||
## 怎么找到联系人
|
||||
|
||||
档案搜索会综合多个身份字段匹配联系人或群聊,包括:
|
||||
|
||||
- 通讯录备注(remark);
|
||||
- 微信昵称;
|
||||
- 当前微信号;
|
||||
- wxid;
|
||||
- 拼音全拼和拼音首字母。
|
||||
|
||||
因此可以直接输入备注、昵称、微信号或拼音查找。搜索联系人和搜索消息是两步:先确认目标会话,再在会话内查关键词;记得大意但不知道原话时,改用[AI Search](./ai-search.md)。
|
||||
|
||||
## 文字转语音
|
||||
|
||||
在档案中选择当前联系人或群聊,输入文字后生成语音,试听确认后发送。这个入口只处理明确的文字转语音动作,不是任意文本、图片或本地语音文件发送器。
|
||||
|
||||
## 消息和媒体
|
||||
|
||||
根据微信数据中实际可用的资源,档案可以展示文本、图片、视频、语音、文件、链接、引用、小程序、表情和系统消息等类型。媒体是否能显示,取决于本机原始资源是否仍然存在、权限是否完整以及当前微信版本的存储方式。
|
||||
@@ -27,11 +43,7 @@
|
||||
|
||||
如果文字正常但图片无法打开,进入“设置 → 图片解密”查看当前状态。可以尝试自动获取,也可以在已经知道正确密钥时手动配置;原文件已经被微信清理时,仅配置密钥也无法恢复图片。
|
||||
|
||||
## 可选保留撤回消息
|
||||
|
||||
“设置 → 防撤回”提供一个默认关闭的可选功能。开启后,应用会尽量保留之后捕获到的撤回消息,并在气泡旁标记“消息已撤回”。它不能找回开启前已经消失或应用未捕获到的内容,也可能增加加载开销。
|
||||
|
||||
该功能与普通只读浏览的数据边界不同。开启前请阅读[防撤回](./recall-protection.md)。
|
||||
联系人和群聊列表会尽量显示头像、备注和昵称。头像或资料缺失时不影响消息读取;这通常表示本机没有对应资源,或微信没有返回完整资料。
|
||||
|
||||
## 保护自己不被误导
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@ ZIP 是 HTML 资源包的压缩选项,不是第五种内容格式。
|
||||
5. 设置文件名并开始导出。
|
||||
6. 在导出任务中心查看读取、解析、媒体处理、转写、写入和压缩进度;完成后打开文件位置。
|
||||
|
||||
## 导出设置会被记住
|
||||
|
||||
TraceMemo 会记住上一次使用的导出设置,下次打开导出页面时自动恢复,减少重复选择。包括格式、时间范围、消息类型、名称显示方式、媒体选项(原图/缩略图、头像)、语音转写、缺失资源处理、ZIP、文件名和输出目录。
|
||||
|
||||
这些偏好保存在本机,不会随账号同步到其他设备。
|
||||
|
||||
## 多会话和增量导出
|
||||
|
||||
HTML 支持把最多五个会话合并到一个档案中;选择多个会话后,其他格式会不可用。再次使用相同名称导出 HTML 时,可以把新消息增量合并到已有档案;这不会删除之前已导出的消息。
|
||||
|
||||
@@ -8,15 +8,32 @@
|
||||
|
||||
## 1. 开始前准备
|
||||
|
||||
| 系统 | 已测试的微信客户端 | 需要注意 |
|
||||
| ------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|
||||
| macOS | [微信 macOS `4.1.8.100`](https://github.com/zsbai/wechat-versions/releases/tag/4.1.8.100) | 自动获取数据库密钥前,需要按连接页面提示完成授权;页面明确要求时还需要处理 SIP |
|
||||
| Windows | [微信 Windows `4.1.9.57`](https://github.com/iibob/wechat-win-archive/releases#release-v4.1.9.57) | 首次使用时请确认微信数据目录;Windows 不需要关闭 SIP |
|
||||
TraceMemo 需要读取微信本地数据库。首次使用前,请确认已安装受支持的微信客户端,并按照连接页面完成数据库密钥获取。
|
||||
|
||||
- 上表是当前实际测试过的客户端版本,不代表只有这些版本可以使用。其他微信 4.x 版本可能可以连接,但尚未逐一验证。
|
||||
| 系统 | 微信客户端 | 首次连接说明 |
|
||||
| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| macOS | **微信 4.1.13 系列**(推荐 [4.1.13.8](https://github.com/zsbai/wechat-versions/releases/tag/4.1.13.8))<br>备选 [4.1.8.100](https://github.com/zsbai/wechat-versions/releases/tag/4.1.8.100) | 支持 Apple Silicon(M 系列)和 Intel Mac 自动获取数据库密钥。首次连接时,请按照 TraceMemo 页面提示完成系统授权及微信登录操作。 |
|
||||
| Windows | **微信 4.x**(推荐 [4.1.9.57](https://github.com/iibob/wechat-win-archive/releases/tag/v4.1.9.57)) | 支持自动获取数据库密钥。首次使用时请确认微信数据目录正确,无需处理 macOS 的 SIP 设置。 |
|
||||
|
||||
### macOS 用户
|
||||
|
||||
TraceMemo 已支持两种 Mac 架构:
|
||||
|
||||
- **Apple Silicon(M1 / M2 / M3 / M4 等)**
|
||||
- **Intel Mac(x64)**
|
||||
|
||||
两种架构均支持自动获取微信数据库密钥,TraceMemo 会根据当前 Mac 自动选择对应的连接方式。
|
||||
|
||||
Apple Silicon 和 Intel 均已适配微信 macOS `4.1.13` 系列。首次获取密钥时,请让微信停留在登录页面,并按照 TraceMemo 中显示的步骤操作。
|
||||
|
||||
> 不同 Mac 架构的连接流程可能略有区别,请始终以应用内「第一次使用」页面显示的提示为准。
|
||||
|
||||
### 关于微信版本
|
||||
|
||||
- 上表中的版本是当前 TraceMemo 已适配或推荐使用的版本,并不代表只有这些版本可以运行。
|
||||
- TraceMemo 必须取得当前微信账号对应的数据库密钥,才能读取聊天记录。
|
||||
- 你需要有权访问要读取的微信账号和聊天数据。
|
||||
- 如果要使用 AI 问答、群聊日报或图片理解,还需要在应用中配置一个 AI 服务。
|
||||
- 如果要使用 AI 问答、群聊日报或图片理解,还需要在应用中配置一个 AI 服务。「图片文字索引」不在此列——它在本机识别图片里的文字,不需要配置 AI。
|
||||
|
||||
当前代码按微信 4.x 数据结构处理。不同微信客户端版本、系统权限和数据迁移状态可能影响自动连接;遇到问题时请查看[常见问题与排查](./troubleshooting.md)。
|
||||
|
||||
@@ -26,14 +43,16 @@
|
||||
|
||||
### Windows
|
||||
|
||||
1. 从 Releases 下载 Windows x64 的 `TraceMemo-<版本号>-setup.exe` 安装包。
|
||||
1. 从 Releases 下载 Windows x64 的 `tracememo-<版本号>-setup.exe` 安装包。
|
||||
2. 双击安装包,按向导完成安装。
|
||||
3. 启动 TraceMemo。
|
||||
4. 如果安装完成后软件无法启动,请安装 Microsoft Visual C++ x64 运行库:[vc_redist.x64.exe](https://aka.ms/vc14/vc_redist.x64.exe),安装完成后重新启动 TraceMemo。
|
||||
|
||||
### macOS
|
||||
|
||||
1. 下载 Apple Silicon(M 系列、`arm64`)版本的 `.dmg`。当前版本不支持 Intel 芯片的 Mac。
|
||||
1. 从 Releases 下载与你 Mac 处理器架构匹配的 `.dmg`:
|
||||
- Apple Silicon(M 系列、`arm64`):`tracememo-<版本号>-arm64.dmg`
|
||||
- Intel(`x64`):`tracememo-<版本号>-x64.dmg`
|
||||
2. 打开 DMG,将 TraceMemo 拖入“应用程序”文件夹。
|
||||
3. 如果系统提示“无法打开,因为开发者无法验证”,前往“系统设置 → 隐私与安全性”,点击“仍要打开”。
|
||||
4. 如果系统提示应用已损坏,可在终端执行:
|
||||
@@ -42,7 +61,16 @@
|
||||
xattr -cr "/Applications/TraceMemo.app"
|
||||
```
|
||||
|
||||
5. 启动 TraceMemo。首次自动获取数据库密钥时,按连接页面显示的授权要求操作;只有页面明确提示时才按[关闭 SIP 教程](../mac-disable-sip.md)处理。关闭 SIP 会降低系统安全性,完成密钥配置后应重新开启。
|
||||
5. 先让微信停在**未登录窗口**(如果微信已经登录,请退出当前账号,**只关闭窗口不算**),再启动 TraceMemo。
|
||||
- 连接时会按提示自动获取数据库密钥;应用会根据当前架构进入对应流程,按连接页面显示的授权要求操作即可。
|
||||
- **等第五步 明确提示可以登录后,再回到微信点击登录。** 在此之前不要先点登录,否则这次密钥获取会失败,需要重新开始。
|
||||
- 只有页面明确提示时才按[关闭 SIP 教程](../mac-disable-sip.md)处理。关闭 SIP 会降低系统安全性,完成密钥配置后应重新开启。
|
||||
|
||||
> **注意事项:取密钥时提示监听超时(`CAPTURE_TIMEOUT`,或相关失败)**
|
||||
>
|
||||
> 这说明「先让微信停在未登录窗口」这一步操作有误——常见原因是微信当时已经登录,或者还没等连接页面提示就先点了登录
|
||||
>
|
||||
> 请先退出微信账号、回到**未登录窗口**,然后按上面的第 5 步**重新来一遍**(等连接页面明确提示可以登录后,再回到微信点击登录)。
|
||||
|
||||
更完整的权限和安全边界见 [macOS 数据访问说明](../platform/macos.md)。
|
||||
|
||||
@@ -106,7 +134,7 @@
|
||||
- [生成群聊日报或总结](./report.md)
|
||||
- [转写微信语音](./voice.md)
|
||||
- [导出聊天档案](./export.md)
|
||||
- [可选开启防撤回](./recall-protection.md)
|
||||
- [让日报、退群通知按规则自动运行](../README.md#日报与自动化)
|
||||
- [在微信里向 TraceMemo 提问](../agent/agent-hub.md)
|
||||
- [让外部 Agent 查询微信历史](../agent/overview.md)
|
||||
|
||||
@@ -132,17 +160,19 @@ Agent Hub 是普通用户可以直接使用的入口,不需要安装 Reader Sk
|
||||
|
||||
## 8. 需要配置 AI 吗?
|
||||
|
||||
不一定。浏览聊天、普通关键词搜索、建立本地知识库和导出不要求在线 AI 服务。
|
||||
不一定。浏览聊天、普通关键词搜索、建立本地知识库、图片文字识别、离线语音转写和导出都不要求在线 AI 服务。
|
||||
|
||||
使用“问问微信”、群聊日报或图片理解时,需要在“设置 → AI 模型”中添加并测试 AI 服务。你主动开始并确认远程 AI 功能后,完成任务所需的内容才可能发送给该服务;计费、留存和地区规则由对应服务商决定。
|
||||
|
||||
这两种情况容易混淆:**本机识别图片里的文字**(图片文字索引)不联网、不需要 AI 服务;**让模型看图并回答**(图片理解)才需要配置 AI 服务。
|
||||
|
||||
## 9. 数据和隐私的最低须知
|
||||
|
||||
- 微信数据库、聊天解析和本地索引默认留在本机。
|
||||
- 微信数据库、聊天解析、本地索引和图片文字识别默认留在本机。
|
||||
- 离线语音转写使用本地模型;它与在线 AI 请求是两条不同的数据路径。
|
||||
- 图片文字索引只在本机识别,原始图片不会因为本地识别而上传;识别出的文字会进入本地索引,供搜索和“问问微信”使用。
|
||||
- 你主动开始并确认 AI 问答或日报后,完成任务所需的受控上下文才可能发送给你选择的 AI 服务;打开应用不会自动上传全部聊天。
|
||||
- 应用内 Local HTTP API 默认只监听 `127.0.0.1:6131`,受保护接口需要 Token。
|
||||
- 防撤回默认关闭;首次开启会为微信消息数据库增加本地撤回日志/监听结构,详细边界见[防撤回](./recall-protection.md)。
|
||||
|
||||
完整边界见[数据、隐私与安全](./privacy.md)。
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Intel Mac 首次获取密钥
|
||||
|
||||
请先备份微信本地数据。密钥获取和数据库验证都在本机完成,不要把密钥、日志或数据库发给他人。
|
||||
|
||||
## 开始使用
|
||||
|
||||
1. 启动 TraceMemo,在首次连接页面点击“重新检查环境”。
|
||||
2. 如果页面显示需要准备连接环境,点击“准备环境”,按页面提示完成。
|
||||
3. 打开微信,让微信停在未登录页面,不要先点击登录。
|
||||
4. 回到 TraceMemo,选择微信账号,点击“开始获取密钥”。
|
||||
5. 等待页面提示可以登录后,立即回到微信点击登录。
|
||||
6. 等待 TraceMemo 显示“获取成功,验证数据库连接”。
|
||||
|
||||
获取成功后,请保存密钥。如果页面提示需要重新准备,按页面的“查看说明”操作,不要连续重试。
|
||||
|
||||
## 注意
|
||||
|
||||
- 密钥只保存在本机的安全存储中。
|
||||
- 请不要删除微信本地数据目录。
|
||||
@@ -13,7 +13,45 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
|
||||
- **建立本地知识库**:第一次读取当前账号的可检索聊天;
|
||||
- **同步最新记录**:已有索引时,只补充新增或变化的内容。
|
||||
|
||||
同步会在后台运行,完成后页面显示已索引消息、知识片段和磁盘占用。同步期间暂不能开始新的 AI 分析;同步异常时,旧索引仍可能可以继续使用。
|
||||
同步在后台运行,**期间仍然可以正常提问和分析**,不会被禁用。索引还没追完时,答案会基于当前已经可用的部分给出,并在界面标注覆盖范围。
|
||||
|
||||
知识库卡片同时显示两组互相独立的信息:
|
||||
|
||||
- **规模**:已索引消息、知识片段、磁盘占用——说明索引有多大;
|
||||
- **状态与本轮进度**:说明索引现在处于什么状态、这一轮同步在做什么(扫了多少、真正新增了多少、处理到第几个会话)。
|
||||
|
||||
`最新索引` 只表示索引已经覆盖到聊天记录的哪个时间点,**不等于**整库已经建完;进度里的计数是**本轮**的数字,不是全部历史的总数。
|
||||
|
||||
### 状态怎么读
|
||||
|
||||
| 状态 | 含义 |
|
||||
| ------------------- | ------------------------------------------------ |
|
||||
| 可用 · 已追至最新 | 索引已覆盖到聊天记录的最新位置,可以直接用 |
|
||||
| 可用 · 正在追新 | 索引可用,正在后台补充最近新增的消息 |
|
||||
| 可用 · 正在补齐历史 | 索引可用,正在后台补齐较早的历史内容 |
|
||||
| 可用 · 同步已取消 | 索引仍然可用;上一轮同步被取消,已建立的部分保留 |
|
||||
| 可用 · 更新失败 | 索引仍然可用;上一轮同步出错,可以稍后重试 |
|
||||
|
||||
只有确实追平、且没有待补齐内容时才会出现“已追至最新”。索引不可查询时不会显示“可用”。
|
||||
|
||||
### 取消和继续
|
||||
|
||||
同步过程中可以点击 **取消同步**(点击后显示“正在取消…”)。取消只结束当前这一轮,不会删除已经建立的索引,也不会回滚已完成的部分;下次同步会从上次停下的位置继续,不需要从头重扫。中断过的索引仍然可以正常搜索。
|
||||
|
||||
## 图片文字索引(另一份索引)
|
||||
|
||||
本地索引其实有两份,彼此独立:
|
||||
|
||||
- **聊天记录索引**(也就是上面说的 Knowledge):索引文字消息,用于跨会话、跨时间查找;
|
||||
- **图片文字索引**:在本机识别微信图片里的文字(截图、公告、报价图等),把识别结果也变成可搜索的文字。
|
||||
|
||||
“独立”的意思是:聊天记录索引建好了,并不代表图片里的文字就搜得到。建立图片文字索引后,可以在“问问微信”里直接搜截图或公告图里写过的词。
|
||||
|
||||
图片文字索引只在本机识别,原始图片不会因为本地识别而上传。它**不等于“图片理解”**:识别文字不联网、不需要 AI 服务;而让模型看图并回答属于图片理解,需要配置 AI 服务,走的是另一条路径。
|
||||
|
||||
识别失败的图片可以单独重试,也有“只重建搜索索引、不重新识别图片”的修复入口——修索引不需要重跑几万张图。
|
||||
|
||||
两个索引都可以在“设置 → 本地索引”里集中查看状态、建立、同步和清理。
|
||||
|
||||
## 账号隔离
|
||||
|
||||
@@ -35,4 +73,3 @@ Knowledge 不会在第一次连接后自动悄悄建立。进入“问问微信
|
||||
## 产品术语(可选)
|
||||
|
||||
源码和日志中可能出现 SQLite、FTS、Chunk、索引等词。它们描述的是本地存储和检索实现,不是你开始使用 TraceMemo 的前置知识。
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
# macOS 更新后读不到微信数据:权限恢复
|
||||
|
||||
本文只处理一种情况:**TraceMemo 之前能连上微信数据库,升级 macOS 或更新 TraceMemo 之后读不到了**。
|
||||
|
||||
正常使用、没有出现权限提示的用户,不需要做任何操作。
|
||||
|
||||
---
|
||||
|
||||
## 1. 适用版本与典型表现
|
||||
|
||||
### 适用系统
|
||||
|
||||
- macOS 27 及更高版本(本文的主要场景)
|
||||
- 从 macOS 26 或更早版本升级到 macOS 27 之后首次启动 TraceMemo
|
||||
- TraceMemo 2.5.2 及更高版本(更早的版本升到新版时同样可能出现),且此前已经成功连接过一次微信数据库
|
||||
|
||||
如果你从来没有成功连接过,卡在「自动获取密钥」这一步,那不是本文的场景,请看[第一次使用](./getting-started.md)里的密钥获取流程。
|
||||
|
||||
### 典型表现
|
||||
|
||||
出现下面任意一条,且**微信数据目录确实存在**,再按本文处理:
|
||||
|
||||
- 连接页提示「无法读取微信数据库」,错误码 `DATABASE_PERMISSION_DENIED`
|
||||
- 提示「无法打开数据库」,但微信能正常登录、聊天记录能正常查看(权限不足有时会被包装成「打不开」)
|
||||
- 昨天还能用,更新应用后重启就连接失败,期间没有换账号、没有迁移数据目录
|
||||
- 「系统设置 → 隐私与安全性 → 完全磁盘访问权限」里,TraceMemo 的开关是**打开**的,但应用仍然读不到
|
||||
|
||||
如果提示的是「**密钥与当前账号不匹配**」,那不属于本文范围 —— 那是密钥和账号对不上,按[常见问题与排查](./troubleshooting.md#连接微信失败)里的密钥流程处理。
|
||||
|
||||
判断数据目录是否真的存在,可以在终端执行(把路径里的账号目录换成你自己的):
|
||||
|
||||
```bash
|
||||
ls ~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files
|
||||
```
|
||||
|
||||
能列出账号目录,说明数据是完整的,问题出在**权限**,不在文件。
|
||||
|
||||
> 终端能读到、TraceMemo 读不到,是完全正常的情况。macOS 的隐私权限按「应用」判定,不按「用户」判定,两者走的是两套不同的检查。所以「终端能读」不能用来排除权限问题。
|
||||
|
||||
---
|
||||
|
||||
## 2. 为什么更新应用之后会失去访问权限
|
||||
|
||||
一句话:**macOS 认的是应用文件的「指纹」,不是应用的名字。**
|
||||
|
||||
TraceMemo 目前发布的 macOS 版本没有使用 Apple 开发者证书签名,用的是 ad-hoc 签名(相当于临时签名,没有可核验的开发者身份)。这种签名没有稳定的身份标识,系统只能靠应用二进制的指纹来记住「这是哪个应用、你给它授过什么权」。
|
||||
|
||||
每次发布新版本,二进制内容通常会变,指纹随之改变。系统看到的是一个指纹不同的新应用,之前那条授权记录对不上号,于是按「未授权」处理 —— 微信数据在另一个应用的沙盒容器里,读取被拒绝,连接页就报「无法读取微信数据库」。
|
||||
|
||||
几个容易误解的点:
|
||||
|
||||
- **不是数据库损坏**。数据一直好好的,微信自己也能正常读写。
|
||||
- **不是密钥失效**。密钥还在本地,验证也没问题,卡住的是「打开文件」这一步。
|
||||
- **不是 macOS 27 单独引入的缺陷**。指纹变化导致授权失效,在更早的 macOS 上也会发生;macOS 27 上反馈更集中,但没有做过版本对照验证。
|
||||
- **重装应用通常无效**。重装会生成同样的新指纹,旧授权依旧对不上。
|
||||
|
||||
---
|
||||
|
||||
## 3. 一次性终端修复
|
||||
|
||||
先**完全退出** TraceMemo,不是关窗口,是退出进程:
|
||||
|
||||
- 菜单栏 `TraceMemo → 退出 TraceMemo`,或按 `Command + Q`
|
||||
- 托盘/菜单栏图标里如果有「退出」,也点一次
|
||||
- 确认没有残留:打开「活动监视器」,搜索 `TraceMemo`,有残留就选中并点「退出」
|
||||
|
||||
然后打开「终端」(`应用程序 → 实用工具 → 终端`),执行:
|
||||
|
||||
```bash
|
||||
tccutil reset SystemPolicyAppDataDetailed com.tracememo.app
|
||||
```
|
||||
|
||||
再执行:
|
||||
|
||||
```bash
|
||||
tccutil reset SystemPolicyAllFiles com.tracememo.app
|
||||
```
|
||||
|
||||
两条命令都只影响当前用户,不需要 `sudo`。
|
||||
|
||||
执行后**不会**看到「授权成功」之类的提示。这条命令的作用是**删掉旧记录**,不是**发放权限**。删除之后,需要你在系统设置里重新授权一次(见第 5 节)。
|
||||
|
||||
### 如果提示服务名无效
|
||||
|
||||
终端报下面这类错误:
|
||||
|
||||
```
|
||||
tccutil: Invalid service name
|
||||
```
|
||||
|
||||
说明当前系统不认识 `SystemPolicyAppDataDetailed` 这个服务名。改用 Apple 公开文档里的写法:
|
||||
|
||||
```bash
|
||||
tccutil reset SystemPolicyAppData com.tracememo.app
|
||||
```
|
||||
|
||||
`SystemPolicyAppDataDetailed` 是否在所有 macOS 27 版本上都可用,尚未逐一验证。两种情况的效果一样:都是清掉 TraceMemo 在这类「其他应用数据」权限上的旧记录。无论用哪条,都还是要走第 5 节手动重新授权。
|
||||
|
||||
---
|
||||
|
||||
## 4. 两条命令分别管什么
|
||||
|
||||
| 命令 | 管的是 | 什么时候需要 |
|
||||
| --- | --- | --- |
|
||||
| `SystemPolicyAppDataDetailed`(或 `SystemPolicyAppData`) | 访问**其他应用沙盒容器内文件**的授权。微信数据正好在这个范围内 | 主要用这条。它清掉的是「读微信容器」这一层的旧记录 |
|
||||
| `SystemPolicyAllFiles` | **完全磁盘访问权限**的授权记录 | 系统设置里 TraceMemo 的开关看起来是开的、但实际不生效时,用它清掉整条记录重来 |
|
||||
|
||||
适用范围:
|
||||
|
||||
- 两条都只针对 `com.tracememo.app` 这一个应用,不影响微信、不影响其他软件
|
||||
- 都只影响当前登录的 Mac 用户
|
||||
- 都只是**删除记录**,不会自动给权限,也不会把权限收得更紧
|
||||
- 不要在命令里用 `All`(例如 `tccutil reset All`)—— 那会清掉这台机器上**所有应用**的所有隐私授权,微信、输入法、录屏、麦克风全要重新授权一遍,代价远大于收益
|
||||
- 不要用 `sudo`。系统级重置需要重启、影响所有用户,和本文的场景无关
|
||||
|
||||
两条命令可以只执行第一条先试。第一条无效、或系统设置里的开关状态明显不对,再执行第二条。
|
||||
|
||||
---
|
||||
|
||||
## 5. 执行命令后手动重新授权
|
||||
|
||||
1. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||
(不同系统版本的条目名称略有差异,位置都在「隐私与安全性」下)
|
||||
2. 在列表里找到 **TraceMemo**
|
||||
- 如果还在列表里:选中,点列表下方的 `−` 删除
|
||||
- 如果已经不在列表里:跳过这一步
|
||||
3. 点 `+`,在弹出的文件选择器里进入 **应用程序**,选中 **TraceMemo.app**,点「打开」
|
||||
4. 确认 TraceMemo 右侧的开关是**打开**状态
|
||||
5. **完全退出 TraceMemo 再重新打开**。授权只在应用下次启动时生效,当前正在运行的进程拿不到新权限
|
||||
|
||||
如果第 3 步选不到应用,或添加后开关立刻又关掉,先确认应用确实在 `/Applications/TraceMemo.app`,而不是在下载目录、挂载的 dmg 镜像里、或某个临时文件夹里。从 dmg 直接运行的副本每次挂载路径都不同,系统无法稳定记住授权。
|
||||
|
||||
---
|
||||
|
||||
## 6. 完全不使用终端的做法
|
||||
|
||||
不想碰终端也可以,只是机制上少了一步,成功率没有统计数据。
|
||||
|
||||
### 步骤
|
||||
|
||||
1. 完全退出 TraceMemo(`Command + Q`,再从活动监视器确认没有残留进程)
|
||||
2. 打开 **系统设置 → 隐私与安全性 → 完全磁盘访问权限**
|
||||
3. 在列表里选中 **TraceMemo**,点 `−` 删除
|
||||
4. 完全退出「系统设置」(`Command + Q`)
|
||||
5. 重新打开「系统设置」,回到同一页面,点 `+`,添加 `/Applications/TraceMemo.app`
|
||||
6. 确认开关已打开
|
||||
7. 重新启动 TraceMemo,回到连接页重试
|
||||
|
||||
### 局限性
|
||||
|
||||
- **删掉再添加,不一定能清掉底层旧记录**。系统设置里删的是可见条目,某些情况下底层的授权记录仍然存在且指向旧的应用指纹,界面看起来正常、实际依旧不生效。终端那两条命令做的正是清掉这一层。
|
||||
- **开关是开的,不等于权限生效**。系统偶尔会显示开关已开,但实际判定仍是拒绝。这时只能靠重置记录解决。
|
||||
- **没有「修复」按钮**。系统设置不提供「重新校验应用」这类操作,能做的只有删除和重新添加。
|
||||
|
||||
两步的分工要说清:终端命令负责**清掉旧记录**,本节负责**重新建立记录**。
|
||||
|
||||
- 只做本节:旧记录可能还在,界面看着正常、实际不生效。
|
||||
- 只做终端命令:记录被一起删掉,必须再走本节第 3 到 5 步添加回来,否则权限是空的。
|
||||
- 已收到的恢复反馈里,成功案例都是两步连着做的。
|
||||
|
||||
所以推荐顺序是:第 3 节命令 → 本节删除并重新添加 → 重启应用。
|
||||
|
||||
---
|
||||
|
||||
## 7. 如何重启并验证
|
||||
|
||||
授权改完必须**重启进程**,不是重新打开窗口。
|
||||
|
||||
### 从 Dock 退出
|
||||
|
||||
1. 在 Dock 里找到 TraceMemo 图标
|
||||
2. 右键(或双指点按)→ **退出**
|
||||
3. 确认图标下方的运行指示点消失
|
||||
4. 重新点图标启动
|
||||
|
||||
### 从 Finder 退出
|
||||
|
||||
1. 打开「活动监视器」(`应用程序 → 实用工具 → 活动监视器`)
|
||||
2. 搜索框输入 `TraceMemo`
|
||||
3. 选中 `TraceMemo` 进程,点左上角的 `×`,选「退出」
|
||||
4. 确认列表里已经没有 TraceMemo
|
||||
5. 打开「访达 → 应用程序」,双击 **TraceMemo**
|
||||
|
||||
### 验证是否恢复
|
||||
|
||||
启动后回到连接页,看这几点:
|
||||
|
||||
- 不再出现「无法读取微信数据库」
|
||||
- 账号、联系人、会话能正常加载
|
||||
- 随便搜一个关键词,能返回结果
|
||||
|
||||
只看到「已连接」但列表是空的,不算恢复,按第 8 节收集信息。
|
||||
|
||||
---
|
||||
|
||||
## 8. 修复失败要提供什么
|
||||
|
||||
按顺序做一遍,仍然失败,把下面这些信息一起提交:
|
||||
|
||||
1. **系统版本**:苹果菜单 → 关于本机,记录版本号(例如 macOS 27.x)和芯片(Apple Silicon / Intel)
|
||||
2. **TraceMemo 版本**:应用内「设置 → 关于」,或菜单栏 `TraceMemo → 关于 TraceMemo`
|
||||
3. **微信版本**:微信 `设置 → 关于微信`
|
||||
4. **连接页的完整提示原文**,包括错误码。有截图更好
|
||||
5. **脱敏诊断摘要**:连接页上的「复制脱敏诊断摘要」按钮,点一下会复制到剪贴板,直接粘贴到反馈里
|
||||
6. **第 3 节命令的实际输出**,包括报错。如果提示 `Invalid service name`,一定要写出来
|
||||
7. **系统设置里 TraceMemo 那条记录的状态**:在不在列表里、开关是开还是关
|
||||
|
||||
诊断摘要里不包含聊天内容、数据库密钥、完整文件路径,可以放心贴出来。
|
||||
|
||||
---
|
||||
|
||||
## 9. 不需要重新取密钥,也不要动微信数据
|
||||
|
||||
这一步很重要,能省掉大量无用操作。
|
||||
|
||||
- **不需要重新获取 WCDB 密钥**。密钥保存在本地,本次故障里它一直是正确的。重新走一遍密钥获取流程,只会多一次监听微信登录的动作,不会改变权限结果。
|
||||
- **不要删除微信数据库**。数据完好,删了就是真的没了。
|
||||
- **不要删除 TraceMemo 的配置目录**。里面有账号指向、密钥、索引,删掉要全部重来。
|
||||
- **不要用 `sudo` 运行 TraceMemo**。以 root 运行会换一个进程身份,权限判定更混乱,还会让配置文件属主变成 root,后续正常启动反而出问题。
|
||||
- **不要 `chmod` / `chown` 整个微信目录**。改了会影响微信自身的读写,属于制造新问题。
|
||||
- **不要为了这个问题关闭 SIP**。SIP 管的是系统完整性保护,和「某个应用能不能读另一个应用的容器」不是一回事。关闭 SIP 不解决这个权限判定,还会降低整机安全性。SIP 相关说明见[关闭 SIP 教程](../mac-disable-sip.md),那是密钥获取流程里的独立话题。
|
||||
|
||||
### 顺带区分:这不是 Frida 附加失败
|
||||
|
||||
两类问题长得像,处理方式完全不同:
|
||||
|
||||
| | 数据库访问权限问题(本文) | 密钥获取/进程附加问题 |
|
||||
| --- | --- | --- |
|
||||
| 出现时机 | 已经连过、升级后重新打开 | 首次连接,或重新获取密钥时 |
|
||||
| 界面提示 | 「无法读取微信数据库」`DATABASE_PERMISSION_DENIED` | 监听超时 `CAPTURE_TIMEOUT`、内存扫描失败,或提示无法绑定微信进程 |
|
||||
| 数据目录检测 | 显示已检测到 | 通常在更早的步骤就失败 |
|
||||
| 处理方向 | 系统设置里重新授权 | 检查微信是否停在登录页、是否需要管理员授权、微信版本是否适配 |
|
||||
|
||||
如果你的现象是「点了自动获取密钥,一直等到超时」,那走的是右边一列,不是本文的权限问题。
|
||||
|
||||
---
|
||||
|
||||
## 10. 这只是当前故障的恢复方案
|
||||
|
||||
说清楚边界:
|
||||
|
||||
- 本文解决的是**已经发生**的授权断裂,不改变应用的签名方式。
|
||||
- 只要发布包仍然是当前这种 ad-hoc 签名,**下一次更新后仍可能再次发生**。
|
||||
- 出现时,重复第 3 到 5 节即可,通常不需要重装、不需要重新取密钥。
|
||||
- 彻底解决需要发布端改用稳定的开发者签名并完成公证,这属于打包流程的改动,不在用户侧。
|
||||
|
||||
正常使用、没有出现问题的用户,不需要提前做任何权限设置。授权不是安装前置条件。
|
||||
@@ -9,16 +9,15 @@ TraceMemo 的核心路径是本地优先,但“本地优先”不等于所有
|
||||
- 读取和解析微信数据库;
|
||||
- 聊天档案浏览和普通关键词搜索;
|
||||
- 本地 Knowledge 索引及其账号隔离;
|
||||
- 图片文字索引:识别图片中的文字在本机完成,原始图片不会因为本地识别而上传;
|
||||
- 离线语音转写;
|
||||
- 导出文件生成和本地日报历史。
|
||||
|
||||
应用不会因为你打开 TraceMemo 就自动把整份微信数据库上传。
|
||||
|
||||
防撤回默认关闭,并且和上面的普通读取路径不同。用户第一次明确开启时,当前实现会在微信消息数据库中安装本地撤回日志/监听结构,同时在 TraceMemo 用户数据目录保存必要的恢复记录。v2.1.9 的旧恢复记录会随首次启动迁移复制到 TraceMemo,旧目录仍保留。关闭开关不等于移除已经安装的结构或清空既有记录;当前 UI 没有对应的清理入口。详见[防撤回](./recall-protection.md)。
|
||||
|
||||
## 什么时候会请求外部服务
|
||||
|
||||
当你主动使用 AI Search、群聊日报或图片理解,并配置了远程 Provider 时,完成任务所需的内容可能发送给该 Provider。当前设置页给出的边界是:
|
||||
当你主动使用 AI Search、群聊日报或图片理解,并配置了远程 Provider 时,完成任务所需的内容可能发送给该 Provider。图片文字索引、离线语音转写、档案浏览和普通搜索不会触发这一步。当前设置页给出的边界是:
|
||||
|
||||
- 当前用户问题;
|
||||
- 受控检索所需的有限上下文;
|
||||
@@ -30,7 +29,14 @@ Ollama 等本机 Provider 可以把模型请求留在本机,但本机服务的
|
||||
|
||||
## 语音和媒体
|
||||
|
||||
离线语音转写在本机进行。图片理解属于 AI 功能:只有你主动启用并使用相关报告/分析路径时,图片才可能按该 Provider 的请求规则被处理。无法读取的媒体不会被自动“猜出来”。
|
||||
离线语音转写在本机进行。
|
||||
|
||||
图片有两条完全不同的路径,不要混为一谈:
|
||||
|
||||
- **图片文字索引**:在本机识别图片里的文字,产出的是本地索引数据;原始图片不会因为这一步被上传,也不需要配置 AI 服务。
|
||||
- **图片理解**:属于 AI 功能。只有你主动启用并使用相关报告/分析路径时,图片才可能按该 Provider 的请求规则被处理。
|
||||
|
||||
无法读取的媒体不会被自动“猜出来”。
|
||||
|
||||
## Local HTTP API
|
||||
|
||||
@@ -58,4 +64,3 @@ Token 由应用生成,使用 Electron `safeStorage` 加密保存在本机 `loc
|
||||
- 对需要外发的 AI 功能逐项确认 Provider;
|
||||
- 定期在“设置 → 缓存与清理”清理不再需要的检索、导出和索引缓存;
|
||||
- 在共享电脑上退出应用并保护系统账户。
|
||||
- 在开启防撤回前确认你接受其数据库写入、性能和清理边界,并先用微信官方方式备份重要数据。
|
||||
@@ -1,37 +0,0 @@
|
||||
# 防撤回
|
||||
|
||||
防撤回是一个默认关闭的可选功能。开启后,TraceMemo 会尽量保留它能够捕获到的撤回消息,并在聊天气泡旁标记“消息已撤回”。
|
||||
|
||||
它适合希望在本机档案中保留后续聊天上下文的用户,但不能保证找回每一条撤回消息。
|
||||
|
||||
## 如何开启
|
||||
|
||||
1. 先连接微信数据库,并确认“档案”可以正常读取聊天。
|
||||
2. 打开“设置 → 防撤回”。
|
||||
3. 阅读性能和数据提示后,开启“防撤回”。
|
||||
4. 保持 TraceMemo 与当前微信数据连接;之后捕获到的撤回消息会尽量保留并标记。
|
||||
|
||||
防撤回不是第一次使用的必要步骤。只想浏览、搜索、提问或导出时,可以保持关闭。
|
||||
|
||||
## 当前能做什么
|
||||
|
||||
- 监听应用能够识别到的后续撤回变化;
|
||||
- 在本地保留必要的消息和撤回关系;
|
||||
- 将已识别的原消息与撤回状态一起显示在档案中;
|
||||
- 按微信账号隔离 TraceMemo 保存的恢复记录。
|
||||
|
||||
## 当前限制
|
||||
|
||||
- 不能恢复开启前已经撤回、且应用从未保存到的消息;
|
||||
- TraceMemo 未运行、数据库未连接或没有捕获到撤回变化时,消息可能无法保留;
|
||||
- 微信版本、消息表结构和数据库事件变化都可能让部分消息无法恢复或正确匹配;
|
||||
- 开启后需要为消息表增加监听,聊天很多或磁盘较慢时可能影响加载性能;
|
||||
- “消息已撤回”只说明应用识别到了撤回关系,不保证恢复内容完整。
|
||||
|
||||
## 数据写入与关闭边界
|
||||
|
||||
普通浏览、搜索和 Knowledge 不会修改微信原始聊天数据库;防撤回是一个例外。用户第一次明确开启时,当前实现会在微信消息数据库中安装用于记录撤回的本地日志/监听结构,并在 TraceMemo 的用户数据目录保存必要的本地恢复记录。v2.1.9 的旧恢复记录会在用户确认迁移后复制到 TraceMemo,旧目录不会删除。
|
||||
|
||||
关闭设置中的开关,不等同于删除已经安装的日志结构或清空此前保存的恢复记录。当前版本没有在 UI 中提供“移除防撤回日志结构”或“清空防撤回记录”的独立操作。对数据库写入、磁盘占用或完全回滚有要求时,应在开启前先确认这一边界,并使用微信官方方式备份重要数据。
|
||||
|
||||
完整的数据边界见[数据、隐私与安全](./privacy.md)。
|
||||
@@ -6,8 +6,8 @@
|
||||
|
||||
典型场景包括:
|
||||
|
||||
- 整理今天工作群的讨论重点;
|
||||
- 回顾昨天错过的决定和资源;
|
||||
- 整理今日工作群的讨论重点;
|
||||
- 回顾昨日错过的决定和资源;
|
||||
- 汇总近 7 天的项目进展、待办和未解决问题;
|
||||
- 把群里的图片、语音统计和重要消息放进一张长图或 HTML 页面。
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
你可以从两个入口开始:打开一级导航“日报”后新建报告,或者在“档案”中选中一个群聊并点击“生成 AI 日报”。
|
||||
|
||||
1. 选择一个群聊。当前日报入口只支持群聊,不支持单聊。
|
||||
2. 选择时间范围:今天、昨天或近 7 天。
|
||||
2. 选择时间范围:今日、昨日或近 7 天。
|
||||
3. 按需要选择参与总结的消息类型,先从文字开始最容易核对。
|
||||
4. 选择报告模板/内容模式并开始生成。
|
||||
5. 等待“整理输入 → AI 生成 → HTML/PNG 导出”完成。
|
||||
@@ -33,10 +33,26 @@
|
||||
|
||||
生成成功后会保存本地 HTML 与 PNG,并出现在日报历史中。你可以复制图片、打开文件位置或重新生成。删除历史日报只删除本地生成的报告文件,不会影响微信聊天数据库。
|
||||
|
||||
## 定时日报(在自动化里)
|
||||
|
||||
定时日报现在是「自动化」里的一种规则,不再单独占一个页面:打开一级导航的「自动化」,新建或编辑一条「定时日报」规则,选择群聊、执行时间、日报范围、消息类型和发送目标。日报页顶部的指引条也会直接跳到自动化。
|
||||
|
||||
TraceMemo 会按计划执行:
|
||||
|
||||
```text
|
||||
定时触发 → 读取群聊 → 生成报告 → 保存 Report History → 尝试发送
|
||||
```
|
||||
|
||||
生成和发送是两个阶段。当前微信发送能力不可用、未绑定或发送失败时,报告仍会保存,PNG 和执行记录也会保留;这类结果会显示为“已生成,但未发送”或“已生成,发送失败”。
|
||||
|
||||
执行记录支持查看已生成的日报。对“等待发送”或“发送失败”的记录,可以直接重试发送,重试会复用已经生成的 PNG,不会重新调用 AI 生成整份报告;完整执行状态和发送边界见[如何把聊天变成可用的信息](../concepts/how-it-works.md#动作执行与审计)。
|
||||
|
||||
发送目标当前支持**当前群聊、文件传输助手、自己、指定好友**——还不是任意群发。
|
||||
|
||||
## 让报告更可靠
|
||||
|
||||
- 先选正确的群和时间范围;
|
||||
- 不确定时先只选择文字消息;
|
||||
- 群太活跃时分成“今天”和“近 7 天”两次生成;
|
||||
- 群太活跃时分成“今日”和“近 7 天”两次生成;
|
||||
- 看到待办和结论后回到原消息核对上下文;
|
||||
- AI Provider 不可用时先检查模型配置和网络/本地服务状态。
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
### macOS
|
||||
|
||||
- 确认下载的构建与 Mac 处理器匹配:Apple Silicon(M 系列)用 `arm64`,Intel 用 `x64`。
|
||||
- 提示“无法打开,因为开发者无法验证”时,前往“系统设置 → 隐私与安全性”并点击“仍要打开”。
|
||||
- 提示应用已损坏时,确认应用位于“应用程序”目录,再执行 `xattr -cr "/Applications/TraceMemo.app"`。
|
||||
|
||||
@@ -24,11 +25,26 @@
|
||||
1. 数据目录是否指向当前登录账号,而不是旧备份或迁移前目录;
|
||||
2. 微信版本是否属于当前代码面向的 4.x 数据结构;
|
||||
3. 微信是否处于页面要求的登录/退出状态;
|
||||
4. macOS 是否完成页面要求的授权;
|
||||
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题。
|
||||
4. macOS 是否完成页面要求的授权;如果是升级 macOS 或更新 TraceMemo 之后才失败的,按[权限恢复文档](./macos27-permission-recovery.md)处理,只打开开关通常不够;
|
||||
5. 连接页面的诊断项是否明确指出密钥、账号或数据库问题;
|
||||
6. macOS 上 Apple Silicon 与 Intel 使用不同的连接流程,按连接页面提示操作;两者都可以自动获取数据库密钥。
|
||||
7. 页面显示「Intel Mac 自动获取」但电脑是 Apple 芯片时,多半是装了 Intel 版,见[架构不匹配说明](../platform/macos.md#提示intel-mac-自动获取但电脑是-apple-芯片)。
|
||||
|
||||
重新输入密钥或断开连接不会删除微信原始数据库。macOS 的 SIP 和授权说明见[平台说明](../platform/macos.md)。
|
||||
|
||||
### 提示「无法读取微信数据库」但文件确实存在
|
||||
|
||||
这是**权限问题,不是文件缺失** —— 如果你在终端里能列出 `db_storage/session/session.db`,说明数据目录是完整的,只是 TraceMemo 这个进程读不到。
|
||||
|
||||
注意:**终端能读到文件不代表 TraceMemo 有权限** —— macOS 的隐私权限按应用进程的身份判定,两者走的是不同的授权。
|
||||
|
||||
按出现时机分两种情况:
|
||||
|
||||
- **首次连接就没成功**:给 TraceMemo 授予「完全磁盘访问权限」即可,步骤见 [macOS 数据访问与系统权限 → 提示「无法读取微信数据库」时](../platform/macos.md#提示无法读取微信数据库时)。
|
||||
- **之前能用,升级 macOS 或更新 TraceMemo 之后才失败**:多数是旧授权记录对不上新版本的应用,只打开开关不够,需要先清掉旧记录再重新授权。完整步骤见[macOS 更新后读不到微信数据:权限恢复](./macos27-permission-recovery.md)。
|
||||
|
||||
仍然失败时,记录 **macOS 版本、CPU 架构(Apple Silicon / Intel)、微信版本、TraceMemo 版本和页面错误提示** 后,扫码 README 文档二维码进群反馈,或提交 Issue。连接页的「复制脱敏诊断摘要」可以直接提供这些环境信息。
|
||||
|
||||
## 连接成功但没有联系人或消息
|
||||
|
||||
确认账号身份和数据目录匹配。返回“设置 → 账号与数据库”查看数据库连接状态,重新加载会话后再试。若仍为空,记录系统、微信版本和错误提示后提交 Issue。
|
||||
@@ -89,6 +105,14 @@ Agent Hub 和外部 Agent 是两条路径。机器人异常时依次确认:
|
||||
|
||||
当前机器人不支持群发、定时任务或与文字同等的图片、语音、文件和视频理解。详细边界见[Agent Hub](../agent/agent-hub.md)。
|
||||
|
||||
## 防撤回没有保留消息
|
||||
## 点击关闭后应用没有退出
|
||||
|
||||
防撤回只能尽量保留开启后且应用成功捕获到的撤回变化。确认开启时数据库已经连接、TraceMemo 在撤回发生时保持运行,并检查聊天加载是否明显变慢。开启前已经消失、应用未捕获或微信结构无法识别的消息不能保证恢复;详见[防撤回](./recall-protection.md)。
|
||||
「关闭窗口时」可能被配置为**最小化到托盘** —— 窗口隐藏,应用仍在后台运行。
|
||||
|
||||
到「设置 → 外观与行为 → 关闭窗口时」可以改成:
|
||||
|
||||
- **每次询问**:每次关闭都弹窗确认;
|
||||
- **最小化到托盘**:窗口隐藏,应用继续在后台运行;
|
||||
- **退出应用**:直接结束 TraceMemo 进程。
|
||||
|
||||
选择「每次询问」时,在关闭弹窗里勾选「记住我的选择,下次不再询问」会自动切换到这里对应的项。
|
||||
@@ -0,0 +1,20 @@
|
||||
extends: ./electron-builder.yml
|
||||
extraResources:
|
||||
- from: build/app-update.yml
|
||||
to: app-update.yml
|
||||
- from: resources
|
||||
to: resources
|
||||
filter:
|
||||
- '**/*'
|
||||
- from: resources/wcdb/macos/arm64
|
||||
to: resources/wcdb/macos/arm64
|
||||
filter:
|
||||
- 'tm-wcdb-config-helper'
|
||||
- from: docs/skill/tracememo-reader
|
||||
to: skill/tracememo-reader
|
||||
filter:
|
||||
- '**/*'
|
||||
mac:
|
||||
target:
|
||||
- dmg
|
||||
- zip
|
||||
@@ -19,6 +19,8 @@ asarUnpack:
|
||||
- node_modules/silk-wasm/**
|
||||
- node_modules/sherpa-onnx-node/**
|
||||
- node_modules/sherpa-onnx-*/**
|
||||
- node_modules/@napi-rs/system-ocr/**
|
||||
- node_modules/@napi-rs/system-ocr-*/**
|
||||
extraResources:
|
||||
# Keep the updater provider in every packaged Windows app. electron-builder also
|
||||
# regenerates this file during publish, using the same release configuration.
|
||||
@@ -33,10 +35,20 @@ extraResources:
|
||||
- mobile_daily_report.html
|
||||
- mobile_daily_report_v1.html
|
||||
- mobile_daily_report_v2.html
|
||||
- connectors/wechat/win32-x64/**
|
||||
- key/win32/x64/**
|
||||
- runtime/win32/**
|
||||
- wcdb/win32/x64/**
|
||||
- '!wcdb/**/tm-wcdb-config-helper*'
|
||||
# 官方扩展模板(构建期由 scripts/build-extension-templates.cjs 生成)
|
||||
- from: build/extension-templates
|
||||
to: extension-templates
|
||||
filter:
|
||||
- '**/*'
|
||||
# 默认不打包helper
|
||||
# - from: resources/wcdb/win32/x64
|
||||
# to: resources/wcdb/win32/x64
|
||||
# filter:
|
||||
# - 'tm-wcdb-config-helper.exe'
|
||||
- from: docs/skill/tracememo-reader
|
||||
to: skill/tracememo-reader
|
||||
filter:
|
||||
@@ -51,6 +63,7 @@ win:
|
||||
nsis:
|
||||
oneClick: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
include: build/installer.nsh
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
uninstallDisplayName: ${productName}
|
||||
@@ -63,4 +76,6 @@ publish:
|
||||
provider: github
|
||||
owner: Wxw-Gu
|
||||
repo: TraceMemo
|
||||
releaseType: release
|
||||
# 一律先上传为草稿 再到 GitHub 上手动 Publish。
|
||||
# 需要预发布时用 `pnpm release:beta`(EP_PRE_RELEASE 会覆盖这里的 draft)。
|
||||
releaseType: draft
|
||||
@@ -19,6 +19,11 @@ asarUnpack:
|
||||
- node_modules/silk-wasm/**
|
||||
- node_modules/sherpa-onnx-node/**
|
||||
- node_modules/sherpa-onnx-*/**
|
||||
# System OCR(@napi-rs/system-ocr)的 native binding 必须 unpacked,否则
|
||||
# macOS 的系统 OCR 会在运行时 MODULE_NOT_FOUND。平台本机的 binding 由
|
||||
# scripts/after-pack.cjs 校验,外架构的同级包在 afterPack 里被裁掉。
|
||||
- node_modules/@napi-rs/system-ocr/**
|
||||
- node_modules/@napi-rs/system-ocr-*/**
|
||||
extraResources:
|
||||
# Keep the updater provider in every packaged macOS app. electron-builder also
|
||||
# regenerates this file during publish, using the same release configuration.
|
||||
@@ -29,14 +34,22 @@ extraResources:
|
||||
to: resources
|
||||
filter:
|
||||
- '**/*'
|
||||
- '!connectors/wechat-personal/**'
|
||||
- '!runtime/darwin-arm64/**'
|
||||
- '!wcdb/**/tm-wcdb-config-helper*'
|
||||
- from: docs/skill/tracememo-reader
|
||||
to: skill/tracememo-reader
|
||||
filter:
|
||||
- '**/*'
|
||||
# 官方扩展模板:构建期由 scripts/build-extension-templates.cjs 生成,
|
||||
# 安装包必须自带,运行时不依赖源码树或网络。
|
||||
- from: build/extension-templates
|
||||
to: extension-templates
|
||||
filter:
|
||||
- '**/*'
|
||||
nsis:
|
||||
oneClick: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
include: build/installer.nsh
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
uninstallDisplayName: ${productName}
|
||||
@@ -71,4 +84,6 @@ publish:
|
||||
provider: github
|
||||
owner: Wxw-Gu
|
||||
repo: TraceMemo
|
||||
releaseType: release
|
||||
# 一律先上传为草稿 再到 GitHub 上手动 Publish。
|
||||
# 需要预发布时用 `pnpm release:beta`(EP_PRE_RELEASE 会覆盖这里的 draft)。
|
||||
releaseType: draft
|
||||
@@ -2,24 +2,32 @@ import { resolve } from 'path'
|
||||
import { defineConfig } from 'electron-vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
const editionOutDir = process.env.TRACEMEMO_EDITION_OUT_DIR
|
||||
|
||||
export default defineConfig({
|
||||
main: {
|
||||
build: {
|
||||
...(editionOutDir ? { outDir: editionOutDir } : {}),
|
||||
rollupOptions: {
|
||||
input: {
|
||||
index: resolve('src/main/index.ts'),
|
||||
/* 扩展后台宿主:由 `ExtensionHost` 以子进程方式 fork,不在主进程加载。 */
|
||||
extensionHost: resolve('src/main/extensions/host-runtime.ts'),
|
||||
reportTemplateTest: resolve('src/main/report-template-test-entry.ts'),
|
||||
queryAgentPoc: resolve('src/main/query-agent-poc-entry.ts'),
|
||||
voiceRecognitionWorker: resolve('src/main/voice-pipeline/voice-recognition-worker.ts'),
|
||||
knowledgeWorker: resolve('src/main/knowledge/knowledge-worker.ts')
|
||||
},
|
||||
output: {
|
||||
entryFileNames: '[name].js'
|
||||
},
|
||||
external: ['koffi', 'sherpa-onnx-node']
|
||||
external: ['koffi', 'sherpa-onnx-node', '@napi-rs/system-ocr']
|
||||
}
|
||||
}
|
||||
},
|
||||
preload: {},
|
||||
preload: editionOutDir ? { build: { outDir: editionOutDir } } : {},
|
||||
renderer: {
|
||||
...(editionOutDir ? { build: { outDir: editionOutDir } } : {}),
|
||||
resolve: {
|
||||
alias: {
|
||||
'@renderer': resolve('src/renderer/src')
|
||||
|
||||
@@ -34,5 +34,14 @@ export default defineConfig(
|
||||
...eslintPluginReactRefresh.configs.vite.rules
|
||||
}
|
||||
},
|
||||
{
|
||||
// 扩展示例是给第三方作者抄的 CommonJS,不是 TS 源码:
|
||||
// 返回类型/require 规则在这里没有意义,强制它们只会让示例变成反例。
|
||||
files: ['examples/**/*.{js,mjs}'],
|
||||
rules: {
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/no-require-imports': 'off'
|
||||
}
|
||||
},
|
||||
eslintConfigPrettier
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
# 扩展示例
|
||||
|
||||
四个可直接安装的官方模板示例,覆盖扩展中心从安装、媒体解析、离线渲染、通知中心到受控发送的完整链路。
|
||||
|
||||
| 目录 | 用途 | 申请权限 |
|
||||
| --- | --- | --- |
|
||||
| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` |
|
||||
| `group-chat-bot/` | 多套群聊人格、单群长期与短期记忆、按需解析图片与语音、随机回复文字或语音 | `messages.subscribe`、`messages.query`、`media.ocr`、`media.transcribe`、`ai.vision`、`contacts.list`、`wechat.send.text`、`wechat.send.voice`、`ai.chat`、`notifications.create`、`storage` |
|
||||
| `morning-digest/` | AI 晨报:分页查询消息、批量媒体解析、AI 总结、离线 HTML 长图渲染、扩展通知与可选微信发送 | `messages.query`、`media.ocr`、`media.transcribe`、`ai.chat`、`ai.vision`、`render.html`、`notifications.create`、`contacts.list`、`wechat.send.image`、`automation.action`、`storage` |
|
||||
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
|
||||
|
||||
## 安装
|
||||
|
||||
TraceMemo → 左侧「扩展」→「官方模板」一键安装,或点「安装目录」选择对应目录。
|
||||
|
||||
安装后扩展默认**未启用**:
|
||||
|
||||
- `keyword-bot` 的 `enabled` 为 `false`,需要在配置页手动打开才会回复;
|
||||
- `group-chat-bot` 需要本机已配置 AI Provider(需要语音回复时在「设置 → 文字转语音」配置音色),并在配置页勾选生效群聊;
|
||||
- `douyin-sender` 依赖本机的 `python3`、Chrome 和抖音解析脚本,安装前先看它自己的 README。
|
||||
|
||||
## 测试建议
|
||||
|
||||
- 关键词机器人默认监听全部群聊 + 私聊;想只对某个群生效,在「监听范围」里搜索并多选群聊。
|
||||
- 冷却时间按「会话 + 规则」计算,避免同一句话连续刷屏。
|
||||
- 扩展的发送走 `tm.wechat.send`,最终仍由 TraceMemo Gateway 做权限、授权校验、限流与审计。
|
||||
|
||||
## 开发
|
||||
|
||||
扩展目录里只需要 `manifest.json` 与入口文件:
|
||||
|
||||
```text
|
||||
my-extension/
|
||||
manifest.json
|
||||
ui/index.html
|
||||
background/index.js
|
||||
```
|
||||
|
||||
`background/index.js` 导出 `activate(tm)`(或 `module.exports = { activate }`)。页面通过
|
||||
`postMessage` 与宿主通信,协议见 `docs/extensions/api-reference.md`。
|
||||
@@ -0,0 +1,143 @@
|
||||
# 抖音视频搬运
|
||||
|
||||
被 @ 且消息里带抖音分享链接时,解析作品、下载视频,并发回原会话。
|
||||
|
||||
判定范围由扩展自己控制:只有**真正 @ 到当前登录账号**的文本消息才会进入流程
|
||||
(`subscriptions.requireMentionMe: true`),普通消息直接忽略。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 本机有 `python3`(3.10 及以上)。
|
||||
- 本机装了 Chrome:解析脚本用真实浏览器打开作品页、拦截页面自己发出的 `aweme/detail` 响应,
|
||||
不自造签名。
|
||||
- 解析脚本已存在于本机(默认 `scripts/douyin.py`,相对于扩展目录,也可在配置页指定自定义路径)。
|
||||
- 首次运行时脚本会在 `~/Library/Caches/douyin-video/venv`(Windows 落在 `%LOCALAPPDATA%`)
|
||||
自建 venv 并安装 `playwright` / `requests`,约 30 秒;之后复用,不再安装。
|
||||
|
||||
## 安装
|
||||
|
||||
TraceMemo → 左侧「扩展」→「安装目录」,选择本目录 `douyin-sender/`。
|
||||
|
||||
安装完成后:
|
||||
|
||||
1. 打开「抖音解析设置」页面,确认 Python 路径与脚本路径;
|
||||
2. 打开总开关,保存;
|
||||
3. 在「测试发送」里选目标群、粘贴抖音分享文案,点「测试发送」验证;
|
||||
或在微信里 @ 自己发一条带抖音分享链接的文本消息。
|
||||
|
||||
扩展默认 `enabled: false`,安装后不会自动对外发送。
|
||||
|
||||
配置页的群列表来自本机通讯录,对应权限 `contacts.list`(只读群名与会话 id,不含聊天内容)。
|
||||
|
||||
升级同 id 的扩展会替换代码并保留配置;如果新版本**新增了权限**(例如从 image 换成 video),
|
||||
升级后请「停用 → 启用」一次,让宿主按新 manifest 重新授权。
|
||||
|
||||
## 测试发送(配置页)
|
||||
|
||||
配置页底部有独立的「测试发送」:
|
||||
|
||||
1. 下拉选择目标群(列表来自 `contacts.listGroups`,需要 `contacts.list` 权限);
|
||||
2. 粘贴抖音链接或整段分享文案(命令行脚本不需要手动截取 URL);
|
||||
3. 点「测试发送」,页面会轮询进度,解析完成后把去水印视频发到该群;
|
||||
4. 测试路径**不发回执**,避免测试时多一条消息;
|
||||
5. 测试任务同样计入统计,进度显示在「当前任务」。
|
||||
|
||||
设置页可选使用「抖音 Cookie」面板粘贴并保存 Cookie header。宿主通过系统安全存储加密后保存在本机,页面只展示是否已配置,不会回显内容;测试发送与自动解析时在后台使用该 Cookie,未配置时也可回退读取本机 `douyin-cookie` 文件。
|
||||
|
||||
## 配置字段
|
||||
|
||||
| 字段 | 默认值 | 说明 |
|
||||
| ----------------- | ------------------------ | ---------------------------------------------------------------------- |
|
||||
| `enabled` | `false` | 总开关;关闭时任何消息都不处理 |
|
||||
| `pythonPath` | `python3` | Python 可执行文件,支持 `~` |
|
||||
| `scriptPath` | `scripts/douyin.py` | 解析脚本路径(默认相对于扩展目录,支持 `~` 与绝对路径) |
|
||||
| `quality` | `720` | `''` 最高 / `1080` / `720` / `540`;其他值收敛到 `720` |
|
||||
| `showUi` | `false` | 排障开关:显示浏览器窗口以观察最终页面;不保证改变平台响应 |
|
||||
| 抖音 Cookie | 未配置 | 配置页输入后由 Electron `safeStorage` 加密保存 |
|
||||
| `ackText` | `收到,正在解析,请稍候…`| 命中后先回复的文本;留空表示不回执 |
|
||||
| `errorReply` | `true` | 失败时是否在原会话回一条简短说明 |
|
||||
| `includeDirect` | `false` | 是否同时处理私聊 |
|
||||
| `groups` | `[]` | 群白名单;空数组表示全部群 |
|
||||
| `cooldownSeconds` | `60` | 按会话计的冷却,0–3600 |
|
||||
| `maxFileMB` | `100` | 单文件上限,1–100,不能超过宿主 100 MB 硬限制 |
|
||||
|
||||
保存时写入 `configVersion: 1`;后台最多 1 秒内读到新配置(配置缓存 TTL 1000 ms)。
|
||||
|
||||
## 处理流程
|
||||
|
||||
1. `message.received` → 判定顺序:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
|
||||
2. 命中后先回执(`ackText`,默认「收到,正在解析,请稍候…」;留空关闭),再进入解析。
|
||||
3. `python3 <script> "<链接>" -o <dataDir>/downloads --wait 40 --download-timeout 90 --json --video-only --download`,单次打开作品页并完成解析、下载;图集只返回类型、不下载;进程总超时 420 秒,输出上限 8 MB,`cwd` 为扩展数据目录。
|
||||
4. 从 JSON 结果中读取作品元数据与 `saved` 绝对路径;校验文件存在、是普通文件、未超过上限。
|
||||
5. 若结果为图集,记为 `IMAGE_SET` 并按配置处理失败提示;若解析/下载失败,保留脚本返回的错误原因。
|
||||
6. 发送视频,`dedupeKey = eventId + ':video'`(不再额外发送作品标题文本)。
|
||||
7. 每个阶段都写 `progress` 快照并记一条日志;配置页每 2 秒刷新一次进度。
|
||||
8. 无论成败写一条统计(成功/失败分别计数);失败只记阶段、错误码与去掉 URL / 路径的短原因。
|
||||
9. 冷却只在**视频发送成功后**写入。
|
||||
|
||||
同一会话同时只跑一个任务;同一条消息重复投递时按 `会话 + 链接` 去重。启动时会清理
|
||||
`<dataDir>/downloads`:只保留最近 20 个文件,并删除 7 天前的文件。
|
||||
|
||||
失败文案固定为三种,原因截断到 60 字且不含路径:
|
||||
|
||||
- `解析失败:<短原因>`
|
||||
- `视频过大(<N>MB),已跳过`
|
||||
- `暂不支持图集`
|
||||
|
||||
## 发送通道
|
||||
|
||||
视频走宿主的 **video 通道**:`tm.wechat.send({ type: 'video', to, path })`。
|
||||
原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交,所以 `permissions` 里申请的是 `wechat.send.video`。
|
||||
|
||||
媒体文件必须落在扩展数据目录或系统临时目录内(宿主会用 `realpath` 复核),扩展名必须是
|
||||
`mp4/mov/m4v`,大小 1 B–100 MB。所有发送仍要过 Gateway 的权限、
|
||||
授权与限流:同一扩展 60 秒最多 10 条,两条之间至少 2 秒。
|
||||
|
||||
## 限制
|
||||
|
||||
- 只处理视频;图集(`type: 'image'`)不下载,按配置回「暂不支持图集」。
|
||||
- 单个文件 ≤ 100 MB,超过不发送。
|
||||
- 冷却按会话计,冷却期内同一会话的新链接会被忽略。
|
||||
- 事件投递是「至多一次」:TraceMemo 未运行期间的消息不会补发。
|
||||
- 脚本路径必须在本机真实存在;路径错误时错误文案会提示检查 Python 路径。
|
||||
- 解析依赖抖音页面结构,脚本自身失效时扩展只能报「解析失败」。
|
||||
|
||||
## 排障:`页面已加载(NNNKB)但未发出 detail 请求`
|
||||
|
||||
这是浏览器打开了页面,但没有捕获到 `aweme/detail` 的作品数据。仅凭这一条错误不能判断作品已删除;页面也可能是作品壳、推荐页或平台验证状态。先看 `--debug` 现场中的页面标题、地址和截图。扩展不会并发启动第二次解析;测试发送失败时会在页面显示阶段、错误码和去掉 URL / 本地路径后的短原因。
|
||||
|
||||
仍需手动复试时:
|
||||
|
||||
1. 先等一会儿再尝试,避免同一作品短时间内重复请求;
|
||||
2. 配置页勾选「显示浏览器窗口」后重新测试,观察最终停留页面;
|
||||
3. 命令行单独验证时使用同一份脚本,避免与扩展并发运行:
|
||||
|
||||
```bash
|
||||
python3 scripts/douyin.py \
|
||||
"https://v.douyin.com/xxxxxx/" --json --wait 40 --show-ui
|
||||
```
|
||||
|
||||
## 进度与统计
|
||||
|
||||
- 回执:命中后先发一条 `ackText`,默认「收到,正在解析,请稍候…」;留空则不回。
|
||||
- 进度:存储键 `progress`,结构 `{stage,status,startedAt,updatedAt,awemeId,errorType,errorMessage}`。
|
||||
配置页每 2 秒读取一次,显示「已接收 / 解析 / 下载 / 发送 / 补发文案 / 完成」,
|
||||
失败时显示失败所在阶段与错误码。
|
||||
- 统计:存储键 `stats`,结构 `{dateKey,todayTotal,todaySuccess,todayFailure,lastJobs[]}`;
|
||||
失败也计数,`lastJobs` 保留最近 20 条(含阶段与错误码)。
|
||||
- 页面顶部「统计」显示今日总计 / 成功 / 失败;表格展示最近 8 条。
|
||||
|
||||
## 隐私
|
||||
|
||||
- 分享链接会交给本机脚本,由脚本访问抖音页面;扩展本身不向任何第三方发请求。
|
||||
- 下载的视频存放在扩展数据目录 `downloads/` 下,发送后不自动删除(按上面的规则轮转清理)。
|
||||
- 统计只保存时间、作品 id、阶段、成败、错误码,**不含** URL、标题、作者、会话 id。
|
||||
- 日志只写阶段与错误类型。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
|
||||
```
|
||||
|
||||
用例全部离线:不联网、不启动 python、不读写真实文件。
|
||||
@@ -0,0 +1,842 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 抖音视频搬运 —— 后台入口。
|
||||
*
|
||||
* 链路:`message.received` → 纯函数判定 → 解析并下载脚本 →
|
||||
* 经宿主 `wechat.send` 的 video 通道发回原会话。
|
||||
*
|
||||
* 这个文件跑在宿主的扩展子进程里,**只**用 `tm` 暴露的能力:
|
||||
* 没有 socket、没有 dylib、没有直接读写微信数据目录。
|
||||
*/
|
||||
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const fsSync = require('node:fs')
|
||||
const fs = require('node:fs/promises')
|
||||
const { execFile } = require('node:child_process')
|
||||
const { promisify } = require('node:util')
|
||||
|
||||
const {
|
||||
normalizeConfig,
|
||||
extractDouyinUrl,
|
||||
parseDownloadedResult,
|
||||
shouldHandle,
|
||||
isFileTooLarge
|
||||
} = require('../lib/douyin')
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
/** 安全存储里的 Cookie 键名。 */
|
||||
const SECRET_COOKIE_KEY = 'douyinCookie'
|
||||
const PROGRESS_KEY = 'progress'
|
||||
const TEST_RESULT_KEY = 'testResult'
|
||||
const CONFIG_TTL_MS = 1000
|
||||
|
||||
/** 配置页「测试发送」的轮询间隔;页面只负责写请求、读结果。 */
|
||||
|
||||
/** 阶段名只用于展示与日志,不参与判断。 */
|
||||
const STAGE_LABELS = {
|
||||
accepted: '已接收',
|
||||
resolve: '解析',
|
||||
resolveDownload: '解析并下载',
|
||||
download: '下载',
|
||||
send: '发送',
|
||||
caption: '补发文案',
|
||||
done: '完成',
|
||||
failed: '失败'
|
||||
}
|
||||
|
||||
/** 脚本内部等待抖音接口的秒数,解析与下载共用。 */
|
||||
const SCRIPT_WAIT_SECONDS = '40'
|
||||
const DOWNLOAD_AND_RESOLVE_TIMEOUT_MS = 420_000
|
||||
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
|
||||
|
||||
/** 宿主限制:同一扩展两次发送之间至少 2 秒,这里留 200ms 余量。 */
|
||||
const SEND_GAP_MS = 2200
|
||||
|
||||
const KEEP_RECENT_FILES = 20
|
||||
const MAX_FILE_AGE_MS = 7 * 24 * 60 * 60 * 1000
|
||||
const MAX_JOB_HISTORY = 20
|
||||
const COOLDOWN_MAP_LIMIT = 500
|
||||
|
||||
let tm = null
|
||||
let cachedConfig = null
|
||||
let cachedAt = 0
|
||||
let cachedStats = null
|
||||
let cachedProgress = null
|
||||
|
||||
/** 会话 → 冷却截止时间(epoch 毫秒)。 */
|
||||
const cooldownUntil = new Map()
|
||||
/** 正在处理的会话:同一会话同时只跑一个任务。 */
|
||||
const activeConversations = new Set()
|
||||
/** 正在处理的 `会话|链接`:避免同一条消息被重复投递时跑两遍。 */
|
||||
const activeJobs = new Set()
|
||||
|
||||
function safeLog(level, message) {
|
||||
try {
|
||||
const writer = tm && tm.log && tm.log[level]
|
||||
if (typeof writer === 'function') writer.call(tm.log, String(message))
|
||||
} catch {
|
||||
// 日志通道本身不可用时不能影响发送流程。
|
||||
}
|
||||
}
|
||||
|
||||
/** 错误类型化:日志只保留阶段与错误码,不写 URL、路径、标题。 */
|
||||
function errorType(error) {
|
||||
if (!error) return 'UNKNOWN'
|
||||
if (error.killed || error.signal) return 'TIMEOUT'
|
||||
// 数字退出码单独标成 EXIT_n,避免统计里只看到一个「2」。
|
||||
if (typeof error.code === 'number') return `EXIT_${error.code}`
|
||||
if (typeof error.code === 'string' && /^[A-Z0-9_]+$/.test(error.code)) return error.code
|
||||
if (error.name === 'Error') return 'ERROR'
|
||||
return String(error.name || 'ERROR')
|
||||
}
|
||||
|
||||
/** 去掉换行、链接与路径,只留 ≤60 字的短原因。 */
|
||||
function shortReason(input) {
|
||||
let text = String(input === null || input === undefined ? '' : input)
|
||||
.replace(/https?:\/\/\S+/gi, ' ')
|
||||
.replace(/[\r\n\t]+/g, ' ')
|
||||
.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s"'))]+)+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
text = text.replace(/^[::,,。;;-]+/, '').trim()
|
||||
text = text.replace(/title=[^,,))]+/gi, 'title=已隐藏')
|
||||
if (!text) return '未知原因'
|
||||
return text.slice(0, 60)
|
||||
}
|
||||
|
||||
function parseFailure(cause, type) {
|
||||
return { ok: false, message: `解析失败:${shortReason(cause)}`, errorType: type || 'PARSE' }
|
||||
}
|
||||
|
||||
function tooLargeMessage(sizeBytes) {
|
||||
const megabytes = Math.max(1, Math.ceil(Number(sizeBytes) / (1024 * 1024)))
|
||||
return `视频过大(${megabytes}MB),已跳过`
|
||||
}
|
||||
|
||||
function expandHome(value) {
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw) return ''
|
||||
if (raw === '~') return os.homedir()
|
||||
if (raw.startsWith('~/') || raw.startsWith('~' + path.sep)) {
|
||||
return path.join(os.homedir(), raw.slice(2))
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
function downloadsDir() {
|
||||
return path.join(tm.extension.dataDir, 'downloads')
|
||||
}
|
||||
|
||||
async function loadConfig() {
|
||||
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return cachedConfig
|
||||
let stored = null
|
||||
try {
|
||||
stored = await tm.storage.get(CONFIG_KEY)
|
||||
} catch (error) {
|
||||
safeLog('warn', `读取配置失败:${errorType(error)}`)
|
||||
}
|
||||
cachedConfig = normalizeConfig(stored)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
}
|
||||
|
||||
function dateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
function normalizeStats(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const lastJobs = Array.isArray(input.lastJobs)
|
||||
? input.lastJobs
|
||||
.filter((job) => job && typeof job === 'object')
|
||||
.slice(0, MAX_JOB_HISTORY)
|
||||
.map((job) => ({
|
||||
at: Number(job.at) || 0,
|
||||
awemeId: String(job.awemeId || '').slice(0, 32),
|
||||
ok: job.ok === true,
|
||||
stage: String(job.stage || '').slice(0, 20),
|
||||
errorType: String(job.errorType || '').slice(0, 24)
|
||||
}))
|
||||
: []
|
||||
const total = Math.max(0, Math.trunc(Number(input.todayTotal ?? input.todayCount) || 0))
|
||||
return {
|
||||
dateKey: typeof input.dateKey === 'string' ? input.dateKey.slice(0, 10) : '',
|
||||
todayTotal: total,
|
||||
todaySuccess: Math.max(0, Math.trunc(Number(input.todaySuccess) || 0)),
|
||||
todayFailure: Math.max(0, Math.trunc(Number(input.todayFailure) || 0)),
|
||||
lastJobs
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
if (cachedStats) return cachedStats
|
||||
let stored = null
|
||||
try {
|
||||
stored = await tm.storage.get(STATS_KEY)
|
||||
} catch (error) {
|
||||
safeLog('warn', `读取统计失败:${errorType(error)}`)
|
||||
}
|
||||
cachedStats = normalizeStats(stored)
|
||||
return cachedStats
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加一条任务记录。
|
||||
*
|
||||
* 统计里只允许出现 awemeId / 时间 / 阶段 / 成败 / 错误类型;URL、标题、作者、
|
||||
* 会话 id 都不写,避免把聊天内容沉淀成扩展数据。
|
||||
*/
|
||||
async function recordJob(job) {
|
||||
const now = Date.now()
|
||||
const current = await loadStats()
|
||||
const key = dateKey(now)
|
||||
const sameDay = current.dateKey === key
|
||||
const next = {
|
||||
dateKey: key,
|
||||
todayTotal: (sameDay ? current.todayTotal : 0) + 1,
|
||||
todaySuccess: (sameDay ? current.todaySuccess : 0) + (job.ok === true ? 1 : 0),
|
||||
todayFailure: (sameDay ? current.todayFailure : 0) + (job.ok === true ? 0 : 1),
|
||||
lastJobs: [
|
||||
{
|
||||
at: now,
|
||||
awemeId: String(job.awemeId || '').slice(0, 32),
|
||||
ok: job.ok === true,
|
||||
stage: String(job.stage || '').slice(0, 20),
|
||||
errorType: String(job.errorType || '').slice(0, 24)
|
||||
},
|
||||
...current.lastJobs
|
||||
].slice(0, MAX_JOB_HISTORY)
|
||||
}
|
||||
cachedStats = next
|
||||
try {
|
||||
await tm.storage.set(STATS_KEY, next)
|
||||
} catch (error) {
|
||||
safeLog('warn', `写入统计失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写「当前任务」快照,供配置页展示进度。
|
||||
*
|
||||
* 只保留一条最近任务:jobId 用事件 id(不可逆哈希),不含会话与正文。
|
||||
* 写失败只 warn,不能因为展示层异常影响发送。
|
||||
*/
|
||||
async function setProgress(patch) {
|
||||
const now = Date.now()
|
||||
const next = {
|
||||
...(cachedProgress || {}),
|
||||
...patch,
|
||||
updatedAt: now
|
||||
}
|
||||
if (!next.startedAt) next.startedAt = now
|
||||
cachedProgress = next
|
||||
const label = STAGE_LABELS[next.stage] || next.stage || ''
|
||||
safeLog('info', `任务进度:${label}${next.awemeId ? `(${next.awemeId})` : ''}`)
|
||||
try {
|
||||
await tm.storage.set(PROGRESS_KEY, next)
|
||||
} catch (error) {
|
||||
safeLog('warn', `写入进度失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function markCooldown(conversationId, seconds) {
|
||||
if (!conversationId || !(seconds > 0)) return
|
||||
cooldownUntil.set(conversationId, Date.now() + seconds * 1000)
|
||||
if (cooldownUntil.size > COOLDOWN_MAP_LIMIT) {
|
||||
const now = Date.now()
|
||||
for (const [key, until] of cooldownUntil) {
|
||||
if (until <= now) cooldownUntil.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
/** WindowsApps 下的是 Microsoft Store 别名,执行不成脚本,探测时要跳过。 */
|
||||
function isStoreAliasPath(value) {
|
||||
return /[\\/]WindowsApps[\\/]/i.test(String(value || ''))
|
||||
}
|
||||
|
||||
/** 在 PATH 中按顺序找第一个真实存在的可执行文件。 */
|
||||
function findOnPath(names) {
|
||||
const dirs = String(process.env.PATH || '')
|
||||
.split(path.delimiter)
|
||||
.filter((dir) => dir && !isStoreAliasPath(dir))
|
||||
for (const name of names) {
|
||||
for (const dir of dirs) {
|
||||
for (const ext of ['.exe', '.EXE', '']) {
|
||||
const candidate = path.join(dir, name + ext)
|
||||
try {
|
||||
if (fsSync.existsSync(candidate) && fsSync.statSync(candidate).isFile()) return candidate
|
||||
} catch {
|
||||
// 目录不可读就跳过,继续下一个候选。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 配置为空或是默认名时,按 py -3 → python 的顺序探测。 */
|
||||
function resolveWindowsPython(pythonPath) {
|
||||
const configured = expandHome(pythonPath)
|
||||
const looksDefault = !configured || configured === 'python' || configured === 'python3'
|
||||
if (!looksDefault && !isStoreAliasPath(configured)) {
|
||||
return { file: configured, prefixArgs: [] }
|
||||
}
|
||||
const py = findOnPath(['py'])
|
||||
if (py) return { file: py, prefixArgs: ['-3'] }
|
||||
const python = findOnPath(['python'])
|
||||
if (python) return { file: python, prefixArgs: [] }
|
||||
return { file: 'python', prefixArgs: [] }
|
||||
}
|
||||
|
||||
// Apple Silicon 上 x86_64 的 python3 会把 P_TRANSLATED 传给 Chrome,页面卡加载;
|
||||
// 优先用 venv 原生解释器并经 /usr/bin/arch -arm64 强制原生运行。
|
||||
function resolvePythonInvocation(pythonPath, scriptPath, args) {
|
||||
if (process.platform === 'win32') {
|
||||
const resolved = resolveWindowsPython(pythonPath)
|
||||
return {
|
||||
file: resolved.file,
|
||||
args: [...resolved.prefixArgs, scriptPath, ...args]
|
||||
}
|
||||
}
|
||||
if (process.platform !== 'darwin') {
|
||||
return { file: pythonPath, args: [scriptPath, ...args] }
|
||||
}
|
||||
const resolvedPython = pythonPath
|
||||
try {
|
||||
if (fsSync.existsSync('/usr/bin/arch')) {
|
||||
return {
|
||||
file: '/usr/bin/arch',
|
||||
args: ['-arm64', resolvedPython, scriptPath, ...args]
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 非标准系统环境缺少 /usr/bin/arch 时直接调用解释器。
|
||||
}
|
||||
return { file: resolvedPython, args: [scriptPath, ...args] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析可用的抖音 Cookie。
|
||||
*
|
||||
* 只认两个来源:调用方显式传入的 header,以及扩展私有目录里由用户配置生成的文件。
|
||||
* **不扫描桌面**——扩展不该去读用户没有明确交给它的文件。
|
||||
*/
|
||||
async function resolveCookieHeader(explicitHeader) {
|
||||
const direct = String(explicitHeader || '').trim()
|
||||
if (direct) return direct
|
||||
if (tm && tm.douyin && typeof tm.douyin.getCookie === 'function') {
|
||||
try {
|
||||
const fromHost = String((await tm.douyin.getCookie()) || '').trim()
|
||||
if (fromHost) return fromHost
|
||||
} catch {
|
||||
// 宿主未提供或读取失败时按「未配置」处理。
|
||||
}
|
||||
}
|
||||
// 优先用安全存储;未授权或不可用时再退回旧的扩展数据文件(迁移期兼容)。
|
||||
if (tm.secrets) {
|
||||
try {
|
||||
const stored = await tm.secrets.get(SECRET_COOKIE_KEY)
|
||||
if (stored) return String(stored).trim()
|
||||
} catch {
|
||||
// 未授予 secrets 权限或系统安全存储不可用:继续走兼容分支。
|
||||
}
|
||||
}
|
||||
try {
|
||||
const content = String(await fs.readFile(path.join(tm.extension.dataDir, 'douyin-cookie.txt'), 'utf8')).trim()
|
||||
if (content) return content
|
||||
} catch {
|
||||
// 未配置 Cookie 时走游客模式。
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 把旧的明文 Cookie 迁进安全存储,成功后删除明文文件。
|
||||
*
|
||||
* 只在「安全存储可用 + 用户已授权 secrets」时执行;否则保持原样,
|
||||
* 绝不把加密数据降级成明文,也不谎报迁移成功。
|
||||
*/
|
||||
async function migrateLegacyCookie() {
|
||||
if (!tm.secrets) return
|
||||
try {
|
||||
const existing = await tm.secrets.get(SECRET_COOKIE_KEY)
|
||||
if (existing) return
|
||||
const legacyPath = path.join(tm.extension.dataDir, 'douyin-cookie.txt')
|
||||
const legacy = String(await fs.readFile(legacyPath, 'utf8')).trim()
|
||||
if (!legacy) return
|
||||
await tm.secrets.set(SECRET_COOKIE_KEY, legacy)
|
||||
await fs.unlink(legacyPath).catch(() => undefined)
|
||||
tm.log.info('已把旧版明文 Cookie 迁入系统安全存储,并删除明文文件')
|
||||
} catch {
|
||||
// 未授权或不可用时静默保留旧文件,由页面提示用户重新填写。
|
||||
}
|
||||
}
|
||||
|
||||
function resolveScriptPath(value) {
|
||||
const expanded = expandHome(value)
|
||||
if (!expanded) return path.resolve(__dirname, '..', 'scripts', 'douyin.py')
|
||||
if (path.isAbsolute(expanded)) return expanded
|
||||
return path.resolve(__dirname, '..', expanded)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析脚本不随应用分发(来源与分发许可未确认),缺失时整条视频链路必须停住。
|
||||
* 缺失提示只打一次,避免每条消息刷日志。
|
||||
*/
|
||||
let scriptMissingLogged = false
|
||||
|
||||
function ensureScriptReady(config) {
|
||||
let ready = false
|
||||
try {
|
||||
ready = fsSync.existsSync(resolveScriptPath(config.scriptPath))
|
||||
} catch {
|
||||
ready = false
|
||||
}
|
||||
if (!ready && !scriptMissingLogged) {
|
||||
scriptMissingLogged = true
|
||||
safeLog('warn', '缺少解析脚本 scripts/douyin.py,视频处理已暂停;请按扩展说明自行提供后重启')
|
||||
}
|
||||
if (ready) scriptMissingLogged = false
|
||||
return ready
|
||||
}
|
||||
|
||||
/** 统一封装脚本调用:固定 cwd、超时、输出上限、UTF-8 与 macOS 原生 arm64 执行。 */
|
||||
async function runPython(args, timeoutMs, config) {
|
||||
// 首次启用时 dataDir 可能还没被创建;execFile 的 cwd 不存在会直接 ENOENT。
|
||||
await fs.mkdir(tm.extension.dataDir, { recursive: true })
|
||||
const pythonPath = expandHome(config.pythonPath)
|
||||
const scriptPath = resolveScriptPath(config.scriptPath)
|
||||
const invocation = resolvePythonInvocation(pythonPath, scriptPath, args)
|
||||
return execFileAsync(invocation.file, invocation.args, {
|
||||
cwd: tm.extension.dataDir,
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
env: {
|
||||
...process.env,
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUNBUFFERED: '1',
|
||||
DOUYIN_ARM64_READY: '1'
|
||||
},
|
||||
windowsHide: true
|
||||
})
|
||||
}
|
||||
|
||||
function describeExecError(error) {
|
||||
if (!error) return '失败'
|
||||
if (error.code === 'ENOENT') return '找不到 Python 可执行文件,请检查 Python 路径'
|
||||
if (error.killed || error.signal) return '超时'
|
||||
if (typeof error.code === 'number') return `脚本退出码 ${error.code}`
|
||||
if (typeof error.code === 'string' && /^E[A-Z]+$/.test(error.code)) {
|
||||
return `失败(${error.code})`
|
||||
}
|
||||
return '失败'
|
||||
}
|
||||
|
||||
async function resolveAndDownloadVideo(url, config, options = {}) {
|
||||
const dir = downloadsDir()
|
||||
try {
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
} catch (error) {
|
||||
return parseFailure('下载目录不可用(' + errorType(error) + ')', errorType(error))
|
||||
}
|
||||
|
||||
const args = [
|
||||
url,
|
||||
'-o',
|
||||
dir,
|
||||
'--wait',
|
||||
SCRIPT_WAIT_SECONDS,
|
||||
'--download-timeout',
|
||||
'90',
|
||||
'--json',
|
||||
'--debug',
|
||||
'--video-only',
|
||||
'--download'
|
||||
]
|
||||
if (config.quality) args.push('-q', config.quality)
|
||||
if (config.showUi) args.push('--show-ui')
|
||||
const cookieHeader = await resolveCookieHeader(options.cookieHeader)
|
||||
let temporaryCookieFile = ''
|
||||
let stdout = ''
|
||||
try {
|
||||
if (cookieHeader) {
|
||||
await fs.mkdir(tm.extension.dataDir, { recursive: true })
|
||||
temporaryCookieFile = path.join(
|
||||
tm.extension.dataDir,
|
||||
`.douyin-cookie-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`
|
||||
)
|
||||
await fs.writeFile(temporaryCookieFile, cookieHeader, { mode: 0o600, flag: 'wx' })
|
||||
await fs.chmod(temporaryCookieFile, 0o600)
|
||||
args.push('--cookie-file', temporaryCookieFile)
|
||||
}
|
||||
|
||||
const result = await runPython(args, DOWNLOAD_AND_RESOLVE_TIMEOUT_MS, config)
|
||||
stdout = String(result.stdout || '')
|
||||
} catch (error) {
|
||||
stdout = String((error && error.stdout) || '')
|
||||
if (!stdout.trim()) {
|
||||
// 别把失败统一报成「Cookie 不可用」,否则 ENOENT 和脚本退出码都被盖掉。
|
||||
const reason = describeExecError(error)
|
||||
const withMode = temporaryCookieFile ? `${reason}(Cookie 模式)` : reason
|
||||
return parseFailure(withMode, temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error))
|
||||
}
|
||||
} finally {
|
||||
if (temporaryCookieFile) {
|
||||
try {
|
||||
await fs.unlink(temporaryCookieFile)
|
||||
} catch {
|
||||
// 解析结束后清除临时凭证文件。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = parseDownloadedResult(stdout)
|
||||
if (!parsed) {
|
||||
const failure = /✗\s*(?:失败[::])?\s*(.+)/.exec(stdout)
|
||||
return parseFailure(failure ? failure[1] : '脚本输出无法识别', 'INVALID_OUTPUT')
|
||||
}
|
||||
if (!parsed.ok) return parseFailure(parsed.message, parsed.errorType)
|
||||
|
||||
let stat = null
|
||||
try {
|
||||
stat = await fs.stat(parsed.path)
|
||||
} catch {
|
||||
return parseFailure('下载文件不存在', 'MISSING_FILE')
|
||||
}
|
||||
if (!stat.isFile()) return parseFailure('下载结果不是文件', 'NOT_A_FILE')
|
||||
if (isFileTooLarge(stat.size, config.maxFileMB)) {
|
||||
return { ok: false, message: tooLargeMessage(stat.size), errorType: 'TOO_LARGE' }
|
||||
}
|
||||
return { ok: true, path: parsed.path, size: stat.size, meta: parsed.meta }
|
||||
}
|
||||
|
||||
let lastSendAt = 0
|
||||
|
||||
async function waitSendSlot() {
|
||||
const elapsed = Date.now() - lastSendAt
|
||||
if (lastSendAt > 0 && elapsed < SEND_GAP_MS) {
|
||||
await sleep(SEND_GAP_MS - elapsed)
|
||||
}
|
||||
lastSendAt = Date.now()
|
||||
}
|
||||
|
||||
async function sendText(to, text, dedupeKey, stage) {
|
||||
try {
|
||||
await waitSendSlot()
|
||||
await tm.wechat.send({ to, text, dedupeKey })
|
||||
lastSendAt = Date.now()
|
||||
return true
|
||||
} catch (error) {
|
||||
safeLog('warn', `未完成:阶段=${stage || 'text'} 错误=${errorType(error)}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 发视频:走宿主 video 通道,`dedupeKey` 保证同一条消息只发一次。 */
|
||||
async function sendVideo(event, filePath) {
|
||||
try {
|
||||
await waitSendSlot()
|
||||
await tm.wechat.send({
|
||||
type: 'video',
|
||||
to: event.conversationId,
|
||||
path: filePath,
|
||||
dedupeKey: `${event.eventId}:video`
|
||||
})
|
||||
lastSendAt = Date.now()
|
||||
return true
|
||||
} catch (error) {
|
||||
safeLog('warn', `未完成:阶段=send 错误=${errorType(error)}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function reportFailure(event, config, message) {
|
||||
if (!config.errorReply) return
|
||||
await sendText(event.conversationId, message, `${event.eventId}:error`, 'reply')
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次完整任务。
|
||||
*
|
||||
* `stage` 记录失败发生的位置:`resolveDownload` / `send` / `done`。
|
||||
* 进度快照与统计都会落盘;失败原因只保留错误类型,不写 URL / 路径 / 标题。
|
||||
*/
|
||||
async function processLink(event, config, url, options = {}) {
|
||||
if (!ensureScriptReady(config)) return
|
||||
const jobId = event.eventId
|
||||
let awemeId = ''
|
||||
let stage = 'accepted'
|
||||
let ok = false
|
||||
let failureCode = ''
|
||||
let failureMessage = ''
|
||||
|
||||
try {
|
||||
stage = 'resolveDownload'
|
||||
await setProgress({ jobId, awemeId, stage, status: 'running' })
|
||||
const downloaded = await resolveAndDownloadVideo(url, config, options)
|
||||
if (!downloaded.ok) {
|
||||
failureCode = downloaded.errorType || 'DOWNLOAD_FAILED'
|
||||
failureMessage = downloaded.message
|
||||
return
|
||||
}
|
||||
const meta = downloaded.meta
|
||||
awemeId = String(meta.aweme_id || '')
|
||||
|
||||
stage = 'send'
|
||||
await setProgress({ jobId, awemeId, stage, status: 'running' })
|
||||
const sent = await sendVideo(event, downloaded.path)
|
||||
if (!sent) {
|
||||
failureCode = 'SEND_FAILED'
|
||||
failureMessage = '视频发送失败'
|
||||
return
|
||||
}
|
||||
|
||||
ok = true
|
||||
stage = 'done'
|
||||
// 冷却只在视频真正发出去之后才写入,失败不占用下一次机会。
|
||||
markCooldown(event.conversationId, config.cooldownSeconds)
|
||||
} catch (error) {
|
||||
failureCode = errorType(error)
|
||||
failureMessage = '处理异常'
|
||||
safeLog('warn', `处理异常:阶段=${stage} 错误=${failureCode}`)
|
||||
} finally {
|
||||
if (ok) {
|
||||
await setProgress({ jobId, awemeId, stage: 'done', status: 'done', errorType: '' })
|
||||
} else {
|
||||
if (failureMessage && options.replyOnFailure !== false) {
|
||||
await reportFailure(event, config, failureMessage)
|
||||
}
|
||||
await setProgress({
|
||||
jobId,
|
||||
awemeId,
|
||||
stage: stage === 'accepted' ? 'resolve' : stage,
|
||||
status: 'failed',
|
||||
errorType: failureCode || 'FAILED',
|
||||
errorMessage: failureMessage ? shortReason(failureMessage) : ''
|
||||
})
|
||||
safeLog('warn', `未完成:阶段=${stage} 错误=${failureCode || 'FAILED'}`)
|
||||
}
|
||||
await recordJob({
|
||||
awemeId,
|
||||
ok,
|
||||
stage: ok ? 'done' : stage,
|
||||
errorType: ok ? '' : failureCode || 'FAILED'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEvent(event) {
|
||||
try {
|
||||
const config = await loadConfig()
|
||||
if (!ensureScriptReady(config)) return
|
||||
const decision = shouldHandle(event, config, cooldownUntil, Date.now())
|
||||
if (!decision.handle) return
|
||||
|
||||
const conversationId = event.conversationId
|
||||
const jobKey = `${conversationId}|${decision.url}`
|
||||
if (activeConversations.has(conversationId) || activeJobs.has(jobKey)) return
|
||||
|
||||
activeConversations.add(conversationId)
|
||||
activeJobs.add(jobKey)
|
||||
try {
|
||||
await setProgress({
|
||||
jobId: event.eventId,
|
||||
stage: 'accepted',
|
||||
status: 'running',
|
||||
startedAt: Date.now(),
|
||||
awemeId: '',
|
||||
errorType: '',
|
||||
errorMessage: ''
|
||||
})
|
||||
// 先回执再干活:解析/下载要十几秒,用户不该靠猜。
|
||||
if (config.ackText) {
|
||||
await sendText(conversationId, config.ackText, `${event.eventId}:ack`, 'ack')
|
||||
}
|
||||
await processLink(event, config, decision.url)
|
||||
} finally {
|
||||
activeConversations.delete(conversationId)
|
||||
activeJobs.delete(jobKey)
|
||||
}
|
||||
} catch (error) {
|
||||
safeLog('warn', `事件处理失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
let lastTestRequestId = ''
|
||||
let testInFlight = false
|
||||
let pendingTestRequest = null
|
||||
|
||||
async function writeTestResult(result) {
|
||||
try {
|
||||
await tm.storage.set(TEST_RESULT_KEY, result)
|
||||
} catch (error) {
|
||||
safeLog('warn', `写入测试结果失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置页「测试发送」。
|
||||
*
|
||||
* 测试请求通过宿主一次性送达,不落入扩展持久化存储。
|
||||
*/
|
||||
async function pollTestRequest() {
|
||||
if (testInFlight) return
|
||||
const request = pendingTestRequest
|
||||
pendingTestRequest = null
|
||||
if (!request || typeof request !== 'object') return
|
||||
const id = String(request.id || '').trim()
|
||||
if (!id || id === lastTestRequestId) return
|
||||
lastTestRequestId = id
|
||||
const to = String(request.to || '').trim()
|
||||
const text = String(request.text || '').trim()
|
||||
|
||||
if (!to || !text) {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: '测试请求缺少群聊或链接',
|
||||
at: Date.now()
|
||||
})
|
||||
return
|
||||
}
|
||||
if (activeConversations.has(to)) {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: '该群正在执行其他任务,请稍后重试',
|
||||
at: Date.now()
|
||||
})
|
||||
return
|
||||
}
|
||||
const url = extractDouyinUrl(text)
|
||||
if (!url) {
|
||||
await writeTestResult({ id, status: 'failed', message: '没有识别到抖音链接', at: Date.now() })
|
||||
return
|
||||
}
|
||||
|
||||
const config = await loadConfig()
|
||||
const cookieHeader = request.cookieHeader ? String(request.cookieHeader) : ''
|
||||
testInFlight = true
|
||||
activeConversations.add(to)
|
||||
try {
|
||||
await writeTestResult({ id, status: 'running', message: '已开始解析…', at: Date.now() })
|
||||
await setProgress({
|
||||
jobId: `test:${id}`,
|
||||
stage: 'accepted',
|
||||
status: 'running',
|
||||
startedAt: Date.now(),
|
||||
awemeId: '',
|
||||
errorType: '',
|
||||
errorMessage: ''
|
||||
})
|
||||
// 测试路径不发回执:结果直接显示在配置页,视频发到目标群。
|
||||
await processLink(
|
||||
{
|
||||
eventId: `test:${id}`,
|
||||
conversationId: to,
|
||||
isGroup: to.endsWith('@chatroom'),
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text,
|
||||
mentionsMe: true
|
||||
},
|
||||
config,
|
||||
url,
|
||||
{ replyOnFailure: false, cookieHeader }
|
||||
)
|
||||
const progress = cachedProgress || {}
|
||||
if (progress.status === 'done') {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'done',
|
||||
message: '测试发送完成:视频已发到该群',
|
||||
at: Date.now()
|
||||
})
|
||||
} else {
|
||||
const label = STAGE_LABELS[progress.stage] || progress.stage || '未知阶段'
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: `测试发送失败:${label}${progress.errorType ? `(${progress.errorType})` : ''}${progress.errorMessage ? `:${progress.errorMessage}` : ''}`,
|
||||
at: Date.now()
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: `测试发送异常:${errorType(error)}`,
|
||||
at: Date.now()
|
||||
})
|
||||
} finally {
|
||||
activeConversations.delete(to)
|
||||
testInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理下载目录:只保留最近 20 个文件,并删除 7 天前的文件。
|
||||
*
|
||||
* 清理失败不影响发送能力,逐条 try/catch,最坏情况是目录继续变大。
|
||||
*/
|
||||
async function cleanupDownloads() {
|
||||
const dir = downloadsDir()
|
||||
let entries = []
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
const files = []
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue
|
||||
const full = path.join(dir, entry.name)
|
||||
try {
|
||||
const stat = await fs.stat(full)
|
||||
files.push({ full, mtime: stat.mtimeMs })
|
||||
} catch {
|
||||
// 枚举期间被删除或无法访问,跳过即可。
|
||||
}
|
||||
}
|
||||
|
||||
files.sort((left, right) => right.mtime - left.mtime)
|
||||
const now = Date.now()
|
||||
for (let index = 0; index < files.length; index += 1) {
|
||||
const fresh = now - files[index].mtime <= MAX_FILE_AGE_MS
|
||||
if (index < KEEP_RECENT_FILES && fresh) continue
|
||||
try {
|
||||
await fs.unlink(files[index].full)
|
||||
} catch {
|
||||
// 单个文件删不掉就留着,下一次启动再试。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function activate(api) {
|
||||
tm = api
|
||||
// 宿主对 handler 有 10 秒超时;脚本可能要跑几分钟,所以这里只排队不等待。
|
||||
tm.events.on('message.received', (event) => {
|
||||
void handleEvent(event)
|
||||
})
|
||||
void cleanupDownloads()
|
||||
globalThis.__tmTestSend = async (request) => {
|
||||
pendingTestRequest = request
|
||||
await pollTestRequest()
|
||||
return { accepted: true }
|
||||
}
|
||||
tm.log.info('抖音搬运已加载')
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 抖音分享链接解析的纯函数层。
|
||||
*
|
||||
* 这一层不碰文件系统、不启子进程、不读时钟:所有输入都从参数进来,
|
||||
* 所有输出都可序列化,便于在 `node:test` 里离线断言。
|
||||
*
|
||||
* 单位约定:
|
||||
* - 时间一律 epoch 毫秒;
|
||||
* - 文件大小一律字节,配置里的上限单位是 MB(1 MB = 1024 * 1024 B)。
|
||||
*/
|
||||
|
||||
/** 宿主发送通道的硬上限:单个媒体文件 100 MB,配置不允许突破。 */
|
||||
const HOST_MAX_FILE_MB = 100
|
||||
|
||||
/** 解析脚本的默认位置(相对于扩展目录,支持自定义绝对路径或 `~/`)。 */
|
||||
const DEFAULT_SCRIPT_PATH = 'scripts/douyin.py'
|
||||
|
||||
/** 画质白名单;空串表示「最高」,不传 `-q` 给脚本。 */
|
||||
const QUALITY_VALUES = ['', '1080', '720', '540']
|
||||
|
||||
// Windows 的 python3.exe 通常是 Microsoft Store 别名,执行不成脚本。
|
||||
const DEFAULT_PYTHON_PATH =
|
||||
typeof process !== 'undefined' && process.platform === 'win32' ? 'python' : 'python3'
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: 1,
|
||||
enabled: false,
|
||||
pythonPath: DEFAULT_PYTHON_PATH,
|
||||
scriptPath: DEFAULT_SCRIPT_PATH,
|
||||
quality: '720',
|
||||
/** 排障开关:显示浏览器窗口以观察实际页面状态。 */
|
||||
showUi: false,
|
||||
/** 命中后先回一句,避免用户不知道是否收到;空串表示不回复。 */
|
||||
ackText: '收到,正在解析,请稍候…',
|
||||
sendCaption: false,
|
||||
captionTemplate: '{author}:{title}',
|
||||
errorReply: true,
|
||||
includeDirect: false,
|
||||
groups: [],
|
||||
cooldownSeconds: 60,
|
||||
maxFileMB: HOST_MAX_FILE_MB
|
||||
}
|
||||
|
||||
/** 分享链接只认这三种形态;短链的 id 是字母数字,长链只认数字作品 id。 */
|
||||
const DOUYIN_URL_PATTERN =
|
||||
/https?:\/\/(?:v\.douyin\.com\/[A-Za-z0-9_-]{1,64}|(?:www\.)?douyin\.com\/(?:video|note)\/\d{1,32})/i
|
||||
|
||||
/** 中文文案里链接后面常跟这些符号,属于分隔符不属于链接。 */
|
||||
const TRAILING_PUNCTUATION = /[)\]}>,.;:!?'"`。,、;:!?…)】》〉」』”’]+$/
|
||||
|
||||
const CAPTION_MAX_LENGTH = 200
|
||||
const GROUP_MAX_COUNT = 200
|
||||
|
||||
function clampInt(value, min, max, fallback) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
const rounded = Math.trunc(numeric)
|
||||
if (rounded < min) return min
|
||||
if (rounded > max) return max
|
||||
return rounded
|
||||
}
|
||||
|
||||
function normalizeQuality(value) {
|
||||
if (value === null || value === undefined) return DEFAULT_CONFIG.quality
|
||||
const text = String(value).trim()
|
||||
// 数值型画质(720)与字符串画质('720')同义;`''` 表示最高。
|
||||
if (text === '') return ''
|
||||
return QUALITY_VALUES.includes(text) ? text : DEFAULT_CONFIG.quality
|
||||
}
|
||||
|
||||
function normalizeGroups(value) {
|
||||
const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\s,]+/) : []
|
||||
const result = []
|
||||
for (const item of list) {
|
||||
const id = String(item === null || item === undefined ? '' : item).trim()
|
||||
if (!id) continue
|
||||
if (result.includes(id)) continue
|
||||
result.push(id.slice(0, 128))
|
||||
if (result.length >= GROUP_MAX_COUNT) break
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function normalizeText(value, fallback, maxLength) {
|
||||
const text = typeof value === 'string' ? value.trim() : ''
|
||||
return (text || fallback).slice(0, maxLength)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把任意来源(存储、表单、旧版本)的配置收敛成可执行形态。
|
||||
*
|
||||
* 契约:**永不抛错**,字段缺失或非法时回落到默认值;返回对象永远是全新的,
|
||||
* 调用方可以直接持有并修改,不会污染 `DEFAULT_CONFIG`。
|
||||
*/
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
return {
|
||||
configVersion: 1,
|
||||
enabled: input.enabled === true,
|
||||
pythonPath: normalizeText(input.pythonPath, DEFAULT_CONFIG.pythonPath, 512),
|
||||
scriptPath: normalizeText(input.scriptPath, DEFAULT_SCRIPT_PATH, 512),
|
||||
quality: normalizeQuality(input.quality),
|
||||
showUi: input.showUi === true,
|
||||
ackText:
|
||||
input.ackText === undefined
|
||||
? DEFAULT_CONFIG.ackText
|
||||
: String(input.ackText).trim().slice(0, 200),
|
||||
sendCaption: input.sendCaption === true,
|
||||
captionTemplate: normalizeText(input.captionTemplate, DEFAULT_CONFIG.captionTemplate, 200),
|
||||
errorReply: input.errorReply !== false,
|
||||
includeDirect: input.includeDirect === true,
|
||||
groups: normalizeGroups(input.groups),
|
||||
cooldownSeconds: clampInt(input.cooldownSeconds, 0, 3600, DEFAULT_CONFIG.cooldownSeconds),
|
||||
maxFileMB: clampInt(input.maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从一段文本里取第一个抖音分享链接。
|
||||
*
|
||||
* 输入可能是裸链接,也可能是「复制打开抖音…」整段文案;返回值已去掉尾随标点,
|
||||
* 查询串与 fragment 一并丢弃(短链换长链由脚本完成,扩展不参与)。
|
||||
*
|
||||
* 返回 `null` 表示没有可识别的抖音作品链接;`javascript:` / `ftp:` / 非抖音域名
|
||||
* 一律不匹配。
|
||||
*/
|
||||
function extractDouyinUrl(text) {
|
||||
const source = typeof text === 'string' ? text : ''
|
||||
if (!source) return null
|
||||
const matched = DOUYIN_URL_PATTERN.exec(source)
|
||||
if (!matched) return null
|
||||
const cleaned = matched[0].replace(TRAILING_PUNCTUATION, '')
|
||||
return cleaned || null
|
||||
}
|
||||
|
||||
/** 从 `start` 处的 `[` 找到配对的 `]`,跳过字符串字面量与转义;失败返回 -1。 */
|
||||
function findArrayEnd(text, start) {
|
||||
let depth = 0
|
||||
let inString = false
|
||||
let escaped = false
|
||||
for (let index = start; index < text.length; index += 1) {
|
||||
const char = text[index]
|
||||
if (inString) {
|
||||
if (escaped) escaped = false
|
||||
else if (char === '\\') escaped = true
|
||||
else if (char === '"') inString = false
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
inString = true
|
||||
continue
|
||||
}
|
||||
if (char === '[') {
|
||||
depth += 1
|
||||
continue
|
||||
}
|
||||
if (char === ']') {
|
||||
depth -= 1
|
||||
if (depth === 0) return index
|
||||
if (depth < 0) return -1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function isResolveResultList(value) {
|
||||
if (!Array.isArray(value) || value.length === 0) return false
|
||||
return value.every(
|
||||
(item) =>
|
||||
item &&
|
||||
typeof item === 'object' &&
|
||||
typeof item.url === 'string' &&
|
||||
typeof item.ok === 'boolean'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 stdout 中取第一个结构合法的结果数组。
|
||||
*
|
||||
* 按结构判定(非空数组、每项含 `url:string` 与 `ok:boolean`),跳过进度行里的
|
||||
* `[1]` 与嵌套的 `quality_options`;空数组与非法 JSON 返回 `null`。
|
||||
*/
|
||||
function parseResolveJson(stdout) {
|
||||
const text = typeof stdout === 'string' ? stdout : ''
|
||||
if (!text) return null
|
||||
for (let start = 0; start < text.length; start += 1) {
|
||||
if (text[start] !== '[') continue
|
||||
const end = findArrayEnd(text, start)
|
||||
if (end < 0) continue
|
||||
try {
|
||||
const value = JSON.parse(text.slice(start, end + 1))
|
||||
if (isResolveResultList(value)) return value
|
||||
} catch {
|
||||
// 这个 `[` 不是数组起点(可能在字符串里),继续向后找。
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 从下载输出里取最后一个 `✅` 后面的绝对路径。
|
||||
*
|
||||
* 脚本对视频打印 ` ✅ /abs/xxx.mp4`,对图集打印目录后面再跟一段「(N 个文件)」。
|
||||
* 路径里可能含空格(作者名与标题),所以只按行首标记切分,不按空白切分。
|
||||
*
|
||||
* 返回 `null` 表示没有可用的绝对路径。
|
||||
*/
|
||||
function parseSavedPath(stdout) {
|
||||
const text = typeof stdout === 'string' ? stdout : ''
|
||||
if (!text) return null
|
||||
const lines = text.split(/\r?\n/)
|
||||
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
||||
const marker = lines[index].indexOf('✅')
|
||||
if (marker < 0) continue
|
||||
let rest = lines[index].slice(marker + 1).trim()
|
||||
// 去掉尾部的「(N 个文件)」之类附注,它不属于路径。
|
||||
rest = rest.replace(/\s*[((][^(())]*[))]\s*$/, '').trim()
|
||||
if (!rest) continue
|
||||
if (!isAbsoluteMediaPath(rest)) continue
|
||||
return rest
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 绝对路径判定:POSIX `/x`、Windows `C:\x` / `C:/x`、UNC `\\server\share`。
|
||||
function isAbsoluteMediaPath(value) {
|
||||
if (typeof value !== 'string') return false
|
||||
const text = value.trim()
|
||||
if (!text) return false
|
||||
if (text.startsWith('/')) return true // POSIX
|
||||
if (/^[A-Za-z]:[\\/]/.test(text)) return true // C:\ 或 C:/
|
||||
if (text.startsWith('\\\\')) return true // UNC \\server\share
|
||||
return false
|
||||
}
|
||||
|
||||
function parseDownloadedResult(stdout) {
|
||||
const results = parseResolveJson(stdout)
|
||||
const video = pickVideoResult(results)
|
||||
if (video) {
|
||||
const saved = Array.isArray(video.saved)
|
||||
? video.saved.find((value) => isAbsoluteMediaPath(value))
|
||||
: null
|
||||
if (saved) return { ok: true, meta: video, path: saved }
|
||||
if (video.error) return { ok: false, message: video.error, errorType: 'DOWNLOAD_FAILED' }
|
||||
return null
|
||||
}
|
||||
|
||||
const image = results && results.find((item) => item && item.ok === true && item.type === 'image')
|
||||
if (image) return { ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
|
||||
|
||||
const failure = results && results.find((item) => item && item.ok === false)
|
||||
if (failure && failure.error) {
|
||||
return {
|
||||
ok: false,
|
||||
message: failure.error,
|
||||
errorType: failure.aweme_id ? 'DOWNLOAD_FAILED' : 'RESOLVE_FAILED'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 按模板渲染文案。
|
||||
*
|
||||
* 已知变量 `{author}` / `{title}` / `{awemeId}` 会被替换;未知变量原样保留,
|
||||
* 让用户能看见自己写错了什么。结果 trim 后截断到 200 字。
|
||||
*/
|
||||
function renderCaption(template, meta) {
|
||||
const source = typeof template === 'string' ? template : ''
|
||||
const data = meta && typeof meta === 'object' ? meta : {}
|
||||
const values = {
|
||||
author: data.author === null || data.author === undefined ? '' : String(data.author),
|
||||
title: data.title === null || data.title === undefined ? '' : String(data.title),
|
||||
awemeId: data.awemeId === null || data.awemeId === undefined ? '' : String(data.awemeId)
|
||||
}
|
||||
// 已知变量即使取不到值也替换成空串:正文里留下 `{author}` 会被当成程序缺陷。
|
||||
const rendered = source.replace(/\{(author|title|awemeId)\}/g, (whole, name) => values[name])
|
||||
return rendered.trim().slice(0, CAPTION_MAX_LENGTH)
|
||||
}
|
||||
|
||||
function inScope(event, config) {
|
||||
if (event.isGroup) {
|
||||
return config.groups.length === 0 || config.groups.includes(event.conversationId)
|
||||
}
|
||||
return config.includeDirect === true
|
||||
}
|
||||
|
||||
function readCooldown(cooldownUntil, conversationId) {
|
||||
if (!cooldownUntil || !conversationId) return 0
|
||||
const value =
|
||||
typeof cooldownUntil.get === 'function'
|
||||
? cooldownUntil.get(conversationId)
|
||||
: cooldownUntil[conversationId]
|
||||
const numeric = Number(value)
|
||||
return Number.isFinite(numeric) && numeric > 0 ? numeric : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一条事件是否该进入处理流程。
|
||||
*
|
||||
* 判定顺序固定:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
|
||||
* `reason` 的取值集合固定为
|
||||
* `disabled | self | type | mention | no_link | scope | cooldown | ok`。
|
||||
*
|
||||
* `url` 只要提取成功就会返回,即使后续被范围或冷却拦下,便于调用方写日志。
|
||||
*/
|
||||
function shouldHandle(event, config, cooldownUntil, now) {
|
||||
const settings = normalizeConfig(config)
|
||||
if (!settings.enabled) return { handle: false, url: null, reason: 'disabled' }
|
||||
if (!event || typeof event !== 'object') return { handle: false, url: null, reason: 'no_link' }
|
||||
if (event.isSelf) return { handle: false, url: null, reason: 'self' }
|
||||
if (event.type !== 'text') return { handle: false, url: null, reason: 'type' }
|
||||
if (!event.mentionsMe) return { handle: false, url: null, reason: 'mention' }
|
||||
|
||||
const url = extractDouyinUrl(event.text)
|
||||
if (!url) return { handle: false, url: null, reason: 'no_link' }
|
||||
if (!inScope(event, settings)) return { handle: false, url, reason: 'scope' }
|
||||
|
||||
const until = readCooldown(cooldownUntil, event.conversationId)
|
||||
const timestamp = Number.isFinite(Number(now)) ? Number(now) : Date.now()
|
||||
if (timestamp < until) return { handle: false, url, reason: 'cooldown' }
|
||||
|
||||
return { handle: true, url, reason: 'ok' }
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件是否不该发送。
|
||||
*
|
||||
* 返回 true 的三种情况:超过配置上限、字节数非法、文件为空。
|
||||
* 上限本身被收敛到 1–100 MB,宿主 100 MB 的硬限制不会被配置绕过。
|
||||
*/
|
||||
function isFileTooLarge(sizeBytes, maxFileMB) {
|
||||
const limitMB = clampInt(maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
|
||||
const size = Number(sizeBytes)
|
||||
if (!Number.isFinite(size) || size <= 0) return true
|
||||
return size > limitMB * 1024 * 1024
|
||||
}
|
||||
|
||||
/**
|
||||
* 从解析结果里挑第一条可下载的视频。
|
||||
*
|
||||
* 图集(`type === 'image'`)与失败项都不算;没有视频时返回 `null`,
|
||||
* 由调用方决定回复「暂不支持图集」还是通用失败文案。
|
||||
*/
|
||||
function pickVideoResult(results) {
|
||||
if (!Array.isArray(results)) return null
|
||||
for (const item of results) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if (item.ok !== true) continue
|
||||
if (item.type !== 'video') continue
|
||||
return item
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_CONFIG,
|
||||
normalizeConfig,
|
||||
extractDouyinUrl,
|
||||
parseResolveJson,
|
||||
parseSavedPath,
|
||||
isAbsoluteMediaPath,
|
||||
parseDownloadedResult,
|
||||
renderCaption,
|
||||
shouldHandle,
|
||||
isFileTooLarge,
|
||||
pickVideoResult
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.douyin-sender",
|
||||
"name": "抖音视频搬运",
|
||||
"version": "1.0.5",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。需要本机 Python、Chrome 与解析脚本。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"secrets",
|
||||
"messages.subscribe",
|
||||
"contacts.list",
|
||||
"wechat.send.video",
|
||||
"wechat.send.text",
|
||||
"storage"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": [
|
||||
"text"
|
||||
],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": true,
|
||||
"includeSelf": false
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "settings",
|
||||
"title": "抖音解析设置"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
用 urllib 从镜像拉 wheel,再交给 pip 本地安装 —— 绕开 pip 自己那层网络栈。
|
||||
|
||||
python fetch_wheels.py <目标目录> [包名 ...]
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
MIRRORS = [
|
||||
"https://pypi.tuna.tsinghua.edu.cn/simple",
|
||||
"https://mirrors.aliyun.com/pypi/simple",
|
||||
]
|
||||
|
||||
DEFAULT_PACKAGES = ["requests", "playwright"]
|
||||
|
||||
WHEEL_RE = re.compile(r'href="([^"#]+\.whl)[^"]*"')
|
||||
VER_RE = re.compile(r'-(\d+(?:\.\d+)*)')
|
||||
|
||||
# 部分镜像对浏览器 UA 返回 403,用 pip 自己的才放行。
|
||||
USER_AGENT = "pip/26.1.2"
|
||||
|
||||
|
||||
def page_links(mirror: str, package: str) -> list[str]:
|
||||
"""索引页 href 是相对路径,用 urljoin 归一。"""
|
||||
url = f"{mirror}/{package}/"
|
||||
ctx = ssl.create_default_context()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
|
||||
html = resp.read().decode("utf-8", "replace")
|
||||
return [urllib.parse.urljoin(url, href) for href in WHEEL_RE.findall(html)]
|
||||
|
||||
|
||||
def wheel_key(name: str) -> tuple:
|
||||
"""排序键:越靠后越优先。"""
|
||||
base = name.rsplit("/", 1)[-1].lower()
|
||||
pure = 1 if ("none-any" in base) else 0
|
||||
win_amd64 = 1 if "win_amd64" in base else 0
|
||||
cp313 = 1 if "cp313" in base else 0
|
||||
abi3 = 1 if "abi3" in base else 0
|
||||
return (pure, win_amd64, abi3, cp313)
|
||||
|
||||
|
||||
def version_key(url: str) -> tuple:
|
||||
"""从文件名取版本号数字段。"""
|
||||
m = VER_RE.search(url.rsplit("/", 1)[-1])
|
||||
if not m:
|
||||
return ()
|
||||
return tuple(int(part) for part in m.group(1).split("."))
|
||||
|
||||
|
||||
def pick(links: list[str]) -> str | None:
|
||||
"""挑一个 Windows x64 / cp313 可用的 wheel。"""
|
||||
candidates = []
|
||||
for link in links:
|
||||
low = link.lower()
|
||||
if "macosx" in low or "manylinux" in low or "musllinux" in low:
|
||||
continue
|
||||
if "win32" in low or "win_arm64" in low:
|
||||
continue
|
||||
if "none-any.whl" in low or "win_amd64.whl" in low:
|
||||
candidates.append(link)
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda url: (wheel_key(url), version_key(url)))
|
||||
return candidates[-1]
|
||||
|
||||
|
||||
def download(url: str, dest_dir: Path) -> Path:
|
||||
name = url.rsplit("/", 1)[-1].split("#")[0]
|
||||
target = dest_dir / name
|
||||
if target.exists() and target.stat().st_size > 0:
|
||||
print(f" cached {name}")
|
||||
return target
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
data = resp.read()
|
||||
target.write_bytes(data)
|
||||
print(f" saved {name} ({len(data)//1024} KB)")
|
||||
return target
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return 2
|
||||
dest = Path(sys.argv[1]).expanduser()
|
||||
packages = sys.argv[2:] or DEFAULT_PACKAGES
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
failed = []
|
||||
for package in packages:
|
||||
print(f"[{package}]")
|
||||
chosen = None
|
||||
for mirror in MIRRORS:
|
||||
try:
|
||||
links = page_links(mirror, package)
|
||||
except Exception as exc:
|
||||
print(f" mirror {mirror} failed: {type(exc).__name__}")
|
||||
continue
|
||||
chosen = pick(links)
|
||||
if chosen:
|
||||
print(f" mirror {mirror}")
|
||||
break
|
||||
if not chosen:
|
||||
print(" no compatible wheel found")
|
||||
failed.append(package)
|
||||
continue
|
||||
try:
|
||||
download(chosen, dest)
|
||||
except Exception as exc:
|
||||
print(f" download failed: {type(exc).__name__} {exc}")
|
||||
failed.append(package)
|
||||
|
||||
if failed:
|
||||
print("FAILED: " + ", ".join(failed))
|
||||
return 1
|
||||
print(f"OK -> {dest}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,439 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 纯函数层测试:不联网、不启动 python、不读真实文件。
|
||||
* 运行:node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
|
||||
*/
|
||||
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import douyin from '../lib/douyin.js'
|
||||
|
||||
const {
|
||||
DEFAULT_CONFIG,
|
||||
normalizeConfig,
|
||||
extractDouyinUrl,
|
||||
parseResolveJson,
|
||||
parseSavedPath,
|
||||
isAbsoluteMediaPath,
|
||||
parseDownloadedResult,
|
||||
renderCaption,
|
||||
shouldHandle,
|
||||
isFileTooLarge,
|
||||
pickVideoResult
|
||||
} = douyin
|
||||
|
||||
const SHORT_URL = 'https://v.douyin.com/fixture123'
|
||||
const SHORT_TEXT_URL = 'https://v.douyin.com/fixture123/'
|
||||
const VIDEO_URL = 'https://www.douyin.com/video/7300000000000000001'
|
||||
const NOTE_URL = 'https://douyin.com/note/7300000000000000002'
|
||||
|
||||
function makeEvent(overrides = {}) {
|
||||
return {
|
||||
eventId: 'message:fixture-1',
|
||||
accountId: 'wxid_fixture',
|
||||
conversationId: 'fixture-room@chatroom',
|
||||
messageId: 'local-1',
|
||||
senderId: 'wxid_fixture',
|
||||
senderName: '张三',
|
||||
isGroup: true,
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text: `@李四 ${SHORT_TEXT_URL}`,
|
||||
mentionsMe: true,
|
||||
timestamp: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function makeConfig(overrides = {}) {
|
||||
return normalizeConfig({ enabled: true, ...overrides })
|
||||
}
|
||||
|
||||
test('从裸短链里提取链接', () => {
|
||||
assert.equal(extractDouyinUrl(SHORT_TEXT_URL), SHORT_URL)
|
||||
})
|
||||
|
||||
test('从长链 video 里提取链接', () => {
|
||||
assert.equal(extractDouyinUrl(VIDEO_URL), VIDEO_URL)
|
||||
})
|
||||
|
||||
test('从 note 链接里提取链接', () => {
|
||||
assert.equal(extractDouyinUrl(NOTE_URL), NOTE_URL)
|
||||
})
|
||||
|
||||
test('从整段分享文案里提取链接', () => {
|
||||
const text =
|
||||
'7.89 复制打开抖音,看看【张三的作品】很有意思 https://v.douyin.com/fixture123/ 01/02 abc:/'
|
||||
assert.equal(extractDouyinUrl(text), SHORT_URL)
|
||||
})
|
||||
|
||||
test('去掉链接尾随的中文标点', () => {
|
||||
assert.equal(extractDouyinUrl('看这个 https://v.douyin.com/fixture123/。'), SHORT_URL)
|
||||
})
|
||||
|
||||
test('拒绝非抖音域名', () => {
|
||||
assert.equal(extractDouyinUrl('https://example.com/video/7300000000000000001'), null)
|
||||
assert.equal(extractDouyinUrl('https://douyin.com.evil.test/video/1'), null)
|
||||
assert.equal(extractDouyinUrl('https://foo.douyin.com/video/1'), null)
|
||||
})
|
||||
|
||||
test('拒绝 javascript: 与 ftp:', () => {
|
||||
assert.equal(extractDouyinUrl('javascript://v.douyin.com/fixture123/'), null)
|
||||
assert.equal(extractDouyinUrl('ftp://v.douyin.com/fixture123/'), null)
|
||||
})
|
||||
|
||||
test('没有链接时返回 null', () => {
|
||||
assert.equal(extractDouyinUrl('今天天气不错'), null)
|
||||
assert.equal(extractDouyinUrl(''), null)
|
||||
assert.equal(extractDouyinUrl(undefined), null)
|
||||
})
|
||||
|
||||
test('JSON 前后有噪声也能解析出数组', () => {
|
||||
const stdout = [
|
||||
'共 1 个链接',
|
||||
'▶ https://v.douyin.com/fixture123/',
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
'',
|
||||
'[{"url":"https://v.douyin.com/fixture123/","ok":true,"type":"video","aweme_id":"730"}]',
|
||||
'',
|
||||
'完成:1/1 成功'
|
||||
].join('\n')
|
||||
const parsed = parseResolveJson(stdout)
|
||||
assert.ok(Array.isArray(parsed))
|
||||
assert.equal(parsed.length, 1)
|
||||
assert.equal(parsed[0].aweme_id, '730')
|
||||
})
|
||||
|
||||
test('缩进的多行 JSON 数组按真实输出解析', () => {
|
||||
const stdout = [
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
'==================================================',
|
||||
'完成:1/1 成功',
|
||||
'[',
|
||||
' {',
|
||||
' "url": "https://v.douyin.com/fixture123/",',
|
||||
' "ok": true,',
|
||||
' "type": "video",',
|
||||
' "quality_options": [',
|
||||
' {"gear": "720p", "rank": 720}',
|
||||
' ]',
|
||||
' }',
|
||||
']'
|
||||
].join('\n')
|
||||
const parsed = parseResolveJson(stdout)
|
||||
assert.ok(Array.isArray(parsed))
|
||||
assert.equal(parsed[0].quality_options[0].rank, 720)
|
||||
})
|
||||
|
||||
test('非法 JSON 返回 null', () => {
|
||||
assert.equal(parseResolveJson('不是 JSON'), null)
|
||||
assert.equal(parseResolveJson('[{"ok":true,'), null)
|
||||
assert.equal(parseResolveJson(''), null)
|
||||
})
|
||||
|
||||
test('进度行里的方括号不会被误认为结果数组', () => {
|
||||
const stdout = [
|
||||
' [1] 跳过(无地址)',
|
||||
' ✅ /tmp/fixture-folder (2 个文件)',
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","aweme_id":"730"}]'
|
||||
].join('\n')
|
||||
const parsed = parseResolveJson(stdout)
|
||||
assert.ok(Array.isArray(parsed))
|
||||
assert.equal(parsed.length, 1)
|
||||
assert.equal(parsed[0].type, 'image')
|
||||
})
|
||||
|
||||
test('空数组视为无效结果', () => {
|
||||
assert.equal(parseResolveJson('[]'), null)
|
||||
})
|
||||
|
||||
test('合法 JSON 但不是数组时返回 null', () => {
|
||||
assert.equal(parseResolveJson('{"ok":true}'), null)
|
||||
})
|
||||
|
||||
test('下载输出里能取到绝对路径', () => {
|
||||
const stdout = [
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
' 下载中 → 张三 - 标题 - 730.mp4',
|
||||
' ✅ /tmp/fixture/downloads/张三 - 标题 - 730.mp4',
|
||||
' 5.2MB | MP4'
|
||||
].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), '/tmp/fixture/downloads/张三 - 标题 - 730.mp4')
|
||||
})
|
||||
|
||||
test('多条 ✅ 时取最后一个', () => {
|
||||
const stdout = [' ✅ /tmp/one.mp4', ' ✅ /tmp/two.mp4', ' 1.0MB | MP4'].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), '/tmp/two.mp4')
|
||||
})
|
||||
|
||||
test('从 JSON 下载结果同时提取作品元数据和保存路径', () => {
|
||||
const parsed = parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","aweme_id":"730","saved":["/tmp/fixture-video.mp4"]}]'
|
||||
)
|
||||
assert.deepEqual(parsed, {
|
||||
ok: true,
|
||||
meta: {
|
||||
url: 'https://v.douyin.com/fixture123',
|
||||
ok: true,
|
||||
type: 'video',
|
||||
aweme_id: '730',
|
||||
saved: ['/tmp/fixture-video.mp4']
|
||||
},
|
||||
path: '/tmp/fixture-video.mp4'
|
||||
})
|
||||
assert.equal(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","saved":["relative.mp4"]}]'
|
||||
),
|
||||
null
|
||||
)
|
||||
})
|
||||
|
||||
test('Windows 盘符路径同样算绝对路径', () => {
|
||||
const winPath = 'C:\\fixture\\Downloads\\张三 - 标题 - 730.mp4'
|
||||
assert.equal(isAbsoluteMediaPath(winPath), true)
|
||||
assert.equal(isAbsoluteMediaPath('C:/fixture/a.mp4'), true)
|
||||
assert.equal(isAbsoluteMediaPath('\\\\server\\share\\a.mp4'), true)
|
||||
assert.equal(isAbsoluteMediaPath('Downloads/a.mp4'), false)
|
||||
assert.equal(isAbsoluteMediaPath(''), false)
|
||||
assert.equal(isAbsoluteMediaPath(null), false)
|
||||
|
||||
// 只认 '/' 开头会把 Windows 的 ✅ 行整条丢掉
|
||||
const stdout = [
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
' ✅ ' + winPath,
|
||||
' 5.2MB | MP4'
|
||||
].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), winPath)
|
||||
|
||||
const json = JSON.stringify([
|
||||
{ url: 'https://v.douyin.com/fixture123', ok: true, type: 'video', saved: [winPath] }
|
||||
])
|
||||
const parsed = parseDownloadedResult(json)
|
||||
assert.equal(parsed.ok, true)
|
||||
assert.equal(parsed.path, winPath)
|
||||
})
|
||||
|
||||
test('JSON 下载失败保留脚本错误,图集保持不支持状态', () => {
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":false,"error":"fixture platform error"}]'
|
||||
),
|
||||
{ ok: false, message: 'fixture platform error', errorType: 'RESOLVE_FAILED' }
|
||||
)
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","images":[]}]'
|
||||
),
|
||||
{ ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
|
||||
)
|
||||
})
|
||||
|
||||
test('下载阶段失败时标记为下载错误', () => {
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":false,"aweme_id":"730","error":"fixture CDN timeout"}]'
|
||||
),
|
||||
{ ok: false, message: 'fixture CDN timeout', errorType: 'DOWNLOAD_FAILED' }
|
||||
)
|
||||
})
|
||||
|
||||
test('图集目录后面的附注被剥离', () => {
|
||||
const stdout = [' ✅ /tmp/fixture-folder (5 个文件)'].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), '/tmp/fixture-folder')
|
||||
})
|
||||
|
||||
test('没有 ✅ 行时返回 null', () => {
|
||||
assert.equal(parseSavedPath(' ✗ 失败:超时\n完成:0/1 成功'), null)
|
||||
assert.equal(parseSavedPath(''), null)
|
||||
})
|
||||
|
||||
test('模板替换三个已知变量', () => {
|
||||
const caption = renderCaption('{author}:{title}({awemeId})', {
|
||||
author: '张三',
|
||||
title: '测试标题',
|
||||
awemeId: '730'
|
||||
})
|
||||
assert.equal(caption, '张三:测试标题(730)')
|
||||
})
|
||||
|
||||
test('未知变量原样保留', () => {
|
||||
const caption = renderCaption('{author} {unknownVar}', { author: '张三' })
|
||||
assert.equal(caption, '张三 {unknownVar}')
|
||||
})
|
||||
|
||||
test('超长文案截断到 200 字', () => {
|
||||
const caption = renderCaption('{title}', { title: '字'.repeat(400) })
|
||||
assert.equal(caption.length, 200)
|
||||
})
|
||||
|
||||
test('默认配置符合约定', () => {
|
||||
const config = normalizeConfig(undefined)
|
||||
assert.equal(config.configVersion, 1)
|
||||
assert.equal(config.enabled, false)
|
||||
// Windows 的 python3.exe 通常是 Microsoft Store 的应用执行别名,默认改用 python。
|
||||
assert.equal(config.pythonPath, process.platform === 'win32' ? 'python' : 'python3')
|
||||
assert.equal(config.scriptPath, 'scripts/douyin.py')
|
||||
assert.equal(config.quality, '720')
|
||||
assert.equal(config.showUi, false)
|
||||
assert.equal(config.sendCaption, false)
|
||||
assert.equal(config.captionTemplate, '{author}:{title}')
|
||||
assert.equal(config.errorReply, true)
|
||||
assert.equal(config.includeDirect, false)
|
||||
assert.deepEqual(config.groups, [])
|
||||
assert.equal(config.cooldownSeconds, 60)
|
||||
assert.equal(config.maxFileMB, 100)
|
||||
})
|
||||
|
||||
test('常规配置不接纳 Cookie 凭证字段', () => {
|
||||
const config = normalizeConfig({ cookie: 'must-not-persist', cookieFile: '/tmp/fixture-cookie' })
|
||||
assert.equal(Object.hasOwn(config, 'cookie'), false)
|
||||
assert.equal(Object.hasOwn(config, 'cookieFile'), false)
|
||||
})
|
||||
|
||||
test('非法画质收敛到 720,空串表示最高', () => {
|
||||
assert.equal(normalizeConfig({ quality: '4k' }).quality, '720')
|
||||
assert.equal(normalizeConfig({ quality: '' }).quality, '')
|
||||
assert.equal(normalizeConfig({ quality: '1080' }).quality, '1080')
|
||||
})
|
||||
|
||||
test('数值型画质按字符串处理', () => {
|
||||
assert.equal(normalizeConfig({ quality: 540 }).quality, '540')
|
||||
})
|
||||
|
||||
test('showUi 只接受布尔 true', () => {
|
||||
assert.equal(normalizeConfig({ showUi: true }).showUi, true)
|
||||
assert.equal(normalizeConfig({ showUi: 'true' }).showUi, false)
|
||||
assert.equal(normalizeConfig({ showUi: 1 }).showUi, false)
|
||||
})
|
||||
|
||||
test('ackText 默认有回执,空串表示关闭', () => {
|
||||
assert.match(normalizeConfig({}).ackText, /收到/)
|
||||
assert.equal(normalizeConfig({ ackText: '' }).ackText, '')
|
||||
assert.equal(normalizeConfig({ ackText: ' 好的 ' }).ackText, '好的')
|
||||
assert.equal(normalizeConfig({ ackText: 'x'.repeat(300) }).ackText.length, 200)
|
||||
})
|
||||
|
||||
test('冷却与文件上限被夹到合法区间', () => {
|
||||
assert.equal(normalizeConfig({ cooldownSeconds: -10 }).cooldownSeconds, 0)
|
||||
assert.equal(normalizeConfig({ cooldownSeconds: 999999 }).cooldownSeconds, 3600)
|
||||
assert.equal(normalizeConfig({ maxFileMB: 0 }).maxFileMB, 1)
|
||||
assert.equal(normalizeConfig({ maxFileMB: 500 }).maxFileMB, 100)
|
||||
})
|
||||
|
||||
test('群 id 去空、去重并截断上限', () => {
|
||||
const config = normalizeConfig({
|
||||
groups: [' fixture-room@chatroom ', '', 'fixture-room@chatroom']
|
||||
})
|
||||
assert.deepEqual(config.groups, ['fixture-room@chatroom'])
|
||||
})
|
||||
|
||||
test('总开关关闭时拒绝处理', () => {
|
||||
const decision = shouldHandle(makeEvent(), makeConfig({ enabled: false }), new Map(), Date.now())
|
||||
assert.deepEqual(decision, { handle: false, url: null, reason: 'disabled' })
|
||||
})
|
||||
|
||||
test('自己发的消息拒绝处理', () => {
|
||||
const decision = shouldHandle(makeEvent({ isSelf: true }), makeConfig(), new Map(), Date.now())
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'self')
|
||||
})
|
||||
|
||||
test('非 text 消息拒绝处理', () => {
|
||||
const decision = shouldHandle(makeEvent({ type: 'image' }), makeConfig(), new Map(), Date.now())
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'type')
|
||||
})
|
||||
|
||||
test('没有真正 @ 我时拒绝处理', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent({ mentionsMe: false }),
|
||||
makeConfig(),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'mention')
|
||||
})
|
||||
|
||||
test('消息里没有链接时拒绝处理', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent({ text: '@李四 今天天气不错' }),
|
||||
makeConfig(),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'no_link')
|
||||
})
|
||||
|
||||
test('群不在白名单里时拒绝处理,但仍返回提取到的链接', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent(),
|
||||
makeConfig({ groups: ['other-room@chatroom'] }),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'scope')
|
||||
assert.equal(decision.url, SHORT_URL)
|
||||
})
|
||||
|
||||
test('群在白名单里时允许处理', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent(),
|
||||
makeConfig({ groups: ['fixture-room@chatroom'] }),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.deepEqual(decision, { handle: true, url: SHORT_URL, reason: 'ok' })
|
||||
})
|
||||
|
||||
test('私聊默认不处理,开启后处理', () => {
|
||||
const direct = makeEvent({ isGroup: false, conversationId: 'wxid_fixture' })
|
||||
assert.equal(shouldHandle(direct, makeConfig(), new Map(), Date.now()).reason, 'scope')
|
||||
assert.equal(
|
||||
shouldHandle(direct, makeConfig({ includeDirect: true }), new Map(), Date.now()).reason,
|
||||
'ok'
|
||||
)
|
||||
})
|
||||
|
||||
test('冷却未过期时拒绝,过期后放行', () => {
|
||||
const now = 1_767_225_600_000
|
||||
const cooldown = new Map([['fixture-room@chatroom', now + 30_000]])
|
||||
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now).reason, 'cooldown')
|
||||
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now + 30_001).reason, 'ok')
|
||||
})
|
||||
|
||||
test('图集不算视频', () => {
|
||||
const results = [
|
||||
{ url: SHORT_URL, ok: true, type: 'image', aweme_id: '730' },
|
||||
{ url: VIDEO_URL, ok: true, type: 'video', aweme_id: '731' }
|
||||
]
|
||||
assert.equal(pickVideoResult(results).aweme_id, '731')
|
||||
assert.equal(pickVideoResult([results[0]]), null)
|
||||
})
|
||||
|
||||
test('跳过失败项并容忍非数组输入', () => {
|
||||
assert.equal(pickVideoResult([{ ok: false, error: '超时' }]), null)
|
||||
assert.equal(pickVideoResult(null), null)
|
||||
assert.equal(pickVideoResult([]), null)
|
||||
})
|
||||
|
||||
test('文件大小判定覆盖上限与非法值', () => {
|
||||
assert.equal(isFileTooLarge(100 * 1024 * 1024, 100), false)
|
||||
assert.equal(isFileTooLarge(100 * 1024 * 1024 + 1, 100), true)
|
||||
assert.equal(isFileTooLarge(2 * 1024 * 1024, 1), true)
|
||||
assert.equal(isFileTooLarge(0, 100), true)
|
||||
assert.equal(isFileTooLarge(Number.NaN, 100), true)
|
||||
assert.equal(isFileTooLarge(1, 100), false)
|
||||
})
|
||||
|
||||
test('DEFAULT_CONFIG 不被 normalizeConfig 修改', () => {
|
||||
const before = JSON.stringify(DEFAULT_CONFIG)
|
||||
const config = normalizeConfig({ enabled: true, groups: ['fixture-room@chatroom'] })
|
||||
config.groups.push('wxid_fixture')
|
||||
assert.equal(JSON.stringify(DEFAULT_CONFIG), before)
|
||||
})
|
||||
@@ -0,0 +1,618 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 扩展页面桥。
|
||||
*
|
||||
* 页面只能通过宿主白名单能力与宿主通信,
|
||||
* 没有发送能力,也没有 `require`。
|
||||
*/
|
||||
|
||||
const EXTENSION_ID = 'com.example.douyin-sender'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
const PROGRESS_KEY = 'progress'
|
||||
const TEST_RESULT_KEY = 'testResult'
|
||||
|
||||
const ALLOWED_METHODS = new Set([
|
||||
'storage.get',
|
||||
'storage.set',
|
||||
'storage.remove',
|
||||
'storage.list',
|
||||
'capabilities.get',
|
||||
'contacts.listGroups',
|
||||
'extension.request',
|
||||
'extension.info'
|
||||
])
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: 1,
|
||||
enabled: false,
|
||||
pythonPath: 'python3',
|
||||
scriptPath: 'scripts/douyin.py',
|
||||
quality: '720',
|
||||
showUi: false,
|
||||
ackText: '收到,正在解析,请稍候…',
|
||||
sendCaption: false,
|
||||
captionTemplate: '{author}:{title}',
|
||||
errorReply: true,
|
||||
includeDirect: false,
|
||||
groups: [],
|
||||
cooldownSeconds: 60,
|
||||
maxFileMB: 100
|
||||
}
|
||||
|
||||
const STAGE_LABELS = {
|
||||
accepted: '已接收',
|
||||
resolve: '解析',
|
||||
resolveDownload: '解析并下载',
|
||||
download: '下载',
|
||||
send: '发送',
|
||||
caption: '补发文案',
|
||||
done: '完成',
|
||||
failed: '失败'
|
||||
}
|
||||
|
||||
const pending = new Map()
|
||||
let sequence = 0
|
||||
let config = clone(DEFAULT_CONFIG)
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!ALLOWED_METHODS.has(method)) {
|
||||
reject(new Error(`不支持的调用:${method}`))
|
||||
return
|
||||
}
|
||||
const requestId = `req-${++sequence}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const entry = pending.get(data.requestId)
|
||||
if (!entry) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) entry.resolve(data.result)
|
||||
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
|
||||
})
|
||||
|
||||
const status = document.getElementById('status')
|
||||
const rows = document.getElementById('job-rows')
|
||||
const todayTotal = document.getElementById('today-total')
|
||||
const todaySuccess = document.getElementById('today-success')
|
||||
const todayFailure = document.getElementById('today-failure')
|
||||
const progressBadge = document.getElementById('progress-badge')
|
||||
const progressStage = document.getElementById('progress-stage')
|
||||
const progressTime = document.getElementById('progress-time')
|
||||
const progressDetail = document.getElementById('progress-detail')
|
||||
const testGroup = document.getElementById('test-group')
|
||||
const testUrl = document.getElementById('test-url')
|
||||
const cookieHeader = document.getElementById('cookie-header')
|
||||
const cookieState = document.getElementById('cookie-state')
|
||||
const testResult = document.getElementById('test-result')
|
||||
const groupPicker = document.getElementById('group-picker')
|
||||
const groupChips = document.getElementById('group-chips')
|
||||
const groupSearch = document.getElementById('group-search')
|
||||
const groupOptions = document.getElementById('group-options')
|
||||
|
||||
let allGroups = []
|
||||
let selectedGroupIds = new Set()
|
||||
let groupLoadError = ''
|
||||
|
||||
function setStatus(text, kind) {
|
||||
status.textContent = text
|
||||
status.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function clampInt(value, fallback, min, max) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.max(min, Math.min(Math.trunc(numeric), max))
|
||||
}
|
||||
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' ? raw : {}
|
||||
const quality = ['', '1080', '720', '540'].includes(String(input.quality))
|
||||
? String(input.quality)
|
||||
: DEFAULT_CONFIG.quality
|
||||
return {
|
||||
configVersion: 1,
|
||||
enabled: input.enabled === true,
|
||||
pythonPath: String(input.pythonPath || DEFAULT_CONFIG.pythonPath).trim(),
|
||||
scriptPath: String(input.scriptPath || DEFAULT_CONFIG.scriptPath).trim(),
|
||||
quality,
|
||||
showUi: input.showUi === true,
|
||||
ackText:
|
||||
input.ackText === undefined
|
||||
? DEFAULT_CONFIG.ackText
|
||||
: String(input.ackText).trim().slice(0, 200),
|
||||
sendCaption: false,
|
||||
captionTemplate: String(input.captionTemplate || DEFAULT_CONFIG.captionTemplate).slice(0, 200),
|
||||
errorReply: input.errorReply !== false,
|
||||
includeDirect: input.includeDirect === true,
|
||||
groups: Array.isArray(input.groups)
|
||||
? input.groups
|
||||
.map((id) => String(id).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 200)
|
||||
: [],
|
||||
cooldownSeconds: clampInt(input.cooldownSeconds, DEFAULT_CONFIG.cooldownSeconds, 0, 3600),
|
||||
maxFileMB: clampInt(input.maxFileMB, DEFAULT_CONFIG.maxFileMB, 1, 100)
|
||||
}
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('enabled').checked = config.enabled === true
|
||||
document.getElementById('python-path').value = config.pythonPath
|
||||
document.getElementById('script-path').value = config.scriptPath
|
||||
document.getElementById('quality').value = config.quality
|
||||
document.getElementById('show-ui').checked = config.showUi === true
|
||||
document.getElementById('ack-text').value = config.ackText
|
||||
document.getElementById('error-reply').checked = config.errorReply === true
|
||||
selectedGroupIds = new Set(config.groups)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
document.getElementById('include-direct').checked = config.includeDirect === true
|
||||
document.getElementById('cooldown').value = String(config.cooldownSeconds)
|
||||
document.getElementById('max-file-mb').value = String(config.maxFileMB)
|
||||
}
|
||||
|
||||
function readForm() {
|
||||
config.enabled = document.getElementById('enabled').checked
|
||||
config.pythonPath = document.getElementById('python-path').value.trim()
|
||||
config.scriptPath = document.getElementById('script-path').value.trim()
|
||||
config.quality = document.getElementById('quality').value
|
||||
config.showUi = document.getElementById('show-ui').checked
|
||||
config.ackText = document.getElementById('ack-text').value.trim().slice(0, 200)
|
||||
config.sendCaption = false
|
||||
config.errorReply = document.getElementById('error-reply').checked
|
||||
config.groups = [...selectedGroupIds].slice(0, 200)
|
||||
config.includeDirect = document.getElementById('include-direct').checked
|
||||
config.cooldownSeconds = clampInt(
|
||||
document.getElementById('cooldown').value,
|
||||
DEFAULT_CONFIG.cooldownSeconds,
|
||||
0,
|
||||
3600
|
||||
)
|
||||
config.maxFileMB = clampInt(
|
||||
document.getElementById('max-file-mb').value,
|
||||
DEFAULT_CONFIG.maxFileMB,
|
||||
1,
|
||||
100
|
||||
)
|
||||
config.configVersion = 1
|
||||
}
|
||||
|
||||
function formatTime(value) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric) || numeric <= 0) return '—'
|
||||
const date = new Date(numeric)
|
||||
const pad = (part) => String(part).padStart(2, '0')
|
||||
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
function renderStats(raw) {
|
||||
const stats = raw && typeof raw === 'object' ? raw : {}
|
||||
const jobs = Array.isArray(stats.lastJobs) ? stats.lastJobs.slice(0, 8) : []
|
||||
const total = Math.max(0, Math.trunc(Number(stats.todayTotal ?? stats.todayCount) || 0))
|
||||
todayTotal.textContent = String(total)
|
||||
todaySuccess.textContent = String(Math.max(0, Math.trunc(Number(stats.todaySuccess) || 0)))
|
||||
todayFailure.textContent = String(Math.max(0, Math.trunc(Number(stats.todayFailure) || 0)))
|
||||
rows.textContent = ''
|
||||
if (!jobs.length) {
|
||||
const row = document.createElement('tr')
|
||||
const cell = document.createElement('td')
|
||||
cell.colSpan = 5
|
||||
cell.className = 'empty'
|
||||
cell.textContent = '暂无记录'
|
||||
row.append(cell)
|
||||
rows.append(row)
|
||||
return
|
||||
}
|
||||
for (const job of jobs) {
|
||||
const row = document.createElement('tr')
|
||||
const time = document.createElement('td')
|
||||
time.textContent = formatTime(job && job.at)
|
||||
const id = document.createElement('td')
|
||||
id.className = 'mono'
|
||||
id.textContent = (job && job.awemeId) || '—'
|
||||
const stage = document.createElement('td')
|
||||
stage.textContent = STAGE_LABELS[job && job.stage] || (job && job.stage) || '—'
|
||||
const result = document.createElement('td')
|
||||
const ok = job && job.ok === true
|
||||
result.textContent = ok ? '成功' : '失败'
|
||||
result.className = ok ? 'ok' : 'fail'
|
||||
const error = document.createElement('td')
|
||||
error.className = 'mono'
|
||||
error.textContent = (job && job.errorType) || '—'
|
||||
row.append(time, id, stage, result, error)
|
||||
rows.append(row)
|
||||
}
|
||||
}
|
||||
|
||||
/** 进度:运行中显示阶段与已用时间;失败显示失败阶段与错误码。 */
|
||||
function renderProgress(raw) {
|
||||
const progress = raw && typeof raw === 'object' ? raw : null
|
||||
if (!progress || !progress.stage) {
|
||||
progressBadge.textContent = '空闲'
|
||||
progressBadge.dataset.status = 'idle'
|
||||
progressStage.textContent = '暂无任务'
|
||||
progressTime.textContent = ''
|
||||
progressDetail.textContent = '触发后这里会显示解析、下载、发送进行到哪一步。'
|
||||
return
|
||||
}
|
||||
const status =
|
||||
progress.status === 'failed' ? 'failed' : progress.status === 'done' ? 'done' : 'running'
|
||||
progressBadge.textContent = status === 'failed' ? '失败' : status === 'done' ? '完成' : '进行中'
|
||||
progressBadge.dataset.status = status
|
||||
progressStage.textContent =
|
||||
status === 'failed'
|
||||
? `失败于:${STAGE_LABELS[progress.stage] || progress.stage}`
|
||||
: status === 'done'
|
||||
? '已完成'
|
||||
: `正在${STAGE_LABELS[progress.stage] || progress.stage}`
|
||||
const startedAt = Number(progress.startedAt)
|
||||
// 运行中用当前时间计算,脚本卡住时秒数也会继续走,不会看起来停在 0s。
|
||||
const updatedAt = status === 'running' ? Date.now() : Number(progress.updatedAt) || Date.now()
|
||||
const elapsed =
|
||||
Number.isFinite(startedAt) && startedAt > 0
|
||||
? Math.max(0, Math.round((updatedAt - startedAt) / 1000))
|
||||
: null
|
||||
progressTime.textContent = elapsed === null ? '' : `· ${elapsed}s`
|
||||
const parts = []
|
||||
if (progress.awemeId) parts.push(`作品 ${progress.awemeId}`)
|
||||
if (status === 'failed' && progress.errorType) parts.push(`错误 ${progress.errorType}`)
|
||||
if (status === 'failed' && progress.errorMessage) parts.push(progress.errorMessage)
|
||||
if (status === 'done') parts.push('视频已发送')
|
||||
progressDetail.textContent = parts.join(' · ') || ''
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: STATS_KEY })
|
||||
renderStats(stored)
|
||||
} catch (error) {
|
||||
renderStats(null)
|
||||
setStatus(`统计读取失败:${error.message}`, 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function loadProgress() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: PROGRESS_KEY })
|
||||
renderProgress(stored)
|
||||
} catch {
|
||||
renderProgress(null)
|
||||
}
|
||||
}
|
||||
|
||||
let testPollTimer = null
|
||||
let activeTestId = ''
|
||||
|
||||
function setTestResult(text, kind) {
|
||||
testResult.textContent = text
|
||||
testResult.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function groupDisplayName(group) {
|
||||
if (!group) return ''
|
||||
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
|
||||
}
|
||||
|
||||
function emptyGroupOption(text) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-option-empty'
|
||||
empty.textContent = text
|
||||
return empty
|
||||
}
|
||||
|
||||
function renderGroupChips() {
|
||||
groupChips.textContent = ''
|
||||
groupChips.hidden = selectedGroupIds.size === 0
|
||||
for (const id of selectedGroupIds) {
|
||||
const group = allGroups.find((item) => item.id === id)
|
||||
const chip = document.createElement('span')
|
||||
chip.className = 'group-chip'
|
||||
const name = document.createElement('span')
|
||||
name.textContent = group ? group.name || id : id
|
||||
name.title = id
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'group-chip-remove'
|
||||
remove.textContent = '×'
|
||||
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
|
||||
remove.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
selectedGroupIds.delete(id)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
})
|
||||
chip.append(name, remove)
|
||||
groupChips.append(chip)
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroupOptions() {
|
||||
if (groupOptions.hidden) return
|
||||
const query = groupSearch.value.trim().toLowerCase()
|
||||
groupOptions.textContent = ''
|
||||
if (groupLoadError) {
|
||||
groupOptions.append(emptyGroupOption(groupLoadError))
|
||||
return
|
||||
}
|
||||
if (!allGroups.length) {
|
||||
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
|
||||
return
|
||||
}
|
||||
const matches = allGroups.filter((group) => {
|
||||
if (!query) return true
|
||||
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
|
||||
})
|
||||
if (!matches.length) {
|
||||
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
|
||||
return
|
||||
}
|
||||
for (const group of matches.slice(0, 200)) {
|
||||
const option = document.createElement('label')
|
||||
option.className = 'group-option'
|
||||
const checkbox = document.createElement('input')
|
||||
checkbox.type = 'checkbox'
|
||||
checkbox.checked = selectedGroupIds.has(group.id)
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedGroupIds.add(group.id)
|
||||
else selectedGroupIds.delete(group.id)
|
||||
renderGroupChips()
|
||||
})
|
||||
const text = document.createElement('span')
|
||||
text.textContent = groupDisplayName(group)
|
||||
option.append(checkbox, text)
|
||||
groupOptions.append(option)
|
||||
}
|
||||
}
|
||||
|
||||
function openGroupOptions() {
|
||||
groupOptions.hidden = false
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function closeGroupOptions() {
|
||||
groupOptions.hidden = true
|
||||
groupSearch.value = ''
|
||||
}
|
||||
|
||||
groupSearch.addEventListener('focus', openGroupOptions)
|
||||
groupSearch.addEventListener('input', openGroupOptions)
|
||||
groupSearch.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
closeGroupOptions()
|
||||
groupSearch.blur()
|
||||
}
|
||||
})
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!groupPicker.contains(event.target)) closeGroupOptions()
|
||||
})
|
||||
|
||||
/** 群列表来自宿主通讯录;数据库未连接时给出明确空态,而不是假装有选项。 */
|
||||
async function loadGroups() {
|
||||
const current = testGroup.value
|
||||
try {
|
||||
const result = await callHost('contacts.listGroups', {})
|
||||
allGroups = result && Array.isArray(result.groups) ? result.groups : []
|
||||
groupLoadError = ''
|
||||
testGroup.textContent = ''
|
||||
if (!allGroups.length) {
|
||||
const option = document.createElement('option')
|
||||
option.value = ''
|
||||
option.textContent = '未读取到群列表(请先连接微信数据库)'
|
||||
testGroup.append(option)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
return
|
||||
}
|
||||
const placeholder = document.createElement('option')
|
||||
placeholder.value = ''
|
||||
placeholder.textContent = '请选择群聊'
|
||||
testGroup.append(placeholder)
|
||||
for (const group of allGroups) {
|
||||
const option = document.createElement('option')
|
||||
option.value = group.id
|
||||
option.textContent = groupDisplayName(group)
|
||||
testGroup.append(option)
|
||||
}
|
||||
const saved = await callHost('storage.get', { key: 'testGroup' }).catch(() => null)
|
||||
const target = current || (typeof saved === 'string' ? saved : '')
|
||||
if (target && allGroups.some((group) => group.id === target)) testGroup.value = target
|
||||
} catch (error) {
|
||||
allGroups = []
|
||||
groupLoadError = `群列表读取失败:${error.message}`
|
||||
testGroup.textContent = ''
|
||||
const option = document.createElement('option')
|
||||
option.value = ''
|
||||
option.textContent = groupLoadError
|
||||
testGroup.append(option)
|
||||
}
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
/** 轮询后台写入的测试结果;只认本次请求的 id,避免串台。 */
|
||||
async function pollTestResult() {
|
||||
if (!activeTestId) return
|
||||
window.clearTimeout(testPollTimer)
|
||||
try {
|
||||
const result = await callHost('storage.get', { key: TEST_RESULT_KEY })
|
||||
if (result && result.id === activeTestId) {
|
||||
if (result.status === 'running') {
|
||||
setTestResult(result.message || '处理中…', 'running')
|
||||
} else if (result.status === 'done') {
|
||||
setTestResult(result.message || '测试发送完成', 'ok')
|
||||
activeTestId = ''
|
||||
return
|
||||
} else if (result.status === 'failed') {
|
||||
setTestResult(result.message || '测试发送失败', 'error')
|
||||
activeTestId = ''
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 单次读取失败继续重试。
|
||||
}
|
||||
testPollTimer = window.setTimeout(() => {
|
||||
void pollTestResult()
|
||||
}, 1500)
|
||||
}
|
||||
|
||||
async function loadConfig() {
|
||||
const stored = await callHost('storage.get', { key: CONFIG_KEY })
|
||||
config = normalizeConfig(stored)
|
||||
syncForm()
|
||||
}
|
||||
|
||||
async function loadCookieState() {
|
||||
try {
|
||||
const result = await callHost('extension.request', { method: 'douyinCookie.status', params: {} })
|
||||
cookieState.textContent =
|
||||
result && result.configured ? '已保存 Cookie(内容不可回显)' : '未配置'
|
||||
} catch {
|
||||
cookieState.textContent = '安全存储不可用,无法读取状态'
|
||||
}
|
||||
}
|
||||
void loadCookieState()
|
||||
|
||||
async function checkCapabilities() {
|
||||
try {
|
||||
const snapshot = await callHost('capabilities.get', {})
|
||||
const send = snapshot && snapshot.send ? snapshot.send : null
|
||||
if (!send || !send.canSendVideo) {
|
||||
setStatus('当前环境未就绪:视频发送通道不可用,配置仍可保存。', 'error')
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
// 能力查询失败不阻塞配置编辑。
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
testGroup.addEventListener('change', () => {
|
||||
void callHost('storage.set', { key: 'testGroup', value: testGroup.value }).catch(() => undefined)
|
||||
})
|
||||
|
||||
document.getElementById('test-refresh').addEventListener('click', () => {
|
||||
void loadGroups()
|
||||
})
|
||||
|
||||
document.getElementById('test-send').addEventListener('click', async () => {
|
||||
const to = testGroup.value
|
||||
const text = testUrl.value.trim()
|
||||
if (!to) {
|
||||
setTestResult('请先选择目标群聊。', 'error')
|
||||
return
|
||||
}
|
||||
if (!text) {
|
||||
setTestResult('请粘贴抖音分享链接或整段分享文案。', 'error')
|
||||
return
|
||||
}
|
||||
activeTestId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
setTestResult('已提交,等待后台开始解析…', 'running')
|
||||
try {
|
||||
const submitted = callHost('extension.request', {
|
||||
method: 'testSend',
|
||||
params: { id: activeTestId, to, text, at: Date.now() }
|
||||
})
|
||||
void pollTestResult()
|
||||
await submitted
|
||||
} catch (error) {
|
||||
activeTestId = ''
|
||||
setTestResult(`提交失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('cookie-save').addEventListener('click', async () => {
|
||||
const value = cookieHeader.value.trim()
|
||||
if (!value) {
|
||||
setStatus('请先粘贴抖音 Cookie。', 'error')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await callHost('extension.request', {
|
||||
method: 'douyinCookie.set',
|
||||
params: { cookieHeader: value }
|
||||
})
|
||||
cookieHeader.value = ''
|
||||
await loadCookieState()
|
||||
setStatus('Cookie 已安全保存。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`Cookie 保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('cookie-clear').addEventListener('click', async () => {
|
||||
try {
|
||||
await callHost('extension.request', { method: 'douyinCookie.clear', params: {} })
|
||||
cookieHeader.value = ''
|
||||
await loadCookieState()
|
||||
setStatus('Cookie 已清除。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`Cookie 清除失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('save').addEventListener('click', async () => {
|
||||
readForm()
|
||||
if (!config.pythonPath) {
|
||||
setStatus('Python 可执行文件不能为空。', 'error')
|
||||
return
|
||||
}
|
||||
if (!config.scriptPath) {
|
||||
setStatus('解析脚本路径不能为空。', 'error')
|
||||
return
|
||||
}
|
||||
if (!config.captionTemplate.trim() && config.sendCaption) {
|
||||
setStatus('已开启标题文案,模板不能为空。', 'error')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setStatus('配置已保存,后台 1 秒内生效', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('reload').addEventListener('click', async () => {
|
||||
try {
|
||||
await loadConfig()
|
||||
await loadStats()
|
||||
await loadProgress()
|
||||
setStatus('已重新读取配置。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`读取失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
async function boot() {
|
||||
await loadConfig()
|
||||
await Promise.all([loadStats(), loadProgress(), loadGroups()])
|
||||
const blocked = await checkCapabilities()
|
||||
if (!blocked) setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
|
||||
// 页面打开期间轮询进度,任务跑到哪一步不用猜;统计低频刷新即可。
|
||||
window.setInterval(() => {
|
||||
void loadProgress()
|
||||
}, 2000)
|
||||
window.setInterval(() => {
|
||||
void loadStats()
|
||||
}, 6000)
|
||||
}
|
||||
|
||||
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
|
||||
@@ -0,0 +1,192 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>抖音视频搬运</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>抖音视频搬运</h1>
|
||||
<p>
|
||||
被 @ 且消息里带抖音分享链接时,解析视频并发回原会话。本页只写配置,发送全部由后台经
|
||||
TraceMemo Gateway 完成。
|
||||
</p>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input id="enabled" type="checkbox" />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="panel">
|
||||
<h2>运行环境</h2>
|
||||
<label class="field">
|
||||
<span>Python 可执行文件</span>
|
||||
<input id="python-path" type="text" placeholder="python3" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>解析脚本路径(默认相对于扩展目录,支持 <code>~</code>,首次运行会在缓存目录创建 venv)</span>
|
||||
<input
|
||||
id="script-path"
|
||||
type="text"
|
||||
placeholder="scripts/douyin.py"
|
||||
/>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>画质</span>
|
||||
<select id="quality">
|
||||
<option value="">最高</option>
|
||||
<option value="1080">1080</option>
|
||||
<option value="720">720</option>
|
||||
<option value="540">540</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="check">
|
||||
<input id="show-ui" type="checkbox" />
|
||||
<span>显示浏览器窗口(排障用;可观察作品页实际停留状态,不保证改变平台响应)</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>抖音 Cookie</h2>
|
||||
<label class="field">
|
||||
<span>Cookie(安全加密保存;仅本机使用)</span>
|
||||
<input
|
||||
id="cookie-header"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
spellcheck="false"
|
||||
placeholder="粘贴抖音 Cookie header"
|
||||
/>
|
||||
</label>
|
||||
<p id="cookie-state" class="muted">未配置</p>
|
||||
<div class="row">
|
||||
<button id="cookie-save" type="button" class="primary">保存 Cookie</button>
|
||||
<button id="cookie-clear" type="button" class="ghost">清除 Cookie</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>回复与文案</h2>
|
||||
<label class="field">
|
||||
<span>触发后先回复一句(留空表示不回复)</span>
|
||||
<input id="ack-text" type="text" maxlength="200" placeholder="收到,正在解析,请稍候…" />
|
||||
</label>
|
||||
<label class="check"
|
||||
><input id="error-reply" type="checkbox" /><span
|
||||
>失败时在原会话回一条简短说明</span
|
||||
></label
|
||||
>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>监听范围</h2>
|
||||
<div class="field">
|
||||
<span>只处理这些群(可多选、可搜索;留空表示全部群)</span>
|
||||
<div id="group-picker" class="group-picker">
|
||||
<div id="group-chips" class="group-chips" hidden></div>
|
||||
<input
|
||||
id="group-search"
|
||||
type="text"
|
||||
placeholder="搜索群聊名称或 id…"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<div id="group-options" class="group-options" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="check"
|
||||
><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label
|
||||
>
|
||||
</div>
|
||||
<div class="grid-2">
|
||||
<label class="field">
|
||||
<span>冷却秒数(0–3600,按会话计)</span>
|
||||
<input id="cooldown" type="number" min="0" max="3600" step="1" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>文件大小上限(MB,1–100)</span>
|
||||
<input id="max-file-mb" type="number" min="1" max="100" step="1" />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>测试发送</h2>
|
||||
<label class="field">
|
||||
<span>目标群聊</span>
|
||||
<select id="test-group">
|
||||
<option value="">加载中…</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>抖音分享链接或整段分享文案</span>
|
||||
<textarea
|
||||
id="test-url"
|
||||
rows="3"
|
||||
placeholder="https://v.douyin.com/xxxxxx/ 复制打开抖音…"
|
||||
></textarea>
|
||||
</label>
|
||||
<div class="row">
|
||||
<button id="test-send" type="button" class="primary">测试发送</button>
|
||||
<button id="test-refresh" type="button" class="ghost">刷新群列表</button>
|
||||
</div>
|
||||
<p id="test-result" class="status">
|
||||
选择群聊、粘贴链接后点「测试发送」,解析完成后视频会直接发到该群。已保存的 Cookie
|
||||
自动用于测试。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>当前任务</h2>
|
||||
<span id="progress-badge" class="badge">空闲</span>
|
||||
</div>
|
||||
<p class="progress-line">
|
||||
<strong id="progress-stage">暂无任务</strong>
|
||||
<span id="progress-time" class="muted"></span>
|
||||
</p>
|
||||
<p id="progress-detail" class="muted">触发后这里会显示解析、下载、发送进行到哪一步。</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>统计</h2>
|
||||
<span class="muted"
|
||||
>今日 总计 <strong id="today-total">0</strong> · 成功
|
||||
<strong id="today-success">0</strong> · 失败 <strong id="today-failure">0</strong></span
|
||||
>
|
||||
</div>
|
||||
<table class="stats">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>作品 ID</th>
|
||||
<th>阶段</th>
|
||||
<th>结果</th>
|
||||
<th>错误</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="job-rows">
|
||||
<tr>
|
||||
<td colspan="5" class="empty">暂无记录</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<footer class="page-footer">
|
||||
<div class="row">
|
||||
<button id="save" type="button" class="primary">保存配置</button>
|
||||
<button id="reload" type="button" class="ghost">重新读取</button>
|
||||
</div>
|
||||
<p id="status" class="status" role="status"></p>
|
||||
</footer>
|
||||
</main>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,387 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f8f7;
|
||||
--card: #ffffff;
|
||||
--text: #1c2622;
|
||||
--muted: #6b7a73;
|
||||
--border: #dfe6e2;
|
||||
--brand: #247a63;
|
||||
--danger: #b4472f;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #161c19;
|
||||
--card: #1e2622;
|
||||
--text: #eef4f1;
|
||||
--muted: #9aaba3;
|
||||
--border: #33403a;
|
||||
--brand: #4bb894;
|
||||
--danger: #e0735a;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
padding: 26px 22px 40px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
header p {
|
||||
margin: 8px 0 0;
|
||||
max-width: 52ch;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.field > span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
input[type='number'],
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.grid-2 {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.check,
|
||||
.switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.switch {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 6px 11px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: transparent;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
button.ghost:hover {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 18px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status[data-kind='ok'] {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.status[data-kind='error'] {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.muted strong {
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.stats {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats th {
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.stats td {
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.stats tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.stats td.empty {
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stats .mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.stats .ok {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.stats .fail {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 当前任务:状态徽标 + 一行阶段 + 一行细节。 */
|
||||
.badge {
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge[data-status='running'] {
|
||||
background: color-mix(in srgb, var(--brand) 14%, transparent);
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.badge[data-status='done'] {
|
||||
background: color-mix(in srgb, var(--brand) 14%, transparent);
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.badge[data-status='failed'] {
|
||||
background: color-mix(in srgb, var(--danger) 14%, transparent);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.progress-line {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.progress-line .muted {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
|
||||
.group-picker {
|
||||
position: relative;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.group-picker:focus-within {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.group-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 2px 4px 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.group-chip > span {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-chip-remove {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.group-chip-remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.group-picker > input[type='text'] {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
padding: 4px 2px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-options {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 4px);
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.group-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 6px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-option:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.group-option input {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group-option-empty {
|
||||
padding: 8px 6px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
# 群聊机器人 (`com.example.group-chat-bot`)
|
||||
|
||||
> **这是模板壳,不是完整运行包。** 本目录不含 `lib/bot-engine.js` 运行时核心。直接把本目录打成 ZIP 安装,后台会走 `background/index.js` 的静默壳逻辑,页面可预览配置但不会执行自动回复。
|
||||
|
||||
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型、文字转语音(TTS)音色、本地系统 OCR、AI 视觉理解与语音转写能力,在指定微信群聊中按角色设定自然接话,支持单群长期记忆、按需解析图片与语音内容,以及随机回复文字 / 发送语音。
|
||||
|
||||
## 核心特性
|
||||
|
||||
1. **多套群聊人格(Persona)**:内置四套预设人格并支持自定义编辑,可按群绑定不同人格。
|
||||
2. **短期上下文 + 单群长期记忆(Memory)**:按群维护固定备注与 AI 提炼的互动摘要。
|
||||
3. **按需图片与语音理解(v1.1 新增)**:
|
||||
- 订阅范围已扩展至 `text` / `image` / `voice`,通过统一的 `messageRef` 按需调用 `tm.media.ocrImage`、`tm.media.analyzeImage` 与 `tm.media.transcribeVoice`。
|
||||
- 图片优先走本地系统 OCR(零联网消耗),按需降级/切换视觉模型;语音复用主程序转写队列与缓存。
|
||||
4. **随机回复文字 / 发送语音 + 动态一级导航**:声明 `contributions.navigation`,支持在扩展详情页一键「固定到一级菜单」。
|
||||
|
||||
## 申请权限
|
||||
|
||||
| 权限 | 用途 |
|
||||
| --- | --- |
|
||||
| `messages.subscribe` | 接收微信群聊文本、图片与语音新消息事件 |
|
||||
| `messages.query` | 分页读取触发群聊最近的上下文消息 |
|
||||
| `media.ocr` | 按需识别群聊图片中的文字(纯本地,不联网) |
|
||||
| `media.transcribe` | 按需将群聊语音转为文字(复用主程序转写缓存) |
|
||||
| `ai.vision` | 按需调用已配置的视觉模型理解图片内容 |
|
||||
| `contacts.list` | 在配置页读取群聊列表供勾选生效范围 |
|
||||
| `wechat.send.text` | 经 TraceMemo Gateway 发送群聊文字回复 |
|
||||
| `wechat.send.voice` | 经 TraceMemo 文字转语音服务与 Gateway 发送群聊语音气泡 |
|
||||
| `ai.chat` | 调用 TraceMemo 已配置的 AI Provider 进行思考回复与记忆提炼 |
|
||||
| `notifications.create` | 在扩展通知中心汇报关键状态 |
|
||||
| `storage` | 保存机器人配置、单群长期记忆与今日统计 |
|
||||
@@ -0,0 +1,114 @@
|
||||
'use strict'
|
||||
|
||||
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,并内置按需图片/语音解析适配。 */
|
||||
|
||||
let engine = null
|
||||
try {
|
||||
engine = require('../lib/bot-engine')
|
||||
} catch {
|
||||
engine = null
|
||||
}
|
||||
|
||||
function hasGrantedPermission(tm, permission) {
|
||||
const perms = tm && tm.extension && Array.isArray(tm.extension.permissions)
|
||||
? tm.extension.permissions
|
||||
: []
|
||||
return perms.includes(permission)
|
||||
}
|
||||
|
||||
/** 按需将图片或语音消息解析为可供机器人理解的纯文本摘要,缺权限或失败时安全降级为 null。 */
|
||||
async function resolveIncomingMediaText(tm, event, options = {}) {
|
||||
if (!event || typeof event !== 'object') return null
|
||||
if (event.type === 'text') {
|
||||
const text = String(event.text || '').trim()
|
||||
return text ? { text, source: 'text' } : null
|
||||
}
|
||||
const messageRef = String(event.messageRef || '').trim()
|
||||
if (!messageRef || !tm || !tm.media) return null
|
||||
|
||||
if (event.type === 'image') {
|
||||
const imageMode = options.imageMode || 'ocr'
|
||||
if (imageMode === 'off') return null
|
||||
|
||||
if (imageMode === 'vision' && hasGrantedPermission(tm, 'ai.vision')) {
|
||||
try {
|
||||
const analyzed = await tm.media.analyzeImage({ messageRef })
|
||||
const parts = [analyzed && analyzed.description, analyzed && analyzed.ocrText]
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
if (parts.length > 0) {
|
||||
return { text: `[图片内容] ${parts.join(';')}`, source: 'image_vision' }
|
||||
}
|
||||
} catch {
|
||||
// 视觉理解失败时降级到本地 OCR。
|
||||
}
|
||||
}
|
||||
|
||||
if (hasGrantedPermission(tm, 'media.ocr')) {
|
||||
try {
|
||||
const ocr = await tm.media.ocrImage({ messageRef })
|
||||
const ocrText = String((ocr && ocr.text) || '').trim()
|
||||
if (ocrText) {
|
||||
return { text: `[图片文字] ${ocrText}`, source: 'image_ocr' }
|
||||
}
|
||||
} catch {
|
||||
// 本地 OCR 不可用时继续尝试可选视觉回退。
|
||||
}
|
||||
}
|
||||
|
||||
if (options.visionFallback === true && hasGrantedPermission(tm, 'ai.vision')) {
|
||||
try {
|
||||
const analyzed = await tm.media.analyzeImage({ messageRef })
|
||||
const desc = String((analyzed && analyzed.description) || '').trim()
|
||||
if (desc) return { text: `[图片内容] ${desc}`, source: 'image_vision' }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (event.type === 'voice') {
|
||||
if (options.voiceTranscribeEnabled === false) return null
|
||||
if (!hasGrantedPermission(tm, 'media.transcribe')) return null
|
||||
try {
|
||||
const result = await tm.media.transcribeVoice({
|
||||
messageRef,
|
||||
waitMs: Number(options.voiceWaitMs) > 0 ? Number(options.voiceWaitMs) : 12_000
|
||||
})
|
||||
if (result && result.state === 'transcribed' && String(result.transcript || '').trim()) {
|
||||
return {
|
||||
text: `[语音转文字] ${String(result.transcript).trim()}`,
|
||||
source: 'voice_transcript'
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function registerFallbackHandlers(tm) {
|
||||
if (!tm || !tm.page || typeof tm.page.onRequest !== 'function') return
|
||||
const unavailable = async () => {
|
||||
throw new Error('当前功能暂不可用')
|
||||
}
|
||||
tm.page.onRequest('previewReply', unavailable)
|
||||
tm.page.onRequest('refreshGroupMemory', unavailable)
|
||||
tm.page.onRequest('testSend', unavailable)
|
||||
}
|
||||
|
||||
function activate(api) {
|
||||
if (engine && typeof engine.activateBotRuntime === 'function') {
|
||||
engine.activateBotRuntime(api, { resolveIncomingMediaText })
|
||||
} else {
|
||||
registerFallbackHandlers(api)
|
||||
}
|
||||
if (api && api.log && typeof api.log.info === 'function') {
|
||||
api.log.info('群聊机器人已启动')
|
||||
}
|
||||
}
|
||||
|
||||
activate.resolveIncomingMediaText = resolveIncomingMediaText
|
||||
module.exports = activate
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.group-chat-bot",
|
||||
"name": "群聊机器人 - 模板(如需使用请找授权你的人",
|
||||
"version": "1.1.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.7.0",
|
||||
"description": "支持多套群聊人格设定、群聊长期与短期记忆、按需解析图片与语音内容,并可结合 TraceMemo 音色随机回复文字或发送语音。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.subscribe",
|
||||
"messages.query",
|
||||
"media.ocr",
|
||||
"media.transcribe",
|
||||
"contacts.list",
|
||||
"wechat.send.text",
|
||||
"wechat.send.voice",
|
||||
"ai.chat",
|
||||
"ai.vision",
|
||||
"notifications.create",
|
||||
"storage"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": [
|
||||
"text",
|
||||
"image",
|
||||
"voice"
|
||||
],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": false,
|
||||
"includeSelf": false
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "settings",
|
||||
"title": "群聊机器人设置"
|
||||
}
|
||||
],
|
||||
"navigation": {
|
||||
"label": "群聊机器人",
|
||||
"icon": "bot",
|
||||
"pageId": "settings"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>群聊机器人 - 模板(如需使用请找授权你的人</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="hero">
|
||||
<div>
|
||||
<p class="eyebrow">TraceMemo 官方扩展模板 · com.example.group-chat-bot</p>
|
||||
<div class="hero-title-row">
|
||||
<h1>群聊机器人 - 模板(如需使用请找授权你的人</h1>
|
||||
<span id="hero-send-warn" class="send-warn-badge" hidden>
|
||||
<span class="send-warn-bang" aria-hidden="true">!</span>
|
||||
当前暂无发送能力
|
||||
</span>
|
||||
</div>
|
||||
<p class="subtitle">
|
||||
支持多套群聊人格设定、基于本机聊天记录的群记忆提炼、敏感探测安全拦截,并可结合
|
||||
TraceMemo 已选音色随机回复文字或发送微信语音。
|
||||
</p>
|
||||
</div>
|
||||
<div class="hero-stats">
|
||||
<div class="stat-pill">
|
||||
<span>今日回复</span>
|
||||
<strong id="stat-total">0</strong>
|
||||
</div>
|
||||
<div class="stat-pill">
|
||||
<span>文字 / 语音</span>
|
||||
<strong id="stat-split">0 / 0</strong>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="send-unavailable-mask" class="send-unavailable-mask" hidden>
|
||||
<div class="send-unavailable-dialog">
|
||||
<button
|
||||
id="close-send-mask-btn"
|
||||
type="button"
|
||||
class="send-unavailable-close"
|
||||
aria-label="关闭提示并预览界面"
|
||||
title="关闭提示(可浏览界面,无法保存启用)"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<div class="send-unavailable-icon" aria-hidden="true">!</div>
|
||||
<h2>当前暂无发送能力</h2>
|
||||
<p id="send-unavailable-reason">
|
||||
当前尚未绑定个人微信或发送组件未就绪。你可以点击右上角 × 关闭遮罩预览界面,但无法保存启用。
|
||||
</p>
|
||||
<div class="send-unavailable-actions">
|
||||
<button id="recheck-send-cap-btn" type="button" class="primary">重新检测发送能力</button>
|
||||
<button id="preview-only-btn" type="button" class="ghost">关闭并预览界面</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="capability-bar" aria-label="宿主能力状态">
|
||||
<div class="cap-item">
|
||||
<span class="cap-dot" id="cap-ai-dot"></span>
|
||||
<span>AI 模型:<strong id="cap-ai-text">检测中…</strong></span>
|
||||
</div>
|
||||
<div class="cap-item">
|
||||
<span class="cap-dot" id="cap-send-dot"></span>
|
||||
<span>微信发送:<strong id="cap-send-text">检测中…</strong></span>
|
||||
</div>
|
||||
<div class="cap-item">
|
||||
<span class="cap-dot" id="cap-tts-dot"></span>
|
||||
<span>语音合成:<strong id="cap-tts-text">检测中…</strong></span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-header">
|
||||
<div>
|
||||
<h2>语音回复与 TraceMemo 音色</h2>
|
||||
<p class="hint">
|
||||
自动同步展示 TraceMemo「设置 → 文字转语音」中选定的音色,可配置随机回复文字或随机发送语音。
|
||||
</p>
|
||||
</div>
|
||||
<button id="refresh-voice-btn" type="button" class="ghost">刷新音色状态</button>
|
||||
</div>
|
||||
|
||||
<div class="voice-showcase" id="voice-showcase">
|
||||
<div class="voice-avatar" id="voice-avatar">音</div>
|
||||
<div class="voice-info">
|
||||
<div class="voice-title-row">
|
||||
<strong id="voice-name">正在读取 TraceMemo 选定音色…</strong>
|
||||
<span class="badge" id="voice-badge">未检测</span>
|
||||
<span class="badge muted" id="voice-model-badge">s2.1-pro-free</span>
|
||||
</div>
|
||||
<p class="voice-desc" id="voice-desc">
|
||||
在 TraceMemo「设置 → 文字转语音」中选择音色后,这里会自动展示当前音色详情。
|
||||
</p>
|
||||
<div class="voice-meta-row" id="voice-tags"></div>
|
||||
</div>
|
||||
<div class="voice-actions">
|
||||
<button id="voice-preview-btn" type="button" class="ghost" hidden>试听音色样本</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>默认回复形式</span>
|
||||
<select id="delivery-mode">
|
||||
<option value="random_mix">随机混合(随机回复文字 / 随机发送语音)</option>
|
||||
<option value="text_only">仅回复文字</option>
|
||||
<option value="voice_only">仅发送语音</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field" id="voice-chance-field">
|
||||
<span>随机发送语音概率(0–100%)</span>
|
||||
<input id="voice-chance" type="number" min="0" max="100" value="35" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>单条语音最大字数(超出自动改发文字)</span>
|
||||
<input id="voice-max-chars" type="number" min="20" max="400" value="120" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>指定覆盖音色 ID(可选,留空跟随上方 TraceMemo 音色)</span>
|
||||
<input
|
||||
id="custom-voice-id"
|
||||
type="text"
|
||||
maxlength="80"
|
||||
placeholder="留空则默认使用 TraceMemo 当前选定的音色"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="check">
|
||||
<input id="voice-fallback" type="checkbox" checked />
|
||||
<span>当语音合成未就绪或发送失败时,自动降级为发送文字回复(推荐开启,避免漏回)</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-header">
|
||||
<div>
|
||||
<h2>群聊人格设定</h2>
|
||||
<p class="hint">
|
||||
可准备多套群聊人格(人设背景 + 说话风格),支持全局默认人格或为不同微信群分配专属人格。
|
||||
</p>
|
||||
</div>
|
||||
<div class="inline-actions">
|
||||
<select id="preset-import-select" aria-label="选择预设人格导入">
|
||||
<option value="">+ 导入预设人格…</option>
|
||||
<option value="casual-friend">日常群友</option>
|
||||
<option value="tech-partner">技术搭子</option>
|
||||
<option value="warm-listener">温柔捧场王</option>
|
||||
<option value="witty-vibe">幽默气氛组</option>
|
||||
</select>
|
||||
<button id="persona-add-btn" type="button" class="ghost">新建人格</button>
|
||||
<button id="persona-delete-btn" type="button" class="ghost danger">删除当前</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>当前编辑的人格</span>
|
||||
<select id="persona-select"></select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>人格显示名称</span>
|
||||
<input id="persona-name" type="text" maxlength="36" placeholder="例如:日常群友" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="field">
|
||||
<span>人设背景与角色定位</span>
|
||||
<textarea
|
||||
id="persona-identity"
|
||||
rows="3"
|
||||
maxlength="3000"
|
||||
placeholder="描述机器人在群里的身份、性格特点与处事原则"
|
||||
></textarea>
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<span>说话风格与语气约束</span>
|
||||
<textarea
|
||||
id="persona-style"
|
||||
rows="2"
|
||||
maxlength="1500"
|
||||
placeholder="例如:口语化短句,1-2句话说清,不端架子,不用列表和客服腔"
|
||||
></textarea>
|
||||
</label>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>该人格回复字数上限(40–500)</span>
|
||||
<input id="persona-max-chars" type="number" min="40" max="500" value="180" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>单次回复允许反问上限(0–2,0 代表不主动追问)</span>
|
||||
<input id="persona-follow-up" type="number" min="0" max="2" value="0" />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>触发策略、节奏与安全防护</h2>
|
||||
<p class="hint">扩展在扩展中心启用后即开始接话,接话范围由下方勾选的群聊决定。</p>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>触发方式</span>
|
||||
<select id="trigger-mode">
|
||||
<option value="mention">仅被 @我 时接话</option>
|
||||
<option value="mention_or_wake">被 @我 或命中唤醒词时接话</option>
|
||||
<option value="wake_word">仅命中唤醒词时接话</option>
|
||||
<option value="ambient">自然活跃接话(@我必回 + 普通群消息按概率随机搭话)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>全局默认人格</span>
|
||||
<select id="default-persona-select"></select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="field" id="wake-words-field">
|
||||
<span>唤醒词列表(逗号分隔,最多 16 个)</span>
|
||||
<input id="wake-words" type="text" placeholder="例如:小助手, 搭子, 机器人" />
|
||||
</label>
|
||||
|
||||
<div class="grid three">
|
||||
<label class="field">
|
||||
<span>直接唤醒冷却(秒)</span>
|
||||
<input id="cooldown-seconds" type="number" min="3" max="600" value="20" />
|
||||
</label>
|
||||
<label class="field" id="ambient-chance-field">
|
||||
<span>普通群消息随机接话概率(%)</span>
|
||||
<input id="ambient-chance" type="number" min="0" max="100" value="25" />
|
||||
</label>
|
||||
<label class="field" id="ambient-cooldown-field">
|
||||
<span>环境闲聊冷却(秒)</span>
|
||||
<input id="ambient-cooldown" type="number" min="5" max="1800" value="45" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>短期记忆:每次读取本群最近消息条数(4–40)</span>
|
||||
<input id="context-limit" type="number" min="4" max="40" value="18" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>长期记忆:每回复多少轮自动更新一次群摘要(3–50)</span>
|
||||
<input id="memory-interval" type="number" min="3" max="50" value="8" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="check-row">
|
||||
<label class="check">
|
||||
<input id="suppress-duplicate" type="checkbox" checked />
|
||||
<span>开启重复表达抑制(防止环境闲聊连续发送相同回复)</span>
|
||||
</label>
|
||||
<label class="check">
|
||||
<input id="memory-enabled" type="checkbox" checked />
|
||||
<span>启用群聊长期记忆(按群独立保存固定记忆与历史摘要)</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<hr style="border: 0; border-top: 1px solid var(--border); margin: 14px 0" />
|
||||
|
||||
<label class="check" style="margin-top: 4px">
|
||||
<input id="security-guard-enabled" type="checkbox" checked />
|
||||
<span
|
||||
><strong>开启敏感探测与 AI 二次安全拦截</strong>(第一层:正则确定性阻断提示词套取、敏感词过滤规则试探、端口/root/IP
|
||||
探测及编码外带;第二层:调用 AI 时注入二次安全审查指令,识别伪装话术并拦截)</span
|
||||
>
|
||||
</label>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>命中安全拦截时的处理方式</span>
|
||||
<select id="security-reply-mode">
|
||||
<option value="refuse">返回安全拒答话术</option>
|
||||
<option value="silent">静默忽略不回复</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>安全拒答话术</span>
|
||||
<input
|
||||
id="security-refuse-text"
|
||||
type="text"
|
||||
maxlength="120"
|
||||
value="这个话题我没法回答哈,咱们聊点别的吧~"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="field">
|
||||
<span>AI 二次安全审查拦截提示词(调用模型时注入,识别“通用示例/假设场景”等伪装套话并触发 SECURITY_BLOCK)</span>
|
||||
<textarea
|
||||
id="ai-security-prompt"
|
||||
rows="2"
|
||||
maxlength="600"
|
||||
placeholder="定义需要 AI 在推理时二次识别并拦截的诱导场景…"
|
||||
></textarea>
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<span>自定义敏感屏蔽词(可选,逗号分隔,最多 32 个)</span>
|
||||
<input
|
||||
id="blocked-keywords"
|
||||
type="text"
|
||||
placeholder="例如:内部接口, 测试密码, 后台地址"
|
||||
/>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-header">
|
||||
<div>
|
||||
<h2>生效群聊与单群策略</h2>
|
||||
<p class="hint">
|
||||
先在上方下拉里挑选群聊,选中的会列在下方;每行的「生效」控制该群是否接话。人格、回复形式与群记忆可按群单独设置。
|
||||
</p>
|
||||
</div>
|
||||
<button id="reload-groups-btn" type="button" class="ghost">刷新群列表</button>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<span>选择群聊</span>
|
||||
<div id="roster-picker" class="roster-picker">
|
||||
<button
|
||||
id="roster-toggle"
|
||||
type="button"
|
||||
class="roster-toggle"
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
>
|
||||
选择群聊…
|
||||
</button>
|
||||
<div id="roster-menu" class="roster-menu" hidden>
|
||||
<input
|
||||
id="roster-search"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="搜索群名称或 chatroom ID…"
|
||||
/>
|
||||
<div id="roster-options"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="group-table-header">
|
||||
<span>群聊名称</span>
|
||||
<span>生效</span>
|
||||
<span>绑定人格</span>
|
||||
<span>回复形式</span>
|
||||
<span>群记忆</span>
|
||||
<span>操作</span>
|
||||
</div>
|
||||
<div id="group-list" class="group-list"></div>
|
||||
<p id="group-empty" class="empty-hint">
|
||||
还未选择群聊。请在上方下拉中选择需要接话的群聊。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-header">
|
||||
<div>
|
||||
<h2>群聊记忆管理(基于本机聊天记录均衡采样提炼)</h2>
|
||||
<p class="hint">
|
||||
从 TraceMemo 本机微信记录提炼群记忆:自动按「每人基础条数上限(7 天 12 条/人、30 天 15 条/人)」均衡采样,若总条数未满上限(100/160 条)则自动轮询扩充余量,防止单人刷屏占满上下文。
|
||||
</p>
|
||||
</div>
|
||||
<div class="inline-actions">
|
||||
<select id="memory-group-select" aria-label="选择要管理记忆的群聊">
|
||||
<option value="">选择群聊查看记忆…</option>
|
||||
</select>
|
||||
<button id="memory-extract-7d-btn" type="button" class="ghost">
|
||||
提炼最近 7 天记录
|
||||
</button>
|
||||
<button id="memory-extract-30d-btn" type="button" class="ghost">
|
||||
提炼最近 30 天记录
|
||||
</button>
|
||||
<button id="memory-clear-btn" type="button" class="ghost danger">清空该群记忆</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="meta-line" id="memory-meta">
|
||||
请先在上方下拉框选择一个群聊,即可查看或从本机最近 7 天 / 30 天聊天记录提炼群记忆。
|
||||
</p>
|
||||
|
||||
<label class="field">
|
||||
<span>本群固定记忆与背景备注(手动维护,每次对话最高优先级注入)</span>
|
||||
<textarea
|
||||
id="memory-pinned"
|
||||
rows="2"
|
||||
maxlength="800"
|
||||
placeholder="例如:群主是老王;每周五晚 9 点固定组队;大家喜欢聊独立开发与数码产品。"
|
||||
></textarea>
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<span>本群长期互动记忆摘要(可根据最近 7 天 / 30 天本机聊天记录提炼,也可手动修订)</span>
|
||||
<textarea
|
||||
id="memory-summary"
|
||||
rows="4"
|
||||
maxlength="800"
|
||||
placeholder="点击右上角「提炼最近 7 天记录」或「提炼最近 30 天记录」,即可从 TraceMemo 本机微信数据库中读取该群历史发言并生成长期记忆摘要。"
|
||||
></textarea>
|
||||
</label>
|
||||
|
||||
<div class="inline-actions">
|
||||
<button id="memory-save-btn" type="button" class="ghost">保存该群记忆修改</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>AI 回复预览与发送测试</h2>
|
||||
<p class="hint">
|
||||
使用 TraceMemo 当前配置的 AI 模型测试人格思考与安全拦截效果,或向指定群测试文字/语音发送(需先在扩展中心启用本扩展)。
|
||||
</p>
|
||||
|
||||
<div class="grid two">
|
||||
<label class="field">
|
||||
<span>测试目标群聊(可选,用于读取群记忆或测试真实发送)</span>
|
||||
<select id="test-group-select">
|
||||
<option value="">不指定群聊(仅用当前人格预览)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>模拟群友昵称</span>
|
||||
<input id="test-sender-name" type="text" maxlength="32" value="测试群友" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="field">
|
||||
<span>模拟群友消息 / 测试发送内容</span>
|
||||
<input
|
||||
id="test-message-input"
|
||||
type="text"
|
||||
maxlength="400"
|
||||
value="今晚大家有什么安排?出来聊五毛钱的~"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div class="inline-actions">
|
||||
<button id="preview-reply-btn" type="button" class="ghost">
|
||||
预览 AI 思考回复(不发微信)
|
||||
</button>
|
||||
<button id="test-send-auto-btn" type="button" class="ghost">
|
||||
按配置随机测试发送
|
||||
</button>
|
||||
<button id="test-send-text-btn" type="button" class="ghost">
|
||||
测试发送文字
|
||||
</button>
|
||||
<button id="test-send-voice-btn" type="button" class="ghost">
|
||||
测试发送语音
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<pre id="test-output" class="preview-box" hidden></pre>
|
||||
</section>
|
||||
|
||||
<footer class="footer-bar">
|
||||
<div class="footer-buttons">
|
||||
<button id="save-config-btn" type="button" class="primary">保存全部配置</button>
|
||||
<button id="reload-config-btn" type="button" class="ghost">重新读取</button>
|
||||
</div>
|
||||
<span id="status-banner" class="status-banner" role="status" aria-live="polite"></span>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,651 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f7f9;
|
||||
--surface: #ffffff;
|
||||
--surface-subtle: #f1f5f9;
|
||||
--border: #e2e8f0;
|
||||
--text: #0f172a;
|
||||
--muted: #64748b;
|
||||
--accent: #059669;
|
||||
--accent-hover: #047857;
|
||||
--accent-soft: rgba(5, 150, 105, 0.12);
|
||||
--warn: #d97706;
|
||||
--danger: #dc2626;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #0b0f17;
|
||||
--surface: #131b26;
|
||||
--surface-subtle: #1c2636;
|
||||
--border: #263244;
|
||||
--text: #f1f5f9;
|
||||
--muted: #94a3b8;
|
||||
--accent: #10b981;
|
||||
--accent-hover: #059669;
|
||||
--accent-soft: rgba(16, 185, 129, 0.16);
|
||||
--warn: #f59e0b;
|
||||
--danger: #f87171;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.55 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
padding: 20px 24px 48px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 4px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.subtitle,
|
||||
.hint,
|
||||
.meta-line {
|
||||
margin: 4px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.hero-stats {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.stat-pill {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 8px 14px;
|
||||
min-width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.stat-pill span {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.stat-pill strong {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.capability-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 10px 14px;
|
||||
margin-bottom: 14px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.cap-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.cap-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.cap-dot.ok {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.cap-dot.warn {
|
||||
background: var(--warn);
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 16px 18px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
white-space: normal;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.voice-showcase {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.voice-avatar {
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
border-radius: 10px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.voice-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.voice-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.voice-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.voice-desc {
|
||||
margin: 4px 0 6px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.voice-meta-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.badge.muted {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.badge.warn {
|
||||
background: rgba(217, 119, 6, 0.14);
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.grid.two {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.grid.three {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 680px) {
|
||||
.grid.two,
|
||||
.grid.three {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.hero,
|
||||
.card-header {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.field > span {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
input[type="number"],
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.check-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.inline-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.card-header .inline-actions {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
padding: 7px 13px;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
border: 1px solid transparent;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
button.primary:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.card-header > button {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: transparent;
|
||||
border-color: var(--border);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button.ghost.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.roster-picker {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* 下拉开关:外观对齐同排 select,右侧给个箭头。 */
|
||||
.roster-toggle {
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.roster-toggle::after {
|
||||
content: '▾';
|
||||
float: right;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.roster-options {
|
||||
margin-top: 4px;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.roster-menu {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 4px);
|
||||
max-height: 230px;
|
||||
overflow-y: auto;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 6px;
|
||||
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.18);
|
||||
}
|
||||
|
||||
.roster-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.roster-option:hover {
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
.roster-empty {
|
||||
padding: 10px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.group-table-header {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 1.4fr) 64px minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
padding: 0 8px 6px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.group-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 1.4fr) 64px minmax(120px, 1fr) minmax(130px, 1fr) 80px 88px;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
/* 未勾选生效的群:整行降透明,但仍可编辑人格/回复形式。 */
|
||||
.group-row.is-off {
|
||||
opacity: 0.62;
|
||||
}
|
||||
|
||||
.group-row.is-off:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.group-title {
|
||||
font-weight: 500;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-title small {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.group-table-header {
|
||||
display: none;
|
||||
}
|
||||
.group-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-hint {
|
||||
margin: 12px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.preview-box {
|
||||
margin: 12px 0 0;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-subtle);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.footer-bar {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.footer-buttons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.status-banner {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.status-banner[data-tone="ok"] {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.status-banner[data-tone="error"] {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.hero-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.send-warn-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(220, 38, 38, 0.12);
|
||||
border: 1px solid rgba(220, 38, 38, 0.3);
|
||||
color: #dc2626;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.send-warn-bang {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: #dc2626;
|
||||
color: #ffffff;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.send-unavailable-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: rgba(15, 23, 42, 0.38);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.send-unavailable-mask[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.send-unavailable-dialog {
|
||||
position: relative;
|
||||
max-width: 440px;
|
||||
width: 100%;
|
||||
padding: 26px 28px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(220, 38, 38, 0.28);
|
||||
background: var(--surface);
|
||||
box-shadow: 0 20px 44px rgba(0, 0, 0, 0.2);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.send-unavailable-close {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.send-unavailable-close:hover {
|
||||
background: var(--surface-subtle);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.send-unavailable-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
background: #dc2626;
|
||||
color: #ffffff;
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
box-shadow: 0 6px 16px rgba(220, 38, 38, 0.3);
|
||||
}
|
||||
|
||||
.send-unavailable-dialog h2 {
|
||||
margin: 12px 0 8px;
|
||||
color: #dc2626;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.send-unavailable-dialog p {
|
||||
margin: 0 0 18px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.send-unavailable-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# 关键词回复机器人
|
||||
|
||||
监听微信文本消息,按规则表匹配关键词,命中后经 TraceMemo Gateway 回复。
|
||||
|
||||
两条入口共用同一份配置与同一套判定(`lib/matcher.js`):
|
||||
|
||||
- `message.received` 事件:扩展自己判断范围与冷却,再调用 `tm.wechat.send`;
|
||||
- 自动化动作 `keyword.reply`:只返回回复文本,不发送,发送由宿主的自动化流程完成。
|
||||
|
||||
扩展本身不碰 socket、dylib 或 HTTP,所有发送都经过宿主 Gateway 的权限、授权校验、限流与审计。
|
||||
|
||||
## 目录
|
||||
|
||||
```text
|
||||
keyword-bot/
|
||||
manifest.json 权限、订阅、页面与自动化动作声明
|
||||
background/index.js 事件编排、冷却表、命中统计
|
||||
lib/matcher.js 纯函数:规范化 / 匹配 / 范围 / 模板 / 决策
|
||||
ui/ 配置页(沙箱 iframe,只调用 storage.* / capabilities.get / extension.info)
|
||||
tests/matcher.test.mjs
|
||||
```
|
||||
|
||||
## 功能
|
||||
|
||||
- 规则支持三种匹配方式:`contains`(包含)、`exact`(完全匹配)、`prefix`(以…开头),均不区分大小写;
|
||||
- 每条规则可单独启用/停用,并设置优先级与冷却;
|
||||
- 监听范围可按群限定,可开关私聊,可要求真正 @ 我;
|
||||
- 回复内容支持模板变量;
|
||||
- 配置页展示今日命中数与最近 5 条命中结果。
|
||||
|
||||
## 配置字段
|
||||
|
||||
顶层:
|
||||
|
||||
| 字段 | 类型 | 默认 | 说明 |
|
||||
| ------------------------ | -------- | ------- | ----------------------------------------- |
|
||||
| `configVersion` | number | `2` | 保存时写入;v1(无此字段)读取时自动迁移 |
|
||||
| `enabled` | boolean | `false` | 总开关。缺省关闭,避免安装后立即对外发送 |
|
||||
| `rules` | array | `[]` | 规则表,见下 |
|
||||
| `scope.groups` | string[] | `[]` | 群 id(`xxx@chatroom`);空数组表示全部群 |
|
||||
| `scope.includeDirect` | boolean | `true` | 是否处理私聊 |
|
||||
| `scope.requireMentionMe` | boolean | `false` | 是否只处理真正 @ 登录账号的消息 |
|
||||
|
||||
规则:
|
||||
|
||||
| 字段 | 类型 | 默认 | 约束 |
|
||||
| ----------------- | ------- | ------------- | ------------------------------------------- |
|
||||
| `id` | string | `rule-<序号>` | ≤ 64 字符;冷却键的一部分,尽量稳定 |
|
||||
| `keyword` | string | `''` | ≤ 120 字符;启用中为空的规则会被丢弃 |
|
||||
| `mode` | string | `contains` | `contains` / `exact` / `prefix` |
|
||||
| `reply` | string | `''` | ≤ 2000 字符;启用中为空的规则会被丢弃 |
|
||||
| `cooldownSeconds` | number | `0` | 0–3600,取整到秒 |
|
||||
| `enabled` | boolean | `true` | v1 规则迁移后为 `true`;显式 `false` 才停用 |
|
||||
| `priority` | number | `0` | 0–100 整数,越大越先匹配 |
|
||||
|
||||
配置页保存时只校验**启用中**的规则必须有 `keyword` 与 `reply`;停用的规则允许留空,方便先存草稿。
|
||||
|
||||
## 模板变量
|
||||
|
||||
| 变量 | 含义 |
|
||||
| ----------- | -------------------------------------------------------------------------- |
|
||||
| `{sender}` | 发送者昵称;为空时渲染为「你」。自动化动作路径没有发送者上下文,恒为「你」 |
|
||||
| `{keyword}` | 命中的关键词(规则里的原文) |
|
||||
| `{time}` | 当前本地时间 `HH:mm` |
|
||||
|
||||
未知变量(例如 `{group}`)原样保留,不会被静默删除。渲染结果 trim 后截断到 2000 字符。
|
||||
|
||||
## 优先级与冷却语义
|
||||
|
||||
- 只考虑 `enabled !== false` 的规则;按 `priority` 降序排列,同优先级保持规则在数组中的顺序;
|
||||
- 取**第一个**命中的规则,一条消息最多回复一次(stopOnMatch),不会叠加多条回复;
|
||||
- 冷却键是 `conversationId:ruleId`,即「同一会话 + 同一条规则」各自独立计时;
|
||||
- 冷却只在**发送成功后**写入:发送失败不占用冷却,下一条命中会立刻重试;
|
||||
- 冷却表只存在内存里,扩展进程重启后清空——宁可多回一条,也不跨重启误拦。
|
||||
|
||||
## 统计口径与隐私边界
|
||||
|
||||
存储键 `stats`,结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"dateKey": "2026-11-12",
|
||||
"todayCount": 3,
|
||||
"lastHits": [{ "at": 0, "ruleId": "rule-1", "ok": true }]
|
||||
}
|
||||
```
|
||||
|
||||
- 每条命中记一条,**成功和失败都记**;`todayCount` 统计的是命中的次数(含发送失败);
|
||||
- `lastHits` 最多保留 20 条,配置页只展示最近 5 条;`at` 是 epoch 毫秒;
|
||||
- 跨日后读取会把 `todayCount` 归零,`lastHits` 作为滚动历史保留;
|
||||
- 只记录规则 id、时间与发送结果,**不记录会话 id、消息正文、发送者昵称或群名**;
|
||||
- 统计写入失败只打 warn 日志,不影响回复;
|
||||
- 统计只覆盖事件自动回复,不包含自动化动作 `keyword.reply` 的调用。
|
||||
|
||||
## 测试
|
||||
|
||||
零依赖,Node 内置测试运行器,不安装任何包:
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
|
||||
node --check examples/extensions/keyword-bot/lib/matcher.js
|
||||
node --check examples/extensions/keyword-bot/background/index.js
|
||||
node --check examples/extensions/keyword-bot/ui/app.js
|
||||
```
|
||||
|
||||
用例覆盖:三种匹配方式、大小写、空关键词、禁用规则、优先级与稳定性、群范围与私聊开关、@ 要求、自己发的消息、冷却中/过期、模板替换与未知变量、超长截断、v1 迁移、非法规则丢弃、数值越界收敛、决策顺序。
|
||||
|
||||
`tests/matcher.test.mjs` 中的 fixture 全部为占位数据(`张三`、`李四`、`测试群`、`fixture-room@chatroom`、`wxid_fixture`)。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 不回复自己发送的消息(`isSelf` 直接跳过);
|
||||
- 消息事件是「至多一次」投递:扩展进程重启的瞬间可能丢事件,没有补投队列;
|
||||
- 不读取群名,因此没有 `{group}` 变量;需要按群定制时请拆成多条规则并配合「监听范围」;
|
||||
- 配置缓存窗口为 1 秒,保存后最多 1 秒生效;
|
||||
- 冷却表与配置缓存都在扩展后台进程内存中,进程重启即丢失。
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* 关键词回复机器人。
|
||||
*
|
||||
* 两条入口共用同一份配置与 `lib/matcher.js` 的同一套判定:
|
||||
* 1. `message.received` 事件 → 自己判断范围 / 冷却 → `tm.wechat.send`;
|
||||
* 2. 自动化动作 `keyword.reply` → 只返回回复内容,由宿主 Gateway 发送。
|
||||
*
|
||||
* 发送**永远**经过宿主:本文件里没有任何 socket、dylib 或 HTTP 调用。
|
||||
* 匹配/规范化逻辑全部在 `lib/matcher.js`,本文件只负责编排与统计。
|
||||
*/
|
||||
|
||||
const { normalizeConfig, pickRule, renderReply, shouldReply } = require('../lib/matcher.js')
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
/** 配置缓存窗口:配置页保存后最多 1 秒生效,避免每条消息都读一次 storage。 */
|
||||
const CONFIG_TTL_MS = 1000
|
||||
/** 最近命中记录上限;只保留规则 id、时间与结果,不保留任何会话内容。 */
|
||||
const STATS_HISTORY_LIMIT = 20
|
||||
/** 冷却表清理阈值:超过后剔除已过期项,避免长期运行无限增长。 */
|
||||
const COOLDOWN_PRUNE_SIZE = 500
|
||||
|
||||
let tm = null
|
||||
let cachedConfig = null
|
||||
let cachedAt = 0
|
||||
let cachedStats = null
|
||||
const cooldownUntil = new Map()
|
||||
/** 统计写入串行化:并发消息不互相覆盖 `stats` 快照。 */
|
||||
let statsChain = Promise.resolve()
|
||||
|
||||
function loadConfig() {
|
||||
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return Promise.resolve(cachedConfig)
|
||||
return Promise.resolve(tm.storage.get(CONFIG_KEY))
|
||||
.then((stored) => {
|
||||
cachedConfig = normalizeConfig(stored)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
})
|
||||
.catch((error) => {
|
||||
tm.log.warn(`读取配置失败,本次按未启用处理:${describeError(error)}`)
|
||||
// 读失败也要缓存一小段时间,避免每条消息都打一次失败日志。
|
||||
cachedConfig = normalizeConfig(null)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
})
|
||||
}
|
||||
|
||||
/** 本地时区的 `YYYY-MM-DD`,用于判定「今日」。 */
|
||||
function statsDateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
/** 本地时区的 `HH:mm`,模板变量 `{time}` 与统计展示共用。 */
|
||||
function formatClock(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${hour}:${minute}`
|
||||
}
|
||||
|
||||
function emptyStats(timestamp) {
|
||||
return { dateKey: statsDateKey(timestamp), todayCount: 0, lastHits: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化统计快照。
|
||||
*
|
||||
* 跨日后 `todayCount` 归零;`lastHits` 作为滚动历史保留(它记的是「最近命中」,
|
||||
* 不是「今日命中」)。任何字段缺失或类型不对都退化为空值,统计损坏不能影响回复。
|
||||
*/
|
||||
function normalizeStats(raw, timestamp) {
|
||||
const base = emptyStats(timestamp)
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base
|
||||
const lastHits = Array.isArray(raw.lastHits)
|
||||
? raw.lastHits
|
||||
.filter((hit) => hit && typeof hit === 'object')
|
||||
.map((hit) => ({
|
||||
at: Number(hit.at),
|
||||
ruleId: String(hit.ruleId == null ? '' : hit.ruleId).slice(0, 64),
|
||||
ok: hit.ok === true
|
||||
}))
|
||||
.filter((hit) => Number.isFinite(hit.at) && hit.at > 0 && hit.ruleId)
|
||||
.slice(-STATS_HISTORY_LIMIT)
|
||||
: []
|
||||
const sameDay = raw.dateKey === base.dateKey
|
||||
const count = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
|
||||
return { dateKey: base.dateKey, todayCount: count, lastHits }
|
||||
}
|
||||
|
||||
function loadStats() {
|
||||
if (cachedStats) return Promise.resolve(cachedStats)
|
||||
return Promise.resolve(tm.storage.get(STATS_KEY))
|
||||
.then((stored) => {
|
||||
cachedStats = normalizeStats(stored, Date.now())
|
||||
return cachedStats
|
||||
})
|
||||
.catch(() => {
|
||||
cachedStats = emptyStats(Date.now())
|
||||
return cachedStats
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加一条命中记录并落库。
|
||||
*
|
||||
* 成功与失败都记;只写 `ruleId` / `at` / `ok`,绝不写会话 id、正文或昵称。
|
||||
* 写失败只 warn:统计是旁路,不能因为 storage 异常把回复一起吞掉。
|
||||
*/
|
||||
function recordHit(ruleId, ok) {
|
||||
statsChain = statsChain
|
||||
.then(async () => {
|
||||
const stats = await loadStats()
|
||||
const now = Date.now()
|
||||
const dateKey = statsDateKey(now)
|
||||
if (stats.dateKey !== dateKey) {
|
||||
stats.dateKey = dateKey
|
||||
stats.todayCount = 0
|
||||
}
|
||||
stats.todayCount += 1
|
||||
stats.lastHits = stats.lastHits
|
||||
.concat({ at: now, ruleId: String(ruleId || '').slice(0, 64), ok: ok === true })
|
||||
.slice(-STATS_HISTORY_LIMIT)
|
||||
await tm.storage.set(STATS_KEY, stats)
|
||||
})
|
||||
.catch((error) => {
|
||||
tm.log.warn(`命中统计写入失败:${describeError(error)}`)
|
||||
})
|
||||
return statsChain
|
||||
}
|
||||
|
||||
/** 冷却只在真正发送成功后写入;发送失败不占冷却,下一条可以立刻重试。 */
|
||||
function markCooldown(conversationId, rule, timestamp) {
|
||||
const seconds = Number(rule.cooldownSeconds) || 0
|
||||
cooldownUntil.set(`${conversationId}:${rule.id}`, timestamp + seconds * 1000)
|
||||
if (cooldownUntil.size > COOLDOWN_PRUNE_SIZE) {
|
||||
for (const [key, until] of cooldownUntil) {
|
||||
if (until <= timestamp) cooldownUntil.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function describeError(error) {
|
||||
return error && error.message ? error.message : String(error)
|
||||
}
|
||||
|
||||
async function onMessage(event) {
|
||||
try {
|
||||
const config = await loadConfig()
|
||||
// 交给自动化规则处理时,订阅路径必须彻底闭嘴,否则同一条消息回复两次。
|
||||
if (config.executionMode === 'automation') return
|
||||
const now = Date.now()
|
||||
const verdict = shouldReply(event, config, cooldownUntil, now)
|
||||
if (!verdict.reply || !verdict.rule) return
|
||||
|
||||
const rule = verdict.rule
|
||||
const text = renderReply(rule.reply, {
|
||||
senderName: event.senderName,
|
||||
keyword: rule.keyword,
|
||||
time: formatClock(now)
|
||||
})
|
||||
|
||||
try {
|
||||
await tm.wechat.send({
|
||||
to: event.conversationId,
|
||||
text,
|
||||
// 同一条微信消息在补投/重启后 eventId 不变,交给 Gateway 幂等短路。
|
||||
dedupeKey: event.eventId
|
||||
})
|
||||
} catch (error) {
|
||||
await recordHit(rule.id, false)
|
||||
throw error
|
||||
}
|
||||
|
||||
markCooldown(event.conversationId, rule, Date.now())
|
||||
await recordHit(rule.id, true)
|
||||
tm.log.info(`关键词命中,已发送回复(规则 ${rule.id})`)
|
||||
} catch (error) {
|
||||
tm.log.error(`自动回复失败:${describeError(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function activate(api) {
|
||||
tm = api
|
||||
tm.events.on('message.received', onMessage)
|
||||
|
||||
tm.automation.registerAction({
|
||||
id: 'keyword.reply',
|
||||
title: '关键词回复',
|
||||
description: '按机器人配置匹配关键词并返回回复内容',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { text: { type: 'string' } },
|
||||
required: ['text']
|
||||
},
|
||||
async handler(input) {
|
||||
const config = await loadConfig()
|
||||
if (!config.enabled) {
|
||||
return { success: false, error: '机器人未启用' }
|
||||
}
|
||||
// 订阅模式下这条路径同样会发送:直接跳过,避免与事件路径重复回复。
|
||||
if (config.executionMode === 'subscribe') {
|
||||
return { success: true, output: { matched: false, skipped: 'subscribe-mode' } }
|
||||
}
|
||||
const rule = pickRule(input.text, config)
|
||||
if (!rule) {
|
||||
return { success: true, output: { matched: false } }
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
output: { matched: true, ruleId: rule.id },
|
||||
// 动作路径没有发送者上下文,`{sender}` 会渲染成「你」。
|
||||
reply: {
|
||||
type: 'text',
|
||||
text: renderReply(rule.reply, {
|
||||
keyword: rule.keyword,
|
||||
time: formatClock(Date.now())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
tm.log.info('关键词回复机器人已加载')
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 关键词回复的纯函数层:配置规范化、匹配、范围判定、模板渲染、决策。
|
||||
*
|
||||
* 契约:
|
||||
* - 全部函数无副作用、不读写 storage、不打印日志,便于单测与后台进程复用;
|
||||
* - 输入一律容忍 `undefined` / 错误类型,坏配置退化为「不回复」而不是抛错;
|
||||
* - `enabled` 在任何一层都是硬开关:配置损坏时不能自动对外发送。
|
||||
*/
|
||||
|
||||
/** 当前配置结构版本。v1 没有该字段,读取时按 v1 迁移。 */
|
||||
const CONFIG_VERSION = 2
|
||||
|
||||
/** 与 UI、宿主动作输出保持一致的长度上限(字符)。 */
|
||||
const MAX_RULE_ID_LENGTH = 64
|
||||
const MAX_KEYWORD_LENGTH = 120
|
||||
const MAX_REPLY_LENGTH = 2000
|
||||
const MAX_GROUPS = 200
|
||||
|
||||
const MODES = new Set(['contains', 'exact', 'prefix'])
|
||||
|
||||
/**
|
||||
* 两条回复入口的执行模式。
|
||||
*
|
||||
* 同一条消息若同时被「事件订阅」和「自动化动作」处理,会回复两次。
|
||||
* 这里用互斥模式从根上避免:默认保留订阅(兼容旧用户),
|
||||
* 切到 `automation` 后订阅路径完全不再发送。
|
||||
*/
|
||||
const EXECUTION_MODES = new Set(['subscribe', 'automation'])
|
||||
|
||||
/**
|
||||
* 把任意来源的配置规范化为 `configVersion: 2`。
|
||||
*
|
||||
* 启用中的空规则丢弃,停用的空规则保留为草稿;顶层 `enabled` 缺省 `false`,
|
||||
* 配置缺失或损坏时宁可静默,也不能自动群发。
|
||||
*
|
||||
* @param {unknown} raw storage 里读出的原始值
|
||||
*/
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const sourceRules = Array.isArray(input.rules) ? input.rules : []
|
||||
const rules = sourceRules
|
||||
.filter((rule) => rule && typeof rule === 'object' && !Array.isArray(rule))
|
||||
.map((rule, index) => ({
|
||||
id: String(rule.id || `rule-${index + 1}`).slice(0, MAX_RULE_ID_LENGTH),
|
||||
keyword: String(rule.keyword == null ? '' : rule.keyword).slice(0, MAX_KEYWORD_LENGTH),
|
||||
mode: MODES.has(rule.mode) ? rule.mode : 'contains',
|
||||
reply: String(rule.reply == null ? '' : rule.reply).slice(0, MAX_REPLY_LENGTH),
|
||||
cooldownSeconds: clampNumber(rule.cooldownSeconds, 0, 3600),
|
||||
// v1 规则没有该字段;只有显式 false 才算禁用。
|
||||
enabled: rule.enabled !== false,
|
||||
priority: clampNumber(rule.priority, 0, 100)
|
||||
}))
|
||||
.filter((rule) => rule.enabled === false || (rule.keyword.trim() && rule.reply.trim()))
|
||||
|
||||
const scope = input.scope && typeof input.scope === 'object' ? input.scope : {}
|
||||
return {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: input.enabled === true,
|
||||
executionMode: EXECUTION_MODES.has(input.executionMode) ? input.executionMode : 'subscribe',
|
||||
rules,
|
||||
scope: {
|
||||
groups: Array.isArray(scope.groups)
|
||||
? scope.groups
|
||||
.map((id) => String(id == null ? '' : id).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, MAX_GROUPS)
|
||||
: [],
|
||||
includeDirect: scope.includeDirect !== false,
|
||||
requireMentionMe: scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条规则是否命中文本:大小写不敏感;`exact` / `prefix` 先 trim,
|
||||
* `contains` 只 trim 关键词;空关键词恒为 false。
|
||||
*
|
||||
* @param {unknown} text 消息正文
|
||||
* @param {{ keyword?: unknown, mode?: unknown }} rule
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function matchRule(text, rule) {
|
||||
const keyword = String((rule && rule.keyword) == null ? '' : rule.keyword)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (!keyword) return false
|
||||
const haystack = String(text == null ? '' : text).toLowerCase()
|
||||
const mode = rule && MODES.has(rule.mode) ? rule.mode : 'contains'
|
||||
if (mode === 'exact') return haystack.trim() === keyword
|
||||
if (mode === 'prefix') return haystack.trim().startsWith(keyword)
|
||||
return haystack.includes(keyword)
|
||||
}
|
||||
|
||||
/**
|
||||
* 选出唯一命中的规则:`priority` 降序、同优先级保持数组顺序,取第一个命中。
|
||||
*
|
||||
* 这就是 stopOnMatch 语义:一条消息最多回复一次,命中即停。
|
||||
* 禁用规则(`enabled === false`)不参与匹配。
|
||||
*
|
||||
* @param {unknown} text
|
||||
* @param {object} config normalizeConfig 的产物
|
||||
*/
|
||||
function pickRule(text, config) {
|
||||
const rules = config && Array.isArray(config.rules) ? config.rules : []
|
||||
const candidates = rules
|
||||
.map((rule, index) => ({ rule, index }))
|
||||
.filter((item) => item.rule && item.rule.enabled !== false)
|
||||
// 显式带下标排序,避免依赖引擎排序稳定性。
|
||||
.sort((a, b) => (b.rule.priority || 0) - (a.rule.priority || 0) || a.index - b.index)
|
||||
for (const item of candidates) {
|
||||
if (matchRule(text, item.rule)) return item.rule
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话是否在生效范围内。
|
||||
*
|
||||
* - 群聊:`groups` 为空表示全部群;非空时必须包含 `event.conversationId`;
|
||||
* - 私聊:只看 `includeDirect`。
|
||||
*
|
||||
* 范围在规则匹配之前判定:范围外的会话连匹配都不做,避免误触统计。
|
||||
*/
|
||||
function inScope(event, config) {
|
||||
const scope = (config && config.scope) || {}
|
||||
if (event && event.isGroup) {
|
||||
const groups = Array.isArray(scope.groups) ? scope.groups : []
|
||||
return groups.length === 0 || groups.includes(event.conversationId)
|
||||
}
|
||||
return scope.includeDirect !== false
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染回复模板。
|
||||
*
|
||||
* 支持 `{sender}`(发送者昵称,空则「你」)、`{keyword}`(命中关键词)、
|
||||
* `{time}`(调用方给的本地时间字符串,缺省空串)。未知 `{xxx}` 原样保留,
|
||||
* 方便用户在模板里写其它占位而不是被静默吃掉。结果 trim 后截断到 2000 字符。
|
||||
*/
|
||||
function renderReply(template, ctx) {
|
||||
const source = String(template == null ? '' : template)
|
||||
const context = ctx && typeof ctx === 'object' ? ctx : {}
|
||||
const sender = String(context.senderName == null ? '' : context.senderName).trim() || '你'
|
||||
const keyword = String(context.keyword == null ? '' : context.keyword)
|
||||
const time = String(context.time == null ? '' : context.time)
|
||||
const rendered = source.replace(/\{(sender|keyword|time)\}/g, (match, token) => {
|
||||
if (token === 'sender') return sender
|
||||
if (token === 'keyword') return keyword
|
||||
if (token === 'time') return time
|
||||
return match
|
||||
})
|
||||
return rendered.trim().slice(0, MAX_REPLY_LENGTH)
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合决策:是否回复、用哪条规则、为什么。
|
||||
*
|
||||
* `reason` 取值固定,可直接用于日志/统计口径:
|
||||
* `disabled` | `self` | `type` | `scope` | `mention` | `no_match` | `cooldown` | `ok`。
|
||||
*
|
||||
* 判断顺序固定为:总开关 → 自己发的 → 消息类型 → 会话范围 → @ 要求 → 规则匹配 → 冷却。
|
||||
* 冷却键为 `conversationId:ruleId`,值为到期时间戳(epoch 毫秒),`now < until` 即冷却中。
|
||||
* 冷却表允许是 `Map` 或普通对象,后台进程重启后自然清空(宁可多回一条,也不跨重启误拦)。
|
||||
*
|
||||
* @param {object} event 宿主的 message.received 事件
|
||||
* @param {object} config normalizeConfig 的产物
|
||||
* @param {Map<string, number>|Record<string, number>} [cooldownUntil]
|
||||
* @param {number} [now] epoch 毫秒,缺省取当前时间
|
||||
*/
|
||||
function shouldReply(event, config, cooldownUntil, now) {
|
||||
if (!config || config.enabled !== true) {
|
||||
return { reply: false, rule: null, reason: 'disabled' }
|
||||
}
|
||||
if (!event || event.isSelf === true) {
|
||||
return { reply: false, rule: null, reason: 'self' }
|
||||
}
|
||||
if (event.type !== 'text') {
|
||||
return { reply: false, rule: null, reason: 'type' }
|
||||
}
|
||||
if (!inScope(event, config)) {
|
||||
return { reply: false, rule: null, reason: 'scope' }
|
||||
}
|
||||
if (config.scope && config.scope.requireMentionMe === true && event.mentionsMe !== true) {
|
||||
return { reply: false, rule: null, reason: 'mention' }
|
||||
}
|
||||
const rule = pickRule(event.text, config)
|
||||
if (!rule) {
|
||||
return { reply: false, rule: null, reason: 'no_match' }
|
||||
}
|
||||
const currentTime = Number.isFinite(now) ? now : Date.now()
|
||||
const key = `${event.conversationId}:${rule.id}`
|
||||
if (currentTime < readCooldown(cooldownUntil, key)) {
|
||||
return { reply: false, rule: null, reason: 'cooldown' }
|
||||
}
|
||||
return { reply: true, rule, reason: 'ok' }
|
||||
}
|
||||
|
||||
/** 冷却表读取:兼容 Map 与普通对象,缺失值按 0(永不冷却)。 */
|
||||
function readCooldown(table, key) {
|
||||
if (!table) return 0
|
||||
const value = table instanceof Map ? table.get(key) : table[key]
|
||||
const until = Number(value)
|
||||
return Number.isFinite(until) ? until : 0
|
||||
}
|
||||
|
||||
/** 收敛到 [min, max] 的整数;非数字 / NaN 一律当 0。 */
|
||||
function clampNumber(value, min, max) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return 0
|
||||
return Math.min(Math.max(Math.round(numeric), min), max)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CONFIG_VERSION,
|
||||
EXECUTION_MODES,
|
||||
normalizeConfig,
|
||||
matchRule,
|
||||
pickRule,
|
||||
inScope,
|
||||
renderReply,
|
||||
shouldReply
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.keyword-bot",
|
||||
"name": "关键词回复机器人",
|
||||
"version": "1.0.1",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.subscribe",
|
||||
"contacts.list",
|
||||
"wechat.send.text",
|
||||
"storage",
|
||||
"automation.action"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": [
|
||||
"text"
|
||||
],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": false,
|
||||
"includeSelf": false
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "settings",
|
||||
"title": "机器人配置"
|
||||
}
|
||||
],
|
||||
"automationActions": [
|
||||
{
|
||||
"id": "keyword.reply",
|
||||
"title": "关键词回复",
|
||||
"description": "按机器人配置匹配关键词并返回回复内容"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import matcher from '../lib/matcher.js'
|
||||
|
||||
const { normalizeConfig, matchRule, pickRule, inScope, renderReply, shouldReply } = matcher
|
||||
|
||||
const GROUP_ID = 'fixture-room@chatroom'
|
||||
const NOW = 1_700_000_000_000
|
||||
|
||||
/** 构造一份启用状态下的最小配置,参数按需覆盖。 */
|
||||
function buildConfig(overrides = {}) {
|
||||
return normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [{ id: 'rule-1', keyword: '关键词', mode: 'contains', reply: '默认回复' }],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false },
|
||||
...overrides
|
||||
})
|
||||
}
|
||||
|
||||
/** 构造一条群聊文本消息事件。 */
|
||||
function buildEvent(overrides = {}) {
|
||||
return {
|
||||
eventId: 'event-fixture-1',
|
||||
accountId: 'account-fixture',
|
||||
conversationId: GROUP_ID,
|
||||
messageId: 'message-fixture-1',
|
||||
senderId: 'wxid_fixture',
|
||||
senderName: '张三',
|
||||
isGroup: true,
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text: '你好,关键词',
|
||||
mentionsMe: false,
|
||||
timestamp: NOW,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
test('exact 模式比较 trim 后的完整文本', () => {
|
||||
const rule = { keyword: '关键词', mode: 'exact' }
|
||||
assert.equal(matchRule(' 关键词 ', rule), true)
|
||||
assert.equal(matchRule('你好,关键词', rule), false)
|
||||
})
|
||||
|
||||
test('exact 模式不匹配大小写不同的关键词之外的差异', () => {
|
||||
const rule = { keyword: 'Hello', mode: 'exact' }
|
||||
assert.equal(matchRule('hello', rule), true)
|
||||
assert.equal(matchRule('hello world', rule), false)
|
||||
})
|
||||
|
||||
test('contains 模式匹配任意位置的子串', () => {
|
||||
const rule = { keyword: '关键词', mode: 'contains' }
|
||||
assert.equal(matchRule('前面的关键词后面', rule), true)
|
||||
assert.equal(matchRule('完全无关', rule), false)
|
||||
})
|
||||
|
||||
test('prefix 模式只匹配开头', () => {
|
||||
const rule = { keyword: '你好', mode: 'prefix' }
|
||||
assert.equal(matchRule(' 你好世界', rule), true)
|
||||
assert.equal(matchRule('世界你好', rule), false)
|
||||
})
|
||||
|
||||
test('匹配对大小写不敏感', () => {
|
||||
assert.equal(matchRule('Say HELLO now', { keyword: 'hello', mode: 'contains' }), true)
|
||||
assert.equal(matchRule('HELLO WORLD', { keyword: 'hello', mode: 'prefix' }), true)
|
||||
})
|
||||
|
||||
test('空关键词在任何模式下都不命中', () => {
|
||||
for (const mode of ['contains', 'exact', 'prefix']) {
|
||||
assert.equal(matchRule('任意文本', { keyword: ' ', mode }), false)
|
||||
assert.equal(matchRule('', { keyword: '', mode }), false)
|
||||
}
|
||||
})
|
||||
|
||||
test('pickRule 跳过禁用规则', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'disabled', keyword: '关键词', reply: '不会发送', enabled: false },
|
||||
{ id: 'active', keyword: '关键词', reply: '会发送' }
|
||||
]
|
||||
})
|
||||
const rule = pickRule('关键词', config)
|
||||
assert.equal(rule.id, 'active')
|
||||
})
|
||||
|
||||
test('pickRule 按 priority 降序选择', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'low', keyword: '关键词', reply: '低', priority: 10 },
|
||||
{ id: 'high', keyword: '关键词', reply: '高', priority: 90 }
|
||||
]
|
||||
})
|
||||
assert.equal(pickRule('关键词', config).id, 'high')
|
||||
})
|
||||
|
||||
test('同优先级保持数组顺序(先定义先命中)', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'first', keyword: '关键词', reply: '一', priority: 50 },
|
||||
{ id: 'second', keyword: '关键词', reply: '二', priority: 50 }
|
||||
]
|
||||
})
|
||||
assert.equal(pickRule('关键词', config).id, 'first')
|
||||
})
|
||||
|
||||
test('同一条消息只返回一个规则(stopOnMatch)', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'a', keyword: '关键词', reply: '一', priority: 1 },
|
||||
{ id: 'b', keyword: '关键词', reply: '二', priority: 2 }
|
||||
]
|
||||
})
|
||||
const rule = pickRule('关键词 关键词', config)
|
||||
assert.equal(rule.id, 'b')
|
||||
})
|
||||
|
||||
test('群范围命中指定群', () => {
|
||||
const config = buildConfig({ scope: { groups: [GROUP_ID] } })
|
||||
assert.equal(inScope(buildEvent(), config), true)
|
||||
})
|
||||
|
||||
test('群范围排除未列出的群', () => {
|
||||
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
|
||||
assert.equal(inScope(buildEvent(), config), false)
|
||||
})
|
||||
|
||||
test('groups 为空表示全部群聊', () => {
|
||||
const config = buildConfig({ scope: { groups: [] } })
|
||||
assert.equal(inScope(buildEvent(), config), true)
|
||||
})
|
||||
|
||||
test('includeDirect 为 false 时不处理私聊', () => {
|
||||
const closed = buildConfig({ scope: { groups: [], includeDirect: false } })
|
||||
const open = buildConfig({ scope: { groups: [], includeDirect: true } })
|
||||
const direct = buildEvent({ isGroup: false, conversationId: 'wxid_fixture' })
|
||||
assert.equal(inScope(direct, closed), false)
|
||||
assert.equal(inScope(direct, open), true)
|
||||
})
|
||||
|
||||
test('requireMentionMe 只放行真正 @ 我的消息', () => {
|
||||
const config = buildConfig({ scope: { groups: [], requireMentionMe: true } })
|
||||
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'mention')
|
||||
assert.equal(shouldReply(buildEvent({ mentionsMe: true }), config, new Map(), NOW).reason, 'ok')
|
||||
})
|
||||
|
||||
test('自己发的消息不回复', () => {
|
||||
const verdict = shouldReply(buildEvent({ isSelf: true }), buildConfig(), new Map(), NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'self' })
|
||||
})
|
||||
|
||||
test('非文本消息不回复', () => {
|
||||
const verdict = shouldReply(buildEvent({ type: 'image' }), buildConfig(), new Map(), NOW)
|
||||
assert.equal(verdict.reason, 'type')
|
||||
})
|
||||
|
||||
test('总开关关闭时不回复', () => {
|
||||
const config = buildConfig({ enabled: false })
|
||||
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'disabled')
|
||||
assert.equal(shouldReply(buildEvent(), null, new Map(), NOW).reason, 'disabled')
|
||||
})
|
||||
|
||||
test('没有命中规则时 reason 为 no_match', () => {
|
||||
const verdict = shouldReply(buildEvent({ text: '无关内容' }), buildConfig(), new Map(), NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'no_match' })
|
||||
})
|
||||
|
||||
test('冷却中不回复', () => {
|
||||
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW + 30_000]])
|
||||
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'cooldown' })
|
||||
})
|
||||
|
||||
test('冷却过期后恢复回复', () => {
|
||||
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW]])
|
||||
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
|
||||
assert.equal(verdict.reply, true)
|
||||
assert.equal(verdict.reason, 'ok')
|
||||
assert.equal(verdict.rule.id, 'rule-1')
|
||||
})
|
||||
|
||||
test('冷却表也支持普通对象', () => {
|
||||
const cooldown = { [`${GROUP_ID}:rule-1`]: NOW + 1 }
|
||||
assert.equal(shouldReply(buildEvent(), buildConfig(), cooldown, NOW).reason, 'cooldown')
|
||||
assert.equal(shouldReply(buildEvent(), buildConfig(), {}, NOW).reason, 'ok')
|
||||
})
|
||||
|
||||
test('模板变量按上下文替换', () => {
|
||||
const text = renderReply('{sender} 说了 {keyword},现在是 {time}', {
|
||||
senderName: '张三',
|
||||
keyword: '关键词',
|
||||
time: '09:05'
|
||||
})
|
||||
assert.equal(text, '张三 说了 关键词,现在是 09:05')
|
||||
})
|
||||
|
||||
test('发送者昵称为空时渲染为「你」', () => {
|
||||
assert.equal(renderReply('{sender}', { senderName: ' ' }), '你')
|
||||
assert.equal(renderReply('{sender}', {}), '你')
|
||||
})
|
||||
|
||||
test('未知变量原样保留', () => {
|
||||
const text = renderReply('{sender} 和 {group}', { senderName: '李四' })
|
||||
assert.equal(text, '李四 和 {group}')
|
||||
})
|
||||
|
||||
test('模板缺失的时间变量渲染为空串', () => {
|
||||
assert.equal(renderReply('[{time}]', {}), '[]')
|
||||
})
|
||||
|
||||
test('渲染结果 trim 后截断到 2000 字符', () => {
|
||||
const input = ` ${'长'.repeat(2100)} `
|
||||
const text = renderReply(input, {})
|
||||
assert.equal(text.length, 2000)
|
||||
assert.equal(text, '长'.repeat(2000))
|
||||
})
|
||||
|
||||
test('v1 配置迁移补齐 enabled / priority 与 configVersion', () => {
|
||||
const config = normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [{ id: 'old', keyword: '关键词', mode: 'contains', reply: '旧规则' }],
|
||||
scope: { groups: ['fixture-room@chatroom'] }
|
||||
})
|
||||
assert.equal(config.configVersion, 2)
|
||||
assert.equal(config.rules.length, 1)
|
||||
assert.equal(config.rules[0].enabled, true)
|
||||
assert.equal(config.rules[0].priority, 0)
|
||||
assert.equal(config.scope.includeDirect, true)
|
||||
assert.equal(config.scope.requireMentionMe, false)
|
||||
})
|
||||
|
||||
test('keyword 或 reply 为空的启用规则被丢弃,停用草稿保留', () => {
|
||||
const config = normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [
|
||||
{ id: 'no-keyword', keyword: ' ', reply: '有回复' },
|
||||
{ id: 'no-reply', keyword: '有词', reply: ' ' },
|
||||
{ id: 'draft', keyword: '', reply: '', enabled: false },
|
||||
{ id: 'ok', keyword: '有词', reply: '有回复' }
|
||||
]
|
||||
})
|
||||
assert.deepEqual(
|
||||
config.rules.map((rule) => rule.id),
|
||||
['draft', 'ok']
|
||||
)
|
||||
})
|
||||
|
||||
test('非对象与缺失字段的配置退化为未启用空配置', () => {
|
||||
for (const raw of [null, undefined, 'broken', 42, []]) {
|
||||
const config = normalizeConfig(raw)
|
||||
assert.equal(config.configVersion, 2)
|
||||
assert.equal(config.enabled, false)
|
||||
assert.deepEqual(config.rules, [])
|
||||
assert.deepEqual(config.scope, { groups: [], includeDirect: true, requireMentionMe: false })
|
||||
}
|
||||
})
|
||||
|
||||
test('越界数值收敛到边界,非法值按 0', () => {
|
||||
const config = normalizeConfig({
|
||||
rules: [
|
||||
{ id: 'clamp-high', keyword: '一', reply: '一', cooldownSeconds: 99_999, priority: 999 },
|
||||
{ id: 'clamp-low', keyword: '二', reply: '二', cooldownSeconds: -5, priority: -5 },
|
||||
{ id: 'nan', keyword: '三', reply: '三', cooldownSeconds: 'oops', priority: 'oops' }
|
||||
]
|
||||
})
|
||||
assert.equal(config.rules[0].cooldownSeconds, 3600)
|
||||
assert.equal(config.rules[0].priority, 100)
|
||||
assert.equal(config.rules[1].cooldownSeconds, 0)
|
||||
assert.equal(config.rules[1].priority, 0)
|
||||
assert.equal(config.rules[2].cooldownSeconds, 0)
|
||||
assert.equal(config.rules[2].priority, 0)
|
||||
})
|
||||
|
||||
test('群范围过滤先于规则匹配,范围外不产生命中', () => {
|
||||
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
|
||||
const verdict = shouldReply(buildEvent(), config, new Map(), NOW)
|
||||
assert.equal(verdict.reason, 'scope')
|
||||
assert.equal(verdict.rule, null)
|
||||
})
|
||||
@@ -0,0 +1,495 @@
|
||||
const EXTENSION_ID = 'com.example.keyword-bot'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
const CONFIG_VERSION = 2
|
||||
const MAX_KEYWORD_LENGTH = 120
|
||||
const MAX_REPLY_LENGTH = 2000
|
||||
const STATS_PREVIEW = 5
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: false,
|
||||
rules: [
|
||||
{
|
||||
id: 'rule-1',
|
||||
keyword: '你好',
|
||||
mode: 'contains',
|
||||
reply: '你好呀,{sender}!',
|
||||
cooldownSeconds: 30,
|
||||
enabled: true,
|
||||
priority: 0
|
||||
}
|
||||
],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false }
|
||||
}
|
||||
|
||||
const pending = new Map()
|
||||
let sequence = 0
|
||||
let config = clone(DEFAULT_CONFIG)
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = `req-${++sequence}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const entry = pending.get(data.requestId)
|
||||
if (!entry) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) entry.resolve(data.result)
|
||||
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
|
||||
})
|
||||
|
||||
const rulesContainer = document.getElementById('rules')
|
||||
const status = document.getElementById('status')
|
||||
const statsSummary = document.getElementById('stats-summary')
|
||||
const statsList = document.getElementById('stats-list')
|
||||
const groupPicker = document.getElementById('group-picker')
|
||||
const groupChips = document.getElementById('group-chips')
|
||||
const groupSearch = document.getElementById('group-search')
|
||||
const groupOptions = document.getElementById('group-options')
|
||||
|
||||
let allGroups = []
|
||||
let selectedGroupIds = new Set()
|
||||
let groupLoadError = ''
|
||||
|
||||
function groupDisplayName(group) {
|
||||
if (!group) return ''
|
||||
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
|
||||
}
|
||||
|
||||
function renderGroupChips() {
|
||||
groupChips.textContent = ''
|
||||
groupChips.hidden = selectedGroupIds.size === 0
|
||||
for (const id of selectedGroupIds) {
|
||||
const group = allGroups.find((item) => item.id === id)
|
||||
const chip = document.createElement('span')
|
||||
chip.className = 'group-chip'
|
||||
const name = document.createElement('span')
|
||||
name.textContent = group ? group.name || id : id
|
||||
name.title = id
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'group-chip-remove'
|
||||
remove.textContent = '×'
|
||||
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
|
||||
remove.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
selectedGroupIds.delete(id)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
})
|
||||
chip.append(name, remove)
|
||||
groupChips.append(chip)
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroupOptions() {
|
||||
if (groupOptions.hidden) return
|
||||
const query = groupSearch.value.trim().toLowerCase()
|
||||
groupOptions.textContent = ''
|
||||
if (groupLoadError) {
|
||||
groupOptions.append(emptyGroupOption(groupLoadError))
|
||||
return
|
||||
}
|
||||
if (!allGroups.length) {
|
||||
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
|
||||
return
|
||||
}
|
||||
const matches = allGroups.filter((group) => {
|
||||
if (!query) return true
|
||||
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
|
||||
})
|
||||
if (!matches.length) {
|
||||
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
|
||||
return
|
||||
}
|
||||
for (const group of matches.slice(0, 200)) {
|
||||
const option = document.createElement('label')
|
||||
option.className = 'group-option'
|
||||
const checkbox = document.createElement('input')
|
||||
checkbox.type = 'checkbox'
|
||||
checkbox.checked = selectedGroupIds.has(group.id)
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedGroupIds.add(group.id)
|
||||
else selectedGroupIds.delete(group.id)
|
||||
renderGroupChips()
|
||||
})
|
||||
const text = document.createElement('span')
|
||||
text.textContent = groupDisplayName(group)
|
||||
option.append(checkbox, text)
|
||||
groupOptions.append(option)
|
||||
}
|
||||
}
|
||||
|
||||
function emptyGroupOption(text) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-option-empty'
|
||||
empty.textContent = text
|
||||
return empty
|
||||
}
|
||||
|
||||
function openGroupOptions() {
|
||||
groupOptions.hidden = false
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function closeGroupOptions() {
|
||||
groupOptions.hidden = true
|
||||
groupSearch.value = ''
|
||||
}
|
||||
|
||||
groupSearch.addEventListener('focus', openGroupOptions)
|
||||
groupSearch.addEventListener('input', openGroupOptions)
|
||||
groupSearch.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
closeGroupOptions()
|
||||
groupSearch.blur()
|
||||
}
|
||||
})
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!groupPicker.contains(event.target)) closeGroupOptions()
|
||||
})
|
||||
|
||||
async function loadGroups() {
|
||||
try {
|
||||
const result = await callHost('contacts.listGroups', {})
|
||||
allGroups = result && Array.isArray(result.groups) ? result.groups : []
|
||||
groupLoadError = ''
|
||||
} catch (error) {
|
||||
allGroups = []
|
||||
groupLoadError = `群列表读取失败:${error.message}`
|
||||
}
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function setStatus(text, kind) {
|
||||
status.textContent = text
|
||||
status.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function clampInteger(value, min, max, fallback) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.min(Math.max(Math.round(numeric), min), max)
|
||||
}
|
||||
|
||||
function newRuleId() {
|
||||
return `rule-${Date.now().toString(36)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面侧的轻量规范化:只用于展示与回写,真正的判定在后台 lib/matcher.js。
|
||||
* 缺字段一律补默认值,保证 v1 配置打开后能直接编辑。
|
||||
*/
|
||||
function normalizeRule(rule, index) {
|
||||
const source = rule && typeof rule === 'object' ? rule : {}
|
||||
return {
|
||||
id: String(source.id || `rule-${index + 1}`).slice(0, 64),
|
||||
keyword: String(source.keyword == null ? '' : source.keyword).slice(0, MAX_KEYWORD_LENGTH),
|
||||
mode: ['contains', 'exact', 'prefix'].includes(source.mode) ? source.mode : 'contains',
|
||||
reply: String(source.reply == null ? '' : source.reply).slice(0, MAX_REPLY_LENGTH),
|
||||
cooldownSeconds: clampInteger(source.cooldownSeconds, 0, 3600, 0),
|
||||
enabled: source.enabled !== false,
|
||||
priority: clampInteger(source.priority, 0, 100, 0)
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStoredConfig(stored) {
|
||||
if (!stored || typeof stored !== 'object') return clone(DEFAULT_CONFIG)
|
||||
const scope = stored.scope && typeof stored.scope === 'object' ? stored.scope : {}
|
||||
return {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: stored.enabled === true,
|
||||
rules: Array.isArray(stored.rules)
|
||||
? stored.rules.map(normalizeRule)
|
||||
: clone(DEFAULT_CONFIG.rules),
|
||||
scope: {
|
||||
groups: Array.isArray(scope.groups)
|
||||
? scope.groups.map((id) => String(id).trim()).filter(Boolean)
|
||||
: [],
|
||||
includeDirect: scope.includeDirect !== false,
|
||||
requireMentionMe: scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function field(label, control) {
|
||||
const wrapper = document.createElement('label')
|
||||
wrapper.className = 'field'
|
||||
const caption = document.createElement('span')
|
||||
caption.textContent = label
|
||||
wrapper.append(caption, control)
|
||||
return wrapper
|
||||
}
|
||||
|
||||
function renderRules() {
|
||||
rulesContainer.textContent = ''
|
||||
config.rules.forEach((rule, index) => {
|
||||
const card = document.createElement('article')
|
||||
card.className = 'rule-card'
|
||||
if (!rule.enabled) card.classList.add('is-disabled')
|
||||
|
||||
const head = document.createElement('div')
|
||||
head.className = 'rule-head'
|
||||
const title = document.createElement('strong')
|
||||
title.textContent = `规则 ${index + 1}`
|
||||
const toggle = document.createElement('label')
|
||||
toggle.className = 'check'
|
||||
const enabledInput = document.createElement('input')
|
||||
enabledInput.type = 'checkbox'
|
||||
enabledInput.checked = rule.enabled
|
||||
enabledInput.addEventListener('change', () => {
|
||||
rule.enabled = enabledInput.checked
|
||||
card.classList.toggle('is-disabled', !rule.enabled)
|
||||
})
|
||||
const toggleText = document.createElement('span')
|
||||
toggleText.textContent = '启用'
|
||||
toggle.append(enabledInput, toggleText)
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'ghost danger'
|
||||
remove.textContent = '删除'
|
||||
remove.addEventListener('click', () => {
|
||||
config.rules.splice(index, 1)
|
||||
renderRules()
|
||||
})
|
||||
const headActions = document.createElement('div')
|
||||
headActions.className = 'rule-head-actions'
|
||||
headActions.append(toggle, remove)
|
||||
head.append(title, headActions)
|
||||
|
||||
const keywordInput = document.createElement('input')
|
||||
keywordInput.type = 'text'
|
||||
keywordInput.maxLength = MAX_KEYWORD_LENGTH
|
||||
keywordInput.value = rule.keyword
|
||||
keywordInput.addEventListener('input', () => {
|
||||
rule.keyword = keywordInput.value
|
||||
})
|
||||
|
||||
const modeSelect = document.createElement('select')
|
||||
;[
|
||||
['contains', '包含'],
|
||||
['exact', '完全匹配'],
|
||||
['prefix', '以…开头']
|
||||
].forEach(([value, label]) => {
|
||||
const option = document.createElement('option')
|
||||
option.value = value
|
||||
option.textContent = label
|
||||
option.selected = rule.mode === value
|
||||
modeSelect.append(option)
|
||||
})
|
||||
modeSelect.addEventListener('change', () => {
|
||||
rule.mode = modeSelect.value
|
||||
})
|
||||
|
||||
const replyInput = document.createElement('textarea')
|
||||
replyInput.rows = 2
|
||||
replyInput.maxLength = MAX_REPLY_LENGTH
|
||||
replyInput.value = rule.reply
|
||||
replyInput.addEventListener('input', () => {
|
||||
rule.reply = replyInput.value
|
||||
})
|
||||
const replyBlock = field('回复内容', replyInput)
|
||||
const replyHint = document.createElement('p')
|
||||
replyHint.className = 'hint'
|
||||
replyHint.textContent =
|
||||
'可用变量:{sender}(发送者)、{keyword}(命中词)、{time}(当前时间 HH:mm)'
|
||||
replyBlock.append(replyHint)
|
||||
|
||||
const cooldownInput = document.createElement('input')
|
||||
cooldownInput.type = 'number'
|
||||
cooldownInput.min = '0'
|
||||
cooldownInput.max = '3600'
|
||||
cooldownInput.value = String(rule.cooldownSeconds)
|
||||
cooldownInput.addEventListener('change', () => {
|
||||
rule.cooldownSeconds = clampInteger(cooldownInput.value, 0, 3600, 0)
|
||||
cooldownInput.value = String(rule.cooldownSeconds)
|
||||
})
|
||||
|
||||
const priorityInput = document.createElement('input')
|
||||
priorityInput.type = 'number'
|
||||
priorityInput.min = '0'
|
||||
priorityInput.max = '100'
|
||||
priorityInput.step = '1'
|
||||
priorityInput.value = String(rule.priority)
|
||||
priorityInput.addEventListener('change', () => {
|
||||
rule.priority = clampInteger(priorityInput.value, 0, 100, 0)
|
||||
priorityInput.value = String(rule.priority)
|
||||
})
|
||||
|
||||
const numberRow = document.createElement('div')
|
||||
numberRow.className = 'field-row'
|
||||
const cooldownField = field('冷却时间(秒)', cooldownInput)
|
||||
const priorityField = field('优先级(0–100,越大越先匹配)', priorityInput)
|
||||
numberRow.append(cooldownField, priorityField)
|
||||
|
||||
card.append(
|
||||
head,
|
||||
field('关键词', keywordInput),
|
||||
field('匹配方式', modeSelect),
|
||||
replyBlock,
|
||||
numberRow
|
||||
)
|
||||
rulesContainer.append(card)
|
||||
})
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('enabled').checked = config.enabled === true
|
||||
selectedGroupIds = new Set(config.scope.groups)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
document.getElementById('include-direct').checked = config.scope.includeDirect !== false
|
||||
document.getElementById('require-mention').checked = config.scope.requireMentionMe === true
|
||||
renderRules()
|
||||
}
|
||||
|
||||
function readForm() {
|
||||
config.enabled = document.getElementById('enabled').checked
|
||||
config.scope.groups = [...selectedGroupIds].slice(0, 200)
|
||||
config.scope.includeDirect = document.getElementById('include-direct').checked
|
||||
config.scope.requireMentionMe = document.getElementById('require-mention').checked
|
||||
}
|
||||
|
||||
function localDateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
function formatClock(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${hour}:${minute}`
|
||||
}
|
||||
|
||||
/** 统计展示:只读 storage,不参与任何写入。 */
|
||||
function renderStats(raw) {
|
||||
statsList.textContent = ''
|
||||
const now = Date.now()
|
||||
const sameDay = raw && raw.dateKey === localDateKey(now)
|
||||
const todayCount = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
|
||||
const hits = raw && Array.isArray(raw.lastHits) ? raw.lastHits.filter((hit) => hit && hit.at) : []
|
||||
|
||||
if (!hits.length && todayCount === 0) {
|
||||
statsSummary.textContent = '暂无命中记录'
|
||||
return
|
||||
}
|
||||
statsSummary.textContent = `今日命中 ${todayCount} 次`
|
||||
|
||||
hits
|
||||
.slice(-STATS_PREVIEW)
|
||||
.reverse()
|
||||
.forEach((hit) => {
|
||||
const item = document.createElement('li')
|
||||
item.className = 'stats-item'
|
||||
const time = document.createElement('span')
|
||||
time.textContent = formatClock(Number(hit.at))
|
||||
const ruleId = document.createElement('code')
|
||||
ruleId.textContent = String(hit.ruleId || '未知规则')
|
||||
const result = document.createElement('span')
|
||||
result.className = hit.ok === true ? 'stats-ok' : 'stats-fail'
|
||||
result.textContent = hit.ok === true ? '成功' : '失败'
|
||||
item.append(time, ruleId, result)
|
||||
statsList.append(item)
|
||||
})
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: STATS_KEY })
|
||||
renderStats(stored)
|
||||
} catch (error) {
|
||||
renderStats(null)
|
||||
setStatus(`统计读取失败:${error.message}`, 'error')
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('add-rule').addEventListener('click', () => {
|
||||
config.rules.push({
|
||||
id: newRuleId(),
|
||||
keyword: '',
|
||||
mode: 'contains',
|
||||
reply: '',
|
||||
cooldownSeconds: 30,
|
||||
enabled: true,
|
||||
priority: 0
|
||||
})
|
||||
renderRules()
|
||||
})
|
||||
|
||||
document.getElementById('save').addEventListener('click', async () => {
|
||||
readForm()
|
||||
// 只有启用中的规则必须有内容:停用的草稿允许留空,方便先存后写。
|
||||
const invalid = config.rules.find(
|
||||
(rule) => rule.enabled && (!rule.keyword.trim() || !rule.reply.trim())
|
||||
)
|
||||
if (invalid) {
|
||||
setStatus('启用中的规则都需要关键词和回复内容;也可以先取消启用再保存。', 'error')
|
||||
return
|
||||
}
|
||||
const payload = {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: config.enabled === true,
|
||||
rules: config.rules.map(normalizeRule),
|
||||
scope: {
|
||||
groups: config.scope.groups.slice(0, 200),
|
||||
includeDirect: config.scope.includeDirect !== false,
|
||||
requireMentionMe: config.scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: payload })
|
||||
// 回写规范化结果但保留原对象引用:卡片上的输入事件仍在改这些对象。
|
||||
payload.rules.forEach((rule, index) => Object.assign(config.rules[index], rule))
|
||||
config.configVersion = CONFIG_VERSION
|
||||
setStatus('配置已保存。后台进程会在下一次收到消息时生效。', 'ok')
|
||||
loadStats()
|
||||
} catch (error) {
|
||||
setStatus(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('reset').addEventListener('click', async () => {
|
||||
config = clone(DEFAULT_CONFIG)
|
||||
syncForm()
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setStatus('已恢复默认配置。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`重置失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('refresh-stats').addEventListener('click', () => {
|
||||
loadStats()
|
||||
})
|
||||
|
||||
async function boot() {
|
||||
const stored = await callHost('storage.get', { key: CONFIG_KEY })
|
||||
config = normalizeStoredConfig(stored)
|
||||
syncForm()
|
||||
await loadGroups()
|
||||
setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
|
||||
loadStats()
|
||||
}
|
||||
|
||||
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
|
||||
@@ -0,0 +1,71 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>关键词回复机器人</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>关键词回复机器人</h1>
|
||||
<p>收到文本消息后按规则匹配,命中即经 TraceMemo Gateway 回复。本页只写配置,不直接发送。</p>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input id="enabled" type="checkbox" />
|
||||
<span>启用机器人</span>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>关键词规则</h2>
|
||||
<button id="add-rule" type="button" class="ghost">添加规则</button>
|
||||
</div>
|
||||
<div id="rules" class="rules"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>监听范围</h2>
|
||||
<div class="field">
|
||||
<span>只监听这些群聊(可多选、可搜索;留空表示全部群聊)</span>
|
||||
<div id="group-picker" class="group-picker">
|
||||
<div id="group-chips" class="group-chips" hidden></div>
|
||||
<input
|
||||
id="group-search"
|
||||
type="text"
|
||||
placeholder="搜索群聊名称或 id…"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<div id="group-options" class="group-options" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="check"><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label>
|
||||
<label class="check"><input id="require-mention" type="checkbox" /><span>只处理真正 @ 我的消息</span></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>运行统计</h2>
|
||||
<button id="refresh-stats" type="button" class="ghost">刷新</button>
|
||||
</div>
|
||||
<p id="stats-summary" class="stats-summary">暂无命中记录</p>
|
||||
<ul id="stats-list" class="stats-list"></ul>
|
||||
<p class="hint">统计只记录规则编号、命中时间与发送结果,不含会话、昵称与消息正文。</p>
|
||||
</section>
|
||||
|
||||
<footer class="page-footer">
|
||||
<div class="row">
|
||||
<button id="save" type="button" class="primary">保存配置</button>
|
||||
<button id="reset" type="button" class="ghost">恢复默认</button>
|
||||
</div>
|
||||
<p id="status" class="status" role="status"></p>
|
||||
</footer>
|
||||
</main>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,384 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f8f7;
|
||||
--card: #ffffff;
|
||||
--text: #1c2622;
|
||||
--muted: #6b7a73;
|
||||
--border: #dfe6e2;
|
||||
--brand: #247a63;
|
||||
--danger: #b4472f;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #161c19;
|
||||
--card: #1e2622;
|
||||
--text: #eef4f1;
|
||||
--muted: #9aaba3;
|
||||
--border: #33403a;
|
||||
--brand: #4bb894;
|
||||
--danger: #e0735a;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
padding: 26px 22px 40px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
header p {
|
||||
margin: 8px 0 0;
|
||||
max-width: 52ch;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rules {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rule-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.rule-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rule-head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.rule-card.is-disabled {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.rule-card.is-disabled .field,
|
||||
.rule-card.is-disabled .field-row {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.stats-summary {
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.stats-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats-ok {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.stats-fail {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.field-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.field > span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
input[type='number'],
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.check,
|
||||
.switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.switch {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 6px 11px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: transparent;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
button.ghost:hover {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
button.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 18px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status[data-kind='ok'] {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.status[data-kind='error'] {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
|
||||
.group-picker {
|
||||
position: relative;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.group-picker:focus-within {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.group-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 2px 4px 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.group-chip > span {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-chip-remove {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.group-chip-remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.group-picker > input[type='text'] {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
padding: 4px 2px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-options {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 4px);
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.group-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 6px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-option:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.group-option input {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group-option-empty {
|
||||
padding: 8px 6px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# AI 晨报 (`com.example.morning-digest`)
|
||||
|
||||
TraceMemo 官方示例模板,完整演示扩展系统第二阶段全链路能力:
|
||||
|
||||
1. **分页消息查询**:使用 `tm.messages.query({ order: 'asc', cursor, limit })` 稳定翻页读取多群历史记录。
|
||||
2. **按需媒体解析**:使用 `tm.media.batch` 按需触发图片本地 OCR、可选 AI 视觉理解与语音转写,自动复用主程序缓存。
|
||||
3. **AI 总结**:经 `tm.ai.chat` 提炼今日重点、待办事项与各群速览。
|
||||
4. **通用 HTML 长图渲染**:经 `tm.render.htmlToImage` 在隔离离线窗口中输出 PNG 长图至扩展私有目录。
|
||||
5. **扩展通知中心 & 一级导航固定**:声明 `contributions.navigation` 支持固定到左侧一级导航;生成完成后通过 `tm.notifications.create` 写入去重通知。
|
||||
6. **可选微信发送**:默认关闭自动发送,用户确认生成效果后可手动选择测试群聊发送长图,全链路仍经 TraceMemo Gateway 与授权校验。
|
||||
@@ -0,0 +1,240 @@
|
||||
'use strict'
|
||||
|
||||
/** AI 晨报后台:串联分页消息读取、批量媒体解析、AI 总结、离线长图渲染、通知中心与可选微信发送。 */
|
||||
|
||||
const {
|
||||
DIGEST_CSS,
|
||||
normalizeConfig,
|
||||
selectMediaBatchItems,
|
||||
buildDigestPromptMessages,
|
||||
parseDigestSummary,
|
||||
buildDigestHtml
|
||||
} = require('../lib/digest-builder')
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const LAST_DIGEST_KEY = 'lastDigest'
|
||||
|
||||
function localDateKey(timestamp = Date.now()) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
async function queryAllGroupMessages(tm, conversationId, startTime, endTime, maxMessages) {
|
||||
const collected = []
|
||||
let cursor = undefined
|
||||
const pageSize = Math.min(100, maxMessages)
|
||||
|
||||
for (let pageIndex = 0; pageIndex < 20 && collected.length < maxMessages; pageIndex += 1) {
|
||||
const page = await tm.messages.query({
|
||||
conversationId,
|
||||
startTime,
|
||||
endTime,
|
||||
order: 'asc',
|
||||
limit: Math.min(pageSize, maxMessages - collected.length),
|
||||
...(cursor ? { cursor } : {})
|
||||
})
|
||||
const batch = Array.isArray(page && page.messages) ? page.messages : []
|
||||
collected.push(...batch)
|
||||
if (!page || !page.hasMore || !page.nextCursor) break
|
||||
cursor = page.nextCursor
|
||||
}
|
||||
return collected
|
||||
}
|
||||
|
||||
async function generateMorningDigest(tm, overrideConfig = null) {
|
||||
const stored = await tm.storage.get(CONFIG_KEY).catch(() => null)
|
||||
const config = normalizeConfig(overrideConfig ? { ...(stored || {}), ...overrideConfig } : stored)
|
||||
if (config.groupIds.length === 0) {
|
||||
throw new Error('请先在 AI 晨报配置页至少选择一个群聊')
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const startTime = now - config.windowHours * 60 * 60 * 1000
|
||||
const dateLabel = localDateKey(now)
|
||||
const grantedPermissions = (tm.extension && tm.extension.permissions) || []
|
||||
|
||||
const groupReports = []
|
||||
let totalMessages = 0
|
||||
let totalMediaResolved = 0
|
||||
|
||||
for (const groupId of config.groupIds) {
|
||||
const messages = await queryAllGroupMessages(
|
||||
tm,
|
||||
groupId,
|
||||
startTime,
|
||||
now,
|
||||
config.maxMessagesPerGroup
|
||||
)
|
||||
totalMessages += messages.length
|
||||
|
||||
const mediaByRef = new Map()
|
||||
const batchItems = selectMediaBatchItems(messages, config, grantedPermissions)
|
||||
if (batchItems.length > 0 && tm.media && typeof tm.media.batch === 'function') {
|
||||
try {
|
||||
const batchResult = await tm.media.batch({ items: batchItems, concurrency: 2 })
|
||||
for (const entry of (batchResult && batchResult.results) || []) {
|
||||
if (!entry || !entry.ok || !entry.result) continue
|
||||
if (entry.op === 'ocrImage' && entry.result.text) {
|
||||
mediaByRef.set(entry.messageRef, `[图片文字] ${entry.result.text}`)
|
||||
totalMediaResolved += 1
|
||||
} else if (entry.op === 'analyzeImage' && entry.result.description) {
|
||||
mediaByRef.set(entry.messageRef, `[图片理解] ${entry.result.description}`)
|
||||
totalMediaResolved += 1
|
||||
} else if (
|
||||
entry.op === 'transcribeVoice' &&
|
||||
entry.result.state === 'transcribed' &&
|
||||
entry.result.transcript
|
||||
) {
|
||||
mediaByRef.set(entry.messageRef, `[语音转文字] ${entry.result.transcript}`)
|
||||
totalMediaResolved += 1
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
tm.log.warn(`AI 晨报:媒体按需解析降级跳过(${error instanceof Error ? error.message : '未知错误'})`)
|
||||
}
|
||||
}
|
||||
|
||||
const lines = []
|
||||
for (const msg of messages) {
|
||||
const sender = msg.senderName || (msg.isSelf ? '我' : '群友')
|
||||
if (msg.text && msg.text.trim()) {
|
||||
lines.push(`${sender}:${msg.text.trim().slice(0, 180)}`)
|
||||
} else if (msg.messageRef && mediaByRef.has(msg.messageRef)) {
|
||||
lines.push(`${sender}:${String(mediaByRef.get(msg.messageRef)).slice(0, 180)}`)
|
||||
}
|
||||
}
|
||||
|
||||
groupReports.push({
|
||||
groupId,
|
||||
name: config.groupNames[groupId] || groupId,
|
||||
messageCount: messages.length,
|
||||
mediaResolvedCount: mediaByRef.size,
|
||||
lines
|
||||
})
|
||||
}
|
||||
|
||||
let summaryText = ''
|
||||
if (grantedPermissions.includes('ai.chat')) {
|
||||
const promptMessages = buildDigestPromptMessages({ dateLabel, groups: groupReports })
|
||||
const aiResp = await tm.ai.chat(promptMessages)
|
||||
summaryText = String((aiResp && aiResp.text) || '')
|
||||
}
|
||||
const summary = parseDigestSummary(summaryText, groupReports)
|
||||
|
||||
const html = buildDigestHtml({
|
||||
dateLabel,
|
||||
headline: summary.headline,
|
||||
highlights: summary.highlights,
|
||||
actionItems: summary.actionItems,
|
||||
groupBriefs: summary.groupBriefs,
|
||||
totalMessages,
|
||||
totalMediaResolved,
|
||||
groupCount: groupReports.length
|
||||
})
|
||||
|
||||
const rendered = await tm.render.htmlToImage({
|
||||
html,
|
||||
css: DIGEST_CSS,
|
||||
fileName: `morning-digest-${dateLabel}.png`,
|
||||
width: config.renderWidth
|
||||
})
|
||||
|
||||
const record = {
|
||||
dateLabel,
|
||||
generatedAt: now,
|
||||
headline: summary.headline,
|
||||
highlights: summary.highlights,
|
||||
actionItems: summary.actionItems,
|
||||
groupBriefs: summary.groupBriefs,
|
||||
totalMessages,
|
||||
totalMediaResolved,
|
||||
groupCount: groupReports.length,
|
||||
imagePath: rendered.path,
|
||||
previewUrl: rendered.previewUrl || '',
|
||||
width: rendered.width,
|
||||
height: rendered.height,
|
||||
pixelWidth: rendered.pixelWidth || rendered.width,
|
||||
pixelHeight: rendered.pixelHeight || rendered.height,
|
||||
deviceScaleFactor: rendered.deviceScaleFactor || 1,
|
||||
bytes: rendered.bytes
|
||||
}
|
||||
await tm.storage.set(LAST_DIGEST_KEY, record)
|
||||
|
||||
if (grantedPermissions.includes('notifications.create')) {
|
||||
try {
|
||||
await tm.notifications.create({
|
||||
title: `AI 晨报已生成 · ${dateLabel}`,
|
||||
body: `${summary.headline}(${groupReports.length} 个群 / ${totalMessages} 条消息)`,
|
||||
level: 'success',
|
||||
dedupeKey: `morning-digest:${dateLabel}`,
|
||||
pageId: 'digest'
|
||||
})
|
||||
} catch (error) {
|
||||
tm.log.warn(`AI 晨报:通知写入失败(${error instanceof Error ? error.message : '未知错误'})`)
|
||||
}
|
||||
}
|
||||
|
||||
let sentToWechat = false
|
||||
if (
|
||||
config.autoSendWechat &&
|
||||
config.wechatTargetGroupId &&
|
||||
grantedPermissions.includes('wechat.send.image')
|
||||
) {
|
||||
await tm.wechat.send({
|
||||
type: 'image',
|
||||
to: config.wechatTargetGroupId,
|
||||
path: rendered.path,
|
||||
dedupeKey: `morning-digest-send:${dateLabel}:${config.wechatTargetGroupId}`
|
||||
})
|
||||
sentToWechat = true
|
||||
}
|
||||
|
||||
tm.log.info(
|
||||
`AI 晨报已生成:${groupReports.length} 个群,${totalMessages} 条消息,解析媒体 ${totalMediaResolved} 条`
|
||||
)
|
||||
return { ...record, sentToWechat }
|
||||
}
|
||||
|
||||
module.exports = function activate(tm) {
|
||||
if (tm.page && typeof tm.page.onRequest === 'function') {
|
||||
tm.page.onRequest('generateDigest', async (params) => {
|
||||
return generateMorningDigest(tm, params && typeof params === 'object' ? params : null)
|
||||
})
|
||||
|
||||
tm.page.onRequest('sendLastDigest', async (params) => {
|
||||
const target = String((params && params.to) || '').trim()
|
||||
if (!target) throw new Error('请先选择发送目标群聊')
|
||||
const last = await tm.storage.get(LAST_DIGEST_KEY)
|
||||
if (!last || !last.imagePath) throw new Error('请先生成今日晨报长图')
|
||||
const sent = await tm.wechat.send({
|
||||
type: 'image',
|
||||
to: target,
|
||||
path: last.imagePath,
|
||||
dedupeKey: `morning-digest-manual:${last.dateLabel}:${target}:${Date.now()}`
|
||||
})
|
||||
return { ok: true, actionId: sent.actionId, to: target }
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
tm.automation &&
|
||||
typeof tm.automation.registerAction === 'function' &&
|
||||
tm.extension &&
|
||||
Array.isArray(tm.extension.permissions) &&
|
||||
tm.extension.permissions.includes('automation.action')
|
||||
) {
|
||||
tm.automation.registerAction({
|
||||
id: 'morning-digest.generate',
|
||||
title: '生成 AI 晨报',
|
||||
description: '汇总已配置群聊消息并渲染晨报长图',
|
||||
handler: async () => {
|
||||
const result = await generateMorningDigest(tm)
|
||||
return { success: true, output: { headline: result.headline, imagePath: result.imagePath } }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
tm.log.info('AI 晨报已启动')
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
'use strict'
|
||||
|
||||
/** AI 晨报纯逻辑模块:配置收敛、媒体批次编排、AI 摘要提示词与严格静态 HTML 渲染构建。 */
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
groupIds: [],
|
||||
groupNames: {},
|
||||
windowHours: 24,
|
||||
maxMessagesPerGroup: 300,
|
||||
enableImageOcr: true,
|
||||
enableImageVision: false,
|
||||
enableVoiceTranscribe: true,
|
||||
maxMediaPerGroup: 6,
|
||||
renderWidth: 460,
|
||||
/** 默认禁止自动发微信,需用户显式开启或手动点击发送。 */
|
||||
autoSendWechat: false,
|
||||
wechatTargetGroupId: ''
|
||||
}
|
||||
|
||||
function clampInt(value, fallback, min, max) {
|
||||
const num = Number(value)
|
||||
if (!Number.isFinite(num)) return fallback
|
||||
return Math.max(min, Math.min(max, Math.round(num)))
|
||||
}
|
||||
|
||||
function normalizeConfig(raw) {
|
||||
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const groupIds = Array.isArray(src.groupIds)
|
||||
? Array.from(
|
||||
new Set(
|
||||
src.groupIds
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 10)
|
||||
)
|
||||
)
|
||||
: []
|
||||
const groupNames = {}
|
||||
if (src.groupNames && typeof src.groupNames === 'object' && !Array.isArray(src.groupNames)) {
|
||||
for (const [id, name] of Object.entries(src.groupNames)) {
|
||||
const cleanId = String(id || '').trim()
|
||||
const cleanName = String(name || '').trim().slice(0, 64)
|
||||
if (cleanId && cleanName) groupNames[cleanId] = cleanName
|
||||
}
|
||||
}
|
||||
return {
|
||||
groupIds,
|
||||
groupNames,
|
||||
windowHours: clampInt(src.windowHours, DEFAULT_CONFIG.windowHours, 1, 168),
|
||||
maxMessagesPerGroup: clampInt(
|
||||
src.maxMessagesPerGroup,
|
||||
DEFAULT_CONFIG.maxMessagesPerGroup,
|
||||
20,
|
||||
1000
|
||||
),
|
||||
enableImageOcr: src.enableImageOcr !== false,
|
||||
enableImageVision: src.enableImageVision === true,
|
||||
enableVoiceTranscribe: src.enableVoiceTranscribe !== false,
|
||||
maxMediaPerGroup: clampInt(src.maxMediaPerGroup, DEFAULT_CONFIG.maxMediaPerGroup, 0, 15),
|
||||
renderWidth: clampInt(src.renderWidth, DEFAULT_CONFIG.renderWidth, 320, 960),
|
||||
autoSendWechat: src.autoSendWechat === true,
|
||||
wechatTargetGroupId: String(src.wechatTargetGroupId || '').trim().slice(0, 128)
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
/** 挑选待按需解析的图片与语音消息引用,单群总量受限以避免慢任务拖垮晨报生成。 */
|
||||
function selectMediaBatchItems(messages, config, grantedPermissions = []) {
|
||||
const limit = clampInt(config.maxMediaPerGroup, 6, 0, 15)
|
||||
if (limit === 0 || !Array.isArray(messages) || messages.length === 0) return []
|
||||
const perms = new Set(Array.isArray(grantedPermissions) ? grantedPermissions : [])
|
||||
const items = []
|
||||
const recent = [...messages].reverse()
|
||||
|
||||
for (const msg of recent) {
|
||||
if (items.length >= limit) break
|
||||
const messageRef = String((msg && msg.messageRef) || '').trim()
|
||||
if (!messageRef) continue
|
||||
if (msg.type === 'image') {
|
||||
if (config.enableImageVision && perms.has('ai.vision')) {
|
||||
items.push({ op: 'analyzeImage', messageRef })
|
||||
} else if (config.enableImageOcr && perms.has('media.ocr')) {
|
||||
items.push({ op: 'ocrImage', messageRef })
|
||||
}
|
||||
} else if (msg.type === 'voice') {
|
||||
if (config.enableVoiceTranscribe && perms.has('media.transcribe')) {
|
||||
items.push({ op: 'transcribeVoice', messageRef, options: { waitMs: 10_000 } })
|
||||
}
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
function buildDigestPromptMessages(input) {
|
||||
const dateLabel = String(input.dateLabel || '').trim() || new Date().toISOString().slice(0, 10)
|
||||
const sections = (input.groups || []).map((group) => {
|
||||
const lines = (group.lines || []).slice(0, 120).join('\n')
|
||||
return `【群聊:${group.name}】(共 ${group.messageCount} 条消息,解析媒体 ${group.mediaResolvedCount} 条)\n${lines || '(暂无有效内容)'}`
|
||||
})
|
||||
|
||||
return [
|
||||
{
|
||||
role: 'system',
|
||||
content: [
|
||||
'你是一名简洁高效的中文晨报编辑,负责根据多个微信群最近一天的聊天记录与图片/语音解析结果整理一份结构化「AI 晨报」。',
|
||||
'请严格输出纯 JSON,不要包含 Markdown 代码块包裹:',
|
||||
'{"headline":"一句话总览(<=28字)","highlights":["重点1","重点2"],"actionItems":["待办或约定1"],"groupBriefs":[{"groupName":"群名","summary":"该群简述(<=80字)"}]}'
|
||||
].join('\n')
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `日期:${dateLabel}\n\n${sections.join('\n\n')}`
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function parseDigestSummary(rawText, fallbackGroups = []) {
|
||||
const cleaned = String(rawText || '')
|
||||
.trim()
|
||||
.replace(/^```(?:json)?\s*/i, '')
|
||||
.replace(/\s*```$/i, '')
|
||||
.trim()
|
||||
try {
|
||||
const parsed = JSON.parse(cleaned)
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
const headline = String(parsed.headline || '今日群聊晨报').trim().slice(0, 60)
|
||||
const highlights = Array.isArray(parsed.highlights)
|
||||
? parsed.highlights.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
|
||||
: []
|
||||
const actionItems = Array.isArray(parsed.actionItems)
|
||||
? parsed.actionItems.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
|
||||
: []
|
||||
const groupBriefs = Array.isArray(parsed.groupBriefs)
|
||||
? parsed.groupBriefs
|
||||
.filter((item) => item && typeof item === 'object')
|
||||
.map((item) => ({
|
||||
groupName: String(item.groupName || '群聊').trim().slice(0, 48),
|
||||
summary: String(item.summary || '').trim().slice(0, 200)
|
||||
}))
|
||||
.filter((item) => item.summary)
|
||||
.slice(0, 10)
|
||||
: []
|
||||
if (headline || highlights.length > 0 || groupBriefs.length > 0) {
|
||||
return { headline, highlights, actionItems, groupBriefs }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON 文本回退为单条摘要展示,不中断渲染。
|
||||
}
|
||||
return {
|
||||
headline: '今日群聊晨报',
|
||||
highlights: cleaned ? [cleaned.slice(0, 240)] : ['最近周期内暂无重点讨论'],
|
||||
actionItems: [],
|
||||
groupBriefs: fallbackGroups.map((g) => ({
|
||||
groupName: g.name,
|
||||
summary: `共采集 ${g.messageCount} 条消息,解析媒体 ${g.mediaResolvedCount} 条。`
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
const DIGEST_CSS = `
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background: #f4f6f9;
|
||||
color: #18212f;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
.digest-card {
|
||||
background: #ffffff;
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
border: 1px solid #e5e9f0;
|
||||
}
|
||||
.digest-kicker {
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.08em;
|
||||
color: #2563eb;
|
||||
font-weight: 700;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.digest-title {
|
||||
margin: 0 0 8px;
|
||||
font-size: 22px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.digest-meta {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.digest-section {
|
||||
margin-top: 18px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid #edf0f5;
|
||||
}
|
||||
.digest-section h2 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 15px;
|
||||
color: #0f172a;
|
||||
}
|
||||
.digest-list {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
line-height: 1.65;
|
||||
font-size: 14px;
|
||||
}
|
||||
.digest-group {
|
||||
background: #f8fafc;
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.digest-group-name {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.digest-group-summary {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #334155;
|
||||
}
|
||||
.digest-footer {
|
||||
margin-top: 18px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px dashed #e2e8f0;
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
}
|
||||
`
|
||||
|
||||
/** 构建纯静态、无脚本、无外链的晨报 HTML,满足 HtmlRenderService 的严格安全校验。 */
|
||||
function buildDigestHtml(data) {
|
||||
const dateLabel = escapeHtml(data.dateLabel || '')
|
||||
const headline = escapeHtml(data.headline || '今日群聊晨报')
|
||||
const totalMessages = Number(data.totalMessages) || 0
|
||||
const totalMedia = Number(data.totalMediaResolved) || 0
|
||||
const groupCount = Number(data.groupCount) || 0
|
||||
|
||||
const highlightsHtml = (data.highlights || [])
|
||||
.map((item) => `<li>${escapeHtml(item)}</li>`)
|
||||
.join('')
|
||||
const actionsHtml = (data.actionItems || [])
|
||||
.map((item) => `<li>${escapeHtml(item)}</li>`)
|
||||
.join('')
|
||||
const briefsHtml = (data.groupBriefs || [])
|
||||
.map(
|
||||
(item) =>
|
||||
`<div class="digest-group"><div class="digest-group-name">${escapeHtml(item.groupName)}</div><p class="digest-group-summary">${escapeHtml(item.summary)}</p></div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
return `<main class="digest-card">
|
||||
<div class="digest-kicker">TRACEMEMO AI 晨报 · ${dateLabel}</div>
|
||||
<h1 class="digest-title">${headline}</h1>
|
||||
<div class="digest-meta">覆盖 ${groupCount} 个群聊 · 采样 ${totalMessages} 条消息 · 解析 ${totalMedia} 条图片/语音</div>
|
||||
${highlightsHtml ? `<section class="digest-section"><h2>今日重点</h2><ul class="digest-list">${highlightsHtml}</ul></section>` : ''}
|
||||
${actionsHtml ? `<section class="digest-section"><h2>待办与约定</h2><ul class="digest-list">${actionsHtml}</ul></section>` : ''}
|
||||
${briefsHtml ? `<section class="digest-section"><h2>各群速览</h2>${briefsHtml}</section>` : ''}
|
||||
<footer class="digest-footer">由 TraceMemo 扩展「AI 晨报」离线生成</footer>
|
||||
</main>`
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_CONFIG,
|
||||
DIGEST_CSS,
|
||||
normalizeConfig,
|
||||
escapeHtml,
|
||||
selectMediaBatchItems,
|
||||
buildDigestPromptMessages,
|
||||
parseDigestSummary,
|
||||
buildDigestHtml
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.morning-digest",
|
||||
"name": "AI 晨报",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.7.0",
|
||||
"description": "分页拉取指定群聊最近消息,按需解析图片与语音并经 AI 总结,离线渲染为晨报 PNG 长图、发送应用内通知,并支持人工确认后可选发送到微信。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.query",
|
||||
"media.ocr",
|
||||
"media.transcribe",
|
||||
"ai.chat",
|
||||
"ai.vision",
|
||||
"render.html",
|
||||
"notifications.create",
|
||||
"contacts.list",
|
||||
"wechat.send.image",
|
||||
"automation.action",
|
||||
"storage"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "digest",
|
||||
"title": "AI 晨报"
|
||||
}
|
||||
],
|
||||
"navigation": {
|
||||
"label": "AI 晨报",
|
||||
"icon": "digest",
|
||||
"pageId": "digest",
|
||||
"order": 10
|
||||
},
|
||||
"automationActions": [
|
||||
{
|
||||
"id": "morning-digest.generate",
|
||||
"title": "生成 AI 晨报",
|
||||
"description": "汇总已配置群聊的文字、图片与语音消息并渲染晨报长图"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const {
|
||||
normalizeConfig,
|
||||
selectMediaBatchItems,
|
||||
parseDigestSummary,
|
||||
buildDigestHtml
|
||||
} = require('../lib/digest-builder.js')
|
||||
|
||||
test('normalizeConfig 默认关闭自动发微信并收敛数值边界', () => {
|
||||
const cfg = normalizeConfig({ windowHours: 999, renderWidth: 100, groupIds: ['g1@chatroom', 'g1@chatroom'] })
|
||||
assert.equal(cfg.autoSendWechat, false)
|
||||
assert.equal(cfg.windowHours, 168)
|
||||
assert.equal(cfg.renderWidth, 320)
|
||||
assert.deepEqual(cfg.groupIds, ['g1@chatroom'])
|
||||
})
|
||||
|
||||
test('selectMediaBatchItems 按权限筛选图片 OCR/视觉与语音转写批次', () => {
|
||||
const messages = [
|
||||
{ type: 'text', messageRef: 'ref-1', text: '早安' },
|
||||
{ type: 'image', messageRef: 'ref-img' },
|
||||
{ type: 'voice', messageRef: 'ref-voice' }
|
||||
]
|
||||
const items = selectMediaBatchItems(
|
||||
messages,
|
||||
normalizeConfig({ enableImageOcr: true, enableVoiceTranscribe: true, maxMediaPerGroup: 5 }),
|
||||
['media.ocr', 'media.transcribe']
|
||||
)
|
||||
assert.equal(items.length, 2)
|
||||
assert.equal(items[0].op, 'transcribeVoice')
|
||||
assert.equal(items[1].op, 'ocrImage')
|
||||
})
|
||||
|
||||
test('buildDigestHtml 转义 HTML 特殊字符且不包含脚本或外链', () => {
|
||||
const summary = parseDigestSummary(
|
||||
JSON.stringify({
|
||||
headline: '今日<script>alert(1)</script>焦点',
|
||||
highlights: ['项目评审通过'],
|
||||
actionItems: ['张三跟进上线'],
|
||||
groupBriefs: [{ groupName: '产品测试群', summary: '讨论了发布排期' }]
|
||||
})
|
||||
)
|
||||
const html = buildDigestHtml({
|
||||
dateLabel: '2026-12-01',
|
||||
...summary,
|
||||
totalMessages: 42,
|
||||
totalMediaResolved: 3,
|
||||
groupCount: 1
|
||||
})
|
||||
assert.equal(/<script/i.test(html), false)
|
||||
assert.equal(html.includes('<script>'), true)
|
||||
assert.equal(html.includes('产品测试群'), true)
|
||||
})
|
||||
@@ -0,0 +1,251 @@
|
||||
'use strict'
|
||||
|
||||
const EXTENSION_ID = 'com.example.morning-digest'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const LAST_DIGEST_KEY = 'lastDigest'
|
||||
|
||||
const pending = new Map()
|
||||
let seq = 0
|
||||
let groups = []
|
||||
let lastDigest = null
|
||||
let config = {
|
||||
groupIds: [],
|
||||
groupNames: {},
|
||||
windowHours: 24,
|
||||
enableImageOcr: true,
|
||||
enableImageVision: false,
|
||||
enableVoiceTranscribe: true,
|
||||
maxMediaPerGroup: 6,
|
||||
renderWidth: 460,
|
||||
autoSendWechat: false,
|
||||
wechatTargetGroupId: ''
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = `req-${++seq}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params: params || {} },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const item = pending.get(data.requestId)
|
||||
if (!item) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) item.resolve(data.result)
|
||||
else item.reject(new Error((data.error && data.error.message) || '请求失败'))
|
||||
})
|
||||
|
||||
function setBanner(text, tone) {
|
||||
const el = document.getElementById('banner')
|
||||
el.textContent = text
|
||||
el.dataset.tone = tone || ''
|
||||
}
|
||||
|
||||
function renderGroupList() {
|
||||
const keyword = document.getElementById('group-search').value.trim().toLowerCase()
|
||||
const container = document.getElementById('group-list')
|
||||
container.textContent = ''
|
||||
const filtered = groups.filter((g) => !keyword || g.name.toLowerCase().includes(keyword))
|
||||
if (filtered.length === 0) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-item'
|
||||
empty.textContent = groups.length === 0 ? '暂无可选群聊(请先连接微信数据库)' : '没有匹配的群聊'
|
||||
container.appendChild(empty)
|
||||
return
|
||||
}
|
||||
const selectedSet = new Set(config.groupIds)
|
||||
for (const group of filtered) {
|
||||
const label = document.createElement('label')
|
||||
label.className = 'group-item'
|
||||
const input = document.createElement('input')
|
||||
input.type = 'checkbox'
|
||||
input.checked = selectedSet.has(group.id)
|
||||
input.addEventListener('change', () => {
|
||||
if (input.checked) {
|
||||
if (!config.groupIds.includes(group.id) && config.groupIds.length < 10) {
|
||||
config.groupIds.push(group.id)
|
||||
config.groupNames[group.id] = group.name
|
||||
} else {
|
||||
input.checked = false
|
||||
}
|
||||
} else {
|
||||
config.groupIds = config.groupIds.filter((id) => id !== group.id)
|
||||
}
|
||||
})
|
||||
const span = document.createElement('span')
|
||||
span.textContent = group.name
|
||||
label.appendChild(input)
|
||||
label.appendChild(span)
|
||||
container.appendChild(label)
|
||||
}
|
||||
}
|
||||
|
||||
function renderTargetSelect() {
|
||||
const select = document.getElementById('wechat-target')
|
||||
select.textContent = ''
|
||||
const none = document.createElement('option')
|
||||
none.value = ''
|
||||
none.textContent = '不自动发送'
|
||||
select.appendChild(none)
|
||||
for (const group of groups) {
|
||||
const opt = document.createElement('option')
|
||||
opt.value = group.id
|
||||
opt.textContent = group.name
|
||||
select.appendChild(opt)
|
||||
}
|
||||
select.value = config.wechatTargetGroupId || ''
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('window-hours').value = String(config.windowHours || 24)
|
||||
document.getElementById('enable-ocr').checked = config.enableImageOcr !== false
|
||||
document.getElementById('enable-vision').checked = config.enableImageVision === true
|
||||
document.getElementById('enable-voice').checked = config.enableVoiceTranscribe !== false
|
||||
document.getElementById('max-media').value = String(config.maxMediaPerGroup ?? 6)
|
||||
document.getElementById('render-width').value = String(config.renderWidth ?? 460)
|
||||
document.getElementById('auto-send').checked = config.autoSendWechat === true
|
||||
renderGroupList()
|
||||
renderTargetSelect()
|
||||
}
|
||||
|
||||
function collectForm() {
|
||||
config.windowHours = Number(document.getElementById('window-hours').value) || 24
|
||||
config.enableImageOcr = document.getElementById('enable-ocr').checked
|
||||
config.enableImageVision = document.getElementById('enable-vision').checked
|
||||
config.enableVoiceTranscribe = document.getElementById('enable-voice').checked
|
||||
config.maxMediaPerGroup = Number(document.getElementById('max-media').value) || 0
|
||||
config.renderWidth = Number(document.getElementById('render-width').value) || 460
|
||||
config.wechatTargetGroupId = document.getElementById('wechat-target').value
|
||||
config.autoSendWechat = document.getElementById('auto-send').checked
|
||||
}
|
||||
|
||||
function renderDigestResult(record) {
|
||||
const el = document.getElementById('digest-result')
|
||||
const sendBtn = document.getElementById('send-last-btn')
|
||||
const previewWrap = document.getElementById('digest-preview-wrap')
|
||||
const previewImg = document.getElementById('digest-preview-img')
|
||||
const previewCaption = document.getElementById('digest-preview-caption')
|
||||
if (!record || !record.headline) {
|
||||
el.className = 'result-body empty'
|
||||
el.textContent = '尚未生成晨报,勾选群聊后点击右上角「立即生成今日晨报」。'
|
||||
previewWrap.hidden = true
|
||||
previewImg.removeAttribute('src')
|
||||
sendBtn.disabled = true
|
||||
return
|
||||
}
|
||||
el.className = 'result-body'
|
||||
const pixelMeta =
|
||||
record.pixelWidth && record.pixelHeight
|
||||
? `(实际像素 ${record.pixelWidth}×${record.pixelHeight}px,${record.deviceScaleFactor || 1}x)`
|
||||
: ''
|
||||
const lines = [
|
||||
`【标题】${record.headline}(${record.dateLabel})`,
|
||||
`【统计】覆盖 ${record.groupCount} 个群 · ${record.totalMessages} 条消息 · 解析 ${record.totalMediaResolved} 条媒体`,
|
||||
`【长图】逻辑 ${record.width}×${record.height}px${pixelMeta} · ${(Number(record.bytes || 0) / 1024).toFixed(1)}KB`,
|
||||
`【输出文件】${record.imagePath}`
|
||||
]
|
||||
if (Array.isArray(record.highlights) && record.highlights.length > 0) {
|
||||
lines.push('', '【今日重点】', ...record.highlights.map((item, idx) => `${idx + 1}. ${item}`))
|
||||
}
|
||||
if (Array.isArray(record.actionItems) && record.actionItems.length > 0) {
|
||||
lines.push('', '【待办与约定】', ...record.actionItems.map((item, idx) => `${idx + 1}. ${item}`))
|
||||
}
|
||||
el.textContent = lines.join('\n')
|
||||
if (record.previewUrl) {
|
||||
previewWrap.hidden = false
|
||||
previewCaption.textContent = `长图实时预览(受控扩展私有媒体协议):${record.previewUrl}`
|
||||
previewImg.src = `${record.previewUrl}?t=${record.generatedAt || Date.now()}`
|
||||
} else {
|
||||
previewWrap.hidden = true
|
||||
previewImg.removeAttribute('src')
|
||||
}
|
||||
sendBtn.disabled = false
|
||||
}
|
||||
|
||||
document.getElementById('group-search').addEventListener('input', renderGroupList)
|
||||
|
||||
document.getElementById('save-btn').addEventListener('click', async () => {
|
||||
collectForm()
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setBanner('配置已保存。', 'ok')
|
||||
} catch (error) {
|
||||
setBanner(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('generate-btn').addEventListener('click', async () => {
|
||||
collectForm()
|
||||
if (config.groupIds.length === 0) {
|
||||
setBanner('请先勾选至少一个群聊。', 'error')
|
||||
return
|
||||
}
|
||||
const btn = document.getElementById('generate-btn')
|
||||
btn.disabled = true
|
||||
setBanner('正在分页拉取消息、按需解析图片/语音并离线渲染长图…')
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
const result = await callHost('extension.request', {
|
||||
method: 'generateDigest',
|
||||
params: config
|
||||
})
|
||||
lastDigest = result
|
||||
renderDigestResult(result)
|
||||
setBanner(
|
||||
result.sentToWechat
|
||||
? '今日晨报已生成、写入通知中心并已发送至目标群聊。'
|
||||
: '今日晨报已生成并写入扩展通知中心。',
|
||||
'ok'
|
||||
)
|
||||
} catch (error) {
|
||||
setBanner(`生成失败:${error.message}`, 'error')
|
||||
} finally {
|
||||
btn.disabled = false
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('send-last-btn').addEventListener('click', async () => {
|
||||
collectForm()
|
||||
if (!config.wechatTargetGroupId) {
|
||||
setBanner('请先在「发送目标群聊」下拉框中选择一个群聊。', 'error')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await callHost('extension.request', {
|
||||
method: 'sendLastDigest',
|
||||
params: { to: config.wechatTargetGroupId }
|
||||
})
|
||||
setBanner('已通过 TraceMemo Gateway 发送晨报长图。', 'ok')
|
||||
} catch (error) {
|
||||
setBanner(`发送失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
async function init() {
|
||||
const [savedConfig, savedDigest, roster] = await Promise.all([
|
||||
callHost('storage.get', { key: CONFIG_KEY }).catch(() => null),
|
||||
callHost('storage.get', { key: LAST_DIGEST_KEY }).catch(() => null),
|
||||
callHost('contacts.listGroups', {}).catch(() => ({ groups: [] }))
|
||||
])
|
||||
if (savedConfig && typeof savedConfig === 'object') {
|
||||
config = { ...config, ...savedConfig }
|
||||
}
|
||||
groups = Array.isArray(roster && roster.groups) ? roster.groups : []
|
||||
lastDigest = savedDigest
|
||||
syncForm()
|
||||
renderDigestResult(lastDigest)
|
||||
setBanner('AI 晨报已就绪。建议先点击「立即生成今日晨报」离线预览。')
|
||||
}
|
||||
|
||||
init().catch((error) => {
|
||||
setBanner(`初始化失败:${error.message}`, 'error')
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AI 晨报</title>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<header class="hero">
|
||||
<div>
|
||||
<div class="kicker">TraceMemo 官方模板 · com.example.morning-digest</div>
|
||||
<h1>AI 晨报</h1>
|
||||
<p class="subtitle">分页拉取群聊记录、按需解析图片与语音、AI 总结并离线生成 PNG 长图,支持通知提醒与可选微信发送。</p>
|
||||
</div>
|
||||
<div class="hero-actions">
|
||||
<button id="generate-btn" class="btn primary" type="button">立即生成今日晨报</button>
|
||||
<button id="save-btn" class="btn" type="button">保存配置</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="banner" class="banner" role="status">正在加载配置与群聊列表…</div>
|
||||
|
||||
<div class="grid">
|
||||
<section class="card">
|
||||
<h2>1. 选择采集群聊与时间窗</h2>
|
||||
<div class="field">
|
||||
<label for="window-hours">采集范围(小时)</label>
|
||||
<select id="window-hours">
|
||||
<option value="24">最近 24 小时</option>
|
||||
<option value="48">最近 48 小时</option>
|
||||
<option value="72">最近 72 小时</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="group-search">搜索并勾选目标群聊(最多 10 个)</label>
|
||||
<input id="group-search" type="search" placeholder="按群名筛选…">
|
||||
<div id="group-list" class="group-list"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>2. 按需媒体解析与长图渲染</h2>
|
||||
<label class="check-row">
|
||||
<input id="enable-ocr" type="checkbox" checked>
|
||||
<span>图片本地 OCR 文字识别(纯本地,优先复用索引缓存)</span>
|
||||
</label>
|
||||
<label class="check-row">
|
||||
<input id="enable-vision" type="checkbox">
|
||||
<span>图片 AI 视觉理解(需配置视觉模型)</span>
|
||||
</label>
|
||||
<label class="check-row">
|
||||
<input id="enable-voice" type="checkbox" checked>
|
||||
<span>语音本地转文字(复用本机语音转写服务)</span>
|
||||
</label>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="max-media">每群最多解析媒体数</label>
|
||||
<input id="max-media" type="number" min="0" max="15" value="6">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="render-width">长图宽度(px)</label>
|
||||
<input id="render-width" type="number" min="320" max="960" value="460">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>3. 可选微信发送(默认关闭)</h3>
|
||||
<div class="field">
|
||||
<label for="wechat-target">发送目标群聊</label>
|
||||
<select id="wechat-target">
|
||||
<option value="">不自动发送</option>
|
||||
</select>
|
||||
</div>
|
||||
<label class="check-row">
|
||||
<input id="auto-send" type="checkbox">
|
||||
<span>生成后自动发送晨报长图到所选目标群(默认关闭,建议先预览)</span>
|
||||
</label>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="card result-card">
|
||||
<div class="result-head">
|
||||
<h2>最近一次晨报结果</h2>
|
||||
<button id="send-last-btn" class="btn" type="button" disabled>手动发送长图到目标群</button>
|
||||
</div>
|
||||
<div id="digest-result" class="result-body empty">尚未生成晨报,勾选群聊后点击右上角「立即生成今日晨报」。</div>
|
||||
<div id="digest-preview-wrap" class="preview-wrap" hidden>
|
||||
<div class="preview-caption" id="digest-preview-caption"></div>
|
||||
<img id="digest-preview-img" class="preview-img" alt="晨报长图预览">
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,225 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 24px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
background: #f5f7fa;
|
||||
color: #18212f;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
background: #ffffff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 14px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.kicker {
|
||||
font-size: 12px;
|
||||
color: #2563eb;
|
||||
font-weight: 600;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #cbd5e1;
|
||||
background: #ffffff;
|
||||
color: #1e293b;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn.primary {
|
||||
background: #2563eb;
|
||||
border-color: #2563eb;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.banner {
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
font-size: 13px;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
border: 1px solid #bfdbfe;
|
||||
}
|
||||
|
||||
.banner[data-tone="error"] {
|
||||
background: #fef2f2;
|
||||
color: #b91c1c;
|
||||
border-color: #fecaca;
|
||||
}
|
||||
|
||||
.banner[data-tone="ok"] {
|
||||
background: #f0fdf4;
|
||||
color: #15803d;
|
||||
border-color: #bbf7d0;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #ffffff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 14px;
|
||||
padding: 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.card h3 {
|
||||
margin: 8px 0 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #cbd5e1;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.check-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.group-list {
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
padding: 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.group-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.group-item:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.result-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.result-body {
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
white-space: pre-wrap;
|
||||
background: #f8fafc;
|
||||
border-radius: 10px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.result-body.empty {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.preview-wrap {
|
||||
margin-top: 14px;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.preview-caption {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
word-break: break-all;
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.preview-img {
|
||||
max-width: 100%;
|
||||
width: 460px;
|
||||
height: auto;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #cbd5e1;
|
||||
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
|
||||
background: #ffffff;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"version": 1,
|
||||
"templates": {
|
||||
"douyin-sender@1.0.3": {
|
||||
"sha256": "01cd4b1a7af2b9e0208145b64e487af2a17f354ab7344f32cf9ff7565deb11a6",
|
||||
"bytes": 32839
|
||||
},
|
||||
"douyin-sender@1.0.4": {
|
||||
"sha256": "4fd4a478232d6b52a68187d2e0c3f42733acda1e65ce9f9594f99440e6edd3e5",
|
||||
"bytes": 32981
|
||||
},
|
||||
"douyin-sender@1.0.5": {
|
||||
"sha256": "d33559d6620ca173c97a19aafc8570521bf6426f6420e6fb8f90923333b554c8",
|
||||
"bytes": 33471
|
||||
},
|
||||
"group-chat-bot@1.0.0": {
|
||||
"sha256": "eb672f076710619dc363756d854319a8ded9b8f6a4833c258c1493c57bb89629",
|
||||
"bytes": 25231
|
||||
},
|
||||
"group-chat-bot@1.1.0": {
|
||||
"sha256": "be1fb28a2b8a20c95fccd19f6e2229f7166abfffefcf120309febcf3c882f437",
|
||||
"bytes": 25947
|
||||
},
|
||||
"keyword-bot@1.0.0": {
|
||||
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
|
||||
"bytes": 19121
|
||||
},
|
||||
"keyword-bot@1.0.1": {
|
||||
"sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41",
|
||||
"bytes": 19517
|
||||
},
|
||||
"morning-digest@1.0.0": {
|
||||
"sha256": "3336d3c7739aad0d40919546ca7884581aaaf7e3487db5428041d6bc0f6bd992",
|
||||
"bytes": 14556
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# TraceMemo 日报模板示例
|
||||
|
||||
此目录是可安装的最小日报模板源文件,使用全部虚构数据进行预览。运行 `node scripts/build-report-template-example.cjs` 会生成 `examples/report-template-basic.zip`。
|
||||
|
||||
模板只能调整已有日报模块的 HTML/CSS 排版。作者不能加入 JavaScript、事件属性、外部网络资源、嵌套页面、数据库访问、AI Prompt 或新的业务分析。
|
||||
|
||||
占位符分为三类:普通文本(会被 HTML 转义)、应用生成的 HTML 片段(只能作为元素内容使用)、受限样式类(只能放进 `class` 属性,并由应用输出合法 token)。`*_MORE_NOTE` 是 HTML 片段,不是样式类。
|
||||
|
||||
允许的标签和属性由 `src/shared/report-template-package.ts` 统一定义;图片资源只能是包内 `assets/` 下的 PNG/JPEG/WebP。缺少可选模块时应用输出空字符串和 `*_EMPTY_CLASS`,模板应允许该模块隐藏。
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"protocolVersion": "1.0",
|
||||
"kind": "daily-report",
|
||||
"id": "community.github.example.basic-feed",
|
||||
"name": "基础信息流",
|
||||
"author": { "name": "example" },
|
||||
"templateVersion": "1.0.0",
|
||||
"interfaceVersion": "1",
|
||||
"entry": "template.html",
|
||||
"preview": "preview.png",
|
||||
"capture": { "width": 430, "maxWidth": 430, "maxHeight": 20000 },
|
||||
"license": { "spdx": "MIT" },
|
||||
"platform": "mobile"
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>{{REPORT_TITLE}}</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; width: 430px; background: #f3f5f7; color: #18202a; font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
|
||||
.report { padding: 18px 14px 32px; }
|
||||
.hero, .section { margin-top: 10px; padding: 16px; border-radius: 14px; background: #fff; }
|
||||
.hero { margin-top: 0; border-top: 4px solid #1769aa; }
|
||||
h1 { margin: 0 0 8px; font-size: 23px; }
|
||||
.meta, .muted { color: #64748b; font-size: 12px; line-height: 1.5; }
|
||||
.section-title { margin: 0 0 8px; font-size: 14px; }
|
||||
.topics-grid, .important-list { display: grid; gap: 8px; }
|
||||
.topic-card, .important-card { padding: 10px; border: 1px solid #dbe4ee; border-radius: 10px; }
|
||||
.empty-section { display: none !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="report {{REPORT_MODE_CLASS}}">
|
||||
<section class="hero {{REPORT_MODE_CLASS}}">
|
||||
<h1>{{REPORT_TITLE}}</h1>
|
||||
<div class="meta">{{REPORT_DATE}} · {{DATE_RANGE}}</div>
|
||||
<p>{{HERO_SUMMARY}}</p>
|
||||
<div class="muted">{{HERO_STATUS_LINE}}</div>
|
||||
</section>
|
||||
<section class="section {{TOPICS_EMPTY_CLASS}}">
|
||||
<h2 class="section-title">今日话题</h2>
|
||||
<div class="topics-grid">{{TOPIC_CARDS}}</div>
|
||||
{{TOPICS_MORE_NOTE}}
|
||||
</section>
|
||||
<section class="section {{MESSAGES_EMPTY_CLASS}}">
|
||||
<h2 class="section-title">重要消息</h2>
|
||||
<div class="important-list">{{IMPORTANT_MESSAGES}}</div>
|
||||
</section>
|
||||
<footer class="muted">{{FOOTER_NOTE}}</footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>TraceMemo(迹忆)</title>
|
||||
<link rel="icon" type="image/svg+xml" href="./assets/brand-icon-DQrJvdgV.svg" />
|
||||
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:; frame-src tm-extension:;"
|
||||
/>
|
||||
<script type="module" crossorigin src="./assets/index-CRoZdOvo.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-DJPGPmFx.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tracememo",
|
||||
"version": "2.2.3",
|
||||
"version": "2.7.0",
|
||||
"packageManager": "pnpm@7.33.7",
|
||||
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
|
||||
"keywords": [
|
||||
@@ -25,22 +25,28 @@
|
||||
},
|
||||
"main": "./out/main/index.js",
|
||||
"scripts": {
|
||||
"test": "pnpm typecheck && pnpm test:unit && pnpm test:component && pnpm test:integration && pnpm test:skill-install && pnpm test:wechat-connector && pnpm test:e2e:build && playwright test",
|
||||
"test": "pnpm typecheck && pnpm test:unit && pnpm test:component && pnpm test:integration && pnpm test:skill-install && pnpm test:e2e:build && playwright test",
|
||||
"format": "prettier --write .",
|
||||
"lint": "eslint --cache .",
|
||||
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
|
||||
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web",
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:test",
|
||||
"typecheck:test": "node scripts/typecheck-tests.cjs",
|
||||
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
|
||||
"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",
|
||||
"prepare:wechat-personal": "node scripts/prepare-wechat-chatter-runtime.cjs",
|
||||
"prepare:ffmpeg:mac:arm64": "node scripts/prepare-electron-runtime.cjs --platform darwin --arch arm64",
|
||||
"prepare:ffmpeg:mac:x64": "node scripts/prepare-electron-runtime.cjs --platform darwin --arch x64",
|
||||
"prepare:win-runtime": "node scripts/prepare-win-runtime.cjs && npm run prepare:ffmpeg:win",
|
||||
"prepare:wechat-native": "node scripts/prepare-wechat-native-runtime.cjs",
|
||||
"start": "electron-vite preview",
|
||||
"predev": "node -e \"require('electron')\"",
|
||||
"dev": "node scripts/ensure-env.cjs && node scripts/build-wechat-connector.cjs && electron-vite dev",
|
||||
"predev": "node scripts/ensure-electron-binary.cjs",
|
||||
"dev": "node scripts/ensure-env.cjs && electron-vite dev",
|
||||
"dev:update": "cross-env TRACEMEMO_UPDATE_SIMULATION=true pnpm dev",
|
||||
"test:wechat-connector": "go -C services/wechat-connector test ./... && go -C services/wechat-connector vet ./...",
|
||||
"poc:query-agent": "electron-vite build && node scripts/run-query-agent-poc.cjs",
|
||||
"poc:query-agent:run": "node scripts/run-query-agent-poc.cjs",
|
||||
"test:unit": "vitest run --config vitest.unit.config.ts",
|
||||
"test:component": "vitest run --config vitest.component.config.ts",
|
||||
"test:integration": "vitest run --config vitest.integration.config.ts",
|
||||
@@ -51,26 +57,34 @@
|
||||
"test:e2e": "pnpm test:e2e:build && playwright test --grep-invert @visual",
|
||||
"test:visual": "pnpm test:e2e:build && playwright test tests/e2e/visual.spec.ts",
|
||||
"test:smoke": "node --test tests/smoke/native-environment.test.mjs",
|
||||
"build:wechat-connector": "node scripts/build-wechat-connector.cjs",
|
||||
"build:wechat-connector:win": "node scripts/build-wechat-connector.cjs --platform win32 --arch x64",
|
||||
"build:wechat-connector:mac": "node scripts/build-wechat-connector.cjs --platform darwin --arch arm64",
|
||||
"build:native-services": "npm run build:wechat-connector",
|
||||
"build": "npm run typecheck && npm run build:native-services && electron-vite build",
|
||||
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs",
|
||||
"build": "npm run typecheck && electron-vite build",
|
||||
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs && node scripts/ensure-electron-binary.cjs",
|
||||
"build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir",
|
||||
"build:win": "npm run typecheck && npm run build:wechat-connector:win && npm run prepare:ffmpeg:win && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
|
||||
"build:mac:arm64": "npm run typecheck && node scripts/build-wechat-connector.cjs --platform darwin --arch arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
|
||||
"build:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64",
|
||||
"build:mac:arm64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
|
||||
"build:mac:arm64:send-runtime": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64",
|
||||
"build:mac:public": "node scripts/build-macos-edition.cjs public",
|
||||
"build:mac:native": "node scripts/build-macos-edition.cjs native",
|
||||
"build:mac:x64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
|
||||
"release": "npm run release:mac && npm run release:win",
|
||||
"release:mac": "npm run typecheck && npm run build:wechat-connector:mac && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64 --publish always",
|
||||
"release:win": "npm run typecheck && npm run build:wechat-connector:win && npm run prepare:ffmpeg:win && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
|
||||
"release:beta": "cross-env RELEASE_TYPE=prerelease npm run release",
|
||||
"release:stable": "cross-env RELEASE_TYPE=release npm run release",
|
||||
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux"
|
||||
"release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64",
|
||||
"release:mac:arm64": "npm run build:templates && npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64",
|
||||
"release:mac:x64": "npm run build:templates && npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64",
|
||||
"release:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always",
|
||||
"release:beta": "cross-env EP_PRE_RELEASE=true npm run release",
|
||||
"release:stable": "npm run release",
|
||||
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux",
|
||||
"build:templates": "node scripts/build-extension-templates.cjs",
|
||||
"prebuild": "node scripts/build-extension-templates.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@electron-toolkit/preload": "^3.0.2",
|
||||
"@electron-toolkit/utils": "^4.0.0",
|
||||
"@koromix/koffi-darwin-x64": "3.1.0",
|
||||
"@koromix/koffi-win32-x64": "3.1.0",
|
||||
"@napi-rs/system-ocr": "1.2.0",
|
||||
"@napi-rs/system-ocr-darwin-x64": "1.2.0",
|
||||
"@napi-rs/system-ocr-win32-x64-msvc": "1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.23",
|
||||
"@radix-ui/react-checkbox": "^1.3.11",
|
||||
"@radix-ui/react-dialog": "^1.1.23",
|
||||
@@ -90,6 +104,7 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cross-env": "^10.1.0",
|
||||
"css-tree": "^3.0.1",
|
||||
"electron-updater": "^6.6.2",
|
||||
"ffmpeg-static": "5.3.0",
|
||||
"fs-extra": "^11.3.2",
|
||||
@@ -97,10 +112,15 @@
|
||||
"jsonrepair": "^3.15.0",
|
||||
"koffi": "^3.1.0",
|
||||
"openai": "^6.10.0",
|
||||
"parse5": "^8.0.0",
|
||||
"pinyin-pro": "^3.26.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"sherpa-onnx-darwin-x64": "1.13.3",
|
||||
"sherpa-onnx-node": "1.13.3",
|
||||
"sherpa-onnx-win-x64": "1.13.4",
|
||||
"silk-wasm": "^3.7.1",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"unzipper": "^0.12.0",
|
||||
"wechat-emojis": "^1.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -159,4 +179,4 @@
|
||||
"ffmpeg-static"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# @tracememo/extension-sdk
|
||||
|
||||
TraceMemo 扩展 SDK v1 的**类型定义**。运行期不需要安装或打包这个包:宿主在扩展后台进程里注入全局 `tm`。
|
||||
|
||||
## 用法
|
||||
|
||||
把 `index.d.ts` 复制进扩展仓库(或作为 devDependency),然后:
|
||||
|
||||
```ts
|
||||
import type { TraceMemoApi } from './extension-sdk'
|
||||
|
||||
module.exports = function activate(tm: TraceMemoApi): void {
|
||||
tm.events.on('message.received', async (event) => {
|
||||
if (event.isSelf || event.type !== 'text') return
|
||||
if (!event.text?.includes('你好')) return
|
||||
await tm.wechat.send({ to: event.conversationId, text: '你好呀!', dedupeKey: event.eventId })
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## 约定
|
||||
|
||||
- 所有能力都要在 `manifest.json` 里声明权限;未声明的调用返回 `PERMISSION_DENIED`。
|
||||
- 后台是**独立 Node 子进程**,不是强沙箱:安装即表示信任该扩展代码。
|
||||
- 页面运行在 `sandbox="allow-scripts"` 的 iframe 里,只能通过 postMessage 调用
|
||||
`storage.*` / `capabilities.get` / `extension.info`,不能发送微信消息。
|
||||
- 发送永远经过宿主 Gateway:权限、授权校验、限流、审计与幂等都在宿主侧执行。
|
||||
@@ -0,0 +1,430 @@
|
||||
/** TraceMemo 扩展 SDK v1(兼容扩展):仅类型定义,运行期由宿主注入全局 tm。 */
|
||||
|
||||
export type ExtensionMessageType =
|
||||
| 'text'
|
||||
| 'image'
|
||||
| 'voice'
|
||||
| 'video'
|
||||
| 'sticker'
|
||||
| 'file'
|
||||
| 'link'
|
||||
| 'system'
|
||||
| 'other'
|
||||
|
||||
export type ExtensionNavigationIcon =
|
||||
| 'spark'
|
||||
| 'bot'
|
||||
| 'digest'
|
||||
| 'bell'
|
||||
| 'media'
|
||||
| 'puzzle'
|
||||
| 'compass'
|
||||
| 'message'
|
||||
|
||||
export type ExtensionNotificationLevel = 'info' | 'success' | 'warning' | 'error'
|
||||
|
||||
export interface TraceMemoMessageEvent {
|
||||
/** 同一条微信消息稳定不变:`message:<sha1(sessionId:localId)>`。 */
|
||||
eventId: string
|
||||
/** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */
|
||||
messageRef: string
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
isGroup: boolean
|
||||
isSelf: boolean
|
||||
type: ExtensionMessageType
|
||||
text?: string
|
||||
/** 真正 @ 到当前登录账号,不是正文里的 `@昵称`。 */
|
||||
mentionsMe: boolean
|
||||
/** epoch 毫秒。 */
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface TraceMemoQueriedMessage {
|
||||
messageId: string
|
||||
/** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */
|
||||
messageRef: string
|
||||
conversationId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
isSelf: boolean
|
||||
type: string
|
||||
text?: string
|
||||
/** epoch 毫秒。 */
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface TraceMemoMessagesQueryRequest {
|
||||
conversationId: string
|
||||
/** epoch 毫秒;默认最近 24 小时。 */
|
||||
startTime?: number
|
||||
/** epoch 毫秒;默认现在。 */
|
||||
endTime?: number
|
||||
limit?: number
|
||||
/** 上一页返回的 opaque 游标;同时间戳多条消息不漏不重。 */
|
||||
cursor?: string
|
||||
order?: 'asc' | 'desc'
|
||||
types?: ExtensionMessageType[]
|
||||
}
|
||||
|
||||
export interface TraceMemoMessagesQueryResult {
|
||||
messages: TraceMemoQueriedMessage[]
|
||||
nextCursor?: string
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaReadImageResult {
|
||||
messageRef: string
|
||||
mimeType: string
|
||||
bytes: number
|
||||
sha256: string
|
||||
/** 扩展私有数据目录内的可读副本路径。 */
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览 URL。 */
|
||||
previewUrl?: string
|
||||
quality: 'original' | 'thumbnail'
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaReadVoiceResult {
|
||||
messageRef: string
|
||||
mimeType: 'audio/wav'
|
||||
bytes: number
|
||||
sha256: string
|
||||
durationMs?: number
|
||||
path: string
|
||||
previewUrl?: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaReadVideoResult {
|
||||
messageRef: string
|
||||
mimeType: 'video/mp4'
|
||||
bytes: number
|
||||
sha256: string
|
||||
path: string
|
||||
previewUrl?: string
|
||||
posterPath?: string
|
||||
posterPreviewUrl?: string
|
||||
durationMs?: number
|
||||
width?: number
|
||||
height?: number
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaOcrImageResult {
|
||||
messageRef: string
|
||||
text: string
|
||||
language: string | null
|
||||
engine: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaTranscribeVoiceResult {
|
||||
messageRef: string
|
||||
state: 'transcribed' | 'pending' | 'failed'
|
||||
transcript?: string
|
||||
durationMs?: number
|
||||
cached: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaAnalyzeImageResult {
|
||||
messageRef: string
|
||||
description: string
|
||||
ocrText?: string
|
||||
tags?: string[]
|
||||
category?: string
|
||||
model?: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export type TraceMemoMediaBatchOperation =
|
||||
| 'readImage'
|
||||
| 'readVoice'
|
||||
| 'readVideo'
|
||||
| 'ocrImage'
|
||||
| 'transcribeVoice'
|
||||
| 'analyzeImage'
|
||||
|
||||
export interface TraceMemoMediaBatchItem {
|
||||
op: TraceMemoMediaBatchOperation
|
||||
messageRef: string
|
||||
options?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaBatchItemResult {
|
||||
index: number
|
||||
op: TraceMemoMediaBatchOperation
|
||||
messageRef: string
|
||||
ok: boolean
|
||||
result?:
|
||||
| TraceMemoMediaReadImageResult
|
||||
| TraceMemoMediaReadVoiceResult
|
||||
| TraceMemoMediaReadVideoResult
|
||||
| TraceMemoMediaOcrImageResult
|
||||
| TraceMemoMediaTranscribeVoiceResult
|
||||
| TraceMemoMediaAnalyzeImageResult
|
||||
error?: { code: string; message: string }
|
||||
}
|
||||
|
||||
export interface TraceMemoRenderHtmlRequest {
|
||||
html: string
|
||||
css?: string
|
||||
/** 可选相对文件名(输出到扩展私有目录的 rendered/ 下)。 */
|
||||
fileName?: string
|
||||
width?: number
|
||||
maxHeight?: number
|
||||
backgroundColor?: string
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export interface TraceMemoRenderHtmlResult {
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览 URL。 */
|
||||
previewUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
pixelWidth?: number
|
||||
pixelHeight?: number
|
||||
deviceScaleFactor?: number
|
||||
bytes: number
|
||||
mimeType: 'image/png'
|
||||
sha256: string
|
||||
}
|
||||
|
||||
export interface TraceMemoNotificationCreateRequest {
|
||||
title: string
|
||||
body?: string
|
||||
level?: ExtensionNotificationLevel
|
||||
/** 扩展内去重键;相同键更新既有通知而不重复叠加未读数。 */
|
||||
dedupeKey?: string
|
||||
/** 点击通知后跳转的本扩展页面 id。 */
|
||||
pageId?: string
|
||||
}
|
||||
|
||||
export interface TraceMemoNotificationCreateResult {
|
||||
id: string
|
||||
deduped: boolean
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export interface TraceMemoNotificationItem {
|
||||
id: string
|
||||
extensionId: string
|
||||
extensionName: string
|
||||
title: string
|
||||
body?: string
|
||||
level: ExtensionNotificationLevel
|
||||
dedupeKey?: string
|
||||
pageId?: string
|
||||
read: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface TraceMemoSendTextRequest {
|
||||
/** 缺省为 text。 */
|
||||
type?: 'text'
|
||||
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
|
||||
to: string
|
||||
text: string
|
||||
at?: Record<string, string>
|
||||
/** 相同键的重复请求会被 Gateway 审计短路。 */
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
/** 图片发送。 */
|
||||
export interface TraceMemoSendImageRequest {
|
||||
type: 'image'
|
||||
to: string
|
||||
path: string
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
/** 视频发送。原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交;路径必须位于扩展数据目录或系统临时目录。 */
|
||||
export interface TraceMemoSendVideoRequest {
|
||||
type: 'video'
|
||||
to: string
|
||||
path: string
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
export interface TraceMemoSendVoiceRequest {
|
||||
type: 'voice'
|
||||
to: string
|
||||
/** 传 `text` 时由宿主使用已配置的文字转语音服务合成并发送。 */
|
||||
text?: string
|
||||
/** 传 `path` 时发送扩展数据目录或系统临时目录中的音频文件。 */
|
||||
path?: string
|
||||
/** 可选音色 ID;省略时使用 TraceMemo 设置页选定的默认音色。 */
|
||||
voiceId?: string
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
export type TraceMemoSendRequest =
|
||||
| TraceMemoSendTextRequest
|
||||
| TraceMemoSendImageRequest
|
||||
| TraceMemoSendVideoRequest
|
||||
| TraceMemoSendVoiceRequest
|
||||
|
||||
export interface TraceMemoAutomationActionDefinition {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
inputSchema?: {
|
||||
type: 'object'
|
||||
properties?: Record<string, { type?: 'string' | 'number' | 'boolean'; description?: string }>
|
||||
required?: string[]
|
||||
}
|
||||
handler: (input: Record<string, unknown>) => unknown | Promise<unknown>
|
||||
}
|
||||
|
||||
export interface TraceMemoAutomationActionOutput {
|
||||
success: boolean
|
||||
output?: Record<string, unknown>
|
||||
/** 宿主经 Gateway 发回原会话;扩展自己不发消息。 */
|
||||
reply?: { type: 'text'; text: string; at?: Record<string, string> }
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface TraceMemoCapabilities {
|
||||
extensionId: string
|
||||
enabled: boolean
|
||||
permissions: string[]
|
||||
platform: string
|
||||
databaseReady: boolean
|
||||
send: {
|
||||
supported: boolean
|
||||
ready: boolean
|
||||
canSendText: boolean
|
||||
canSendImage: boolean
|
||||
canSendVideo: boolean
|
||||
canSendVoice?: boolean
|
||||
licensed: boolean
|
||||
message: string
|
||||
}
|
||||
ai: { configured: boolean; modelName: string }
|
||||
tts?: {
|
||||
configured: boolean
|
||||
model: string
|
||||
selectedVoiceId: string
|
||||
selectedVoice: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
tags: string[]
|
||||
languages: string[]
|
||||
authorName?: string
|
||||
previewUrl?: string
|
||||
coverImage?: string
|
||||
} | null
|
||||
}
|
||||
}
|
||||
|
||||
export interface TraceMemoApi {
|
||||
extension: {
|
||||
readonly id: string
|
||||
/** 扩展私有数据目录;下载与生成的文件应放在这里。 */
|
||||
readonly dataDir: string
|
||||
readonly permissions: string[]
|
||||
}
|
||||
page: {
|
||||
onRequest(
|
||||
method: string,
|
||||
handler: (params: Record<string, unknown>) => unknown | Promise<unknown>
|
||||
): void
|
||||
}
|
||||
secrets: {
|
||||
get(key: string): Promise<string | null>
|
||||
set(key: string, value: string): Promise<void>
|
||||
delete(key: string): Promise<void>
|
||||
has(key: string): Promise<boolean>
|
||||
}
|
||||
events: {
|
||||
on(
|
||||
name: 'message.received',
|
||||
handler: (event: TraceMemoMessageEvent) => void | Promise<void>
|
||||
): () => void
|
||||
off(
|
||||
name: 'message.received',
|
||||
handler: (event: TraceMemoMessageEvent) => void | Promise<void>
|
||||
): void
|
||||
}
|
||||
messages: {
|
||||
query(request: TraceMemoMessagesQueryRequest): Promise<TraceMemoMessagesQueryResult>
|
||||
}
|
||||
media: {
|
||||
readImage(request: {
|
||||
messageRef: string
|
||||
quality?: 'original' | 'thumbnail'
|
||||
}): Promise<TraceMemoMediaReadImageResult>
|
||||
readVoice(request: { messageRef: string }): Promise<TraceMemoMediaReadVoiceResult>
|
||||
readVideo(request: { messageRef: string }): Promise<TraceMemoMediaReadVideoResult>
|
||||
ocrImage(request: {
|
||||
messageRef: string
|
||||
language?: string
|
||||
force?: boolean
|
||||
}): Promise<TraceMemoMediaOcrImageResult>
|
||||
transcribeVoice(request: {
|
||||
messageRef: string
|
||||
force?: boolean
|
||||
waitMs?: number
|
||||
}): Promise<TraceMemoMediaTranscribeVoiceResult>
|
||||
analyzeImage(request: {
|
||||
messageRef: string
|
||||
prompt?: string
|
||||
force?: boolean
|
||||
}): Promise<TraceMemoMediaAnalyzeImageResult>
|
||||
batch(request: {
|
||||
items: TraceMemoMediaBatchItem[]
|
||||
concurrency?: number
|
||||
}): Promise<{ results: TraceMemoMediaBatchItemResult[] }>
|
||||
}
|
||||
render: {
|
||||
htmlToImage(request: TraceMemoRenderHtmlRequest): Promise<TraceMemoRenderHtmlResult>
|
||||
}
|
||||
notifications: {
|
||||
create(request: TraceMemoNotificationCreateRequest): Promise<TraceMemoNotificationCreateResult>
|
||||
list(): Promise<TraceMemoNotificationItem[]>
|
||||
markRead(request?: { id?: string; all?: boolean }): Promise<{ changed: number }>
|
||||
}
|
||||
wechat: {
|
||||
send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }>
|
||||
}
|
||||
ai: {
|
||||
chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }>
|
||||
analyzeImage(request: {
|
||||
messageRef: string
|
||||
prompt?: string
|
||||
force?: boolean
|
||||
}): Promise<TraceMemoMediaAnalyzeImageResult>
|
||||
}
|
||||
storage: {
|
||||
get(key: string): Promise<unknown>
|
||||
set(key: string, value: unknown): Promise<void>
|
||||
remove(key: string): Promise<boolean>
|
||||
list(): Promise<Array<{ key: string; value: unknown }>>
|
||||
}
|
||||
automation: {
|
||||
registerAction(definition: TraceMemoAutomationActionDefinition): void
|
||||
}
|
||||
capabilities: {
|
||||
get(): Promise<TraceMemoCapabilities>
|
||||
}
|
||||
log: {
|
||||
info(message: unknown): void
|
||||
warn(message: unknown): void
|
||||
error(message: unknown): void
|
||||
}
|
||||
}
|
||||
|
||||
/** 后台入口签名。 */
|
||||
export type TraceMemoActivate = (tm: TraceMemoApi) => void | Promise<void>
|
||||
|
||||
declare global {
|
||||
var tm: TraceMemoApi
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@tracememo/extension-sdk",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "TraceMemo 扩展 SDK 的类型定义(v1)。运行期由宿主注入 tm 对象,无需打包进扩展。",
|
||||
"types": "index.d.ts",
|
||||
"files": ["index.d.ts", "README.md"],
|
||||
"license": "MIT"
|
||||
}
|
||||
@@ -11,7 +11,11 @@ specifiers:
|
||||
'@electron-toolkit/preload': ^3.0.2
|
||||
'@electron-toolkit/tsconfig': ^2.0.0
|
||||
'@electron-toolkit/utils': ^4.0.0
|
||||
'@koromix/koffi-darwin-x64': 3.1.0
|
||||
'@koromix/koffi-win32-x64': 3.1.0
|
||||
'@napi-rs/system-ocr': 1.2.0
|
||||
'@napi-rs/system-ocr-darwin-x64': 1.2.0
|
||||
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
|
||||
'@playwright/test': ^1.62.1
|
||||
'@radix-ui/react-alert-dialog': ^1.1.23
|
||||
'@radix-ui/react-checkbox': ^1.3.11
|
||||
@@ -46,6 +50,7 @@ specifiers:
|
||||
class-variance-authority: ^0.7.1
|
||||
clsx: ^2.1.1
|
||||
cross-env: ^10.1.0
|
||||
css-tree: ^3.0.1
|
||||
electron: ^43.0.0
|
||||
electron-builder: ^26.0.12
|
||||
electron-updater: ^6.6.2
|
||||
@@ -61,18 +66,23 @@ specifiers:
|
||||
jsonrepair: ^3.15.0
|
||||
koffi: ^3.1.0
|
||||
openai: ^6.10.0
|
||||
parse5: ^8.0.0
|
||||
pinyin-pro: ^3.26.0
|
||||
postcss: ^8.5.26
|
||||
prettier: ^3.7.4
|
||||
qrcode: ^1.5.4
|
||||
react: ^19.2.1
|
||||
react-dom: ^19.2.1
|
||||
sass: ^1.102.0
|
||||
sherpa-onnx-darwin-x64: 1.13.3
|
||||
sherpa-onnx-node: 1.13.3
|
||||
sherpa-onnx-win-x64: 1.13.4
|
||||
silk-wasm: ^3.7.1
|
||||
tailwind-merge: ^3.6.0
|
||||
tailwindcss: 3.4.17
|
||||
tailwindcss-animate: ^1.0.7
|
||||
typescript: ^5.9.3
|
||||
unzipper: ^0.12.0
|
||||
vite: ^7.2.6
|
||||
vitest: ^4.1.10
|
||||
wechat-emojis: ^1.0.2
|
||||
@@ -81,7 +91,11 @@ specifiers:
|
||||
dependencies:
|
||||
'@electron-toolkit/preload': 3.0.2_electron@43.1.0
|
||||
'@electron-toolkit/utils': 4.0.0_electron@43.1.0
|
||||
'@koromix/koffi-darwin-x64': 3.1.0
|
||||
'@koromix/koffi-win32-x64': 3.1.0
|
||||
'@napi-rs/system-ocr': 1.2.0
|
||||
'@napi-rs/system-ocr-darwin-x64': 1.2.0
|
||||
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
|
||||
'@radix-ui/react-alert-dialog': 1.1.23_eijghdl4n2x4hz6j4cg7ctgbuu
|
||||
'@radix-ui/react-checkbox': 1.3.11_eijghdl4n2x4hz6j4cg7ctgbuu
|
||||
'@radix-ui/react-dialog': 1.1.23_eijghdl4n2x4hz6j4cg7ctgbuu
|
||||
@@ -101,6 +115,7 @@ dependencies:
|
||||
class-variance-authority: 0.7.1
|
||||
clsx: 2.1.1
|
||||
cross-env: 10.1.0
|
||||
css-tree: 3.2.1
|
||||
electron-updater: 6.8.9
|
||||
ffmpeg-static: 5.3.0
|
||||
fs-extra: 11.3.2
|
||||
@@ -108,10 +123,15 @@ dependencies:
|
||||
jsonrepair: 3.15.0
|
||||
koffi: 3.1.0
|
||||
openai: 6.10.0
|
||||
parse5: 8.0.1
|
||||
pinyin-pro: 3.29.3
|
||||
qrcode: 1.5.4
|
||||
sherpa-onnx-darwin-x64: 1.13.3
|
||||
sherpa-onnx-node: 1.13.3
|
||||
sherpa-onnx-win-x64: 1.13.4
|
||||
silk-wasm: 3.7.1
|
||||
tailwind-merge: 3.6.0
|
||||
unzipper: 0.12.5
|
||||
wechat-emojis: 1.0.2
|
||||
|
||||
devDependencies:
|
||||
@@ -1573,7 +1593,6 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-freebsd-arm64/3.1.0:
|
||||
resolution: {integrity: sha512-vazoPYIhOAlXZksVIqDRMIID4VeUZKx8F3dR90hOobT2ATyOkqNS5dv5UCV7Q7DSq22lQTrdbvENBAhROzCp0w==}
|
||||
@@ -1677,6 +1696,46 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@napi-rs/system-ocr-darwin-arm64/1.2.0:
|
||||
resolution: {integrity: sha512-cK8dcDBEl3P4A04xmFJSHEJQxfDytaAIFyDCLqavTp92FVU5plESttWzZsqtTkS81/kzKiBfHyPQffSIndfWbQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@napi-rs/system-ocr-darwin-x64/1.2.0:
|
||||
resolution: {integrity: sha512-u3TBvBGrhmT5Os6AfaxbUEg6VHe8lvrFJNPgThJgshJHyRXUx/wCfTyOroJ22KdVCP5AE4GpwS5tFHMb6p6iaQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
dev: false
|
||||
|
||||
/@napi-rs/system-ocr-win32-arm64-msvc/1.2.0:
|
||||
resolution: {integrity: sha512-7ej8uMvmXomw3NXo5gZ5p2Nl6UKsHI+VRU3ELv0mhcxR0sJ6wFifYTu5bJrM1TGcz1/RsaX+TjWMmsDq8vriKQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@napi-rs/system-ocr-win32-x64-msvc/1.2.0:
|
||||
resolution: {integrity: sha512-oOoCj3FPWDVctTxx98vMBiMI6m51U+w7SMmMefvmtpcpLelzZ/zYTqdwtWZFAjShaHO+RdaKkcpeVcQuBQiVbA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
dev: false
|
||||
|
||||
/@napi-rs/system-ocr/1.2.0:
|
||||
resolution: {integrity: sha512-r0f2xNH6U+sth44qF+lUP+2WuHSGUBAry5KSCNuaLDGRbgslFqeROr/qJJ/fb6AjBp3Ov+CJP5MdrOWoaoM3cw==}
|
||||
engines: {node: '>= 10'}
|
||||
optionalDependencies:
|
||||
'@napi-rs/system-ocr-darwin-arm64': 1.2.0
|
||||
'@napi-rs/system-ocr-darwin-x64': 1.2.0
|
||||
'@napi-rs/system-ocr-win32-arm64-msvc': 1.2.0
|
||||
'@napi-rs/system-ocr-win32-x64-msvc': 1.2.0
|
||||
dev: false
|
||||
|
||||
/@nodelib/fs.scandir/2.1.5:
|
||||
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
|
||||
engines: {node: '>= 8'}
|
||||
@@ -3898,6 +3957,10 @@ packages:
|
||||
resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==}
|
||||
dev: true
|
||||
|
||||
/bluebird/3.7.2:
|
||||
resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}
|
||||
dev: false
|
||||
|
||||
/brace-expansion/1.1.12:
|
||||
resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
|
||||
dependencies:
|
||||
@@ -4350,7 +4413,6 @@ packages:
|
||||
dependencies:
|
||||
mdn-data: 2.27.1
|
||||
source-map-js: 1.2.1
|
||||
dev: true
|
||||
|
||||
/css.escape/1.5.1:
|
||||
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
|
||||
@@ -4570,6 +4632,12 @@ packages:
|
||||
gopd: 1.2.0
|
||||
dev: true
|
||||
|
||||
/duplexer2/0.1.4:
|
||||
resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}
|
||||
dependencies:
|
||||
readable-stream: 2.3.8
|
||||
dev: false
|
||||
|
||||
/eastasianwidth/0.2.0:
|
||||
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
|
||||
dev: true
|
||||
@@ -4697,7 +4765,6 @@ packages:
|
||||
/entities/8.0.0:
|
||||
resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}
|
||||
engines: {node: '>=20.19.0'}
|
||||
dev: true
|
||||
|
||||
/env-paths/2.2.1:
|
||||
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
|
||||
@@ -5301,6 +5368,15 @@ packages:
|
||||
jsonfile: 6.2.0
|
||||
universalify: 2.0.1
|
||||
|
||||
/fs-extra/11.3.1:
|
||||
resolution: {integrity: sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==}
|
||||
engines: {node: '>=14.14'}
|
||||
dependencies:
|
||||
graceful-fs: 4.2.11
|
||||
jsonfile: 6.2.0
|
||||
universalify: 2.0.1
|
||||
dev: false
|
||||
|
||||
/fs-extra/11.3.2:
|
||||
resolution: {integrity: sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==}
|
||||
engines: {node: '>=14.14'}
|
||||
@@ -6326,7 +6402,6 @@ packages:
|
||||
|
||||
/mdn-data/2.27.1:
|
||||
resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}
|
||||
dev: true
|
||||
|
||||
/merge2/1.4.1:
|
||||
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
|
||||
@@ -6552,6 +6627,10 @@ packages:
|
||||
semver: 7.7.3
|
||||
dev: true
|
||||
|
||||
/node-int64/0.4.0:
|
||||
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
|
||||
dev: false
|
||||
|
||||
/node-releases/2.0.27:
|
||||
resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==}
|
||||
dev: true
|
||||
@@ -6771,7 +6850,6 @@ packages:
|
||||
resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}
|
||||
dependencies:
|
||||
entities: 8.0.0
|
||||
dev: true
|
||||
|
||||
/path-exists/4.0.0:
|
||||
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
|
||||
@@ -6835,6 +6913,10 @@ packages:
|
||||
engines: {node: '>=0.10.0'}
|
||||
dev: true
|
||||
|
||||
/pinyin-pro/3.29.3:
|
||||
resolution: {integrity: sha512-+UU9bx6vfDw8amOJGHm0TE0rdQl8VPylsDWviQ5OOQ3e+on1xRP4OqDbiDuMT5OISgvfl/Y6ez1BBRaIP80GLQ==}
|
||||
dev: false
|
||||
|
||||
/pirates/4.0.7:
|
||||
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
|
||||
engines: {node: '>= 6'}
|
||||
@@ -7516,7 +7598,6 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/sherpa-onnx-linux-arm64/1.13.4:
|
||||
resolution: {integrity: sha512-RMjMRqT82BgTXypNNGmLe6ZFYhc3WEvnAGl3DdkK7qB/kuXwkL3iHhV31wAecbnWPsnEpUoD+8cFovWSBzsCuw==}
|
||||
@@ -7555,7 +7636,6 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/side-channel-list/1.0.0:
|
||||
resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
|
||||
@@ -7659,7 +7739,6 @@ packages:
|
||||
/source-map-js/1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
dev: true
|
||||
|
||||
/source-map-support/0.5.21:
|
||||
resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==}
|
||||
@@ -8204,6 +8283,16 @@ packages:
|
||||
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
|
||||
engines: {node: '>= 10.0.0'}
|
||||
|
||||
/unzipper/0.12.5:
|
||||
resolution: {integrity: sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==}
|
||||
dependencies:
|
||||
bluebird: 3.7.2
|
||||
duplexer2: 0.1.4
|
||||
fs-extra: 11.3.1
|
||||
graceful-fs: 4.2.11
|
||||
node-int64: 0.4.0
|
||||
dev: false
|
||||
|
||||
/update-browserslist-db/1.2.2_browserslist@4.28.1:
|
||||
resolution: {integrity: sha512-E85pfNzMQ9jpKkA7+TJAi4TJN+tBCuWh5rUcS/sv6cFi+1q9LYDwDI5dpUL0u/73EElyQ8d3TEaeW4sPedBqYA==}
|
||||
hasBin: true
|
||||
|
||||
|
Before Width: | Height: | Size: 156 KiB After Width: | Height: | Size: 152 KiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 278 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 138 KiB |
|
After Width: | Height: | Size: 338 KiB |
@@ -68,21 +68,29 @@
|
||||
.overview {
|
||||
margin-top: 2px;
|
||||
}
|
||||
/*
|
||||
* hero 头像簇的几何必须由 contract 变量驱动,不能再写死容器尺寸。
|
||||
*
|
||||
* 生产导出会额外注入 `report-template-fragment-contract.ts`,其中
|
||||
* `img.tm-avatar.tm-avatar--hero` 用 !important 把头像钉在
|
||||
* clamp(28px, var(--tm-avatar-hero-size, 40px), 56px)。
|
||||
* 旧版这里写死 58x58(单头像 28x28),两个权威打架:头像实际 40px,
|
||||
* 2 列 x 40px + 3px gap = 83px 塞不进 58px 的盒子,于是头像向右向下溢出容器,
|
||||
* 视觉上越过卡片内边距、压到卡片边缘之外。
|
||||
*
|
||||
* 现在容器尺寸由内容决定(列宽/行高都取同一个变量):头像数 1..4 都不会溢出,
|
||||
* 主题调整 --tm-avatar-hero-size 时容器与头像也不会分叉。
|
||||
*/
|
||||
.avatar-grid {
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-columns: repeat(2, var(--tm-avatar-hero-size, 40px));
|
||||
grid-auto-rows: var(--tm-avatar-hero-size, 40px);
|
||||
gap: 3px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
/* 单头像时不保留空列,簇宽恰好等于一个头像。 */
|
||||
.avatar-grid.avatar-count-1 {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.avatar-grid.avatar-count-2 {
|
||||
height: 28px;
|
||||
grid-template-columns: var(--tm-avatar-hero-size, 40px);
|
||||
}
|
||||
.avatar-grid.empty-section {
|
||||
display: none;
|
||||
|
||||
@@ -61,21 +61,29 @@
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
/*
|
||||
* hero 头像簇的几何必须由 contract 变量驱动,不能再写死容器尺寸。
|
||||
*
|
||||
* 生产导出会额外注入 `report-template-fragment-contract.ts`,其中
|
||||
* `img.tm-avatar.tm-avatar--hero` 用 !important 把头像钉在
|
||||
* clamp(28px, var(--tm-avatar-hero-size, 40px), 56px)。
|
||||
* 旧版这里写死 58x58(单头像 28x28),两个权威打架:头像实际 40px,
|
||||
* 2 列 x 40px + 3px gap = 83px 塞不进 58px 的盒子,于是头像向右向下溢出容器,
|
||||
* 视觉上越过卡片内边距、压到卡片边缘之外。
|
||||
*
|
||||
* 现在容器尺寸由内容决定(列宽/行高都取同一个变量):头像数 1..4 都不会溢出,
|
||||
* 主题调整 --tm-avatar-hero-size 时容器与头像也不会分叉。
|
||||
*/
|
||||
.avatar-grid {
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-columns: repeat(2, var(--tm-avatar-hero-size, 40px));
|
||||
grid-auto-rows: var(--tm-avatar-hero-size, 40px);
|
||||
gap: 3px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
/* 单头像时不保留空列,簇宽恰好等于一个头像。 */
|
||||
.avatar-grid.avatar-count-1 {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.avatar-grid.avatar-count-2 {
|
||||
height: 28px;
|
||||
grid-template-columns: var(--tm-avatar-hero-size, 40px);
|
||||
}
|
||||
.avatar-grid.empty-section {
|
||||
display: none;
|
||||
|
||||