mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop
This commit is contained in:
commit
028e8b6553
11 files changed
+843
-14
No files matched your search
@@ -337,3 +337,50 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/convers
|
||||
调用方**必须**把 `coverage` 当真:`coverage.state` 不是 `complete` 且 `evidence` 为空时,只能说明"这段范围暂时无法确认",**不能**下"没有找到"的结论。索引落后时服务端会自动请求一次追赶同步,但不会让请求无限等待;`freshness.catchUp` 为 `pending` 表示追赶仍在后台进行,稍后重试即可拿到更新的覆盖。
|
||||
|
||||
`query/messages` 与 `query/conversation-overview` 直读聊天数据库,不受索引新鲜度影响。
|
||||
|
||||
### 语音转文字(voice-transcribe)
|
||||
|
||||
语音消息的正文固定是 `[语音消息]`。本机已转写过的语音,读取时会直接带上转写结果(只读缓存,不触发识别):
|
||||
|
||||
- `query/messages`、`query/message-context`:`voiceTranscriptState` 与 `voiceTranscript`,`derivedSource` 为 `voice_transcript`;
|
||||
- `/chatlog`:语音消息额外带 `messageRef`、`voiceTranscriptState` 与 `voiceTranscript`。
|
||||
|
||||
`voiceTranscriptState` 为 `pending` 表示**还没转写**,不能当成"语音里没说话"。需要内容时,把这些语音的 `messageRef` 交给 `POST /api/v1/query/voice-transcribe`:
|
||||
|
||||
```bash
|
||||
curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/voice-transcribe" \
|
||||
-d '{"messageRefs":["<语音消息的 messageRef>"],"waitMs":15000}'
|
||||
```
|
||||
|
||||
| 字段 | 含义 |
|
||||
| ------------- | --------------------------------------------------------------------------------------- |
|
||||
| `messageRefs` | 必填,1~20 条;重复的引用会合并 |
|
||||
| `waitMs` | 可选,最多同步等待的毫秒数,默认 15000,上限 60000;`0` 表示只排队、不等待 |
|
||||
| `force` | 可选,`true` 时忽略已有转写和失败记录、重新识别;只在用户明确要求重试时使用 |
|
||||
|
||||
识别在本机离线进行(需要先在 TraceMemo 设置里下载语音识别模型),和界面共用同一份缓存与同一条串行队列:界面上点开语音会优先处理,API 的任务随后继续。等待超时的条目返回 `pending`,识别会在后台继续;稍后用同样的 `messageRefs` 再调用即可取回结果,不会重复排队。
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "completed",
|
||||
"items": [
|
||||
{ "messageRef": "…", "state": "transcribed", "transcript": "…", "cached": false },
|
||||
{ "messageRef": "…", "state": "pending", "code": "still_processing", "hint": "…" }
|
||||
],
|
||||
"summary": { "transcribed": 1, "pending": 1, "failed": 0 }
|
||||
}
|
||||
```
|
||||
|
||||
每个未成功的条目都带 `code` 与 `hint`(下一步该怎么做):
|
||||
|
||||
| `code` | 含义 |
|
||||
| ----------------------- | ------------------------------------------ |
|
||||
| `still_processing` | 仍在后台转写,稍后原样重试 |
|
||||
| `previously_failed` | 之前识别失败,默认不自动重跑 |
|
||||
| `recognition_failed` | 本次识别失败(音频损坏、过短或没有人声) |
|
||||
| `recognition_timeout` | 识别超时 |
|
||||
| `not_voice_message` | 不是语音消息 |
|
||||
| `message_not_found` | 找不到消息(可能已切换账号) |
|
||||
| `invalid_message_ref` | `messageRef` 无法解析 |
|
||||
|
||||
整次请求的状态:`200 completed`;`400 invalid_tool_arguments`(带 `field`、`constraint`、`hint`);`503 voice_model_not_ready`(模型未下载)或 `knowledge_unavailable`(数据库未连接);`429 busy`(队列已满,带 `retryAfterSeconds` 与 `Retry-After` 头)。
|
||||
@@ -42,6 +42,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
| POST | `/query/search` | 受限语义关键词检索(依赖本地索引,见 freshness) |
|
||||
| POST | `/query/message-context` | 用 `messageRef` 取某条消息的前后文 |
|
||||
| POST | `/query/conversation-overview` | 按会话与时间范围提取可总结的证据 |
|
||||
| POST | `/query/voice-transcribe` | 把指定语音消息转成文字(本机离线识别) |
|
||||
| GET | `/query/capabilities` | Query 端点能力目录 |
|
||||
| GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) |
|
||||
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
|
||||
@@ -118,6 +119,7 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
- `query/search`:受限语义关键词检索,依赖本地索引;
|
||||
- `query/message-context`:用返回的 `messageRef` 取前后文;
|
||||
- `query/conversation-overview`:按会话与时间范围提取可总结的证据。
|
||||
- `query/voice-transcribe`:把指定语音消息的 `messageRef` 转成文字。
|
||||
|
||||
两个要点:
|
||||
|
||||
@@ -147,6 +149,18 @@ description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的
|
||||
|
||||
不要只根据 `[图片]` 猜测内容,不要把一次 OCR 当作完整图片理解,也不要直接读取任意本地图片路径。
|
||||
|
||||
### 语音消息
|
||||
|
||||
语音消息的正文固定是 `[语音消息]`,转写结果在 `voiceTranscript`,状态在 `voiceTranscriptState`(`/chatlog` 与 `query/*` 都会返回)。
|
||||
|
||||
1. `transcribed`:直接使用 `voiceTranscript`。
|
||||
2. `pending`:还没转写,**不能**说成“语音里没内容”。回答需要它时,把这些语音的 `messageRef` 批量(每次最多 20 条)交给 `POST /query/voice-transcribe`。
|
||||
3. 返回 `pending`(`still_processing`)时,稍后用同样的 `messageRefs` 再调用一次;不要换参数反复重试。
|
||||
4. 返回 `failed` 时按 `hint` 处理;`previously_failed` 只有用户明确要求才传 `force: true` 重试。
|
||||
5. `503 voice_model_not_ready`:告诉用户先在 TraceMemo 设置中下载语音识别模型,在此之前不要重试。
|
||||
6. `429 busy`:等待 `retryAfterSeconds` 后再调用。
|
||||
7. 只转写回答问题所需的语音,不要一次把整个会话的语音都提交。
|
||||
|
||||
## 隐私和安全
|
||||
|
||||
只读取用户请求所需的会话和时间范围。不要把完整聊天数据库、密钥或 Token 暴露给用户。Reader API 本身不自动把聊天转发到外部服务器,但当前 Agent 可能会把工具结果交给其配置的模型;如有疑问,提醒用户检查 Agent 的数据策略。
|
||||
|
||||
+50
-3
@@ -8,7 +8,8 @@ import {
|
||||
listMessages,
|
||||
getGroupSnapshot,
|
||||
listRecentChat,
|
||||
resolveMd5
|
||||
resolveMd5,
|
||||
type FormattedMessage
|
||||
} from './services/chat-service'
|
||||
import { exportGroupReport } from './group-report-service'
|
||||
import { GroupReportExportRequest } from '../shared/group-report'
|
||||
@@ -34,6 +35,13 @@ import { automationExecutionLogService } from './services/automation-execution-l
|
||||
import { groupExitMonitorService } from './services/group-exit-monitor-service'
|
||||
import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent-api-service'
|
||||
import type { GroupStatsService } from './services/group-stats-service'
|
||||
import { encodeMessageRef } from '../shared/local-query-api'
|
||||
import type {
|
||||
VoiceMessageReference,
|
||||
VoiceTranscriptSnapshot,
|
||||
VoiceTranscriptState
|
||||
} from '../shared/voice-recognition'
|
||||
import { voiceMessageReferenceOf } from './voice-pipeline/voice-message-identity'
|
||||
|
||||
export const DEFAULT_HTTP_HOST = '127.0.0.1'
|
||||
export const DEFAULT_HTTP_PORT = 6131
|
||||
@@ -82,6 +90,35 @@ export function setLocalGroupStatsService(
|
||||
configuredGroupStatsService = service
|
||||
}
|
||||
|
||||
let configuredVoiceTranscriptSnapshot:
|
||||
| ((reference: VoiceMessageReference) => VoiceTranscriptSnapshot)
|
||||
| undefined
|
||||
export function setLocalVoiceTranscriptSnapshotProvider(
|
||||
provider: ((reference: VoiceMessageReference) => VoiceTranscriptSnapshot) | undefined
|
||||
): void {
|
||||
configuredVoiceTranscriptSnapshot = provider
|
||||
}
|
||||
|
||||
/**
|
||||
* chatlog 的语音消息补上本地已有的转写(只读缓存,不触发识别)与 messageRef,
|
||||
* 调用方据 `voiceTranscriptState` 决定是否调用 query/voice-transcribe。
|
||||
*/
|
||||
function withChatlogVoiceTranscript(
|
||||
conversationId: string,
|
||||
message: FormattedMessage
|
||||
): FormattedMessage & { messageRef?: string; voiceTranscriptState?: VoiceTranscriptState } {
|
||||
const reference = voiceMessageReferenceOf(message)
|
||||
if (!reference || !configuredVoiceTranscriptSnapshot) return message
|
||||
const snapshot = configuredVoiceTranscriptSnapshot(reference)
|
||||
const transcript = snapshot.state === 'transcribed' ? snapshot.transcript?.trim() : undefined
|
||||
return {
|
||||
...message,
|
||||
messageRef: encodeMessageRef(conversationId, message.id),
|
||||
voiceTranscriptState: snapshot.state,
|
||||
...(transcript ? { voiceTranscript: transcript } : {})
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_JSON_BODY_BYTES = 1024 * 1024
|
||||
|
||||
class RequestBodyTooLargeError extends Error {
|
||||
@@ -389,7 +426,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
query: { talker, time: timeParam, startTime, endTime },
|
||||
count: messages.length,
|
||||
messages: messages.map((message) =>
|
||||
sanitizeChatlogMessage(message as unknown as Record<string, unknown>)
|
||||
sanitizeChatlogMessage(
|
||||
withChatlogVoiceTranscript(resolved.md5, message) as unknown as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
})
|
||||
}),
|
||||
@@ -654,6 +693,8 @@ function queryStatusCode(status: string): number {
|
||||
if (status === 'contact_not_found') return 404
|
||||
if (status === 'ambiguous_contact') return 409
|
||||
if (status === 'knowledge_unavailable') return 503
|
||||
if (status === 'voice_model_not_ready' || status === 'voice_transcription_unavailable') return 503
|
||||
if (status === 'busy') return 429
|
||||
if (status === 'retrieval_incomplete') return 206
|
||||
return 400
|
||||
}
|
||||
@@ -669,6 +710,7 @@ function createQueryRoute(pathname: string, api: LocalQueryApiService): RouteHan
|
||||
| Awaited<ReturnType<LocalQueryApiService['search']>>
|
||||
| Awaited<ReturnType<LocalQueryApiService['context']>>
|
||||
| Awaited<ReturnType<LocalQueryApiService['overview']>>
|
||||
| Awaited<ReturnType<LocalQueryApiService['transcribeVoice']>>
|
||||
const operations: Record<string, (payload: unknown) => Promise<QueryOperationResult>> = {
|
||||
'/api/v1/query/messages': (payload) =>
|
||||
api.messages(payload as Parameters<LocalQueryApiService['messages']>[0]),
|
||||
@@ -677,7 +719,9 @@ function createQueryRoute(pathname: string, api: LocalQueryApiService): RouteHan
|
||||
'/api/v1/query/message-context': (payload) =>
|
||||
api.context(payload as Parameters<LocalQueryApiService['context']>[0]),
|
||||
'/api/v1/query/conversation-overview': (payload) =>
|
||||
api.overview(payload as Parameters<LocalQueryApiService['overview']>[0])
|
||||
api.overview(payload as Parameters<LocalQueryApiService['overview']>[0]),
|
||||
'/api/v1/query/voice-transcribe': (payload) =>
|
||||
api.transcribeVoice(payload as Parameters<LocalQueryApiService['transcribeVoice']>[0])
|
||||
}
|
||||
const operation = operations[pathname]
|
||||
if (!operation) return undefined
|
||||
@@ -687,6 +731,9 @@ function createQueryRoute(pathname: string, api: LocalQueryApiService): RouteHan
|
||||
if (!payload || typeof payload !== 'object') return sendError(res, 400, 'invalid_request')
|
||||
try {
|
||||
const result = await operation(payload)
|
||||
if ('retryAfterSeconds' in result && typeof result.retryAfterSeconds === 'number') {
|
||||
res.setHeader('Retry-After', String(result.retryAfterSeconds))
|
||||
}
|
||||
return sendJson(res, queryStatusCode(result.status), result)
|
||||
} catch (error) {
|
||||
return sendError(res, 400, error instanceof Error ? error.message : 'invalid_request')
|
||||
|
||||
+16
-1
@@ -77,7 +77,12 @@ import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../
|
||||
import { KeyServiceMac } from './key-service-mac'
|
||||
import { KeyService as KeyServiceWin } from './key-service-win'
|
||||
import * as chat from './services/chat-service'
|
||||
import { apiServer, setLocalGroupStatsService, setLocalQueryApiService } from './http-server'
|
||||
import {
|
||||
apiServer,
|
||||
setLocalGroupStatsService,
|
||||
setLocalQueryApiService,
|
||||
setLocalVoiceTranscriptSnapshotProvider
|
||||
} from './http-server'
|
||||
import { skillResourceService } from './services/skill-resource-service'
|
||||
import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service'
|
||||
import { isWechatRunning } from './services/wechat-process-status'
|
||||
@@ -373,6 +378,7 @@ import type { ExportRequest } from '../shared/export'
|
||||
import { discoverAccounts } from './services/account-discovery'
|
||||
import { VoiceRecognitionUseCase } from './voice-pipeline/voice-recognition-use-case'
|
||||
import { VoiceBatchService } from './voice-pipeline/voice-batch-service'
|
||||
import { VoiceTranscriptionGateway } from './voice-pipeline/voice-transcription-gateway'
|
||||
import type { VoiceBatchRequest, VoiceMessageReference } from '../shared/voice-recognition'
|
||||
import type { AiSearchPipelineRequest } from '../shared/ai-search'
|
||||
import type {
|
||||
@@ -1031,6 +1037,15 @@ app.whenReady().then(async () => {
|
||||
localQueryApiService.setImageOcrEntryProvider((conversationId, messageId) =>
|
||||
imageTextIndexService.getConversationOcr(conversationId).get(messageId)
|
||||
)
|
||||
/**
|
||||
* 语音转写:读消息时只读缓存快照;只有 query/voice-transcribe 会真正排队识别,
|
||||
* 识别仍走同一个 VoiceRecognitionUseCase(同一份缓存、同一条串行队列)。
|
||||
*/
|
||||
const voiceTranscriptionGateway = new VoiceTranscriptionGateway(voiceRecognition)
|
||||
localQueryApiService.setVoiceTranscriptionGateway(voiceTranscriptionGateway)
|
||||
setLocalVoiceTranscriptSnapshotProvider((reference) =>
|
||||
voiceTranscriptionGateway.snapshot(reference)
|
||||
)
|
||||
setLocalQueryApiService(localQueryApiService)
|
||||
// Query Agent:生产 Runtime 只在这里实例化一次,桌面问问微信与 Agent Hub 共用同一个实例。
|
||||
queryAgentService = new QueryAgentService(
|
||||
|
||||
@@ -19,15 +19,27 @@ import type {
|
||||
QueryMessagesRequest,
|
||||
SearchMessagesRequest,
|
||||
MessageContextRequest,
|
||||
ConversationOverviewRequest
|
||||
ConversationOverviewRequest,
|
||||
VoiceTranscribeItem,
|
||||
VoiceTranscribeRequest,
|
||||
VoiceTranscribeResponse
|
||||
} from '../../shared/local-query-api'
|
||||
// messageRef 编解码是 main 与 renderer 共用的契约,只定义一次(`src/shared/local-query-api.ts`):
|
||||
// 两侧各写一份 base64url 实现会悄悄漂移,那会让「跳转到原聊天」偶发失效。
|
||||
import {
|
||||
encodeMessageRef as toRef,
|
||||
decodeMessageRef as fromRef,
|
||||
normalizeMessageIdentity
|
||||
normalizeMessageIdentity,
|
||||
VOICE_TRANSCRIBE_DEFAULT_WAIT_MS,
|
||||
VOICE_TRANSCRIBE_MAX_REFS,
|
||||
VOICE_TRANSCRIBE_MAX_WAIT_MS
|
||||
} from '../../shared/local-query-api'
|
||||
import type { VoiceMessageReference, VoiceTranscriptSnapshot } from '../../shared/voice-recognition'
|
||||
import { voiceMessageReferenceOf } from '../voice-pipeline/voice-message-identity'
|
||||
import type {
|
||||
VoiceTranscriptionGateway,
|
||||
VoiceTranscriptionOutcome
|
||||
} from '../voice-pipeline/voice-transcription-gateway'
|
||||
import {
|
||||
IMAGE_TEXT_BACKFILL_TIER_LABEL,
|
||||
describeImageTextCoverage,
|
||||
@@ -223,7 +235,8 @@ function toQueryMessage(
|
||||
conversationId: string,
|
||||
message: FormattedMessage,
|
||||
target: FormattedContact,
|
||||
imageOcr?: { state: string; text: string }
|
||||
imageOcr?: { state: string; text: string },
|
||||
voice?: VoiceTranscriptSnapshot
|
||||
): QueryMessage {
|
||||
const kind = kindOf(message)
|
||||
const content = message.contentData
|
||||
@@ -247,7 +260,12 @@ function toQueryMessage(
|
||||
: derived.state === 'empty'
|
||||
? 'empty'
|
||||
: 'not_indexed'
|
||||
return { messageRef: toRef(conversationId, message.id), timestamp: (message.createTime || 0) * 1000, datetime: message.datetime, sender: message.isSender ? '我' : (message.name || target.m_nsNickName), direction: message.isSender ? 'to_target' : 'from_target', messageType: kind, sourceKind: kind, ...(attachment ? { attachment } : {}), ...(text ? { text } : {}), ...(ocrText ? { imageOcrText: ocrText, derivedSource: 'image_ocr' as const } : {}), ...(kind === 'image' ? { imageTextState } : {}) }
|
||||
// 语音转写与图片 OCR 同为派生文本:走独立字段,不改写 `text`(语音正文是 `[语音消息]`)。
|
||||
const voiceText = kind === 'voice' && voice?.state === 'transcribed' ? voice.transcript?.trim() || '' : ''
|
||||
const voiceFields = kind === 'voice' && voice
|
||||
? { voiceTranscriptState: voice.state, ...(voiceText ? { voiceTranscript: voiceText, derivedSource: 'voice_transcript' as const } : {}) }
|
||||
: {}
|
||||
return { messageRef: toRef(conversationId, message.id), timestamp: (message.createTime || 0) * 1000, datetime: message.datetime, sender: message.isSender ? '我' : (message.name || target.m_nsNickName), direction: message.isSender ? 'to_target' : 'from_target', messageType: kind, sourceKind: kind, ...(attachment ? { attachment } : {}), ...(text ? { text } : {}), ...(ocrText ? { imageOcrText: ocrText, derivedSource: 'image_ocr' as const } : {}), ...(kind === 'image' ? { imageTextState } : {}), ...voiceFields }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -299,6 +317,45 @@ function outsideScopeError(scope: ResolvedCorpusScope, actual: string): { status
|
||||
}
|
||||
}
|
||||
|
||||
type VoiceTranscriptionPort = Pick<VoiceTranscriptionGateway, 'snapshot' | 'transcribe' | 'modelReady' | 'inFlightCount'>
|
||||
|
||||
const VOICE_MODEL_NOT_READY_HINT =
|
||||
'本机还没有可用的离线语音识别模型。请让用户在 TraceMemo 设置里下载语音识别模型后再试;在此之前不要重试。'
|
||||
|
||||
/**
|
||||
* 语音转写条目的原因码 → 给调用方(通常是 AI)的下一步建议。
|
||||
* 关键是把"还没转完 / 转不了 / 不该转"三类分开,避免模型把它们说成"语音里没内容"。
|
||||
*/
|
||||
const VOICE_ITEM_HINTS: Record<string, string> = {
|
||||
invalid_message_ref: 'messageRef 无法解析。请原样使用 query/messages、query/message-context 或 chatlog 返回的 messageRef,不要自行构造。',
|
||||
message_not_found: '找不到这条消息(可能已切换账号或消息已不存在)。请重新读取消息,用新的 messageRef 调用。',
|
||||
not_voice_message: '这不是语音消息,不需要转写。只对 messageType=voice(chatlog 中 type=语音)的消息调用。',
|
||||
still_processing: '已在本机后台排队转写。稍后用同样的 messageRef 再调用一次即可取回结果,不会重复排队;在此之前不能认定这条语音没有内容。',
|
||||
previously_failed: '这条语音之前识别失败,默认不会自动重跑。除非用户明确要求,不要反复重试;确需重试时传 force=true。',
|
||||
recognition_timeout: '本机识别超时。可以稍后传 force=true 重试一次;仍失败就如实告诉用户这条语音无法转写。',
|
||||
recognition_failed: '本机识别失败(音频可能损坏、过短或没有人声)。不要立即重复调用,如实告诉用户这条语音无法转写即可。',
|
||||
voice_model_not_ready: VOICE_MODEL_NOT_READY_HINT,
|
||||
not_connected: 'TraceMemo 当前没有连接微信数据库。请让用户在 TraceMemo 中重新连接后再试。',
|
||||
cancelled: '识别被取消(可能切换了账号或移除了模型)。确认环境正常后可再调用一次。'
|
||||
}
|
||||
|
||||
function voiceFailureCode(outcome: Extract<VoiceTranscriptionOutcome, { state: 'failed' }>): string {
|
||||
if (outcome.code === 'PREVIOUSLY_FAILED') return 'previously_failed'
|
||||
if (outcome.code === 'TIMEOUT') return 'recognition_timeout'
|
||||
if (outcome.code === 'MODEL_NOT_READY') return 'voice_model_not_ready'
|
||||
if (outcome.code === 'NOT_CONNECTED') return 'not_connected'
|
||||
if (outcome.code === 'CANCELLED') return 'cancelled'
|
||||
return 'recognition_failed'
|
||||
}
|
||||
|
||||
function voiceItemProblem(messageRef: string, state: 'pending' | 'failed', code: string, error?: string): VoiceTranscribeItem {
|
||||
return { messageRef, state, code, ...(error ? { error } : {}), hint: VOICE_ITEM_HINTS[code] }
|
||||
}
|
||||
|
||||
function invalidVoiceTranscribeArguments(field: string, constraint: string, hint: string): VoiceTranscribeResponse & Record<string, unknown> {
|
||||
return { status: 'invalid_tool_arguments', field, constraint, hint }
|
||||
}
|
||||
|
||||
export class LocalQueryApiService {
|
||||
/**
|
||||
* 图片文字索引覆盖度提供者(同步、只读)。
|
||||
@@ -343,8 +400,24 @@ export class LocalQueryApiService {
|
||||
): void {
|
||||
this.imageOcrEntry = provider
|
||||
}
|
||||
|
||||
/**
|
||||
* 语音转写入口。读消息时只读它的缓存快照(不触发识别);
|
||||
* 只有 `transcribeVoice` 会真正排队识别。
|
||||
*/
|
||||
private voiceTranscription: VoiceTranscriptionPort | undefined
|
||||
|
||||
setVoiceTranscriptionGateway(gateway: VoiceTranscriptionPort | undefined): void {
|
||||
this.voiceTranscription = gateway
|
||||
}
|
||||
|
||||
private voiceSnapshot(message: FormattedMessage): VoiceTranscriptSnapshot | undefined {
|
||||
const reference = voiceMessageReferenceOf(message)
|
||||
return reference ? this.voiceTranscription?.snapshot(reference) : undefined
|
||||
}
|
||||
|
||||
capabilities(): QueryCapabilitiesResponse {
|
||||
return { version: 1, tools: { query_messages: { operation: '读取指定联系人的确定性消息', directions: ['any', 'from_target', 'to_target'], messageTypes: kinds, timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, search_messages: { operation: '受限 Knowledge 关键词检索', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, message_context: { operation: '读取消息前后文', timeRanges: ['all'], limitMax: CONTEXT_MAX }, conversation_overview: { operation: '按会话时间片提取概览证据', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX } } }
|
||||
return { version: 1, tools: { query_messages: { operation: '读取指定联系人的确定性消息', directions: ['any', 'from_target', 'to_target'], messageTypes: kinds, timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, search_messages: { operation: '受限 Knowledge 关键词检索', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, message_context: { operation: '读取消息前后文', timeRanges: ['all'], limitMax: CONTEXT_MAX }, conversation_overview: { operation: '按会话时间片提取概览证据', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, voice_transcribe: { operation: '把指定语音消息转成文字(本机离线识别,结果缓存)', timeRanges: [], limitMax: VOICE_TRANSCRIBE_MAX_REFS } } }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -416,7 +489,7 @@ export class LocalQueryApiService {
|
||||
kindOf(message) === 'image'
|
||||
? this.imageOcrEntry?.(contact.md5, sourceMessageId(message))
|
||||
: undefined
|
||||
return toQueryMessage(contact.md5, message, contact, ocr)
|
||||
return toQueryMessage(contact.md5, message, contact, ocr, this.voiceSnapshot(message))
|
||||
})
|
||||
const imageOcrCoverage = buildImageOcrCoverage(this.imageTextCoverage())
|
||||
return { status: 'completed' as const, target: contactView(contact), query: { direction, messageTypes: request.messageTypes || [], order: request.order || 'asc', limit: Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)), excludeSystem: request.excludeSystem !== false, resolvedTimeRange: range }, coverage: { state: 'complete' as const }, returnedCount: filtered.length, messages, scope: corpus.scope, ...(imageOcrCoverage ? { imageOcrCoverage } : {}) }
|
||||
@@ -685,9 +758,92 @@ export class LocalQueryApiService {
|
||||
}
|
||||
}
|
||||
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)
|
||||
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) }
|
||||
}
|
||||
/**
|
||||
* 把指定语音消息转成文字。
|
||||
*
|
||||
* 这是 Query API 里**唯一会触发计算**的操作:识别在本机离线进行、结果写入语音缓存,
|
||||
* 之后 query/messages 等读路径就能直接读到。并发、去重与排队上限见 VoiceTranscriptionGateway。
|
||||
*/
|
||||
async transcribeVoice(request: VoiceTranscribeRequest): Promise<VoiceTranscribeResponse> {
|
||||
const refs = request?.messageRefs
|
||||
if (!Array.isArray(refs) || refs.length === 0 || refs.some((ref) => typeof ref !== 'string' || !ref)) {
|
||||
return invalidVoiceTranscribeArguments('messageRefs', 'non_empty_string_array', 'messageRefs 必须是非空字符串数组,元素取自 query/messages 或 chatlog 返回的语音消息 messageRef。')
|
||||
}
|
||||
if (refs.length > VOICE_TRANSCRIBE_MAX_REFS) {
|
||||
return invalidVoiceTranscribeArguments('messageRefs', `max_items_${VOICE_TRANSCRIBE_MAX_REFS}`, `一次最多转写 ${VOICE_TRANSCRIBE_MAX_REFS} 条语音,请分批调用。`)
|
||||
}
|
||||
if (request.force !== undefined && typeof request.force !== 'boolean') {
|
||||
return invalidVoiceTranscribeArguments('force', 'boolean', 'force 只能是 true 或 false。')
|
||||
}
|
||||
const waitMs = request.waitMs ?? VOICE_TRANSCRIBE_DEFAULT_WAIT_MS
|
||||
if (typeof waitMs !== 'number' || !Number.isFinite(waitMs) || waitMs < 0 || waitMs > VOICE_TRANSCRIBE_MAX_WAIT_MS) {
|
||||
return invalidVoiceTranscribeArguments('waitMs', `0_to_${VOICE_TRANSCRIBE_MAX_WAIT_MS}`, `waitMs 必须是 0 到 ${VOICE_TRANSCRIBE_MAX_WAIT_MS} 之间的毫秒数;0 表示只排队、不等待。`)
|
||||
}
|
||||
const gateway = this.voiceTranscription
|
||||
if (!gateway) return { status: 'voice_transcription_unavailable', hint: '当前 TraceMemo 没有启用语音转写服务,无法转写语音。' }
|
||||
if (!isReady()) return { status: 'knowledge_unavailable', hint: VOICE_ITEM_HINTS.not_connected }
|
||||
if (!(await gateway.modelReady())) return { status: 'voice_model_not_ready', hint: VOICE_MODEL_NOT_READY_HINT }
|
||||
|
||||
const uniqueRefs = Array.from(new Set(refs))
|
||||
const problems = new Map<string, VoiceTranscribeItem>()
|
||||
const references = new Map<string, VoiceMessageReference>()
|
||||
const refsByConversation = new Map<string, Array<{ messageRef: string; messageId: string }>>()
|
||||
for (const messageRef of uniqueRefs) {
|
||||
const identity = fromRef(messageRef)
|
||||
if (!identity) {
|
||||
problems.set(messageRef, voiceItemProblem(messageRef, 'failed', 'invalid_message_ref'))
|
||||
continue
|
||||
}
|
||||
const group = refsByConversation.get(identity.conversationId) || []
|
||||
group.push({ messageRef, messageId: identity.messageId })
|
||||
refsByConversation.set(identity.conversationId, group)
|
||||
}
|
||||
// 同一会话只读一次源消息;与 message-context 同样按会话读取后匹配消息身份。
|
||||
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 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'))
|
||||
}
|
||||
}
|
||||
|
||||
const pendingRefs = Array.from(references.keys())
|
||||
const outcomes = pendingRefs.length
|
||||
? await gateway.transcribe(pendingRefs.map((ref) => references.get(ref)!), { force: request.force, waitMs })
|
||||
: []
|
||||
if (!outcomes) {
|
||||
// 粗估:按每条语音约 1 秒的本机识别耗时。
|
||||
const retryAfterSeconds = Math.max(5, gateway.inFlightCount)
|
||||
return { status: 'busy', retryAfterSeconds, hint: `本机语音转写队列已满。请等待约 ${retryAfterSeconds} 秒后用同样的参数重试,或减少本次的 messageRefs 数量。` }
|
||||
}
|
||||
const resolved = new Map<string, VoiceTranscribeItem>()
|
||||
pendingRefs.forEach((messageRef, index) => {
|
||||
const outcome = outcomes[index]
|
||||
if (outcome.state === 'transcribed') {
|
||||
resolved.set(messageRef, { messageRef, state: 'transcribed', transcript: outcome.transcript, cached: outcome.cached, ...(outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}) })
|
||||
} else if (outcome.state === 'pending') {
|
||||
resolved.set(messageRef, voiceItemProblem(messageRef, 'pending', 'still_processing'))
|
||||
} else {
|
||||
resolved.set(messageRef, voiceItemProblem(messageRef, 'failed', voiceFailureCode(outcome), outcome.error))
|
||||
}
|
||||
})
|
||||
const items = uniqueRefs.map((ref) => resolved.get(ref) || problems.get(ref)!)
|
||||
const summary = { transcribed: 0, pending: 0, failed: 0 }
|
||||
for (const item of items) summary[item.state] += 1
|
||||
return {
|
||||
status: 'completed',
|
||||
items,
|
||||
summary,
|
||||
...(summary.pending ? { hint: VOICE_ITEM_HINTS.still_processing } : {})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话概览。
|
||||
*
|
||||
|
||||
@@ -23,3 +23,30 @@ export function voiceAccountIdentity(accountRoot: string): string {
|
||||
)
|
||||
.digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* 从一条已格式化的消息里取出语音定位信息;不是语音或标识不完整时返回 undefined。
|
||||
* 本地 API 用它判断"这条消息能否转写",与批量转写的口径一致。
|
||||
*/
|
||||
export function voiceMessageReferenceOf(message: {
|
||||
type?: string
|
||||
sessionId?: string
|
||||
localId?: number
|
||||
createTime?: number
|
||||
serverId?: string
|
||||
}): VoiceMessageReference | undefined {
|
||||
if (
|
||||
message.type !== '语音' ||
|
||||
!message.sessionId ||
|
||||
message.localId === undefined ||
|
||||
!message.createTime
|
||||
) {
|
||||
return undefined
|
||||
}
|
||||
return {
|
||||
sessionId: message.sessionId,
|
||||
localId: message.localId,
|
||||
createTime: message.createTime,
|
||||
svrId: message.serverId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import type {
|
||||
VoiceMessageReference,
|
||||
VoiceRecognitionErrorCode,
|
||||
VoiceRecognitionResult,
|
||||
VoiceTranscriptSnapshot
|
||||
} from '../../shared/voice-recognition'
|
||||
import { voiceMessageIdentity } from './voice-message-identity'
|
||||
import type { VoiceRecognitionUseCase } from './voice-recognition-use-case'
|
||||
|
||||
/** API 发起、尚未完成的转写任务上限(跨请求共享)。 */
|
||||
export const VOICE_TRANSCRIBE_MAX_IN_FLIGHT = 100
|
||||
/** 被界面上的交互请求抢占后,最多重新排队几次。 */
|
||||
const MAX_PREEMPTION_RETRIES = 5
|
||||
|
||||
type Recognition = Pick<
|
||||
VoiceRecognitionUseCase,
|
||||
'recognize' | 'getTranscriptSnapshot' | 'getModelStatus' | 'accountIdentity'
|
||||
>
|
||||
|
||||
export type VoiceTranscriptionOutcome =
|
||||
| { state: 'transcribed'; transcript: string; cached: boolean; durationMs?: number }
|
||||
| { state: 'pending' }
|
||||
| { state: 'failed'; code: VoiceRecognitionErrorCode | 'PREVIOUSLY_FAILED'; error: string }
|
||||
|
||||
/**
|
||||
* 本地 API 触发语音转写的入口。
|
||||
*
|
||||
* 识别本身(缓存、单 worker 串行调度、失败记录、Knowledge 增量)仍完全由
|
||||
* VoiceRecognitionUseCase 负责;这里只补 API 调用方需要的三件事:
|
||||
* - 同一条语音被反复轮询时复用同一个进行中的任务,不重复排队;
|
||||
* - 限制 API 积压的任务总量,避免一次塞入上千条把界面上的识别饿死;
|
||||
* - 调用方只等待有限时间,没做完的继续在后台跑,结果进缓存供下次读取。
|
||||
*/
|
||||
export class VoiceTranscriptionGateway {
|
||||
private readonly inFlight = new Map<string, Promise<VoiceRecognitionResult>>()
|
||||
|
||||
constructor(
|
||||
private readonly recognition: Recognition,
|
||||
private readonly maxInFlight = VOICE_TRANSCRIBE_MAX_IN_FLIGHT
|
||||
) {}
|
||||
|
||||
/** 只读缓存,不触发识别。 */
|
||||
snapshot(reference: VoiceMessageReference): VoiceTranscriptSnapshot {
|
||||
return this.recognition.getTranscriptSnapshot(reference)
|
||||
}
|
||||
|
||||
async modelReady(): Promise<boolean> {
|
||||
return (await this.recognition.getModelStatus()).state === 'ready'
|
||||
}
|
||||
|
||||
get inFlightCount(): number {
|
||||
return this.inFlight.size
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回与 references 一一对应的结果;剩余容量装不下本次新增任务时返回 null,
|
||||
* 且不排入任何任务(整批拒绝,调用方稍后原样重试即可)。
|
||||
*/
|
||||
async transcribe(
|
||||
references: VoiceMessageReference[],
|
||||
options: { force?: boolean; waitMs: number }
|
||||
): Promise<VoiceTranscriptionOutcome[] | null> {
|
||||
const accountIdentity = this.recognition.accountIdentity
|
||||
const keyOf = (reference: VoiceMessageReference): string =>
|
||||
`${accountIdentity}:${voiceMessageIdentity(reference)}`
|
||||
|
||||
const immediate = references.map((reference): VoiceTranscriptionOutcome | undefined => {
|
||||
if (options.force || this.inFlight.has(keyOf(reference))) return undefined
|
||||
const snapshot = this.recognition.getTranscriptSnapshot(reference)
|
||||
if (snapshot.state === 'transcribed' && snapshot.transcript?.trim()) {
|
||||
return { state: 'transcribed', transcript: snapshot.transcript.trim(), cached: true }
|
||||
}
|
||||
// 失败过的语音不自动重跑:调用方轮询时会反复命中同一条坏音频。
|
||||
if (snapshot.state === 'failed') {
|
||||
return {
|
||||
state: 'failed',
|
||||
code: 'PREVIOUSLY_FAILED',
|
||||
error: snapshot.error || '语音识别失败'
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
|
||||
const newKeys = new Set<string>()
|
||||
references.forEach((reference, index) => {
|
||||
const key = keyOf(reference)
|
||||
if (!immediate[index] && !this.inFlight.has(key)) newKeys.add(key)
|
||||
})
|
||||
if (this.inFlight.size + newKeys.size > this.maxInFlight) return null
|
||||
|
||||
const tasks = references.map((reference, index) => {
|
||||
if (immediate[index]) return undefined
|
||||
const key = keyOf(reference)
|
||||
let task = this.inFlight.get(key)
|
||||
if (!task) {
|
||||
task = this.run(reference, options.force, accountIdentity).finally(() => {
|
||||
this.inFlight.delete(key)
|
||||
})
|
||||
this.inFlight.set(key, task)
|
||||
}
|
||||
return task
|
||||
})
|
||||
|
||||
let timer: NodeJS.Timeout | undefined
|
||||
const deadline = new Promise<'pending'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('pending'), Math.max(0, options.waitMs))
|
||||
})
|
||||
try {
|
||||
return await Promise.all(
|
||||
references.map(async (_reference, index): Promise<VoiceTranscriptionOutcome> => {
|
||||
const done = immediate[index]
|
||||
if (done) return done
|
||||
const result = await Promise.race([tasks[index]!, deadline])
|
||||
if (result === 'pending') return { state: 'pending' }
|
||||
if (result.success) {
|
||||
return {
|
||||
state: 'transcribed',
|
||||
transcript: result.transcript?.trim() || '',
|
||||
cached: Boolean(result.cached),
|
||||
...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {})
|
||||
}
|
||||
}
|
||||
return {
|
||||
state: 'failed',
|
||||
code: result.code || 'RECOGNITION_FAILED',
|
||||
error: result.error || '语音识别失败'
|
||||
}
|
||||
})
|
||||
)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
private async run(
|
||||
reference: VoiceMessageReference,
|
||||
force: boolean | undefined,
|
||||
accountIdentity: string
|
||||
): Promise<VoiceRecognitionResult> {
|
||||
for (let attempt = 0; ; attempt += 1) {
|
||||
// 用后台优先级:用户在界面上点开语音时可以立即抢占,不必排在 API 积压之后。
|
||||
const result = await this.recognition.recognize(reference, { priority: 'background', force })
|
||||
if (
|
||||
result.success ||
|
||||
result.code !== 'CANCELLED' ||
|
||||
attempt >= MAX_PREEMPTION_RETRIES ||
|
||||
this.recognition.accountIdentity !== accountIdentity
|
||||
) {
|
||||
return result
|
||||
}
|
||||
// 被交互请求抢占:账号没变就重新排队,与批量转写的处理一致。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KnowledgeDerivedSource, KnowledgeEvidence, KnowledgeVoiceCoverage } from './knowledge'
|
||||
import type { VoiceTranscriptState } from './voice-recognition'
|
||||
|
||||
export type QueryDirection = 'any' | 'from_target' | 'to_target'
|
||||
export type QueryOrder = 'asc' | 'desc'
|
||||
@@ -254,6 +255,21 @@ export interface QueryMessage {
|
||||
* `empty` 也不允许被当成"可以凭画面猜内容"(OCR 不是 Vision)。
|
||||
*/
|
||||
imageTextState?: 'indexed' | 'empty' | 'not_indexed'
|
||||
/**
|
||||
* 语音转写派生文本(**仅**语音消息、且本地已转写时存在)。
|
||||
*
|
||||
* 与 `imageOcrText` 同理不并入 `text`:语音消息的正文仍是 `[语音消息]`,
|
||||
* 这段文字来自本地离线识别,`derivedSource` 为 `voice_transcript`。
|
||||
*/
|
||||
voiceTranscript?: string
|
||||
/**
|
||||
* 这条语音消息的本地转写状态(仅语音消息)。
|
||||
*
|
||||
* - `transcribed`:已转写(此时 `voiceTranscript` 有值)
|
||||
* - `pending`:尚未转写 —— 不能当成"语音里没说话",可调用 `query/voice-transcribe`
|
||||
* - `failed`:之前识别失败
|
||||
*/
|
||||
voiceTranscriptState?: VoiceTranscriptState
|
||||
}
|
||||
export interface QueryMessagesResponse {
|
||||
status: string
|
||||
@@ -419,6 +435,38 @@ export interface MessageContextResponse {
|
||||
before?: QueryMessage[]
|
||||
after?: QueryMessage[]
|
||||
}
|
||||
/** 单次 `query/voice-transcribe` 最多处理多少条语音。 */
|
||||
export const VOICE_TRANSCRIBE_MAX_REFS = 20
|
||||
/** 同步等待的默认值与上限(毫秒);超时的条目返回 `pending`,识别继续在后台进行。 */
|
||||
export const VOICE_TRANSCRIBE_DEFAULT_WAIT_MS = 15_000
|
||||
export const VOICE_TRANSCRIBE_MAX_WAIT_MS = 60_000
|
||||
export interface VoiceTranscribeRequest {
|
||||
/** 来自 `query/messages` / `query/message-context` / `chatlog` 的语音消息 `messageRef`。 */
|
||||
messageRefs: string[]
|
||||
/** 忽略已有转写与失败记录,重新识别。 */
|
||||
force?: boolean
|
||||
/** 最多同步等待多久;0 = 只排队不等待。 */
|
||||
waitMs?: number
|
||||
}
|
||||
export interface VoiceTranscribeItem {
|
||||
messageRef: string
|
||||
state: VoiceTranscriptState
|
||||
transcript?: string
|
||||
cached?: boolean
|
||||
durationMs?: number
|
||||
/** 机器可读的原因,仅 `pending` / `failed` 时存在。 */
|
||||
code?: string
|
||||
error?: string
|
||||
/** 给调用方(通常是 AI)的下一步建议。 */
|
||||
hint?: string
|
||||
}
|
||||
export interface VoiceTranscribeResponse {
|
||||
status: string
|
||||
items?: VoiceTranscribeItem[]
|
||||
summary?: { transcribed: number; pending: number; failed: number }
|
||||
retryAfterSeconds?: number
|
||||
hint?: string
|
||||
}
|
||||
export interface ConversationOverviewRequest { target: QueryTarget; timeRange: QueryTimeRange; scope?: QueryCorpusScope }
|
||||
export interface ConversationOverviewResponse {
|
||||
status: string
|
||||
|
||||
@@ -68,7 +68,14 @@ vi.mock('../../src/main/services/agent-hub-service', () => ({
|
||||
}))
|
||||
|
||||
import { apiTokenStore } from '../../src/main/api-token-store'
|
||||
import { apiServer, startHttpServer, type HttpServerHandle } from '../../src/main/http-server'
|
||||
import {
|
||||
apiServer,
|
||||
setLocalVoiceTranscriptSnapshotProvider,
|
||||
startHttpServer,
|
||||
type HttpServerHandle
|
||||
} from '../../src/main/http-server'
|
||||
import type { LocalQueryApiService } from '../../src/main/services/local-query-api-service'
|
||||
import { decodeMessageRef } from '../../src/shared/local-query-api'
|
||||
import { HttpMediaError } from '../../src/main/http-media-service'
|
||||
import {
|
||||
buildLocalApiCurlCommand,
|
||||
@@ -209,7 +216,8 @@ describe('Local API authentication', () => {
|
||||
['POST', '/api/v1/agent/group-report'],
|
||||
['POST', '/api/v1/agent/send'],
|
||||
['GET', '/api/v1/query/capabilities'],
|
||||
['POST', '/api/v1/query/messages']
|
||||
['POST', '/api/v1/query/messages'],
|
||||
['POST', '/api/v1/query/voice-transcribe']
|
||||
])('protects every non-health route: %s %s', async (method, pathname) => {
|
||||
const handle = await startFixtureServer()
|
||||
const response = await fetch(`${baseUrl(handle)}${pathname}`, {
|
||||
@@ -274,6 +282,65 @@ describe('Local API authentication', () => {
|
||||
expect(body.messages[0].contentData).not.toHaveProperty('aeskey')
|
||||
})
|
||||
|
||||
it('adds cached voice transcripts and a messageRef to chatlog voice messages', async () => {
|
||||
const voice = {
|
||||
id: '41',
|
||||
type: '语音',
|
||||
content: '[语音消息]',
|
||||
sessionId: 'wxid_fixture',
|
||||
localId: 41,
|
||||
createTime: 1_785_895_200
|
||||
}
|
||||
fixture.chatlogMessages.push(voice as never)
|
||||
const snapshot = vi.fn(() => ({ state: 'transcribed' as const, transcript: '合成的转写文本' }))
|
||||
setLocalVoiceTranscriptSnapshotProvider(snapshot)
|
||||
try {
|
||||
const handle = await startFixtureServer()
|
||||
const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=fixture`, {
|
||||
headers: { Authorization: `Bearer ${VALID_TOKEN}` }
|
||||
})
|
||||
const body = await response.json()
|
||||
expect(body.messages[0]).not.toHaveProperty('voiceTranscriptState')
|
||||
expect(body.messages[1]).toMatchObject({
|
||||
id: '41',
|
||||
voiceTranscript: '合成的转写文本',
|
||||
voiceTranscriptState: 'transcribed'
|
||||
})
|
||||
expect(decodeMessageRef(body.messages[1].messageRef)).toEqual({
|
||||
conversationId: 'fixture-md5',
|
||||
messageId: '41'
|
||||
})
|
||||
expect(snapshot).toHaveBeenCalledWith({
|
||||
sessionId: 'wxid_fixture',
|
||||
localId: 41,
|
||||
createTime: 1_785_895_200,
|
||||
svrId: undefined
|
||||
})
|
||||
} finally {
|
||||
setLocalVoiceTranscriptSnapshotProvider(undefined)
|
||||
fixture.chatlogMessages.pop()
|
||||
}
|
||||
})
|
||||
|
||||
it('maps a full voice transcription queue to 429 with Retry-After', async () => {
|
||||
const queryApiService = {
|
||||
transcribeVoice: vi.fn(async () => ({ status: 'busy', retryAfterSeconds: 12, hint: '队列已满' }))
|
||||
} as unknown as LocalQueryApiService
|
||||
const handle = await startHttpServer('127.0.0.1', 0, {
|
||||
tokenProvider: () => VALID_TOKEN,
|
||||
queryApiService
|
||||
})
|
||||
handles.push(handle)
|
||||
const response = await fetch(`${baseUrl(handle)}/api/v1/query/voice-transcribe`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${VALID_TOKEN}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ messageRefs: ['ref'] })
|
||||
})
|
||||
expect(response.status).toBe(429)
|
||||
expect(response.headers.get('retry-after')).toBe('12')
|
||||
await expect(response.json()).resolves.toMatchObject({ status: 'busy', retryAfterSeconds: 12 })
|
||||
})
|
||||
|
||||
it('serves opaque media handles while preserving the chatlog message id', async () => {
|
||||
const mediaId = `image:${'a'.repeat(64)}`
|
||||
const previousUrl = fixture.chatlogMessages[0].media.url
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { describe, expect, it, vi, beforeEach, type Mock } from 'vitest'
|
||||
|
||||
// Keep local-time label assertions deterministic; production follows the host timezone.
|
||||
process.env.TZ = 'Asia/Shanghai'
|
||||
@@ -20,6 +20,10 @@ vi.mock('../../src/main/services/chat-service', () => ({
|
||||
}))
|
||||
|
||||
import { LocalQueryApiService } from '../../src/main/services/local-query-api-service'
|
||||
import { listMessagesAsync } from '../../src/main/services/chat-service'
|
||||
import { encodeMessageRef } from '../../src/shared/local-query-api'
|
||||
import type { VoiceMessageReference, VoiceTranscriptSnapshot } from '../../src/shared/voice-recognition'
|
||||
import type { VoiceTranscriptionOutcome } from '../../src/main/voice-pipeline/voice-transcription-gateway'
|
||||
|
||||
describe('LocalQueryApiService', () => {
|
||||
const knowledge = {
|
||||
@@ -424,3 +428,111 @@ describe('LocalQueryApiService — indexCoverage 结论句', () => {
|
||||
expect(result.indexCoverage?.summary).not.toMatch(/\d{12,}/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LocalQueryApiService voice transcription', () => {
|
||||
const voiceMessage = {
|
||||
id: 'v1',
|
||||
from: 'user',
|
||||
type: '语音',
|
||||
datetime: '2026/8/4 10:00:00',
|
||||
content: '[语音消息]',
|
||||
isSender: false,
|
||||
name: 'BOBO',
|
||||
sessionId: 'wxid_fixture_member',
|
||||
localId: 31,
|
||||
createTime: Math.floor(new Date('2026-08-04T10:00:00+08:00').getTime() / 1000)
|
||||
}
|
||||
const textMessage = { id: 't1', from: 'user', type: '文本', datetime: '2026/8/4 10:01:00', content: '你好', isSender: false, name: 'BOBO', createTime: voiceMessage.createTime + 60 }
|
||||
const voiceRef = encodeMessageRef('md5-bobo', 'v1')
|
||||
const textRef = encodeMessageRef('md5-bobo', 't1')
|
||||
|
||||
type GatewayStub = {
|
||||
inFlightCount: number
|
||||
snapshot: Mock<(reference: VoiceMessageReference) => VoiceTranscriptSnapshot>
|
||||
modelReady: Mock<() => Promise<boolean>>
|
||||
transcribe: Mock<(references: VoiceMessageReference[], options: { force?: boolean; waitMs: number }) => Promise<VoiceTranscriptionOutcome[] | null>>
|
||||
}
|
||||
function makeGateway(): GatewayStub {
|
||||
return {
|
||||
inFlightCount: 0,
|
||||
snapshot: vi.fn(() => ({ state: 'transcribed' as const, transcript: '明天下午三点开会' })),
|
||||
modelReady: vi.fn(async () => true),
|
||||
transcribe: vi.fn(async (references: VoiceMessageReference[]) =>
|
||||
references.map(() => ({ state: 'transcribed' as const, transcript: '明天下午三点开会', cached: false }))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let service: LocalQueryApiService
|
||||
let gateway: GatewayStub
|
||||
beforeEach(() => {
|
||||
vi.mocked(listMessagesAsync).mockResolvedValue([voiceMessage, textMessage] as never)
|
||||
gateway = makeGateway()
|
||||
service = new LocalQueryApiService(undefined, () => new Date('2026-09-09T12:00:00+08:00'))
|
||||
service.setVoiceTranscriptionGateway(gateway)
|
||||
})
|
||||
|
||||
it('reads cached transcripts on query/messages and message-context without triggering recognition', async () => {
|
||||
const result = await service.messages({ scope: { kind: 'current', conversationId: 'md5-bobo' }, timeRange: { kind: 'all' }, messageTypes: ['voice'] })
|
||||
expect(result).toMatchObject({
|
||||
messages: [{ messageType: 'voice', text: '[语音消息]', voiceTranscript: '明天下午三点开会', voiceTranscriptState: 'transcribed', derivedSource: 'voice_transcript' }]
|
||||
})
|
||||
|
||||
gateway.snapshot.mockReturnValueOnce({ state: 'pending' })
|
||||
const context = await service.context({ messageRef: voiceRef, before: 0, after: 1 })
|
||||
expect(context).toMatchObject({ anchor: { voiceTranscriptState: 'pending' }, after: [{ messageType: 'text' }] })
|
||||
expect(context).not.toHaveProperty('anchor.voiceTranscript')
|
||||
expect(context).not.toHaveProperty('after.0.voiceTranscriptState')
|
||||
expect(gateway.transcribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('transcribes voice refs and explains refs that cannot be transcribed', async () => {
|
||||
const result = await service.transcribeVoice({ messageRefs: [voiceRef, voiceRef, textRef, 'not-a-ref'], waitMs: 0 })
|
||||
|
||||
expect(gateway.transcribe).toHaveBeenCalledTimes(1)
|
||||
expect(gateway.transcribe).toHaveBeenCalledWith(
|
||||
[{ sessionId: 'wxid_fixture_member', localId: 31, createTime: voiceMessage.createTime, svrId: undefined }],
|
||||
{ force: undefined, waitMs: 0 }
|
||||
)
|
||||
expect(result.status).toBe('completed')
|
||||
expect(result.summary).toEqual({ transcribed: 1, pending: 0, failed: 2 })
|
||||
expect(result.items).toEqual([
|
||||
{ messageRef: voiceRef, state: 'transcribed', transcript: '明天下午三点开会', cached: false },
|
||||
expect.objectContaining({ messageRef: textRef, state: 'failed', code: 'not_voice_message', hint: expect.stringContaining('不是语音') }),
|
||||
expect.objectContaining({ messageRef: 'not-a-ref', state: 'failed', code: 'invalid_message_ref', hint: expect.stringContaining('不要自行构造') })
|
||||
])
|
||||
})
|
||||
|
||||
it('reports still-processing and failed recognitions with next-step hints', async () => {
|
||||
const other = { ...voiceMessage, id: 'v2', localId: 32 }
|
||||
vi.mocked(listMessagesAsync).mockResolvedValue([voiceMessage, other] as never)
|
||||
gateway.transcribe.mockResolvedValueOnce([
|
||||
{ state: 'pending' },
|
||||
{ state: 'failed', code: 'PREVIOUSLY_FAILED', error: 'decode failed' }
|
||||
])
|
||||
|
||||
const result = await service.transcribeVoice({ messageRefs: [voiceRef, encodeMessageRef('md5-bobo', 'v2')] })
|
||||
|
||||
expect(result.summary).toEqual({ transcribed: 0, pending: 1, failed: 1 })
|
||||
expect(result.items?.[0]).toMatchObject({ state: 'pending', code: 'still_processing', hint: expect.stringContaining('同样的 messageRef') })
|
||||
expect(result.items?.[1]).toMatchObject({ state: 'failed', code: 'previously_failed', error: 'decode failed', hint: expect.stringContaining('force=true') })
|
||||
expect(result.hint).toContain('同样的 messageRef')
|
||||
})
|
||||
|
||||
it('rejects invalid arguments with a correctable hint', async () => {
|
||||
await expect(service.transcribeVoice({ messageRefs: [] })).resolves.toMatchObject({ status: 'invalid_tool_arguments', field: 'messageRefs' })
|
||||
await expect(service.transcribeVoice({ messageRefs: Array.from({ length: 21 }, (_, index) => `ref-${index}`) })).resolves.toMatchObject({ status: 'invalid_tool_arguments', hint: expect.stringContaining('分批') })
|
||||
await expect(service.transcribeVoice({ messageRefs: [voiceRef], waitMs: 600_000 })).resolves.toMatchObject({ status: 'invalid_tool_arguments', field: 'waitMs' })
|
||||
expect(gateway.transcribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops before reading messages when the model is not ready or the queue is full', async () => {
|
||||
gateway.modelReady.mockResolvedValueOnce(false)
|
||||
await expect(service.transcribeVoice({ messageRefs: [voiceRef] })).resolves.toMatchObject({ status: 'voice_model_not_ready', hint: expect.stringContaining('下载语音识别模型') })
|
||||
expect(gateway.transcribe).not.toHaveBeenCalled()
|
||||
|
||||
gateway.inFlightCount = 30
|
||||
gateway.transcribe.mockResolvedValueOnce(null)
|
||||
await expect(service.transcribeVoice({ messageRefs: [voiceRef] })).resolves.toMatchObject({ status: 'busy', retryAfterSeconds: 30 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, it, vi, type Mock } from 'vitest'
|
||||
import type {
|
||||
VoiceMessageReference,
|
||||
VoiceModelStatus,
|
||||
VoiceRecognitionResult,
|
||||
VoiceTranscriptSnapshot
|
||||
} from '../../src/shared/voice-recognition'
|
||||
import { VoiceTranscriptionGateway } from '../../src/main/voice-pipeline/voice-transcription-gateway'
|
||||
|
||||
const reference = (localId: number): VoiceMessageReference => ({
|
||||
sessionId: 'wxid_fixture_member',
|
||||
localId,
|
||||
createTime: 1_785_895_200 + localId
|
||||
})
|
||||
|
||||
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
type RecognitionStub = {
|
||||
accountIdentity: string
|
||||
getModelStatus: Mock<() => Promise<Pick<VoiceModelStatus, 'state'>>>
|
||||
getTranscriptSnapshot: Mock<(reference: VoiceMessageReference) => VoiceTranscriptSnapshot>
|
||||
recognize: Mock<(...args: unknown[]) => Promise<VoiceRecognitionResult>>
|
||||
}
|
||||
|
||||
function makeRecognition(): RecognitionStub {
|
||||
return {
|
||||
accountIdentity: 'account-a',
|
||||
getModelStatus: vi.fn(async () => ({ state: 'ready' as const })),
|
||||
getTranscriptSnapshot: vi.fn(() => ({ state: 'pending' as const })),
|
||||
recognize: vi.fn(async () => ({
|
||||
success: true,
|
||||
transcript: ' 转写结果 ',
|
||||
cached: false,
|
||||
durationMs: 1200
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
describe('VoiceTranscriptionGateway', () => {
|
||||
it('returns cached transcripts without scheduling recognition', async () => {
|
||||
const recognition = makeRecognition()
|
||||
recognition.getTranscriptSnapshot.mockReturnValue({
|
||||
state: 'transcribed',
|
||||
transcript: '已转写'
|
||||
})
|
||||
const gateway = new VoiceTranscriptionGateway(recognition as never)
|
||||
|
||||
const result = await gateway.transcribe([reference(1)], { waitMs: 1000 })
|
||||
|
||||
expect(result).toEqual([{ state: 'transcribed', transcript: '已转写', cached: true }])
|
||||
expect(recognition.recognize).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not rerun previously failed voice unless force is set', async () => {
|
||||
const recognition = makeRecognition()
|
||||
recognition.getTranscriptSnapshot.mockReturnValue({ state: 'failed', error: 'decode failed' })
|
||||
const gateway = new VoiceTranscriptionGateway(recognition as never)
|
||||
|
||||
await expect(gateway.transcribe([reference(1)], { waitMs: 1000 })).resolves.toEqual([
|
||||
{ state: 'failed', code: 'PREVIOUSLY_FAILED', error: 'decode failed' }
|
||||
])
|
||||
expect(recognition.recognize).not.toHaveBeenCalled()
|
||||
|
||||
await expect(
|
||||
gateway.transcribe([reference(1)], { force: true, waitMs: 1000 })
|
||||
).resolves.toEqual([
|
||||
{ state: 'transcribed', transcript: '转写结果', cached: false, durationMs: 1200 }
|
||||
])
|
||||
expect(recognition.recognize).toHaveBeenCalledWith(reference(1), {
|
||||
priority: 'background',
|
||||
force: true
|
||||
})
|
||||
})
|
||||
|
||||
it('returns pending at the deadline and lets the next call join the same task', async () => {
|
||||
const recognition = makeRecognition()
|
||||
const running = deferred<VoiceRecognitionResult>()
|
||||
recognition.recognize.mockReturnValue(running.promise)
|
||||
const gateway = new VoiceTranscriptionGateway(recognition as never)
|
||||
|
||||
await expect(gateway.transcribe([reference(1)], { waitMs: 0 })).resolves.toEqual([
|
||||
{ state: 'pending' }
|
||||
])
|
||||
expect(gateway.inFlightCount).toBe(1)
|
||||
|
||||
const second = gateway.transcribe([reference(1)], { waitMs: 1000 })
|
||||
running.resolve({ success: true, transcript: '晚到的结果', cached: false })
|
||||
|
||||
await expect(second).resolves.toEqual([
|
||||
{ state: 'transcribed', transcript: '晚到的结果', cached: false }
|
||||
])
|
||||
expect(recognition.recognize).toHaveBeenCalledTimes(1)
|
||||
expect(gateway.inFlightCount).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects the whole request when the queue cannot take the new work', async () => {
|
||||
const recognition = makeRecognition()
|
||||
recognition.recognize.mockReturnValue(new Promise(() => undefined))
|
||||
const gateway = new VoiceTranscriptionGateway(recognition as never, 2)
|
||||
|
||||
await gateway.transcribe([reference(1)], { waitMs: 0 })
|
||||
await expect(
|
||||
gateway.transcribe([reference(2), reference(3)], { waitMs: 0 })
|
||||
).resolves.toBeNull()
|
||||
|
||||
expect(recognition.recognize).toHaveBeenCalledTimes(1)
|
||||
expect(gateway.inFlightCount).toBe(1)
|
||||
})
|
||||
|
||||
it('requeues an item preempted by an interactive request', async () => {
|
||||
const recognition = makeRecognition()
|
||||
recognition.recognize
|
||||
.mockResolvedValueOnce({ success: false, code: 'CANCELLED', error: '语音识别已取消' })
|
||||
.mockResolvedValueOnce({ success: true, transcript: '重排后完成', cached: false })
|
||||
const gateway = new VoiceTranscriptionGateway(recognition as never)
|
||||
|
||||
await expect(gateway.transcribe([reference(1)], { waitMs: 1000 })).resolves.toEqual([
|
||||
{ state: 'transcribed', transcript: '重排后完成', cached: false }
|
||||
])
|
||||
expect(recognition.recognize).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('stops requeueing after the account changes', async () => {
|
||||
const recognition = makeRecognition()
|
||||
recognition.recognize.mockImplementation(async () => {
|
||||
recognition.accountIdentity = 'account-b'
|
||||
return { success: false, code: 'CANCELLED', error: '语音识别已取消' }
|
||||
})
|
||||
const gateway = new VoiceTranscriptionGateway(recognition as never)
|
||||
|
||||
await expect(gateway.transcribe([reference(1)], { waitMs: 1000 })).resolves.toEqual([
|
||||
{ state: 'failed', code: 'CANCELLED', error: '语音识别已取消' }
|
||||
])
|
||||
expect(recognition.recognize).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user