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
|
|
@ -5,6 +5,7 @@ import { ipcMain, session, desktopCapturer } from 'electron'
|
|||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
|
||||
import { getCaptionService } from '../services/CaptionService'
|
||||
import { getLogger } from '../services/LoggerService'
|
||||
import type { CaptionConfig } from '@d3ro/core/types'
|
||||
import {
|
||||
endCaptionOverlayDrag,
|
||||
|
|
@ -13,6 +14,8 @@ import {
|
|||
startCaptionOverlayDrag
|
||||
} from '../windows/WindowManager'
|
||||
|
||||
const logger = getLogger('CaptionHandlers')
|
||||
|
||||
export function registerCaptionHandlers(): void {
|
||||
// ── 자막 창 손잡이 (팝업 → 메인) ──
|
||||
ipcMain.on(IPC_CHANNELS.POPUP_CAPTION.SET_INTERACTIVE, (_event, interactive: unknown) => {
|
||||
|
|
@ -25,12 +28,19 @@ export function registerCaptionHandlers(): void {
|
|||
// 시스템 오디오 루프백: setDisplayMediaRequestHandler로 audio: 'loopback' 설정
|
||||
ipcMain.handle(IPC_CHANNELS.SYSTEM_AUDIO.ENABLE_LOOPBACK, async () => {
|
||||
session.defaultSession.setDisplayMediaRequestHandler(async (_request, callback) => {
|
||||
const sources = await desktopCapturer.getSources({ types: ['screen'] })
|
||||
if (sources.length === 0) {
|
||||
try {
|
||||
const sources = await desktopCapturer.getSources({ types: ['screen'] })
|
||||
if (sources.length === 0) {
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
callback({ video: sources[0], audio: 'loopback' })
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
`Display media source lookup failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
callback({})
|
||||
return
|
||||
}
|
||||
callback({ video: sources[0], audio: 'loopback' })
|
||||
})
|
||||
return ipcSuccess(undefined)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ class AudioCaptureService extends EventEmitter {
|
|||
private _refCount = 0
|
||||
private _cachedDevices: AudioDevice[] | null = null
|
||||
private _soxProcess: ChildProcess | null = null
|
||||
private _soxExited = false
|
||||
private _stream: Readable | null = null
|
||||
private _levelInterval: ReturnType<typeof setInterval> | null = null
|
||||
/** 새 SoX 를 띄울 때마다 증가 — 임대(lease)가 자기 캡처인지 판단한다 */
|
||||
|
|
@ -155,15 +156,21 @@ class AudioCaptureService extends EventEmitter {
|
|||
return
|
||||
}
|
||||
|
||||
// 마지막 참조가 꼬리를 받는 중에 새 소비자가 오면 정지를 취소하고 같은 SoX 로 이어 간다
|
||||
// 마지막 참조가 꼬리를 받는 중에 새 소비자가 오면 SoX가 아직 살아 있을 때만 정지를 취소하고 이어 간다
|
||||
if (this._state === 'stopping' && this._pendingStopToken !== 0) {
|
||||
this._pendingStopToken = 0
|
||||
this._cancelTailWait?.()
|
||||
this._state = 'capturing'
|
||||
this._refCount = 1
|
||||
this._startLevelTimer()
|
||||
logger.debug('Pending stop cancelled by a new consumer — capture continues')
|
||||
return
|
||||
if (this._isSoxProcessAlive()) {
|
||||
this._state = 'capturing'
|
||||
this._refCount = 1
|
||||
this._startLevelTimer()
|
||||
logger.debug('Pending stop cancelled by a new consumer — capture continues')
|
||||
return
|
||||
}
|
||||
this._emitResidual()
|
||||
this._cleanup()
|
||||
this._currentDevice = null
|
||||
this._state = 'idle'
|
||||
}
|
||||
|
||||
if (this._state !== 'idle' && this._state !== 'error') {
|
||||
|
|
@ -202,6 +209,7 @@ class AudioCaptureService extends EventEmitter {
|
|||
logger.info(`SoX args: ${soxArgs.join(' ')}`)
|
||||
const child = spawn(soxExe, soxArgs, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
|
||||
this._soxProcess = child
|
||||
this._soxExited = false
|
||||
this._generation++
|
||||
this._stream = child.stdout
|
||||
this._residualBuffer = Buffer.alloc(0)
|
||||
|
|
@ -222,11 +230,18 @@ class AudioCaptureService extends EventEmitter {
|
|||
if (msg) logger.warn(`SoX stderr: ${msg}`)
|
||||
})
|
||||
|
||||
child.once('exit', () => {
|
||||
if (this._soxProcess === child) {
|
||||
this._soxExited = true
|
||||
}
|
||||
})
|
||||
|
||||
// SoX 프로세스 종료 감지.
|
||||
// 자기 프로세스인지 먼저 확인한다 — 예전엔 kill 한 옛 SoX 의 'close' 가 몇 ms 뒤에 와서
|
||||
// 그사이 시작된 새 캡처('capturing')를 오류로 끝냈다(회의 중 마이크 테스트로 회의 마이크가 끊김).
|
||||
child.on('close', (code) => {
|
||||
if (this._soxProcess !== child) return
|
||||
this._soxExited = true
|
||||
if (this._state === 'capturing') {
|
||||
logger.warn(`SoX process exited unexpectedly (code: ${code})`)
|
||||
this._handleError(
|
||||
|
|
@ -238,6 +253,7 @@ class AudioCaptureService extends EventEmitter {
|
|||
|
||||
child.on('error', (err: Error) => {
|
||||
if (this._soxProcess !== child) return
|
||||
this._soxExited = true
|
||||
logger.error(`SoX process spawn error: ${err.message}`)
|
||||
const hint =
|
||||
soxExe === 'sox' && (err as NodeJS.ErrnoException).code === 'ENOENT'
|
||||
|
|
@ -264,6 +280,7 @@ class AudioCaptureService extends EventEmitter {
|
|||
this.emit('started', { deviceId: this._currentDevice.deviceId })
|
||||
logger.info('Audio capture started')
|
||||
} catch (error) {
|
||||
this._cleanup()
|
||||
this._state = 'error'
|
||||
const d3roError = new D3ROError(
|
||||
ErrorCode.AudioCaptureStartFailed,
|
||||
|
|
@ -626,11 +643,19 @@ class AudioCaptureService extends EventEmitter {
|
|||
this.emit('stopped', { reason: stopReason })
|
||||
}
|
||||
|
||||
/** 현재 보유 중인 SoX 프로세스가 아직 살아 있는지 확인한다 */
|
||||
private _isSoxProcessAlive(): boolean {
|
||||
const child = this._soxProcess
|
||||
if (!child || this._soxExited) return false
|
||||
return child.exitCode == null && !child.killed
|
||||
}
|
||||
|
||||
/**
|
||||
* 녹음 프로세스와 타이머를 정리한다.
|
||||
*/
|
||||
private _cleanup(): void {
|
||||
this._stopLevelTimer()
|
||||
this._soxExited = false
|
||||
|
||||
if (this._stream) {
|
||||
this._stream.removeAllListeners()
|
||||
|
|
|
|||
|
|
@ -128,6 +128,10 @@ class CaptionService extends EventEmitter {
|
|||
private _captionModelId: string | null = null
|
||||
private _refineQueue: CaptionSegment[] = []
|
||||
private _refining = false
|
||||
private _refineEpoch = 0
|
||||
private _refineRunId = 0
|
||||
private _refineController: AbortController | null = null
|
||||
private _stopPromise: Promise<CaptionSessionResult | null> | null = null
|
||||
|
||||
/** 이번 세션이 잡은 오디오 소스(마이크 캡처·시스템 소리 요청) — 해제는 멱등 */
|
||||
private _audio: CaptionAudioSources = this._createAudioSources()
|
||||
|
|
@ -189,6 +193,9 @@ class CaptionService extends EventEmitter {
|
|||
if (epoch !== this._startEpoch || this._disposed) throw new CaptionStartCancelledError()
|
||||
}
|
||||
let ownAudio: CaptionAudioSources | null = null
|
||||
let loadedAuxModelId: string | null = null
|
||||
this._captionModelId = null
|
||||
this._resetRefineState()
|
||||
this._setState('starting')
|
||||
|
||||
// 오버레이를 즉시 표시 (로딩 상태) — 회의 모드처럼 자체 UI 가 있으면 띄우지 않는다
|
||||
|
|
@ -204,9 +211,13 @@ class CaptionService extends EventEmitter {
|
|||
await sttService.initialize()
|
||||
assertCurrent()
|
||||
// 자막 전용 모델을 골랐으면 받아쓰기 모델과 별도로 올려 둔다(보조 자리).
|
||||
this._captionModelId = configGet('captionSttModelId') ?? null
|
||||
if (this._captionModelId) await sttService.ensureAuxModel(this._captionModelId)
|
||||
const candidateAuxModelId = configGet('captionSttModelId') ?? null
|
||||
if (candidateAuxModelId) {
|
||||
await sttService.ensureAuxModel(candidateAuxModelId)
|
||||
loadedAuxModelId = candidateAuxModelId
|
||||
}
|
||||
assertCurrent()
|
||||
this._captionModelId = loadedAuxModelId
|
||||
|
||||
// 세션 초기화
|
||||
this._sessionId = crypto.randomUUID()
|
||||
|
|
@ -261,7 +272,9 @@ class CaptionService extends EventEmitter {
|
|||
// 이 시도가 연 자원만 돌려준다(release 는 멱등).
|
||||
await ownAudio?.release()
|
||||
// stop() 이 내릴 때 아직 로딩 중이던 보조 모델이 뒤늦게 올라왔을 수 있다. 새 시작이 없을 때만 내린다.
|
||||
if (this._captionModelId && this._state === 'inactive') void getLocalSTTService().releaseAuxModel()
|
||||
if (loadedAuxModelId && (this._state === 'inactive' || this._state === 'stopping')) {
|
||||
void getLocalSTTService().releaseAuxModel()
|
||||
}
|
||||
logger.info('캡션 시작 취소: 로딩 중 정지됨')
|
||||
throw new D3ROError(ErrorCode.CaptionStartFailed, '캡션 시작이 취소되었습니다')
|
||||
}
|
||||
|
|
@ -274,7 +287,9 @@ class CaptionService extends EventEmitter {
|
|||
await this._audio.release()
|
||||
this._hideOverlaySafely()
|
||||
// 시작 실패(오디오 장치 없음 등)에도 올려 둔 보조 모델을 내린다 — 안 그러면 다음 세션 종료까지 VRAM 을 잡는다.
|
||||
if (this._captionModelId) void getLocalSTTService().releaseAuxModel()
|
||||
const auxToRelease = this._captionModelId ?? loadedAuxModelId
|
||||
this._captionModelId = null
|
||||
if (auxToRelease) void getLocalSTTService().releaseAuxModel()
|
||||
this._session = { ...DEFAULT_START_OPTIONS }
|
||||
this._setState('inactive')
|
||||
const d3roErr =
|
||||
|
|
@ -299,6 +314,13 @@ class CaptionService extends EventEmitter {
|
|||
* @returns 세션 요약(세그먼트가 없으면 null), 다른 소유자라 거부했으면 false
|
||||
*/
|
||||
async stop(owner?: CaptionOwner): Promise<CaptionSessionResult | null | false> {
|
||||
if (this._state === 'stopping' && this._stopPromise) {
|
||||
if (owner && owner !== this._session.owner) {
|
||||
logger.warn(`캡션 중지 거부: 세션 소유자=${this._session.owner}, 요청=${owner}`)
|
||||
return false
|
||||
}
|
||||
return this._stopPromise
|
||||
}
|
||||
if (this._state !== 'active' && this._state !== 'starting') {
|
||||
logger.warn(`캡션 중지 불가: 현재 상태=${this._state}`)
|
||||
return null
|
||||
|
|
@ -311,7 +333,14 @@ class CaptionService extends EventEmitter {
|
|||
// 로딩 중(start 가 모델을 기다리는 중)이면 그 start 를 무효화한다 — 깨어나도 마이크를 열지 않는다.
|
||||
if (this._state === 'starting') this._startEpoch += 1
|
||||
this._setState('stopping')
|
||||
this._resetRefineState()
|
||||
|
||||
const stopRun = this._performStop()
|
||||
this._stopPromise = stopRun
|
||||
return stopRun
|
||||
}
|
||||
|
||||
private async _performStop(): Promise<CaptionSessionResult | null> {
|
||||
// 타이머 정리
|
||||
if (this._tickTimer) {
|
||||
clearInterval(this._tickTimer)
|
||||
|
|
@ -335,7 +364,9 @@ class CaptionService extends EventEmitter {
|
|||
this._hideOverlaySafely()
|
||||
// 자막 전용 보조 모델은 세션이 끝나면 내린다 — 남겨 두면 받아쓰기 모델과 함께 VRAM 을 잡아
|
||||
// Ollama 로드를 느리게 하거나 OOM 을 부른다. 다음 세션 시작 때 다시 올린다.
|
||||
if (this._captionModelId) void getLocalSTTService().releaseAuxModel()
|
||||
const auxToRelease = this._captionModelId
|
||||
this._captionModelId = null
|
||||
if (auxToRelease) void getLocalSTTService().releaseAuxModel()
|
||||
}
|
||||
|
||||
// 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다)
|
||||
|
|
@ -352,6 +383,7 @@ class CaptionService extends EventEmitter {
|
|||
this._refineQueue = []
|
||||
this._sessionLanguage = null
|
||||
this._session = { ...DEFAULT_START_OPTIONS }
|
||||
this._stopPromise = null
|
||||
|
||||
this._setState('inactive')
|
||||
getSoundEffectService().play('recording-stop')
|
||||
|
|
@ -369,8 +401,9 @@ class CaptionService extends EventEmitter {
|
|||
async dispose(): Promise<void> {
|
||||
if (this._disposed) return
|
||||
this._disposed = true
|
||||
this._resetRefineState()
|
||||
|
||||
if (this._state === 'active' || this._state === 'starting') {
|
||||
if (this._state === 'active' || this._state === 'starting' || this._state === 'stopping') {
|
||||
await this.stop()
|
||||
}
|
||||
|
||||
|
|
@ -522,7 +555,17 @@ class CaptionService extends EventEmitter {
|
|||
|
||||
// ── 내부: 문맥 다듬기 ──
|
||||
|
||||
private _resetRefineState(): void {
|
||||
this._refineEpoch += 1
|
||||
this._refineRunId += 1
|
||||
this._refineQueue = []
|
||||
this._refining = false
|
||||
this._refineController?.abort()
|
||||
this._refineController = null
|
||||
}
|
||||
|
||||
private _enqueueRefine(segment: CaptionSegment): void {
|
||||
if (this._disposed || this._state !== 'active') return
|
||||
if (configGet('captionRefineEnabled') === false) return
|
||||
if (!getLocalLLMService().isAvailable()) return
|
||||
this._refineQueue.push(segment)
|
||||
|
|
@ -532,17 +575,30 @@ class CaptionService extends EventEmitter {
|
|||
}
|
||||
|
||||
private async _drainRefineQueue(): Promise<void> {
|
||||
const runId = ++this._refineRunId
|
||||
const epoch = this._refineEpoch
|
||||
this._refining = true
|
||||
try {
|
||||
for (let next = this._refineQueue.shift(); next; next = this._refineQueue.shift()) {
|
||||
await this._refine(next)
|
||||
while (
|
||||
!this._disposed &&
|
||||
this._state === 'active' &&
|
||||
epoch === this._refineEpoch &&
|
||||
this._refineQueue.length > 0
|
||||
) {
|
||||
const next = this._refineQueue.shift()
|
||||
if (!next) break
|
||||
await this._refine(next, epoch)
|
||||
}
|
||||
} finally {
|
||||
this._refining = false
|
||||
if (this._refineRunId === runId) {
|
||||
this._refining = false
|
||||
this._refineController = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async _refine(segment: CaptionSegment): Promise<void> {
|
||||
private async _refine(segment: CaptionSegment, epoch: number): Promise<void> {
|
||||
if (this._disposed || this._state !== 'active' || epoch !== this._refineEpoch) return
|
||||
const index = this._segments.findIndex((item) => item.id === segment.id)
|
||||
if (index === -1) return
|
||||
const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text)
|
||||
|
|
@ -552,19 +608,27 @@ class CaptionService extends EventEmitter {
|
|||
previous,
|
||||
...(glossary ? { glossary } : {}),
|
||||
})
|
||||
const controller = new AbortController()
|
||||
this._refineController = controller
|
||||
try {
|
||||
const result = await getLocalLLMService().generate(text, {
|
||||
systemPrompt,
|
||||
temperature: 0,
|
||||
maxTokens: Math.min(256, segment.text.length * 2 + 32),
|
||||
timeoutMs: REFINE_TIMEOUT_MS,
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (this._disposed || this._state !== 'active' || epoch !== this._refineEpoch) return
|
||||
const refined = acceptCaptionRefinement(segment.text, result.text)
|
||||
if (!refined) return
|
||||
// 모델이 용어를 다른 표기로 되돌렸을 수 있다 — 정본 표기를 마지막에 다시 강제한다.
|
||||
this._replaceSegmentText(segment.id, getTranscriptGlossaryService().correct(refined).text)
|
||||
} catch (err) {
|
||||
logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`)
|
||||
} finally {
|
||||
if (this._refineController === controller) {
|
||||
this._refineController = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -186,6 +186,7 @@ class LocalLLMService extends EventEmitter {
|
|||
private _activeRequests = new Set<ActiveRequest>()
|
||||
private _ensureRunningPromise: Promise<'running' | 'starting' | 'not-installed' | 'failed'> | null = null
|
||||
private _startCheckTimers = new Set<ReturnType<typeof setTimeout>>()
|
||||
private _pullControllers = new Set<AbortController>()
|
||||
private _disposed = false
|
||||
|
||||
get state(): LLMState {
|
||||
|
|
@ -414,7 +415,7 @@ class LocalLLMService extends EventEmitter {
|
|||
* Ollama 가용성 폴링을 시작한다 (5초 간격).
|
||||
*/
|
||||
startPolling(): void {
|
||||
if (this._pollInterval) return
|
||||
if (this._pollInterval || this._disposed) return
|
||||
this._checkAvailability()
|
||||
this._pollInterval = setInterval(() => {
|
||||
if (this._state !== LLMState.Generating) {
|
||||
|
|
@ -686,8 +687,13 @@ class LocalLLMService extends EventEmitter {
|
|||
text: string,
|
||||
action: LLMAction,
|
||||
targetLanguage?: string,
|
||||
customPrompt?: string
|
||||
customPrompt?: string,
|
||||
options?: { signal?: AbortSignal; timeoutMs?: number }
|
||||
): Promise<string> {
|
||||
if (options?.signal?.aborted) {
|
||||
throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LLM processing was cancelled')
|
||||
}
|
||||
|
||||
// Phase 11: LLM 처리 쿼터 체크
|
||||
try {
|
||||
const { getLicenseService } = await import('./LicenseService')
|
||||
|
|
@ -708,10 +714,18 @@ class LocalLLMService extends EventEmitter {
|
|||
// LicenseService 미초기화 시 허용
|
||||
}
|
||||
|
||||
if (options?.signal?.aborted) {
|
||||
throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LLM processing was cancelled')
|
||||
}
|
||||
|
||||
const basePrompt = resolveSystemPrompt(action, targetLanguage, customPrompt)
|
||||
const systemPrompt = `${NO_THINK}\n${basePrompt}`
|
||||
|
||||
const result = await this.generate(text, { systemPrompt })
|
||||
const result = await this.generate(text, {
|
||||
systemPrompt,
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {})
|
||||
})
|
||||
const cleaned = stripReasoningBlocks(result.text)
|
||||
// reasoning 블록 제거 후 빈 응답이면 원본 텍스트 폴백
|
||||
// (모델이 thinking만 하고 출력은 안 한 경우 / 응답 파싱 실패 케이스)
|
||||
|
|
@ -784,67 +798,97 @@ class LocalLLMService extends EventEmitter {
|
|||
}
|
||||
|
||||
private async _doPullModel(modelId: string): Promise<void> {
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LocalLLMService disposed')
|
||||
}
|
||||
|
||||
const serverUrl = getOllamaServerUrl()
|
||||
const controller = new AbortController()
|
||||
this._pullControllers.add(controller)
|
||||
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null
|
||||
const onAbort = (): void => {
|
||||
void reader?.cancel().catch(() => undefined)
|
||||
}
|
||||
controller.signal.addEventListener('abort', onAbort, { once: true })
|
||||
logger.info(`Pull 시작: ${modelId}`)
|
||||
|
||||
const response = await fetch(`${serverUrl}/api/pull`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model: modelId, stream: true })
|
||||
})
|
||||
try {
|
||||
const response = await fetch(`${serverUrl}/api/pull`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model: modelId, stream: true }),
|
||||
signal: controller.signal
|
||||
})
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.LLMServerUnreachable,
|
||||
`Pull 실패: HTTP ${response.status}`
|
||||
)
|
||||
}
|
||||
if (!response.ok || !response.body) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.LLMServerUnreachable,
|
||||
`Pull 실패: HTTP ${response.status}`
|
||||
)
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
reader = response.body.getReader()
|
||||
if (this._disposed || controller.signal.aborted) {
|
||||
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
|
||||
}
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
for (;;) {
|
||||
if (this._disposed || controller.signal.aborted) {
|
||||
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
|
||||
}
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() ?? ''
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() ?? ''
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (trimmed.length === 0) continue
|
||||
try {
|
||||
const chunk = JSON.parse(trimmed) as {
|
||||
status: string
|
||||
digest?: string
|
||||
total?: number
|
||||
completed?: number
|
||||
error?: string
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (trimmed.length === 0) continue
|
||||
try {
|
||||
const chunk = JSON.parse(trimmed) as {
|
||||
status: string
|
||||
digest?: string
|
||||
total?: number
|
||||
completed?: number
|
||||
error?: string
|
||||
}
|
||||
if (chunk.error) {
|
||||
throw new D3ROError(ErrorCode.LLMServerUnreachable, chunk.error)
|
||||
}
|
||||
this.emit('pull-progress', {
|
||||
modelId,
|
||||
status: chunk.status,
|
||||
digest: chunk.digest ?? null,
|
||||
total: chunk.total ?? 0,
|
||||
completed: chunk.completed ?? 0,
|
||||
percent:
|
||||
chunk.total && chunk.total > 0
|
||||
? Math.min(100, Math.floor(((chunk.completed ?? 0) / chunk.total) * 100))
|
||||
: 0
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof D3ROError) throw err
|
||||
// JSON 파싱 실패한 부분 라인은 스킵
|
||||
}
|
||||
if (chunk.error) {
|
||||
throw new D3ROError(ErrorCode.LLMServerUnreachable, chunk.error)
|
||||
}
|
||||
this.emit('pull-progress', {
|
||||
modelId,
|
||||
status: chunk.status,
|
||||
digest: chunk.digest ?? null,
|
||||
total: chunk.total ?? 0,
|
||||
completed: chunk.completed ?? 0,
|
||||
percent:
|
||||
chunk.total && chunk.total > 0
|
||||
? Math.min(100, Math.floor(((chunk.completed ?? 0) / chunk.total) * 100))
|
||||
: 0
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof D3ROError) throw err
|
||||
// JSON 파싱 실패한 부분 라인은 스킵
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`Pull 완료: ${modelId}`)
|
||||
if (this._disposed || controller.signal.aborted) {
|
||||
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
|
||||
}
|
||||
|
||||
logger.info(`Pull 완료: ${modelId}`)
|
||||
} finally {
|
||||
controller.signal.removeEventListener('abort', onAbort)
|
||||
this._pullControllers.delete(controller)
|
||||
if (reader) {
|
||||
await reader.cancel().catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getStatus(): LLMStatus {
|
||||
|
|
@ -989,8 +1033,14 @@ class LocalLLMService extends EventEmitter {
|
|||
clearTimeout(timer)
|
||||
}
|
||||
this._startCheckTimers.clear()
|
||||
for (const controller of this._pullControllers) {
|
||||
controller.abort()
|
||||
}
|
||||
this._pullControllers.clear()
|
||||
this.stopPolling()
|
||||
this.cancelGeneration()
|
||||
this._available = false
|
||||
this._serverVersion = null
|
||||
this._refreshState()
|
||||
this.removeAllListeners()
|
||||
logger.info('LocalLLMService disposed')
|
||||
|
|
@ -1022,6 +1072,8 @@ class LocalLLMService extends EventEmitter {
|
|||
// ignore
|
||||
}
|
||||
|
||||
if (this._disposed) return
|
||||
|
||||
if (!isOk) {
|
||||
try {
|
||||
const tagsRes = await fetch(`${serverUrl}/api/tags`, {
|
||||
|
|
@ -1035,6 +1087,8 @@ class LocalLLMService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
if (this._disposed) return
|
||||
|
||||
const wasAvailable = this._available
|
||||
this._available = isOk
|
||||
if (detectedVersion) this._serverVersion = detectedVersion
|
||||
|
|
|
|||
|
|
@ -243,6 +243,8 @@ class LocalSTTService extends EventEmitter {
|
|||
// errorEmitted 플래그로 이벤트 중복 방지
|
||||
private _errorEmitted: boolean = false
|
||||
private _idleUnloadTimer: NodeJS.Timeout | null = null
|
||||
private _downloadControllers = new Set<AbortController>()
|
||||
private _downloadSleepCancelers = new Set<() => void>()
|
||||
|
||||
// ── 상태 접근자 ──
|
||||
|
||||
|
|
@ -521,13 +523,22 @@ class LocalSTTService extends EventEmitter {
|
|||
}
|
||||
|
||||
await this._supervisor.ready()
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.STTModelDownloadCancelled,
|
||||
'모델 다운로드 중 서비스가 종료되었습니다',
|
||||
)
|
||||
}
|
||||
|
||||
const startRes = await fetch(`${this._baseUrl}/download`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
const startRes = await this._fetchDownload(
|
||||
`${this._baseUrl}/download`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
},
|
||||
10000,
|
||||
)
|
||||
|
||||
// 409 = 이미 다운로드 진행 중 — 실패가 아니라 기존 진행에 합류해 폴링
|
||||
if (!startRes.ok && startRes.status !== 409) {
|
||||
|
|
@ -551,17 +562,33 @@ class LocalSTTService extends EventEmitter {
|
|||
// 진행률 폴링 — sidecar 통신 실패가 연속되면 중단
|
||||
let consecutiveFailures = 0
|
||||
for (;;) {
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.STTModelDownloadCancelled,
|
||||
`모델 다운로드 취소: ${modelId}`,
|
||||
)
|
||||
}
|
||||
await this._sleep(500)
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.STTModelDownloadCancelled,
|
||||
`모델 다운로드 취소: ${modelId}`,
|
||||
)
|
||||
}
|
||||
|
||||
let status: DownloadStatusResponse
|
||||
try {
|
||||
const res = await fetch(`${this._baseUrl}/download/status`, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
})
|
||||
const res = await this._fetchDownload(`${this._baseUrl}/download/status`, {}, 3000)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
status = (await res.json()) as DownloadStatusResponse
|
||||
consecutiveFailures = 0
|
||||
} catch (err) {
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.STTModelDownloadCancelled,
|
||||
`모델 다운로드 취소: ${modelId}`,
|
||||
)
|
||||
}
|
||||
consecutiveFailures++
|
||||
if (consecutiveFailures >= 5) {
|
||||
throw new D3ROError(
|
||||
|
|
@ -572,6 +599,13 @@ class LocalSTTService extends EventEmitter {
|
|||
continue
|
||||
}
|
||||
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(
|
||||
ErrorCode.STTModelDownloadCancelled,
|
||||
`모델 다운로드 취소: ${modelId}`,
|
||||
)
|
||||
}
|
||||
|
||||
this._emitDownloadProgress(
|
||||
modelId,
|
||||
status.percent,
|
||||
|
|
@ -637,6 +671,14 @@ class LocalSTTService extends EventEmitter {
|
|||
logger.info('LocalSTTService dispose 시작')
|
||||
|
||||
this._clearIdleUnload()
|
||||
for (const cancelSleep of this._downloadSleepCancelers) {
|
||||
cancelSleep()
|
||||
}
|
||||
this._downloadSleepCancelers.clear()
|
||||
for (const controller of this._downloadControllers) {
|
||||
controller.abort()
|
||||
}
|
||||
this._downloadControllers.clear()
|
||||
this._initializing = null
|
||||
this._modelReady = false
|
||||
this._auxModelId = null
|
||||
|
|
@ -995,8 +1037,38 @@ class LocalSTTService extends EventEmitter {
|
|||
logger.error(`STT 에러: [${error.code}] ${error.message}`)
|
||||
}
|
||||
|
||||
private async _fetchDownload(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
timeoutMs: number,
|
||||
): Promise<Response> {
|
||||
if (this._disposed) {
|
||||
throw new D3ROError(ErrorCode.STTModelDownloadCancelled, 'LocalSTTService가 dispose되었습니다')
|
||||
}
|
||||
const controller = new AbortController()
|
||||
this._downloadControllers.add(controller)
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
timer.unref?.()
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
this._downloadControllers.delete(controller)
|
||||
}
|
||||
}
|
||||
|
||||
private _sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
if (this._disposed) return Promise.resolve()
|
||||
return new Promise((resolve) => {
|
||||
const cancel = (): void => {
|
||||
clearTimeout(timer)
|
||||
this._downloadSleepCancelers.delete(cancel)
|
||||
resolve()
|
||||
}
|
||||
const timer = setTimeout(cancel, ms)
|
||||
timer.unref?.()
|
||||
this._downloadSleepCancelers.add(cancel)
|
||||
})
|
||||
}
|
||||
|
||||
// ── 타입 안전한 이벤트 메서드 오버라이드 ──
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ class VoiceConversationService extends EventEmitter {
|
|||
* 카운트가 쌓였고, 세션을 끝내도 마이크(SoX)가 계속 열려 있었다.
|
||||
*/
|
||||
private _micHeld = false
|
||||
private _listenEpoch = 0
|
||||
private _responseAbortController: AbortController | null = null
|
||||
/** 취소·세션 종료마다 올린다 — 전사가 끝났을 때 그 사이 취소됐는지 가린다(전사 중엔 abort 할 응답이 없다). */
|
||||
private _turn = 0
|
||||
|
|
@ -122,8 +123,10 @@ class VoiceConversationService extends EventEmitter {
|
|||
this._turn += 1
|
||||
this._stopListening()
|
||||
// 이 대화의 응답만 멈춘다 — signal 이 LLM 호출까지 전달된다(전역 cancelGeneration 은 다른 기능의
|
||||
// 진행 중 호출까지 끊었다).
|
||||
this._responseAbortController?.abort()
|
||||
// 진행 중 호출까지 끊었다). 포인터를 먼저 비워 취소 직후 새 턴이 막히지 않게 한다.
|
||||
const responseController = this._responseAbortController
|
||||
this._responseAbortController = null
|
||||
responseController?.abort()
|
||||
getTTSPlaybackService().stop()
|
||||
|
||||
this._isActive = false
|
||||
|
|
@ -147,7 +150,9 @@ class VoiceConversationService extends EventEmitter {
|
|||
*/
|
||||
cancelResponse(): void {
|
||||
this._turn += 1
|
||||
this._responseAbortController?.abort()
|
||||
const responseController = this._responseAbortController
|
||||
this._responseAbortController = null
|
||||
responseController?.abort()
|
||||
getTTSPlaybackService().stop()
|
||||
if (this._isActive && this._state !== 'listening') {
|
||||
this._resumeListening()
|
||||
|
|
@ -266,7 +271,9 @@ class VoiceConversationService extends EventEmitter {
|
|||
|
||||
if (!this._micHeld) {
|
||||
this._micHeld = true
|
||||
const listenEpoch = ++this._listenEpoch
|
||||
audioService.start().catch((err) => {
|
||||
if (!this._isActive || this._listenEpoch !== listenEpoch) return
|
||||
this._micHeld = false
|
||||
logger.error('Failed to start audio capture for conversation:', err)
|
||||
this._emitError('stt', 'Failed to start microphone')
|
||||
|
|
@ -278,6 +285,7 @@ class VoiceConversationService extends EventEmitter {
|
|||
}
|
||||
|
||||
private _stopListening(): void {
|
||||
this._listenEpoch += 1
|
||||
const audioService = getAudioCaptureService()
|
||||
if (this._audioListenerBound) {
|
||||
audioService.off('audio-data', this._onAudioData)
|
||||
|
|
|
|||
|
|
@ -1023,8 +1023,10 @@ class VoiceModeService extends EventEmitter {
|
|||
action: LLMAction,
|
||||
targetLanguage?: string,
|
||||
customPrompt?: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
return getLlmGateway().processText(text, action, targetLanguage, customPrompt, {
|
||||
...(signal ? { signal } : {}),
|
||||
onFallback: (reason) => this._emitPremiumFallback(reason),
|
||||
})
|
||||
}
|
||||
|
|
@ -1087,8 +1089,8 @@ class VoiceModeService extends EventEmitter {
|
|||
|
||||
const processedText =
|
||||
route.kind === 'instruction'
|
||||
? await this._processWithInstruction(userText, route.instructionId)
|
||||
: await this._processWithAction(userText, route.action)
|
||||
? await this._processWithInstruction(userText, route.instructionId, run.controller.signal)
|
||||
: await this._processWithAction(userText, route.action, run.controller.signal)
|
||||
|
||||
if (!this._isCurrent(run)) return
|
||||
|
||||
|
|
@ -1115,7 +1117,11 @@ class VoiceModeService extends EventEmitter {
|
|||
}
|
||||
|
||||
/** 지시문(음성 단축키 또는 활성 지시문·파이프라인)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
|
||||
private async _processWithInstruction(userText: string, instructionId: string | null): Promise<string> {
|
||||
private async _processWithInstruction(
|
||||
userText: string,
|
||||
instructionId: string | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
let invocationText = userText
|
||||
let instructionPrompt: string | undefined
|
||||
|
||||
|
|
@ -1146,13 +1152,14 @@ class VoiceModeService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt)
|
||||
return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt, signal)
|
||||
}
|
||||
|
||||
/** 일반 액션(refine/translate/…)으로 처리한다 */
|
||||
private async _processWithAction(
|
||||
userText: string,
|
||||
action: Extract<LlmProcessingRoute, { kind: 'action' }>['action'],
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const targetLanguage = resolveTargetLanguage()
|
||||
logger.info(
|
||||
|
|
@ -1164,6 +1171,8 @@ class VoiceModeService extends EventEmitter {
|
|||
userText,
|
||||
action,
|
||||
action === 'translate' ? targetLanguage : undefined,
|
||||
undefined,
|
||||
signal,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -114,7 +114,13 @@ export interface PremiumLlmAdapter {
|
|||
|
||||
export interface LocalLlmAdapter {
|
||||
isAvailable(): boolean
|
||||
processText(text: string, action: LLMAction, targetLanguage?: string, customPrompt?: string): Promise<string>
|
||||
processText(
|
||||
text: string,
|
||||
action: LLMAction,
|
||||
targetLanguage?: string,
|
||||
customPrompt?: string,
|
||||
options?: { signal?: AbortSignal; timeoutMs?: number },
|
||||
): Promise<string>
|
||||
generate(
|
||||
text: string,
|
||||
options?: LlmGenerateOptions & { signal?: AbortSignal; timeoutMs?: number },
|
||||
|
|
@ -214,8 +220,10 @@ class RoutedLlmGateway implements LlmGateway {
|
|||
}
|
||||
}
|
||||
throwIfAborted(hooks?.signal)
|
||||
// 로컬 processText 는 호출 단위 signal 을 받지 않는다 — 끝난 뒤 취소됐으면 결과를 버린다.
|
||||
const result = await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt)
|
||||
const perCall = callOptions(hooks)
|
||||
const result = perCall
|
||||
? await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt, perCall)
|
||||
: await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt)
|
||||
throwIfAborted(hooks?.signal)
|
||||
return result
|
||||
}
|
||||
|
|
|
|||
|
|
@ -567,6 +567,8 @@ ipcMain.on(IPC_CHANNELS.POPUP_RESULT.MEASURED, (event: Electron.IpcMainEvent, da
|
|||
})
|
||||
|
||||
export function hideResultPopup(): void {
|
||||
cancelPendingResultShow()
|
||||
lastResultCursor = null
|
||||
if (resultPopupWindow && !resultPopupWindow.isDestroyed()) {
|
||||
resultPopupWindow.hide()
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue