d3ro-voice/apps/desktop/tests/main/services/caption-aux-release.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

151 lines
5.3 KiB
TypeScript

// tests/main/services/caption-aux-release.test.ts
// 자막 전용 보조 STT 모델은 시작이 취소되거나 실패해도 내린다 — 안 그러면 다음 세션을 정지할 때까지
// 받아쓰기 모델과 함께 VRAM 을 잡는다.
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(),
}))
const stt = vi.hoisted(() => ({
gate: null as Promise<void> | null,
initialize: vi.fn(async () => undefined),
releaseAuxModel: vi.fn(async () => undefined),
}))
vi.mock('../../../src/main/services/LocalSTTService', () => ({
getLocalSTTService: () => ({
initialize: stt.initialize,
ensureAuxModel: vi.fn(async () => {
if (stt.gate) await stt.gate
}),
releaseAuxModel: stt.releaseAuxModel,
transcribe: vi.fn(async () => ({ text: '' })),
}),
}))
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() }),
}))
vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => ({ isAvailable: () => false, generate: vi.fn() }),
}))
vi.mock('../../../src/main/services/HistoryService', () => ({
getHistoryService: () => ({ create: vi.fn(() => ({ id: 'h' })) }),
}))
vi.mock('../../../src/main/services/caption/StreamingCaptionTrack', () => ({
StreamingCaptionTrack: class {
push(): void {}
async tick(): Promise<void> {}
async flush(): Promise<void> {}
},
}))
type CaptionModule = typeof import('../../../src/main/services/CaptionService')
let mod: CaptionModule
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
config.values = { captionSttModelId: 'caption-small' }
stt.gate = null
stt.initialize.mockImplementation(async () => undefined)
audio.stopGate = null
audio.start.mockImplementation(async () => undefined)
audio.stop.mockImplementation(async () => {
if (audio.stopGate) await audio.stopGate
})
mod = await import('../../../src/main/services/CaptionService')
mod.resetCaptionServiceForTests()
})
describe('CaptionService — 자막 전용 보조 모델 해제', () => {
it('보조 모델 로딩 중에 정지하면, 뒤늦게 올라온 모델을 내린다', async () => {
let finishLoad: () => void = () => undefined
stt.gate = new Promise<void>((r) => {
finishLoad = r
})
const caption = mod.getCaptionService()
const starting = caption.start({ audioSource: 'mic', showOverlay: false })
await new Promise((r) => setTimeout(r, 0))
await caption.stop()
stt.releaseAuxModel.mockClear()
finishLoad()
await expect(starting).rejects.toBeTruthy()
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
expect(caption.getState()).toBe('inactive')
})
it('오디오 시작이 실패해도 올려 둔 보조 모델을 내린다', async () => {
audio.start.mockImplementation(async () => {
throw new Error('no microphone')
})
const caption = mod.getCaptionService()
await expect(caption.start({ audioSource: 'mic', showOverlay: false })).rejects.toBeTruthy()
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
expect(caption.getState()).toBe('inactive')
})
it('releaseAuxModel_auxFinishesLoadingWhileStopping_stillReleasesAuxModel', async () => {
let finishLoad: () => void = () => undefined
stt.gate = new Promise<void>((r) => {
finishLoad = r
})
const caption = mod.getCaptionService()
const starting = caption.start({ audioSource: 'mic', showOverlay: false })
await new Promise((r) => setTimeout(r, 0))
// stop() immediately transitions state to 'stopping' before yielding to awaits
const stopping = caption.stop()
expect(caption.getState()).toBe('stopping')
// Aux model finishes loading on the same tick while stop() is still in 'stopping'
stt.releaseAuxModel.mockClear()
finishLoad()
await expect(starting).rejects.toBeTruthy()
await stopping
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
expect(caption.getState()).toBe('inactive')
})
it('start_failsBeforeAuxLoadWhenPreviousSessionHadAux_doesNotReleaseSpuriously', async () => {
audio.start.mockRejectedValueOnce(new Error('no mic'))
const caption = mod.getCaptionService()
await expect(caption.start({ audioSource: 'mic', showOverlay: false })).rejects.toBeTruthy()
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
stt.releaseAuxModel.mockClear()
config.values = {}
stt.initialize.mockRejectedValueOnce(new Error('sidecar down'))
await expect(caption.start({ audioSource: 'mic', showOverlay: false })).rejects.toBeTruthy()
expect(stt.releaseAuxModel).not.toHaveBeenCalled()
})
})