d3ro-voice/apps/desktop/tests/main/services/VoiceModeService.test.ts
Yun Chan 4ad1ae6ed4 feat(keybinding): several shortcuts per action, mouse buttons, searchable picker
Shortcuts were defined in four places that drifted apart: per-action IPC channel
pairs, a hand-written VK table in the service, a second one in the renderer, and
three copies of the keycap styling. Adding an action meant editing all of them,
so two shortcuts stayed hardcoded in bootstrap and one had no settings entry at
all.

packages/core/src/keybinding.ts is now the single source for the binding type,
the selectable key catalog, the action catalog, normalization, validation,
conflict detection, display labels, search and deserialization. Main, preload
and renderer all read from it; nothing redefines keys or rules locally.

- Each action holds a list of bindings instead of one. AppConfig's four
  *Shortcut fields collapse into a single keyBindings map, migrated on launch.
- Mouse buttons can be bound. Left click is refused, right/middle need a
  modifier, side buttons are free. uiohook cannot swallow events, so the
  original click still fires and the UI says so.
- Keys can be picked from a grouped dropdown with a search box, not only by
  recording a keypress.
- HOTKEY's 14 channels become KEYBINDING's 9, taking the action as a parameter,
  so actions no longer multiply channels. The history and command popups moved
  out of bootstrap into ordinary actions.
- displayLabel is gone; labels derive from the binding and follow the app
  language and platform.

Fixes found on the way:
- Double-press hands-free was unreachable: lookup returned only the first
  matching action, and dictation shares its default binding.
- Reserved-combination checks compared joined key names, so a different modifier
  order let Ctrl+C through.
- Disabling shortcuts released every global registration in the process,
  including the popup ones, and never restored them.
- Enabling shortcuts after starting disabled left nothing registered.
- The dashboard stored the caption event payload instead of the state in it.
2026-09-21 13:41:47 +09:00

267 lines
8.1 KiB
TypeScript

// tests/main/services/VoiceModeService.test.ts
// 상태 머신 전이 + 이중 조건 플러시 + accidentalPress 테스트
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { EventEmitter } from 'events'
import { RecognitionState, AudioState } from '@d3ro/core/types'
import { TIMING } from '@d3ro/core/constants'
// 모든 하위 서비스 모킹
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn()
})
}))
const mockSTT = {
initialize: vi.fn(() => Promise.resolve()),
transcribe: vi.fn(() =>
Promise.resolve({ text: '테스트 전사', segments: [], language: 'ko', duration: 2, processingTime: 500 })
),
getStatus: vi.fn(() => ({ state: 'ready', modelId: 'base', uptime: 0 })),
// 프리플라이트 검증(모델 설치 여부)용 — 기본은 설치된 상태로 목킹
getModels: vi.fn(() => [
{ id: 'base', name: 'Base', sizeBytes: 0, downloaded: true, languages: [], accuracy: 2, speed: 4 },
]),
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/LocalSTTService', () => ({
getLocalSTTService: () => mockSTT,
resetLocalSTTServiceForTests: () => undefined,
}))
const audioBus = new EventEmitter()
const mockAudio = {
start: vi.fn(() => Promise.resolve()),
stop: vi.fn(() => Promise.resolve()),
on: vi.fn((ev: string, fn: (...args: unknown[]) => void) => {
audioBus.on(ev, fn)
}),
off: vi.fn((ev: string, fn: (...args: unknown[]) => void) => {
audioBus.off(ev, fn)
}),
}
vi.mock('../../../src/main/services/AudioCaptureService', () => ({
getAudioCaptureService: () => mockAudio
}))
const mockKeyBinding = {
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/KeyBindingService', () => ({
getKeyBindingService: () => mockKeyBinding
}))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: string) => {
const defaults: Record<string, unknown> = {
sttModelId: 'base',
defaultLLMAction: 'refine',
ollamaServerUrl: 'http://localhost:11434',
llmModelId: 'gemma4:e4b'
}
return defaults[key]
})
}))
const mockTextInsert = {
insertText: vi.fn(() => Promise.resolve({ success: true, method: 'clipboard', textLength: 10, durationMs: 50 }))
}
vi.mock('../../../src/main/services/TextInsertService', () => ({
getTextInsertService: () => mockTextInsert
}))
const mockLLM = {
isAvailable: vi.fn(() => false),
processText: vi.fn(() => Promise.resolve('다듬어진 텍스트')),
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => mockLLM
}))
let getVoiceModeService: () => ReturnType<typeof import('../../../src/main/services/VoiceModeService')['getVoiceModeService']>
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
audioBus.removeAllListeners()
mockSTT.initialize.mockResolvedValue(undefined as never)
mockSTT.transcribe.mockResolvedValue({
text: '테스트 전사',
segments: [],
language: 'ko',
duration: 2,
processingTime: 500,
} as never)
mockLLM.processText.mockResolvedValue('다듬어진 텍스트' as never)
const mod = await import('../../../src/main/services/VoiceModeService')
mod.resetVoiceModeServiceForTests()
getVoiceModeService = mod.getVoiceModeService
})
describe('VoiceModeService', () => {
describe('상태 머신', () => {
it('초기 상태는 IDLE이다', () => {
const svc = getVoiceModeService()
const state = svc.getState()
expect(state.recognitionState).toBe(RecognitionState.IDLE)
expect(state.audioState).toBe(AudioState.IDLE)
expect(state.sessionId).toBeNull()
})
it('startSession 호출 시 PREPARING으로 전이한다', async () => {
const svc = getVoiceModeService()
const stateChanges: RecognitionState[] = []
svc.on('recognition-state-changed', (payload: { current: RecognitionState }) => {
stateChanges.push(payload.current)
})
await svc.startSession('dictation')
// PREPARING → CONNECTING → READY 순서
expect(stateChanges[0]).toBe(RecognitionState.PREPARING)
expect(stateChanges).toContain(RecognitionState.CONNECTING)
})
it('isActive는 세션이 활성일 때 true이다', async () => {
const svc = getVoiceModeService()
expect(svc.isActive).toBe(false)
// startSession은 완전 비동기이므로 await 후 세션 활성 확인
await svc.startSession('dictation')
expect(svc.isActive).toBe(true)
})
})
describe('accidentalPress', () => {
it('700ms 미만 세션은 자동 취소된다', async () => {
const svc = getVoiceModeService()
let cancelReason: string | null = null
svc.on('session-cancelled', (payload: { reason: string }) => {
cancelReason = payload.reason
})
// 세션 시작 즉시 종료 (700ms 미만)
await svc.startSession('dictation')
await svc.stopSession()
expect(cancelReason).toBe('too-short')
})
})
describe('STT 준비 대기', () => {
it('전사가 시작된 뒤에는 readiness timeout 으로 세션을 취소하지 않는다', async () => {
let resolveInit: (() => void) | undefined
mockSTT.initialize.mockImplementation(
() =>
new Promise<void>((resolve) => {
resolveInit = resolve
}),
)
mockSTT.transcribe.mockResolvedValue({
text: '안녕하세요',
segments: [],
language: 'ko',
duration: 2,
processingTime: 50,
} as never)
const svc = getVoiceModeService()
let cancelReason: string | null = null
let completed = false
svc.on('session-cancelled', (payload: { reason: string }) => {
cancelReason = payload.reason
})
const completedPromise = new Promise<void>((resolve) => {
svc.once('session-completed', () => {
completed = true
resolve()
})
})
await svc.startSession('dictation')
audioBus.emit('audio-data', { buffer: Buffer.alloc(16000 * 2) })
await new Promise((r) => setTimeout(r, 850))
await svc.stopSession()
resolveInit?.()
await Promise.race([completedPromise, new Promise((r) => setTimeout(r, 1000))])
expect(cancelReason).not.toBe('timeout')
expect(completed).toBe(true)
})
})
describe('cancelSession', () => {
it('user 취소로 세션을 종료한다', async () => {
const svc = getVoiceModeService()
let cancelReason: string | null = null
svc.on('session-cancelled', (payload: { reason: string }) => {
cancelReason = payload.reason
})
await svc.startSession('dictation')
svc.cancelSession()
expect(cancelReason).toBe('user')
})
})
describe('getState', () => {
it('현재 상태를 VoiceState 형태로 반환한다', () => {
const svc = getVoiceModeService()
const state = svc.getState()
expect(state).toHaveProperty('recognitionState')
expect(state).toHaveProperty('audioState')
expect(state).toHaveProperty('mode')
expect(state).toHaveProperty('sessionId')
expect(state).toHaveProperty('recordingStartedAt')
})
})
describe('터미널 상태', () => {
it('cancelSession 후 _resetToIdle의 200ms 딜레이 후 IDLE로 전이한다', async () => {
vi.useFakeTimers()
const svc = getVoiceModeService()
await svc.startSession('dictation')
svc.cancelSession()
// 200ms 딜레이로 IDLE 전이 예약됨
vi.advanceTimersByTime(250)
const state = svc.getState()
expect(state.recognitionState).toBe(RecognitionState.IDLE)
vi.useRealTimers()
})
})
})
describe('TIMING 상수', () => {
it('핵심 타이밍 값이 Speakly 패턴과 일치한다', () => {
expect(TIMING.MIN_AUDIO_DURATION).toBe(700)
expect(TIMING.DOUBLE_PRESS_DURATION).toBe(300)
expect(TIMING.POST_RECORDING_WAIT).toBe(4000)
expect(TIMING.POST_RECORDING_WAIT_BUFFERED).toBe(6000)
expect(TIMING.ABSOLUTE_MAX_WAIT).toBe(120000)
expect(TIMING.AUDIO_LEVEL_INTERVAL).toBe(100)
})
})