mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
fix: 超大会话索引改为分批流式,修复回填时主进程堆溢出闪退 #75
Fixes https://github.com/Wxw-Gu/TraceMemo/issues/75
This commit is contained in:
1 parent
b86582e606
commit
d436b064c3
41 files changed
+4214
-400
No files matched your search
+52
-1
@@ -610,7 +610,15 @@ import type {
|
||||
AskWechatQueryRequest,
|
||||
AskWechatQueryResult
|
||||
} from '../shared/query-agent'
|
||||
import type { KnowledgeSearchIpcRequest, KnowledgeSearchIpcResult } from '../shared/knowledge'
|
||||
import type {
|
||||
KnowledgeIndexScope,
|
||||
KnowledgeSearchIpcRequest,
|
||||
KnowledgeSearchIpcResult
|
||||
} from '../shared/knowledge'
|
||||
import {
|
||||
DEFAULT_KNOWLEDGE_INDEX_SCOPE,
|
||||
normalizeKnowledgeIndexScope
|
||||
} from '../shared/knowledge'
|
||||
// 消息身份的规范化在 main / renderer 之间必须一致,所以只从 shared 取一份实现。
|
||||
import { normalizeMessageIdentity } from '../shared/local-query-api'
|
||||
import {
|
||||
@@ -618,6 +626,7 @@ import {
|
||||
WINDOWS_VC_RUNTIME_ERROR_MESSAGE
|
||||
} from '../shared/windows-runtime'
|
||||
import { KnowledgeSearchService } from './knowledge/knowledge-search-service'
|
||||
import { ConversationMessageCountService } from './knowledge/conversation-message-count-service'
|
||||
import {
|
||||
MESSAGES_AROUND_MAX_WINDOW,
|
||||
messagesAroundRadii,
|
||||
@@ -660,6 +669,7 @@ let voiceService: VoiceService | null = null
|
||||
let voiceRecognition: VoiceRecognitionUseCase | null = null
|
||||
let voiceBatchService: VoiceBatchService | null = null
|
||||
let knowledgeSearchService: KnowledgeSearchService | null = null
|
||||
let conversationMessageCountService: ConversationMessageCountService | null = null
|
||||
let groupStatsService: GroupStatsService | null = null
|
||||
let localQueryApiService: LocalQueryApiService | null = null
|
||||
let aiSearchPipelineService: AiSearchPipelineService | null = null
|
||||
@@ -1169,6 +1179,12 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
||||
app.getPath('userData'),
|
||||
join(__dirname, 'knowledgeWorker.js')
|
||||
)
|
||||
conversationMessageCountService = new ConversationMessageCountService()
|
||||
conversationMessageCountService.onCountsChange((entries) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) window.webContents.send('knowledge:conversationCounts', entries)
|
||||
}
|
||||
})
|
||||
knowledgeSearchService.setVoiceTranscriptResolver(
|
||||
(reference) => voiceRecognition?.getTranscriptSnapshot(reference) || { state: 'pending' }
|
||||
)
|
||||
@@ -2690,6 +2706,10 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
||||
})
|
||||
|
||||
ipcMain.handle('db:search', (_, keyword: string) => chat.searchMessages(keyword))
|
||||
/** 会话最后活跃时间(epoch ms,按 md5 索引):只用于排序展示,不参与索引判断。 */
|
||||
ipcMain.handle('db:conversationActivity', () =>
|
||||
Object.fromEntries(chat.getConversationActivityMs())
|
||||
)
|
||||
ipcMain.handle(
|
||||
'knowledge:search',
|
||||
(_, request: KnowledgeSearchIpcRequest): Promise<KnowledgeSearchIpcResult> => {
|
||||
@@ -2719,6 +2739,37 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
||||
if (!knowledgeSearchService) throw new Error('本地知识库服务尚未初始化')
|
||||
return knowledgeSearchService.cancelCurrentAccountIndex()
|
||||
})
|
||||
/** 保存范围时若正在同步,先让旧任务在安全边界停下再按新范围重启。 */
|
||||
ipcMain.handle('knowledge:getIndexScope', (): KnowledgeIndexScope => {
|
||||
const accountId = chat.getSelfAccountInfo()?.wxid || chat.getCurrentAccountRoot()
|
||||
if (!accountId) return { ...DEFAULT_KNOWLEDGE_INDEX_SCOPE }
|
||||
const scopes = loadSettings().knowledgeIndexScopes ?? {}
|
||||
return normalizeKnowledgeIndexScope(scopes[accountId])
|
||||
})
|
||||
ipcMain.handle('knowledge:setIndexScope', async (_, scope: unknown): Promise<KnowledgeIndexScope> => {
|
||||
const accountId = chat.getSelfAccountInfo()?.wxid || chat.getCurrentAccountRoot()
|
||||
const normalized = normalizeKnowledgeIndexScope(scope)
|
||||
if (!accountId) return normalized
|
||||
const scopes = { ...(loadSettings().knowledgeIndexScopes ?? {}) }
|
||||
scopes[accountId] = normalized
|
||||
updateSettings({ knowledgeIndexScopes: scopes })
|
||||
if (!knowledgeSearchService) return normalized
|
||||
const status = await knowledgeSearchService.getStatus()
|
||||
if (status.state === 'syncing' || status.state === 'building') {
|
||||
await knowledgeSearchService.cancelCurrentAccountIndex()
|
||||
await knowledgeSearchService.waitForIndexingComplete(15_000)
|
||||
knowledgeSearchService.startCurrentAccountIndex()
|
||||
}
|
||||
return normalized
|
||||
})
|
||||
/** 立即返回已知快照,未知项后台补算后推送;绝不为排序去加载正文。 */
|
||||
ipcMain.handle('knowledge:getConversationCounts', (_, conversationIds: string[]) => {
|
||||
if (!conversationMessageCountService) return { entries: [] }
|
||||
return conversationMessageCountService.read(Array.isArray(conversationIds) ? conversationIds : [])
|
||||
})
|
||||
ipcMain.handle('knowledge:cancelConversationCounts', () => {
|
||||
conversationMessageCountService?.cancel()
|
||||
})
|
||||
// ---- 图片文字索引(本地 System OCR 派生文本,非 AI Provider)----
|
||||
ipcMain.handle('image-text-index:getStatus', () => imageTextIndexService.getStatus())
|
||||
/**
|
||||
|
||||
@@ -64,25 +64,57 @@ export function chunkConversation(
|
||||
throw new Error('Conversation chunker received messages from multiple accounts or conversations')
|
||||
}
|
||||
|
||||
const chunks: KnowledgeChunk[] = []
|
||||
const streamer = createChunkStreamer(config)
|
||||
return [...streamer.push(sorted), ...streamer.drain()]
|
||||
}
|
||||
|
||||
export interface KnowledgeChunkStreamer {
|
||||
/** 追加一批有序消息,返回因此**收盘**的 chunk(不含尾部未完成段)。 */
|
||||
push(messages: KnowledgeNormalizedMessage[]): KnowledgeChunk[]
|
||||
/** 收盘尾部未完成段;之后再 `push` 会开启新段。 */
|
||||
drain(): KnowledgeChunk[]
|
||||
/** 尚未收盘的消息数;用于持久化续跑位置。 */
|
||||
pendingCount(): number
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分只依赖相邻两条与累积长度,所以分批 push 与一次性切分逐字等价。
|
||||
*/
|
||||
export function createChunkStreamer(config: KnowledgeChunkerConfig): KnowledgeChunkStreamer {
|
||||
let current: KnowledgeNormalizedMessage[] = []
|
||||
let currentCharacters = 0
|
||||
for (const message of sorted) {
|
||||
const previous = current[current.length - 1]
|
||||
const nextCharacters = currentCharacters + message.searchableText.length
|
||||
const shouldSplit =
|
||||
current.length > 0 &&
|
||||
(message.createTime - previous.createTime > config.maxGapMs ||
|
||||
current.length >= config.maxMessages ||
|
||||
nextCharacters > config.maxCharacters)
|
||||
if (shouldSplit) {
|
||||
chunks.push(buildChunk(current, config))
|
||||
|
||||
return {
|
||||
push(messages) {
|
||||
const chunks: KnowledgeChunk[] = []
|
||||
for (const message of messages) {
|
||||
if (!isIndexableKnowledgeMessage(message)) continue
|
||||
const previous = current[current.length - 1]
|
||||
const nextCharacters = currentCharacters + message.searchableText.length
|
||||
const shouldSplit =
|
||||
current.length > 0 &&
|
||||
(message.createTime - previous.createTime > config.maxGapMs ||
|
||||
current.length >= config.maxMessages ||
|
||||
nextCharacters > config.maxCharacters)
|
||||
if (shouldSplit) {
|
||||
chunks.push(buildChunk(current, config))
|
||||
current = []
|
||||
currentCharacters = 0
|
||||
}
|
||||
current.push(message)
|
||||
currentCharacters += message.searchableText.length
|
||||
}
|
||||
return chunks
|
||||
},
|
||||
drain() {
|
||||
if (!current.length) return []
|
||||
const chunk = buildChunk(current, config)
|
||||
current = []
|
||||
currentCharacters = 0
|
||||
return [chunk]
|
||||
},
|
||||
pendingCount() {
|
||||
return current.length
|
||||
}
|
||||
current.push(message)
|
||||
currentCharacters += message.searchableText.length
|
||||
}
|
||||
if (current.length) chunks.push(buildChunk(current, config))
|
||||
return chunks
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import * as chat from '../services/chat-service'
|
||||
import type {
|
||||
ConversationMessageCountEntry,
|
||||
ConversationMessageCountSnapshot
|
||||
} from '../../shared/conversation-message-count'
|
||||
import { EMPTY_CONVERSATION_MESSAGE_COUNT } from '../../shared/conversation-message-count'
|
||||
|
||||
/** 成功结果的有效期。聊天记录会增长,缓存不能永久有效。 */
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000
|
||||
/** 失败结果只短暂记住,避免每次打开下拉框都对同一批坏分片重试。 */
|
||||
const FAILURE_TTL_MS = 60 * 1000
|
||||
/** 同时在跑的 `COUNT(*)` 条数上限。 */
|
||||
const MAX_CONCURRENT = 4
|
||||
/** 合并推送的窗口,避免上千个会话逐条打 IPC。 */
|
||||
const FLUSH_INTERVAL_MS = 80
|
||||
|
||||
/** 只读 COUNT(*):为排序去加载正文正是 #75 的写法;失败返回 null,不是 0。 */
|
||||
export class ConversationMessageCountService {
|
||||
private readonly cache = new Map<string, ConversationMessageCountEntry>()
|
||||
private readonly inFlight = new Set<string>()
|
||||
private readonly listeners = new Set<(entries: ConversationMessageCountEntry[]) => void>()
|
||||
private queue: string[] = []
|
||||
private active = 0
|
||||
private generation = 0
|
||||
private flushTimer: NodeJS.Timeout | null = null
|
||||
private readonly dirty = new Map<string, ConversationMessageCountEntry>()
|
||||
/** 统计按账号隔离:换账号后旧 md5 的条数一个都不能复用。 */
|
||||
private accountId = ''
|
||||
|
||||
onCountsChange(listener: (entries: ConversationMessageCountEntry[]) => void): () => void {
|
||||
this.listeners.add(listener)
|
||||
return () => this.listeners.delete(listener)
|
||||
}
|
||||
|
||||
/** 立即返回快照(含缓存与「尚未统计」占位),并把未知项排进后台队列。 */
|
||||
read(conversationIds: string[]): ConversationMessageCountSnapshot {
|
||||
this.syncAccount()
|
||||
const entries = conversationIds.map((id) => this.cached(id))
|
||||
this.enqueue(conversationIds.filter((id) => entries.find((e) => e.conversationId === id)?.measuredAt === 0))
|
||||
return { entries }
|
||||
}
|
||||
|
||||
/** 只读缓存,不触发统计。 */
|
||||
peek(conversationIds: string[]): ConversationMessageCountEntry[] {
|
||||
return conversationIds.map((id) => this.cached(id))
|
||||
}
|
||||
|
||||
enqueue(conversationIds: string[]): void {
|
||||
this.syncAccount()
|
||||
for (const id of conversationIds) {
|
||||
if (!id || this.inFlight.has(id)) continue
|
||||
const cached = this.cache.get(id)
|
||||
if (cached && Date.now() - cached.measuredAt < this.ttl(cached)) continue
|
||||
this.inFlight.add(id)
|
||||
this.queue.push(id)
|
||||
}
|
||||
this.pump()
|
||||
}
|
||||
|
||||
/** 停止推进并丢弃队列;已算出的结果保留(它们仍然有效)。 */
|
||||
cancel(): void {
|
||||
this.generation += 1
|
||||
this.queue = []
|
||||
this.inFlight.clear()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.cancel()
|
||||
if (this.flushTimer) clearTimeout(this.flushTimer)
|
||||
this.flushTimer = null
|
||||
this.listeners.clear()
|
||||
this.dirty.clear()
|
||||
this.cache.clear()
|
||||
}
|
||||
|
||||
private syncAccount(): void {
|
||||
const next = chat.isReady() ? chat.getSelfAccountInfo()?.wxid || '' : ''
|
||||
if (next === this.accountId) return
|
||||
this.accountId = next
|
||||
this.cancel()
|
||||
this.cache.clear()
|
||||
this.dirty.clear()
|
||||
}
|
||||
|
||||
private ttl(entry: ConversationMessageCountEntry): number {
|
||||
return entry.count === null ? FAILURE_TTL_MS : CACHE_TTL_MS
|
||||
}
|
||||
|
||||
private cached(conversationId: string): ConversationMessageCountEntry {
|
||||
const hit = this.cache.get(conversationId)
|
||||
if (hit && Date.now() - hit.measuredAt < this.ttl(hit)) return hit
|
||||
return { ...EMPTY_CONVERSATION_MESSAGE_COUNT, conversationId }
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
while (this.active < MAX_CONCURRENT && this.queue.length) {
|
||||
const conversationId = this.queue.shift() as string
|
||||
const generation = this.generation
|
||||
this.active += 1
|
||||
void this.measure(conversationId)
|
||||
.then((result) => {
|
||||
if (generation !== this.generation) return
|
||||
this.publish({ conversationId, ...result, measuredAt: Date.now() })
|
||||
})
|
||||
.catch(() => {
|
||||
if (generation !== this.generation) return
|
||||
// 统计失败必须是「未知」:0 会让一个真有 57 万条的群排到最后并显示误导性数字。
|
||||
this.publish({ conversationId, count: null, approximate: false, measuredAt: Date.now() })
|
||||
})
|
||||
.finally(() => {
|
||||
this.inFlight.delete(conversationId)
|
||||
this.active -= 1
|
||||
this.pump()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private async measure(
|
||||
conversationId: string
|
||||
): Promise<{ count: number | null; approximate: boolean }> {
|
||||
if (!chat.isReady()) return { count: null, approximate: false }
|
||||
const result = await chat.countConversationMessagesAsync(conversationId)
|
||||
return { count: result.count, approximate: result.approximate }
|
||||
}
|
||||
|
||||
private publish(entry: ConversationMessageCountEntry): void {
|
||||
this.cache.set(entry.conversationId, entry)
|
||||
this.dirty.set(entry.conversationId, entry)
|
||||
if (this.flushTimer) return
|
||||
this.flushTimer = setTimeout(() => {
|
||||
this.flushTimer = null
|
||||
const batch = Array.from(this.dirty.values())
|
||||
this.dirty.clear()
|
||||
if (!batch.length) return
|
||||
for (const listener of this.listeners) listener(batch)
|
||||
}, FLUSH_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
@@ -23,14 +23,15 @@ import type {
|
||||
import {
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
emptyKnowledgeSearchTimings
|
||||
emptyKnowledgeSearchTimings,
|
||||
normalizeKnowledgeIndexScope,
|
||||
type KnowledgeConversationIndexState,
|
||||
type KnowledgeIndexScope
|
||||
} from '../../shared/knowledge'
|
||||
import { KnowledgeService } from './knowledge-service'
|
||||
import { loadSettings } from '../services/settings-store'
|
||||
import { sourceMessageId } from './message-identity'
|
||||
import {
|
||||
voiceAccountIdentity,
|
||||
voiceMessageIdentity
|
||||
} from '../voice-pipeline/voice-message-identity'
|
||||
import { voiceAccountIdentity } from '../voice-pipeline/voice-message-identity'
|
||||
|
||||
const FALLBACK_LIMIT = 240
|
||||
const MAX_SENDER_NAME_CONVERSATIONS = 8
|
||||
@@ -50,6 +51,14 @@ const SENDER_ENRICHMENT_SESSION_TTL_MS = 5 * 60 * 1000
|
||||
*/
|
||||
const DELTA_OVERLAP_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
/**
|
||||
* 后台回填的单页消息数:调到更大能少走 IPC,但主进程驻留的上限也随之变大。
|
||||
*/
|
||||
const KNOWLEDGE_INDEX_PAGE_SIZE = 1500
|
||||
|
||||
/** 增量窗口超过这个条数就改为分批重建,否则一次读完会重演「整会话进内存」。 */
|
||||
const DELTA_STREAM_THRESHOLD = 20_000
|
||||
|
||||
/**
|
||||
* event-loop 滞后采样的分辨率(ms)。
|
||||
*
|
||||
@@ -321,6 +330,7 @@ export class KnowledgeSearchService {
|
||||
catchupConversations: 0,
|
||||
backfillConversations: 0,
|
||||
backfillCompletedConversations: 0,
|
||||
excludedConversations: 0,
|
||||
mainLoopLagMs: 0
|
||||
}
|
||||
const started: KnowledgeRuntimeStatus = {
|
||||
@@ -611,6 +621,13 @@ export class KnowledgeSearchService {
|
||||
return () => this.statusListeners.delete(listener)
|
||||
}
|
||||
|
||||
/** 会话级索引状态:覆盖度判断的依据,全局 indexLatestAt 不算证明。 */
|
||||
async getConversationIndexStates(): Promise<Record<string, KnowledgeConversationIndexState>> {
|
||||
const accountId = this.currentAccountId()
|
||||
if (!accountId) return {}
|
||||
return this.service.conversationStates({ accountId }).catch(() => ({}))
|
||||
}
|
||||
|
||||
async getStatus(): Promise<KnowledgeRuntimeStatus> {
|
||||
const accountId = this.currentAccountId()
|
||||
if (!accountId) return this.emptyStatus('')
|
||||
@@ -622,9 +639,102 @@ export class KnowledgeSearchService {
|
||||
return chat.getSelfAccountInfo()?.wxid || chat.getCurrentAccountRoot()
|
||||
}
|
||||
|
||||
/** 当前账号的索引范围;缺省(老用户/新账号)是全部会话。 */
|
||||
private resolveIndexScope(accountId: string): KnowledgeIndexScope {
|
||||
const scopes = loadSettings().knowledgeIndexScopes ?? {}
|
||||
return normalizeKnowledgeIndexScope(scopes[accountId])
|
||||
}
|
||||
|
||||
/** 后台重索引也要过这一关,否则排除掉的群会因一次 OCR 完成被整段建回来。 */
|
||||
private isIndexableConversation(accountId: string, conversationId: string): boolean {
|
||||
const scope = this.resolveIndexScope(accountId)
|
||||
return scope.mode === 'all' || scope.conversationIds.includes(conversationId)
|
||||
}
|
||||
|
||||
/** 分页读 + 分批写:已提交的批次连同续跑位置保留,下一遍从该边界继续。 */
|
||||
private async backfillConversation(
|
||||
accountId: string,
|
||||
contact: { md5: string },
|
||||
options: { sourceHighWaterHint?: number; fromScratch?: boolean },
|
||||
onProgress: (processed: number, chunks: number) => void
|
||||
): Promise<{ processed: number; scanned: number; latest: number; cancelled: boolean }> {
|
||||
const conversationId = contact.md5
|
||||
const start = await this.service.startConversationStream(
|
||||
{
|
||||
accountId,
|
||||
conversationId,
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
completeSnapshot: true,
|
||||
// 后台重索引是「整段重建」,不能接上次断点 —— 否则只补半段还声明完整。
|
||||
...(options.fromScratch ? { resume: null } : {})
|
||||
},
|
||||
(progress) => onProgress(progress.processedMessages, progress.indexedChunks)
|
||||
)
|
||||
|
||||
let scanned = 0
|
||||
let latest = 0
|
||||
let cancelled = false
|
||||
try {
|
||||
for await (const page of chat.iterateMessagesAsync(conversationId, {
|
||||
pageSize: KNOWLEDGE_INDEX_PAGE_SIZE,
|
||||
// 续跑边界来自 `chunk.endTime`,单位是**毫秒**(消息 createTime),
|
||||
// 不能再乘 1000;分页层自己转秒。
|
||||
sinceMs: start.resumedFrom ?? undefined
|
||||
})) {
|
||||
if (this.cancelRequested) {
|
||||
cancelled = true
|
||||
break
|
||||
}
|
||||
await this.interactiveIdle
|
||||
if (page.failedStores.length) {
|
||||
throw new Error(`历史消息分片读取失败:${page.failedStores.join(', ')}`)
|
||||
}
|
||||
if (!page.messages.length) continue
|
||||
scanned += page.messages.length
|
||||
for (const message of page.messages) {
|
||||
const createTime = (message.createTime || 0) * 1000
|
||||
if (createTime > latest) latest = createTime
|
||||
}
|
||||
const sourceMessages = page.messages
|
||||
.map((message) => this.toSourceMessage(accountId, conversationId, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
await this.service.pushConversationBatch({
|
||||
accountId,
|
||||
conversationId,
|
||||
messages: sourceMessages
|
||||
})
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
await this.service.abortConversationStream({ accountId, conversationId })
|
||||
return { processed: 0, scanned, latest, cancelled: true }
|
||||
}
|
||||
|
||||
const result = await this.service.finishConversationStream({
|
||||
accountId,
|
||||
conversationId,
|
||||
sourceHighWaterTime: Math.max(options.sourceHighWaterHint ?? 0, latest)
|
||||
})
|
||||
return { processed: result.processedMessages, scanned, latest, cancelled: result.cancelled }
|
||||
} catch (error) {
|
||||
await this.service
|
||||
.abortConversationStream({ accountId, conversationId })
|
||||
.catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async indexAccount(accountId: string): Promise<void> {
|
||||
// 整遍后台索引走 background 通道:交互查询可以插到它前面,不至于被 pass 拖慢。
|
||||
const contacts = await this.listContacts('background')
|
||||
const allContacts = await this.listContacts('background')
|
||||
const scope = this.resolveIndexScope(accountId)
|
||||
// `selected` 且一个都没勾时结果是空集 —— 这是「不索引任何会话」,不是「全部」。
|
||||
const contacts =
|
||||
scope.mode === 'all'
|
||||
? allContacts
|
||||
: allContacts.filter((contact) => scope.conversationIds.includes(contact.md5))
|
||||
const excludedByScope = allContacts.length - contacts.length
|
||||
const startedAt = Date.now()
|
||||
// 源侧每会话最后活跃时间(零额外 WCDB 调用:直接来自 Session 列表)。
|
||||
const activity = chat.getConversationActivityMs()
|
||||
@@ -674,6 +784,7 @@ export class KnowledgeSearchService {
|
||||
|
||||
if (this.passProgress) {
|
||||
this.passProgress.totalConversations = contacts.length
|
||||
this.passProgress.excludedConversations = excludedByScope
|
||||
this.passProgress.startedAt = startedAt
|
||||
this.passProgress.skippedConversations = skippedConversations
|
||||
this.passProgress.catchupConversations = catchUpContacts.length
|
||||
@@ -716,75 +827,106 @@ export class KnowledgeSearchService {
|
||||
const sinceTime = isDelta
|
||||
? Math.max(0, Math.floor((mark - DELTA_OVERLAP_MS) / 1000))
|
||||
: undefined
|
||||
const messages = await this.listMessages(contact.md5, sinceTime, undefined, 'background')
|
||||
scannedMessages += messages.length
|
||||
// 这一遍扫到的源数据最新时间:用**未过滤**的原始消息计算,
|
||||
// 这样「不可建模」的消息(图片/空正文)不会让 freshness 口径偏旧。
|
||||
let conversationProcessed = 0
|
||||
let conversationScanned = 0
|
||||
let conversationLatest = 0
|
||||
for (const message of messages) {
|
||||
const createTime = (message.createTime || 0) * 1000
|
||||
if (createTime > conversationLatest) conversationLatest = createTime
|
||||
}
|
||||
if (conversationLatest > sourceLatestAt) sourceLatestAt = conversationLatest
|
||||
const sourceMessages = messages
|
||||
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
// 记录**源侧**边界(而不是索引里最后一条可建模消息的时间):
|
||||
// 否则"最后一条恰好落在图片上"的会话会永远被判成有新消息,增量永远跳不过它。
|
||||
//
|
||||
// 安全阀:delta 范围读**空**、但源侧声称有新消息 → **不推进** checkpoint。
|
||||
// 宁可下一遍重试,也不让"一次可疑的空读"升级成"谎报已覆盖"(那会静默丢消息)。
|
||||
const suspiciousEmptyDelta =
|
||||
isDelta && messages.length === 0 && (previousActivity ?? 0) > (mark ?? 0)
|
||||
const sourceHighWaterTime = suspiciousEmptyDelta
|
||||
? undefined
|
||||
: Math.max(previousActivity ?? 0, conversationLatest)
|
||||
const result = await this.service.index(
|
||||
{
|
||||
accountId,
|
||||
conversations: [
|
||||
{
|
||||
conversationId: contact.md5,
|
||||
// delta 模式下绝不能声明"完整快照":否则 store 会把"不在 delta 里的历史消息"
|
||||
// 误判为被删除,从而整段重建这个会话,增量就白做了。
|
||||
completeSnapshot: !isDelta,
|
||||
messages: sourceMessages,
|
||||
...(sourceHighWaterTime && sourceHighWaterTime > 0 ? { sourceHighWaterTime } : {})
|
||||
}
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
// 只有「这一遍真的读完了全部会话」(没有任何跳过、没有取消)才写入总量口径,
|
||||
// 否则会把增量 pass 的部分计数冒充成全量。
|
||||
//
|
||||
// 这里数的是真正被建模进索引的源消息,不是"扫到的原始条数";后者(含不可建模的
|
||||
// 图片/空正文)另走 pass 进度里的 scannedMessages。两个数字回答不同问题。
|
||||
sourceMessageCount:
|
||||
index === orderedContacts.length - 1 && skippedConversations === 0
|
||||
? indexedMessages + sourceMessages.length
|
||||
: undefined,
|
||||
sourceLatestAt:
|
||||
index === orderedContacts.length - 1 && sourceLatestAt > 0 ? sourceLatestAt : undefined
|
||||
},
|
||||
(progress) => {
|
||||
const current = this.statusByAccount.get(accountId) || this.emptyStatus(accountId)
|
||||
this.publishStatus({
|
||||
...current,
|
||||
state: current.indexedMessageCount ? 'syncing' : 'building',
|
||||
processedMessages: indexedMessages + progress.processedMessages,
|
||||
totalMessages: null,
|
||||
currentConversationId: progress.conversationId,
|
||||
estimatedRemainingMs: null,
|
||||
pass: this.passSnapshot()
|
||||
})
|
||||
let conversationCancelled = false
|
||||
|
||||
// delta 窗口的规模由「上次 checkpoint 到现在的活跃度」决定,可能是一年。
|
||||
// 先只数一次(COUNT 不解码正文),超阈值就退回分批重建,而不是把几十万条读进数组。
|
||||
const deltaCount = isDelta
|
||||
? await chat
|
||||
.countConversationMessagesAsync(contact.md5, {
|
||||
sinceMs: (sinceTime ?? 0) * 1000
|
||||
})
|
||||
.catch(() => null)
|
||||
: null
|
||||
const deltaTooLarge =
|
||||
typeof deltaCount?.count === 'number' && deltaCount.count > DELTA_STREAM_THRESHOLD
|
||||
|
||||
if (isDelta && !deltaTooLarge) {
|
||||
const messages = await this.listMessages(contact.md5, sinceTime, undefined, 'background')
|
||||
conversationScanned = messages.length
|
||||
for (const message of messages) {
|
||||
const createTime = (message.createTime || 0) * 1000
|
||||
if (createTime > conversationLatest) conversationLatest = createTime
|
||||
}
|
||||
)
|
||||
if (result.cancelled) {
|
||||
const sourceMessages = messages
|
||||
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
// 安全阀:delta 读空、但源侧声称有新消息 → 不推进 checkpoint。
|
||||
// 宁可下一遍重试,也不让"一次可疑的空读"升级成"谎报已覆盖"。
|
||||
const suspiciousEmptyDelta =
|
||||
messages.length === 0 && (previousActivity ?? 0) > (mark ?? 0)
|
||||
const sourceHighWaterTime = suspiciousEmptyDelta
|
||||
? undefined
|
||||
: Math.max(previousActivity ?? 0, conversationLatest)
|
||||
const result = await this.service.index(
|
||||
{
|
||||
accountId,
|
||||
conversations: [
|
||||
{
|
||||
conversationId: contact.md5,
|
||||
// delta 不能声明完整快照:否则不在 delta 里的历史会被判成已删除并整段重建。
|
||||
completeSnapshot: false,
|
||||
messages: sourceMessages,
|
||||
...(sourceHighWaterTime && sourceHighWaterTime > 0
|
||||
? { sourceHighWaterTime }
|
||||
: {})
|
||||
}
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||
},
|
||||
(progress) => {
|
||||
const current = this.statusByAccount.get(accountId) || this.emptyStatus(accountId)
|
||||
this.publishStatus({
|
||||
...current,
|
||||
state: current.indexedMessageCount ? 'syncing' : 'building',
|
||||
processedMessages: indexedMessages + progress.processedMessages,
|
||||
totalMessages: null,
|
||||
currentConversationId: progress.conversationId,
|
||||
estimatedRemainingMs: null,
|
||||
pass: this.passSnapshot()
|
||||
})
|
||||
}
|
||||
)
|
||||
conversationCancelled = result.cancelled
|
||||
conversationProcessed = result.cancelled ? result.processedMessages : sourceMessages.length
|
||||
} else {
|
||||
const backfill = await this.backfillConversation(
|
||||
accountId,
|
||||
contact,
|
||||
{ sourceHighWaterHint: previousActivity },
|
||||
(processed) => {
|
||||
if (this.passProgress) this.passProgress.currentConversationProcessed = processed
|
||||
const current = this.statusByAccount.get(accountId) || this.emptyStatus(accountId)
|
||||
this.publishStatus({
|
||||
...current,
|
||||
state: current.indexedMessageCount ? 'syncing' : 'building',
|
||||
processedMessages: indexedMessages + processed,
|
||||
totalMessages: null,
|
||||
currentConversationId: contact.md5,
|
||||
estimatedRemainingMs: null,
|
||||
pass: this.passSnapshot()
|
||||
})
|
||||
}
|
||||
)
|
||||
conversationCancelled = backfill.cancelled
|
||||
conversationProcessed = backfill.processed
|
||||
conversationScanned = backfill.scanned
|
||||
conversationLatest = backfill.latest
|
||||
}
|
||||
|
||||
scannedMessages += conversationScanned
|
||||
// 用未过滤的原始消息算 freshness,图片/空正文才不会让口径偏旧。
|
||||
if (conversationLatest > sourceLatestAt) sourceLatestAt = conversationLatest
|
||||
if (conversationCancelled) {
|
||||
cancelled = true
|
||||
indexedMessages += result.processedMessages
|
||||
indexedMessages += conversationProcessed
|
||||
break
|
||||
}
|
||||
indexedMessages += sourceMessages.length
|
||||
indexedMessages += conversationProcessed
|
||||
if (isBackfill) backfillCompletedConversations += 1
|
||||
if (this.passProgress) {
|
||||
this.passProgress.scannedMessages = scannedMessages
|
||||
@@ -804,12 +946,24 @@ export class KnowledgeSearchService {
|
||||
})
|
||||
}
|
||||
if (cancelled && this.passProgress) this.passProgress.phase = 'cancelled'
|
||||
// 全局源口径只在「读完全部会话」时可信:有跳过或取消时写进去,下一秒就会被
|
||||
// 当成"源侧总量"用来算覆盖率。
|
||||
if (!cancelled && skippedConversations === 0 && sourceLatestAt > 0) {
|
||||
await this.service
|
||||
.writeSourceTotals({
|
||||
accountId,
|
||||
sourceMessageCount: indexedMessages,
|
||||
sourceLatestAt
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
// 一遍 pass 一行汇总(低频、只在结束时输出一次)。这些数字同时喂给 UI 的 pass 进度;
|
||||
// lag 输出分位数而不是单点,因为"最大值看着还行"不能说明没有 stall。
|
||||
console.info(
|
||||
`[Knowledge] pass ${cancelled ? 'cancelled' : 'done'} conversations=${contacts.length} ` +
|
||||
`skipped=${skippedConversations} scanned=${scannedMessages} indexed=${indexedMessages} ` +
|
||||
`catchup=${catchUpContacts.length} backfill=${backfillContacts.length}/${backfillCompletedConversations} ` +
|
||||
`excludedByScope=${excludedByScope} ` +
|
||||
`elapsedMs=${Date.now() - startedAt} ` +
|
||||
`lagP50=${this.lagStats?.p50 ?? 0} lagP95=${this.lagStats?.p95 ?? 0} ` +
|
||||
`lagP99=${this.lagStats?.p99 ?? 0} lagMax=${this.lagStats?.max ?? this.lagMaxMs} ` +
|
||||
@@ -1187,23 +1341,14 @@ export class KnowledgeSearchService {
|
||||
if (!chat.isReady()) return
|
||||
const accountId = this.currentAccountId()
|
||||
if (!accountId) return
|
||||
// OCR 完成不是绕过索引范围的理由:被排除的会话不该因为一次识别又被整段建回来。
|
||||
if (!this.isIndexableConversation(accountId, conversationId)) return
|
||||
const activeIndex = this.indexing.get(accountId)
|
||||
if (activeIndex) await activeIndex
|
||||
const contacts = await this.listContacts()
|
||||
const contact = contacts.find((item) => item.md5 === conversationId)
|
||||
if (!contact) return
|
||||
const messages = await this.listMessages(contact.md5, undefined, undefined, 'background')
|
||||
const sourceMessages = messages
|
||||
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
await this.service.index({
|
||||
accountId,
|
||||
conversations: [
|
||||
{ conversationId: contact.md5, completeSnapshot: true, messages: sourceMessages }
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||
})
|
||||
await this.backfillConversation(accountId, contact, { fromScratch: true }, () => undefined)
|
||||
await this.refreshStatus(accountId)
|
||||
}
|
||||
|
||||
@@ -1223,39 +1368,10 @@ export class KnowledgeSearchService {
|
||||
const contacts = await this.listContacts()
|
||||
const contact = contacts.find((item) => item.m_nsUsrName === update.reference.sessionId)
|
||||
if (!contact) return
|
||||
const messages = await this.listMessages(contact.md5)
|
||||
const sourceMessages = messages
|
||||
.map((message) => {
|
||||
const reference = this.voiceReferenceFromMessage(message)
|
||||
const transcriptOverride =
|
||||
reference && voiceMessageIdentity(reference) === update.messageIdentity
|
||||
? update.transcript
|
||||
: undefined
|
||||
const stateOverride =
|
||||
reference && voiceMessageIdentity(reference) === update.messageIdentity
|
||||
? update.state
|
||||
: undefined
|
||||
return this.toSourceMessage(
|
||||
accountId,
|
||||
contact.md5,
|
||||
message,
|
||||
transcriptOverride,
|
||||
stateOverride
|
||||
)
|
||||
})
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
await this.service.index({
|
||||
accountId,
|
||||
conversations: [
|
||||
{
|
||||
conversationId: contact.md5,
|
||||
completeSnapshot: true,
|
||||
messages: sourceMessages
|
||||
}
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||
})
|
||||
// 转写结果已写进语音缓存,`toSourceMessage` 会通过 resolver 取到最新文本,
|
||||
// 所以这里不需要(也不应该)为了覆盖一条消息而重读整会话。
|
||||
if (!this.isIndexableConversation(accountId, contact.md5)) return
|
||||
await this.backfillConversation(accountId, contact, { fromScratch: true }, () => undefined)
|
||||
await this.refreshStatus(accountId)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,15 @@ import type {
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchRequest,
|
||||
KnowledgeSearchResult,
|
||||
KnowledgeStatusRequest
|
||||
KnowledgeStatusRequest,
|
||||
KnowledgeConversationIndexState,
|
||||
KnowledgeConversationStatesRequest,
|
||||
KnowledgeSourceTotalsRequest,
|
||||
KnowledgeStreamBatchRequest,
|
||||
KnowledgeStreamConversationRequest,
|
||||
KnowledgeStreamResult,
|
||||
KnowledgeStreamStartRequest,
|
||||
KnowledgeStreamStartResult
|
||||
} from '../../shared/knowledge'
|
||||
import { KnowledgeWorkerHost } from './knowledge-worker-host'
|
||||
|
||||
@@ -32,6 +40,39 @@ export class KnowledgeService {
|
||||
return this.worker.index({ ...request, databaseRoot: this.databaseRoot }, onProgress)
|
||||
}
|
||||
|
||||
/** 开始一个会话的分批索引:消息不随请求下发,由调用方逐批推送。 */
|
||||
startConversationStream(
|
||||
request: Omit<KnowledgeStreamStartRequest, 'databaseRoot'>,
|
||||
onProgress?: (progress: KnowledgeIndexProgress) => void
|
||||
): Promise<KnowledgeStreamStartResult> {
|
||||
return this.worker.startConversationStream(
|
||||
{ ...request, databaseRoot: this.databaseRoot },
|
||||
onProgress
|
||||
)
|
||||
}
|
||||
|
||||
pushConversationBatch(
|
||||
request: Omit<KnowledgeStreamBatchRequest, 'databaseRoot'>
|
||||
): Promise<void> {
|
||||
return this.worker.pushConversationBatch({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
finishConversationStream(
|
||||
request: Omit<KnowledgeStreamConversationRequest, 'databaseRoot'>
|
||||
): Promise<KnowledgeStreamResult> {
|
||||
return this.worker.finishConversationStream({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
abortConversationStream(
|
||||
request: Omit<KnowledgeStreamConversationRequest, 'databaseRoot'>
|
||||
): Promise<void> {
|
||||
return this.worker.abortConversationStream({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
writeSourceTotals(request: Omit<KnowledgeSourceTotalsRequest, 'databaseRoot'>): Promise<void> {
|
||||
return this.worker.writeSourceTotals({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
preflight(
|
||||
request: Omit<KnowledgeCapacityPreflightRequest, 'databaseRoot'>
|
||||
): Promise<KnowledgeCapacityPreflight> {
|
||||
@@ -50,6 +91,13 @@ export class KnowledgeService {
|
||||
return this.worker.status({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
/** 每个会话的索引状态(是否完整覆盖),查询侧据此判断覆盖度。 */
|
||||
conversationStates(
|
||||
request: Omit<KnowledgeConversationStatesRequest, 'databaseRoot'>
|
||||
): Promise<Record<string, KnowledgeConversationIndexState>> {
|
||||
return this.worker.conversationStates({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
/** 每个会话已经索引到的源侧时刻(epoch ms);增量 pass 用它跳过没有变化的会话。 */
|
||||
highWaterMarks(request: Omit<KnowledgeStatusRequest, 'databaseRoot'>): Promise<Record<string, number>> {
|
||||
return this.worker.highWaterMarks({ ...request, databaseRoot: this.databaseRoot })
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
KnowledgeCapacityPreflight,
|
||||
KnowledgeCapacityPreflightRequest,
|
||||
KnowledgeChunk,
|
||||
KnowledgeChunkerConfig,
|
||||
KnowledgeConversationRetrieval,
|
||||
KnowledgeEvidence,
|
||||
KnowledgeVoiceCoverage,
|
||||
@@ -18,18 +19,29 @@ import type {
|
||||
KnowledgeNormalizedMessage,
|
||||
KnowledgeQuery,
|
||||
KnowledgeSearchTimings,
|
||||
KnowledgeSearchResult
|
||||
KnowledgeSearchResult,
|
||||
KnowledgeSourceMessage,
|
||||
KnowledgeConversationIndexState
|
||||
} from '../../shared/knowledge'
|
||||
import {
|
||||
emptyKnowledgeSearchTimings,
|
||||
KNOWLEDGE_SCHEMA_VERSION,
|
||||
toEvidenceDisplayText
|
||||
} from '../../shared/knowledge'
|
||||
import { chunkConversation } from './chunker'
|
||||
import { chunkConversation, createChunkStreamer } from './chunker'
|
||||
import { normalizeKnowledgeMessage } from './normalizer'
|
||||
|
||||
type DbRow = Record<string, unknown>
|
||||
|
||||
export interface KnowledgeStreamIndexResult {
|
||||
processedMessages: number
|
||||
chunkCount: number
|
||||
cancelled: boolean
|
||||
/** 最后一条已提交收盘 chunk 的结束秒;取消或失败后从这里续跑。 */
|
||||
resumeTime: number | null
|
||||
resumeMessageIds: string[]
|
||||
}
|
||||
|
||||
const YIELD_EVERY = 500
|
||||
const MAX_SAFE_ACCOUNT_SEGMENT = /^[a-f0-9]{32}$/
|
||||
const MAX_CONVERSATION_SUMMARY_SOURCE_MESSAGES = 2_000
|
||||
@@ -1048,7 +1060,10 @@ export class KnowledgeStore {
|
||||
indexed_message_count INTEGER NOT NULL DEFAULT 0,
|
||||
complete_snapshot INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
updated_at INTEGER NOT NULL
|
||||
updated_at INTEGER NOT NULL,
|
||||
source_high_water_time INTEGER,
|
||||
backfill_resume_time INTEGER,
|
||||
backfill_resume_message_ids TEXT
|
||||
) STRICT;
|
||||
`)
|
||||
const stateColumns = new Set(asRows(this.database.prepare('PRAGMA table_info(knowledge_index_state)').all()).map((row) => String(row.name)))
|
||||
@@ -1058,6 +1073,16 @@ export class KnowledgeStore {
|
||||
if (!stateColumns.has('source_high_water_time')) {
|
||||
this.database.exec('ALTER TABLE knowledge_index_state ADD COLUMN source_high_water_time INTEGER')
|
||||
}
|
||||
// 分批回填的续跑位置:最后一条**已提交**收盘 chunk 的结束秒与它的消息 id。
|
||||
// 进程退出后从这里重读并跳过这些 id,重切结果才能与不间断运行一致。
|
||||
if (!stateColumns.has('backfill_resume_time')) {
|
||||
this.database.exec('ALTER TABLE knowledge_index_state ADD COLUMN backfill_resume_time INTEGER')
|
||||
}
|
||||
if (!stateColumns.has('backfill_resume_message_ids')) {
|
||||
this.database.exec(
|
||||
'ALTER TABLE knowledge_index_state ADD COLUMN backfill_resume_message_ids TEXT'
|
||||
)
|
||||
}
|
||||
const messageColumns = new Set(
|
||||
asRows(this.database.prepare('PRAGMA table_info(knowledge_messages)').all()).map((row) =>
|
||||
String(row.name)
|
||||
@@ -1074,7 +1099,19 @@ export class KnowledgeStore {
|
||||
if (!messageColumns.has('image_ocr_text')) {
|
||||
this.database.exec('ALTER TABLE knowledge_messages ADD COLUMN image_ocr_text TEXT')
|
||||
}
|
||||
this.writeMetaIfMissing('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||
const storedSchemaVersion = Number(this.readMeta('schema_version') ?? 0)
|
||||
if (storedSchemaVersion > 0 && storedSchemaVersion !== KNOWLEDGE_SCHEMA_VERSION) {
|
||||
// 身份规则变了:旧 message_id 与新身份完全失配,保留等于留下一堆指向错误消息的证据。
|
||||
// 索引是派生的、可重建,这里整体作废,让下一遍 pass 按新身份重建。
|
||||
this.database.exec(
|
||||
'DELETE FROM knowledge_chunks; DELETE FROM knowledge_messages; DELETE FROM knowledge_index_state;'
|
||||
)
|
||||
this.database.exec('DROP TABLE IF EXISTS knowledge_fts')
|
||||
this.createFtsTable()
|
||||
this.writeMeta('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||
} else {
|
||||
this.writeMetaIfMissing('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||
}
|
||||
const storedAccount = this.readMeta('account_id')
|
||||
if (storedAccount && storedAccount !== this.accountId) {
|
||||
throw new Error('Knowledge database account isolation check failed')
|
||||
@@ -1244,8 +1281,293 @@ export class KnowledgeStore {
|
||||
}
|
||||
}
|
||||
|
||||
private async writeMessageLedger(
|
||||
/** 分批索引:不持有整会话消息;旧 chunk 不预删,取消后原索引仍可用。 */
|
||||
async indexConversationStreaming(
|
||||
conversationId: string,
|
||||
batches: AsyncIterable<readonly KnowledgeSourceMessage[]>,
|
||||
chunker: KnowledgeChunkerConfig,
|
||||
options: {
|
||||
completeSnapshot: boolean
|
||||
sourceHighWaterTime?: number
|
||||
/** 上次中断位置;从该秒重读并跳过这些已提交消息。 */
|
||||
resume?: { time: number; messageIds: string[] }
|
||||
},
|
||||
signal: AbortSignal | undefined,
|
||||
onProgress: (processed: number, chunks: number) => void
|
||||
): Promise<KnowledgeStreamIndexResult> {
|
||||
if (!conversationId) throw new Error('Knowledge conversation id is required')
|
||||
const streamer = createChunkStreamer(chunker)
|
||||
const passStartedAt = Date.now()
|
||||
const skipIds = new Set(options.resume?.messageIds ?? [])
|
||||
// 续跑只重建边界之后的部分;边界那一秒已提交的消息必须整秒排除,
|
||||
// 否则重切出的 chunk 会与已提交的那一个重复。
|
||||
const rebuildFromTime = options.resume ? options.resume.time + 1 : 0
|
||||
if (options.resume) {
|
||||
const rows = asRows(
|
||||
this.database
|
||||
.prepare(
|
||||
'SELECT message_id FROM knowledge_messages WHERE conversation_id = ? AND create_time = ?'
|
||||
)
|
||||
.all(conversationId, options.resume.time)
|
||||
)
|
||||
for (const row of rows) skipIds.add(String(row.message_id))
|
||||
}
|
||||
let processed = 0
|
||||
let chunkCount = 0
|
||||
let resumeTime = options.resume?.time ?? null
|
||||
let resumeIds: string[] = options.resume?.messageIds?.slice() ?? []
|
||||
|
||||
const commitChunks = (chunks: KnowledgeChunk[], now: number): void => {
|
||||
for (const chunk of chunks) {
|
||||
this.upsertChunkIdempotent(chunk, now)
|
||||
chunkCount += 1
|
||||
resumeTime = chunk.endTime
|
||||
resumeIds = chunk.messageIds.slice()
|
||||
}
|
||||
}
|
||||
|
||||
const commitBatch = async (normalized: KnowledgeNormalizedMessage[]): Promise<void> => {
|
||||
this.database.exec('BEGIN IMMEDIATE')
|
||||
try {
|
||||
await this.writeMessageLedger(conversationId, normalized, false, signal, (count) => {
|
||||
onProgress(processed + count, chunkCount)
|
||||
})
|
||||
commitChunks(streamer.push(normalized), Date.now())
|
||||
this.writeBackfillCursor(
|
||||
conversationId,
|
||||
chunker.version,
|
||||
processed,
|
||||
resumeTime,
|
||||
resumeIds
|
||||
)
|
||||
this.database.exec('COMMIT')
|
||||
} catch (error) {
|
||||
this.database.exec('ROLLBACK')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
try {
|
||||
for await (const batch of batches) {
|
||||
this.assertNotAborted(signal)
|
||||
if (!batch.length) continue
|
||||
const normalized: KnowledgeNormalizedMessage[] = []
|
||||
for (const message of batch) {
|
||||
if (message.accountId !== this.accountId) {
|
||||
throw new Error('Knowledge source account does not match database')
|
||||
}
|
||||
if (message.conversationId !== conversationId) {
|
||||
throw new Error('Knowledge source conversation does not match request')
|
||||
}
|
||||
const item = normalizeKnowledgeMessage(message)
|
||||
// 续跑重读到的已提交消息不能再进入切分,否则会产生内容重复的 chunk。
|
||||
if (skipIds.delete(item.messageId)) continue
|
||||
normalized.push(item)
|
||||
}
|
||||
processed += normalized.length
|
||||
// 空批次也要落一次游标:上游可能连续返回"全是已提交消息"的页。
|
||||
if (normalized.length) await commitBatch(normalized)
|
||||
onProgress(processed, chunkCount)
|
||||
}
|
||||
|
||||
this.database.exec('BEGIN IMMEDIATE')
|
||||
try {
|
||||
commitChunks(streamer.drain(), Date.now())
|
||||
await this.purgeStaleChunks(
|
||||
conversationId,
|
||||
chunker.version,
|
||||
rebuildFromTime,
|
||||
passStartedAt,
|
||||
signal
|
||||
)
|
||||
this.upsertState(
|
||||
conversationId,
|
||||
chunker.version,
|
||||
'ready',
|
||||
resumeTime,
|
||||
processed,
|
||||
null,
|
||||
options.completeSnapshot,
|
||||
options.sourceHighWaterTime ?? null
|
||||
)
|
||||
this.clearBackfillCursor(conversationId)
|
||||
this.database.exec('COMMIT')
|
||||
} catch (error) {
|
||||
this.database.exec('ROLLBACK')
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal?.aborted) {
|
||||
cancelled = true
|
||||
} else {
|
||||
this.markBackfillFailed(conversationId, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return { processedMessages: processed, chunkCount, cancelled, resumeTime, resumeMessageIds: resumeIds }
|
||||
}
|
||||
|
||||
/** 每个会话的索引状态快照:覆盖度判断只能看它,不能看全局最新时间。 */
|
||||
readConversationIndexStates(): Record<string, KnowledgeConversationIndexState> {
|
||||
const rows = asRows(
|
||||
this.database
|
||||
.prepare(
|
||||
`SELECT conversation_id, state, complete_snapshot, source_high_water_time, indexed_message_count
|
||||
FROM knowledge_index_state`
|
||||
)
|
||||
.all()
|
||||
)
|
||||
const result: Record<string, KnowledgeConversationIndexState> = {}
|
||||
for (const row of rows) {
|
||||
const highWater = Number(row.source_high_water_time)
|
||||
result[String(row.conversation_id)] = {
|
||||
state: String(row.state ?? ''),
|
||||
completeSnapshot: Number(row.complete_snapshot) === 1,
|
||||
sourceHighWaterTime: Number.isFinite(highWater) && highWater > 0 ? highWater : null,
|
||||
indexedMessageCount: Number(row.indexed_message_count) || 0
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** 分批回填结束后补写源侧边界;只前进,不回退。 */
|
||||
advanceSourceHighWater(conversationId: string, value: number): void {
|
||||
if (!Number.isFinite(value) || value <= 0) return
|
||||
this.database
|
||||
.prepare(
|
||||
`UPDATE knowledge_index_state
|
||||
SET source_high_water_time = MAX(COALESCE(source_high_water_time, 0), ?),
|
||||
updated_at = ?
|
||||
WHERE conversation_id = ?`
|
||||
)
|
||||
.run(Math.floor(value), Date.now(), conversationId)
|
||||
}
|
||||
|
||||
/** 整遍读完时才刷新的全局口径;分批 pass 不得调用。 */
|
||||
writeSourceTotals(sourceMessageCount: number, sourceLatestAt?: number): void {
|
||||
this.writeMeta('source_message_count', String(sourceMessageCount))
|
||||
this.refreshStatsSnapshot()
|
||||
if (typeof sourceLatestAt === 'number' && sourceLatestAt > 0) {
|
||||
this.writeMeta('source_latest_at', String(Math.floor(sourceLatestAt)))
|
||||
}
|
||||
}
|
||||
|
||||
/** 上次中断的分页位置;没有可复用的位置时返回 null。 */
|
||||
readBackfillResume(conversationId: string): { time: number; messageIds: string[] } | null {
|
||||
const row = this.database
|
||||
.prepare(
|
||||
'SELECT backfill_resume_time, backfill_resume_message_ids FROM knowledge_index_state WHERE conversation_id = ?'
|
||||
)
|
||||
.get(conversationId) as DbRow | undefined
|
||||
const time = Number(row?.backfill_resume_time)
|
||||
if (!Number.isFinite(time) || time <= 0) return null
|
||||
let messageIds: string[] = []
|
||||
try {
|
||||
const parsed = JSON.parse(String(row?.backfill_resume_message_ids || '[]'))
|
||||
if (Array.isArray(parsed)) messageIds = parsed.map((value) => String(value))
|
||||
} catch {
|
||||
messageIds = []
|
||||
}
|
||||
return { time, messageIds }
|
||||
}
|
||||
|
||||
private writeBackfillCursor(
|
||||
conversationId: string,
|
||||
chunkerVersion: string,
|
||||
messageCount: number,
|
||||
resumeTime: number | null,
|
||||
resumeMessageIds: string[]
|
||||
): void {
|
||||
this.database
|
||||
.prepare(
|
||||
`INSERT INTO knowledge_index_state (
|
||||
conversation_id, account_id, chunker_version, state, high_water_time,
|
||||
indexed_message_count, complete_snapshot, last_error, updated_at,
|
||||
backfill_resume_time, backfill_resume_message_ids
|
||||
) VALUES (?, ?, ?, 'backfilling', NULL, ?, 0, NULL, ?, ?, ?)
|
||||
ON CONFLICT(conversation_id) DO UPDATE SET
|
||||
chunker_version = excluded.chunker_version,
|
||||
state = 'backfilling',
|
||||
indexed_message_count = excluded.indexed_message_count,
|
||||
complete_snapshot = 0,
|
||||
updated_at = excluded.updated_at,
|
||||
backfill_resume_time = excluded.backfill_resume_time,
|
||||
backfill_resume_message_ids = excluded.backfill_resume_message_ids`
|
||||
)
|
||||
.run(
|
||||
conversationId,
|
||||
this.accountId,
|
||||
chunkerVersion,
|
||||
messageCount,
|
||||
Date.now(),
|
||||
resumeTime,
|
||||
encodedJson(resumeMessageIds)
|
||||
)
|
||||
}
|
||||
|
||||
private clearBackfillCursor(conversationId: string): void {
|
||||
this.database
|
||||
.prepare(
|
||||
`UPDATE knowledge_index_state
|
||||
SET backfill_resume_time = NULL, backfill_resume_message_ids = NULL
|
||||
WHERE conversation_id = ?`
|
||||
)
|
||||
.run(conversationId)
|
||||
}
|
||||
|
||||
private markBackfillFailed(conversationId: string, error: unknown): void {
|
||||
try {
|
||||
this.database
|
||||
.prepare(
|
||||
`UPDATE knowledge_index_state
|
||||
SET state = 'partial', last_error = ?, updated_at = ?
|
||||
WHERE conversation_id = ?`
|
||||
)
|
||||
.run(error instanceof Error ? error.message : String(error), Date.now(), conversationId)
|
||||
} catch {
|
||||
// 失败标记本身失败时保留原状态,调用方仍能从异常得知结果。
|
||||
}
|
||||
}
|
||||
|
||||
/** 两个条件缺一不可:漏掉 `end_time >= fromEndTime` 会把已提交的前半段整段删掉。 */
|
||||
private async purgeStaleChunks(
|
||||
conversationId: string,
|
||||
chunkerVersion: string,
|
||||
fromEndTime: number,
|
||||
beforeUpdatedAt: number,
|
||||
signal: AbortSignal | undefined
|
||||
): Promise<void> {
|
||||
const select = this.database.prepare(
|
||||
`SELECT rowid, text FROM knowledge_chunks
|
||||
WHERE conversation_id = ? AND chunker_version = ? AND updated_at < ? AND end_time >= ?
|
||||
LIMIT 200`
|
||||
)
|
||||
const remove = this.database.prepare('DELETE FROM knowledge_chunks WHERE rowid = ?')
|
||||
while (true) {
|
||||
this.assertNotAborted(signal)
|
||||
const rows = asRows(select.all(conversationId, chunkerVersion, beforeUpdatedAt, fromEndTime))
|
||||
if (!rows.length) break
|
||||
for (const row of rows) {
|
||||
this.deleteFtsRow(Number(row.rowid), String(row.text))
|
||||
remove.run(Number(row.rowid))
|
||||
}
|
||||
await waitForWorkerTurn()
|
||||
}
|
||||
}
|
||||
|
||||
private upsertChunkIdempotent(chunk: KnowledgeChunk, now: number): void {
|
||||
const existing = this.database
|
||||
.prepare('SELECT rowid FROM knowledge_chunks WHERE chunk_id = ?')
|
||||
.get(chunk.chunkId) as DbRow | undefined
|
||||
// chunk_id 由 messageIds 决定,同 id 即同正文;重读时先撤旧 FTS 行再插入,
|
||||
// 否则 FTS5 会对已存在的 rowid 报唯一约束。
|
||||
if (existing) this.deleteFtsRow(Number(existing.rowid), chunk.text)
|
||||
this.upsertChunk(chunk, now)
|
||||
}
|
||||
|
||||
private async writeMessageLedger( conversationId: string,
|
||||
messages: KnowledgeNormalizedMessage[],
|
||||
completeSnapshot: boolean,
|
||||
signal: AbortSignal | undefined,
|
||||
|
||||
@@ -12,6 +12,14 @@ import type {
|
||||
KnowledgeSearchRequest,
|
||||
KnowledgeSearchResult,
|
||||
KnowledgeStatusRequest,
|
||||
KnowledgeConversationIndexState,
|
||||
KnowledgeConversationStatesRequest,
|
||||
KnowledgeSourceTotalsRequest,
|
||||
KnowledgeStreamBatchRequest,
|
||||
KnowledgeStreamConversationRequest,
|
||||
KnowledgeStreamResult,
|
||||
KnowledgeStreamStartRequest,
|
||||
KnowledgeStreamStartResult,
|
||||
KnowledgeWorkerRequest,
|
||||
KnowledgeWorkerResponse
|
||||
} from '../../shared/knowledge'
|
||||
@@ -22,7 +30,10 @@ type WorkerResult =
|
||||
| KnowledgeSearchResult
|
||||
| KnowledgeRuntimeStatus
|
||||
| KnowledgeMemberStatsResult
|
||||
| KnowledgeStreamStartResult
|
||||
| KnowledgeStreamResult
|
||||
| { marks: Record<string, number> }
|
||||
| { accepted: true }
|
||||
| { removed: true }
|
||||
type PendingRequest = {
|
||||
resolve: (result: WorkerResult) => void
|
||||
@@ -48,6 +59,8 @@ export class KnowledgeWorkerHost {
|
||||
* 精确地只中止索引,而**不会**影响任何并发进行的查询请求。
|
||||
*/
|
||||
private activeIndexRequestId: string | null = null
|
||||
/** 进度消息回带的是已 resolve 的 streamStart requestId,不能靠 `pending` 找回调。 */
|
||||
private readonly streamProgress = new Map<string, (progress: KnowledgeIndexProgress) => void>()
|
||||
|
||||
constructor(private readonly workerPath: string) {}
|
||||
|
||||
@@ -72,6 +85,16 @@ export class KnowledgeWorkerHost {
|
||||
return this.request('status', payload) as Promise<KnowledgeRuntimeStatus>
|
||||
}
|
||||
|
||||
/** 每个会话的索引状态;覆盖度判断的唯一依据。 */
|
||||
conversationStates(
|
||||
payload: KnowledgeConversationStatesRequest
|
||||
): Promise<Record<string, KnowledgeConversationIndexState>> {
|
||||
return this.request('conversationStates', payload).then(
|
||||
(result) =>
|
||||
(result as { states?: Record<string, KnowledgeConversationIndexState> }).states ?? {}
|
||||
)
|
||||
}
|
||||
|
||||
/** 每个会话已经索引到的源侧时刻;用于增量 pass 跳过没有变化的会话。 */
|
||||
highWaterMarks(payload: KnowledgeStatusRequest): Promise<Record<string, number>> {
|
||||
return this.request('highWater', payload as unknown as KnowledgeWorkerRequest['payload']).then(
|
||||
@@ -84,6 +107,46 @@ export class KnowledgeWorkerHost {
|
||||
return this.request('memberStats', payload) as Promise<KnowledgeMemberStatsResult>
|
||||
}
|
||||
|
||||
/** 开始一个会话的分批索引;消息由调用方逐批推送。 */
|
||||
async startConversationStream(
|
||||
payload: KnowledgeStreamStartRequest,
|
||||
onProgress?: (progress: KnowledgeIndexProgress) => void
|
||||
): Promise<KnowledgeStreamStartResult> {
|
||||
if (onProgress) this.streamProgress.set(payload.conversationId, onProgress)
|
||||
try {
|
||||
return (await this.request('streamStart', payload)) as KnowledgeStreamStartResult
|
||||
} catch (error) {
|
||||
this.streamProgress.delete(payload.conversationId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async pushConversationBatch(payload: KnowledgeStreamBatchRequest): Promise<void> {
|
||||
await this.request('streamBatch', payload)
|
||||
}
|
||||
|
||||
async finishConversationStream(
|
||||
payload: KnowledgeStreamConversationRequest
|
||||
): Promise<KnowledgeStreamResult> {
|
||||
try {
|
||||
return (await this.request('streamFinish', payload)) as KnowledgeStreamResult
|
||||
} finally {
|
||||
this.streamProgress.delete(payload.conversationId)
|
||||
}
|
||||
}
|
||||
|
||||
async writeSourceTotals(payload: KnowledgeSourceTotalsRequest): Promise<void> {
|
||||
await this.request('sourceTotals', payload)
|
||||
}
|
||||
|
||||
async abortConversationStream(payload: KnowledgeStreamConversationRequest): Promise<void> {
|
||||
try {
|
||||
await this.request('streamAbort', payload)
|
||||
} finally {
|
||||
this.streamProgress.delete(payload.conversationId)
|
||||
}
|
||||
}
|
||||
|
||||
/** 只中止正在跑的索引任务,返回是否真的有任务被中止。 */
|
||||
async cancelActiveIndex(): Promise<boolean> {
|
||||
const target = this.activeIndexRequestId
|
||||
@@ -148,9 +211,16 @@ export class KnowledgeWorkerHost {
|
||||
child.on('message', (message: KnowledgeWorkerResponse) => {
|
||||
if (message?.version !== 1) return
|
||||
if (message.type === 'progress') {
|
||||
const progress = message.payload as KnowledgeIndexProgress | undefined
|
||||
if (!progress) return
|
||||
const pending = this.pending.get(message.requestId)
|
||||
if (pending && message.payload)
|
||||
pending.onProgress?.(message.payload as KnowledgeIndexProgress)
|
||||
if (pending?.onProgress) {
|
||||
pending.onProgress(progress)
|
||||
return
|
||||
}
|
||||
if (progress.conversationId) {
|
||||
this.streamProgress.get(progress.conversationId)?.(progress)
|
||||
}
|
||||
return
|
||||
}
|
||||
this.finish(
|
||||
@@ -218,6 +288,7 @@ export class KnowledgeWorkerHost {
|
||||
}
|
||||
|
||||
private failAll(error: Error): void {
|
||||
this.streamProgress.clear()
|
||||
for (const requestId of this.pending.keys()) this.finish(requestId, undefined, error)
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,21 @@ import type {
|
||||
KnowledgeMemberStatsResult,
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchRequest,
|
||||
KnowledgeSourceMessage,
|
||||
KnowledgeStatusRequest,
|
||||
KnowledgeStreamBatchRequest,
|
||||
KnowledgeStreamConversationRequest,
|
||||
KnowledgeStreamResult,
|
||||
KnowledgeConversationStatesRequest,
|
||||
KnowledgeSourceTotalsRequest,
|
||||
KnowledgeStreamStartRequest,
|
||||
KnowledgeWorkerRequest,
|
||||
KnowledgeWorkerResponse
|
||||
} from '../../shared/knowledge'
|
||||
import { emptyKnowledgeSearchTimings } from '../../shared/knowledge'
|
||||
import {
|
||||
DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
emptyKnowledgeSearchTimings
|
||||
} from '../../shared/knowledge'
|
||||
import {
|
||||
KnowledgeStore,
|
||||
estimateKnowledgeCapacityPreflight,
|
||||
@@ -22,6 +32,74 @@ import { serialize } from 'v8'
|
||||
const stores = new Map<string, KnowledgeStore>()
|
||||
const controllers = new Map<string, AbortController>()
|
||||
|
||||
/** 背压:主进程拉下一页前 Worker 已提交上一批,两侧同时驻留上限是「一页 × 2」。 */
|
||||
class StreamingBatchQueue {
|
||||
private readonly buffer: KnowledgeSourceMessage[][] = []
|
||||
private wake: (() => void) | null = null
|
||||
private closed = false
|
||||
private failure: Error | null = null
|
||||
|
||||
push(batch: KnowledgeSourceMessage[]): void {
|
||||
if (this.closed) return
|
||||
this.buffer.push(batch)
|
||||
this.release()
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return
|
||||
this.closed = true
|
||||
this.release()
|
||||
}
|
||||
|
||||
fail(error: Error): void {
|
||||
if (this.failure) return
|
||||
this.failure = error
|
||||
this.closed = true
|
||||
this.release()
|
||||
}
|
||||
|
||||
private release(): void {
|
||||
const resolve = this.wake
|
||||
this.wake = null
|
||||
resolve?.()
|
||||
}
|
||||
|
||||
async *iterate(): AsyncGenerator<readonly KnowledgeSourceMessage[], void, void> {
|
||||
while (true) {
|
||||
if (!this.buffer.length && !this.closed) {
|
||||
await new Promise<void>((resolve) => {
|
||||
this.wake = resolve
|
||||
})
|
||||
}
|
||||
const next = this.buffer.shift()
|
||||
if (next) {
|
||||
yield next
|
||||
continue
|
||||
}
|
||||
if (this.failure) throw this.failure
|
||||
if (this.closed) return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type StreamSession = {
|
||||
queue: StreamingBatchQueue
|
||||
controller: AbortController
|
||||
store: KnowledgeStore
|
||||
task: Promise<{
|
||||
processedMessages: number
|
||||
chunkCount: number
|
||||
cancelled: boolean
|
||||
resumeTime: number | null
|
||||
}>
|
||||
}
|
||||
|
||||
const streamSessions = new Map<string, StreamSession>()
|
||||
|
||||
function streamKey(payload: { databaseRoot: string; accountId: string; conversationId: string }): string {
|
||||
return `${payload.databaseRoot}|${payload.accountId}|${payload.conversationId}`
|
||||
}
|
||||
|
||||
function send(
|
||||
message: KnowledgeWorkerResponse,
|
||||
transport?: KnowledgeWorkerResponse['transport']
|
||||
@@ -91,8 +169,139 @@ async function handleIndex(
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePreflight(
|
||||
async function handleStreamStart(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamStartRequest
|
||||
): Promise<void> {
|
||||
const key = streamKey(payload)
|
||||
if (streamSessions.has(key)) throw new Error('该会话已在建立索引')
|
||||
|
||||
const queue = new StreamingBatchQueue()
|
||||
const controller = new AbortController()
|
||||
const store = getStore(payload)
|
||||
// 续跑位置由 Worker 自己读:主进程只知道"这一遍要重建",不该关心分页细节。
|
||||
// 显式 `null` 表示从零重建,不能落到 `??` 的默认分支里。
|
||||
const explicitResume = payload.resume
|
||||
const resume =
|
||||
explicitResume === null
|
||||
? undefined
|
||||
: explicitResume ??
|
||||
(payload.completeSnapshot
|
||||
? store.readBackfillResume(payload.conversationId) ?? undefined
|
||||
: undefined)
|
||||
const task = store.indexConversationStreaming(
|
||||
payload.conversationId,
|
||||
queue.iterate(),
|
||||
payload.chunker,
|
||||
{
|
||||
completeSnapshot: payload.completeSnapshot,
|
||||
sourceHighWaterTime: payload.sourceHighWaterTime,
|
||||
resume
|
||||
},
|
||||
controller.signal,
|
||||
(processedMessages, indexedChunks) => {
|
||||
send({
|
||||
version: 1,
|
||||
type: 'progress',
|
||||
requestId: request.requestId,
|
||||
payload: {
|
||||
accountId: payload.accountId,
|
||||
phase: 'indexing',
|
||||
conversationId: payload.conversationId,
|
||||
processedMessages,
|
||||
// 流式回填的会话总量未知,进度只上报已处理条数。
|
||||
totalMessages: 0,
|
||||
indexedChunks
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
// 主进程可能在中途放弃这个会话;未消费的 rejection 会打崩 Worker 进程。
|
||||
task.catch(() => undefined)
|
||||
streamSessions.set(key, { queue, controller, store, task })
|
||||
|
||||
send({
|
||||
version: 1,
|
||||
type: 'result',
|
||||
requestId: request.requestId,
|
||||
payload: { started: true, resumedFrom: resume?.time ?? null }
|
||||
})
|
||||
}
|
||||
|
||||
async function handleStreamBatch(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamBatchRequest
|
||||
): Promise<void> {
|
||||
const session = streamSessions.get(streamKey(payload))
|
||||
if (!session) throw new Error('该会话没有进行中的索引任务')
|
||||
session.queue.push(payload.messages)
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { accepted: true } })
|
||||
}
|
||||
|
||||
async function handleStreamFinish(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamConversationRequest
|
||||
): Promise<void> {
|
||||
const key = streamKey(payload)
|
||||
const session = streamSessions.get(key)
|
||||
if (!session) throw new Error('该会话没有进行中的索引任务')
|
||||
streamSessions.delete(key)
|
||||
session.queue.close()
|
||||
const result = await session.task
|
||||
if (typeof payload.sourceHighWaterTime === 'number') {
|
||||
session.store.advanceSourceHighWater(payload.conversationId, payload.sourceHighWaterTime)
|
||||
}
|
||||
if (typeof payload.sourceMessageCount === 'number') {
|
||||
session.store.writeSourceTotals(payload.sourceMessageCount, payload.sourceLatestAt)
|
||||
}
|
||||
const streamResult: KnowledgeStreamResult = {
|
||||
conversationId: payload.conversationId,
|
||||
processedMessages: result.processedMessages,
|
||||
chunkCount: result.chunkCount,
|
||||
cancelled: result.cancelled,
|
||||
resumeTime: result.resumeTime
|
||||
}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: streamResult })
|
||||
}
|
||||
|
||||
async function handleConversationStates(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeConversationStatesRequest
|
||||
): Promise<void> {
|
||||
const path = getKnowledgeDatabasePath(payload.databaseRoot, payload.accountId)
|
||||
const states = existsSync(path)
|
||||
? getStore({ ...payload, fts: DEFAULT_KNOWLEDGE_FTS_CONFIG }).readConversationIndexStates()
|
||||
: {}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { states } })
|
||||
}
|
||||
|
||||
async function handleSourceTotals(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeSourceTotalsRequest
|
||||
): Promise<void> {
|
||||
// 没有已打开的库就说明这一遍没有真正写过索引,不新建空库来记口径。
|
||||
stores
|
||||
.get(storeKey(payload.databaseRoot, payload.accountId))
|
||||
?.writeSourceTotals(payload.sourceMessageCount, payload.sourceLatestAt)
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { accepted: true } })
|
||||
}
|
||||
|
||||
async function handleStreamAbort(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamConversationRequest
|
||||
): Promise<void> {
|
||||
const key = streamKey(payload)
|
||||
const session = streamSessions.get(key)
|
||||
streamSessions.delete(key)
|
||||
if (session) {
|
||||
session.controller.abort()
|
||||
session.queue.close()
|
||||
await session.task.catch(() => undefined)
|
||||
}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { removed: true } })
|
||||
}
|
||||
|
||||
async function handlePreflight( request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeCapacityPreflightRequest
|
||||
): Promise<void> {
|
||||
const result = await estimateKnowledgeCapacityPreflight(payload)
|
||||
@@ -226,11 +435,21 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
||||
if (request.type === 'cancel') {
|
||||
const payload = request.payload as { targetRequestId: string }
|
||||
controllers.get(payload.targetRequestId)?.abort()
|
||||
// 分批索引用的是自己的 controller:漏掉它,取消会一直等到整遍跑完才生效。
|
||||
for (const session of streamSessions.values()) {
|
||||
session.controller.abort()
|
||||
session.queue.close()
|
||||
}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { removed: true } })
|
||||
return
|
||||
}
|
||||
if (request.type === 'close') {
|
||||
for (const controller of controllers.values()) controller.abort()
|
||||
for (const session of streamSessions.values()) {
|
||||
session.controller.abort()
|
||||
session.queue.close()
|
||||
}
|
||||
streamSessions.clear()
|
||||
for (const store of stores.values()) store.close()
|
||||
stores.clear()
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { removed: true } })
|
||||
@@ -268,6 +487,30 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
||||
await handleIndex(request, request.payload as KnowledgeIndexRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamStart') {
|
||||
await handleStreamStart(request, request.payload as KnowledgeStreamStartRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamBatch') {
|
||||
await handleStreamBatch(request, request.payload as KnowledgeStreamBatchRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamFinish') {
|
||||
await handleStreamFinish(request, request.payload as KnowledgeStreamConversationRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamAbort') {
|
||||
await handleStreamAbort(request, request.payload as KnowledgeStreamConversationRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'conversationStates') {
|
||||
await handleConversationStates(request, request.payload as KnowledgeConversationStatesRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'sourceTotals') {
|
||||
await handleSourceTotals(request, request.payload as KnowledgeSourceTotalsRequest)
|
||||
return
|
||||
}
|
||||
throw new Error(`Unsupported knowledge worker request: ${String(request.type)}`)
|
||||
} catch (error) {
|
||||
send({
|
||||
@@ -279,7 +522,14 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
||||
}
|
||||
}
|
||||
|
||||
// 必须串行:分批索引在批与批之间 await,新请求切入会把 BEGIN IMMEDIATE 嵌套起来。
|
||||
let requestChain: Promise<void> = Promise.resolve()
|
||||
|
||||
process.on('message', (message: KnowledgeWorkerRequest) => {
|
||||
if (message?.version !== 1) return
|
||||
void handle(message, Date.now())
|
||||
if (message.type === 'streamAbort' || message.type === 'cancel') {
|
||||
void handle(message, Date.now())
|
||||
return
|
||||
}
|
||||
requestChain = requestChain.then(() => handle(message, Date.now()))
|
||||
})
|
||||
@@ -1,24 +1,9 @@
|
||||
/**
|
||||
* 消息身份的**唯一真源**。
|
||||
*
|
||||
* 这个规则同时被三处需要:
|
||||
* - Knowledge 索引写入 `knowledge_messages.message_id`
|
||||
* - 图片文字索引的 binding(必须与 Knowledge 里的 message_id 完全一致,否则 OCR 文本贴不到消息上)
|
||||
* - Evidence → 档案跳转的 messageRef
|
||||
*
|
||||
* 任何一处各自复制一份,都会在 `local:` 前缀上静默失配(项目里已经有这个坑的历史注释),
|
||||
* 所以抽成一个模块,谁都不许再抄。
|
||||
*/
|
||||
/** 消息身份的唯一真源:Knowledge 索引、图片 OCR binding、messageRef 三处必须用同一份。 */
|
||||
import type * as chat from '../services/chat-service'
|
||||
|
||||
/**
|
||||
* 源消息 → 稳定消息 id。
|
||||
*
|
||||
* 降级顺序刻意保守:`localId` 是 WCDB 行内最稳的本地 id;其次用消息自带 id;
|
||||
* 最后才退化成「时间 + 服务端 id / 内容」的组合(仅在极端缺字段时命中)。
|
||||
*/
|
||||
/** localId 跨分片会重号,必须带上 create_time 才唯一;serverId 会被复用,不能当身份。 */
|
||||
export function sourceMessageId(message: chat.FormattedMessage): string {
|
||||
if (message.localId) return `local:${message.localId}`
|
||||
if (message.localId) return `local:${message.createTime || 0}:${message.localId}`
|
||||
if (message.id) return String(message.id)
|
||||
return `${message.createTime || 0}:${message.serverId || message.content}`
|
||||
}
|
||||
@@ -157,17 +157,27 @@ export class AskWechatService {
|
||||
reason: AskWechatFallbackReason,
|
||||
diagnostics: QueryAgentDiagnostics
|
||||
): Promise<AskWechatQueryResult> {
|
||||
if (!this.options.runLegacy) {
|
||||
const scopeKind = request.scope?.scope.kind
|
||||
// Legacy 表达不了「指定多个会话」:窄范围回退等于静默搜全库,宁可明确失败。
|
||||
const legacyScope: 'global' | 'groups' | null =
|
||||
!scopeKind || scopeKind === 'all' ? 'global' : scopeKind === 'groups' ? 'groups' : null
|
||||
if (!this.options.runLegacy || legacyScope === null) {
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'error',
|
||||
message: RUNTIME_FAILURE_MESSAGE,
|
||||
diagnostics
|
||||
message:
|
||||
legacyScope === null
|
||||
? '本次查询没有完成。当前搜索范围(指定会话)不支持自动重试,请缩小时间范围或换一种问法。'
|
||||
: RUNTIME_FAILURE_MESSAGE,
|
||||
diagnostics: {
|
||||
...diagnostics,
|
||||
...(legacyScope === null ? { fallbackSkipped: 'scope_too_narrow_for_legacy' } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
const legacyResult = await this.options.runLegacy({
|
||||
scope: 'global',
|
||||
scope: legacyScope,
|
||||
range: 'all',
|
||||
...request.legacy,
|
||||
requestId: request.requestId,
|
||||
|
||||
@@ -851,6 +851,58 @@ export async function listMessagesAsync(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按页读取一个会话的消息:不把整个会话读进数组,格式化走同一个 `listSourceMessages`。
|
||||
*/
|
||||
export async function* iterateMessagesAsync(
|
||||
userMd5: string,
|
||||
options: { pageSize?: number; sinceMs?: number } = {}
|
||||
): AsyncGenerator<{ messages: FormattedMessage[]; failedStores: string[] }> {
|
||||
if (!dbRef) return
|
||||
const requestId = nextListMessagesRequestId()
|
||||
const client = dbRef.getWcdb4Client()
|
||||
for await (const page of client.iterateMessagePagesAsync(userMd5, {
|
||||
pageSize: options.pageSize,
|
||||
sinceSec: options.sinceMs ? Math.floor(options.sinceMs / 1000) : undefined,
|
||||
requestId
|
||||
})) {
|
||||
if (page.failedStores.length) {
|
||||
yield { messages: [], failedStores: page.failedStores }
|
||||
return
|
||||
}
|
||||
const messages = listSourceMessages(
|
||||
userMd5,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
page.messages,
|
||||
requestId
|
||||
)
|
||||
yield { messages, failedStores: [] }
|
||||
}
|
||||
}
|
||||
|
||||
/** 点查定位:前后文与单条语音都靠它,避免先读整个会话再 findIndex。 */
|
||||
export function locateMessageAsync(
|
||||
userMd5: string,
|
||||
messageId: string
|
||||
): Promise<
|
||||
| { status: 'found'; location: { createTime: number; localId: number } }
|
||||
| { status: 'not_found' | 'ambiguous' | 'unsupported' }
|
||||
> {
|
||||
if (!dbRef) return Promise.resolve({ status: 'not_found' as const })
|
||||
return dbRef.getWcdb4Client().locateMessageAsync(userMd5, messageId)
|
||||
}
|
||||
|
||||
/** 只读 COUNT(*);`count: null` 是有分片读不到,调用方必须显示「未知」而不是 0。 */
|
||||
export function countConversationMessagesAsync(
|
||||
userMd5: string,
|
||||
options: { sinceMs?: number } = {}
|
||||
): Promise<{ count: number | null; approximate: boolean; failedStores: string[] }> {
|
||||
if (!dbRef) return Promise.resolve({ count: null, approximate: false, failedStores: [] })
|
||||
return dbRef.getWcdb4Client().countConversationMessagesAsync(userMd5, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* 只取**图片消息**(图片文字索引专用)。
|
||||
*
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { listContactsAsync, listMessagesAsync, isReady, type FormattedContact, type FormattedMessage } from './chat-service'
|
||||
import {
|
||||
isReady,
|
||||
iterateMessagesAsync,
|
||||
listContactsAsync,
|
||||
listMessagesAsync,
|
||||
locateMessageAsync,
|
||||
type FormattedContact,
|
||||
type FormattedMessage
|
||||
} from './chat-service'
|
||||
import { resolveContact } from './contact-resolution-service'
|
||||
import { sourceMessageId } from '../knowledge/message-identity'
|
||||
import type { KnowledgeSearchService } from '../knowledge/knowledge-search-service'
|
||||
@@ -311,6 +319,11 @@ interface ResolvedCorpus {
|
||||
function describeScope(scope: ResolvedCorpusScope): string {
|
||||
if (scope.kind === 'all') return '所有聊天记录'
|
||||
if (scope.kind === 'groups') return '群聊专属'
|
||||
if (scope.kind === 'selected') {
|
||||
const names = scope.displayNames ?? []
|
||||
const preview = names.slice(0, 3).join('、')
|
||||
return `指定的 ${scope.conversationCount} 个会话${preview ? `(${preview}${names.length > 3 ? ' 等' : ''})` : ''}`
|
||||
}
|
||||
return `${scope.kind === 'contact' ? '单聊专属' : '当前会话'}:${scope.displayName || '未知会话'}`
|
||||
}
|
||||
|
||||
@@ -444,6 +457,36 @@ export class LocalQueryApiService {
|
||||
const ids = contacts.filter((contact) => contact.type === 'group').map((contact) => contact.md5)
|
||||
return { conversationIds: ids, scope: { kind: 'groups', conversationCount: ids.length } }
|
||||
}
|
||||
if (scope.kind === 'selected') {
|
||||
const requested = Array.isArray(scope.conversationIds)
|
||||
? Array.from(new Set(scope.conversationIds.map((id) => String(id ?? '').trim()).filter(Boolean)))
|
||||
: []
|
||||
// 空选择必须是错误:把它当成"全部"就是最典型的静默扩大范围。
|
||||
if (!requested.length) {
|
||||
return {
|
||||
scope: { kind: 'selected', conversationCount: 0 },
|
||||
error: { status: 'scope_selection_empty' }
|
||||
}
|
||||
}
|
||||
const resolved = requested
|
||||
.map((id) => contacts.find((contact) => contact.md5 === id))
|
||||
.filter((contact): contact is FormattedContact => Boolean(contact))
|
||||
// 任何一个 id 不属于当前账号都直接拒绝:静默丢弃会让用户以为搜过那个群。
|
||||
if (resolved.length !== requested.length) {
|
||||
return {
|
||||
scope: { kind: 'selected', conversationCount: resolved.length },
|
||||
error: { status: 'scope_conversation_not_found', kind: 'selected' }
|
||||
}
|
||||
}
|
||||
return {
|
||||
conversationIds: resolved.map((contact) => contact.md5),
|
||||
scope: {
|
||||
kind: 'selected',
|
||||
conversationCount: resolved.length,
|
||||
displayNames: resolved.map((contact) => contactView(contact).displayName)
|
||||
}
|
||||
}
|
||||
}
|
||||
const contact = contacts.find((item) => item.md5 === scope.conversationId)
|
||||
if (!contact) {
|
||||
return { scope: { kind: scope.kind, conversationCount: 0 }, error: { status: 'scope_conversation_not_found', kind: scope.kind } }
|
||||
@@ -622,7 +665,7 @@ export class LocalQueryApiService {
|
||||
status: 'completed' as const,
|
||||
...(targetView ? { target: targetView } : {}),
|
||||
resolvedTimeRange: range,
|
||||
coverage: { state: this.searchCoverage(found, requestedEnd) },
|
||||
coverage: { state: await this.searchCoverage(found, requestedEnd, conversationIds) },
|
||||
probeCount: probes.length,
|
||||
evidenceCount: evidence.size,
|
||||
evidence: Array.from(evidence.values()).slice(0, limit),
|
||||
@@ -848,22 +891,32 @@ export class LocalQueryApiService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖度。
|
||||
*
|
||||
* 只有「派生索引可用 + 请求范围被索引完整覆盖」才是 `complete`。
|
||||
* `complete` 是 0 结果时允许说"没有找到"的唯一前提;索引落后时必须 `partial`。
|
||||
*/
|
||||
private searchCoverage(
|
||||
/** 按会话逐个判断:全局 indexLatestAt 不是证明,缺状态行的会话一律算 partial。 */
|
||||
private async searchCoverage(
|
||||
found: { indexLatestAt: number | null; sourceLatestAt: number | null; derivedReady: boolean; evidence: Map<string, QueryEvidenceItem> },
|
||||
requestedEnd: number
|
||||
): 'complete' | 'partial' | 'unknown' {
|
||||
requestedEnd: number,
|
||||
conversationIds?: string[]
|
||||
): Promise<'complete' | 'partial' | 'unknown'> {
|
||||
if (!found.derivedReady) {
|
||||
// 派生索引不可用(未建立 / 直读源数据的 fallback):有证据也只能算 partial。
|
||||
return found.evidence.size ? 'partial' : 'unknown'
|
||||
}
|
||||
// 索引可用但覆盖口径缺失时不能宣称完整;此时按 partial 处理(宁可保守)。
|
||||
if (found.indexLatestAt === null) return 'partial'
|
||||
if (!this.knowledge) return 'partial'
|
||||
|
||||
const states = await this.knowledge.getConversationIndexStates().catch(() => ({}))
|
||||
const targets = conversationIds?.length ? conversationIds : Object.keys(states)
|
||||
const incomplete = targets.filter((id) => {
|
||||
const state = states[id]
|
||||
// 没有状态行 = 这个会话从来没被索引过,不能算覆盖。
|
||||
if (!state) return true
|
||||
// 回填到一半、失败、取消:都不能当作完整。
|
||||
if (!state.completeSnapshot) return true
|
||||
if (state.state !== 'ready') return true
|
||||
return false
|
||||
})
|
||||
if (incomplete.length) return 'partial'
|
||||
return indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt) ? 'complete' : 'partial'
|
||||
}
|
||||
async context(request: MessageContextRequest) {
|
||||
@@ -876,9 +929,58 @@ export class LocalQueryApiService {
|
||||
return outsideScopeError(corpus.scope, '其他会话的消息') as { status: string }
|
||||
}
|
||||
}
|
||||
const before = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10)); const after = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10)); const messages = await listMessagesAsync(ref.conversationId); const index = messages.findIndex((message) => normalizeMessageIdentity(ref.conversationId, message.id)?.messageId === ref.messageId); if (index < 0) return { status: 'contact_not_found' as const }
|
||||
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId); if (!contact) return { status: 'contact_not_found' as const }; const map = (message: FormattedMessage) => toQueryMessage(ref.conversationId, message, contact, undefined, this.voiceSnapshot(message))
|
||||
return { status: 'completed' as const, anchor: map(messages[index]), before: messages.slice(Math.max(0, index - before), index).map(map), after: messages.slice(index + 1, index + 1 + after).map(map) }
|
||||
const beforeCount = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10))
|
||||
const afterCount = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10))
|
||||
// 先点定位,再读窗口:整会话读进来再 findIndex,正是超大群内存失控的那条路径。
|
||||
const located = await locateMessageAsync(ref.conversationId, ref.messageId)
|
||||
if (located.status !== 'found') {
|
||||
// 身份不唯一或找不到都必须明确失败 —— 随便挑一条会给模型错误的上下文。
|
||||
return {
|
||||
status:
|
||||
located.status === 'ambiguous'
|
||||
? ('ambiguous_message' as const)
|
||||
: ('contact_not_found' as const)
|
||||
}
|
||||
}
|
||||
const anchorTime = located.location.createTime
|
||||
const isAnchor = (message: FormattedMessage): boolean =>
|
||||
message.createTime === anchorTime && message.localId === located.location.localId
|
||||
|
||||
const leading = beforeCount
|
||||
? await listMessagesAsync(ref.conversationId, undefined, anchorTime - 1, {
|
||||
limit: beforeCount
|
||||
})
|
||||
: []
|
||||
|
||||
let anchor: FormattedMessage | undefined
|
||||
const trailing: FormattedMessage[] = []
|
||||
for await (const page of iterateMessagesAsync(ref.conversationId, {
|
||||
pageSize: 300,
|
||||
sinceMs: anchorTime * 1000
|
||||
})) {
|
||||
if (page.failedStores.length) break
|
||||
for (const message of page.messages) {
|
||||
if (!anchor) {
|
||||
if (isAnchor(message)) anchor = message
|
||||
continue
|
||||
}
|
||||
if (trailing.length >= afterCount) break
|
||||
trailing.push(message)
|
||||
}
|
||||
if (anchor && trailing.length >= afterCount) break
|
||||
}
|
||||
if (!anchor) return { status: 'contact_not_found' as const }
|
||||
|
||||
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId)
|
||||
if (!contact) return { status: 'contact_not_found' as const }
|
||||
const map = (message: FormattedMessage) =>
|
||||
toQueryMessage(ref.conversationId, message, contact, undefined, this.voiceSnapshot(message))
|
||||
return {
|
||||
status: 'completed' as const,
|
||||
anchor: map(anchor),
|
||||
before: leading.map(map),
|
||||
after: trailing.map(map)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 把指定语音消息转成文字。
|
||||
@@ -920,15 +1022,39 @@ export class LocalQueryApiService {
|
||||
group.push({ messageRef, messageId: identity.messageId })
|
||||
refsByConversation.set(identity.conversationId, group)
|
||||
}
|
||||
// 同一会话只读一次源消息;与 message-context 同样按会话读取后匹配消息身份。
|
||||
// 逐条点定位后只读它所在的那一秒:转写只需要这一条消息的引用,
|
||||
// 为了它把整个会话读进内存是 #75 那条路径的翻版。
|
||||
for (const [conversationId, wanted] of refsByConversation) {
|
||||
const messages = await listMessagesAsync(conversationId)
|
||||
const byId = new Map(messages.map((message) => [normalizeMessageIdentity(conversationId, message.id)?.messageId, message]))
|
||||
for (const { messageRef, messageId } of wanted) {
|
||||
const message = byId.get(messageId)
|
||||
const located = await locateMessageAsync(conversationId, messageId)
|
||||
if (located.status !== 'found') {
|
||||
problems.set(
|
||||
messageRef,
|
||||
voiceItemProblem(
|
||||
messageRef,
|
||||
'failed',
|
||||
located.status === 'ambiguous' ? 'ambiguous_message' : 'message_not_found'
|
||||
)
|
||||
)
|
||||
continue
|
||||
}
|
||||
const second = located.location.createTime
|
||||
const sameSecond = await listMessagesAsync(conversationId, second, second)
|
||||
const message = sameSecond.find(
|
||||
(item) => item.localId === located.location.localId
|
||||
)
|
||||
const reference = message ? voiceMessageReferenceOf(message) : undefined
|
||||
if (reference) references.set(messageRef, reference)
|
||||
else problems.set(messageRef, voiceItemProblem(messageRef, 'failed', message ? 'not_voice_message' : 'message_not_found'))
|
||||
else {
|
||||
problems.set(
|
||||
messageRef,
|
||||
voiceItemProblem(
|
||||
messageRef,
|
||||
'failed',
|
||||
message ? 'not_voice_message' : 'message_not_found'
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1090,6 +1090,10 @@ function conversationScopeNote(input: QueryAgentConversationScope): string {
|
||||
rules.push(
|
||||
'范围是群聊专属:包含全部群会话以及群成员实际发送的消息。问"谁聊过某话题"时应省略 search_messages 的 target 做跨群检索,并在回答里保留群名与发送者。'
|
||||
)
|
||||
} else if (scope.kind === 'selected') {
|
||||
rules.push(
|
||||
'范围是用户手选的若干会话:可以在它们之间跨会话检索,但每个 target 都必须属于这个集合;用户只选了这些,不要暗示还有其他会话可选。'
|
||||
)
|
||||
} else if (scope.kind === 'contact' || scope.kind === 'current') {
|
||||
rules.push(
|
||||
'范围只有一个会话:所有工具都可以省略 target(query_messages 也可以),省略即在该会话内检索;不要猜会话名,也不要指定其他会话。'
|
||||
|
||||
@@ -3,6 +3,10 @@ import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import type { TextToSpeechModel } from '../../shared/text-to-speech'
|
||||
import {
|
||||
normalizeKnowledgeIndexScopes,
|
||||
type KnowledgeIndexScope
|
||||
} from '../../shared/knowledge'
|
||||
|
||||
/**
|
||||
* 把 V3 时代的 "...\\Documents\\WeChat Files" 路径重定向到
|
||||
@@ -67,6 +71,8 @@ export interface AppSettings {
|
||||
* 始终展示最新版本 —— 忽略的是提示,不是版本本身。空串表示没有忽略任何版本。
|
||||
*/
|
||||
skippedUpdateVersion: string
|
||||
/** 按账号存;缺省 = 全部会话。不同账号的选择绝不能串用。 */
|
||||
knowledgeIndexScopes: Record<string, KnowledgeIndexScope>
|
||||
}
|
||||
|
||||
/** 只接受 `1.2.3` / `1.2.3-beta.1` 这类版本号;其它输入一律按"没有忽略"处理。 */
|
||||
@@ -161,7 +167,8 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
reportImagePostfixText: '今日日报',
|
||||
queryAgentEnabled: true,
|
||||
closeAction: 'ask',
|
||||
skippedUpdateVersion: ''
|
||||
skippedUpdateVersion: '',
|
||||
knowledgeIndexScopes: {}
|
||||
}
|
||||
|
||||
const SETTINGS_FILE = path.join(
|
||||
@@ -217,6 +224,9 @@ export function loadSettings(): AppSettings {
|
||||
}
|
||||
// 版本号是拿来逐字比对的:脏值会让「忽略」永远命中不了同一条记录。
|
||||
cache.skippedUpdateVersion = normalizeSkippedUpdateVersion(cache.skippedUpdateVersion)
|
||||
// 索引范围来自磁盘,可能是旧版本/手改过的脏值:收敛成合法形状,
|
||||
// 尤其不能把 `selected + 空数组` 悄悄升级成"全部"。
|
||||
cache.knowledgeIndexScopes = normalizeKnowledgeIndexScopes(cache.knowledgeIndexScopes)
|
||||
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
|
||||
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
|
||||
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
|
||||
|
||||
+418
-17
@@ -43,6 +43,33 @@ export interface Wcdb4MessageQueryOptions {
|
||||
limit?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页游标。两者都必须是数值:按字符串比较会把 `10` 排到 `9` 前面,翻页就会跳段。
|
||||
*/
|
||||
export interface Wcdb4MessageCursor {
|
||||
createTime: number
|
||||
localId: number
|
||||
}
|
||||
|
||||
export interface Wcdb4MessagePage {
|
||||
messages: Wcdb4Message[]
|
||||
/** 下一页起点;`null` 表示该会话已读完。 */
|
||||
cursor: Wcdb4MessageCursor | null
|
||||
hasMore: boolean
|
||||
/**
|
||||
* 读取失败的分片表名。非空表示本页只是**部分**结果,调用方不得据此把会话标记为已覆盖。
|
||||
*/
|
||||
failedStores: string[]
|
||||
}
|
||||
|
||||
export interface Wcdb4ConversationMessageCount {
|
||||
/** `null` 表示统计失败,调用方不能当成 0。 */
|
||||
count: number | null
|
||||
/** 分片时间范围重叠时为 true:重叠区可能有重复行,`count` 只是上限。 */
|
||||
approximate: boolean
|
||||
failedStores: string[]
|
||||
}
|
||||
|
||||
export interface Wcdb4SessionQueryOptions {
|
||||
hydrateDisplayNames?: boolean
|
||||
hydrateStatuses?: boolean
|
||||
@@ -2678,12 +2705,10 @@ export class Wcdb4Client {
|
||||
return this.finalizeMessages(username, allRows, startTime, endTime, limit)
|
||||
}
|
||||
|
||||
private finalizeMessages(
|
||||
/** 分页必须走这里:`finalizeMessages` 的排序与截断作用在整段行集上,对一页调用语义不同。 */
|
||||
private formatMessageRows(
|
||||
username: string,
|
||||
rows: Record<string, unknown>[],
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
limit?: number
|
||||
rows: Record<string, unknown>[]
|
||||
): Wcdb4Message[] {
|
||||
const messages = rows.map((row) => this.normalizeMessage(row))
|
||||
|
||||
@@ -2694,18 +2719,7 @@ export class Wcdb4Client {
|
||||
? this.getGroupNicknames(username)
|
||||
: undefined
|
||||
|
||||
const sorted = messages
|
||||
.filter((message) => {
|
||||
const createTime = Number(message.msgCreateTime)
|
||||
if (startTime && createTime < startTime) return false
|
||||
if (endTime && createTime > endTime) return false
|
||||
return true
|
||||
})
|
||||
.sort((a, b) => Number(a.msgCreateTime) - Number(b.msgCreateTime))
|
||||
|
||||
const visibleMessages = limit && sorted.length > limit ? sorted.slice(-limit) : sorted
|
||||
|
||||
return visibleMessages.map((message) => {
|
||||
return messages.map((message) => {
|
||||
if (!message.sender) return message
|
||||
const senderNickname =
|
||||
groupNicknames?.get(message.sender) ||
|
||||
@@ -2729,6 +2743,27 @@ export class Wcdb4Client {
|
||||
})
|
||||
}
|
||||
|
||||
private finalizeMessages(
|
||||
username: string,
|
||||
rows: Record<string, unknown>[],
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
limit?: number
|
||||
): Wcdb4Message[] {
|
||||
const messages = this.formatMessageRows(username, rows)
|
||||
|
||||
const sorted = messages
|
||||
.filter((message) => {
|
||||
const createTime = Number(message.msgCreateTime)
|
||||
if (startTime && createTime < startTime) return false
|
||||
if (endTime && createTime > endTime) return false
|
||||
return true
|
||||
})
|
||||
.sort((a, b) => Number(a.msgCreateTime) - Number(b.msgCreateTime))
|
||||
|
||||
return limit && sorted.length > limit ? sorted.slice(-limit) : sorted
|
||||
}
|
||||
|
||||
private normalizeMessageLimit(limit?: number): number | undefined {
|
||||
const normalized = Number(limit)
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) return undefined
|
||||
@@ -2861,6 +2896,372 @@ export class Wcdb4Client {
|
||||
return result
|
||||
}
|
||||
|
||||
/** 点查定位:结果不唯一时返回 `ambiguous`,不许退化成读整个会话再 findIndex。 */
|
||||
async locateMessageAsync(
|
||||
md5OrUsername: string,
|
||||
messageId: string
|
||||
): Promise<{ status: 'found'; location: Wcdb4MessageCursor } | { status: 'not_found' | 'ambiguous' | 'unsupported' }> {
|
||||
if (!this.wcdbExecQuery) return { status: 'unsupported' }
|
||||
const text = String(messageId || '').trim().replace(/^local:/, '')
|
||||
const parts = text.split(':')
|
||||
let wantedTime: number | null = null
|
||||
let wantedLocalId: number | null = null
|
||||
if (parts.length === 2 && /^\d+$/.test(parts[0]) && /^\d+$/.test(parts[1])) {
|
||||
wantedTime = Number(parts[0])
|
||||
wantedLocalId = Number(parts[1])
|
||||
} else if (/^\d+$/.test(text)) {
|
||||
wantedLocalId = Number(text)
|
||||
} else {
|
||||
return { status: 'unsupported' }
|
||||
}
|
||||
if (wantedLocalId === null) return { status: 'unsupported' }
|
||||
|
||||
const username = this.resolveMessageUsername(md5OrUsername)
|
||||
if (!username) return { status: 'not_found' }
|
||||
let stores: Wcdb4MessageStore[] = []
|
||||
try {
|
||||
stores = await this.listMessageStoresAsync(username, true)
|
||||
} catch {
|
||||
return { status: 'not_found' }
|
||||
}
|
||||
|
||||
const hits: Wcdb4MessageCursor[] = []
|
||||
for (const store of stores) {
|
||||
const table = this.quoteSqlIdentifier(store.tableName)
|
||||
try {
|
||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
store.dbPath,
|
||||
`SELECT "create_time" AS t, "local_id" AS l FROM ${table} WHERE "local_id" = ${wantedLocalId} LIMIT 5`
|
||||
)
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
const createTime = Number(row.t)
|
||||
const localId = Number(row.l)
|
||||
if (Number.isFinite(createTime) && Number.isFinite(localId)) {
|
||||
hits.push({ createTime, localId })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 单个分片读不到时继续找其余分片;全都没命中会走 not_found。
|
||||
}
|
||||
}
|
||||
|
||||
if (wantedTime !== null) {
|
||||
const exact = hits.filter((hit) => hit.createTime === wantedTime)
|
||||
if (exact.length === 1) return { status: 'found', location: exact[0] }
|
||||
return { status: exact.length > 1 ? 'ambiguous' : 'not_found' }
|
||||
}
|
||||
if (hits.length === 1) return { status: 'found', location: hits[0] }
|
||||
return { status: hits.length > 1 ? 'ambiguous' : 'not_found' }
|
||||
}
|
||||
|
||||
private rowCreateTimeSeconds(row: Record<string, unknown>): number {
|
||||
const value = this.pickValue(row, [
|
||||
'create_time',
|
||||
'createTime',
|
||||
'msg_create_time',
|
||||
'msgCreateTime',
|
||||
'time',
|
||||
'WCDB_CT_create_time'
|
||||
])
|
||||
const parsed = Number(value)
|
||||
if (!Number.isFinite(parsed)) return 0
|
||||
// 毫秒形态的旧库按秒归一,与 `pickNumber` 同一口径。
|
||||
return Math.floor(parsed > 1e12 ? parsed / 1000 : parsed)
|
||||
}
|
||||
|
||||
private rowLocalId(row: Record<string, unknown>): number {
|
||||
const value = this.pickValue(row, [
|
||||
'local_id',
|
||||
'localId',
|
||||
'msg_local_id',
|
||||
'msgLocalId',
|
||||
'mesLocalID',
|
||||
'id'
|
||||
])
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? Math.floor(parsed) : 0
|
||||
}
|
||||
|
||||
/** 跨分片 keyset 分页:内存上限是「分片数 × pageSize」,与会话总条数无关。 */
|
||||
async *iterateMessagePagesAsync(
|
||||
md5OrUsername: string,
|
||||
options: {
|
||||
pageSize?: number
|
||||
/** 秒,闭区间下界。 */
|
||||
sinceSec?: number
|
||||
/** 秒,闭区间上界。 */
|
||||
untilSec?: number
|
||||
requestId?: string
|
||||
} = {}
|
||||
): AsyncGenerator<Wcdb4MessagePage, void, void> {
|
||||
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持消息分片查询')
|
||||
const requestId = options.requestId ?? 'NO-REQUEST'
|
||||
const pageSize = Math.max(50, Math.min(5000, Math.floor(options.pageSize ?? 1000)))
|
||||
const username = this.resolveMessageUsername(md5OrUsername)
|
||||
if (!username) {
|
||||
yield { messages: [], cursor: null, hasMore: false, failedStores: [] }
|
||||
return
|
||||
}
|
||||
|
||||
const sinceSec =
|
||||
typeof options.sinceSec === 'number' && Number.isFinite(options.sinceSec)
|
||||
? Math.max(0, Math.floor(options.sinceSec))
|
||||
: 0
|
||||
const untilSec =
|
||||
typeof options.untilSec === 'number' && Number.isFinite(options.untilSec)
|
||||
? Math.floor(options.untilSec)
|
||||
: 0
|
||||
|
||||
let stores: Wcdb4MessageStore[] = []
|
||||
try {
|
||||
stores = await this.listMessageStoresAsync(username, true)
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] paged message store lookup failed username=${username}:`, error)
|
||||
yield { messages: [], cursor: null, hasMore: false, failedStores: [] }
|
||||
return
|
||||
}
|
||||
if (!stores.length) {
|
||||
yield { messages: [], cursor: null, hasMore: false, failedStores: [] }
|
||||
return
|
||||
}
|
||||
|
||||
type Shard = {
|
||||
store: Wcdb4MessageStore
|
||||
alias: string
|
||||
rows: Wcdb4Message[]
|
||||
index: number
|
||||
cursor: Wcdb4MessageCursor
|
||||
exhausted: boolean
|
||||
failed: boolean
|
||||
}
|
||||
|
||||
const shards: Shard[] = stores.map((store) => ({
|
||||
store,
|
||||
// JOIN sender 表时必须限定列名,否则 `create_time` 可能歧义。
|
||||
alias: store.senderTableName ? 'm' : '',
|
||||
rows: [],
|
||||
index: 0,
|
||||
cursor: { createTime: 0, localId: 0 },
|
||||
exhausted: false,
|
||||
failed: false
|
||||
}))
|
||||
|
||||
const failedStores = new Set<string>()
|
||||
const column = (shard: Shard, name: string): string =>
|
||||
shard.alias
|
||||
? `${shard.alias}.${this.quoteSqlIdentifier(name)}`
|
||||
: this.quoteSqlIdentifier(name)
|
||||
|
||||
const refill = async (shard: Shard): Promise<void> => {
|
||||
const cursor = shard.cursor
|
||||
const keyset =
|
||||
`(${column(shard, 'create_time')} > ${cursor.createTime} OR ` +
|
||||
`(${column(shard, 'create_time')} = ${cursor.createTime} AND ` +
|
||||
`${column(shard, 'local_id')} > ${cursor.localId}))`
|
||||
const where = [
|
||||
keyset,
|
||||
sinceSec > 0 ? `${column(shard, 'create_time')} >= ${sinceSec}` : '',
|
||||
untilSec > 0 ? `${column(shard, 'create_time')} <= ${untilSec}` : ''
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' AND ')
|
||||
const sql =
|
||||
`${this.messageTableSelect(shard.store)} WHERE ${where} ` +
|
||||
`ORDER BY ${column(shard, 'create_time')} ASC, ${column(shard, 'local_id')} ASC ` +
|
||||
`LIMIT ${pageSize}`
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
shard.store.dbPath,
|
||||
sql
|
||||
)
|
||||
const page = Array.isArray(rows) ? rows : []
|
||||
shard.rows = this.formatMessageRows(username, page)
|
||||
shard.index = 0
|
||||
const lastRow = page[page.length - 1]
|
||||
if (lastRow) {
|
||||
shard.cursor = {
|
||||
createTime: this.rowCreateTimeSeconds(lastRow),
|
||||
localId: this.rowLocalId(lastRow)
|
||||
}
|
||||
}
|
||||
if (page.length < pageSize) shard.exhausted = true
|
||||
wcdbDebugLog(
|
||||
`[${requestId}] WCDB page table=${shard.store.tableName} rows=${page.length} ` +
|
||||
`cursor=${shard.cursor.createTime}:${shard.cursor.localId} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[WCDB4] paged message read failed username=${username} ` +
|
||||
`db=${shard.store.dbPath} table=${shard.store.tableName}:`,
|
||||
error
|
||||
)
|
||||
shard.failed = true
|
||||
shard.exhausted = true
|
||||
shard.rows = []
|
||||
shard.index = 0
|
||||
failedStores.add(shard.store.tableName)
|
||||
}
|
||||
}
|
||||
|
||||
const hasPending = (): boolean =>
|
||||
shards.some((shard) => !shard.exhausted || shard.index < shard.rows.length)
|
||||
|
||||
// 只有 (create_time, server_id) 都相同才判副本:server_id 会被复用,无 id 时不去重。
|
||||
const DEDUPE_WINDOW_LIMIT = 50_000
|
||||
let dedupeSecond = -1
|
||||
let dedupeServers = new Set<string>()
|
||||
|
||||
const serverIdOf = (message: Wcdb4Message): string => {
|
||||
const value = String(message.serverId || '').trim()
|
||||
return value && value !== '0' ? value : ''
|
||||
}
|
||||
|
||||
let page: Wcdb4Message[] = []
|
||||
let pageCursor: Wcdb4MessageCursor | null = null
|
||||
|
||||
while (true) {
|
||||
for (const shard of shards) {
|
||||
if (shard.exhausted || shard.failed) continue
|
||||
if (shard.index < shard.rows.length) continue
|
||||
await refill(shard)
|
||||
}
|
||||
|
||||
let pickedShard: Shard | null = null
|
||||
let pickedMessage: Wcdb4Message | null = null
|
||||
let pickedTime = 0
|
||||
let pickedLocalId = 0
|
||||
for (const shard of shards) {
|
||||
if (shard.index >= shard.rows.length) continue
|
||||
const candidate = shard.rows[shard.index]
|
||||
const candidateTime = Number(candidate.msgCreateTime) || 0
|
||||
const candidateLocalId = Number(candidate.mesLocalID) || 0
|
||||
// 并列时保留先遍历到的分片(shards 顺序稳定),这是跨页唯一确定的 tie-break:
|
||||
// `(create_time, local_id)` 在不同分片之间并不唯一,缺了它翻页顺序会随查询计划漂移。
|
||||
if (
|
||||
!pickedShard ||
|
||||
candidateTime < pickedTime ||
|
||||
(candidateTime === pickedTime && candidateLocalId < pickedLocalId)
|
||||
) {
|
||||
pickedShard = shard
|
||||
pickedMessage = candidate
|
||||
pickedTime = candidateTime
|
||||
pickedLocalId = candidateLocalId
|
||||
}
|
||||
}
|
||||
|
||||
if (!pickedShard || !pickedMessage) break
|
||||
pickedShard.index += 1
|
||||
|
||||
if (pickedTime !== dedupeSecond) {
|
||||
dedupeSecond = pickedTime
|
||||
dedupeServers = new Set<string>()
|
||||
}
|
||||
const serverId = serverIdOf(pickedMessage)
|
||||
if (serverId) {
|
||||
if (dedupeServers.has(serverId)) continue
|
||||
if (dedupeServers.size < DEDUPE_WINDOW_LIMIT) dedupeServers.add(serverId)
|
||||
}
|
||||
|
||||
page.push(pickedMessage)
|
||||
pageCursor = { createTime: pickedTime, localId: pickedLocalId }
|
||||
|
||||
if (page.length >= pageSize) {
|
||||
yield {
|
||||
messages: page,
|
||||
cursor: pageCursor,
|
||||
hasMore: hasPending(),
|
||||
failedStores: Array.from(failedStores)
|
||||
}
|
||||
page = []
|
||||
pageCursor = null
|
||||
}
|
||||
}
|
||||
|
||||
if (page.length || failedStores.size === 0) {
|
||||
yield {
|
||||
messages: page,
|
||||
cursor: pageCursor,
|
||||
hasMore: false,
|
||||
failedStores: Array.from(failedStores)
|
||||
}
|
||||
} else {
|
||||
// 全部批次都失败时仍要发出一页,让调用方看到失败分片而不是"零消息"。
|
||||
yield { messages: [], cursor: null, hasMore: false, failedStores: Array.from(failedStores) }
|
||||
}
|
||||
}
|
||||
|
||||
/** 只读 COUNT(*);`count: null` 是「未知」(有分片读不到),不是 0。 */
|
||||
async countConversationMessagesAsync(
|
||||
md5OrUsername: string,
|
||||
options: { sinceMs?: number } = {}
|
||||
): Promise<Wcdb4ConversationMessageCount> {
|
||||
const failedStores: string[] = []
|
||||
if (!this.wcdbExecQuery) {
|
||||
return { count: null, approximate: false, failedStores }
|
||||
}
|
||||
const username = this.resolveMessageUsername(md5OrUsername)
|
||||
if (!username) return { count: null, approximate: false, failedStores }
|
||||
|
||||
let stores: Wcdb4MessageStore[] = []
|
||||
try {
|
||||
stores = await this.listMessageStoresAsync(username, true)
|
||||
} catch {
|
||||
return { count: null, approximate: false, failedStores }
|
||||
}
|
||||
if (!stores.length) return { count: 0, approximate: false, failedStores }
|
||||
|
||||
const sinceSec =
|
||||
typeof options.sinceMs === 'number' && Number.isFinite(options.sinceMs) && options.sinceMs > 0
|
||||
? Math.floor(options.sinceMs / 1000)
|
||||
: 0
|
||||
const whereSql = sinceSec > 0 ? ` WHERE "create_time" >= ${sinceSec}` : ''
|
||||
|
||||
let total = 0
|
||||
const ranges: Array<{ min: number; max: number }> = []
|
||||
for (const store of stores) {
|
||||
const table = this.quoteSqlIdentifier(store.tableName)
|
||||
try {
|
||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
store.dbPath,
|
||||
`SELECT COUNT(*) AS "row_count", MIN("create_time") AS "min_time", ` +
|
||||
`MAX("create_time") AS "max_time" FROM ${table}${whereSql}`
|
||||
)
|
||||
const row = rows[0] || {}
|
||||
const count = Number(this.pickValue(row, ['row_count', 'count', 'COUNT(*)']))
|
||||
if (!Number.isFinite(count)) throw new Error('计数返回格式无效')
|
||||
total += count
|
||||
const min = Number(this.pickValue(row, ['min_time', 'MIN("create_time")']))
|
||||
const max = Number(this.pickValue(row, ['max_time', 'MAX("create_time")']))
|
||||
if (Number.isFinite(min) && Number.isFinite(max) && max >= min) {
|
||||
ranges.push({ min, max })
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[WCDB4] message count failed username=${username} table=${store.tableName}:`,
|
||||
error
|
||||
)
|
||||
failedStores.push(store.tableName)
|
||||
}
|
||||
}
|
||||
|
||||
if (failedStores.length) {
|
||||
return { count: null, approximate: false, failedStores }
|
||||
}
|
||||
|
||||
ranges.sort((left, right) => left.min - right.min)
|
||||
const approximate = ranges.some(
|
||||
(range, index) => index > 0 && range.min <= ranges[index - 1].max
|
||||
)
|
||||
return { count: total, approximate, failedStores }
|
||||
}
|
||||
|
||||
async getGroupMembersAsync(chatroomId: string): Promise<Wcdb4GroupMember[]> {
|
||||
if (!this.wcdbGetGroupMembers || !chatroomId) return []
|
||||
|
||||
|
||||
Vendored
+15
@@ -168,10 +168,15 @@ import type {
|
||||
QueryAgentProgressEvent
|
||||
} from '../shared/query-agent'
|
||||
import type {
|
||||
KnowledgeIndexScope,
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchIpcRequest,
|
||||
KnowledgeSearchIpcResult
|
||||
} from '../shared/knowledge'
|
||||
import type {
|
||||
ConversationMessageCountEntry,
|
||||
ConversationMessageCountSnapshot
|
||||
} from '../shared/conversation-message-count'
|
||||
import type {
|
||||
PublishWechatShareCardRequest,
|
||||
PublishWechatShareCardResult,
|
||||
@@ -389,9 +394,19 @@ declare global {
|
||||
) => () => void
|
||||
forgetAskWechatConversation: () => Promise<void>
|
||||
getKnowledgeStatus: () => Promise<KnowledgeRuntimeStatus>
|
||||
getConversationActivity: () => Promise<Record<string, number>>
|
||||
getKnowledgeIndexScope: () => Promise<KnowledgeIndexScope>
|
||||
setKnowledgeIndexScope: (scope: KnowledgeIndexScope) => Promise<KnowledgeIndexScope>
|
||||
startKnowledgeIndex: () => Promise<KnowledgeRuntimeStatus>
|
||||
cancelKnowledgeIndex: () => Promise<{ cancellable: boolean; cancelled: boolean }>
|
||||
onKnowledgeStatus: (callback: (status: KnowledgeRuntimeStatus) => void) => () => void
|
||||
getConversationMessageCounts: (
|
||||
conversationIds: string[]
|
||||
) => Promise<ConversationMessageCountSnapshot>
|
||||
cancelConversationMessageCounts: () => Promise<void>
|
||||
onConversationMessageCounts: (
|
||||
callback: (entries: ConversationMessageCountEntry[]) => void
|
||||
) => () => void
|
||||
aiChat: (
|
||||
messages: { role: string; content: string }[],
|
||||
options?: AIChatRequestOptions
|
||||
|
||||
@@ -118,10 +118,15 @@ import type {
|
||||
QueryAgentProgressEvent
|
||||
} from '../shared/query-agent'
|
||||
import type {
|
||||
KnowledgeIndexScope,
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchIpcRequest,
|
||||
KnowledgeSearchIpcResult
|
||||
} from '../shared/knowledge'
|
||||
import type {
|
||||
ConversationMessageCountEntry,
|
||||
ConversationMessageCountSnapshot
|
||||
} from '../shared/conversation-message-count'
|
||||
import type {
|
||||
PublishWechatShareCardRequest,
|
||||
WechatShareServiceConfig
|
||||
@@ -178,6 +183,8 @@ const api = {
|
||||
getBootstrapCache: () => ipcRenderer.invoke('db:getBootstrapCache'),
|
||||
getStartupCache: () => ipcRenderer.invoke('db:getStartupCache'),
|
||||
getContacts: (filter?: string) => ipcRenderer.invoke('db:getContacts', filter),
|
||||
getConversationActivity: (): Promise<Record<string, number>> =>
|
||||
ipcRenderer.invoke('db:conversationActivity'),
|
||||
getContactAvatars: (usernames: string[], options?: { refresh?: boolean }) =>
|
||||
ipcRenderer.invoke('db:getContactAvatars', usernames, options),
|
||||
getCachedMessages: (userMd5: string, startTime?: number, endTime?: number) =>
|
||||
@@ -421,6 +428,25 @@ const api = {
|
||||
ipcRenderer.on('knowledge:status', listener)
|
||||
return () => ipcRenderer.removeListener('knowledge:status', listener)
|
||||
},
|
||||
/** 立即返回已知快照,未知项由 `onConversationMessageCounts` 补齐;null 是未知不是 0。 */
|
||||
getConversationMessageCounts: (conversationIds: string[]): Promise<ConversationMessageCountSnapshot> =>
|
||||
ipcRenderer.invoke('knowledge:getConversationCounts', conversationIds),
|
||||
cancelConversationMessageCounts: (): Promise<void> =>
|
||||
ipcRenderer.invoke('knowledge:cancelConversationCounts'),
|
||||
getKnowledgeIndexScope: (): Promise<KnowledgeIndexScope> =>
|
||||
ipcRenderer.invoke('knowledge:getIndexScope'),
|
||||
setKnowledgeIndexScope: (scope: KnowledgeIndexScope): Promise<KnowledgeIndexScope> =>
|
||||
ipcRenderer.invoke('knowledge:setIndexScope', scope),
|
||||
onConversationMessageCounts: (
|
||||
callback: (entries: ConversationMessageCountEntry[]) => void
|
||||
) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
entries: ConversationMessageCountEntry[]
|
||||
): void => callback(entries)
|
||||
ipcRenderer.on('knowledge:conversationCounts', listener)
|
||||
return () => ipcRenderer.removeListener('knowledge:conversationCounts', listener)
|
||||
},
|
||||
aiChat: (messages: { role: string; content: string }[], options?: AIChatRequestOptions) =>
|
||||
ipcRenderer.invoke('ai:chat', messages, options),
|
||||
listAIProviders: () => ipcRenderer.invoke('ai:listProviders'),
|
||||
|
||||
@@ -14,9 +14,16 @@ export interface MessageJumpTarget {
|
||||
exact: boolean
|
||||
}
|
||||
|
||||
/** 两侧(证据侧 / 归档侧)都用同一套归一化,否则 `local:` 前缀会让匹配静默失败。 */
|
||||
export const normalizeJumpMessageId = (value: string | undefined | null): string =>
|
||||
String(value ?? '').replace(/^local:/, '')
|
||||
/**
|
||||
* 证据侧是 `local:<create_time>:<local_id>`,归档侧只有 `local_id`:取最后一段,否则跳转全落空。
|
||||
*/
|
||||
export const normalizeJumpMessageId = (value: string | undefined | null): string => {
|
||||
const text = String(value ?? '').replace(/^local:/, '')
|
||||
const parts = text.split(':')
|
||||
return parts.length === 2 && /^\d+$/.test(parts[0]) && /^\d+$/.test(parts[1])
|
||||
? parts[1]
|
||||
: text
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析跳转目标。
|
||||
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
knowledgeIsStale,
|
||||
knowledgeStateLabel
|
||||
} from './searchFormatters'
|
||||
import { ConversationMultiSelect } from './ConversationMultiSelect'
|
||||
import { useConversationOptions } from './hooks/useConversationOptions'
|
||||
import { mapPipelineResultToRendererResult } from './searchMappers'
|
||||
import { createSearchResultResetState, resolveSearchResultViewTransition } from './searchState'
|
||||
import { useSearchHistory } from './hooks/useSearchHistory'
|
||||
@@ -70,6 +72,8 @@ export function AISearchWorkspace({
|
||||
const allContacts = useMemo(() => contacts.filter((contact) => contact.md5), [contacts])
|
||||
const [scope, setScope] = useState<SearchScope>('global')
|
||||
const [scopeContactMd5, setScopeContactMd5] = useState(selectedContact?.md5 || '')
|
||||
/** 「指定多个会话」只影响**本次提问**的检索范围,绝不写回长期索引配置。 */
|
||||
const [selectedConversationIds, setSelectedConversationIds] = useState<string[]>([])
|
||||
const [range, setRange] = useState<SearchRange>('30d')
|
||||
const [timeRangeOverride, setTimeRangeOverride] = useState<AiSearchTimeRange | undefined>()
|
||||
const [query, setQuery] = useState('')
|
||||
@@ -92,6 +96,8 @@ export function AISearchWorkspace({
|
||||
const askRequestRef = useRef('')
|
||||
/** Query Agent 是否为当前主路径:控制"搜索范围 / 时间范围"的显隐(主路径隐藏时间范围)。 */
|
||||
const [queryAgentEnabled, setQueryAgentEnabled] = useState(false)
|
||||
// 会话候选只在问答页可见时加载:消息数统计有缓存,但没必要在别的页面空转。
|
||||
const { options: conversationOptions } = useConversationOptions(true)
|
||||
/** Query Agent 本次回答的真实统计(读取条数 / 证据条数 / 模型调用 / 耗时)。 */
|
||||
const [askStats, setAskStats] = useState<AskWechatStats | null>(null)
|
||||
/**
|
||||
@@ -243,9 +249,13 @@ export function AISearchWorkspace({
|
||||
global: '所有聊天记录',
|
||||
groups: '群聊专属',
|
||||
contacts: '单聊专属',
|
||||
conversation: contactLabel(activeContact)
|
||||
conversation: contactLabel(activeContact),
|
||||
selected: `指定 ${selectedConversationIds.length} 个会话`
|
||||
}[scope]
|
||||
|
||||
/** Legacy 表达不了 `selected`,这里给一个不会生效的占位值(服务端会拒绝回退)。 */
|
||||
const legacyScope = scope === 'selected' ? 'global' : scope
|
||||
|
||||
/**
|
||||
* UI 搜索范围 → Query Agent 的 conversationScope(WHERE TO SEARCH)。
|
||||
*
|
||||
@@ -254,6 +264,14 @@ export function AISearchWorkspace({
|
||||
*/
|
||||
const currentAskWechatScope = (): AskWechatScope | undefined => {
|
||||
if (scope === 'global') return { scope: { kind: 'all' }, label: '所有聊天记录' }
|
||||
if (scope === 'selected') {
|
||||
// 空选择不返回 undefined(那会被当成"不限制"),由提交前的守卫直接拦住。
|
||||
if (!selectedConversationIds.length) return undefined
|
||||
return {
|
||||
scope: { kind: 'selected', conversationIds: [...selectedConversationIds] },
|
||||
label: `指定 ${selectedConversationIds.length} 个会话`
|
||||
}
|
||||
}
|
||||
if (scope === 'groups') return { scope: { kind: 'groups' }, label: '群聊专属' }
|
||||
if (scope === 'contacts') {
|
||||
const contact = allContacts.find(
|
||||
@@ -315,6 +333,11 @@ export function AISearchWorkspace({
|
||||
): Promise<void> => {
|
||||
event?.preventDefault()
|
||||
if (stage === 'loading') return
|
||||
// 空选择绝不能落到"不限制":那会把用户以为的"只查这两个群"变成搜全库。
|
||||
if (scope === 'selected' && !selectedConversationIds.length) {
|
||||
onNotice('请先选择要搜索的会话')
|
||||
return
|
||||
}
|
||||
// 索引同步中**不允许**禁止查询:同步是后台的、可取消的、可断点续传的;
|
||||
// 索引没追平时按 partial + freshness warning 如实作答(覆盖范围由主进程的
|
||||
// coverage/freshness 契约给出),绝不把用户挡在门外。
|
||||
@@ -432,7 +455,7 @@ export function AISearchWorkspace({
|
||||
// 搜索范围是 UI 决定的数据边界;时间不在 UI 上(写进问题,由 temporalBasis 理解)。
|
||||
scope: currentAskWechatScope(),
|
||||
legacy: {
|
||||
scope,
|
||||
scope: legacyScope,
|
||||
range: effectiveRange,
|
||||
conversationId,
|
||||
timeRangeOverride: effectiveTimeRangeOverride
|
||||
@@ -491,7 +514,7 @@ export function AISearchWorkspace({
|
||||
const outcome = await startSearch({
|
||||
requestId,
|
||||
text: normalizedQuery,
|
||||
scope,
|
||||
scope: legacyScope,
|
||||
range: effectiveRange,
|
||||
conversationId,
|
||||
timeRangeOverride: effectiveTimeRangeOverride
|
||||
@@ -1160,6 +1183,15 @@ export function AISearchWorkspace({
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={scope === 'selected' ? 'active' : ''}
|
||||
onClick={() => setScope('selected')}
|
||||
>
|
||||
<span aria-hidden>☷</span>
|
||||
指定多个会话
|
||||
{selectedConversationIds.length ? ` · ${selectedConversationIds.length}` : ''}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={scope === 'conversation' ? 'active' : ''}
|
||||
@@ -1178,6 +1210,19 @@ export function AISearchWorkspace({
|
||||
当前会话{activeContact ? ` · ${contactLabel(activeContact)}` : ''}
|
||||
</button>
|
||||
</div>
|
||||
{scope === 'selected' ? (
|
||||
<div className="ai-search-selected-scope">
|
||||
<ConversationMultiSelect
|
||||
options={conversationOptions}
|
||||
selectedIds={selectedConversationIds}
|
||||
onChange={setSelectedConversationIds}
|
||||
triggerLabel="选择本次要搜索的会话"
|
||||
/>
|
||||
<p className="ai-search-scope-hint">
|
||||
只影响这一次提问。要长期只索引这些会话,请到「设置 → 本地索引 → 索引范围」。
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
{/* 单聊专属需要一个明确的联系人(Legacy 下同样由档案选择决定,这里在 Query Agent 主路径提供显式选择) */}
|
||||
{queryAgentEnabled && scope === 'contacts' && (
|
||||
<Select
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
import * as React from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { Checkbox } from '../ui'
|
||||
import { cn } from '../../lib/cn'
|
||||
|
||||
/** 一个可被勾选的会话。 */
|
||||
export interface ConversationSelectOption {
|
||||
conversationId: string
|
||||
name: string
|
||||
type: 'user' | 'group'
|
||||
/** `null` = 数量未知(统计失败或尚未统计)。**不能**当成 0。 */
|
||||
messageCount: number | null
|
||||
/** 分片重叠导致条数只是上限时为 true。 */
|
||||
approximate: boolean
|
||||
/** 最后活跃时间(epoch ms);`null` = 无可靠数据。 */
|
||||
lastActiveAt: number | null
|
||||
/** 区分「还在统计」与「统计失败」:两者都是 null,都不能显示成 0。 */
|
||||
countMeasured: boolean
|
||||
/** 名称之外可被搜到的文本:备注 / 昵称 / 微信号。 */
|
||||
keywords: string
|
||||
}
|
||||
|
||||
export type ConversationSortMode = 'messages-desc' | 'messages-asc' | 'recent' | 'name'
|
||||
export type ConversationTypeFilter = 'all' | 'group' | 'user'
|
||||
|
||||
export const CONVERSATION_SORT_LABELS: Record<ConversationSortMode, string> = {
|
||||
'messages-desc': '消息数最多',
|
||||
'messages-asc': '消息数最少',
|
||||
recent: '最近活跃',
|
||||
name: '名称'
|
||||
}
|
||||
|
||||
function normalize(value: string): string {
|
||||
return value.toLocaleLowerCase().replace(/\s+/g, '')
|
||||
}
|
||||
|
||||
/** 未知数量恒排最后(升降序都一样):混进最小端会被读成"这个群没消息"。 */
|
||||
export function sortConversationOptions(
|
||||
options: readonly ConversationSelectOption[],
|
||||
mode: ConversationSortMode
|
||||
): ConversationSelectOption[] {
|
||||
const byName = (left: ConversationSelectOption, right: ConversationSelectOption): number =>
|
||||
left.name.localeCompare(right.name, 'zh-Hans-CN')
|
||||
|
||||
const sorted = [...options]
|
||||
if (mode === 'name') return sorted.sort(byName)
|
||||
|
||||
if (mode === 'recent') {
|
||||
return sorted.sort((left, right) => {
|
||||
const leftAt = left.lastActiveAt ?? -1
|
||||
const rightAt = right.lastActiveAt ?? -1
|
||||
if (leftAt !== rightAt) return rightAt - leftAt
|
||||
return byName(left, right)
|
||||
})
|
||||
}
|
||||
|
||||
const direction = mode === 'messages-desc' ? -1 : 1
|
||||
return sorted.sort((left, right) => {
|
||||
const leftCount = left.messageCount
|
||||
const rightCount = right.messageCount
|
||||
if (leftCount === null && rightCount === null) return byName(left, right)
|
||||
if (leftCount === null) return 1
|
||||
if (rightCount === null) return -1
|
||||
if (leftCount !== rightCount) return (leftCount - rightCount) * direction
|
||||
return byName(left, right)
|
||||
})
|
||||
}
|
||||
|
||||
export function filterConversationOptions(
|
||||
options: readonly ConversationSelectOption[],
|
||||
criteria: {
|
||||
query?: string
|
||||
typeFilter?: ConversationTypeFilter
|
||||
onlySelected?: boolean
|
||||
selectedIds?: readonly string[]
|
||||
}
|
||||
): ConversationSelectOption[] {
|
||||
const query = normalize(criteria.query ?? '')
|
||||
const selected = new Set(criteria.selectedIds ?? [])
|
||||
return options.filter((option) => {
|
||||
if (criteria.typeFilter && criteria.typeFilter !== 'all' && option.type !== criteria.typeFilter) {
|
||||
return false
|
||||
}
|
||||
if (criteria.onlySelected && !selected.has(option.conversationId)) return false
|
||||
if (!query) return true
|
||||
return (
|
||||
normalize(option.name).includes(query) || normalize(option.keywords).includes(query)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** 已知条数之和;有未知项时 `unknownCount > 0`,调用方必须显示「至少」。 */
|
||||
export function summarizeSelection(
|
||||
options: readonly ConversationSelectOption[],
|
||||
selectedIds: readonly string[]
|
||||
): { conversations: number; messages: number; unknownCount: number } {
|
||||
const selected = new Set(selectedIds)
|
||||
let messages = 0
|
||||
let unknownCount = 0
|
||||
for (const option of options) {
|
||||
if (!selected.has(option.conversationId)) continue
|
||||
if (option.messageCount === null) unknownCount += 1
|
||||
else messages += option.messageCount
|
||||
}
|
||||
return { conversations: selected.size, messages, unknownCount }
|
||||
}
|
||||
|
||||
export function formatConversationCount(
|
||||
count: number | null,
|
||||
approximate: boolean,
|
||||
measured = true
|
||||
): string {
|
||||
// 失败是"未知",不是"永远统计中":这两种状态必须能分辨,否则用户会一直等。
|
||||
if (count === null) return measured ? '未知' : '统计中'
|
||||
const text = count.toLocaleString()
|
||||
return approximate ? `≥ ${text}` : text
|
||||
}
|
||||
|
||||
const ROW_HEIGHT = 52
|
||||
const LIST_HEIGHT = 300
|
||||
const VIRTUALIZE_THRESHOLD = 60
|
||||
|
||||
interface ConversationMultiSelectProps {
|
||||
options: readonly ConversationSelectOption[]
|
||||
selectedIds: readonly string[]
|
||||
onChange: (conversationIds: string[]) => void
|
||||
disabled?: boolean
|
||||
/** 空列表时的提示,例如「还没有可索引的会话」。 */
|
||||
emptyHint?: string
|
||||
/** 触发器上的说明文案,两个页面语义不同,必须各自写清楚。 */
|
||||
triggerLabel?: string
|
||||
}
|
||||
|
||||
/** 选择状态由父组件持有:两个页面的语义不同(单次查询 vs 长期索引),组件不持久化。 */
|
||||
export function ConversationMultiSelect({
|
||||
options,
|
||||
selectedIds,
|
||||
onChange,
|
||||
disabled,
|
||||
emptyHint = '没有匹配的会话',
|
||||
triggerLabel = '选择会话'
|
||||
}: ConversationMultiSelectProps): React.ReactElement {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [query, setQuery] = React.useState('')
|
||||
const [sortMode, setSortMode] = React.useState<ConversationSortMode>('messages-desc')
|
||||
const [typeFilter, setTypeFilter] = React.useState<ConversationTypeFilter>('all')
|
||||
const [onlySelected, setOnlySelected] = React.useState(false)
|
||||
const scrollRef = React.useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const selectedSet = React.useMemo(() => new Set(selectedIds), [selectedIds])
|
||||
const visible = React.useMemo(
|
||||
() =>
|
||||
sortConversationOptions(
|
||||
filterConversationOptions(options, { query, typeFilter, onlySelected, selectedIds }),
|
||||
sortMode
|
||||
),
|
||||
[options, query, typeFilter, onlySelected, selectedIds, sortMode]
|
||||
)
|
||||
const summary = React.useMemo(
|
||||
() => summarizeSelection(options, selectedIds),
|
||||
[options, selectedIds]
|
||||
)
|
||||
|
||||
const toggle = React.useCallback(
|
||||
(conversationId: string): void => {
|
||||
const next = new Set(selectedIds)
|
||||
if (next.has(conversationId)) next.delete(conversationId)
|
||||
else next.add(conversationId)
|
||||
onChange(Array.from(next))
|
||||
},
|
||||
[onChange, selectedIds]
|
||||
)
|
||||
|
||||
const selectVisible = React.useCallback((): void => {
|
||||
const next = new Set(selectedIds)
|
||||
for (const option of visible) next.add(option.conversationId)
|
||||
onChange(Array.from(next))
|
||||
}, [onChange, selectedIds, visible])
|
||||
|
||||
const virtualize = visible.length > VIRTUALIZE_THRESHOLD
|
||||
const virtualizer = useVirtualizer({
|
||||
count: virtualize ? visible.length : 0,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => ROW_HEIGHT,
|
||||
overscan: 8
|
||||
})
|
||||
|
||||
const triggerText = summary.conversations
|
||||
? `已选 ${summary.conversations} 个会话`
|
||||
: triggerLabel
|
||||
|
||||
return (
|
||||
<div className="conversation-multi-select">
|
||||
<button
|
||||
type="button"
|
||||
className={cn('cms-trigger', open && 'is-open')}
|
||||
disabled={disabled}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<span className="cms-trigger-label">{triggerText}</span>
|
||||
<span className="cms-trigger-count">
|
||||
{summary.conversations
|
||||
? `${summary.unknownCount ? '至少 ' : ''}${summary.messages.toLocaleString()} 条消息`
|
||||
: '未选择'}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div className="cms-panel" role="dialog" aria-label="选择会话">
|
||||
<div className="cms-toolbar">
|
||||
<input
|
||||
className="cms-search"
|
||||
type="search"
|
||||
value={query}
|
||||
placeholder="搜索群名、备注、昵称或微信号"
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
<select
|
||||
className="cms-select"
|
||||
value={sortMode}
|
||||
aria-label="排序方式"
|
||||
onChange={(event) => setSortMode(event.target.value as ConversationSortMode)}
|
||||
>
|
||||
{(Object.keys(CONVERSATION_SORT_LABELS) as ConversationSortMode[]).map((mode) => (
|
||||
<option key={mode} value={mode}>
|
||||
{CONVERSATION_SORT_LABELS[mode]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="cms-filters">
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['group', '仅群聊'],
|
||||
['user', '仅单聊'],
|
||||
['selected', '仅已选']
|
||||
] as const
|
||||
).map(([value, label]) => {
|
||||
const active =
|
||||
value === 'selected' ? onlySelected : !onlySelected && typeFilter === value
|
||||
return (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
className={cn('cms-filter', active && 'is-active')}
|
||||
onClick={() => {
|
||||
if (value === 'selected') {
|
||||
setOnlySelected(true)
|
||||
return
|
||||
}
|
||||
setOnlySelected(false)
|
||||
setTypeFilter(value)
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
<span className="cms-filter-spacer" />
|
||||
<button type="button" className="cms-link" onClick={selectVisible}>
|
||||
选择当前结果
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="cms-link"
|
||||
onClick={() => onChange([])}
|
||||
disabled={!selectedIds.length}
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="cms-list" ref={scrollRef} style={{ height: LIST_HEIGHT }}>
|
||||
{visible.length === 0 ? (
|
||||
<p className="cms-empty">{emptyHint}</p>
|
||||
) : virtualize ? (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
const option = visible[item.index]
|
||||
return (
|
||||
<div
|
||||
key={option.conversationId}
|
||||
className="cms-row"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: item.size,
|
||||
transform: `translateY(${item.start}px)`
|
||||
}}
|
||||
>
|
||||
<ConversationRow
|
||||
option={option}
|
||||
checked={selectedSet.has(option.conversationId)}
|
||||
onToggle={toggle}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
visible.map((option) => (
|
||||
<ConversationRow
|
||||
key={option.conversationId}
|
||||
option={option}
|
||||
checked={selectedSet.has(option.conversationId)}
|
||||
onToggle={toggle}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="cms-footer">
|
||||
<span>
|
||||
已选 {summary.conversations} 个 · 共{' '}
|
||||
{summary.unknownCount ? '至少 ' : ''}
|
||||
{summary.messages.toLocaleString()} 条消息
|
||||
{summary.unknownCount ? ` · ${summary.unknownCount} 个会话数量未知` : ''}
|
||||
</span>
|
||||
<button type="button" className="cms-link" onClick={() => setOpen(false)}>
|
||||
完成
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ConversationRow({
|
||||
option,
|
||||
checked,
|
||||
onToggle
|
||||
}: {
|
||||
option: ConversationSelectOption
|
||||
checked: boolean
|
||||
onToggle: (conversationId: string) => void
|
||||
}): React.ReactElement {
|
||||
const countText = formatConversationCount(
|
||||
option.messageCount,
|
||||
option.approximate,
|
||||
option.countMeasured
|
||||
)
|
||||
return (
|
||||
<label className="cms-row-inner" data-selected={checked ? 'true' : undefined}>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
aria-label={option.name}
|
||||
onCheckedChange={() => onToggle(option.conversationId)}
|
||||
/>
|
||||
<span className="cms-row-main">
|
||||
<span className="cms-row-name">{option.name}</span>
|
||||
<span className="cms-row-meta">
|
||||
{option.type === 'group' ? '群聊' : '单聊'} · {countText} 条
|
||||
{option.messageCount !== null && option.approximate ? '(估算)' : ''}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -114,6 +114,10 @@ export function ImageTextIndexSummary({
|
||||
|
||||
return (
|
||||
<section className="local-index-card" aria-label="图片文字索引状态">
|
||||
{/* 覆盖范围必须写清楚:它目前不跟随「索引范围」,不能让人以为两套索引都已过滤。 */}
|
||||
<p className="local-index-note">
|
||||
图片文字索引当前覆盖全部会话,不受上方「索引范围」影响。
|
||||
</p>
|
||||
<header className="local-index-card-head">
|
||||
<div className="local-index-card-title">
|
||||
<h3>图片文字索引</h3>
|
||||
|
||||
@@ -95,6 +95,24 @@ export function KnowledgeIndexCard({
|
||||
</p>
|
||||
)}
|
||||
|
||||
{knowledgeSyncing && knowledgeStatus?.pass ? (
|
||||
<div className="local-index-progress" aria-label="索引进度">
|
||||
<span>
|
||||
会话 {knowledgeStatus.pass.processedConversations} /{' '}
|
||||
{knowledgeStatus.pass.totalConversations}
|
||||
</span>
|
||||
<span>已索引 {knowledgeStatus.pass.indexedMessages.toLocaleString()} 条</span>
|
||||
{knowledgeStatus.pass.currentConversationProcessed ? (
|
||||
<span>
|
||||
当前会话 {knowledgeStatus.pass.currentConversationProcessed.toLocaleString()} 条
|
||||
</span>
|
||||
) : null}
|
||||
{knowledgeStatus.pass.excludedConversations > 0 ? (
|
||||
<span>按范围排除 {knowledgeStatus.pass.excludedConversations} 个会话</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{failed && knowledgeStatus?.lastError ? (
|
||||
<p className="local-index-note is-error">{knowledgeStatus.lastError}</p>
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import * as React from 'react'
|
||||
import type { ConversationMessageCountEntry } from '../../../../../shared/conversation-message-count'
|
||||
import type { ConversationSelectOption } from '../ConversationMultiSelect'
|
||||
|
||||
interface ContactLike {
|
||||
md5: string
|
||||
m_nsNickName: string
|
||||
m_nsUsrName: string
|
||||
type: 'user' | 'group'
|
||||
remark?: string
|
||||
wechatNickname?: string
|
||||
wechatId?: string
|
||||
wxid?: string
|
||||
alias?: string
|
||||
isOfficialAccount?: boolean
|
||||
}
|
||||
|
||||
function toOption(
|
||||
contact: ContactLike,
|
||||
count: ConversationMessageCountEntry | undefined,
|
||||
activity: Record<string, number>
|
||||
): ConversationSelectOption {
|
||||
const keywords = [
|
||||
contact.remark,
|
||||
contact.wechatNickname,
|
||||
contact.wechatId,
|
||||
contact.wxid,
|
||||
contact.alias,
|
||||
contact.m_nsUsrName
|
||||
]
|
||||
.filter((value): value is string => Boolean(value && value.trim()))
|
||||
.join(' ')
|
||||
const lastActiveAt = activity[contact.md5]
|
||||
return {
|
||||
conversationId: contact.md5,
|
||||
name: contact.m_nsNickName || contact.remark || contact.wechatId || contact.m_nsUsrName,
|
||||
type: contact.type,
|
||||
messageCount: count?.count ?? null,
|
||||
approximate: count?.approximate ?? false,
|
||||
countMeasured: (count?.measuredAt ?? 0) > 0,
|
||||
lastActiveAt: typeof lastActiveAt === 'number' && lastActiveAt > 0 ? lastActiveAt : null,
|
||||
keywords
|
||||
}
|
||||
}
|
||||
|
||||
/** 消息数只来自只读 COUNT(*),绝不为排序读正文;未知保持 null。 */
|
||||
export function useConversationOptions(enabled: boolean): {
|
||||
options: ConversationSelectOption[]
|
||||
loading: boolean
|
||||
failed: boolean
|
||||
} {
|
||||
const [contacts, setContacts] = React.useState<ContactLike[]>([])
|
||||
const [counts, setCounts] = React.useState<Map<string, ConversationMessageCountEntry>>(
|
||||
() => new Map()
|
||||
)
|
||||
const [activity, setActivity] = React.useState<Record<string, number>>({})
|
||||
const [loading, setLoading] = React.useState(false)
|
||||
const [failed, setFailed] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!enabled) return
|
||||
let disposed = false
|
||||
setLoading(true)
|
||||
setFailed(false)
|
||||
|
||||
// 旧 preload(渲染层先加载到新代码、桥还是旧的)不该让整个搜索页崩掉。
|
||||
const unsubscribe =
|
||||
window.api.onConversationMessageCounts?.((entries) => {
|
||||
if (disposed) return
|
||||
setCounts((current) => {
|
||||
const next = new Map(current)
|
||||
for (const entry of entries) next.set(entry.conversationId, entry)
|
||||
return next
|
||||
})
|
||||
}) ?? (() => undefined)
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const list = (await window.api.getContacts()) as ContactLike[]
|
||||
if (disposed) return
|
||||
// 公众号不是聊天会话,进索引只会制造噪音。
|
||||
const conversations = (Array.isArray(list) ? list : []).filter(
|
||||
(contact) => contact?.md5 && !contact.isOfficialAccount
|
||||
)
|
||||
setContacts(conversations)
|
||||
|
||||
const ids = conversations.map((contact) => contact.md5)
|
||||
const snapshot = (await window.api.getConversationMessageCounts?.(ids)) ?? { entries: [] }
|
||||
if (disposed) return
|
||||
const seeded = new Map<string, ConversationMessageCountEntry>()
|
||||
for (const entry of snapshot.entries) seeded.set(entry.conversationId, entry)
|
||||
setCounts(seeded)
|
||||
|
||||
const activityRequest = window.api.getConversationActivity?.()
|
||||
const activityMap = activityRequest ? await activityRequest.catch(() => ({})) : {}
|
||||
if (disposed) return
|
||||
setActivity(activityMap ?? {})
|
||||
} catch {
|
||||
if (!disposed) setFailed(true)
|
||||
} finally {
|
||||
if (!disposed) setLoading(false)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
unsubscribe()
|
||||
}
|
||||
}, [enabled])
|
||||
|
||||
const options = React.useMemo(
|
||||
() => contacts.map((contact) => toOption(contact, counts.get(contact.md5), activity)),
|
||||
[contacts, counts, activity]
|
||||
)
|
||||
|
||||
return { options, loading, failed }
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
import type { Contact, Message } from '../../../../shared/types'
|
||||
|
||||
export type SearchStage = 'idle' | 'loading' | 'result' | 'partial' | 'insufficient'
|
||||
export type SearchScope = 'global' | 'groups' | 'contacts' | 'conversation'
|
||||
export type SearchScope = 'global' | 'groups' | 'contacts' | 'conversation' | 'selected'
|
||||
export type SearchRange = 'today' | '7d' | '30d' | 'all'
|
||||
export type SearchIntent = 'general' | 'topic' | 'participants' | 'mixed'
|
||||
|
||||
|
||||
@@ -320,19 +320,23 @@ export const buildSearchCacheKey = (
|
||||
range: SearchRange,
|
||||
query: string,
|
||||
resolvedTimeRange?: Pick<AiSearchTimeRange, 'startTime' | 'endTime'>,
|
||||
knowledgeGeneration?: string
|
||||
knowledgeGeneration?: string,
|
||||
/** 会话集合身份,放末尾:旧 key 的段位不变,老解析函数不受影响。 */
|
||||
selectionKey?: string
|
||||
): string => {
|
||||
const base = [scope, contactMd5, range, query.trim().toLowerCase()]
|
||||
const hasResolvedTime = Boolean(
|
||||
resolvedTimeRange &&
|
||||
(resolvedTimeRange.startTime !== undefined || resolvedTimeRange.endTime !== undefined)
|
||||
)
|
||||
if (!hasResolvedTime && !knowledgeGeneration) return JSON.stringify(base)
|
||||
if (!hasResolvedTime && !knowledgeGeneration && !selectionKey) return JSON.stringify(base)
|
||||
return JSON.stringify([
|
||||
...base,
|
||||
hasResolvedTime ? resolvedTimeRange?.startTime ?? null : null,
|
||||
hasResolvedTime ? resolvedTimeRange?.endTime ?? null : null,
|
||||
knowledgeGeneration || null
|
||||
knowledgeGeneration || null,
|
||||
// 键里再排序一次:调用方可能传未排序的集合,范围身份不该随选择顺序变化。
|
||||
selectionKey ? [...selectionKey.split(',')].sort().join(',') : null
|
||||
])
|
||||
}
|
||||
|
||||
@@ -342,6 +346,8 @@ export type CreateSearchRequestContextInput = {
|
||||
range: SearchRange
|
||||
timeRangeOverride?: AiSearchTimeRange
|
||||
activeContactMd5?: string
|
||||
/** 「指定多个会话」的会话 id;排序后参与缓存键。 */
|
||||
selectedIds?: readonly string[]
|
||||
now?: Date
|
||||
knowledgeGeneration?: string
|
||||
retry?: {
|
||||
@@ -365,6 +371,7 @@ export const createSearchRequestContext = ({
|
||||
range,
|
||||
timeRangeOverride,
|
||||
activeContactMd5,
|
||||
selectedIds,
|
||||
now,
|
||||
knowledgeGeneration,
|
||||
retry
|
||||
@@ -392,7 +399,8 @@ export const createSearchRequestContext = ({
|
||||
effectiveRange,
|
||||
normalizedQuery,
|
||||
resolvedTimeRange,
|
||||
knowledgeGeneration
|
||||
knowledgeGeneration,
|
||||
selectedIds?.length ? [...selectedIds].sort().join(',') : ''
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import * as React from 'react'
|
||||
import type { KnowledgeIndexScope } from '../../../../../shared/knowledge'
|
||||
import { DEFAULT_KNOWLEDGE_INDEX_SCOPE } from '../../../../../shared/knowledge'
|
||||
import {
|
||||
ConversationMultiSelect,
|
||||
summarizeSelection
|
||||
} from '../../../components/search/ConversationMultiSelect'
|
||||
import { useConversationOptions } from '../../../components/search/hooks/useConversationOptions'
|
||||
import { Button } from '../../../components/ui'
|
||||
|
||||
interface KnowledgeScopeCardProps {
|
||||
dbReady: boolean
|
||||
onNotice: (message: string) => void
|
||||
}
|
||||
|
||||
function sameIds(left: readonly string[], right: readonly string[]): boolean {
|
||||
if (left.length !== right.length) return false
|
||||
const set = new Set(left)
|
||||
return right.every((id) => set.has(id))
|
||||
}
|
||||
|
||||
function sameScope(left: KnowledgeIndexScope, right: KnowledgeIndexScope): boolean {
|
||||
// `selected` + 空数组是「不索引任何会话」,与 `all` 必须区分开。
|
||||
return left.mode === right.mode && sameIds(left.conversationIds, right.conversationIds)
|
||||
}
|
||||
|
||||
/** 长期索引范围,按账号持久化;与「问问微信」的一次性范围是两件事。 */
|
||||
export function KnowledgeScopeCard({
|
||||
dbReady,
|
||||
onNotice
|
||||
}: KnowledgeScopeCardProps): React.ReactElement {
|
||||
const { options, loading } = useConversationOptions(true)
|
||||
const [saved, setSaved] = React.useState<KnowledgeIndexScope>(DEFAULT_KNOWLEDGE_INDEX_SCOPE)
|
||||
const [draft, setDraft] = React.useState<KnowledgeIndexScope>(DEFAULT_KNOWLEDGE_INDEX_SCOPE)
|
||||
const [ready, setReady] = React.useState(false)
|
||||
const [saving, setSaving] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
let disposed = false
|
||||
// 旧 preload 没有这个通道时退化成「全部会话」,不阻塞页面渲染。
|
||||
const request = window.api.getKnowledgeIndexScope?.()
|
||||
if (!request) {
|
||||
setReady(true)
|
||||
return
|
||||
}
|
||||
void request
|
||||
.then((scope) => {
|
||||
if (disposed) return
|
||||
setSaved(scope)
|
||||
setDraft(scope)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!disposed) setReady(true)
|
||||
})
|
||||
return () => {
|
||||
disposed = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const dirty = ready && !sameScope(saved, draft)
|
||||
const summary = summarizeSelection(options, draft.conversationIds)
|
||||
|
||||
const apply = async (): Promise<void> => {
|
||||
setSaving(true)
|
||||
try {
|
||||
const next = (await window.api.setKnowledgeIndexScope?.(draft)) ?? draft
|
||||
setSaved(next)
|
||||
setDraft(next)
|
||||
onNotice('索引范围已更新')
|
||||
} catch {
|
||||
onNotice('索引范围保存失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="local-index-card knowledge-scope-card" aria-label="索引范围">
|
||||
<header className="local-index-card-head">
|
||||
<div className="local-index-card-title">
|
||||
<h3>索引范围</h3>
|
||||
<p>决定哪些会话会被自动建立和更新索引</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="scope-mode-list">
|
||||
<label
|
||||
className="scope-mode-option"
|
||||
data-active={draft.mode === 'all' ? 'true' : undefined}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="knowledge-scope-mode"
|
||||
checked={draft.mode === 'all'}
|
||||
disabled={!ready || saving}
|
||||
onChange={() => setDraft({ mode: 'all', conversationIds: [] })}
|
||||
/>
|
||||
<span className="scope-mode-text">
|
||||
<span className="scope-mode-title">全部会话</span>
|
||||
<span className="scope-mode-hint">
|
||||
所有聊天记录都会建立索引。会话很多时首次同步会比较久。
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label
|
||||
className="scope-mode-option"
|
||||
data-active={draft.mode === 'selected' ? 'true' : undefined}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="knowledge-scope-mode"
|
||||
checked={draft.mode === 'selected'}
|
||||
disabled={!ready || saving}
|
||||
onChange={() => setDraft({ ...draft, mode: 'selected' })}
|
||||
/>
|
||||
<span className="scope-mode-text">
|
||||
<span className="scope-mode-title">仅索引我选择的会话</span>
|
||||
<span className="scope-mode-hint">
|
||||
只处理勾选的群聊或联系人;未勾选的会话不会被回填,也不会被增量同步。
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{draft.mode === 'selected' ? (
|
||||
<div className="scope-selection">
|
||||
<ConversationMultiSelect
|
||||
options={options}
|
||||
selectedIds={draft.conversationIds}
|
||||
disabled={!ready || saving}
|
||||
triggerLabel="选择要建立索引的会话"
|
||||
emptyHint={loading ? '正在读取会话列表…' : '没有匹配的会话'}
|
||||
onChange={(conversationIds) => setDraft({ mode: 'selected', conversationIds })}
|
||||
/>
|
||||
<p className="scope-selection-summary">
|
||||
{summary.conversations === 0
|
||||
? '还没有选择任何会话。这种状态下不会索引任何群聊,也与「全部会话」不同。'
|
||||
: `已选 ${summary.conversations} 个会话 · ${
|
||||
summary.unknownCount ? '至少 ' : ''
|
||||
}${summary.messages.toLocaleString()} 条消息${
|
||||
summary.unknownCount ? `(${summary.unknownCount} 个会话数量未知)` : ''
|
||||
}`}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!dbReady ? (
|
||||
<p className="local-index-note is-error">请先连接微信数据,然后再设置索引范围。</p>
|
||||
) : null}
|
||||
|
||||
<div className="scope-actions">
|
||||
<p className="scope-warning">
|
||||
{dirty
|
||||
? '应用后,正在进行的同步会先在安全边界停止,再按新范围重新开始。已建立的索引不会被删除。'
|
||||
: '已有索引不会被自动清理;要删除请使用缓存清理。'}
|
||||
</p>
|
||||
<Button size="sm" disabled={!dirty || saving || !dbReady} onClick={() => void apply()}>
|
||||
{saving ? '正在应用…' : '应用范围'}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react'
|
||||
import { ImageTextIndexSummary } from '../../../components/search/ImageTextIndexSummary'
|
||||
import { KnowledgeIndexCard } from '../../../components/search/KnowledgeIndexCard'
|
||||
import { KnowledgeScopeCard } from '../components/KnowledgeScopeCard'
|
||||
|
||||
interface LocalIndexPageProps {
|
||||
onNotice: (message: string) => void
|
||||
@@ -29,6 +30,7 @@ export function LocalIndexPage({ onNotice, dbReady }: LocalIndexPageProps): Reac
|
||||
</header>
|
||||
<div className="local-index-cards">
|
||||
<KnowledgeIndexCard dbReady={dbReady} onNotice={onNotice} />
|
||||
<KnowledgeScopeCard dbReady={dbReady} onNotice={onNotice} />
|
||||
<ImageTextIndexSummary dbReady={dbReady} onNotice={onNotice} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* 可搜索多选会话框。
|
||||
*
|
||||
* 不用裸 Tailwind:`tailwind.config.cjs` 设了 `preflight: false`,裸类拿不到
|
||||
* 浏览器默认重置,会直接崩掉版式。这里只定义组件自己的类名。
|
||||
*/
|
||||
|
||||
.conversation-multi-select {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cms-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
min-height: 38px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--wxex-border);
|
||||
border-radius: 8px;
|
||||
background: var(--wxex-surface);
|
||||
color: var(--wxex-text-primary);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.cms-trigger:hover:not(:disabled) {
|
||||
border-color: var(--wxex-primary);
|
||||
}
|
||||
|
||||
.cms-trigger.is-open {
|
||||
border-color: var(--wxex-primary);
|
||||
}
|
||||
|
||||
.cms-trigger:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.cms-trigger-label {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cms-trigger-count {
|
||||
color: var(--wxex-text-secondary);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cms-panel {
|
||||
position: absolute;
|
||||
z-index: 40;
|
||||
top: calc(100% + 6px);
|
||||
left: 0;
|
||||
width: min(480px, 100%);
|
||||
padding: 12px;
|
||||
border: 1px solid var(--wxex-border);
|
||||
border-radius: 10px;
|
||||
background: var(--wxex-surface);
|
||||
box-shadow: 0 12px 32px rgb(0 0 0 / 16%);
|
||||
}
|
||||
|
||||
.cms-toolbar {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.cms-search {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 32px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--wxex-border);
|
||||
border-radius: 6px;
|
||||
background: var(--wxex-surface);
|
||||
color: var(--wxex-text-primary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.cms-select {
|
||||
height: 32px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--wxex-border);
|
||||
border-radius: 6px;
|
||||
background: var(--wxex-surface);
|
||||
color: var(--wxex-text-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cms-filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.cms-filter {
|
||||
height: 26px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
background: var(--wxex-surface-sunken);
|
||||
color: var(--wxex-text-secondary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cms-filter.is-active {
|
||||
border-color: var(--wxex-primary);
|
||||
background: var(--wxex-primary-soft);
|
||||
color: var(--wxex-primary);
|
||||
}
|
||||
|
||||
.cms-filter-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.cms-link {
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--wxex-primary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.cms-link:disabled {
|
||||
color: var(--wxex-text-tertiary);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.cms-list {
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--wxex-border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.cms-empty {
|
||||
margin: 0;
|
||||
padding: 24px 12px;
|
||||
color: var(--wxex-text-secondary);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cms-row {
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.cms-row-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 52px;
|
||||
padding: 0 4px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cms-row-inner:hover {
|
||||
background: var(--wxex-surface-sunken);
|
||||
}
|
||||
|
||||
.cms-row-inner[data-selected='true'] {
|
||||
background: var(--wxex-primary-soft);
|
||||
}
|
||||
|
||||
.cms-row-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cms-row-name {
|
||||
overflow: hidden;
|
||||
color: var(--wxex-text-primary);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cms-row-meta {
|
||||
color: var(--wxex-text-secondary);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.cms-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding-top: 8px;
|
||||
color: var(--wxex-text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---- 索引范围卡片 ---- */
|
||||
|
||||
.knowledge-scope-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.scope-mode-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.scope-mode-option {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--wxex-border);
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.scope-mode-option[data-active='true'] {
|
||||
border-color: var(--wxex-primary);
|
||||
background: var(--wxex-primary-soft);
|
||||
}
|
||||
|
||||
.scope-mode-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.scope-mode-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--wxex-text-primary);
|
||||
}
|
||||
|
||||
.scope-mode-hint {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--wxex-text-secondary);
|
||||
}
|
||||
|
||||
.scope-selection {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.scope-selection-summary {
|
||||
font-size: 12px;
|
||||
color: var(--wxex-text-secondary);
|
||||
}
|
||||
|
||||
.scope-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.scope-warning {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: var(--wxex-warning, #b45309);
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
@use './group-exit-event';
|
||||
@use './group-member-stats';
|
||||
@use './local-index';
|
||||
@use './conversation-multi-select';
|
||||
@use './automation';
|
||||
@use './extensions';
|
||||
@use './theme';
|
||||
@@ -47,6 +47,17 @@
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
/* ---- 行进中的分批进度 ---- */
|
||||
|
||||
.local-index-progress {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 16px;
|
||||
font-size: 12px;
|
||||
color: var(--wxex-text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---- 卡片容器 ---- */
|
||||
|
||||
.local-index-cards {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/** `measuredAt` 是 epoch ms;`count: null` 是「未知」,调用方不得当成 0。 */
|
||||
export interface ConversationMessageCountEntry {
|
||||
conversationId: string
|
||||
/** `null` = 未知(统计失败,或尚未统计)。 */
|
||||
count: number | null
|
||||
/**
|
||||
* 分片时间范围存在重叠时为 true:重叠区可能有迁移留下的重复行,
|
||||
* 此时 `count` 是上限而不是精确条数,UI 必须显示为估算。
|
||||
*/
|
||||
approximate: boolean
|
||||
/** 统计完成时间(epoch ms);`0` 表示尚未统计。 */
|
||||
measuredAt: number
|
||||
}
|
||||
|
||||
export interface ConversationMessageCountSnapshot {
|
||||
entries: ConversationMessageCountEntry[]
|
||||
}
|
||||
|
||||
export const EMPTY_CONVERSATION_MESSAGE_COUNT: Omit<ConversationMessageCountEntry, 'conversationId'> =
|
||||
{
|
||||
count: null,
|
||||
approximate: false,
|
||||
measuredAt: 0
|
||||
}
|
||||
+135
-1
@@ -4,7 +4,8 @@
|
||||
* indexer can run in an isolated process.
|
||||
*/
|
||||
|
||||
export const KNOWLEDGE_SCHEMA_VERSION = 1
|
||||
/** 2 = 消息身份改为 `local:<create_time>:<local_id>`;版本不符时 Store 作废重建。 */
|
||||
export const KNOWLEDGE_SCHEMA_VERSION = 2
|
||||
export const DEFAULT_CHUNKER_VERSION = 'conversation-v1'
|
||||
|
||||
export type KnowledgeMessageKind = 'text' | 'voice' | 'file' | 'link' | 'image' | 'video' | 'sticker' | 'system' | 'other'
|
||||
@@ -449,6 +450,12 @@ export interface KnowledgePassProgress {
|
||||
backfillConversations: number
|
||||
/** 这一遍已经补齐的历史会话数。 */
|
||||
backfillCompletedConversations: number
|
||||
/** 因为不在「索引范围」内而整段排除的会话数;它们不计入分母。 */
|
||||
excludedConversations: number
|
||||
/** 当前正在索引的会话名(有展示名时);用于进度文案。 */
|
||||
currentConversationName?: string
|
||||
/** 当前会话已提交的消息条数(每批提交后更新)。 */
|
||||
currentConversationProcessed?: number
|
||||
/** 主线程 event loop 在这一遍期间的最大滞后。用于验证重活没有压在 Main 上。 */
|
||||
mainLoopLagMs: number
|
||||
}
|
||||
@@ -569,6 +576,61 @@ export function isKnowledgeFresh(
|
||||
return status.indexLatestAt + KNOWLEDGE_FRESHNESS_TOLERANCE_MS >= status.sourceLatestAt
|
||||
}
|
||||
|
||||
/** `selected` + 空数组 = 一个都不索引,与 `all` 是两件事。 */
|
||||
export interface KnowledgeIndexScope {
|
||||
mode: 'all' | 'selected'
|
||||
conversationIds: string[]
|
||||
}
|
||||
|
||||
export const DEFAULT_KNOWLEDGE_INDEX_SCOPE: KnowledgeIndexScope = {
|
||||
mode: 'all',
|
||||
conversationIds: []
|
||||
}
|
||||
|
||||
/** 把磁盘/渲染层传来的任意值收敛成合法范围;脏值一律退回 `all`。 */
|
||||
export function normalizeKnowledgeIndexScope(value: unknown): KnowledgeIndexScope {
|
||||
if (!value || typeof value !== 'object') return { ...DEFAULT_KNOWLEDGE_INDEX_SCOPE }
|
||||
const raw = value as { mode?: unknown; conversationIds?: unknown }
|
||||
const mode = raw.mode === 'selected' ? 'selected' : 'all'
|
||||
const ids = Array.isArray(raw.conversationIds)
|
||||
? Array.from(
|
||||
new Set(
|
||||
raw.conversationIds
|
||||
.map((item) => String(item ?? '').trim())
|
||||
.filter((item) => item.length > 0)
|
||||
)
|
||||
).slice(0, 10_000)
|
||||
: []
|
||||
return { mode, conversationIds: mode === 'selected' ? ids : [] }
|
||||
}
|
||||
|
||||
export function normalizeKnowledgeIndexScopes(value: unknown): Record<string, KnowledgeIndexScope> {
|
||||
if (!value || typeof value !== 'object') return {}
|
||||
const result: Record<string, KnowledgeIndexScope> = {}
|
||||
for (const [accountId, scope] of Object.entries(value as Record<string, unknown>)) {
|
||||
const key = String(accountId ?? '').trim()
|
||||
if (!key) continue
|
||||
result[key] = normalizeKnowledgeIndexScope(scope)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** 单个会话的索引状态快照,用于判断"这次查询的会话到底有没有被完整索引"。 */
|
||||
export interface KnowledgeConversationIndexState {
|
||||
/** `ready` / `indexing` / `backfilling` / `partial` / `error` / `cancelled`。 */
|
||||
state: string
|
||||
/** 只有整段读完并提交过的会话才是 true。 */
|
||||
completeSnapshot: boolean
|
||||
/** 源侧已覆盖到的时间(epoch ms);`null` = 没有覆盖证据。 */
|
||||
sourceHighWaterTime: number | null
|
||||
indexedMessageCount: number
|
||||
}
|
||||
|
||||
export interface KnowledgeConversationStatesRequest {
|
||||
accountId: string
|
||||
databaseRoot: string
|
||||
}
|
||||
|
||||
export interface KnowledgeWorkerRequest {
|
||||
version: 1
|
||||
type:
|
||||
@@ -581,6 +643,12 @@ export interface KnowledgeWorkerRequest {
|
||||
| 'close'
|
||||
| 'highWater'
|
||||
| 'memberStats'
|
||||
| 'streamStart'
|
||||
| 'streamBatch'
|
||||
| 'streamFinish'
|
||||
| 'streamAbort'
|
||||
| 'sourceTotals'
|
||||
| 'conversationStates'
|
||||
requestId: string
|
||||
/** Parent monotonic wall-clock used only for transport timing. */
|
||||
sentAt?: number
|
||||
@@ -590,11 +658,72 @@ export interface KnowledgeWorkerRequest {
|
||||
| KnowledgeSearchRequest
|
||||
| KnowledgeStatusRequest
|
||||
| KnowledgeMemberStatsRequest
|
||||
| KnowledgeStreamStartRequest
|
||||
| KnowledgeStreamBatchRequest
|
||||
| KnowledgeStreamConversationRequest
|
||||
| KnowledgeSourceTotalsRequest
|
||||
| KnowledgeConversationStatesRequest
|
||||
| { accountId: string; databaseRoot: string }
|
||||
| { targetRequestId: string }
|
||||
| Record<string, never>
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息不随请求下发:主进程按页推 `streamBatch`,Worker 每批独立事务提交。
|
||||
*/
|
||||
export interface KnowledgeStreamStartRequest {
|
||||
accountId: string
|
||||
databaseRoot: string
|
||||
conversationId: string
|
||||
chunker: KnowledgeChunkerConfig
|
||||
fts: KnowledgeFtsConfig
|
||||
completeSnapshot: boolean
|
||||
sourceHighWaterTime?: number
|
||||
/** 省略 = 读持久化断点;`null` = 从会话开头重建(后台重索引必须用它)。 */
|
||||
resume?: { time: number; messageIds: string[] } | null
|
||||
}
|
||||
|
||||
export interface KnowledgeStreamBatchRequest {
|
||||
accountId: string
|
||||
databaseRoot: string
|
||||
conversationId: string
|
||||
messages: KnowledgeSourceMessage[]
|
||||
}
|
||||
|
||||
/** 整遍读完才可信的全局口径;分批 pass 不得用它冒充全量。 */
|
||||
export interface KnowledgeSourceTotalsRequest {
|
||||
accountId: string
|
||||
databaseRoot: string
|
||||
sourceMessageCount: number
|
||||
sourceLatestAt?: number
|
||||
}
|
||||
|
||||
export interface KnowledgeStreamConversationRequest {
|
||||
accountId: string
|
||||
databaseRoot: string
|
||||
conversationId: string
|
||||
/** 整段读完后才知道的源侧边界(epoch ms),只允许单调推进。 */
|
||||
sourceHighWaterTime?: number
|
||||
/** 只在「本遍读完全部会话」时下发,用于刷新全局总量口径。 */
|
||||
sourceMessageCount?: number
|
||||
sourceLatestAt?: number
|
||||
}
|
||||
|
||||
export interface KnowledgeStreamStartResult {
|
||||
started: boolean
|
||||
/** 复用的续跑位置;`null` 表示从会话开头建立。 */
|
||||
resumedFrom: number | null
|
||||
}
|
||||
|
||||
export interface KnowledgeStreamResult {
|
||||
conversationId: string
|
||||
processedMessages: number
|
||||
chunkCount: number
|
||||
/** 被中止时为 true,`resumeTime` 指向最后一条已提交 chunk 的边界。 */
|
||||
cancelled: boolean
|
||||
resumeTime: number | null
|
||||
}
|
||||
|
||||
export interface KnowledgeWorkerResponse {
|
||||
version: 1
|
||||
type: 'progress' | 'result' | 'error'
|
||||
@@ -606,7 +735,12 @@ export interface KnowledgeWorkerResponse {
|
||||
| KnowledgeSearchResult
|
||||
| KnowledgeRuntimeStatus
|
||||
| KnowledgeMemberStatsResult
|
||||
| KnowledgeStreamStartResult
|
||||
| KnowledgeStreamResult
|
||||
| { removed: true }
|
||||
| { accepted: true }
|
||||
| { marks: Record<string, number> }
|
||||
| { states: Record<string, KnowledgeConversationIndexState> }
|
||||
error?: string
|
||||
transport?: {
|
||||
/** IPC message arrival timestamp in the Worker event loop. */
|
||||
|
||||
@@ -92,6 +92,8 @@ export type QueryCorpusScope =
|
||||
| { kind: 'groups' }
|
||||
| { kind: 'contact'; conversationId: string }
|
||||
| { kind: 'current'; conversationId: string }
|
||||
/** 空数组是非法输入(不是"全部"):UI 必须先让用户选,Host 直接拒绝。 */
|
||||
| { kind: 'selected'; conversationIds: string[] }
|
||||
|
||||
/** 解析后的语料边界(回显给调用方与模型,用于说明"这次只在哪个范围里查")。 */
|
||||
export interface ResolvedCorpusScope {
|
||||
@@ -101,6 +103,8 @@ export interface ResolvedCorpusScope {
|
||||
/** `contact` / `current` 解析出的会话展示名。 */
|
||||
displayName?: string
|
||||
conversationType?: 'user' | 'group'
|
||||
/** `selected` 范围回显的会话展示名(最多前若干个,仅用于文案)。 */
|
||||
displayNames?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user