d3ro-voice/apps/desktop/tests/main/services/caption-lifecycle-refine.test.ts
Yun Chan fc5d45312c fix(desktop): harden cancellation, dispose, and lifecycle races across main services
Cancel pending result-popup measure timers on hideResultPopup; track CaptionService aux-model load state, stop deduplication, and refine abort epochs across restarts; forward per-call AbortSignal through VoiceModeService and LlmGateway to LocalLLMService and abort pull streams plus availability polling on dispose; clear aborted response pointers and gate stale mic start errors in VoiceConversationService; guard AudioCaptureService stopping resume against exited SoX processes and cleanup failed starts; abort LocalSTTService downloadModel polling on dispose; and fail closed when desktopCapturer.getSources rejects in caption loopback setup.
2026-11-14 15:26:18 +09:00

178 lines
6 KiB
TypeScript

// tests/main/services/caption-lifecycle-refine.test.ts
// CaptionService concurrent stop & refine queue cancellation/isolation regression tests.
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
}))
const config = vi.hoisted(() => ({ values: {} as Record<string, unknown> }))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: string) => config.values[key]),
configSet: vi.fn(),
}))
vi.mock('../../../src/main/services/LocalSTTService', () => ({
getLocalSTTService: () => ({
initialize: vi.fn(async () => undefined),
ensureAuxModel: vi.fn(async () => undefined),
releaseAuxModel: vi.fn(async () => undefined),
transcribe: vi.fn(async () => ({ text: '', segments: [] })),
}),
}))
const audio = vi.hoisted(() => ({
stopGate: null as Promise<void> | null,
start: vi.fn(async () => undefined),
stop: vi.fn(async () => {
if (audio.stopGate) await audio.stopGate
}),
}))
vi.mock('../../../src/main/services/AudioCaptureService', () => ({
getAudioCaptureService: () => ({ ...audio, on: vi.fn(), off: vi.fn() }),
calculateRMS: () => 0.1,
}))
vi.mock('../../../src/main/services/SoundEffectService', () => ({
getSoundEffectService: () => ({ play: vi.fn() }),
}))
const llm = vi.hoisted(() => ({
available: true,
generate: vi.fn<
[string, { signal?: AbortSignal; systemPrompt?: string }],
Promise<{ text: string }>
>(async (_prompt, _opts) => ({ text: '' })),
}))
vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => ({
isAvailable: () => llm.available,
generate: llm.generate,
}),
}))
vi.mock('../../../src/main/services/HistoryService', () => ({
getHistoryService: () => ({ create: vi.fn(() => ({ id: 'history-1' })) }),
}))
vi.mock('../../../src/main/services/TranscriptGlossaryService', () => ({
getTranscriptGlossaryService: () => ({
correct: (text: string) => ({ text, corrections: [] }),
promptSection: () => '',
}),
}))
const tracks = vi.hoisted(() => ({
latestDeps: null as { onFinal: (text: string) => void } | null,
flushGate: null as Promise<void> | null,
}))
vi.mock('../../../src/main/services/caption/StreamingCaptionTrack', () => ({
StreamingCaptionTrack: class {
constructor(private readonly deps: { onFinal: (text: string) => void }) {
tracks.latestDeps = deps
}
push(): void {}
async tick(): Promise<void> {}
async flush(): Promise<void> {
if (tracks.flushGate) await tracks.flushGate
}
},
}))
type CaptionModule = typeof import('../../../src/main/services/CaptionService')
let mod: CaptionModule
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
config.values = { captionRefineEnabled: true }
audio.stopGate = null
tracks.latestDeps = null
tracks.flushGate = null
llm.available = true
llm.generate.mockReset()
llm.generate.mockImplementation(async () => ({ text: '' }))
mod = await import('../../../src/main/services/CaptionService')
mod.resetCaptionServiceForTests()
})
describe('CaptionService concurrent stop and refine lifecycle', () => {
it('stop_calledConcurrentlyWhileStopping_waitsForTeardownBeforeResolving', async () => {
let releaseAudio!: () => void
audio.stopGate = new Promise<void>((r) => {
releaseAudio = r
})
const caption = mod.getCaptionService()
await caption.start({ audioSource: 'mic', showOverlay: false, persistHistory: false })
tracks.latestDeps?.onFinal('첫 번째 확정 문장')
const firstStop = caption.stop()
await new Promise((r) => setTimeout(r, 0))
expect(caption.getState()).toBe('stopping')
let secondResolved = false
const secondStop = caption.stop().then((result) => {
secondResolved = true
return result
})
await new Promise((r) => setTimeout(r, 0))
// Second stop must not resolve null prematurely before audio release finishes
expect(secondResolved).toBe(false)
releaseAudio()
const [r1, r2] = await Promise.all([firstStop, secondStop])
expect(caption.getState()).toBe('inactive')
expect(r1 && typeof r1 === 'object' ? r1.segments.map((s) => s.text) : []).toEqual([
'첫 번째 확정 문장',
])
expect(r2).toEqual(r1)
})
it('refine_stoppedWhileLlmInFlight_abortsGenerateAndAllowsNextSessionRefine', async () => {
const signals: Array<AbortSignal | undefined> = []
let rejectFirstOnAbort: (() => void) | null = null
let callCount = 0
llm.generate.mockImplementation(async (_text, opts) => {
callCount += 1
signals.push(opts?.signal)
if (callCount === 1) {
return await new Promise<{ text: string }>((_, reject) => {
rejectFirstOnAbort = () => reject(new Error('aborted'))
})
}
return { text: '오늘 회의는 세 시에 시작합니다.' }
})
const caption = mod.getCaptionService()
const updated: Array<{ id: string; text: string }> = []
caption.on('segment-updated', (u) => updated.push(u))
await caption.start({ audioSource: 'mic', showOverlay: false, persistHistory: false })
tracks.latestDeps?.onFinal('오늘회의는 세시에 시작합니다')
await new Promise((r) => setTimeout(r, 0))
expect(llm.generate).toHaveBeenCalledTimes(1)
expect(signals[0]).toBeInstanceOf(AbortSignal)
expect(signals[0]?.aborted).toBe(false)
await caption.stop()
expect(signals[0]?.aborted).toBe(true)
// Start a brand-new session BEFORE the aborted first LLM promise settles
await caption.start({ audioSource: 'mic', showOverlay: false, persistHistory: false })
tracks.latestDeps?.onFinal('오늘회의는 세시에 시작합니다')
await new Promise((r) => setTimeout(r, 0))
expect(llm.generate).toHaveBeenCalledTimes(2)
expect(updated.length).toBe(1)
// Settling the aborted request later must not emit or break state
rejectFirstOnAbort?.()
await new Promise((r) => setTimeout(r, 0))
await caption.stop()
})
})