mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 本地 API 支持按需转写语音消息
读取消息时返回本地已有的语音转写及其状态 新增 query/voice-transcribe 接口按 messageRef 转写指定语音
This commit is contained in:
1 parent
e5f0aa59f4
commit
4d9af4a193
11 files changed
+843
-14
No files matched your search
@@ -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