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.
This commit is contained in:
parent
4bf0f0df12
commit
fc5d45312c
19 changed files with 922 additions and 94 deletions
|
|
@ -6,6 +6,7 @@
|
|||
// - realtime-token 은 주입된 자격 증명 포트로 호출한다 (item 2)
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { desktopCapturer, session } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
|
||||
const handlers = vi.hoisted(() => new Map<string, (event: unknown, params?: unknown) => Promise<unknown>>())
|
||||
|
|
@ -136,3 +137,25 @@ describe('realtime-token 은 자격 증명 포트를 쓴다', () => {
|
|||
expect(invokeFn).toHaveBeenCalledWith('realtime-token', {})
|
||||
})
|
||||
})
|
||||
|
||||
describe('systemAudio:enableLoopback 예외 처리', () => {
|
||||
it('enableLoopback_getSourcesRejects_invokesCallbackWithEmptyObject', async () => {
|
||||
const mod = await import('../../../src/main/ipc/caption-handlers')
|
||||
mod.registerCaptionHandlers()
|
||||
|
||||
const regResult = await invoke(IPC_CHANNELS.SYSTEM_AUDIO.ENABLE_LOOPBACK)
|
||||
expect(regResult.success).toBe(true)
|
||||
|
||||
const setHandlerCalls = vi.mocked(session.defaultSession.setDisplayMediaRequestHandler).mock.calls
|
||||
const mediaHandler = setHandlerCalls[0]?.[0] as
|
||||
| ((request: unknown, callback: (streams: Record<string, unknown>) => void) => Promise<void>)
|
||||
| undefined
|
||||
expect(typeof mediaHandler).toBe('function')
|
||||
|
||||
vi.mocked(desktopCapturer.getSources).mockRejectedValueOnce(new Error('screen capture failed'))
|
||||
const callback = vi.fn()
|
||||
|
||||
await expect(mediaHandler!({}, callback)).resolves.toBeUndefined()
|
||||
expect(callback).toHaveBeenCalledWith({})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -190,4 +190,64 @@ describe('VoiceConversationService local response ownership', () => {
|
|||
expect(mocks.speakSentences).not.toHaveBeenCalled()
|
||||
expect(service.getHistory().map((message) => message.content)).toEqual(['cancel before response'])
|
||||
})
|
||||
|
||||
it('cancelResponse_followedImmediatelyBySendTextMessage_startsNewTurnWithoutConflict', async () => {
|
||||
let releaseFirstStream: (() => void) | undefined
|
||||
mocks.chatStream
|
||||
.mockImplementationOnce(() => (async function* (): AsyncGenerator<string, string> {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseFirstStream = resolve
|
||||
})
|
||||
return ''
|
||||
})())
|
||||
.mockImplementationOnce(() => (async function* (): AsyncGenerator<string, string> {
|
||||
yield 'second reply.'
|
||||
return 'second reply.'
|
||||
})())
|
||||
|
||||
const service = getVoiceConversationService()
|
||||
await service.startSession()
|
||||
|
||||
const firstResponse = service.sendTextMessage('first question')
|
||||
await vi.waitFor(() => expect(mocks.chatStream).toHaveBeenCalledTimes(1))
|
||||
|
||||
service.cancelResponse()
|
||||
const secondResponse = service.sendTextMessage('second question')
|
||||
releaseFirstStream?.()
|
||||
|
||||
await expect(secondResponse).resolves.toBeUndefined()
|
||||
await firstResponse
|
||||
expect(mocks.chatStream).toHaveBeenCalledTimes(2)
|
||||
expect(service.getHistory().map((m) => m.content)).toEqual([
|
||||
'first question',
|
||||
'second question',
|
||||
'second reply.',
|
||||
])
|
||||
})
|
||||
|
||||
it('startSession_audioStartRejectsAfterStop_doesNotEmitSttErrorOrClobberNewSessionMic', async () => {
|
||||
let rejectFirstMic!: (err: Error) => void
|
||||
mocks.audioStart
|
||||
.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
|
||||
rejectFirstMic = reject
|
||||
}))
|
||||
.mockImplementationOnce(async () => undefined)
|
||||
|
||||
const service = getVoiceConversationService()
|
||||
const errorEvents: Array<{ phase: string; message: string }> = []
|
||||
service.on('error', (payload) => errorEvents.push(payload))
|
||||
|
||||
await service.startSession()
|
||||
service.stopSession()
|
||||
|
||||
await service.startSession()
|
||||
rejectFirstMic(new Error('stale mic failure'))
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
|
||||
expect(errorEvents).toEqual([])
|
||||
expect(mocks.send.mock.calls.filter(([channel]) => channel === IPC_CHANNELS.VOICE_CONVERSATION.ERROR)).toEqual([])
|
||||
|
||||
service.stopSession()
|
||||
expect(mocks.audioStop).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -261,6 +261,36 @@ describe('VoiceModeService', () => {
|
|||
|
||||
expect(cancelReason).toBe('user')
|
||||
})
|
||||
|
||||
it('cancelSession_whileLlmProcessingInFlight_abortsPerCallSignalPassedToLlm', async () => {
|
||||
let capturedSignal: AbortSignal | undefined
|
||||
let rejectLlm: ((reason?: unknown) => void) | undefined
|
||||
mockLLM.processText.mockImplementation(((_text, _action, _lang, _prompt, options?: { signal?: AbortSignal }) => {
|
||||
capturedSignal = options?.signal
|
||||
return new Promise<string>((_resolve, reject) => {
|
||||
rejectLlm = reject
|
||||
options?.signal?.addEventListener('abort', () => reject(new Error('llm aborted')), { once: true })
|
||||
})
|
||||
}) as never)
|
||||
|
||||
const svc = getVoiceModeService()
|
||||
await svc.startSession('dictation')
|
||||
audioBus.emit('audio-data', { buffer: Buffer.alloc(16000 * 2) })
|
||||
await new Promise((r) => setTimeout(r, 850))
|
||||
const stopping = svc.stopSession()
|
||||
|
||||
await vi.waitFor(() => expect(mockLLM.processText).toHaveBeenCalledTimes(1))
|
||||
|
||||
expect(capturedSignal).toBeInstanceOf(AbortSignal)
|
||||
expect(capturedSignal?.aborted).toBe(false)
|
||||
|
||||
svc.cancelSession()
|
||||
rejectLlm?.(new Error('cleanup'))
|
||||
await stopping
|
||||
|
||||
expect(capturedSignal?.aborted).toBe(true)
|
||||
expect(mockTextInsert.insertText).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('LLM 후처리 인자 전달', () => {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { EventEmitter } from 'events'
|
||||
import { spawn } from 'child_process'
|
||||
import { ipcMain } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
|
||||
|
|
@ -228,3 +229,37 @@ describe('마이크 테스트 IPC', () => {
|
|||
expect(proc(0).kill).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('정지/시작 레이스 및 실패 정리', () => {
|
||||
it('start_calledWhileStoppingAfterSoxClosed_spawnsFreshSoxProcess', async () => {
|
||||
const audio = mod.getAudioCaptureService()
|
||||
await audio.start()
|
||||
|
||||
const stopping = audio.stop()
|
||||
proc(0).emit('close', 1)
|
||||
|
||||
await audio.start()
|
||||
await stopping
|
||||
|
||||
expect(spawned.list).toHaveLength(2)
|
||||
expect(audio.state).toBe('capturing')
|
||||
|
||||
await audio.stop()
|
||||
expect(proc(1).kill).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('start_spawnedProcessMissingStdout_cleansUpChildProcess', async () => {
|
||||
const brokenChild = Object.assign(new EventEmitter(), {
|
||||
stdout: null,
|
||||
stderr: new EventEmitter(),
|
||||
kill: vi.fn(),
|
||||
})
|
||||
vi.mocked(spawn).mockReturnValueOnce(brokenChild as never)
|
||||
|
||||
const audio = mod.getAudioCaptureService()
|
||||
await expect(audio.start()).rejects.toMatchObject({ message: expect.stringMatching(/stdout/i) })
|
||||
|
||||
expect(audio.state).toBe('error')
|
||||
expect(brokenChild.kill).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -16,11 +16,12 @@ vi.mock('../../../src/main/services/ConfigService', () => ({
|
|||
|
||||
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: vi.fn(async () => undefined),
|
||||
initialize: stt.initialize,
|
||||
ensureAuxModel: vi.fn(async () => {
|
||||
if (stt.gate) await stt.gate
|
||||
}),
|
||||
|
|
@ -29,7 +30,13 @@ vi.mock('../../../src/main/services/LocalSTTService', () => ({
|
|||
}),
|
||||
}))
|
||||
|
||||
const audio = vi.hoisted(() => ({ start: vi.fn(async () => undefined), stop: vi.fn(async () => undefined) }))
|
||||
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,
|
||||
|
|
@ -63,7 +70,12 @@ beforeEach(async () => {
|
|||
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()
|
||||
})
|
||||
|
|
@ -98,4 +110,42 @@ describe('CaptionService — 자막 전용 보조 모델 해제', () => {
|
|||
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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,178 @@
|
|||
// 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()
|
||||
})
|
||||
})
|
||||
|
|
@ -151,4 +151,17 @@ describe('LlmGateway 호출 단위 취소', () => {
|
|||
})
|
||||
expect(l.processText).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('processText_localBackendWithSignal_forwardsPerCallSignalToLocalAdapter', async () => {
|
||||
const controller = new AbortController()
|
||||
const l = local()
|
||||
const gw = createRoutedLlmGateway({
|
||||
getBackend: () => 'local',
|
||||
loadPremium: async () => premium(),
|
||||
getLocal: () => l,
|
||||
})
|
||||
|
||||
await gw.processText('t', 'refine', undefined, undefined, { signal: controller.signal })
|
||||
expect(l.processText).toHaveBeenCalledWith('t', 'refine', undefined, undefined, { signal: controller.signal })
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -256,3 +256,121 @@ describe('LocalLLMService model residency (2026-10-11 memory policy)', () => {
|
|||
expect(unloads).toEqual([{ model: 'gemma4:e4b', keep_alive: 0 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('LocalLLMService cancellation and dispose safety', () => {
|
||||
beforeEach(() => {
|
||||
initInMemoryConfig()
|
||||
resetLocalLLMServiceForTests()
|
||||
markAvailable()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetLocalLLMServiceForTests()
|
||||
resetInMemoryConfig()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('processText_signalAbortedMidGenerate_rejectsWithCancelled', async () => {
|
||||
let seenSignal: AbortSignal | undefined
|
||||
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
seenSignal = init?.signal ?? undefined
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('fetch was not aborted')), 300)
|
||||
init?.signal?.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(timer)
|
||||
reject(new Error('aborted'))
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
})
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const controller = new AbortController()
|
||||
const promise = (
|
||||
getLocalLLMService() as unknown as {
|
||||
processText: (
|
||||
text: string,
|
||||
action: 'refine',
|
||||
targetLanguage?: string,
|
||||
customPrompt?: string,
|
||||
options?: { signal?: AbortSignal },
|
||||
) => Promise<string>
|
||||
}
|
||||
).processText('안녕', 'refine', undefined, undefined, { signal: controller.signal })
|
||||
|
||||
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
|
||||
controller.abort()
|
||||
|
||||
await expect(promise).rejects.toMatchObject({ code: ErrorCode.LLMProcessingCancelled })
|
||||
expect(seenSignal?.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('pullModel_disposedMidStream_abortsFetchCancelsReaderAndMarksUnavailable', async () => {
|
||||
let safetyTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const cancelReader = vi.fn(async () => {
|
||||
if (safetyTimer) clearTimeout(safetyTimer)
|
||||
})
|
||||
let seenSignal: AbortSignal | undefined
|
||||
let pullFetchAborted = false
|
||||
|
||||
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
seenSignal = init?.signal ?? undefined
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
pullFetchAborted = true
|
||||
})
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
pull() {
|
||||
return new Promise<void>((_resolve, reject) => {
|
||||
safetyTimer = setTimeout(() => reject(new Error('pull was not cancelled')), 300)
|
||||
})
|
||||
},
|
||||
cancel: cancelReader,
|
||||
})
|
||||
return new Response(stream, { status: 200 })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const service = getLocalLLMService()
|
||||
const pullPromise = service.pullModel('gemma4:e4b')
|
||||
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
|
||||
service.dispose()
|
||||
|
||||
await expect(pullPromise).rejects.toMatchObject({ code: ErrorCode.LLMProcessingCancelled })
|
||||
expect(pullFetchAborted || Boolean(seenSignal?.aborted)).toBe(true)
|
||||
expect(cancelReader).toHaveBeenCalledTimes(1)
|
||||
expect(service.isAvailable()).toBe(false)
|
||||
})
|
||||
|
||||
it('checkConnection_disposedWhilePending_doesNotRestoreAvailability', async () => {
|
||||
const service = getLocalLLMService()
|
||||
;(service as unknown as { _available: boolean })._available = false
|
||||
|
||||
let resolveVersion!: (value: Response) => void
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn((input: RequestInfo | URL) => {
|
||||
if (String(input).endsWith('/api/tags')) {
|
||||
return Promise.resolve(new Response(JSON.stringify({ models: [] }), { status: 200 }))
|
||||
}
|
||||
return new Promise<Response>((resolve) => {
|
||||
resolveVersion = resolve
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
const checkPromise = service.checkConnection()
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
|
||||
service.dispose()
|
||||
resolveVersion(new Response(JSON.stringify({ version: '0.20.0' }), { status: 200 }))
|
||||
const status = await checkPromise
|
||||
|
||||
expect(status.available).toBe(false)
|
||||
expect(service.isAvailable()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -374,4 +374,54 @@ describe('LocalSTTService — 사이드카 크래시 재시작', () => {
|
|||
expect(local.currentModelId).toBe('tiny')
|
||||
await local.dispose()
|
||||
})
|
||||
|
||||
it('downloadModel_disposedWhilePolling_abortsPromptlyWithoutPollingAfterDispose', async () => {
|
||||
const h = createHarness()
|
||||
h.setHealthy(true)
|
||||
let statusPollsAfterDispose = 0
|
||||
let disposed = false
|
||||
|
||||
const wrappedFetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input)
|
||||
if (url.endsWith('/download')) {
|
||||
return jsonResponse({ status: 'downloading' })
|
||||
}
|
||||
if (url.endsWith('/download/status')) {
|
||||
if (disposed) {
|
||||
statusPollsAfterDispose++
|
||||
if (statusPollsAfterDispose >= 2) {
|
||||
return jsonResponse({
|
||||
status: 'done',
|
||||
percent: 100,
|
||||
downloaded_bytes: 100,
|
||||
total_bytes: 100,
|
||||
bytes_per_second: 100,
|
||||
})
|
||||
}
|
||||
}
|
||||
return jsonResponse({
|
||||
status: 'downloading',
|
||||
percent: 10,
|
||||
downloaded_bytes: 10,
|
||||
total_bytes: 100,
|
||||
bytes_per_second: 10,
|
||||
})
|
||||
}
|
||||
return h.fetch(url, init)
|
||||
})
|
||||
vi.stubGlobal('fetch', wrappedFetch)
|
||||
|
||||
const local = new LocalSTTService({ supervisor: h.supervisor })
|
||||
const downloadPromise = local.downloadModel('tiny')
|
||||
await vi.waitFor(() =>
|
||||
expect(wrappedFetch.mock.calls.some(([url]) => String(url).endsWith('/download'))).toBe(true),
|
||||
)
|
||||
|
||||
disposed = true
|
||||
const disposePromise = local.dispose()
|
||||
|
||||
await expect(downloadPromise).rejects.toMatchObject({ code: ErrorCode.STTModelDownloadCancelled })
|
||||
await disposePromise
|
||||
expect(statusPollsAfterDispose).toBe(0)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -139,4 +139,23 @@ describe('WindowManager popup hide/show timer race regressions', () => {
|
|||
await vi.advanceTimersByTimeAsync(160)
|
||||
expect(wm.isCommandPopupVisible()).toBe(false)
|
||||
})
|
||||
|
||||
it('hideResultPopup_calledBeforeMeasureTimeout_cancelsPendingShowAndStaysHidden', async () => {
|
||||
const wm = await import('../../../src/main/windows/WindowManager')
|
||||
|
||||
wm.showResultPopup('hello world', 5000)
|
||||
const popupWin = state.windows[0]
|
||||
expect(popupWin?.visible).toBe(true)
|
||||
|
||||
// Hide before RESULT_MEASURE_TIMEOUT_MS (400ms) fires
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
wm.hideResultPopup()
|
||||
expect(popupWin?.visible).toBe(false)
|
||||
|
||||
const sendsBeforeTimeout = popupWin?.webContents.send.mock.calls.length ?? 0
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
|
||||
expect(popupWin?.visible).toBe(false)
|
||||
expect(popupWin?.webContents.send.mock.calls.length ?? 0).toBe(sendsBeforeTimeout)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue