fix(voice): stop mic-test ref stealing, unblock action queue, keep tail audio, and move context/LLM routing behind ports and pure policies

This commit is contained in:
Yun Chan 2026-09-28 02:16:16 +09:00
parent 2cd462333f
commit 2f94d24c99
13 changed files with 1672 additions and 353 deletions

View file

@ -35,6 +35,13 @@ 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')
@ -126,6 +133,8 @@ class SessionRun {
/** 스크린 컨텍스트: 선택 텍스트 캡처 여부와 진행 중 작업 */
captureSelection = false
selectionCapture: Promise<string | null> | null = null
/** 스크린 컨텍스트: 녹음 시작 시점 활성 창 조회 (기다리지 않고 LLM 단계에서 합친다) */
windowContext: Promise<ScreenContext | null> | null = null
dataHandler: ((payload: { buffer: Buffer }) => void) | null = null
levelHandler: ((payload: { level: number }) => void) | null = null
@ -169,6 +178,19 @@ function describe(err: unknown): string {
return err instanceof Error ? err.message : String(err)
}
/** LLM 을 실제로 부르는 경로 */
type LlmProcessingRoute = Exclude<VoiceLlmRoute, { kind: 'insert-raw' }>
/**
* 정지 요청의 결과. 오디오 해제까지는 요청 안에서 끝나고, 전사·LLM 후처리는 `finished` 로 따로 돈다.
* (async 함수가 Promise 를 반환하면 펼쳐지므로 객체로 감싼다)
*/
interface StopOutcome {
finished: Promise<void>
}
const NOTHING_PENDING: StopOutcome = { finished: Promise.resolve() }
// ============================================================
// VoiceModeService
// ============================================================
@ -229,11 +251,11 @@ class VoiceModeService extends EventEmitter {
return
}
const holdMode = this._resolveHoldMode(payload.actionId, payload.holdMode)
const holdMode = resolveGestureHoldMode(payload.actionId, payload.holdMode)
const action: VoiceAction = {
type: payload.type === 'pressed' ? 'press' : 'release',
timestamp: payload.timestamp,
mode: this._resolveMode(payload.actionId, payload.isDoublePress),
mode: resolveGestureMode(payload.actionId, payload.isDoublePress),
actionId: payload.actionId,
holdMode
}
@ -300,16 +322,23 @@ class VoiceModeService extends EventEmitter {
// 선택 텍스트(Ctrl+C)는 여기서 보내지 않는다: 이 시점엔 사용자가 아직 핫키(기본 Right Alt)를
// 누르고 있어 대상 앱에 Ctrl+Alt+C 가 들어가고(복사 안 됨, AltGr 배열에선 문자 입력),
// 클립보드만 비워진다. 선택 텍스트는 녹음 종료(키를 뗀 뒤)에 캡처한다.
let screenContext: ScreenContext | null = null
let captureSelection = false
// 활성 창 조회는 기다리지 않는다 — 예전엔 조회(PowerShell, 0.7~3초)가 세션·마이크 시작 앞을
// 막아 첫 말이 잘리고 짧은 hold-to-talk 가 'too-short' 로 취소됐다. 결과는 LLM 단계에서 합친다.
let windowContext: Promise<ScreenContext | null> | null = null
try {
const { getScreenContextService } = await import('./ScreenContextService')
const ctx = getScreenContextService()
if (ctx.isEnabled()) {
captureSelection = true
const result = await ctx.captureContext(false)
screenContext = result.context
logger.info(`Screen context captured: ${screenContext.appName ?? 'unknown'}`)
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 {
// 컨텍스트 캡처 실패 시 무시 — 핵심 기능 아님
@ -320,7 +349,8 @@ class VoiceModeService extends EventEmitter {
// 세션 생성
const run = new SessionRun(randomUUID())
run.captureSelection = captureSelection
run.captureSelection = windowContext !== null
run.windowContext = windowContext
this._run = run
this._session = {
id: run.id,
@ -332,7 +362,7 @@ class VoiceModeService extends EventEmitter {
transcription: '',
processedText: null,
accidentalPress: false,
screenContext,
screenContext: null,
}
this._setRecognitionState(RecognitionState.PREPARING)
@ -360,16 +390,30 @@ class VoiceModeService extends EventEmitter {
await this._startAudio(run)
}
/**
* 세션을 정지하고 전사·후처리가 끝날 때까지 기다린다 (IPC 등 공개 API).
* 키 입력 경로는 _requestStop 만 기다려 액션 큐를 막지 않는다.
*/
async stopSession(): Promise<void> {
const { finished } = await this._requestStop()
await finished
}
/**
* 정지 요청과 오디오 해제까지만 수행한다. 전사·LLM 은 run 에 묶어 `finished` 로 따로 돈다.
* 예전엔 정지가 STT·LLM 전체(수 초)를 await 해 액션 큐를 막았고, 그사이 들어온 입력이
* 세션이 끝난 뒤 다른 의미로 재생됐다(더블탭 정지의 두 번째 탭이 새 핸즈프리 녹음을 시작).
*/
private async _requestStop(): Promise<StopOutcome> {
const run = this._run
const session = this._session
if (!run || !session || !this._isCurrent(run) || this._isInTerminalState()) return
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
return NOTHING_PENDING
}
run.stopRequested = true
@ -380,23 +424,29 @@ class VoiceModeService extends EventEmitter {
session.accidentalPress = true
logger.info(`Accidental press detected (${duration}ms < ${TIMING.MIN_AUDIO_DURATION}ms)`)
this._cancelSession('too-short')
return
return NOTHING_PENDING
}
// 오디오 캡처 중지
this._setAudioState(AudioState.STOPPED)
await this._releaseAudio(run)
if (!this._isCurrent(run)) return
if (!this._isCurrent(run)) return NOTHING_PENDING
// Speakly 패턴: 녹음 종료 후 thinking 상태로 전환
this.emit('phase', { phase: 'thinking', sessionId: run.id })
// 핫키를 뗀 뒤라 Ctrl+C 가 안전하다 — 전사와 병렬로 선택 텍스트를 캡처한다
this._startSelectionCapture(run)
// 핫키를 뗀 뒤라 복사 단축키가 안전하다 — LLM 이 쓸 것이 확실하면 전사와 병렬로 선택 텍스트를
// 캡처한다. 원문 삽입 경로(none·LLM 불가)에선 보내지 않는다: 쓰지도 않을 Ctrl+C 가 터미널에선
// 프로세스를 중단시킨다. 음성 단축키로 LLM 경로가 될 수도 있으면 LLM 단계에서 늦게 캡처한다.
if (routeUsesLlm(this._resolveLlmRoute(null))) this._startSelectionCapture(run)
// 버퍼가 있으면 STT에 전달
if (run.audioBuffer.length > 0 && run.sttReady) {
await this._transcribe(run)
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')
@ -415,6 +465,7 @@ class VoiceModeService extends EventEmitter {
logger.warn('No audio buffer, cancelling session')
this._cancelSession('too-short')
}
return NOTHING_PENDING
}
cancelSession(): void {
@ -601,17 +652,28 @@ class VoiceModeService extends EventEmitter {
*/
private async _releaseAudio(run: SessionRun): Promise<void> {
run.audioReleaseRequested = true
this._detachAudioHandlers(run)
run.audioStarted = false
this._stopPartialLoop(run)
if (!run.audioAcquired) return
run.audioAcquired = false
try {
await getAudioCaptureService().stop()
} catch (error) {
logger.warn(`Audio stop error: ${describe(error)}`)
// 현재 세션의 정상 정지면 캡처가 꼬리 오디오(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
}
// ── 스크린 컨텍스트(선택 텍스트) ─────────────────────────
@ -629,18 +691,37 @@ class VoiceModeService extends EventEmitter {
})()
}
/** 선택 텍스트 캡처가 끝나기를 기다렸다가 세션 컨텍스트에 합친다. */
private async _applySelectionCapture(run: SessionRun): Promise<void> {
if (!run.selectionCapture) return
const selectedText = await run.selectionCapture
if (!selectedText || !this._isCurrent(run) || !this._session) return
const base: ScreenContext = this._session.screenContext ?? {
/**
* 활성 창 조회(녹음 시작 시점)와 선택 텍스트 캡처(정지 시점)가 끝나기를 기다렸다가
* 세션 컨텍스트로 합친다.
*/
private async _applyScreenContext(run: SessionRun): Promise<void> {
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 = { ...base, selectedText }
this._session.screenContext = selectedText ? { ...base, selectedText } : base
}
/** 세션 컨텍스트를 LLM 입력 접두사로 만든다 (없으면 빈 문자열) */
private async _buildContextPrefix(): Promise<string> {
const screenContext = this._session?.screenContext
if (!screenContext) return ''
try {
const { getScreenContextService } = await import('./ScreenContextService')
return getScreenContextService().buildContextPrompt(screenContext)
} catch {
return ''
}
}
// ── 실시간 부분 전사(미리보기) ─────────────────────────────
@ -806,7 +887,6 @@ class VoiceModeService extends EventEmitter {
// Phase 10.5: 음성 단축키 — 키워드 매칭으로 LLM 명령어 자동 선택
let effectiveText = result.text
let overrideAction: string | null = null
let overrideInstructionId: string | null = null
try {
const { getVoiceCommandService } = await import('./VoiceCommandService')
@ -815,7 +895,6 @@ class VoiceModeService extends EventEmitter {
const match = vcSvc.match(result.text)
if (match.matched && match.instructionId) {
effectiveText = match.cleanedText
overrideAction = 'custom'
overrideInstructionId = match.instructionId
logger.info(`Voice command matched: keyword="${match.matchedKeyword}", instruction=${match.instructionId}`)
}
@ -825,12 +904,9 @@ class VoiceModeService extends EventEmitter {
}
if (!this._isCurrent(run)) return
const llmAction = overrideAction ?? configGet('defaultLLMAction')
const backend = configGet('llmBackend')
const ollamaUnavailable = backend === 'local' && !getLocalLLMService().isAvailable()
const skipLLM = llmAction === 'none' || ollamaUnavailable
if (skipLLM) {
if (llmAction !== 'none' && ollamaUnavailable) {
const route = this._resolveLlmRoute(overrideInstructionId)
if (route.kind === 'insert-raw') {
if (route.reason === 'llm-unavailable') {
this.emit('error', {
error: new D3ROError(
ErrorCode.LLMServerUnreachable,
@ -842,7 +918,7 @@ class VoiceModeService extends EventEmitter {
}
void this._completeSession(run, effectiveText)
} else {
await this._processWithLLM(run, effectiveText, overrideInstructionId)
await this._processWithLLM(run, effectiveText, route)
}
} catch (error) {
if (!this._isCurrent(run)) return
@ -874,50 +950,42 @@ class VoiceModeService extends EventEmitter {
})
}
/** 현재 설정으로 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,
overrideInstructionId?: string | null,
route: LlmProcessingRoute,
): Promise<void> {
if (!this._isCurrent(run)) return
try {
const configuredAction = configGet('defaultLLMAction')
// 음성 단축키가 특정 명령을 지목해 들어왔다면 기본 액션이 'none'이어도 처리한다.
// 명시적 요청을 기본 설정이 무효화하면 안 된다.
if (configuredAction === 'none' && !overrideInstructionId) {
void this._completeSession(run, transcribedText)
return
}
// 여기서 'none'이 남아 있다면 overrideInstructionId가 반드시 있다 → custom 경로.
const action: LLMAction = configuredAction === 'none' ? 'custom' : configuredAction
// Phase 10.2: 스크린 컨텍스트를 LLM 프롬프트에 주입 (선택 텍스트는 정지 시점 캡처)
await this._applySelectionCapture(run)
// Phase 10.2: 스크린 컨텍스트를 LLM 프롬프트에 주입 (선택 텍스트는 정지 이후 캡처).
// 정지 시점에 LLM 경로가 확실하지 않아 캡처를 미뤘다면 여기서 시작한다(멱등).
this._startSelectionCapture(run)
await this._applyScreenContext(run)
if (!this._isCurrent(run)) return
let contextPrefix = ''
if (this._session?.screenContext) {
try {
const { getScreenContextService } = await import('./ScreenContextService')
contextPrefix = getScreenContextService().buildContextPrompt(this._session.screenContext)
} catch {
// 무시
}
}
const userText = (await this._buildContextPrefix()) + transcribedText
// Phase 10.4: 체인 모드 처리
if (action === 'chain') {
if (route.kind === 'chain') {
try {
const { getChainService } = await import('./ChainService')
const activeChainId = configGet('activeChainId')
if (activeChainId) {
const chainResult = await getChainService().execute(activeChainId, contextPrefix + transcribedText)
if (!this._isCurrent(run)) return
if (this._session) this._session.processedText = chainResult.finalText
void this._completeSession(run, chainResult.finalText)
return
}
const chainResult = await getChainService().execute(route.chainId, userText)
if (!this._isCurrent(run)) return
if (this._session) this._session.processedText = chainResult.finalText
void this._completeSession(run, chainResult.finalText)
} catch (error) {
if (!this._isCurrent(run)) return
logger.warn(`Chain execution failed: ${describe(error)}`)
@ -927,60 +995,14 @@ class VoiceModeService extends EventEmitter {
? error
: new D3ROError(ErrorCode.ChainExecutionFailed, `Chain execution failed: ${describe(error)}`),
)
return
}
return
}
let processedText: string
// 음성 단축키 오버라이드 또는 활성 명령어
const effectiveInstructionId = overrideInstructionId
?? configGet('activeInstructionId')
const targetLanguage = resolveTargetLanguage()
if (action === 'custom' || overrideInstructionId) {
const userText = contextPrefix + transcribedText
let invocationText = userText
let instructionPrompt: string | undefined
if (effectiveInstructionId) {
const { getCustomInstructionService } = await import('./CustomInstructionService')
const instruction = getCustomInstructionService().getById(effectiveInstructionId)
if (instruction) {
const invocation = buildInstructionInvocation(
instruction.prompt,
userText,
targetLanguage,
)
invocationText = invocation.text
instructionPrompt = invocation.systemPrompt
logger.info(`Using custom instruction: "${instruction.name}"`)
} else {
logger.warn(
`Custom instruction not found: ${effectiveInstructionId} — processing without an instruction`,
)
}
}
processedText = await this._runProcessorWithFallback(
invocationText,
'custom',
undefined,
instructionPrompt,
)
} else {
logger.info(
action === 'translate'
? `Processing with LLM (action: ${action}, targetLanguage: ${targetLanguage})`
: `Processing with LLM (action: ${action})`,
)
processedText = await this._runProcessorWithFallback(
contextPrefix + transcribedText,
action,
action === 'translate' ? targetLanguage : undefined,
)
}
const processedText =
route.kind === 'instruction'
? await this._processWithInstruction(userText, route.instructionId)
: await this._processWithAction(userText, route.action)
if (!this._isCurrent(run)) return
@ -1003,6 +1025,45 @@ class VoiceModeService extends EventEmitter {
}
}
/** 지시문(음성 단축키 또는 활성 지시문)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
private async _processWithInstruction(userText: string, instructionId: string | null): Promise<string> {
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<LlmProcessingRoute, { kind: 'action' }>['action'],
): Promise<string> {
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,
)
}
// ── 세션 완료/취소 ─────────────────────────────────────
private async _completeSession(run: SessionRun, finalText: string): Promise<void> {
@ -1161,10 +1222,8 @@ class VoiceModeService extends EventEmitter {
try {
switch (action.type) {
case 'press':
await this._handlePress(action)
break
case 'release':
await this._handleRelease(action)
await this._handleGesture(action)
break
case 'escape':
this.cancelSession()
@ -1175,48 +1234,29 @@ class VoiceModeService extends EventEmitter {
}
}
private async _handlePress(action: VoiceAction): Promise<void> {
if (action.mode === 'dictation') {
// Dictation: hold-to-talk — press로 시작
if (!this.isActive) {
await this.startSession('dictation')
}
} else if (action.mode === 'hands-free') {
// HandsFree: toggle
if (this.isActive) {
await this.stopSession()
} else {
await this.startSession('hands-free')
}
}
}
private async _handleRelease(action: VoiceAction): Promise<void> {
if (action.holdMode && action.mode === 'dictation' && this.isActive) {
// Dictation: hold-to-talk — release로 즉시 종료
// Speakly 패턴: 딜레이 없이 즉시 stop (딜레이가 race condition 유발)
await this.stopSession()
}
// HandsFree(토글): release 무시
}
// ── 유틸리티 ───────────────────────────────────────────
private _resolveMode(actionId: KeyBindingActionId, isDoublePress: boolean): VoiceMode {
if (actionId === 'hands-free' || isDoublePress) {
return 'hands-free'
}
return 'dictation'
}
/**
* 'command' 액션에는 아직 전용 핸들러가 없다.
* 현행 동작대로 dictation 파이프라인으로 fallback 하며, 그 경로는 hold-to-talk 이므로
* KEYBINDING_ACTIONS 의 holdMode(false)가 아니라 dictation 과 같은 값을 쓴다.
* 키 제스처를 세션 의도로 바꿔(voice-intent) 실행한다.
* 정지는 오디오 해제까지만 기다린다 — 전사·LLM 동안 큐가 풀려 있어야 처리 중에 들어온 토글이
* 'processing' 단계에서 무시되고, 세션이 끝난 뒤 새 녹음으로 재생되지 않는다.
*/
private _resolveHoldMode(actionId: KeyBindingActionId, specHoldMode: boolean): boolean {
if (actionId === 'command') return true
return specHoldMode
private async _handleGesture(action: VoiceAction): Promise<void> {
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) ─────────────────────────