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

+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
})
})
})