fix(desktop): harden session, meeting, caption and LLM lifecycles; route LLM calls through the gateway
This commit is contained in:
parent
3a46437f28
commit
ddc78546f0
62 changed files with 4786 additions and 648 deletions
|
|
@ -15,6 +15,7 @@ import { getHistoryService } from './HistoryService'
|
|||
import { configGet } from './ConfigService'
|
||||
import { buildCaptionRefinePrompt } from './llm-prompts'
|
||||
import { StreamingCaptionTrack, type CaptionTranscription } from './caption/StreamingCaptionTrack'
|
||||
import { CaptionAudioSources } from './caption/CaptionAudioSources'
|
||||
import { acceptCaptionRefinement } from '@d3ro/core/caption-streaming'
|
||||
import {
|
||||
showCaptionOverlay,
|
||||
|
|
@ -91,7 +92,12 @@ interface CaptionServiceEvents {
|
|||
'segment': (segment: CaptionSegment) => void
|
||||
'delta': (data: { text: string; isFinal: boolean }) => void
|
||||
'session-saved': (summary: CaptionSessionResult) => void
|
||||
'error': (error: D3ROError) => void
|
||||
/**
|
||||
* 인식·시작 실패 알림. 'error' 가 아니다 — 리스너 없는 'error' 는 EventEmitter 가 던져서,
|
||||
* 정지 중 마지막 문장 인식이 실패하면 stop() 이 해제 전에 튕겨 나가 서비스가 'stopping' 에
|
||||
* 마이크가 열린 채 굳었다.
|
||||
*/
|
||||
'failure': (error: D3ROError) => void
|
||||
}
|
||||
|
||||
class CaptionService extends EventEmitter {
|
||||
|
|
@ -113,7 +119,8 @@ class CaptionService extends EventEmitter {
|
|||
private _refineQueue: CaptionSegment[] = []
|
||||
private _refining = false
|
||||
|
||||
private _audioDataHandler: ((payload: { buffer: Buffer; timestamp: number }) => void) | null = null
|
||||
/** 이번 세션이 잡은 오디오 소스(마이크 캡처·시스템 소리 요청) — 해제는 멱등 */
|
||||
private _audio: CaptionAudioSources = this._createAudioSources()
|
||||
/** 현재 세션 옵션(소유자·오버레이·히스토리 저장) — 세션이 없으면 기본값 */
|
||||
private _session: ResolvedStartOptions = { ...DEFAULT_START_OPTIONS }
|
||||
|
||||
|
|
@ -203,22 +210,16 @@ class CaptionService extends EventEmitter {
|
|||
}
|
||||
logger.info(`Caption audioSource: ${audioSource} (owner: ${this._session.owner})`)
|
||||
|
||||
// 마이크 캡처 (mic 또는 both)
|
||||
// 트랙 먼저 — 마이크 첫 청크부터 받을 수 있게
|
||||
if (audioSource === 'mic' || audioSource === 'both') {
|
||||
this._micTrack = this._createTrack('mic', initialContext)
|
||||
const audioCaptureService = getAudioCaptureService()
|
||||
this._audioDataHandler = (payload) => {
|
||||
this._onAudioData(payload.buffer)
|
||||
}
|
||||
audioCaptureService.on('audio-data', this._audioDataHandler)
|
||||
await audioCaptureService.start()
|
||||
}
|
||||
|
||||
// 시스템 오디오 캡처 요청 (system 또는 both) — 렌더러에 시작 요청
|
||||
if (audioSource === 'system' || audioSource === 'both') {
|
||||
this._systemTrack = this._createTrack('system', initialContext)
|
||||
this._sendToMainWindow(IPC_CHANNELS.CAPTION.START_SYSTEM_AUDIO, {})
|
||||
}
|
||||
// 마이크 캡처(mic/both) + 시스템 오디오 캡처 요청(system/both — 렌더러에 시작 요청)
|
||||
this._audio = this._createAudioSources()
|
||||
await this._audio.acquire(audioSource, { onMicChunk: (buffer) => this._onAudioData(buffer) })
|
||||
|
||||
// 트랙 판단 타이머 — 각 트랙은 한 번에 인식 한 건만 돌린다
|
||||
this._tickTimer = setInterval(() => {
|
||||
|
|
@ -236,13 +237,8 @@ class CaptionService extends EventEmitter {
|
|||
}
|
||||
this._micTrack = null
|
||||
this._systemTrack = null
|
||||
if (this._audioDataHandler) {
|
||||
const audioCaptureService = getAudioCaptureService()
|
||||
audioCaptureService.off('audio-data', this._audioDataHandler)
|
||||
this._audioDataHandler = null
|
||||
await audioCaptureService.stop().catch(() => {})
|
||||
}
|
||||
hideCaptionOverlay()
|
||||
await this._audio.release()
|
||||
this._hideOverlaySafely()
|
||||
this._session = { ...DEFAULT_START_OPTIONS }
|
||||
this._setState('inactive')
|
||||
const d3roErr =
|
||||
|
|
@ -252,7 +248,7 @@ class CaptionService extends EventEmitter {
|
|||
ErrorCode.CaptionStartFailed,
|
||||
`캡션 시작 실패: ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
this.emit('error', d3roErr)
|
||||
this._reportFailure(d3roErr)
|
||||
throw d3roErr
|
||||
}
|
||||
}
|
||||
|
|
@ -284,28 +280,31 @@ class CaptionService extends EventEmitter {
|
|||
this._tickTimer = null
|
||||
}
|
||||
|
||||
// 잔여 오디오 처리 — 말하던 중이면 마지막 문장을 확정한다
|
||||
await Promise.all([this._micTrack?.flush(), this._systemTrack?.flush()])
|
||||
this._micTrack = null
|
||||
this._systemTrack = null
|
||||
|
||||
// 마이크 캡처 정리
|
||||
if (this._audioDataHandler) {
|
||||
const audioCaptureService = getAudioCaptureService()
|
||||
audioCaptureService.off('audio-data', this._audioDataHandler)
|
||||
this._audioDataHandler = null
|
||||
await audioCaptureService.stop()
|
||||
// 잔여 오디오 처리 — 말하던 중이면 마지막 문장을 확정한다.
|
||||
// 인식이 실패해도(사이드카 500·타임아웃) 아래 해제·초기화는 반드시 실행한다 — 예전엔 여기서 튕겨
|
||||
// 마이크가 열린 채 'stopping' 에 굳어 재시작 전까지 자막·회의를 다시 시작할 수 없었다.
|
||||
try {
|
||||
const results = await Promise.allSettled([this._micTrack?.flush(), this._systemTrack?.flush()])
|
||||
for (const result of results) {
|
||||
if (result.status === 'rejected') this._reportFailure(this._toSttError(result.reason, 'flush'))
|
||||
}
|
||||
} finally {
|
||||
this._micTrack = null
|
||||
this._systemTrack = null
|
||||
// 마이크 캡처 정리 + 시스템 오디오 캡처 중지 요청 (멱등, 실패해도 계속)
|
||||
await this._audio.release()
|
||||
// 오버레이 숨김
|
||||
this._hideOverlaySafely()
|
||||
}
|
||||
|
||||
// 시스템 오디오 캡처 중지 요청
|
||||
this._sendToMainWindow(IPC_CHANNELS.CAPTION.STOP_SYSTEM_AUDIO, {})
|
||||
|
||||
// 오버레이 숨김
|
||||
hideCaptionOverlay()
|
||||
|
||||
// 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다)
|
||||
const persist = this._session.persistHistory
|
||||
const summary = this._saveSession(persist)
|
||||
let summary: CaptionSessionResult | null = null
|
||||
try {
|
||||
summary = this._saveSession(persist)
|
||||
} catch (err) {
|
||||
logger.error(`캡션 세션 요약 실패: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
|
||||
this._sessionId = null
|
||||
this._sessionStartedAt = null
|
||||
|
|
@ -363,22 +362,65 @@ class CaptionService extends EventEmitter {
|
|||
isVoiced: (chunk) => calculateRMS(chunk) >= SILENCE_RMS_THRESHOLD,
|
||||
onPartial: (text, stable) => this._emitPartial(text, stable),
|
||||
onFinal: (text) => this._emitFinal(text, source),
|
||||
onError: (err) => {
|
||||
const d3roErr =
|
||||
err instanceof D3ROError
|
||||
? err
|
||||
: new D3ROError(
|
||||
ErrorCode.CaptionSTTFailed,
|
||||
`자막 전사 실패(${source}): ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
logger.error(d3roErr.message)
|
||||
this.emit('error', d3roErr)
|
||||
},
|
||||
// 절대 던지지 않는 보고 경로 — 트랙의 인식 실패가 정지·틱을 깨뜨리지 않게
|
||||
onError: (err) => this._reportFailure(this._toSttError(err, source)),
|
||||
},
|
||||
initialContext,
|
||||
)
|
||||
}
|
||||
|
||||
private _toSttError(err: unknown, source: string): D3ROError {
|
||||
return err instanceof D3ROError
|
||||
? err
|
||||
: new D3ROError(
|
||||
ErrorCode.CaptionSTTFailed,
|
||||
`자막 전사 실패(${source}): ${err instanceof Error ? err.message : String(err)}`,
|
||||
)
|
||||
}
|
||||
|
||||
/** 실패를 로그와 'failure' 이벤트로 알린다. 리스너가 던져도 호출자에게 새지 않는다. */
|
||||
private _reportFailure(error: D3ROError): void {
|
||||
logger.error(error.message)
|
||||
try {
|
||||
this.emit('failure', error)
|
||||
} catch (err) {
|
||||
logger.warn(`caption failure listener threw: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
|
||||
private _hideOverlaySafely(): void {
|
||||
try {
|
||||
hideCaptionOverlay()
|
||||
} catch (err) {
|
||||
logger.warn(`캡션 오버레이 숨기기 실패: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 오디오 소스 어댑터 — 마이크는 AudioCaptureService, 시스템 소리는 렌더러 IPC */
|
||||
private _createAudioSources(): CaptionAudioSources {
|
||||
return new CaptionAudioSources({
|
||||
mic: () => {
|
||||
const capture = getAudioCaptureService()
|
||||
return {
|
||||
onChunk: (listener) => {
|
||||
const handler = (payload: { buffer: Buffer; timestamp: number }): void => listener(payload.buffer)
|
||||
capture.on('audio-data', handler)
|
||||
return () => { capture.off('audio-data', handler) }
|
||||
},
|
||||
start: () => capture.start(),
|
||||
stop: () => capture.stop(),
|
||||
}
|
||||
},
|
||||
system: {
|
||||
requestStart: () => this._sendToMainWindow(IPC_CHANNELS.CAPTION.START_SYSTEM_AUDIO, {}),
|
||||
requestStop: () => this._sendToMainWindow(IPC_CHANNELS.CAPTION.STOP_SYSTEM_AUDIO, {}),
|
||||
},
|
||||
onReleaseError: (stage, err) => {
|
||||
logger.warn(`캡션 오디오 해제 실패(${stage}): ${err instanceof Error ? err.message : String(err)}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** 자막은 항상 로컬 엔진으로 인식한다 — 1초마다 다시 인식하므로 클라우드로는 보낼 수 없다. */
|
||||
private async _transcribe(
|
||||
audio: Buffer,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue