feat: Reader Skill 支持版本自检与自助更新

微信机器人回复剥离引用编号、列表改用空行分隔,失败通知补失败时刻
 问问微信关键词检索在索引落后时按单会话直读原始记录兜底
 关闭窗口支持记住选择并在设置中修改
 退群监控刷新列表
This commit is contained in:
Wxw-Gu committed 2026-10-14 10:31:01 +08:00
1 parent fd7d5016a8
commit eaa25cd29e
33 files changed
+1401 -154

No files matched your search

+6
View File
@@ -15,6 +15,9 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
# 版本漂移检查需要与基准分支比较 SKILL.md,浅克隆拿不到基准。
fetch-depth: 0
- uses: pnpm/action-setup@v4
with:
@@ -46,6 +49,9 @@ jobs:
- name: Skill installation instruction tests
run: pnpm test:skill-install
- name: Reader Skill version drift check
run: pnpm check:skill-version
- name: Build Electron test application
run: pnpm test:e2e:build
+53
View File
@@ -35,6 +35,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
| 方法 | 路径 | 作用 | 参数/请求体 |
| ------ | --------------------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------- |
| GET | `/api/v1/health` | 服务与数据库健康状态 | 无 |
| GET | `/api/v1/skill/tracememo-reader` | 当前 Reader Skill 的版本与全文 | 无(需 Token) |
| GET | `/api/v1/current_time` | 本机时间、时区和 Unix 时间戳 | 无 |
| GET | `/api/v1/contact` | 联系人和群聊列表 | `filter`、`type=user\|group` |
| GET | `/api/v1/chatroom` | 群聊列表 | `keyword` |
@@ -384,3 +385,55 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/voice-t
| `invalid_message_ref` | `messageRef` 无法解析 |
整次请求的状态:`200 completed`;`400 invalid_tool_arguments`(带 `field`、`constraint`、`hint`);`503 voice_model_not_ready`(模型未下载)或 `knowledge_unavailable`(数据库未连接);`429 busy`(队列已满,带 `retryAfterSeconds` 与 `Retry-After` 头)。
## Reader Skill 的版本与更新
Reader Skill 是随应用分发的说明文件。它被安装到 Agent 自己的 Skill 目录之后就与 TraceMemo 分离了,不再随应用升级自动变化,所以它必须能自己证明版本:
- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.3.0`);
- `/api/v1/health` 的 `skill.version` 回报当前应用内置的版本;
- 两者不一致,就说明 Agent 手里那份已经过期,接口契约可能已经变化。
### 检查更新
```bash
curl http://127.0.0.1:6131/api/v1/health
```
```json
{
"ok": true,
"ready": true,
"service": "TraceMemo Reader",
"version": "2.5.0",
"skill": { "name": "tracememo-reader", "version": "1.3.0", "available": true },
"timestamp": "2026-10-13T08:43:52.863Z"
}
```
注意区分两个版本号:`version` 是应用版本,`skill.version` 才是 Reader Skill 的版本。Skill 文件读不到时 `available` 为 `false`、`skill.version` 为 `null`,此时 health 仍然返回 `200`——外部 Agent 靠它做自检,这个接口不允许因为 Skill 缺失而失败。
### 拉取最新 Skill
```bash
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
```
```json
{
"name": "tracememo-reader",
"version": "1.3.0",
"contentHash": "<sha256 hex>",
"modifiedAt": "2026-10-13T08:37:30.000Z",
"markdown": "---\nname: tracememo-reader\nversion: 1.3.0\n…"
}
```
`markdown` 就是可以直接落盘的 SKILL.md 全文,`contentHash` 是它的 SHA-256,可用来核对写入结果。响应**不包含**任何本地文件路径。`503 skill_unavailable` 表示应用侧也没找到 Skill 文件,需要重新安装 TraceMemo。
### Agent 侧的自检义务
`docs/skill/tracememo-reader/SKILL.md` 中的「版本自检」要求 Agent 在每次会话开始时比对一次版本:不一致就停止读取数据并提醒用户重新安装;用户同意后,Agent 可以直接调用上面的接口自助覆盖本地文件,不需要用户重新复制安装指令。
修改 `SKILL.md` 内容时必须同步提升 `version`。CI 中的 `pnpm check:skill-version` 会在"只改文档、不升版本"时失败,避免再次出现"文档改了两轮、版本号纹丝不动"的情况。
+17 -1
View File
@@ -26,6 +26,21 @@ Reader Skill 只负责“外部 Agent 主动查询历史微信数据”。它不
TraceMemo 不会自动把 Token 写进 Agent 配置。重新生成 Token 后,必须同步更新 Agent 环境。
## 更新已安装的 Skill
Reader Skill 在 Agent 那边是独立副本,**不会随 TraceMemo 升级自动更新**。判断是否需要更新:
1. 在 API Center 的「Skill 详情」里看到的是 TraceMemo 内置的版本;
2. Agent 调用 `/api/v1/health` 拿到 `skill.version`;
3. 再和 Agent 手里 SKILL.md frontmatter 的 `version` 比对——不一致就是过期了。
更新有两种方式,任选其一:
- **让 Agent 自己更新**:直接告诉 Agent「你的 Reader Skill 过期了,请从本机 TraceMemo 拉最新版覆盖」。它会调用 `/api/v1/skill/tracememo-reader` 取回最新全文并落盘,不需要你重新复制安装指令。
- **手工重新安装**:回到 API Center → 快速接入,重新点一次「复制安装指令」交给 Agent 覆盖安装。
新版 Skill 里带有「版本自检」条款,要求 Agent 每次会话开始时比对一次版本。**如果它从来没提醒过你版本不一致,很可能你手里那份还是旧版**——旧版没有这条自检。
## Agent 的读取顺序
当用户使用“今天”“昨天”“本周”等相对时间时:
@@ -55,7 +70,8 @@ Reader Skill 可以指导 Agent 使用:
- 结构化日报渲染和按群聊生成总结图片;
- 定时日报任务的查询、创建、修改、启停、删除、立即执行和执行记录;删除不可逆,Skill 要求先列出唯一任务并取得用户明确确认;
- 个人微信发送能力状态查询(`/wechat-personal/send-capability`);
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`;
- `query/*` 一组结构化 Query 端点:`messages`、`search`、`message-context`、`conversation-overview`、`voice-transcribe`;
- 自身版本查询(`/skill/tracememo-reader`),用于判断是否需要更新;
- Agent Hub 状态检查与已连接机器人发送测试。这里的发送接口是开发者/测试用途,不是实时机器人入口,也不会让 Reader Skill 自动监听微信消息。
注意这个 API 不只是只读的:`/report`、`/agent/send` 和 `/scheduled-reports*` 会写入状态或真的发出微信消息。
+32 -1
View File
@@ -1,5 +1,6 @@
---
name: tracememo-reader
version: 1.3.0
description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体,并管理定时日报任务。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
---
@@ -17,6 +18,35 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
- 不要把 Token 放到 URL、回答、日志、Skill 文件或仓库。
- 6131 是普通 Local HTTP API,不是 MCP Server;不要生成 `mcpServers` 配置。
## 版本自检(每次会话开始时执行一次)
这份 Skill 随 TraceMemo 一起更新,接口会随版本变化。本文件 frontmatter 里的 `version` 是它的唯一版本标识,服务端在 `/health` 回报当前版本。
1. 读取本文件 frontmatter 的 `version`。
2. 调用 `GET /health`,取返回的 `skill.version`。
3. 两者一致 → 正常继续。
4. 两者不一致(本文件更旧)→ **先停止,不要继续读取数据**,并原样告知用户:
> 本机 TraceMemo Reader Skill 是 {本地版本},而 TraceMemo 当前是 {服务端版本},接口契约可能已经过期。
> 请打开 TraceMemo → API Center → 快速接入 → 选择目标 Agent → 复制安装指令,把新指令发给我重新安装。
5. `/health` 没有返回 `skill.version`(说明 TraceMemo 版本较旧)→ 无法比对,正常继续,但要在回答中提醒用户升级 TraceMemo。
自检只做一次,不要每个任务都执行。**不要**因为版本不一致就自行猜测新接口的用法。
### 自助更新
用户同意更新时,不必让他手动复制安装指令,Agent 可以自己完成:
```bash
curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
"http://127.0.0.1:6131/api/v1/skill/tracememo-reader"
```
响应的 `markdown` 就是最新 SKILL.md 全文,`version` 是它的版本,`contentHash` 可用于核对写入结果。先取得用户同意,再用它覆盖本机这份 SKILL.md(连同 frontmatter 一起写),然后重新读取本文件,并告知用户已更新到哪个版本。
覆盖前先确认目标文件路径并留一份备份;**不要**改动本目录里的其他文件,也不要把 `markdown` 内容写进回答或日志。
## 每次任务前
1. 调用 `/health`,确认服务和数据库状态。
@@ -29,7 +59,8 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
| 方法 | 路径 | 用途 |
| ------ | ------------------------------------------------------- | ------------------------------------------------- |
| GET | `/health` | 健康和数据库状态 |
| GET | `/health` | 健康和数据库状态 + 当前 Skill 版本 |
| GET | `/skill/tracememo-reader` | 当前 SKILL.md 全文与版本号(自助更新用) |
| GET | `/current_time` | 本机时间与时区 |
| GET | `/contact` | 联系人/群聊列表;可传 `filter`、`type` |
| GET | `/chatroom` | 群聊列表;可传 `keyword` |
+1
View File
@@ -33,6 +33,7 @@
"typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:test",
"typecheck:test": "node scripts/typecheck-tests.cjs",
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
"check:skill-version": "node scripts/check-skill-version-drift.cjs",
"cp:env": "node scripts/ensure-env.cjs",
"prepare:env": "node scripts/ensure-env.cjs",
"prepare:ffmpeg:win": "node scripts/prepare-electron-runtime.cjs --platform win32 --arch x64",
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env node
/**
* 防漂移检查:Reader Skill 的版本号只有一个真源 —— SKILL.md frontmatter 的 `version`。
*
* 只要本次变更动了 SKILL.md 的内容,就必须同时提升 version,否则外部 Agent
* 无法通过 /health 上的 skill.version 发现自己手里的 Skill 已经过期,
* 会继续按旧契约调用接口(历史上真实发生过:文档改了两轮,版本号没动)。
*
* 比较基准依次尝试 SKILL_VERSION_BASE / origin/main / origin/develop / HEAD~1;
* 找不到基准(例如浅克隆)时只提示并跳过,不阻塞构建。
*/
const { execFileSync } = require('node:child_process')
const { readFileSync, existsSync } = require('node:fs')
const path = require('node:path')
const REQUESTED_BASE = 'SKILL_VERSION_BASE'
const SKILL_PATH = 'docs/skill/tracememo-reader/SKILL.md'
const SEMVER = /^\d+\.\d+\.\d+$/
function git(args) {
return execFileSync('git', args, {
cwd: process.cwd(),
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe']
}).trim()
}
function resolveBase() {
const candidates = []
if (process.env[REQUESTED_BASE]) candidates.push(process.env[REQUESTED_BASE])
candidates.push('origin/main', 'origin/develop', 'HEAD~1')
for (const candidate of candidates) {
try {
git(['rev-parse', '--verify', '--quiet', `${candidate}^{commit}`])
return candidate
} catch {
// 该基准不存在,继续尝试下一个
}
}
return null
}
function versionOf(markdown) {
if (!markdown) return null
const match = /^version:[ \t]*(\S+)[ \t]*$/m.exec(markdown)
return match ? match[1] : null
}
function skip(reason) {
console.log(`[skill-version] 跳过版本漂移检查:${reason}`)
process.exit(0)
}
function fail(message) {
console.error(`[skill-version] FAIL:${message}`)
process.exit(1)
}
const root = process.cwd()
const skillFile = path.join(root, SKILL_PATH)
if (!existsSync(skillFile)) fail(`找不到 ${SKILL_PATH}。`)
const current = readFileSync(skillFile, 'utf8')
const currentVersion = versionOf(current)
if (!currentVersion) {
fail(`${SKILL_PATH} 的 frontmatter 缺少 version 字段。外部 Agent 依赖它做版本自检。`)
}
if (!SEMVER.test(currentVersion)) {
fail(`${SKILL_PATH} 的 version "${currentVersion}" 不是 x.y.z 形式。`)
}
const base = resolveBase()
if (!base) skip('找不到可用的 git 比较基准(可能是浅克隆)。')
// 已提交的改动 + 工作区未提交的改动都要看,否则本地预检会漏掉。
let changedFiles = new Set()
try {
for (const args of [
['diff', '--name-only', `${base}...HEAD`],
['diff', '--name-only', 'HEAD']
]) {
for (const file of git(args).split('\n')) if (file) changedFiles.add(file)
}
} catch (error) {
skip(`无法计算与 ${base} 的差异(${error.message.split('\n')[0]})。`)
}
if (!changedFiles.has(SKILL_PATH)) {
console.log(`[skill-version] OK:与 ${base} 相比 ${SKILL_PATH} 未变更,无需提升版本。`)
process.exit(0)
}
let previous = null
try {
previous = git(['show', `${base}:${SKILL_PATH}`])
} catch {
previous = null
}
const previousVersion = versionOf(previous)
if (previousVersion === null) {
console.log(
`[skill-version] OK:${base} 上没有可比较的 version,当前为 ${currentVersion}。`
)
process.exit(0)
}
if (previousVersion === currentVersion) {
fail(
`${SKILL_PATH} 内容已变更,但 version 仍是 ${currentVersion}(基准 ${base})。\n` +
' 外部 Agent 只能通过 version 判断自己是否过期,请提升该版本号(例如 1.3.0 → 1.4.0)。'
)
}
console.log(
`[skill-version] OK:版本随文档一起提升 ${previousVersion} → ${currentVersion}(基准 ${base})。`
)
@@ -67,4 +67,34 @@ assert.match(
/https:\/\/example\.com\/skill/
)
// source.version 曾经是死字段:传进来却被模板丢掉,于是安装指令不携带任何版本信息。
for (const target of ['codex', 'claude-code', 'openclaw', 'generic']) {
const text = buildSkillInstallInstruction({
target,
source: { ...local, version: '9.9.9' },
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
})
assert.match(text, /Skill 版本是 9\.9\.9/, `${target} 指令应携带 source.version`)
assert.doesNotMatch(text, /v1\.0/, `${target} 不应残留 fixture 的旧版本号`)
assert.match(text, /覆盖/, `${target} 指令应说明用新版本覆盖旧版本`)
}
// 指令要同时提醒 Agent 做版本自检,否则更新机制又只能靠人记得。
const selfCheckText = buildSkillInstallInstruction({
target: 'codex',
source: local,
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
})
assert.match(selfCheckText, /版本自检/)
assert.match(selfCheckText, /skill\.version/)
// 没有版本号时不编造:不输出版本段,其余指令保持可用。
const withoutVersion = buildSkillInstallInstruction({
target: 'codex',
source: { type: 'local', directoryPath: 'C:/skill/tracememo-reader', skillPath: 'x' },
apiBaseUrl: { host: '127.0.0.1', port: 6131 }
})
assert.doesNotMatch(withoutVersion, /Skill 版本是/)
assert.match(withoutVersion, /TRACEMEMO_API_TOKEN/)
console.log('skill install instruction tests passed')
+25
View File
@@ -28,6 +28,7 @@ import type {
import { agentHubService } from './services/agent-hub-service'
import { safeError, safeLog, safeWarn } from './safe-log'
import { apiTokenStore } from './api-token-store'
import { READER_SKILL_NAME, skillResourceService } from './services/skill-resource-service'
import { HttpMediaError, readImageMedia, type HttpImageResult } from './http-media-service'
import { LocalQueryApiService } from './services/local-query-api-service'
import { automationRuleStore, AutomationRulePersistenceError } from './services/automation-rule-store'
@@ -332,15 +333,39 @@ function getApplicationVersion(): string {
const routes: Record<string, RouteHandler> = {
'/api/v1/health': withMethods(['GET'], ({ res }) => {
const skill = skillResourceService.getStatus()
sendJson(res, 200, {
ok: true,
ready: isReady(),
service: 'TraceMemo Reader',
version: getApplicationVersion(),
skill: {
name: skill.name || READER_SKILL_NAME,
version: skill.version || null,
available: skill.available
},
timestamp: new Date().toISOString()
})
}),
// 外部 Agent 的版本自检与自助更新入口:返回当前 SKILL.md 全文,不返回本地路径。
'/api/v1/skill/tracememo-reader': withMethods(['GET'], ({ res }) => {
const document = skillResourceService.getDocument()
if (!document) {
return sendJson(res, 503, {
error: 'skill_unavailable',
message: '未找到本机 TraceMemo Reader Skill 文件,请确认应用安装是否完整。'
})
}
sendJson(res, 200, {
name: document.name,
version: document.version || null,
contentHash: document.contentHash,
modifiedAt: document.modifiedAt,
markdown: document.markdown
})
}),
'/api/v1/current_time': withMethods(['GET'], ({ res }) => {
const now = new Date()
sendJson(res, 200, {
+91 -29
View File
@@ -94,6 +94,7 @@ import type { SaveImageKeyRequest, TestImageDecryptionRequest } from '../shared/
import {
loadSettings,
saveSettings,
updateSettings,
getSettingsPath,
AppSettings,
validateDbRoot
@@ -139,7 +140,8 @@ import {
resolveHelperPath,
resolveTargetRooms,
type MsgInsertScopeInput,
type MsgInsertSwitchName
type MsgInsertSwitchName,
type MsgInsertSwitchesSnapshot
} from './services/msg-insert-switch-service'
import { GroupStatsService } from './services/group-stats-service'
import {
@@ -181,6 +183,39 @@ function resolveMsgInsertScopeInput(): MsgInsertScopeInput | null {
}
}
/**
* 组装「微信消息插入开关」的快照。**纯读**:不写微信库、不触发 DDL。
*
* 抽出来是为了让 GET 与「运行期刷新」共用同一份展示口径(含退群提示这个本地事件开关),
* 避免两处各拼一遍导致漂移。
*/
function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
const scope = resolveMsgInsertScopeInput()
if (scope) {
const snapshot = readMsgInsertSwitches(scope)
/* 退群提示的开关状态来自本地设置(事件驱动,不装规则),
* 不是微信库里的 _tm_config。 */
snapshot.switches.group_exit_notice = eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled(),
exitNoticeGroupCount()
)
return snapshot
}
return {
success: false,
switches: {
recall_notice: emptyMsgInsertStatus('recall_notice'),
group_exit_notice: eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled()
)
},
helperAvailable: resolveHelperPath() !== null,
detail: '微信数据库尚未连接'
}
}
/**
* 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。
*
@@ -771,8 +806,27 @@ function createWindow(): void {
mainWindow.show()
})
/** 隐藏到托盘。关闭弹窗的"最小化"与"已记住托盘"两条路径共用同一套副作用。 */
const minimizeToTray = (): void => {
setupTray()
mainWindow.hide()
if (process.platform === 'darwin') app.dock?.hide()
}
mainWindow.on('close', (event) => {
if (isQuitting || appShutdownRequested) return
// 用户在关闭弹窗里勾过"记住我的选择"就照做,不再每次都弹。
const remembered = loadSettings().closeAction
if (remembered === 'quit') {
isQuitting = true
app.quit()
return
}
if (remembered === 'tray') {
event.preventDefault()
minimizeToTray()
return
}
event.preventDefault()
if (closePromptInFlight) return
closePromptInFlight = true
@@ -785,16 +839,19 @@ function createWindow(): void {
buttons: ['最小化到系统托盘', '关闭进程', '取消'],
defaultId: 0,
cancelId: 2,
// 勾了就记住这次的选择,之后不再弹窗;设置页里随时可以改回来。
checkboxLabel: '记住我的选择,下次不再询问',
checkboxChecked: false,
noLink: true
})
.then(({ response }) => {
.then(({ response, checkboxChecked }) => {
if (response === 0) {
setupTray()
mainWindow.hide()
if (process.platform === 'darwin') app.dock?.hide()
if (checkboxChecked) updateSettings({ closeAction: 'tray' })
minimizeToTray()
return
}
if (response === 1) {
if (checkboxChecked) updateSettings({ closeAction: 'quit' })
isQuitting = true
app.quit()
}
@@ -2029,32 +2086,37 @@ app.whenReady().then(async () => {
*/
ipcMain.handle('automation:getMsgInsertSwitches', () => {
/* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。
* 规则补齐只发生在「用户打开开关」(helper 的 apply 内部先 ensure)与
* 「应用启动且持久化开关为开」这两个时机。 */
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。 */
return buildMsgInsertSwitchesSnapshot()
})
/**
* 微信消息插入开关 —— **运行期刷新**(允许在分片集合变化时补一次规则)。
*
* 与 GET 的分工:GET 必须纯读;但"微信运行期间新建了 message_N.db"这种情况需要补规则,
* 否则新分片里的会话永远显示未就绪 —— 而规则补齐只在**启动时**跑过一次。
* 用户侧看到的表现就是"计数变了,但分子追不上分母"。
*
* 成本控制:分片清单指纹没变 → 只做纯读立刻返回;变了才 spawn 一次 helper。
*/
ipcMain.handle('automation:refreshMsgInsertSwitches', async () => {
const scope = resolveMsgInsertScopeInput()
if (scope) {
const snapshot = readMsgInsertSwitches(scope)
/* 退群提示的开关状态来自本地设置(事件驱动,不装规则),
* 不是微信库里的 _tm_config。 */
snapshot.switches.group_exit_notice = eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled(),
exitNoticeGroupCount()
)
return snapshot
}
return {
success: false,
switches: {
recall_notice: emptyMsgInsertStatus('recall_notice'),
group_exit_notice: eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled()
)
},
helperAvailable: resolveHelperPath() !== null,
detail: '微信数据库尚未连接'
const client = chat.getChatDb()?.getWcdb4Client()
if (scope && client) {
try {
const signature = client
.listMessageShardPaths()
.map((item) => path.basename(item))
.join(',')
if (signature !== lastMsgInsertReconciledShards) {
lastMsgInsertReconciledShards = signature
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
}
} catch (error) {
console.warn('[MsgInsert] 运行期补齐失败:', error)
}
}
return buildMsgInsertSwitchesSnapshot()
})
/**
* 微信消息插入开关 —— 写入。
+7 -2
View File
@@ -5,8 +5,13 @@ import { join } from 'path'
export function isPackagedRuntime(): boolean {
if (app.isPackaged) return true
// 非 Electron 进程(例如单元/集成测试)里 process.resourcesPath 不存在,
// 此时 join 会抛错。没有 resources 目录就必然不是打包运行时。
const resourcesPath = process.resourcesPath
if (!resourcesPath) return false
return (
existsSync(join(process.resourcesPath, 'app.asar')) &&
existsSync(join(process.resourcesPath, 'app-update.yml'))
existsSync(join(resourcesPath, 'app.asar')) &&
existsSync(join(resourcesPath, 'app-update.yml'))
)
}
+37 -1
View File
@@ -148,12 +148,48 @@ export function resolveInboundRoute(text: string): InboundRoute {
/** 查询大脑不可用时的统一文案(不暴露 stack / provider raw response / 内部 id)。 */
export const QUERY_AGENT_UNAVAILABLE_TEXT = '当前 AI 查询服务暂时不可用,请稍后再试。'
/**
* 桌面 UI 的 inline citation(`[E6]`)在微信里**没有落点** ——
* 点不开、也没有证据卡可以对照,留在正文里纯属噪音。下发前一律剥离。
*
* 只吃行内空格(`[ \t]`)而不是 `\s`:引用可能独占一行,用 `\s*` 会把上一行的换行
* 一起吞掉,把两行粘成一行。
*/
const INLINE_CITATION_PATTERN = /[ \t]*\[E\d+\]/g
function stripInlineCitations(text: string): string {
return text.replace(INLINE_CITATION_PATTERN, '').replace(/[ \t]+$/gm, '')
}
/**
* 微信气泡的换行规则:**单个 `\n` 会被压成空格,只有空行(`\n\n`)才真的换行**。
*
* 所以列表项之间必须用**空行**分隔:单换行等于白发,多条 bullet 会被挤成一整段。
*
* 顺带把 Markdown 列表标记(`-` / `*` / `+`)统一成 `• `:下游
* `markdownToPlainText()` 虽然也做这一步,但它只保证 `• `、不保证前面有空行,
* 在这里先接住才能拿到正确行距。
*/
export function formatWechatReplyText(content: string): string {
return content
.replace(/\r\n?/g, '\n')
.replace(/^[ \t]*[-*+][ \t]+/gm, '• ')
.replace(/[ \t]*•[ \t]*/g, '\n\n• ')
.replace(/[ \t]+(?=\d+[.、][ \t])/g, '\n\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
/**
* 把 Query Agent 结果映射成**微信文字回复**。
* 只输出用户可读文本;Tool trace / temporalBasis / Evidence / 诊断字段一律不下发。
*/
export function queryAgentReplyText(result: AskWechatQueryResult): string {
if (result.status === 'answered') return result.answer
if (result.status === 'answered') {
const text = stripInlineCitations(result.answer).trim()
// 极端情况(整段只有引用编号)宁可原样下发,也不能发一条空消息出去。
return text || result.answer.trim()
}
if (result.status === 'provider_unavailable' || result.status === 'error') return result.message
// Agent Hub 没有 Legacy runner,不会产生 legacy 结果;真出现时按服务不可用处理,不暴露内部结构。
return QUERY_AGENT_UNAVAILABLE_TEXT
+3 -11
View File
@@ -17,6 +17,7 @@ import { QueryAgentService } from './query-agent-service'
import { AskWechatService } from './ask-wechat-service'
import {
QUERY_AGENT_UNAVAILABLE_TEXT,
formatWechatReplyText,
queryAgentReplyText,
resolveInboundRoute,
type GroupMemberChatIntent,
@@ -700,7 +701,7 @@ export class AgentHubService {
{ requestId: `agent-hub-${Date.now()}-${this.nextLogId}`, text },
conversationKey
)
await this.sendToConversation(conversation, this.formatAIReply(queryAgentReplyText(result)))
await this.sendToConversation(conversation, formatWechatReplyText(queryAgentReplyText(result)))
this.addLog('agent-hub', 'info', `查询回答已发送(${result.status})`)
} catch (error) {
this.addLog('agent-hub', 'error', `查询处理失败:${this.errorMessage(error)}`)
@@ -834,7 +835,7 @@ export class AgentHubService {
}
await this.sendToConversation(
conversation,
this.formatAIReply(
formatWechatReplyText(
`${displayName}在“${group.m_nsNickName}”的发言总结(共 ${messages.length} 条):\n\n${summary.data.trim().slice(0, 3500)}`
)
)
@@ -850,15 +851,6 @@ export class AgentHubService {
return `[${label}]`
}
private formatAIReply(content: string): string {
return content
.replace(/\r\n?/g, '\n')
.replace(/[ \t]*•[ \t]*/g, '\n• ')
.replace(/[ \t]+(?=\d+[.、][ \t])/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
private async generateAndSendReport(
conversation: AgentHubTarget,
intent: GroupReportIntent
+131 -12
View File
@@ -64,8 +64,11 @@ const kinds: QueryMessageType[] = ['text', 'image', 'voice', 'video', 'file', 'l
*
* 一次完整 pass 的耗时以分钟计,远超任何交互预算。所以这个预算只用来兜住「已经很接近追平」
* 的情况:追不上就按当前覆盖如实回答并让后台继续追,而不是把查询卡在索引上。
*
* 2 秒连"索引已经快跑完"都等不到,就会出现**索引正在追、查询却拿旧覆盖下结论**的矛盾表现。
* 15 秒仍远小于一次完整 pass,不会把查询卡住,但足以覆盖"追平在即"的绝大多数情况。
*/
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 2000
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 15000
/**
* 两次由查询触发的追赶之间的最小间隔,避免每个 Query 都重跑一遍索引。
@@ -120,17 +123,26 @@ function formatLocalMinute(ms: number): string {
function buildIndexCoverage(
indexLatestAt: number | null,
sourceLatestAt: number | null,
covered: boolean
covered: boolean,
directReadApplied = false
): QueryIndexCoverage | undefined {
if (indexLatestAt === null) return undefined
const indexLabel = formatLocalMinute(indexLatestAt)
return {
// 注意:直读补齐**不**把 covered 改成 true。
//
// 直读只扫了 `indexLatestAt` 之后那一段(权威源、全量),更早的部分仍然依赖索引;
// 而 `indexLatestAt` 是**全局**水位,不代表"这个会话在更早区间被索引得多完整"。
// 所以这里保持诚实:覆盖结论不变,只在 summary 里说明"这之后已用直读补齐"。
// 一旦把 covered 改成 true,prompt 就会允许模型在 0 结果时下"没有",那是错误的否定。
covered,
indexLatestAtLabel: indexLabel,
...(sourceLatestAt !== null ? { sourceLatestAtLabel: formatLocalMinute(sourceLatestAt) } : {}),
summary: covered
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
summary: directReadApplied
? `关键词索引只更新到 ${indexLabel};这之后的聊天已改用直读原始记录补齐,本会话该区间的结果来自直读。`
: covered
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
}
}
@@ -544,6 +556,7 @@ export class LocalQueryApiService {
let found: Awaited<ReturnType<LocalQueryApiService['probe']>>
let freshness: { resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }
let freshnessMs = 0
let directFallback: { evidence: Map<string, QueryEvidenceItem>; scanned: number } | undefined
try {
found = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId)
probeMs.push(...found.probeMs)
@@ -562,13 +575,38 @@ export class LocalQueryApiService {
enrichmentMs += reProbe.enrichmentMs
found = reProbe
}
// 直读兜底必须在这个 `beginInteractiveQuery` 窗口内跑。
//
// 这个窗口的作用就是让后台索引让路;一旦 `endInteractiveQuery()` 放开,
// 正在追赶的索引会立刻进来抢 WCDB,把直读拖成几十秒。
const soleId = conversationIds && conversationIds.length === 1 ? conversationIds[0] : undefined
const soleContact = soleId ? contactByMd5.get(soleId) : undefined
if (!indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt) && soleContact) {
// 索引不可信、而范围又恰好是一个会话 → 用 WCDB 直读把索引落后的那一段补上。
// 微信机器人问"某个群最近聊了 X"时,这正是"索引没追完就拿不到东西"的解药。
directFallback = await this.directReadKeywordFallback({
conversationId: soleContact.md5,
contact: soleContact,
probes,
fromMs: found.indexLatestAt,
range,
limit
})
}
} finally {
this.knowledge.endInteractiveQuery()
}
const requestedEnd = rangeEndMs(range, this.nowProvider().getTime())
const covered = indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt)
const indexCoverage = buildIndexCoverage(found.indexLatestAt, found.sourceLatestAt, covered)
const evidence = new Map(found.evidence)
if (directFallback) for (const [key, item] of directFallback.evidence) evidence.set(key, item)
const indexCoverage = buildIndexCoverage(
found.indexLatestAt,
found.sourceLatestAt,
covered,
directFallback !== undefined
)
// 图片文字索引是**独立覆盖维度**:文字索引再完整也不代表图片里的文字搜得到。
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
const timings: QuerySearchTimings = {
@@ -586,8 +624,8 @@ export class LocalQueryApiService {
resolvedTimeRange: range,
coverage: { state: this.searchCoverage(found, requestedEnd) },
probeCount: probes.length,
evidenceCount: found.evidence.size,
evidence: Array.from(found.evidence.values()).slice(0, limit),
evidenceCount: evidence.size,
evidence: Array.from(evidence.values()).slice(0, limit),
scope: corpus.scope,
indexLatestAt: found.indexLatestAt,
sourceLatestAt: found.sourceLatestAt,
@@ -598,6 +636,80 @@ export class LocalQueryApiService {
}
}
/**
* 索引不可信时的**直读兜底** —— 只在"范围恰好是一个会话"时启用。
*
* `search_messages` 是四个 Query Tool 里唯一依赖派生索引的:索引在追赶期间它给不出新消息,
* 而 WCDB 才是权威源、永远最新。跨会话直读不可行(要遍历上千个会话,实测大会话全量读一次
* 15s 以上),但**单个会话**成本可控 —— 所以只在这一种形状下降级,其余情况仍如实标 partial。
*
* 只扫索引**没覆盖**的那一段(`fromMs` 之后):已经进索引的部分仍以索引结果为准,不重复劳动。
* 匹配口径与索引保持一致:正文 + 语音转写 + 图片 OCR 派生文本。
*/
private async directReadKeywordFallback(input: {
conversationId: string
contact: FormattedContact
probes: string[]
/** 索引水位(epoch **毫秒**);null 表示索引还没建立过,那就从头扫。 */
fromMs: number | null
range: ResolvedTimeRange
limit: number
}): Promise<{ evidence: Map<string, QueryEvidenceItem>; scanned: number }> {
// freshness 是**毫秒**口径,而 WCDB 读消息的时间窗是**秒**口径。
// 显式换算,不让两种单位在同一个表达式里静默错位(这个坑历史上踩过)。
const coveredSeconds = input.fromMs === null ? undefined : Math.floor(input.fromMs / 1000)
const startTime =
coveredSeconds === undefined
? input.range.startTime
: input.range.startTime === undefined
? coveredSeconds
: Math.max(input.range.startTime, coveredSeconds)
const raw = await listMessagesAsync(input.conversationId, startTime, input.range.endTime)
const needles = input.probes
.map((value) => value.trim().toLowerCase())
.filter(Boolean)
const evidence = new Map<string, QueryEvidenceItem>()
for (const message of raw) {
if (evidence.size >= input.limit) break
const kind = kindOf(message)
const ocr =
kind === 'image' ? this.imageOcrEntry?.(input.conversationId, sourceMessageId(message)) : undefined
const haystack = [
message.content,
message.voiceTranscript,
ocr && ocr.state === 'indexed' ? ocr.text : ''
]
.filter(Boolean)
.join('\n')
.toLowerCase()
if (!haystack || !needles.some((needle) => haystack.includes(needle))) continue
const item = toQueryMessage(
input.conversationId,
message,
input.contact,
ocr,
this.voiceSnapshot(message)
)
// key 必须与索引路径一致(`会话:归一化消息 id`):两条路径可能命中同一条消息,
// 合并时要能去重。`message.id` 可能带 `local:` 装饰,所以走归一化。
const normalizedId = normalizeMessageIdentity(input.conversationId, message.id)?.messageId
if (!normalizedId) continue
evidence.set(`${input.conversationId}:${normalizedId}`, {
messageRef: item.messageRef,
timestamp: item.timestamp,
sender: item.sender,
sourceKind: item.sourceKind,
text: toEvidenceDisplayText(item.text ?? ''),
...(item.derivedSource ? { derivedSource: item.derivedSource } : {}),
...(item.imageOcrText ? { imageOcrText: item.imageOcrText } : {}),
conversationName: contactView(input.contact).displayName,
conversationType: input.contact.type
})
}
return { evidence, scanned: raw.length }
}
/** 逐 probe 检索并合并去重;同时记录派生索引的覆盖口径与真实耗时分解。 */
private async probe(
probes: string[],
@@ -721,12 +833,19 @@ export class LocalQueryApiService {
if (lag <= worthThreshold) return { resynced: false, catchUp: 'skipped' }
const request = this.knowledge.requestCatchUp(QUERY_CATCH_UP_MIN_INTERVAL_MS)
if (!request.triggered) {
// 已经在跑 → 复用;刚触发过 → 节流。两种都不阻塞本次查询,后台继续追。
return { resynced: false, catchUp: request.inProgress ? 'reused' : 'skipped' }
// 只有在"刚刚触发过、节流窗口内"时才不等 —— 那种情况再等也没意义。
if (!request.triggered && !request.inProgress) {
return { resynced: false, catchUp: 'skipped' }
}
// 本次触发、以及**正在跑(复用)**两种都要等。
//
// 复用场景若直接返回旧快照,就会出现**索引明明在追、查询却拿旧覆盖下结论**的表现。
// 等待后统一 `resynced: true`:即使没等到追平,索引也可能前进了一段,值得按新覆盖重查一次。
const completed = await this.knowledge.waitForIndexingComplete(QUERY_FRESHNESS_WAIT_BUDGET_MS)
return { resynced: true, catchUp: completed ? 'completed' : 'pending' }
return {
resynced: true,
catchUp: completed ? 'completed' : request.triggered ? 'pending' : 'reused'
}
}
/**
+2
View File
@@ -299,6 +299,8 @@ const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使
- indexCoverage.covered 为 false 时,说明这段时间还没进索引:此时即使结果为 0 也只能说"索引尚未覆盖这段时间,暂时无法确认",**绝不能**说成"没有"。必须如实引用结论里的索引更新时间。
- 已经检索到 Evidence 时,只有当这个覆盖边界真的会影响结论时才补一句说明,不要机械附加警告。
- 只有 coverage.state 为 complete(indexCoverage.covered 为 true)且结果为 0,才可以下"没有找到"的结论。不要自己把 partial 说成 complete。
- 结论句说"暂时无法确认"时**不能只停在那里**:必须同时给出可执行的下一步 —— 明确告诉用户「指定某个群或联系人、再加上时间再问一次」,这类精确查询读的是原始聊天记录,**不受索引进度影响**。索引在后台追赶可以如实说明,但那是背景,不是结论的终点。
- 结论句若说"已改用直读原始记录补齐",表示这段**已经查过原始记录了**:直接按检索结果回答即可,**不要**再让用户换问法,也不要再说"暂时无法确认"。
图片文字索引:search_messages 的 imageOcrCoverage 是**独立于文字索引**的覆盖维度,只针对“图片里的文字”(截图、报价图、公告截图、海报)。规则:
- 文字消息索引完整**不代表**图片里的文字搜得到。不要把这两个维度混着说。
- 问题涉及图片里的文字、而 imageOcrCoverage.state 不是 complete 时:即使图片证据为 0,也**绝不能**回答“没有”或“没找到”。必须如实引用 imageOcrCoverage.summary,说明图片文字索引尚未完成、当前无法确认全部历史图片。
+25 -4
View File
@@ -613,7 +613,10 @@ export class ScheduledReportService {
payload?.severity || notification.severity,
payload?.title || notification.title,
payload?.message || notification.message,
payload?.suggestedAction
payload?.suggestedAction,
// 用**失败发生时刻**而不是发送时刻:pending 通知会跨天补发,
// 同一批里几条文案完全相同的失败,只有这个时间能区分开。
notification.createdAt
)
})
if (result.success) {
@@ -679,17 +682,20 @@ export class ScheduledReportService {
severity: ScheduledReportNotificationSeverity,
title: string,
message: string,
suggestedAction?: string
suggestedAction?: string,
occurredAt?: string
): string {
const icon = severity === 'error' ? '❌' : severity === 'warning' ? '⚠️' : '✅'
const stamp = formatNotificationTimestamp(occurredAt)
return [
`${icon} ${ruleName}`,
`${icon} ${ruleName}${stamp ? ` · ${stamp}` : ''}`,
title,
message,
suggestedAction ? `建议:${suggestedAction}` : ''
]
.filter(Boolean)
.join('\n')
// 必须用**空行**分隔:微信会把单个换行压成空格,否则整条通知会连成一行长句。
.join('\n\n')
}
// ---------------------------------------------------------------------------
@@ -996,6 +1002,21 @@ export class ScheduledReportService {
}
}
/**
* 微信通知里的时间戳(「10月13日 16:28」)。
*
* 必须精确到分钟而不是只到「几月几日」:pending 通知会跨天补发,同一批里
* 几条文案完全相同的失败(同规则、同原因),只到日仍然分不清谁是谁。
* 时间非法时返回空串,调用方据此去掉整段前缀。
*/
const formatNotificationTimestamp = (iso?: string): string => {
if (!iso) return ''
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return ''
const pad = (value: number): string => String(value).padStart(2, '0')
return `${date.getMonth() + 1}月${date.getDate()}日 ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
const asArray = <T>(value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : [])
const executionStatuses = new Set<ScheduledReportExecution['status']>([
+20 -1
View File
@@ -20,6 +20,8 @@ function redirectLegacyWeChatFilesToXwechat(candidate: string): string {
return candidate
}
export type CloseAction = 'ask' | 'tray' | 'quit'
export interface AppSettings {
dbRoot: string
apiEnabled: boolean
@@ -47,6 +49,17 @@ export interface AppSettings {
* 不在用户界面暴露实验性名称)。
*/
queryAgentEnabled: boolean
/**
* 关闭主窗口时的行为。
*
* - `ask`:每次弹窗询问(默认,保持既有行为)
* - `tray`:直接最小化到系统托盘,应用继续在后台跑
* - `quit`:直接退出整个进程
*
* 只有用户在关闭弹窗里勾了"记住我的选择"才会离开 `ask`;
* 设置页随时可以改回来。
*/
closeAction: CloseAction
}
function getDefaultDbRoot(): string {
@@ -131,7 +144,8 @@ const DEFAULT_SETTINGS: AppSettings = {
ttsModel: 's2.1-pro-free',
windowsWechatPort: '',
reportImagePostfixText: '今日日报',
queryAgentEnabled: true
queryAgentEnabled: true,
closeAction: 'ask'
}
const SETTINGS_FILE = path.join(
@@ -176,6 +190,11 @@ export function loadSettings(): AppSettings {
if (cache.dbRoot) {
cache.dbRoot = redirectLegacyWeChatFilesToXwechat(cache.dbRoot)
}
// 关闭行为可能来自旧版本或手改过的 settings.json —— 非法值一律收敛回 `ask`。
// 放任非法值会造成最难排查的一种表现:点关闭窗口什么也不发生。
if (cache.closeAction !== 'ask' && cache.closeAction !== 'tray' && cache.closeAction !== 'quit') {
cache.closeAction = 'ask'
}
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
+138 -18
View File
@@ -1,5 +1,6 @@
import { createHash } from 'crypto'
import { app, shell } from 'electron'
import { existsSync, promises as fs } from 'fs'
import { existsSync, readFileSync, promises as fs, statSync } from 'fs'
import { dirname, join } from 'path'
import { isPackagedRuntime } from '../runtime-mode'
@@ -8,7 +9,8 @@ const SKILL_RELATIVE_PATHS = [
join('skill', 'wechatexplorer-reader', 'SKILL.md')
]
const GITHUB_URL = 'https://github.com/Wxw-Gu/TraceMemo/tree/main/docs/skill/tracememo-reader'
const SKILL_VERSION = 'v1.2'
export const READER_SKILL_NAME = 'tracememo-reader'
type SkillResourceSource = 'development' | 'bundled'
@@ -27,7 +29,9 @@ interface SkillCandidate {
export interface SkillResourceStatus {
available: boolean
name?: string
version?: string
contentHash?: string
filePath?: string
directoryPath?: string
source: SkillResourceSource
@@ -35,6 +39,27 @@ export interface SkillResourceStatus {
error?: string
}
export interface SkillDocument {
name: string
version?: string
contentHash: string
modifiedAt: string
markdown: string
filePath: string
}
export interface SkillFrontmatter {
name?: string
version?: string
}
interface SkillDocumentCacheEntry {
filePath: string
mtimeMs: number
size: number
document: SkillDocument
}
function currentEnvironment(): SkillPathEnvironment {
return {
appPath: app.getAppPath(),
@@ -54,6 +79,81 @@ function uniqueCandidates(candidates: SkillCandidate[]): SkillCandidate[] {
})
}
/**
* 版本号只认 SKILL.md frontmatter 的 `version`,不再维护源码常量:
* 常量与文档分离必然漂移,曾经出现过文档改了两轮而版本号纹丝不动的情况。
*/
export function parseSkillFrontmatter(content: string): SkillFrontmatter {
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content)
if (!match) return {}
const block = match[1]
if (!block) return {}
const frontmatter: SkillFrontmatter = {}
for (const rawLine of block.split(/\r?\n/)) {
const line = rawLine.trim()
if (!line || line.startsWith('#')) continue
const separator = line.indexOf(':')
if (separator <= 0) continue
const key = line.slice(0, separator).trim().toLowerCase()
const value = line
.slice(separator + 1)
.trim()
.replace(/^["']/, '')
.replace(/["']$/, '')
if (!value) continue
if (key === 'name') frontmatter.name = value
else if (key === 'version') frontmatter.version = value
}
return frontmatter
}
function hashSkillContent(content: string): string {
return createHash('sha256').update(content, 'utf8').digest('hex')
}
let cachedDocument: SkillDocumentCacheEntry | null = null
/**
* 同步读取 Skill 文档。`/health` 属于高频接口,因此按 mtime + size 缓存,
* 文件被替换(版本升级)后缓存自动失效。
*/
export function readSkillDocument(filePath: string): SkillDocument | null {
try {
const stats = statSync(filePath)
if (
cachedDocument &&
cachedDocument.filePath === filePath &&
cachedDocument.mtimeMs === stats.mtimeMs &&
cachedDocument.size === stats.size
) {
return cachedDocument.document
}
const markdown = readFileSync(filePath, 'utf-8')
const frontmatter = parseSkillFrontmatter(markdown)
const document: SkillDocument = {
name: frontmatter.name || READER_SKILL_NAME,
contentHash: hashSkillContent(markdown),
modifiedAt: stats.mtime.toISOString(),
markdown,
filePath
}
if (frontmatter.version) document.version = frontmatter.version
cachedDocument = {
filePath,
mtimeMs: stats.mtimeMs,
size: stats.size,
document
}
return document
} catch {
cachedDocument = null
return null
}
}
export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCandidate[] {
const runtime = environment || currentEnvironment()
const developmentPaths = SKILL_RELATIVE_PATHS.flatMap((relativePath) => [
@@ -82,26 +182,40 @@ export function getSkillCandidates(environment?: SkillPathEnvironment): SkillCan
export function resolveSkillResourceStatus(
environment?: SkillPathEnvironment
): SkillResourceStatus {
const candidates = getSkillCandidates(environment)
const resolved = candidates.find((candidate) => existsSync(candidate.path))
const filePath = resolved?.path || candidates[0].path
const source = resolved?.source || candidates[0].source
const directoryPath = dirname(filePath)
if (!resolved) {
return {
available: false,
source,
githubUrl: GITHUB_URL,
error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
let candidates: SkillCandidate[] = []
let source: SkillResourceSource = environment?.packaged ? 'bundled' : 'development'
try {
candidates = getSkillCandidates(environment)
const resolved = candidates.find((candidate) => existsSync(candidate.path))
if (resolved) {
const filePath = resolved.path
const status: SkillResourceStatus = {
available: true,
filePath,
directoryPath: dirname(filePath),
source: resolved.source,
githubUrl: GITHUB_URL
}
const document = readSkillDocument(filePath)
if (document) {
status.name = document.name
status.contentHash = document.contentHash
if (document.version) status.version = document.version
}
return status
}
const fallback = candidates[0]
if (fallback) source = fallback.source
} catch {
// 环境探测失败(例如非 Electron 进程)时退化成“不可用”:
// /health 是外部 Agent 的自检入口,不能因为 Skill 读不到就整条挂掉。
}
return {
available: true,
version: SKILL_VERSION,
filePath,
directoryPath,
available: false,
source,
githubUrl: GITHUB_URL
githubUrl: GITHUB_URL,
error: `未找到 TraceMemo Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
}
}
@@ -112,6 +226,12 @@ function getStatus(): SkillResourceStatus {
export const skillResourceService = {
getStatus,
getDocument(): SkillDocument | null {
const status = this.getStatus()
if (!status.available || !status.filePath) return null
return readSkillDocument(status.filePath)
},
async read(): Promise<{ success: boolean; content?: string; error?: string }> {
const status = this.getStatus()
if (!status.available || !status.filePath) return { success: false, error: status.error }
+5
View File
@@ -338,6 +338,7 @@ declare global {
* 功能真的生效(规则可能没装齐),界面不能只看前者。
*/
getMsgInsertSwitches: () => Promise<MsgInsertSwitchesSnapshot>
refreshMsgInsertSwitches: () => Promise<MsgInsertSwitchesSnapshot>
/**
* 微信消息插入开关:打开 / 关闭。
*
@@ -561,6 +562,7 @@ declare global {
appearanceTheme: 'system' | 'light' | 'dark'
compactMode: boolean
showStartupProgress: boolean
closeAction: 'ask' | 'tray' | 'quit'
ttsSelectedVoiceId: string
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
windowsWechatPort: string
@@ -602,6 +604,7 @@ declare global {
appearanceTheme: 'system' | 'light' | 'dark'
compactMode: boolean
showStartupProgress: boolean
closeAction: 'ask' | 'tray' | 'quit'
ttsSelectedVoiceId: string
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
windowsWechatPort: string
@@ -626,6 +629,7 @@ declare global {
appearanceTheme: 'system' | 'light' | 'dark'
compactMode: boolean
showStartupProgress: boolean
closeAction: 'ask' | 'tray' | 'quit'
ttsSelectedVoiceId: string
ttsModel: import('../shared/text-to-speech').TextToSpeechModel
windowsWechatPort: string
@@ -648,6 +652,7 @@ declare global {
appearanceTheme: 'system' | 'light' | 'dark'
compactMode: boolean
showStartupProgress: boolean
closeAction: 'ask' | 'tray' | 'quit'
windowsWechatPort: string
imageXorKey: string
imageAesKey: string
+3
View File
@@ -235,6 +235,9 @@ const api = {
*/
getMsgInsertSwitches: (): Promise<MsgInsertSwitchesSnapshot> =>
ipcRenderer.invoke('automation:getMsgInsertSwitches'),
/** 运行期刷新:允许在消息分片集合变化时补一次规则,再返回最新状态。 */
refreshMsgInsertSwitches: (): Promise<MsgInsertSwitchesSnapshot> =>
ipcRenderer.invoke('automation:refreshMsgInsertSwitches'),
/**
* 微信消息插入开关 —— 打开 / 关闭。
*
@@ -7,13 +7,13 @@ function requestHost(host: string): string {
function opening(target: AgentInstallTarget): string {
switch (target) {
case 'codex':
return '请将本地目录中的 TraceMemo Reader Skill 安装到当前 Codex 项目或用户 Skill 目录:'
return '请将本地目录中的 TraceMemo Reader Skill 安装或更新到当前 Codex 项目或用户 Skill 目录:'
case 'claude-code':
return '请安装以下本地 TraceMemo Reader Skill,并按照 SKILL.md 调用本地 HTTP API:'
return '请安装或更新以下本地 TraceMemo Reader Skill,并按照 SKILL.md 调用本地 HTTP API:'
case 'openclaw':
return '请将以下本地目录作为 TraceMemo Reader Skill 安装,并阅读其中的 SKILL.md:'
return '请将以下本地目录作为 TraceMemo Reader Skill 安装或更新,并阅读其中的 SKILL.md:'
default:
return '请读取并安装以下 TraceMemo Reader Skill:'
return '请读取并安装(或更新)以下 TraceMemo Reader Skill:'
}
}
@@ -32,8 +32,11 @@ export function buildSkillInstallInstruction({
const sourceText =
source.type === 'local'
? `${opening(target)}\n\n${source.directoryPath}\n\n请先阅读该目录中的 SKILL.md,然后调用:`
: `请从以下地址安装 TraceMemo Reader Skill:\n\n${source.installUrl}\n\n阅读 SKILL.md 后,调用:`
return `${sourceText}\n\n${healthUrl}\n\n先调用公开的 health 接口验证服务。然后请用户在 TraceMemo → API Center → API Token 中点击“复制 Token”,并把 Token 配置为 Agent 本机环境变量 TRACEMEMO_API_TOKEN。读取联系人、会话或聊天记录时,必须发送 Authorization: Bearer $TRACEMEMO_API_TOKEN。若旧配置尚未升级,可兼容读取 WECHATEXPLORER_API_TOKEN,但新配置必须优先使用 TRACEMEMO_API_TOKEN。此服务是 Local HTTP API,不是 MCP Server。安装完成后告诉我验证结果。`
: `请安装或更新 TraceMemo Reader Skill,来源:\n\n${source.installUrl}\n\n阅读 SKILL.md 后,调用:`
const versionNote = source.version
? `\n\n这一份的 Skill 版本是 ${source.version}。如果目标位置已经有旧版本,请用这一份覆盖;安装完成后记住该版本号,之后每次会话开始时按 SKILL.md 的「版本自检」与 health 返回的 skill.version 比对,不一致就提醒用户重新安装。`
: ''
return `${sourceText}\n\n${healthUrl}${versionNote}\n\n先调用公开的 health 接口验证服务。然后请用户在 TraceMemo → API Center → API Token 中点击“复制 Token”,并把 Token 配置为 Agent 本机环境变量 TRACEMEMO_API_TOKEN。读取联系人、会话或聊天记录时,必须发送 Authorization: Bearer $TRACEMEMO_API_TOKEN。若旧配置尚未升级,可兼容读取 WECHATEXPLORER_API_TOKEN,但新配置必须优先使用 TRACEMEMO_API_TOKEN。此服务是 Local HTTP API,不是 MCP Server。安装完成后告诉我验证结果,并说明你的本机 Skill 版本与 health 返回的 skill.version 是否一致。`
}
export function buildSkillVerificationPrompt(): string {
@@ -28,6 +28,9 @@ import { Switch, Spinner, useToast } from '../../components/ui'
const BLOCKED_RETRY_LIMIT = 20
const BLOCKED_RETRY_INTERVAL_MS = 2000
/** 运行期刷新的低频兜底间隔。开销说明见 `refreshQuietly`:指纹没变时只是一次本地读。 */
const REFRESH_INTERVAL_MS = 5 * 60 * 1000
export function MessageInsertSwitches(): React.JSX.Element {
const { toast } = useToast()
const [snapshot, setSnapshot] = React.useState<MsgInsertSwitchesSnapshot | null>(null)
@@ -85,6 +88,37 @@ export function MessageInsertSwitches(): React.JSX.Element {
}
}, [refresh])
/**
* 运行期刷新:**窗口重新聚焦** + **低频兜底**。
*
* 只在挂载时拉一次不够用:微信运行期间会新建 `message_N.db`,目标会话集合随之变化,
* 而规则补齐只在启动时跑过一次 —— 于是 `ready / total` 会一直差着几个。
*
* 刻意不做高频轮询:主进程侧会先比对消息分片清单指纹,没变就只做纯读立刻返回,
* 变了才 spawn 一次 helper,所以这一次调用的实际开销通常只是一次本地读。
*/
const refreshQuietly = React.useCallback(async (): Promise<void> => {
const api = window.api
if (!api?.refreshMsgInsertSwitches) return
try {
const result = await api.refreshMsgInsertSwitches()
setSnapshot(result)
if (result.success) setBlockedReason(null)
} catch {
/* 静默:一次后台刷新失败不应该把已经可用的界面打回禁用态。 */
}
}, [])
React.useEffect(() => {
const timer = window.setInterval(() => void refreshQuietly(), REFRESH_INTERVAL_MS)
const onFocus = (): void => void refreshQuietly()
window.addEventListener('focus', onFocus)
return () => {
window.clearInterval(timer)
window.removeEventListener('focus', onFocus)
}
}, [refreshQuietly])
/** 把结果里的失败原因翻成人话;native code 只进日志。 */
const humanize = React.useCallback((result: MsgInsertApplyResult): string => {
const status = result.status
@@ -129,7 +129,11 @@ function SendCapabilityStatus({
* 退群监控只产生退群事实,不再持有通知模板 —— 两处可编辑必然漂移。
*/
function GroupAvatar({ contact }: { contact: Contact }): React.ReactElement {
const GroupAvatar = React.memo(function GroupAvatar({
contact
}: {
contact: Contact
}): React.ReactElement {
const name = contactDisplayName(contact)
const initial = name.charAt(0) || '?'
return (
@@ -137,7 +141,7 @@ function GroupAvatar({ contact }: { contact: Contact }): React.ReactElement {
{contact.avatar ? <img src={contact.avatar} alt="" aria-hidden="true" /> : initial}
</span>
)
}
})
interface ManageGroupsProps {
groups: Contact[]
@@ -155,7 +159,14 @@ interface ManageGroupsProps {
onCancel: () => void
}
function ManageGroups({
/**
* 管理群聊页。
*
* 必须 `memo`:这个页面**不消费退群监控状态** —— 列表数据来自 `contacts`、选中来自本地 state,
* 而父层会因为监控状态推送反复重渲染(实测约 5 次/秒,且推送间隔 350ms 去抖)。
* 没有 memo 时 200+ 行会跟着每次推送重建,用户看到的就是"列表一直在刷新"。
*/
const ManageGroups = React.memo(function ManageGroups({
groups,
selectedRoomIds,
sendCapability,
@@ -294,7 +305,8 @@ function ManageGroups({
<footer className="exit-monitor-manage-footer">
<span>
保存后将从新的成员快照开始记录退群动态;退群通知发到哪里,请在「自动化 → 退群通知」里配置。
保存后将从新的成员快照开始记录退群动态;退群通知发到哪里,请在「自动化 →
退群通知」里配置。
</span>
<div>
<Button variant="ghost" onClick={onCancel} disabled={saving}>
@@ -307,7 +319,7 @@ function ManageGroups({
</footer>
</div>
)
}
})
export function GroupExitMonitorWorkspace({
dbReady,
@@ -354,6 +366,7 @@ export function GroupExitMonitorWorkspace({
}, [contacts])
React.useEffect(() => {
if (view !== 'events') return
const api = typeof window !== 'undefined' ? window.api : undefined
if (!api || typeof api.getGroupExitMonitorState !== 'function') return
let disposed = false
@@ -372,7 +385,7 @@ export function GroupExitMonitorWorkspace({
disposed = true
unsubscribe?.()
}
}, [])
}, [view])
React.useEffect(() => {
const api = typeof window !== 'undefined' ? window.api : undefined
@@ -536,7 +549,13 @@ export function GroupExitMonitorWorkspace({
}
}
const saveGroups = async (): Promise<void> => {
/**
* 保存监控范围。
*
* `useCallback` 是给 `ManageGroups` 的 `memo` 用的:函数引用不稳定时,
* 每次状态推送都会让 200+ 行的列表跟着重渲染。
*/
const saveGroups = React.useCallback(async (): Promise<void> => {
const api = window.api
if (saving || !dbReady || typeof api.setGroupExitMonitorGroups !== 'function') return
setSaving(true)
@@ -554,7 +573,7 @@ export function GroupExitMonitorWorkspace({
} finally {
setSaving(false)
}
}
}, [dbReady, groups, saving, selectedManageRoomIds])
const setMonitorEnabled = async (enabled: boolean): Promise<void> => {
const api = window.api
@@ -570,16 +589,16 @@ export function GroupExitMonitorWorkspace({
}
}
const toggleManageGroup = (roomId: string): void => {
const toggleManageGroup = React.useCallback((roomId: string): void => {
setSelectedManageRoomIds((current) => {
const next = new Set(current)
if (next.has(roomId)) next.delete(roomId)
else next.add(roomId)
return next
})
}
}, [])
const toggleAllManageGroups = (): void => {
const toggleAllManageGroups = React.useCallback((): void => {
const allRoomIds = groups.map(contactRoomId)
const shouldSelect = allRoomIds.some((roomId) => !selectedManageRoomIds.has(roomId))
setSelectedManageRoomIds((current) => {
@@ -590,7 +609,10 @@ export function GroupExitMonitorWorkspace({
})
return next
})
}
}, [groups, selectedManageRoomIds])
/** 退出管理页返回事件列表。同样为了 `ManageGroups` 的 memo 保持稳定引用。 */
const cancelManage = React.useCallback((): void => setView('events'), [])
if (view === 'manage') {
return (
@@ -606,8 +628,8 @@ export function GroupExitMonitorWorkspace({
onListFilterChange={setManageFilter}
onToggle={toggleManageGroup}
onToggleAll={toggleAllManageGroups}
onSave={() => void saveGroups()}
onCancel={() => setView('events')}
onSave={saveGroups}
onCancel={cancelManage}
/>
)
}
@@ -616,11 +638,11 @@ export function GroupExitMonitorWorkspace({
? '数据库未连接'
: !state.enabled
? '监控已暂停'
: state.running && state.nativeMonitorActive
? '实时监听已启用'
: state.running
? '已连接,等待原生监听'
: '等待启动'
: state.running && state.nativeMonitorActive
? '实时监听已启用'
: state.running
? '已连接,等待原生监听'
: '等待启动'
return (
<div className="exit-monitor-page">
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react'
import { RadioGroup, RadioGroupItem, Switch } from '../../../components/ui'
export type AppearanceTheme = 'system' | 'light' | 'dark'
/** 关闭主窗口时的行为。与主进程 settings-store 的 `CloseAction` 保持一致。 */
export type CloseAction = 'ask' | 'tray' | 'quit'
export function AppearancePage({
onNotice,
@@ -13,6 +15,7 @@ export function AppearancePage({
const [theme, setTheme] = useState<AppearanceTheme>('system')
const [compactMode, setCompactMode] = useState(false)
const [showStartupProgress, setShowStartupProgress] = useState(true)
const [closeAction, setCloseAction] = useState<CloseAction>('ask')
useEffect(() => {
let active = true
@@ -21,6 +24,7 @@ export function AppearancePage({
setTheme(result.settings.appearanceTheme)
setCompactMode(result.settings.compactMode)
setShowStartupProgress(result.settings.showStartupProgress)
setCloseAction(result.settings.closeAction)
onAppearanceChange({
theme: result.settings.appearanceTheme,
compactMode: result.settings.compactMode
@@ -35,11 +39,13 @@ export function AppearancePage({
appearanceTheme?: AppearanceTheme
compactMode?: boolean
showStartupProgress?: boolean
closeAction?: CloseAction
}): Promise<void> => {
const result = await window.api.setSettings(patch)
setTheme(result.settings.appearanceTheme)
setCompactMode(result.settings.compactMode)
setShowStartupProgress(result.settings.showStartupProgress)
setCloseAction(result.settings.closeAction)
onAppearanceChange({
theme: result.settings.appearanceTheme,
compactMode: result.settings.compactMode
@@ -118,6 +124,45 @@ export function AppearancePage({
/>
</label>
</section>
<h2 className="settings-section-heading">关闭窗口时</h2>
<section className="settings-card settings-option-card">
<RadioGroup
className="settings-choice-grid"
value={closeAction}
onValueChange={(value) => {
if (value === 'ask' || value === 'tray' || value === 'quit')
void save({ closeAction: value })
}}
>
{(
[
['ask', '每次询问', '每次关闭窗口都弹出选择框'],
['tray', '最小化到托盘', '窗口隐藏,应用继续在后台运行'],
['quit', '退出应用', '直接结束整个 TraceMemo 进程']
] as const
).map(([value, label, hint]) => (
<label
className={`settings-choice ${closeAction === value ? 'active' : ''}`}
key={value}
htmlFor={`appearance-close-${value}`}
>
<RadioGroupItem
id={`appearance-close-${value}`}
value={value}
className="mt-0.5"
/>
<span>
<b>{label}</b>
<small>{hint}</small>
</span>
</label>
))}
</RadioGroup>
<p className="settings-option-hint">
选择「每次询问」时,关闭弹窗里勾选「记住我的选择」会自动切换到这里对应的项。
</p>
</section>
</div>
</div>
</div>
@@ -546,6 +546,13 @@
}
}
.settings-option-hint {
margin: 12px 0 0;
color: var(--wxex-text-muted);
font-size: 10px;
line-height: 15px;
}
.settings-toggle-list {
display: grid;
gap: 0;
+8 -2
View File
@@ -291,7 +291,13 @@ export interface QueryMessagesResponse {
imageOcrCoverage?: QueryImageTextCoverage
}
export interface SearchMessagesRequest {
target: QueryTarget
/**
* 目标会话。**可选** —— 省略表示"在 `scope` 描述的整个搜索范围内做跨会话检索"。
*
* 实现侧一直是这么用的(`request.target?.query`),Tool schema 也是这么声明的;
* 只有这里漏了 `?`,于是所有"省略 target 的跨会话检索"在类型层面都成了错误。
*/
target?: QueryTarget
timeRange: QueryTimeRange
query: string
variants?: string[]
@@ -467,7 +473,7 @@ export interface VoiceTranscribeResponse {
retryAfterSeconds?: number
hint?: string
}
export interface ConversationOverviewRequest { target: QueryTarget; timeRange: QueryTimeRange; scope?: QueryCorpusScope }
export interface ConversationOverviewRequest { target?: QueryTarget; timeRange: QueryTimeRange; scope?: QueryCorpusScope }
export interface ConversationOverviewResponse {
status: string
target?: { displayName: string; type: 'user' | 'group' }
@@ -149,9 +149,22 @@ describe('GroupExitMonitorWorkspace', () => {
monitoredRoomIds: ['研发群@chatroom'],
monitoredGroupCount: 1
}
const setGroups = vi.fn().mockResolvedValue(savedState)
const setGroups = vi.fn(async (roomIds: string[]) => {
current = {
...configuredState,
monitoredRoomIds: roomIds,
monitoredGroupCount: roomIds.length
}
return current
})
/**
* 真实服务的 `getState()` 返回的是**内存里的当前状态** —— 保存之后再拉一次,
* 拿到的必然是保存后的值。mock 用可变变量体现这一点:
* 否则"切回事件页时重新拉取"会把它覆盖成保存前的旧值,那是 mock 的失真,不是实现的问题。
*/
let current: GroupExitMonitorState = configuredState
window.api = {
getGroupExitMonitorState: vi.fn().mockResolvedValue(configuredState),
getGroupExitMonitorState: vi.fn(async () => current),
onGroupExitMonitorState: vi.fn(() => () => undefined),
setGroupExitMonitorGroups: setGroups,
checkGroupExitMonitorNow: vi.fn().mockResolvedValue(savedState),
@@ -0,0 +1,110 @@
import { act, render, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ToastProvider } from '../../src/renderer/src/components/ui'
import { MessageInsertSwitches } from '../../src/renderer/src/features/automation/MessageInsertSwitches'
import type { MsgInsertSwitchesSnapshot } from '../../src/shared/msg-insert-switch'
/**
* 自动化页右上角的两个开关 —— 只钉**运行期刷新时机**。
*
* 背景:微信运行期间会新建 `message_N.db`,目标会话集合随之变化,而规则补齐此前
* 只在启动时跑过一次。渲染层如果只在挂载时拉一次,用户看到的就是"计数对不上、
* 而且不会自己变好"。所以要在窗口重新聚焦时问一次(主进程侧再用分片指纹决定要不要补)。
*/
function makeSnapshot(ready: number, total: number): MsgInsertSwitchesSnapshot {
return {
success: true,
helperAvailable: true,
switches: {
recall_notice: {
name: 'recall_notice',
mode: 'rules',
desiredEnabled: true,
effectiveEnabled: ready === total,
readyInstallableRooms: ready,
totalInstallableRooms: total,
notReadyRooms: [],
totalShards: 1,
targetShards: 1
},
group_exit_notice: {
name: 'group_exit_notice',
mode: 'event',
desiredEnabled: true,
effectiveEnabled: true,
readyInstallableRooms: 1,
totalInstallableRooms: 1,
notReadyRooms: [],
totalShards: 0,
targetShards: 0
}
}
} as unknown as MsgInsertSwitchesSnapshot
}
function renderSwitches(): void {
render(
<ToastProvider>
<MessageInsertSwitches />
</ToastProvider>
)
}
describe('微信消息插入开关 · 运行期刷新', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('挂载只用 GET,不额外触发刷新', async () => {
const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2))
const refresh = vi.fn().mockResolvedValue(makeSnapshot(2, 2))
window.api = {
getMsgInsertSwitches: get,
refreshMsgInsertSwitches: refresh
} as unknown as typeof window.api
renderSwitches()
await waitFor(() => expect(get).toHaveBeenCalled())
expect(refresh).not.toHaveBeenCalled()
})
it('窗口重新聚焦时刷新一次,并画出更新后的计数', async () => {
const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2))
const refresh = vi.fn().mockResolvedValue(makeSnapshot(2, 2))
window.api = {
getMsgInsertSwitches: get,
refreshMsgInsertSwitches: refresh
} as unknown as typeof window.api
renderSwitches()
await waitFor(() => expect(document.body.textContent).toContain('1 / 2 已启用'))
await act(async () => {
window.dispatchEvent(new Event('focus'))
})
await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1))
await waitFor(() => expect(document.body.textContent).toContain('2 / 2 已启用'))
})
it('刷新失败时保持已有状态,不打回禁用态', async () => {
const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2))
const refresh = vi.fn().mockRejectedValue(new Error('boom'))
window.api = {
getMsgInsertSwitches: get,
refreshMsgInsertSwitches: refresh
} as unknown as typeof window.api
renderSwitches()
await waitFor(() => expect(document.body.textContent).toContain('1 / 2 已启用'))
await act(async () => {
window.dispatchEvent(new Event('focus'))
})
await waitFor(() => expect(refresh).toHaveBeenCalled())
expect(document.body.textContent).toContain('1 / 2 已启用')
})
})
+61 -3
View File
@@ -1,9 +1,11 @@
import fs from 'fs-extra'
import { join } from 'path'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
const fixture = vi.hoisted(() => ({
root: `/tmp/wxe-local-api-auth-${process.pid}`,
storageAvailable: true,
skillVersion: '9.9.9',
contacts: [
{
m_nsUsrName: 'wxid_fixture',
@@ -29,7 +31,16 @@ const fixture = vi.hoisted(() => ({
}))
vi.mock('electron', () => ({
app: { getPath: () => fixture.root, getVersion: () => 'test-version' },
app: {
getPath: () => fixture.root,
getAppPath: () => fixture.root,
getVersion: () => 'test-version',
isPackaged: false
},
shell: {
openPath: async () => '',
openExternal: async () => undefined
},
safeStorage: {
isEncryptionAvailable: () => fixture.storageAvailable,
encryptString: (value: string) => Buffer.from(`encrypted:${value}`, 'utf8'),
@@ -99,7 +110,13 @@ async function startFixtureServer(
}
describe('Local API authentication', () => {
beforeAll(() => fs.ensureDirSync(fixture.root))
beforeAll(() => {
fs.ensureDirSync(fixture.root)
fs.outputFileSync(
join(fixture.root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md'),
`---\nname: tracememo-reader\nversion: ${fixture.skillVersion}\ndescription: fixture\n---\n\n# TraceMemo Reader fixture\n`
)
})
beforeEach(() => {
fixture.storageAvailable = true
@@ -135,6 +152,46 @@ describe('Local API authentication', () => {
await expect(response.json()).resolves.toMatchObject({ count: 1 })
})
it('advertises the Reader Skill version on health and serves SKILL.md to authenticated agents', async () => {
const handle = await startFixtureServer()
const health = await (await fetch(`${baseUrl(handle)}/api/v1/health`)).json()
expect(health).toMatchObject({
ok: true,
skill: { name: 'tracememo-reader', version: fixture.skillVersion, available: true }
})
const path = `${baseUrl(handle)}/api/v1/skill/tracememo-reader`
expect((await fetch(path)).status).toBe(401)
const response = await fetch(path, { headers: { Authorization: `Bearer ${VALID_TOKEN}` } })
expect(response.status).toBe(200)
const body = await response.json()
expect(body).toMatchObject({ name: 'tracememo-reader', version: fixture.skillVersion })
expect(body.markdown).toContain(`version: ${fixture.skillVersion}`)
expect(body.contentHash).toMatch(/^[0-9a-f]{64}$/)
expect(JSON.stringify(body)).not.toMatch(/token|authorization|wxid|databasePath|provider/i)
})
// 外部 Agent 靠 health 上的 skill.version 判断 Skill 是否过期,
// 所以首选位置读不到时也必须正常回答(回退到下一个候选),不能整条 500。
it('falls back to the next Skill candidate and still answers health', async () => {
const handle = await startFixtureServer()
const skillPath = join(fixture.root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
const backup = fs.readFileSync(skillPath, 'utf-8')
fs.removeSync(skillPath)
try {
const response = await fetch(`${baseUrl(handle)}/api/v1/health`)
expect(response.status).toBe(200)
const body = await response.json()
expect(body.ok).toBe(true)
expect(body.skill).toMatchObject({ name: 'tracememo-reader', available: true })
expect(body.skill.version).toMatch(/^\d+\.\d+\.\d+$/)
} finally {
fs.outputFileSync(skillPath, backup)
}
})
it.each([
['POST', '/api/v1/health', 'GET'],
['PATCH', '/api/v1/current_time', 'GET'],
@@ -217,7 +274,8 @@ describe('Local API authentication', () => {
['POST', '/api/v1/agent/send'],
['GET', '/api/v1/query/capabilities'],
['POST', '/api/v1/query/messages'],
['POST', '/api/v1/query/voice-transcribe']
['POST', '/api/v1/query/voice-transcribe'],
['GET', '/api/v1/skill/tracememo-reader']
])('protects every non-health route: %s %s', async (method, pathname) => {
const handle = await startFixtureServer()
const response = await fetch(`${baseUrl(handle)}${pathname}`, {
+2 -3
View File
@@ -1,6 +1,6 @@
{
"note": "测试文件类型检查基线:只允许下降,不允许上升。用 node scripts/typecheck-tests.cjs --update 下调。",
"total": 209,
"total": 203,
"files": {
"tests/component/ai-model-settings.test.tsx": 2,
"tests/component/ai-search-cache-consent.test.tsx": 3,
@@ -32,7 +32,6 @@
"tests/integration/image-text-index-synthetic-e2e.test.ts": 22,
"tests/integration/query-agent-image-ocr-text.test.ts": 16,
"tests/integration/query-agent-self-direction.test.ts": 7,
"tests/unit/agent-hub-routing.test.ts": 1,
"tests/unit/ai-search-pipeline-service.test.ts": 1,
"tests/unit/ai-search-provider-consent.test.ts": 5,
"tests/unit/ai-search-workspace-pure-functions.test.ts": 13,
@@ -40,7 +39,7 @@
"tests/unit/group-report.test.ts": 1,
"tests/unit/http-media-service.test.ts": 2,
"tests/unit/knowledge-freshness.test.ts": 1,
"tests/unit/local-query-api-service.test.ts": 51,
"tests/unit/local-query-api-service.test.ts": 46,
"tests/unit/message-state.test.ts": 1,
"tests/unit/query-agent-image-ocr-coverage.test.ts": 1,
"tests/unit/query-agent-service.test.ts": 4,
+61 -7
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
formatWechatReplyText,
matchGroupReportIntent,
matchRecentChatIntent,
queryAgentReplyText,
@@ -114,15 +115,46 @@ describe('Agent Hub 回复文案映射', () => {
outcome: 'answered' as const
}
/**
* 完整合法的 answered 结果。
* `evidence` / `stats` 是 contract 必填字段 —— 直接写字面量会缺字段报类型错。
*/
const answeredResult = (answer: string): AskWechatQueryResult => ({
engine: 'query-agent',
status: 'answered',
answer,
evidence: [],
stats: {
tools: [],
reads: { messageCount: 0, matchedCount: 0, overviewSourceCount: 0, evidenceCount: 0 },
modelCallCount: 0,
toolCallCount: 0,
totalMs: 0
},
diagnostics
})
it('answered → 直接用 Query Agent 的文本回答', () => {
expect(queryAgentReplyText(answeredResult('最近聊了两件事。'))).toBe('最近聊了两件事。')
})
it('answered → 剥离桌面 UI 的 [E#] 引用编号(微信里点不开,只剩噪音)', () => {
expect(
queryAgentReplyText({
engine: 'query-agent',
status: 'answered',
answer: '最近聊了两件事。',
diagnostics
})
).toBe('最近聊了两件事。')
queryAgentReplyText(
answeredResult('第一件事先看结论、第二件事要留缓冲[E6][E14],第三件不能直接上[E16]。')
)
).toBe('第一件事先看结论、第二件事要留缓冲,第三件不能直接上。')
})
it('独占一行的 [E#] 被移除,但不会把相邻两行粘成一行', () => {
expect(queryAgentReplyText(answeredResult('第一件事[E1]\n[E2]\n第二件事[E3]'))).toBe(
'第一件事\n\n第二件事'
)
})
it('整段只剩引用编号时原样兜底,绝不发空消息', () => {
// 防御分支:正常回答不会走到这里;真走到也宁可有内容,不能发一条空消息。
expect(queryAgentReplyText(answeredResult('[E1][E2]'))).toBe('[E1][E2]')
})
it('provider_unavailable / error → 使用安全文案', () => {
@@ -153,3 +185,25 @@ describe('Agent Hub 回复文案映射', () => {
expect(queryAgentReplyText(legacy)).toBe(QUERY_AGENT_UNAVAILABLE_TEXT)
})
})
describe('Agent Hub 微信文本排版 — 单换行会被压成空格', () => {
it('列表项之间改用空行,否则微信里连成一整段', () => {
expect(formatWechatReplyText('结论:两件事。\n• 做饭\n• 游戏')).toBe(
'结论:两件事。\n\n• 做饭\n\n• 游戏'
)
})
it('Markdown 列表标记归一成 • 后同样独立成行', () => {
expect(formatWechatReplyText('1. 先说结论\n- 做饭\n- 游戏')).toBe(
'1. 先说结论\n\n• 做饭\n\n• 游戏'
)
})
it('连续空行收敛成一个,不留多余空行', () => {
expect(formatWechatReplyText('A\n\n\n\nB')).toBe('A\n\nB')
})
it('水平线不会被误当成列表标记', () => {
expect(formatWechatReplyText('上文\n---\n下文')).toBe('上文\n---\n下文')
})
})
+124 -8
View File
@@ -247,7 +247,7 @@ describe('LocalQueryApiService', () => {
expect(result.sourceLatestAt).toBe(NOW - 1000)
expect(result.freshness).toEqual({ catchUp: 'pending' })
expect(knowledge.requestCatchUp).toHaveBeenCalledTimes(1)
expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(2000)
expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(15000)
})
it('追赶在预算内完成 → 用新索引重新检索(不能拿同步前的结果回答)', async () => {
@@ -315,7 +315,9 @@ describe('LocalQueryApiService', () => {
voiceCoverage: undefined
})
const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'today' }, query: '健身' })
// 刻意**不带 target**:单会话现在会走直读兜底(结论句变成"已用直读补齐"),
// 而这条用例要守的是"索引落后且无法兜底时,结论句必须诚实说无法确认"。
const result = await service.search({ timeRange: { kind: 'today' }, query: '健身' })
expect(result.resolvedTimeRange?.endTime).toEqual(expect.any(Number))
// 请求边界(今天)晚于索引覆盖边界 4 分钟 → 只能 partial。
@@ -324,16 +326,129 @@ describe('LocalQueryApiService', () => {
expect(result.indexCoverage?.summary).toContain('暂时无法确认')
})
it('已有索引任务在跑 → 复用而不阻塞本次查询', async () => {
it('已有索引任务在跑 → 同样等一个有界预算,等不到才按旧覆盖如实回答', async () => {
fixture.contacts.splice(1)
knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
knowledge.requestCatchUp.mockReturnValue({ triggered: false, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(false)
const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' })
const result = await service.search({
target: { query: 'BOBO' },
timeRange: { kind: 'all' },
query: '健身'
})
expect(result.freshness).toEqual({ catchUp: 'reused' })
expect(knowledge.waitForIndexingComplete).not.toHaveBeenCalled()
expect(result.coverage).toEqual({ state: 'partial' })
// 复用场景必须等:直接返回旧快照会出现「索引明明在追,却拿旧覆盖下结论」。
expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(15000)
// 用 toMatchObject 而不是逐字段断言:search() 的返回是联合类型,
// 直接取属性会撞上这个文件既有的"未收窄"类型债(棘轮不允许新增)。
expect(result).toMatchObject({
freshness: { catchUp: 'reused' },
coverage: { state: 'partial' }
})
})
it('复用的索引任务在预算内追完 → 重新检索,不允许拿同步前的结果回答', async () => {
fixture.contacts.splice(1)
knowledge.search
.mockResolvedValueOnce({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
.mockResolvedValueOnce({
state: 'ready',
indexLatestAt: NOW - 30 * 1000,
sourceLatestAt: NOW - 1000,
voiceCoverage: undefined,
evidence: [
{
conversationId: 'md5-bobo',
messageId: 'new-1',
timestamp: NOW - 60_000,
sender: 'BOBO',
sourceKind: 'text',
text: '最近开始健身了'
}
]
})
knowledge.requestCatchUp.mockReturnValue({ triggered: false, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(true)
const result = await service.search({
target: { query: 'BOBO' },
timeRange: { kind: 'all' },
query: '健身'
})
expect(knowledge.search).toHaveBeenCalledTimes(2)
expect(result).toMatchObject({
freshness: { catchUp: 'completed' },
coverage: { state: 'complete' },
evidenceCount: 1
})
})
it('索引没覆盖 + 范围恰是一个会话 → 直读原始记录兜底(微信机器人拿得到新消息)', async () => {
fixture.contacts.splice(1)
knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
knowledge.requestCatchUp.mockReturnValue({ triggered: true, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(false)
const listSpy = listMessagesAsync as unknown as Mock
// 直读必须落在 begin/end 让路窗口**之内**:窗口外后台索引会抢 WCDB,
// 把直读拖成几十秒。用调用顺序固定这个不变量。
const order: string[] = []
knowledge.beginInteractiveQuery.mockImplementation(() => void order.push('begin'))
knowledge.endInteractiveQuery.mockImplementation(() => void order.push('end'))
listSpy.mockImplementation(async () => {
order.push('directRead')
return [
{
id: 'm9',
type: '普通文本',
datetime: '2026/9/9 11:58:00',
content: '刚提到过这个探针词',
isSender: false,
name: 'BOBO',
createTime: Math.floor((NOW - 2 * 60 * 1000) / 1000)
}
]
})
const result = await service.search({
target: { query: 'BOBO' },
timeRange: { kind: 'all' },
query: '探针词'
})
// 直读读的是权威源,证据拿得到 —— 这是微信机器人"能拿到东西"的关键。
// 但 coverage 仍如实是 partial:直读只补了索引水位之后那一段,更早的区间还是索引说了算。
expect(listSpy).toHaveBeenCalledTimes(1)
expect(result).toMatchObject({
coverage: { state: 'partial' },
evidenceCount: 1,
evidence: [{ text: '刚提到过这个探针词', sender: 'BOBO' }]
})
// 结论句必须说明"这段已用直读补上",否则模型会一边拿着证据、一边说"暂时无法确认"。
const indexCoverage = (
result as unknown as { indexCoverage?: { covered: boolean; summary: string } }
).indexCoverage
expect(indexCoverage?.covered).toBe(false)
expect(indexCoverage?.summary).toContain('直读原始记录补齐')
expect(order).toEqual(['begin', 'directRead', 'end'])
})
it('索引没覆盖但范围跨多个会话 → 不直读兜底,仍如实 partial', async () => {
knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
knowledge.requestCatchUp.mockReturnValue({ triggered: true, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(false)
const listSpy = listMessagesAsync as unknown as Mock
const result = await service.search({
timeRange: { kind: 'all' },
query: '探针词',
scope: { kind: 'all' }
})
// 跨会话直读要遍历上千个会话(大会话全量读一次 15s+),只能保持 partial。
expect(listSpy).not.toHaveBeenCalled()
expect(result).toMatchObject({ coverage: { state: 'partial' }, evidenceCount: 0 })
})
it('追平后 0 结果才允许 complete negative;落后时同一条件只能是 partial', async () => {
@@ -417,7 +532,8 @@ describe('LocalQueryApiService — indexCoverage 结论句', () => {
})
it('落后时给出可直接引用的本地时间结论,且明确"暂时无法确认"', async () => {
const result = await service2.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' })
// 同样刻意不带 target —— 见上一条:单会话已经会走直读兜底。
const result = await service2.search({ timeRange: { kind: 'all' }, query: '健身' })
expect(result.coverage).toEqual({ state: 'partial' })
// 8/30 12:00 的本地时间标签(固定时钟下可断言)
expect(result.indexCoverage?.covered).toBe(false)
@@ -323,6 +323,11 @@ describe('定时日报 · 微信异常通知', () => {
const text = sendNotification.mock.calls[0][0].text as string
expect(text).toContain('每日晚报')
expect(text).toContain('日报生成失败')
// 必须带**失败发生时刻**:同一批补发的多条失败文案可能一模一样,
// 只有这个时间戳能把它们区分开。
expect(text).toContain('8月27日 18:31')
// 必须用空行分隔:微信把单个换行压成空格,否则整条通知连成一行。
expect(text).toContain('定时日报执行失败\n\n日报生成失败')
const notifications = await service.listNotifications()
expect(notifications).toHaveLength(1)
+132 -24
View File
@@ -1,9 +1,12 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { createHash } from 'crypto'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { dirname, join, resolve } from 'path'
import { afterEach, describe, expect, it } from 'vitest'
import {
getSkillCandidates,
parseSkillFrontmatter,
readSkillDocument,
resolveSkillResourceStatus
} from '../../src/main/services/skill-resource-service'
@@ -25,9 +28,18 @@ function environment(root: string, packaged: boolean) {
}
}
function writeSkill(filePath: string): void {
function skillBody(version?: string): string {
const versionLine = version ? `version: ${version}\n` : ''
return `---\nname: tracememo-reader\n${versionLine}description: fixture\n---\n\n# TraceMemo Reader\n\n正文内容。\n`
}
function writeSkill(filePath: string, version?: string): void {
mkdirSync(dirname(filePath), { recursive: true })
writeFileSync(filePath, '# TraceMemo Reader\n', 'utf8')
writeFileSync(filePath, skillBody(version), 'utf8')
}
function sha256(content: string): string {
return createHash('sha256').update(content, 'utf8').digest('hex')
}
describe('Reader Skill resource resolution', () => {
@@ -39,44 +51,28 @@ describe('Reader Skill resource resolution', () => {
const root = fixtureRoot()
const runtime = environment(root, false)
const skillPath = join(runtime.cwd, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath)
writeSkill(skillPath, '1.3.0')
expect(resolveSkillResourceStatus(runtime)).toMatchObject({
available: true,
source: 'development',
version: 'v1.2',
name: 'tracememo-reader',
version: '1.3.0',
filePath: skillPath,
directoryPath: dirname(skillPath)
})
})
it('resolves the Reader Skill from this checkout', () => {
const workspace = resolve(__dirname, '../..')
const status = resolveSkillResourceStatus({
appPath: workspace,
cwd: workspace,
resourcesPath: join(workspace, 'node_modules', 'electron', 'resources'),
execPath: join(workspace, 'node_modules', 'electron', 'electron.exe'),
packaged: false
})
expect(status).toMatchObject({
available: true,
source: 'development',
version: 'v1.2',
filePath: join(workspace, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
})
})
it('uses the extraResources Skill directory in a packaged runtime', () => {
const root = fixtureRoot()
const runtime = environment(root, true)
const skillPath = join(runtime.resourcesPath, 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath)
writeSkill(skillPath, '1.3.0')
expect(resolveSkillResourceStatus(runtime)).toMatchObject({
available: true,
source: 'bundled',
version: '1.3.0',
filePath: skillPath
})
})
@@ -104,4 +100,116 @@ describe('Reader Skill resource resolution', () => {
expect(status).toMatchObject({ available: false, source: 'development' })
for (const candidate of candidates) expect(status.error).toContain(candidate.path)
})
it('omits the version when the frontmatter does not declare one', () => {
const root = fixtureRoot()
const runtime = environment(root, false)
const skillPath = join(runtime.cwd, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath)
const status = resolveSkillResourceStatus(runtime)
expect(status.available).toBe(true)
expect(status.version).toBeUndefined()
})
// /health 是外部 Agent 的自检入口:环境探测本身出错时只能降级,不能抛出。
it('degrades to unavailable instead of throwing when the environment is broken', () => {
const status = resolveSkillResourceStatus({
appPath: undefined as unknown as string,
cwd: undefined as unknown as string,
resourcesPath: '',
execPath: undefined as unknown as string,
packaged: false
})
expect(status.available).toBe(false)
expect(status.error).toContain('未找到 TraceMemo Reader Skill 文件')
expect(status.githubUrl).toContain('github.com')
})
})
describe('Reader Skill document identity', () => {
afterEach(() => {
while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true })
})
it('exposes markdown, version and a content hash that matches the file bytes', () => {
const root = fixtureRoot()
const skillPath = join(root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath, '1.3.0')
const content = readFileSync(skillPath, 'utf-8')
const document = readSkillDocument(skillPath)
expect(document).not.toBeNull()
expect(document?.version).toBe('1.3.0')
expect(document?.name).toBe('tracememo-reader')
expect(document?.markdown).toBe(content)
expect(document?.contentHash).toBe(sha256(content))
expect(document?.filePath).toBe(skillPath)
expect(Number.isNaN(Date.parse(document?.modifiedAt || ''))).toBe(false)
})
it('returns null for a missing file instead of throwing', () => {
const root = fixtureRoot()
expect(readSkillDocument(join(root, 'missing', 'SKILL.md'))).toBeNull()
})
// 自助更新的正确性依赖这条:Agent 覆盖 SKILL.md 后,health 必须立刻报出新版本。
it('invalidates the cache once the file on disk is replaced', () => {
const root = fixtureRoot()
const skillPath = join(root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath, '1.3.0')
expect(readSkillDocument(skillPath)?.version).toBe('1.3.0')
writeSkill(skillPath, '1.4.0-with-a-longer-body-to-change-the-file-size')
const updated = readSkillDocument(skillPath)
expect(updated?.version).toBe('1.4.0-with-a-longer-body-to-change-the-file-size')
expect(updated?.contentHash).not.toBe(sha256(skillBody('1.3.0')))
})
})
describe('SKILL.md frontmatter contract', () => {
it('parses name and version from a plain frontmatter block', () => {
expect(parseSkillFrontmatter('---\nname: a\nversion: 2.1.0\n---\nbody')).toEqual({
name: 'a',
version: '2.1.0'
})
})
it('ignores files without frontmatter and tolerates CRLF, quotes and comments', () => {
expect(parseSkillFrontmatter('# no frontmatter\n')).toEqual({})
expect(parseSkillFrontmatter('---\r\n# comment\r\nversion: "3.0.1"\r\n---\r\n')).toEqual({
version: '3.0.1'
})
})
/**
* 防漂移契约:版本号只有一个真源,就是 SKILL.md 的 frontmatter。
* 这里独立地按行正则提取一次,与解析结果逐字比对 —— 任何"把版本写回源码常量"的
* 回归都会让这条测试变红。
*/
it('keeps the reader Skill version declared in the repository SKILL.md', () => {
const workspace = resolve(__dirname, '../..')
const skillPath = join(workspace, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
const content = readFileSync(skillPath, 'utf-8')
const declared = /^version:[ \t]*(\S+)[ \t]*$/m.exec(content)
expect(declared).not.toBeNull()
expect(parseSkillFrontmatter(content).version).toBe(declared![1])
expect(declared![1]).toMatch(/^\d+\.\d+\.\d+$/)
const status = resolveSkillResourceStatus({
appPath: workspace,
cwd: workspace,
resourcesPath: join(workspace, 'node_modules', 'electron', 'resources'),
execPath: join(workspace, 'node_modules', 'electron', 'electron.exe'),
packaged: false
})
expect(status).toMatchObject({
available: true,
source: 'development',
version: declared![1],
filePath: skillPath
})
})
})