mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: Reader Skill 支持版本自检与自助更新
微信机器人回复剥离引用编号、列表改用空行分隔,失败通知补失败时刻 问问微信关键词检索在索引落后时按单会话直读原始记录兜底 关闭窗口支持记住选择并在设置中修改 退群监控刷新列表
This commit is contained in:
1 parent
fd7d5016a8
commit
eaa25cd29e
33 files changed
+1401
-154
No files matched your search
@@ -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
@@ -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()
|
||||
})
|
||||
/**
|
||||
* 微信消息插入开关 —— 写入。
|
||||
|
||||
@@ -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'))
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,说明图片文字索引尚未完成、当前无法确认全部历史图片。
|
||||
|
||||
@@ -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,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) {
|
||||
|
||||
@@ -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 }
|
||||
|
||||
Vendored
+5
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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' }
|
||||
|
||||
Reference in new issue
Block a user