368 lines
14 KiB
TypeScript
368 lines
14 KiB
TypeScript
// apps/desktop/tests/unit/desktop-ux-gaps.test.ts
|
||
// Unit tests for Desktop UX & Main backlog items:
|
||
// GAP-UX-06, GAP-KEY-03, GAP-ADS-02, GAP-UX-01, GAP-UX-02, GAP-UX-03
|
||
|
||
import fs from 'fs'
|
||
import path from 'path'
|
||
import os from 'os'
|
||
import { describe, it, expect, vi } from 'vitest'
|
||
import { EventEmitter } from 'events'
|
||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||
import { ErrorCode, ipcError, ipcSuccess } from '@d3ro/core/errors'
|
||
import { Feature } from '@d3ro/core/types'
|
||
import { STT_PROVIDERS_META } from '../../src/main/services/stt/STTManager'
|
||
import { registerAudioHandlers } from '../../src/main/ipc/audio-handlers'
|
||
import { getAudioCaptureService } from '../../src/main/services/AudioCaptureService'
|
||
import { getDictionaryService } from '../../src/main/services/DictionaryService'
|
||
import { getVoiceConversationService } from '../../src/main/services/VoiceConversationService'
|
||
import { getTTSPlaybackService } from '../../src/main/services/TTSPlaybackService'
|
||
import { registerVoiceConversationHandlers } from '../../src/main/ipc/voice-conversation-handlers'
|
||
import { resolveRagAddError } from '../../src/renderer/pages/KnowledgeBasePage'
|
||
import { getVoiceModeService } from '../../src/main/services/VoiceModeService'
|
||
import { getLicenseService } from '../../src/main/services/LicenseService'
|
||
import { getMeetingModeService } from '../../src/main/services/MeetingModeService'
|
||
import { registerMeetingModeHandlers } from '../../src/main/ipc/meeting-mode-handlers'
|
||
import { syncNotepadMemo, loadNotepad } from '../../src/renderer/components/meeting/meeting-notepad-storage'
|
||
import { getHistoryService } from '../../src/main/services/HistoryService'
|
||
import { registerHistoryHandlers } from '../../src/main/ipc/history-handlers'
|
||
import { getMemoService } from '../../src/main/services/MemoService'
|
||
import {
|
||
MEETING_SUMMARY_PROMPT,
|
||
extractTranscriptCitations,
|
||
parseCitationTimestampMs,
|
||
} from '../../src/main/services/MeetingSummaryService'
|
||
import { splitTextWithCitations } from '../../src/renderer/components/meeting/MarkdownRenderer'
|
||
import { getDatabase } from '../../src/main/db'
|
||
import { meetingSessions } from '../../src/main/db/schema'
|
||
import { historyInput, invokeIpc, useRedHarness } from '../red/harness'
|
||
|
||
useRedHarness()
|
||
|
||
describe('GAP-UX-06: Desktop Main Cleanup (sub-items a–f)', () => {
|
||
it('(a) STT_PROVIDERS_META uses neutral technical descriptions without marketing strings', () => {
|
||
const bannedTerms = ['100% 완전 오프라인', 'Industry Benchmark', 'Ultra Fast', 'Enterprise Ready', 'K-Language Best']
|
||
for (const meta of STT_PROVIDERS_META) {
|
||
for (const banned of bannedTerms) {
|
||
expect(meta.description).not.toContain(banned)
|
||
expect(meta.badge ?? '').not.toContain(banned)
|
||
}
|
||
expect(meta.description.length).toBeGreaterThan(5)
|
||
}
|
||
})
|
||
|
||
it('(b) AUDIO.TEST_DEVICE forwards the requested deviceId to AudioCaptureService.acquire', async () => {
|
||
registerAudioHandlers()
|
||
const audioService = getAudioCaptureService()
|
||
const fakeStream = new EventEmitter()
|
||
const releaseMock = vi.fn().mockResolvedValue(undefined)
|
||
const acquireSpy = vi.spyOn(audioService, 'acquire').mockResolvedValue({
|
||
stream: fakeStream,
|
||
sampleRate: 16000,
|
||
channels: 1,
|
||
release: releaseMock,
|
||
})
|
||
|
||
try {
|
||
const res = await invokeIpc<{ success: boolean }>(IPC_CHANNELS.AUDIO.TEST_DEVICE, {
|
||
deviceId: 'usb-mic-device-42',
|
||
durationMs: 50,
|
||
})
|
||
expect(res.success).toBe(true)
|
||
expect(acquireSpy).toHaveBeenCalledWith('usb-mic-device-42')
|
||
await invokeIpc(IPC_CHANNELS.AUDIO.STOP_TEST)
|
||
} finally {
|
||
acquireSpy.mockRestore()
|
||
}
|
||
})
|
||
|
||
it('(c) DictionaryService includes pronunciation in getPromptHints and applyDictionaryCorrections replaces & increments usageCount', () => {
|
||
const dict = getDictionaryService()
|
||
const added = dict.add({
|
||
word: 'D3ROVoice',
|
||
pronunciation: '디쓰리로보이스, 디쓰리로',
|
||
category: 'general',
|
||
})
|
||
|
||
const hints = dict.getPromptHints()
|
||
expect(hints).toContain('D3ROVoice (디쓰리로보이스, 디쓰리로)')
|
||
|
||
const corrected = dict.applyDictionaryCorrections('오늘 디쓰리로보이스 테스트를 진행합니다')
|
||
expect(corrected.text).toBe('오늘 D3ROVoice 테스트를 진행합니다')
|
||
expect(corrected.matchedIds).toEqual([added.id])
|
||
|
||
const page = dict.list({ page: 0, pageSize: 10 })
|
||
const entry = page.entries.find((e) => e.id === added.id)
|
||
expect(entry?.usageCount).toBe(1)
|
||
})
|
||
|
||
it('(d) VoiceConversationService.replayMessage speaks assistant message via TTSPlaybackService and is exposed via IPC', async () => {
|
||
registerVoiceConversationHandlers()
|
||
const tts = getTTSPlaybackService()
|
||
const speakSpy = vi.spyOn(tts, 'speakSentences').mockResolvedValue(undefined)
|
||
|
||
try {
|
||
const res = await invokeIpc(IPC_CHANNELS.VOICE_CONVERSATION.REPLAY_MESSAGE ?? 'voiceConversation:replayMessage', {
|
||
text: '다시 읽어줄 응답입니다.',
|
||
})
|
||
expect(res.success).toBe(true)
|
||
expect(speakSpy).toHaveBeenCalledWith(['다시 읽어줄 응답입니다.'])
|
||
|
||
await getVoiceConversationService().replayMessage('직접 호출 테스트')
|
||
expect(speakSpy).toHaveBeenCalledWith(['직접 호출 테스트'])
|
||
} finally {
|
||
speakSpy.mockRestore()
|
||
}
|
||
})
|
||
|
||
it('(e) preload instruction.getAll is typed as CustomInstruction[]', () => {
|
||
const preloadSrc = fs.readFileSync(
|
||
path.resolve(__dirname, '../../src/preload/index.ts'),
|
||
'utf-8',
|
||
)
|
||
expect(preloadSrc).toContain('invoke<CustomInstruction[]>(IPC_CHANNELS.INSTRUCTION.GET_ALL)')
|
||
})
|
||
|
||
it('(f) resolveRagAddError checks structured details.cancelled / error code instead of fragile string matching', () => {
|
||
const cancelledResp = ipcError(ErrorCode.RAGIndexingFailed, 'File selection cancelled', {
|
||
cancelled: true,
|
||
reason: 'dialog_cancelled',
|
||
})
|
||
expect(resolveRagAddError(cancelledResp)).toBeNull()
|
||
|
||
const realErrorResp = ipcError(ErrorCode.RAGIndexingFailed, 'Failed to parse PDF', {
|
||
cancelled: false,
|
||
})
|
||
expect(resolveRagAddError(realErrorResp)).toBe('Failed to parse PDF')
|
||
|
||
const okResp = ipcSuccess({
|
||
id: 'doc-1',
|
||
title: 'Test',
|
||
filePath: '/tmp/test.txt',
|
||
chunkCount: 2,
|
||
createdAt: Date.now(),
|
||
})
|
||
expect(resolveRagAddError(okResp)).toBeNull()
|
||
})
|
||
})
|
||
|
||
describe('GAP-KEY-03: command Keybinding Action Dedicated Behavior', () => {
|
||
it('_resolveHoldMode honors specHoldMode for command action and _resolveLlmRoute upgrades none to refine', async () => {
|
||
const { configSet } = await import('../../src/main/services/ConfigService')
|
||
configSet('llmBackend', 'online')
|
||
configSet('defaultLLMAction', 'none')
|
||
|
||
const vm = getVoiceModeService()
|
||
expect(vm._resolveHoldMode('command', false)).toBe(false)
|
||
expect(vm._resolveHoldMode('command', true)).toBe(true)
|
||
|
||
const resolveRoute = (
|
||
vm as unknown as {
|
||
_resolveLlmRoute: (
|
||
overrideId: string | null,
|
||
actionId?: 'dictation' | 'command' | 'hands-free',
|
||
) => { kind: string; action?: string; reason?: string }
|
||
}
|
||
)._resolveLlmRoute.bind(vm)
|
||
|
||
expect(resolveRoute(null, 'dictation')).toEqual({ kind: 'insert-raw', reason: 'none' })
|
||
expect(resolveRoute(null, 'command')).toEqual({ kind: 'action', action: 'refine' })
|
||
})
|
||
})
|
||
|
||
describe('GAP-ADS-02: LicenseService.grantRewardQuota', () => {
|
||
it('increments bonus quota for PREMIUM_LLM and deduplicates nonces', () => {
|
||
const license = getLicenseService()
|
||
const before = license.getUsage(Feature.PREMIUM_LLM)
|
||
|
||
const first = license.grantRewardQuota(50, 'nonce-abc')
|
||
expect(first.granted).toBe(true)
|
||
expect(first.tokensAdded).toBe(50)
|
||
expect(first.bonusQuota).toBe(50)
|
||
expect(first.newTotalQuota).toBe(before.limit + 50)
|
||
|
||
const duplicate = license.grantRewardQuota(50, 'nonce-abc')
|
||
expect(duplicate.granted).toBe(false)
|
||
expect(duplicate.tokensAdded).toBe(0)
|
||
expect(license.getUsage(Feature.PREMIUM_LLM).limit).toBe(before.limit + 50)
|
||
})
|
||
})
|
||
|
||
describe('GAP-UX-01: Meeting Post-Meeting addMemo & Notepad Sync', () => {
|
||
it('allows adding a memo to an ended meeting session by meetingId and syncs via syncNotepadMemo', async () => {
|
||
registerMeetingModeHandlers()
|
||
const now = Date.now()
|
||
getDatabase()
|
||
.insert(meetingSessions)
|
||
.values({
|
||
id: 'ended-session-1',
|
||
title: '종료된 회의',
|
||
status: 'completed',
|
||
startedAt: now - 60_000,
|
||
endedAt: now,
|
||
durationMs: 60_000,
|
||
rawTranscript: '[00:10] 안녕하세요',
|
||
createdAt: now - 60_000,
|
||
updatedAt: now,
|
||
})
|
||
.run()
|
||
|
||
const memo = await getMeetingModeService().addMemo('회의 종료 후 추가한 메모', 'ended-session-1')
|
||
expect(memo.sessionId).toBe('ended-session-1')
|
||
expect(memo.content).toBe('회의 종료 후 추가한 메모')
|
||
expect(memo.timestampMs).toBe(60_000)
|
||
|
||
const detail = getMeetingModeService().getSession('ended-session-1')
|
||
expect(detail.memos).toHaveLength(1)
|
||
expect(detail.memos[0].content).toBe('회의 종료 후 추가한 메모')
|
||
|
||
// Test notepad storage + IPC sync helper
|
||
const fakeStorageMap = new Map<string, string>()
|
||
const fakeStorage = {
|
||
getItem: (k: string) => fakeStorageMap.get(k) ?? null,
|
||
setItem: (k: string, v: string) => {
|
||
fakeStorageMap.set(k, v)
|
||
},
|
||
removeItem: (k: string) => {
|
||
fakeStorageMap.delete(k)
|
||
},
|
||
}
|
||
|
||
const synced = await syncNotepadMemo(
|
||
fakeStorage,
|
||
'ended-session-1',
|
||
'노트패드에서 동기화된 메모',
|
||
{
|
||
addMemo: (params) =>
|
||
invokeIpc(IPC_CHANNELS.MEETING_MODE.ADD_MEMO, params),
|
||
},
|
||
)
|
||
expect(loadNotepad(fakeStorage, 'ended-session-1')).toBe('노트패드에서 동기화된 메모')
|
||
expect(synced?.content).toBe('노트패드에서 동기화된 메모')
|
||
expect(getMeetingModeService().getSession('ended-session-1').memos).toHaveLength(2)
|
||
})
|
||
})
|
||
|
||
describe('GAP-UX-02: History SQLite Multi-Filter, Update, and Markdown Export', () => {
|
||
it('filters HistoryService.getAll in SQLite by mode, isFavorite, tag, search, and beforeCreatedAt', () => {
|
||
const historySvc = getHistoryService()
|
||
const memoSvc = getMemoService()
|
||
|
||
const e1 = historySvc.create(
|
||
historyInput({
|
||
originalText: '알파 프로젝트 일정 논의',
|
||
mode: 'dictation',
|
||
isFavorite: true,
|
||
}),
|
||
)
|
||
const e2 = historySvc.create(
|
||
historyInput({
|
||
originalText: '알파 프로젝트 번역 테스트',
|
||
mode: 'translate',
|
||
isFavorite: true,
|
||
}),
|
||
)
|
||
historySvc.create(
|
||
historyInput({
|
||
originalText: '베타 프로젝트 일반 메모',
|
||
mode: 'dictation',
|
||
isFavorite: false,
|
||
}),
|
||
)
|
||
|
||
memoSvc.addTag(e1.id, 'alpha')
|
||
memoSvc.addTag(e2.id, 'alpha')
|
||
|
||
// Object caller with combined filters
|
||
const filtered = historySvc.getAll({
|
||
page: 0,
|
||
pageSize: 10,
|
||
mode: 'dictation',
|
||
isFavorite: true,
|
||
tag: 'alpha',
|
||
search: '일정',
|
||
})
|
||
expect(filtered.total).toBe(1)
|
||
expect(filtered.entries[0].id).toBe(e1.id)
|
||
|
||
// Backward-compatible positional caller (limit, offset, search)
|
||
const positional = historySvc.getAll(10, 0, '알파')
|
||
expect(positional.total).toBe(2)
|
||
})
|
||
|
||
it('updates history entry title and text via HistoryService.update and history:update IPC', async () => {
|
||
registerHistoryHandlers()
|
||
const historySvc = getHistoryService()
|
||
const created = historySvc.create(
|
||
historyInput({
|
||
originalText: '초기 원문 텍스트',
|
||
polishedText: '초기 다듬은 텍스트',
|
||
}),
|
||
)
|
||
|
||
const res = await invokeIpc<{ id: string; title: string | null; polishedText: string | null }>(
|
||
'history:update',
|
||
{
|
||
id: created.id,
|
||
title: '수정된 제목',
|
||
polishedText: '수정된 본문 내용입니다',
|
||
},
|
||
)
|
||
expect(res.success).toBe(true)
|
||
if (res.success) {
|
||
expect(res.data.title).toBe('수정된 제목')
|
||
expect(res.data.polishedText).toBe('수정된 본문 내용입니다')
|
||
}
|
||
|
||
const reloaded = historySvc.getById(created.id)
|
||
expect(reloaded?.title).toBe('수정된 제목')
|
||
expect(reloaded?.polishedText).toBe('수정된 본문 내용입니다')
|
||
expect(reloaded?.wordCount).toBe(3)
|
||
})
|
||
|
||
it('exports untagged history records and supports custom savePath in MemoService.exportMarkdown', () => {
|
||
const historySvc = getHistoryService()
|
||
historySvc.create(
|
||
historyInput({
|
||
title: '태그 없는 메모',
|
||
originalText: '태그가 없어도 내보내기에 포함됩니다',
|
||
}),
|
||
)
|
||
|
||
const customPath = path.join(os.tmpdir(), `d3ro-memo-export-test-${Date.now()}.md`)
|
||
try {
|
||
const outPath = getMemoService().exportMarkdown({
|
||
format: 'markdown',
|
||
savePath: customPath,
|
||
})
|
||
expect(outPath).toBe(path.resolve(customPath))
|
||
const content = fs.readFileSync(outPath, 'utf-8')
|
||
expect(content).toContain('## Untagged')
|
||
expect(content).toContain('태그가 없어도 내보내기에 포함됩니다')
|
||
} finally {
|
||
if (fs.existsSync(customPath)) fs.unlinkSync(customPath)
|
||
}
|
||
})
|
||
})
|
||
|
||
describe('GAP-UX-03: Meeting Summary Transcript Citations', () => {
|
||
it('parses [MM:SS] and [HH:MM:SS] citations and splits summary text into clickable citation parts', () => {
|
||
expect(MEETING_SUMMARY_PROMPT).toContain('[MM:SS]')
|
||
expect(parseCitationTimestampMs('[01:25]')).toBe(85_000)
|
||
expect(parseCitationTimestampMs('[01:02:03]')).toBe(3_723_000)
|
||
expect(parseCitationTimestampMs('[invalid]')).toBeNull()
|
||
|
||
const sampleMarkdown = `## 요약\n출시 일정을 확정했습니다 [02:15].\n\n## 핵심 결정사항\n- 11월 정식 배포 [05:40]`
|
||
const citations = extractTranscriptCitations(sampleMarkdown)
|
||
expect(citations).toEqual([
|
||
{ label: '[02:15]', timestampMs: 135_000 },
|
||
{ label: '[05:40]', timestampMs: 340_000 },
|
||
])
|
||
|
||
const parts = splitTextWithCitations('출시 일정을 확정했습니다 [02:15].')
|
||
expect(parts).toEqual([
|
||
{ type: 'text', value: '출시 일정을 확정했습니다 ' },
|
||
{ type: 'citation', label: '[02:15]', timestampMs: 135_000 },
|
||
{ type: 'text', value: '.' },
|
||
])
|
||
})
|
||
})
|