// src/main/services/VoiceModeService.ts // 전체 음성 파이프라인 오케스트레이터. // 설계서 01의 IVoiceModeService 구현. Speakly VoiceModeService의 // 상태 머신, 이중 조건 플러시, Action Queue 패턴 적용. // // 세션 런(SessionRun): // 세션마다 run 객체를 하나 만든다. 모든 비동기 단계(STT 초기화, 오디오 시작, 전사, LLM)는 // 자기 run 을 붙잡고 있다가 await 뒤에 `_isCurrent(run)` 으로 아직 자기 세션인지 확인한다. // 예전엔 `_isInTerminalState()` 로만 확인했는데, 취소/에러/완료가 곧바로 IDLE(비터미널)로 // 돌아가므로 취소된 세션의 결과가 다음 세션에 삽입되고 마이크가 새는 버그가 있었다. // 오디오 캡처 참조(refCount)는 run 이 실제로 잡았을 때만, 정확히 한 번 놓는다. // // 표시(RecordingTip/결과 팝업)는 이 서비스가 직접 하지 않는다 — 'phase' / 'audio-level' / // 'partial-transcript' / 'error' / 'insert-failed' 이벤트를 내보내고 // windows/recording-tip-presenter 가 구독해 그린다(오케스트레이션 → 윈도우 의존 제거). import { EventEmitter } from 'events' import { randomUUID } from 'crypto' import { getLogger } from './LoggerService' import { createFsRecordingStore, type RecordingStore } from './recording/recording-store' import { getAudioCaptureService } from './AudioCaptureService' import { getSTTManager } from './stt/STTManager' import type { TranscriptionResult } from './stt/types' import { getKeyBindingService } from './KeyBindingService' import type { KeyBindingTriggerPayload } from './KeyBindingService' import { configGet } from './ConfigService' import { getTextInsertService } from './TextInsertService' import { getLocalLLMService } from './LocalLLMService' import { getLlmGateway } from './llm/LlmGateway' import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { cleanDictatedText } from '@d3ro/core/dictation-cleaner' import { TIMING } from '@d3ro/core/constants' import { RecognitionState, AudioState } from '@d3ro/core/types' import type { KeyBindingActionId, VoiceMode, VoiceState, LLMAction } from '@d3ro/core/types' import type { ScreenContext } from '@d3ro/core/types' import { resolveVoiceLlmRoute, routeUsesLlm, type VoiceLlmRoute } from '@d3ro/core/voice-llm-route' import { deriveVoiceIntentPhase, resolveGestureHoldMode, resolveGestureMode, resolveVoiceIntent, } from './voice-intent' const logger = getLogger('VoiceModeService') // ============================================================ // 내부 타입 // ============================================================ interface VoiceSession { id: string mode: VoiceMode startedAt: number recognitionState: RecognitionState audioState: AudioState audioBufferDurationMs: number transcription: string processedText: string | null accidentalPress: boolean screenContext: ScreenContext | null } interface VoiceAction { type: 'press' | 'release' | 'escape' timestamp: number mode: VoiceMode actionId: KeyBindingActionId /** hold-to-talk 여부 — release 에서 세션을 끊을지 결정한다 */ holdMode: boolean } /** RecordingTip 표시 단계 — 녹음 시작(모델 확인 통과 후) / 녹음 종료 후 처리 중 */ export type VoiceSessionPhase = 'recording' | 'thinking' export interface VoiceModeEvents { 'session-started': (payload: { session: VoiceSession }) => void 'recognition-state-changed': (payload: { previous: RecognitionState current: RecognitionState }) => void 'audio-state-changed': (payload: { previous: AudioState current: AudioState }) => void 'transcription-update': (payload: { text: string; isFinal: boolean }) => void /** audioPath: 저장된 녹음 WAV 경로(완료 이벤트 전에 저장됨). 오디오가 없거나 저장 실패면 null */ /** willInsert: 이어서 자동 입력을 시도하는지(자동 입력 꺼짐·빈 글이면 false) */ 'session-completed': (payload: { session: VoiceSession finalText: string audioPath: string | null willInsert: boolean }) => void /** 완료된 세션의 글을 자동 입력했다 */ 'text-inserted': (payload: { sessionId: string }) => void 'session-cancelled': (payload: { session: VoiceSession reason: 'user' | 'timeout' | 'too-short' }) => void 'audio-level': (payload: { level: number }) => void /** 표시 단계 전환 — 'recording' 은 모델 확인을 통과한 뒤에만 나간다 */ phase: (payload: { phase: VoiceSessionPhase; sessionId: string }) => void /** 녹음 중 실시간 미리보기 텍스트 (최종 삽입과 무관) */ 'partial-transcript': (payload: { text: string; sessionId: string }) => void /** 자동 삽입 실패 — 표시 계층이 결과 팝업으로 텍스트를 보여 준다 */ 'insert-failed': (payload: { text: string; sessionId: string }) => void error: (payload: { error: D3ROError session: VoiceSession | null /** 'warning'은 세션을 막지 않는 알림 (기본 'error') */ severity?: 'error' | 'warning' }) => void /** * Phase 3.2: Premium LLM 호출이 실패해 Local로 자동 fallback된 경우 emit. * renderer에서 이 이벤트를 받아 Snackbar 경고 배너를 띄운다. */ 'premium-llm-fallback': (payload: { reason: string }) => void } /** * 한 세션의 런타임 상태. 세션이 끝나면(완료/취소/에러) abort 되어 늦게 도착한 비동기 * 결과가 다음 세션에 손대지 못하게 한다. */ class SessionRun { readonly controller = new AbortController() /** audio.start() 가 성공해 이 run 이 캡처 참조를 잡고 있다 */ audioAcquired = false /** 오디오 해제가 요청됐다 — start 가 늦게 끝나도 곧바로 놓는다 */ audioReleaseRequested = false /** 녹음이 스트리밍 중이다 (부분 전사·플러시 판단용) */ audioStarted = false /** 사용자가 이미 정지를 요청했다 — 두 번째 release/토글은 무시한다 */ stopRequested = false sttReady = false transcribing = false audioBuffer: Buffer[] = [] audioBufferBytes = 0 /** WAV 저장용 — 다음 세션이 덮어쓰지 못하게 run 에 둔다 */ lastAudio: Buffer | null = null /** 스크린 컨텍스트: 선택 텍스트 캡처 여부와 진행 중 작업 */ captureSelection = false selectionCapture: Promise | null = null /** 스크린 컨텍스트: 녹음 시작 시점 활성 창 조회 (기다리지 않고 LLM 단계에서 합친다) */ windowContext: Promise | null = null dataHandler: ((payload: { buffer: Buffer }) => void) | null = null levelHandler: ((payload: { level: number }) => void) | null = null stoppedHandler: ((payload: { reason: 'manual' | 'device-lost' | 'error' }) => void) | null = null sttWaitTimer: NodeJS.Timeout | null = null partialTimer: NodeJS.Timeout | null = null partialInFlight: Promise | null = null constructor(readonly id: string) {} get aborted(): boolean { return this.controller.signal.aborted } } // ============================================================ // 터미널 상태 헬퍼 // ============================================================ const TERMINAL_STATES = new Set([ RecognitionState.COMPLETED, RecognitionState.CANCELLED, RecognitionState.ERROR, RecognitionState.DESTROYED ]) // ── 실시간 부분 전사(미리보기) ── // 16kHz 16bit mono = 32 bytes/ms const BYTES_PER_MS = 32 /** 부분 전사 주기 */ const PARTIAL_INTERVAL_MS = 1500 /** 부분 전사를 시작할 최소 녹음 길이 */ const PARTIAL_MIN_AUDIO_MS = 1200 /** 부분 전사에 보낼 최대 오디오 창(끝부분만) — 오래 말해도 지연이 늘지 않게 한다 */ const PARTIAL_MAX_WINDOW_MS = 7500 /** 녹음 종료 시 진행 중 부분 전사를 기다리는 최대 시간 */ const PARTIAL_DRAIN_TIMEOUT_MS = 2500 function describe(err: unknown): string { return err instanceof Error ? err.message : String(err) } /** * 청크 목록의 끝에서 maxBytes 만큼만 새 버퍼로 모은다. * 예전엔 1.5초마다 녹음 전체를 concat 한 뒤 잘라 30분 녹음이면 초당 ~38MB 의 가비지를 만들었고, * subarray 라 진행 중 부분 전사가 원본 전체를 붙잡았다. 끝부분 청크만 복사한다. */ function tailAudio(chunks: readonly Buffer[], maxBytes: number): Buffer { const picked: Buffer[] = [] let total = 0 for (let i = chunks.length - 1; i >= 0 && total < maxBytes; i -= 1) { picked.push(chunks[i]) total += chunks[i].length } picked.reverse() const merged = Buffer.concat(picked, total) // 청크 경계에서 넘친 앞부분은 버린다 (merged 는 창 크기 + 청크 하나 정도라 subarray 로 충분) return total > maxBytes ? merged.subarray(total - maxBytes) : merged } /** LLM 을 실제로 부르는 경로 */ type LlmProcessingRoute = Exclude /** * 정지 요청의 결과. 오디오 해제까지는 요청 안에서 끝나고, 전사·LLM 후처리는 `finished` 로 따로 돈다. * (async 함수가 Promise 를 반환하면 펼쳐지므로 객체로 감싼다) */ interface StopOutcome { finished: Promise } const NOTHING_PENDING: StopOutcome = { finished: Promise.resolve() } // ============================================================ // VoiceModeService // ============================================================ class VoiceModeService extends EventEmitter { /** 녹음 저장 포트 — 경로·fs·WAV 인코딩은 어댑터가 맡는다 (DIP) */ constructor(private readonly _recordings: RecordingStore = createFsRecordingStore()) { super() } private _session: VoiceSession | null = null private _run: SessionRun | null = null private _recognitionState = RecognitionState.IDLE private _audioState = AudioState.IDLE // Action Queue (이벤트 직렬화) private _actionQueue: VoiceAction[] = [] private _isProcessingQueue = false private _keyBindingHandler: ((payload: KeyBindingTriggerPayload) => void) | null = null private _disposed = false get currentSession(): VoiceSession | null { return this._session } get isActive(): boolean { return this._session !== null && !this._isInTerminalState() } getState(): VoiceState { return { recognitionState: this._recognitionState, audioState: this._audioState, mode: configGet('defaultLLMAction') === 'translate' ? 'hands-free' : 'dictation', sessionId: this._session?.id ?? null, recordingStartedAt: this._session?.startedAt ?? null } } // ── 초기화 ────────────────────────────────────────────── /** * KeyBindingService 이벤트를 구독하여 키바인딩 → 세션 제어를 연결한다. * bootstrap에서 호출한다. */ connectKeyBindings(): void { this._keyBindingHandler = (payload) => { switch (payload.actionId) { case 'caption': // Phase 10.1: caption은 VoiceModeService가 아닌 CaptionService로 라우팅. // 토글이므로 press만 처리하고 release는 버린다. if (payload.type === 'pressed') this._toggleCaption() return case 'dictation': case 'hands-free': case 'command': break default: // 음성 세션 액션만 여기서 처리한다. 팝업·제안 액션은 bootstrap이 직접 구독한다 // (허용 목록이 아니면 새 액션이 생길 때마다 받아쓰기로 오인돼 녹음이 켜진다). return } const holdMode = resolveGestureHoldMode(payload.actionId, payload.holdMode) const action: VoiceAction = { type: payload.type === 'pressed' ? 'press' : 'release', timestamp: payload.timestamp, mode: resolveGestureMode(payload.actionId, payload.isDoublePress), actionId: payload.actionId, holdMode } this._enqueueAction(action) } getKeyBindingService().on('triggered', this._keyBindingHandler) logger.info('Key binding events connected') } // ── 세션 제어 ────────────────────────────────────────── async startSession(mode: VoiceMode): Promise { if (this._disposed) return if (this._session && !this._isInTerminalState()) { logger.warn('Session already active, ignoring startSession') return } // Phase 11: 라이센스 쿼터 체크 try { const { getLicenseService } = await import('./LicenseService') const { Feature } = await import('@d3ro/core/types') const license = getLicenseService() const access = license.canUse(Feature.DICTATION) if (!access.allowed) { const reason = access.reason === 'quota_exceeded' ? 'quota_exceeded' : access.reason === 'login_required' ? 'login_required' : 'tier_required' license.promptUpgrade(Feature.DICTATION, reason) logger.warn(`Dictation blocked: ${access.reason}`) const code = access.reason === 'quota_exceeded' ? ErrorCode.QuotaExceeded : ErrorCode.TierRequired this.emit('error', { error: new D3ROError(code, `Dictation blocked: ${access.reason}`), session: null, }) return } license.consumeQuota(Feature.DICTATION) } catch (err) { if (err instanceof D3ROError) { this.emit('error', { error: err, session: null }) return } // LicenseService 미초기화 시 허용 (graceful) } // Phase 10.1: 자막 모드 활성 중이면 dictation 세션 시작 불가 (AudioCaptureService 공유) try { const { getCaptionService } = await import('./CaptionService') const captionState = getCaptionService().getState() if (captionState === 'active' || captionState === 'starting') { logger.warn('Cannot start dictation: caption mode active') this.emit('error', { error: new D3ROError(ErrorCode.CaptionAlreadyActive, 'Cannot start dictation: caption mode active'), session: null, }) return } } catch { // CaptionService 미초기화 시 무시 } // Phase 10.2: 스크린 컨텍스트 — 녹음 시작 시점엔 활성 앱 정보만 캡처한다. // 선택 텍스트(Ctrl+C)는 여기서 보내지 않는다: 이 시점엔 사용자가 아직 핫키(기본 Right Alt)를 // 누르고 있어 대상 앱에 Ctrl+Alt+C 가 들어가고(복사 안 됨, AltGr 배열에선 문자 입력), // 클립보드만 비워진다. 선택 텍스트는 녹음 종료(키를 뗀 뒤)에 캡처한다. // 활성 창 조회는 기다리지 않는다 — 예전엔 조회(PowerShell, 0.7~3초)가 세션·마이크 시작 앞을 // 막아 첫 말이 잘리고 짧은 hold-to-talk 가 'too-short' 로 취소됐다. 결과는 LLM 단계에서 합친다. let windowContext: Promise | null = null try { const { getScreenContextService } = await import('./ScreenContextService') const ctx = getScreenContextService() if (ctx.isEnabled()) { windowContext = ctx.captureContext(false).then( (result) => { logger.info(`Screen context captured: ${result.context.appName ?? 'unknown'}`) return result.context }, (err: unknown) => { logger.debug(`Screen context capture skipped: ${describe(err)}`) return null }, ) } } catch { // 컨텍스트 캡처 실패 시 무시 — 핵심 기능 아님 } // 위 await 사이에 다른 경로(IPC 등)가 세션을 시작했으면 양보한다 if (this._disposed || (this._session && !this._isInTerminalState())) return // 세션 생성 const run = new SessionRun(randomUUID()) run.captureSelection = windowContext !== null run.windowContext = windowContext this._run = run this._session = { id: run.id, mode, startedAt: Date.now(), recognitionState: RecognitionState.PREPARING, audioState: AudioState.IDLE, audioBufferDurationMs: 0, transcription: '', processedText: null, accidentalPress: false, screenContext: null, } this._setRecognitionState(RecognitionState.PREPARING) this.emit('session-started', { session: this._session }) logger.info(`Session started: ${run.id} (mode: ${mode})`) const stt = getSTTManager() const missingModel = stt.getMissingModel() if (missingModel) { this._handleError( run, new D3ROError(ErrorCode.STTModelNotFound, `STT model not installed: ${missingModel}`), ) return } // Speakly 패턴: 녹음 시작 시 즉시 RecordingTip 표시 (표시 계층이 'phase' 를 구독) this.emit('phase', { phase: 'recording', sessionId: run.id }) // 이중 조건 플러시: STT 초기화 + 오디오 캡처를 병렬 시작. // 주의: STT 초기화는 await하지 않는다 — sidecar 기동이 느리거나 실패할 때 // press 액션이 action queue를 점유해 release가 수십 초 지연되던 버그의 원인. // (_initSTT는 내부에서 에러를 _handleError로 처리하므로 fire-and-forget 안전) void this._initSTT(run) await this._startAudio(run) } /** * 세션을 정지하고 전사·후처리가 끝날 때까지 기다린다 (IPC 등 공개 API). * 키 입력 경로는 _requestStop 만 기다려 액션 큐를 막지 않는다. */ async stopSession(): Promise { const { finished } = await this._requestStop() await finished } /** * 정지 요청과 오디오 해제까지만 수행한다. 전사·LLM 은 run 에 묶어 `finished` 로 따로 돈다. * 예전엔 정지가 STT·LLM 전체(수 초)를 await 해 액션 큐를 막았고, 그사이 들어온 입력이 * 세션이 끝난 뒤 다른 의미로 재생됐다(더블탭 정지의 두 번째 탭이 새 핸즈프리 녹음을 시작). */ private async _requestStop(): Promise { const run = this._run const session = this._session if (!run || !session || !this._isCurrent(run) || this._isInTerminalState()) return NOTHING_PENDING // 정지는 세션당 한 번이다. 지연 전사가 도는 중에 두 번째 release/토글이 오면 // 예전엔 비어 있는 버퍼를 보고 'too-short' 로 조용히 취소해 받아쓰기를 잃었다. if (run.stopRequested) { logger.info('Stop already requested for this session — ignoring') return NOTHING_PENDING } run.stopRequested = true const duration = Date.now() - session.startedAt // accidentalPress 체크 (700ms 미만) if (duration < TIMING.MIN_AUDIO_DURATION) { session.accidentalPress = true logger.info(`Accidental press detected (${duration}ms < ${TIMING.MIN_AUDIO_DURATION}ms)`) this._cancelSession('too-short') return NOTHING_PENDING } // 오디오 캡처 중지 this._setAudioState(AudioState.STOPPED) await this._releaseAudio(run) if (!this._isCurrent(run)) return NOTHING_PENDING // Speakly 패턴: 녹음 종료 후 thinking 상태로 전환 this.emit('phase', { phase: 'thinking', sessionId: run.id }) // 핫키를 뗀 뒤라 복사 단축키가 안전하다 — LLM 이 쓸 것이 확실하면 전사와 병렬로 선택 텍스트를 // 캡처한다. 원문 삽입 경로(none·LLM 불가)에선 보내지 않는다: 쓰지도 않을 Ctrl+C 가 터미널에선 // 프로세스를 중단시킨다. 음성 단축키로 LLM 경로가 될 수도 있으면 LLM 단계에서 늦게 캡처한다. if (routeUsesLlm(this._resolveLlmRoute(null))) this._startSelectionCapture(run) // 버퍼가 있으면 STT에 전달 if (run.audioBuffer.length > 0 && run.sttReady) { return { finished: this._transcribe(run).catch((err: unknown) => { logger.error(`Unhandled error in _transcribe after stop: ${describe(err)}`) }), } } else if (run.audioBuffer.length > 0 && !run.sttReady) { // STT 아직 준비 안 됨 → _initSTT 완료 후 _tryFlushAll이 전사 logger.info('Waiting for STT to be ready before transcribing') this._clearSttWaitTimer(run) run.sttWaitTimer = setTimeout(() => { run.sttWaitTimer = null // 전사가 이미 시작됐으면(RECOGNIZING) 취소하지 않는다. // 예전엔 6초 타이머가 첫 모델 로딩 직후 전사를 잘라 '전사가 안 됨'으로 보였다. if (this._isCurrent(run) && !run.sttReady && !run.transcribing) { logger.warn('STT readiness timeout, cancelling session') this._cancelSession('timeout') } }, TIMING.ABSOLUTE_MAX_WAIT) } else { // 오디오 없음 logger.warn('No audio buffer, cancelling session') this._cancelSession('too-short') } return NOTHING_PENDING } cancelSession(): void { this._cancelSession('user') } /** * 수정자 없는 Esc — 녹음·처리 중인 세션을 취소한다(2026-09-28: 녹음 팁의 "Esc 취소"). * 액션 큐로 넣어 누름/뗌과 순서를 지킨다. 진행 중인 세션이 없으면 아무것도 하지 않고 false. */ requestEscape(): boolean { if (!this.isActive) return false this._enqueueAction({ type: 'escape', timestamp: Date.now(), mode: 'dictation', actionId: 'dictation', holdMode: false, }) return true } // ── 상태 머신 ────────────────────────────────────────── private _isInTerminalState(): boolean { return TERMINAL_STATES.has(this._recognitionState) } /** run 이 아직 현재 세션인가 — 모든 await 뒤에 이것으로 확인한다 */ private _isCurrent(run: SessionRun): boolean { return this._run === run && !run.aborted } private _setRecognitionState(state: RecognitionState): void { if (this._recognitionState === state) return if (this._isInTerminalState() && state !== RecognitionState.IDLE) return const previous = this._recognitionState this._recognitionState = state if (this._session) { this._session.recognitionState = state } this.emit('recognition-state-changed', { previous, current: state }) logger.debug(`RecognitionState: ${previous} → ${state}`) } private _setAudioState(state: AudioState): void { if (this._audioState === state) return const previous = this._audioState this._audioState = state if (this._session) { this._session.audioState = state } this.emit('audio-state-changed', { previous, current: state }) logger.debug(`AudioState: ${previous} → ${state}`) } // ── STT 초기화 ───────────────────────────────────────── private async _initSTT(run: SessionRun): Promise { try { this._setRecognitionState(RecognitionState.CONNECTING) const stt = getSTTManager() await stt.ensureReady() if (!this._isCurrent(run)) return run.sttReady = true this._clearSttWaitTimer(run) if (!run.transcribing) this._setRecognitionState(RecognitionState.READY) logger.info(`STT ready (provider: ${stt.getActiveProvider()})`) this._tryFlushAll(run) } catch (error) { if (!this._isCurrent(run)) return this._handleError( run, new D3ROError( ErrorCode.STTModelLoadFailed, `STT initialization failed: ${describe(error)}` ) ) } } // ── 오디오 캡처 ──────────────────────────────────────── private async _startAudio(run: SessionRun): Promise { const audio = getAudioCaptureService() try { this._setAudioState(AudioState.INITIALIZING) // 오디오 데이터 수신 — 이 run 이 현재 세션일 때만 적재한다 run.dataHandler = (payload) => { if (!this._isCurrent(run)) return run.audioBuffer.push(payload.buffer) run.audioBufferBytes += payload.buffer.length // 버퍼 duration 업데이트 (16kHz, 16bit, mono) if (this._session) { this._session.audioBufferDurationMs = (run.audioBufferBytes / 2 / 16000) * 1000 } this._tryFlushAll(run) } run.levelHandler = (payload) => { if (!this._isCurrent(run)) return // Speakly 패턴: 오디오 레벨을 RecordingTip 웨이브 바에 전달 (표시 계층이 구독) this.emit('audio-level', { level: payload.level }) } // 캡처가 녹음 도중 죽으면(SoX 종료, 장치 분리) 예전엔 아무도 몰라 녹음 팁이 떠 있는 채 // 'too-short' 로 조용히 취소됐다. 이제 세션이 알아채고 사용자에게 알린다. run.stoppedHandler = ({ reason }) => { if (reason === 'manual') return if (!this._isCurrent(run)) return this._onCaptureLost(run, reason) } audio.on('audio-data', run.dataHandler) audio.on('audio-level', run.levelHandler) audio.on('stopped', run.stoppedHandler) await audio.start() run.audioAcquired = true // start 가 끝나기 전에 세션이 끝났거나 정지가 요청됐으면 방금 잡은 참조를 곧바로 놓는다 // (그냥 return 하면 refCount 가 새어 마이크가 계속 켜진다). if (!this._isCurrent(run) || run.audioReleaseRequested) { await this._releaseAudio(run) return } run.audioStarted = true this._setAudioState(AudioState.STREAMING) logger.info('Audio capture started') this._startPartialLoop(run) this._tryFlushAll(run) } catch (error) { this._detachAudioHandlers(run) if (!this._isCurrent(run)) return this._setAudioState(AudioState.STOPPED) this._handleError( run, new D3ROError( ErrorCode.AudioCaptureStartFailed, `Audio capture failed: ${describe(error)}` ) ) } } /** 캡처가 예기치 않게 끝났을 때 — 들어온 오디오가 있으면 그것으로 마무리, 없으면 에러 */ private _onCaptureLost(run: SessionRun, reason: 'device-lost' | 'error'): void { logger.warn(`Audio capture lost during session (${reason})`) // 캡처 쪽이 이미 정리했다 — 우리 참조로 stop() 을 부르면 다른 소비자의 참조를 깎는다 run.audioAcquired = false const session = this._session const duration = session ? Date.now() - session.startedAt : 0 if (!run.stopRequested && run.audioBufferBytes > 0 && duration >= TIMING.MIN_AUDIO_DURATION) { void this.stopSession() return } if (run.stopRequested) return this._setAudioState(AudioState.STOPPED) this._handleError( run, new D3ROError( ErrorCode.AudioCaptureFailed, `Microphone capture stopped unexpectedly (${reason}). Check the selected microphone.`, ), ) } private _detachAudioHandlers(run: SessionRun): void { const audio = getAudioCaptureService() if (run.dataHandler) { audio.off('audio-data', run.dataHandler) run.dataHandler = null } if (run.levelHandler) { audio.off('audio-level', run.levelHandler) run.levelHandler = null } if (run.stoppedHandler) { audio.off('stopped', run.stoppedHandler) run.stoppedHandler = null } } /** * 이 run 의 오디오를 놓는다. 멱등 — 정지/취소/에러/완료 어디서 불러도 audio.stop() 은 * run 이 실제로 참조를 잡았을 때 정확히 한 번만 호출된다(공유 refCount 보호). */ private async _releaseAudio(run: SessionRun): Promise { run.audioReleaseRequested = true this._stopPartialLoop(run) // 현재 세션의 정상 정지면 캡처가 꼬리 오디오(SoX 버퍼에 남은 끝 음절)를 흘려보낼 때까지 // 핸들러를 붙여 둔다 — 먼저 떼면 그 끝부분을 잃는다. 취소·교체된 run 은 꼬리가 필요 없다. // (그동안 audioStarted 를 유지해 _tryFlushAll 이 전사를 앞당기지 않게 한다) const keepForTail = run.audioAcquired && this._isCurrent(run) if (!keepForTail) { this._detachAudioHandlers(run) run.audioStarted = false } if (run.audioAcquired) { run.audioAcquired = false try { await getAudioCaptureService().stop() } catch (error) { logger.warn(`Audio stop error: ${describe(error)}`) } } this._detachAudioHandlers(run) run.audioStarted = false } // ── 스크린 컨텍스트(선택 텍스트) ───────────────────────── private _startSelectionCapture(run: SessionRun): void { if (!run.captureSelection || run.selectionCapture) return run.selectionCapture = (async (): Promise => { try { const { getScreenContextService } = await import('./ScreenContextService') return await getScreenContextService().captureSelectedText() } catch (err) { logger.debug(`Selected text capture skipped: ${describe(err)}`) return null } })() } /** * 활성 창 조회(녹음 시작 시점)와 선택 텍스트 캡처(정지 시점)가 끝나기를 기다렸다가 * 세션 컨텍스트로 합친다. */ private async _applyScreenContext(run: SessionRun): Promise { if (!run.windowContext && !run.selectionCapture) return const [windowContext, selectedText] = await Promise.all([ run.windowContext ?? Promise.resolve(null), run.selectionCapture ?? Promise.resolve(null), ]) if (!this._isCurrent(run) || !this._session) return if (!windowContext && !selectedText) return const base: ScreenContext = windowContext ?? this._session.screenContext ?? { appName: null, windowTitle: null, selectedText: null, capturedAt: Date.now(), } this._session.screenContext = selectedText ? { ...base, selectedText } : base } /** 세션 컨텍스트를 LLM 입력 접두사로 만든다 (없으면 빈 문자열) */ private async _buildContextPrefix(): Promise { const screenContext = this._session?.screenContext if (!screenContext) return '' try { const { getScreenContextService } = await import('./ScreenContextService') return getScreenContextService().buildContextPrompt(screenContext) } catch { return '' } } // ── 실시간 부분 전사(미리보기) ───────────────────────────── /** * 녹음 중 주기적으로 지금까지의 오디오를 전사해 RecordingTip에 미리보기를 띄운다. * 최종 삽입 텍스트와는 완전히 분리된 경로이며, 실패는 조용히 무시된다. */ private _startPartialLoop(run: SessionRun): void { this._stopPartialLoop(run) if (!getSTTManager().supportsPartial()) return run.partialTimer = setInterval(() => { void this._runPartial(run) }, PARTIAL_INTERVAL_MS) } private _stopPartialLoop(run: SessionRun): void { if (run.partialTimer) { clearInterval(run.partialTimer) run.partialTimer = null } } /** 진행 중인 부분 전사가 끝나기를 최대 PARTIAL_DRAIN_TIMEOUT_MS까지 기다린다. */ private async _drainPartial(run: SessionRun): Promise { const inFlight = run.partialInFlight if (!inFlight) return let timer: NodeJS.Timeout | null = null await Promise.race([ inFlight, new Promise((resolve) => { timer = setTimeout(resolve, PARTIAL_DRAIN_TIMEOUT_MS) }), ]) if (timer) clearTimeout(timer) } private async _runPartial(run: SessionRun): Promise { if (!run.audioStarted || run.partialInFlight) return if (!this._isCurrent(run)) return if (!run.sttReady) return if (run.audioBufferBytes < PARTIAL_MIN_AUDIO_MS * BYTES_PER_MS) return const window = tailAudio(run.audioBuffer, PARTIAL_MAX_WINDOW_MS * BYTES_PER_MS) const language = configGet('sttLanguage') const task = (async (): Promise => { try { const text = await getSTTManager().transcribePartial(window, { language: language === 'auto' ? undefined : language, vadFilter: false, }) // 녹음이 끝났거나 세션이 바뀌었으면 미리보기를 버린다. if (!run.audioStarted || !this._isCurrent(run)) return if (!text) return this.emit('partial-transcript', { text, sessionId: run.id }) } catch (err) { logger.debug(`부분 전사 미리보기 무시: ${describe(err)}`) } finally { run.partialInFlight = null } })() run.partialInFlight = task } // ── 이중 조건 플러시 ─────────────────────────────────── private _tryFlushAll(run: SessionRun): void { // 녹음 진행 중에는 flush 하지 않음 (stopSession에서 오디오를 놓은 뒤 처리) if (run.audioStarted) return // 사용자가 정지하기 전에는 전사하지 않는다 (오디오 시작이 늦을 때 조기 전사 방지) if (!run.stopRequested) return if (!run.sttReady) return if (run.transcribing) return if (run.audioBuffer.length === 0) { logger.warn(`_tryFlushAll skipped: audioBuffer is empty`) return } if (!this._isCurrent(run)) return this._clearSttWaitTimer(run) void this._transcribe(run).catch((err) => { logger.error('Unhandled error in _transcribe flush:', err) }) } // ── 전사 ─────────────────────────────────────────────── private async _transcribe(run: SessionRun): Promise { if (!this._isCurrent(run)) return if (run.audioBuffer.length === 0 || run.transcribing) return run.transcribing = true this._setRecognitionState(RecognitionState.RECOGNIZING) const merged = Buffer.concat(run.audioBuffer) run.lastAudio = merged // WAV 저장용 (run 소유) run.audioBuffer = [] run.audioBufferBytes = 0 // Bug 13: 너무 짧은 오디오는 STT 호출 전에 에러 피드백. // 16kHz 16bit mono 기준 0.5초 = 16000 bytes. const minBytes = 16000 * 2 * 0.5 if (merged.length < minBytes) { this._handleError( run, new D3ROError( ErrorCode.STTAudioTooShort, 'No speech detected. Please speak and try again.' ) ) return } try { const stt = getSTTManager() const language = configGet('sttLanguage') // Dictionary → STT initialPrompt 주입 (Speakly 패턴) let initialPrompt: string | undefined try { const { getDictionaryService } = await import('./DictionaryService') initialPrompt = getDictionaryService().getPromptHints() || undefined } catch { // DictionaryService 미초기화 시 무시 } // 사이드카는 요청을 직렬 처리하므로, 진행 중인 미리보기 요청이 최종 전사를 // 지연시키지 않도록 먼저 배수한다(최대 PARTIAL_DRAIN_TIMEOUT_MS). await this._drainPartial(run) if (!this._isCurrent(run)) return const result: TranscriptionResult = await stt.transcribe(merged, { language: language === 'auto' ? undefined : language, initialPrompt, }) // 취소됐거나 다음 세션이 시작됐으면 결과를 버린다 (다른 세션에 삽입 금지) if (!this._isCurrent(run)) return // Bug 13: VAD가 전체 오디오를 무음 판정했거나 결과가 빈 텍스트일 때 // 조용히 빈 문자열로 complete 하지 않고 사용자에게 피드백. if (!result.text || result.text.trim().length === 0) { this._handleError( run, new D3ROError( ErrorCode.STTNoAudioData, 'No speech detected. Check your microphone and try again.' ) ) return } if (this._session) { this._session.transcription = result.text } this.emit('transcription-update', { text: result.text, isFinal: true }) // Phase 10.5: 음성 단축키 — 키워드 매칭으로 LLM 명령어 자동 선택 let effectiveText = result.text let overrideInstructionId: string | null = null try { const { getVoiceCommandService } = await import('./VoiceCommandService') const vcSvc = getVoiceCommandService() if (vcSvc.isEnabled()) { const match = vcSvc.match(result.text) if (match.matched && match.instructionId) { effectiveText = match.cleanedText overrideInstructionId = match.instructionId logger.info(`Voice command matched: keyword="${match.matchedKeyword}", instruction=${match.instructionId}`) } } } catch { // VoiceCommandService 미초기화 시 무시 } if (!this._isCurrent(run)) return // 결정적 구어 군더더기·추임새·말바꾸기·중복·동음이의어 1차 정리 (LLM 유무와 무관하게 0ms 즉시 적용) effectiveText = cleanDictatedText(effectiveText) const route = this._resolveLlmRoute(overrideInstructionId) if (route.kind === 'insert-raw') { if (route.reason === 'llm-unavailable') { this.emit('error', { error: new D3ROError( ErrorCode.LLMServerUnreachable, 'Ollama unavailable — inserting raw transcription without LLM post-processing', ), session: this._session ? { ...this._session } : null, severity: 'warning', }) } await this._completeSession(run, effectiveText) } else { await this._processWithLLM(run, effectiveText, route) } } catch (error) { if (!this._isCurrent(run)) return this._handleError( run, new D3ROError( ErrorCode.STTTranscriptionFailed, `Transcription failed: ${describe(error)}` ) ) } } // ── LLM 후처리 ───────────────────────────────────────── private _emitPremiumFallback(reason: string): void { this.emit('premium-llm-fallback', { reason }) } /** 백엔드 선택·Premium→Local 폴백은 LlmGateway 가 소유한다. */ private _runProcessorWithFallback( text: string, action: LLMAction, targetLanguage?: string, customPrompt?: string, ): Promise { return getLlmGateway().processText(text, action, targetLanguage, customPrompt, { onFallback: (reason) => this._emitPremiumFallback(reason), }) } /** 현재 설정으로 LLM 후처리 경로를 결정한다 (정책은 @d3ro/core/voice-llm-route 가 소유) */ private _resolveLlmRoute(overrideInstructionId: string | null): VoiceLlmRoute { const backend = configGet('llmBackend') return resolveVoiceLlmRoute({ defaultAction: configGet('defaultLLMAction'), overrideInstructionId, activeChainId: configGet('activeChainId') ?? null, activeInstructionId: configGet('activeInstructionId') ?? null, localLlmAvailable: backend === 'local' ? getLocalLLMService().isAvailable() : true, backend, }) } private async _processWithLLM( run: SessionRun, transcribedText: string, route: LlmProcessingRoute, ): Promise { if (!this._isCurrent(run)) return try { // Phase 10.2: 스크린 컨텍스트를 LLM 프롬프트에 주입 (선택 텍스트는 정지 이후 캡처). // 정지 시점에 LLM 경로가 확실하지 않아 캡처를 미뤘다면 여기서 시작한다(멱등). this._startSelectionCapture(run) await this._applyScreenContext(run) if (!this._isCurrent(run)) return const userText = (await this._buildContextPrefix()) + transcribedText // Phase 10.4: 체인 모드 처리 if (route.kind === 'chain') { try { const { getChainService } = await import('./ChainService') const chainResult = await getChainService().execute(route.chainId, userText) if (!this._isCurrent(run)) return if (this._session) this._session.processedText = chainResult.finalText await this._completeSession(run, chainResult.finalText) } catch (error) { if (!this._isCurrent(run)) return logger.warn(`Chain execution failed: ${describe(error)}`) this._handleError( run, error instanceof D3ROError ? error : new D3ROError(ErrorCode.ChainExecutionFailed, `Chain execution failed: ${describe(error)}`), ) } return } const processedText = route.kind === 'instruction' ? await this._processWithInstruction(userText, route.instructionId) : await this._processWithAction(userText, route.action) if (!this._isCurrent(run)) return if (this._session) { this._session.processedText = processedText } await this._completeSession(run, processedText) } catch (error) { if (!this._isCurrent(run)) return this._handleError( run, error instanceof D3ROError ? error : new D3ROError( ErrorCode.LLMProcessingFailed, `LLM processing failed: ${describe(error)}`, ), ) } } /** 지시문(음성 단축키 또는 활성 지시문)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */ private async _processWithInstruction(userText: string, instructionId: string | null): Promise { let invocationText = userText let instructionPrompt: string | undefined if (instructionId) { const { getCustomInstructionService } = await import('./CustomInstructionService') const instruction = getCustomInstructionService().getById(instructionId) if (instruction) { const invocation = buildInstructionInvocation(instruction.prompt, userText, resolveTargetLanguage()) invocationText = invocation.text instructionPrompt = invocation.systemPrompt logger.info(`Using custom instruction: "${instruction.name}"`) } else { logger.warn(`Custom instruction not found: ${instructionId} — processing without an instruction`) } } return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt) } /** 일반 액션(refine/translate/…)으로 처리한다 */ private async _processWithAction( userText: string, action: Extract['action'], ): Promise { const targetLanguage = resolveTargetLanguage() logger.info( action === 'translate' ? `Processing with LLM (action: ${action}, targetLanguage: ${targetLanguage})` : `Processing with LLM (action: ${action})`, ) return this._runProcessorWithFallback( userText, action, action === 'translate' ? targetLanguage : undefined, ) } // ── 세션 완료/취소 ───────────────────────────────────── /** * 세션 완료 — 녹음을 먼저 저장하고(실제 경로를 이벤트에 싣는다) 완료를 알린 뒤, 삽입은 따로 돈다. * * 예전엔 완료 이벤트(히스토리 생성 + history_audio 동기화 예약)가 먼저 나가고 WAV 는 텍스트 삽입이 * 끝난 뒤에 써졌다 — 그사이 flush 가 돌면 "파일 없음"을 성공으로 처리해 녹음이 영영 올라가지 않았다. */ private async _completeSession(run: SessionRun, finalText: string): Promise { if (!this._isCurrent(run) || !this._session) return const audioPath = await this._recordings.save(this._session.id, run.lastAudio) // 저장하는 사이 취소·새 세션이 시작됐으면 완료를 알리지 않는다. if (!this._isCurrent(run) || !this._session) return const session = { ...this._session } const selectionCapture = run.selectionCapture logger.info(`Session completed: "${finalText.substring(0, 50)}${finalText.length > 50 ? '...' : ''}"`) // Speakly 패턴: 먼저 IDLE 복귀 (다음 핫키 즉시 사용 가능). 표시 계층이 완료 이벤트로 팁을 숨긴다. this._setRecognitionState(RecognitionState.COMPLETED) this._setAudioState(AudioState.STOPPED) const willInsert = Boolean(configGet('autoInsert')) && finalText.length > 0 this.emit('session-completed', { session, finalText, audioPath, willInsert }) this._endRun(run) // 텍스트 삽입은 세션과 무관하게 비동기 실행 (세션 블로킹 방지) void this._insertCompletedText(session.id, finalText, selectionCapture) } private async _insertCompletedText( sessionId: string, finalText: string, selectionCapture: Promise | null, ): Promise { if (!configGet('autoInsert') || finalText.length === 0) return try { // 선택 텍스트 캡처가 클립보드를 쓰는 중이면 끝날 때까지 기다린다 (클립보드 경합 방지) if (selectionCapture) await selectionCapture const insertMethod = configGet('insertMethod') await getTextInsertService().insertText(finalText, insertMethod) this.emit('text-inserted', { sessionId }) } catch (error) { logger.warn(`Text insert failed: ${describe(error)}`) // 삽입 실패 시 표시 계층이 ResultPopup에 텍스트를 보여 준다 this.emit('insert-failed', { text: finalText, sessionId }) } } private _cancelSession(reason: 'user' | 'timeout' | 'too-short'): void { const run = this._run if (!run || !this._session) return this._setRecognitionState(RecognitionState.CANCELLED) this._setAudioState(AudioState.STOPPED) const session = { ...this._session } logger.info(`Session cancelled: ${reason}`) // 표시 계층이 취소 이벤트로 RecordingTip 을 즉시 숨긴다 this.emit('session-cancelled', { session, reason }) this._endRun(run) } private _clearSttWaitTimer(run: SessionRun): void { if (run.sttWaitTimer) { clearTimeout(run.sttWaitTimer) run.sttWaitTimer = null } } /** * run 을 끝낸다: 늦게 도착할 비동기 결과를 무효화(abort)하고, 타이머를 정리하고, * 오디오를 멱등하게 놓은 뒤 IDLE 로 돌아간다. */ private _endRun(run: SessionRun): void { run.controller.abort() this._clearSttWaitTimer(run) this._stopPartialLoop(run) run.partialInFlight = null void this._releaseAudio(run) if (this._run === run) this._resetToIdle() } private _resetToIdle(): void { this._session = null this._run = null // 즉시 IDLE로 전이 (딜레이는 race condition 유발) this._setRecognitionState(RecognitionState.IDLE) this._setAudioState(AudioState.IDLE) } // ── 에러 처리 ────────────────────────────────────────── private _handleError(run: SessionRun, error: D3ROError): void { // 이미 끝난(취소·교체된) 세션의 늦은 실패는 새 세션을 건드리지 않는다 if (!this._isCurrent(run)) { logger.debug(`Ignoring stale session error [${error.code}]: ${error.message}`) return } logger.error(`VoiceMode error [${error.code}]: ${error.message}`) this._setRecognitionState(RecognitionState.ERROR) this._setAudioState(AudioState.STOPPED) // Speakly 패턴: 표시 계층이 'error' 로 RecordingTip 에 에러를 띄우고 3초 후 숨긴다 this.emit('error', { error, session: this._session ? { ...this._session } : null }) this._endRun(run) } // ── Action Queue (이벤트 직렬화) ─────────────────────── private _enqueueAction(action: VoiceAction): void { this._actionQueue.push(action) this._processQueue() } private async _processQueue(): Promise { if (this._isProcessingQueue) return this._isProcessingQueue = true try { while (this._actionQueue.length > 0) { const action = this._actionQueue.shift()! await this._processAction(action) } } finally { this._isProcessingQueue = false } } private async _processAction(action: VoiceAction): Promise { try { switch (action.type) { case 'press': case 'release': await this._handleGesture(action) break case 'escape': this.cancelSession() break } } catch (error) { logger.error(`Action processing error: ${describe(error)}`) } } /** * 키 제스처를 세션 의도로 바꿔(voice-intent) 실행한다. * 정지는 오디오 해제까지만 기다린다 — 전사·LLM 동안 큐가 풀려 있어야 처리 중에 들어온 토글이 * 'processing' 단계에서 무시되고, 세션이 끝난 뒤 새 녹음으로 재생되지 않는다. */ private async _handleGesture(action: VoiceAction): Promise { if (action.type === 'escape') return const phase = deriveVoiceIntentPhase(this.isActive, this._run?.stopRequested ?? false) const intent = resolveVoiceIntent( { type: action.type, mode: action.mode, holdMode: action.holdMode }, phase, ) switch (intent.kind) { case 'start': await this.startSession(intent.mode) break case 'stop': // Speakly 패턴: 딜레이 없이 즉시 stop (딜레이가 race condition 유발) await this._requestStop() break case 'ignore': break } } // ── 자막 모드 토글 (Phase 10.1) ───────────────────────── private async _toggleCaption(): Promise { try { const { getCaptionService } = await import('./CaptionService') const caption = getCaptionService() const state = caption.getState() if (state === 'active' || state === 'starting') { // 자막 활성 중 → 정지. 단, 회의 모드가 소유한 자막 세션은 핫키로 끌 수 없다 // (예전엔 회의의 마이크 캡처·전사가 조용히 멈추고 UI 는 계속 '녹음 중'이었다). const stopped = await caption.stop('user') if (stopped === false) { logger.warn('Caption hotkey ignored: caption session is owned by meeting mode') return } logger.info('Caption stopped via hotkey') } else { // dictation 세션이 활성이면 자막 시작 불가 (상호 배제) if (this._session && !this._isInTerminalState()) { logger.warn('Cannot start caption: dictation session active') return } // 회의 모드 녹음 중이면 자막 시작 불가 (상호 배제) const { getMeetingModeService } = await import('./MeetingModeService') if (getMeetingModeService().getState() === 'recording') { logger.warn('Cannot start caption: meeting mode recording active') return } await caption.start() logger.info('Caption started via hotkey') } } catch (error) { logger.error(`Caption toggle failed: ${describe(error)}`) } } // ── 종료 ─────────────────────────────────────────────── dispose(): void { this._disposed = true this._actionQueue = [] // 진행 중 세션 취소 (오디오 해제 포함 — 멱등이므로 따로 다시 멈추지 않는다) if (this._session && !this._isInTerminalState()) { this._cancelSession('user') } // 키바인딩 리스너 해제 if (this._keyBindingHandler) { getKeyBindingService().off('triggered', this._keyBindingHandler) this._keyBindingHandler = null } this._setRecognitionState(RecognitionState.DESTROYED) this.removeAllListeners() logger.info('VoiceModeService disposed') } // ── EventEmitter 타입 오버라이드 ─────────────────────── override on( event: K, listener: VoiceModeEvents[K] ): this { return super.on(event, listener) } override off( event: K, listener: VoiceModeEvents[K] ): this { return super.off(event, listener) } override emit( event: K, ...args: Parameters ): boolean { return super.emit(event, ...args) } } // ── 싱글톤 ───────────────────────────────────────────── let instance: VoiceModeService | null = null export function getVoiceModeService(): VoiceModeService { if (!instance) { instance = new VoiceModeService() } return instance } /** 테스트 전용: 가짜 녹음 저장소를 주입한 싱글톤을 만든다. */ export function createVoiceModeServiceForTests(recordings: RecordingStore): VoiceModeService { resetVoiceModeServiceForTests() instance = new VoiceModeService(recordings) return instance } export function resetVoiceModeServiceForTests(): void { if (instance) { instance.removeAllListeners() } instance = null }