feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)

This commit is contained in:
Yun Chan 2026-10-31 02:54:54 +09:00
parent f49acf0105
commit 10af20a0ad
157 changed files with 29455 additions and 913 deletions

View file

@ -1,7 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { AdMediationConfig } from '@d3ro/core/types'
import { Feature, type AdMediationConfig } from '@d3ro/core/types'
import { getAdMediationEngine } from '../../src/main/services/ads/AdMediationEngine'
import { getAdSettlementService } from '../../src/main/services/ads/AdSettlementService'
import { getLicenseService } from '../../src/main/services/LicenseService'
import { EthicalAdsAdapter } from '../../src/main/services/ads/EthicalAdsAdapter'
import { CarbonAdsAdapter } from '../../src/main/services/ads/CarbonAdsAdapter'
import { PlaywireAdapter } from '../../src/main/services/ads/PlaywireAdapter'
@ -275,3 +276,88 @@ describe('AdSettlementService fail-closed ledger', () => {
expect(settlement.getRevenueStats('2026-08')).toEqual(before)
})
})
describe('GAP-ADS-02 rewarded quota integration', () => {
const engine = getAdMediationEngine()
const knownNetworks = engine.getConfig().networks
it('grants LicenseService bonus quota on verified rewarded ad completion and blocks replay', async () => {
const license = getLicenseService()
const baseQuota = license.getUsage(Feature.PREMIUM_LLM)
engine.setConfig({
rewardTokensAmount: 50,
rewardCooldownSeconds: 0,
networks: knownNetworks.map((n) =>
n.id === 'direct_sponsor'
? {
...n,
enabled: true,
endpointUrl: 'https://ads.example.com',
apiSecret: 'secret',
}
: { ...n, enabled: false },
),
})
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response(
JSON.stringify({
bidEcpm: 15,
creative: {
id: 'rewarded-ad-1',
title: 'Rewarded Video',
advertiserName: 'D3RO Partner',
clickUrl: 'https://example.com/reward',
format: 'rewarded_video',
rewardTokens: 50,
durationSeconds: 15,
},
}),
{ status: 200 },
),
)
.mockResolvedValueOnce(new Response(JSON.stringify({ ok: true }), { status: 200 }))
.mockResolvedValueOnce(
new Response(JSON.stringify({ success: true, tokenReward: 50 }), { status: 200 }),
)
vi.stubGlobal('fetch', fetchMock)
try {
const auction = await engine.runAuction({
placement: 'rewarded_video_quota',
format: 'rewarded_video',
floorEcpm: 4,
})
expect(auction.winner?.id).toBe('rewarded-ad-1')
engine.recordImpression({
adId: 'rewarded-ad-1',
format: 'rewarded_video',
network: 'direct_sponsor',
earnedEcpm: auction.winningBidEcpm,
})
const claim = await engine.claimReward('rewarded-ad-1', 'direct_sponsor', 'nonce-1')
expect(claim.success).toBe(true)
expect(claim.tokensAdded).toBe(50)
expect(claim.newTotalQuota).toBe(baseQuota.limit + 50)
expect(license.getUsage(Feature.PREMIUM_LLM).limit).toBe(baseQuota.limit + 50)
// Replay with same adId or nonce is rejected
const replay = await engine.claimReward('rewarded-ad-1', 'direct_sponsor', 'nonce-1')
expect(replay).toEqual({
success: false,
tokensAdded: 0,
newTotalQuota: 0,
})
} finally {
vi.unstubAllGlobals()
engine.setConfig({
networks: knownNetworks.map((n) => ({ ...n, enabled: false })),
})
}
})
})

View file

@ -0,0 +1,368 @@
// 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: '.' },
])
})
})

View file

@ -9,10 +9,12 @@ import { describe, expect, it } from 'vitest'
import {
COMMAND_NONE,
commandSelection,
commandSelections,
commandTestRequest,
conversationBadge,
documentIndexLabelKey,
llmActionLabelKey,
removeInstructionFromActiveIds,
resolveCommandPipeline,
withoutHidden,
isInstructionInUse,
@ -32,6 +34,21 @@ describe('resolveCommandPipeline', () => {
const p = resolveCommandPipeline({ defaultLLMAction: 'custom', activeInstructionId: 'i1' }, list)
expect(p).toEqual({ kind: 'instruction', instruction: polish })
expect(commandSelection(p)).toBe('i1')
expect(commandSelections(p)).toEqual(['i1'])
})
it("'custom' + 복수 지시문('i2,i1')이면 선택한 순서대로 다단계 파이프라인을 구성한다", () => {
const p = resolveCommandPipeline({ defaultLLMAction: 'custom', activeInstructionId: 'i2,i1' }, list)
expect(p).toEqual({ kind: 'instructions', instructions: [list[1], polish] })
expect(commandSelection(p)).toBe('i2,i1')
expect(commandSelections(p)).toEqual(['i2', 'i1'])
const testReq = commandTestRequest(p, ' 어 오늘 회의 내용 정리 ')
expect(testReq.ok).toBe(true)
if (testReq.ok) {
expect(testReq.params.action).toBe('custom')
expect(testReq.params.customPrompt).toContain('[1단계: 요약]')
expect(testReq.params.customPrompt).toContain('[2단계: 정중하게]')
}
})
it("'custom' 인데 지시문이 지워졌으면 '선택 안 됨'으로 정직하게", () => {
@ -98,8 +115,10 @@ describe('withoutHidden / documentIndexLabelKey', () => {
})
describe('isInstructionInUse — 명령 삭제 확정 시점의 설정으로 판단', () => {
it('지운 명령이 아직 선택돼 있을 때만 true', () => {
it('지운 명령이 아직 선택돼 있을 때만 true (단일 및 복수 파이프라인 포함)', () => {
expect(isInstructionInUse({ defaultLLMAction: 'custom', activeInstructionId: 'x' }, 'x')).toBe(true)
expect(isInstructionInUse({ defaultLLMAction: 'custom', activeInstructionId: 'y,x' }, 'x')).toBe(true)
expect(removeInstructionFromActiveIds('y,x', 'x')).toEqual(['y'])
// 되돌리기 알림 동안 다른 명령을 골랐다 — 덮으면 안 된다
expect(isInstructionInUse({ defaultLLMAction: 'custom', activeInstructionId: 'y' }, 'x')).toBe(false)
expect(isInstructionInUse({ defaultLLMAction: 'refine', activeInstructionId: 'x' }, 'x')).toBe(false)