fix(llm): stop leaking instruction prompts instead of processed text
Running a custom instruction (translate, summarise, rewrite, explain code,
free prompt) inserted the instruction's own wording instead of the result.
Two faults stacked:
The instruction was passed as the text to process, leaving the system-prompt
argument empty. `BASE_SYSTEM_PROMPTS` has no `custom` key, so resolution fell
back to `refine` without saying so, and the model dutifully polished the
instruction it had been handed. The transcript never reached it.
And only `{{text}}` was substituted, which none of the five built-in
instructions use — they carry `{{targetLanguage}}`, `{{userPrompt}}`, or no
placeholder at all. The substitution was a no-op from the day it was written:
the presets landed ten hours before the code that expected them.
- Instruction prompts now go to the system-prompt argument and the transcript
to the text argument. Instructions that spell out `{{text}}` keep their old
meaning, so hand-written ones still work.
- `renderInstructionPrompt` resolves `{{text}}`, `{{userPrompt}}` and
`{{targetLanguage}}` in one place, and warns by name when a placeholder is
left standing rather than letting it reach the model.
- `resolveSystemPrompt` no longer drops silently to `refine` for `custom`.
- Voice shortcuts no longer die at the `defaultLLMAction === 'none'` gate; an
explicitly named instruction outranks the default. Without one, `none` still
passes the transcript through untouched.
- `translate` receives its target language instead of relying on a default two
call frames away. It is still always English — `AppConfig` has no key for it,
and neither `language` (UI locale) nor `sttLanguage` (source language) can
stand in. Choosing a target language needs a setting and is not in this fix.
- Chains ran instructions with placeholders intact; they share the same
resolution now.
- The command screen's pipeline bench called `llm.generate`, which preload does
not expose, so every run threw and the catch showed the input back as if it
had succeeded. It uses `llm.process` now, over the same path production
takes, and a failure reads as a failure.
Present since the feature shipped: the custom-instruction path has never
worked. Plain actions (refine, summarise, grammar, expand) were unaffected and
are now covered by tests so they stay that way.
This commit is contained in:
parent
30d51c952f
commit
99f06c253c
14 changed files with 992 additions and 44 deletions
|
|
@ -7,6 +7,7 @@ import { getLocalLLMService } from '../services/LocalLLMService'
|
|||
import { getPremiumLLMService } from '../services/PremiumLLMService'
|
||||
import { getOnlineLLMService } from '../services/OnlineLLMService'
|
||||
import { configGet, configSet } from '../services/ConfigService'
|
||||
import { buildInstructionInvocation, resolveTargetLanguage } from '../services/llm-prompts'
|
||||
import { normalizeLoopbackUrl } from '../utils/loopback'
|
||||
import { getMainWindow } from '../windows/WindowManager'
|
||||
import type { SetLLMModelParams, SetServerUrlParams, LLMProcessParams } from '@d3ro/core/types'
|
||||
|
|
@ -87,11 +88,23 @@ export function registerLLMHandlers(): void {
|
|||
backend === 'online' ? getOnlineLLMService() : getLocalLLMService()
|
||||
const start = performance.now()
|
||||
|
||||
// 지시문 프롬프트를 시스템 프롬프트 자리로 보내고 플레이스홀더를 치환하는 판단은
|
||||
// VoiceModeService·ChainService와 같은 함수를 쓴다. 렌더러는 지시문 원문만
|
||||
// 넘기고, 치환 규칙을 복제하지 않는다.
|
||||
const invocation =
|
||||
params.action === 'custom' && params.customPrompt
|
||||
? buildInstructionInvocation(
|
||||
params.customPrompt,
|
||||
params.text,
|
||||
params.targetLanguage ?? resolveTargetLanguage()
|
||||
)
|
||||
: { text: params.text, systemPrompt: params.customPrompt }
|
||||
|
||||
const processedText = await service.processText(
|
||||
params.text,
|
||||
invocation.text,
|
||||
params.action,
|
||||
params.targetLanguage,
|
||||
params.customPrompt
|
||||
invocation.systemPrompt
|
||||
)
|
||||
|
||||
return ipcSuccess({
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { getLogger } from './LoggerService'
|
|||
import { configGet, configSet } from './ConfigService'
|
||||
import { getCustomInstructionService } from './CustomInstructionService'
|
||||
import { getPremiumLLMService } from './PremiumLLMService'
|
||||
import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts'
|
||||
import { getMainWindow } from '../windows/WindowManager'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
|
|
@ -151,6 +152,7 @@ class ChainService {
|
|||
|
||||
const llm = getPremiumLLMService()
|
||||
const instructionService = getCustomInstructionService()
|
||||
const targetLanguage = resolveTargetLanguage()
|
||||
|
||||
logger.info(
|
||||
`Executing chain "${chain.name}" (${chain.steps.length} steps) with input length ${inputText.length}`
|
||||
|
|
@ -189,7 +191,19 @@ class ChainService {
|
|||
// LLM 호출
|
||||
const stepStart = Date.now()
|
||||
try {
|
||||
const result = await llm.processText(stepInput, 'custom', undefined, instruction.prompt)
|
||||
// 지시문은 시스템 프롬프트, 스텝 입력(이전 스텝 출력)은 처리 대상 텍스트.
|
||||
// {{text}}를 쓰는 지시문은 치환 결과가 처리 대상 텍스트가 된다.
|
||||
const invocation = buildInstructionInvocation(
|
||||
instruction.prompt,
|
||||
stepInput,
|
||||
targetLanguage,
|
||||
)
|
||||
const result = await llm.processText(
|
||||
invocation.text,
|
||||
'custom',
|
||||
undefined,
|
||||
invocation.systemPrompt,
|
||||
)
|
||||
const stepDuration = Date.now() - stepStart
|
||||
|
||||
stepResults.push({
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import type { KeyBindingTriggerPayload } from './KeyBindingService'
|
|||
import { configGet } from './ConfigService'
|
||||
import { getTextInsertService } from './TextInsertService'
|
||||
import { getLocalLLMService } from './LocalLLMService'
|
||||
import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import { TIMING } from '@d3ro/core/constants'
|
||||
import { RecognitionState, AudioState } from '@d3ro/core/types'
|
||||
|
|
@ -772,12 +773,17 @@ class VoiceModeService extends EventEmitter {
|
|||
if (this._isInTerminalState()) return
|
||||
|
||||
try {
|
||||
const action = configGet('defaultLLMAction')
|
||||
if (action === 'none') {
|
||||
const configuredAction = configGet('defaultLLMAction')
|
||||
// 음성 단축키가 특정 명령을 지목해 들어왔다면 기본 액션이 'none'이어도 처리한다.
|
||||
// 명시적 요청을 기본 설정이 무효화하면 안 된다.
|
||||
if (configuredAction === 'none' && !overrideInstructionId) {
|
||||
this._completeSession(transcribedText)
|
||||
return
|
||||
}
|
||||
|
||||
// 여기서 'none'이 남아 있다면 overrideInstructionId가 반드시 있다 → custom 경로.
|
||||
const action: LLMAction = configuredAction === 'none' ? 'custom' : configuredAction
|
||||
|
||||
// Phase 10.2: 스크린 컨텍스트를 LLM 프롬프트에 주입
|
||||
let contextPrefix = ''
|
||||
if (this._session?.screenContext) {
|
||||
|
|
@ -818,22 +824,49 @@ class VoiceModeService extends EventEmitter {
|
|||
const effectiveInstructionId = overrideInstructionId
|
||||
?? configGet('activeInstructionId')
|
||||
|
||||
const targetLanguage = resolveTargetLanguage()
|
||||
|
||||
if (action === 'custom' || overrideInstructionId) {
|
||||
let customPrompt = contextPrefix + transcribedText
|
||||
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) {
|
||||
customPrompt = instruction.prompt.replace(/\{\{text\}\}/g, contextPrefix + transcribedText)
|
||||
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(customPrompt, 'custom')
|
||||
processedText = await this._runProcessorWithFallback(
|
||||
invocationText,
|
||||
'custom',
|
||||
undefined,
|
||||
instructionPrompt,
|
||||
)
|
||||
} else {
|
||||
logger.info(`Processing with LLM (action: ${action})`)
|
||||
processedText = await this._runProcessorWithFallback(contextPrefix + transcribedText, action)
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
if (this._isInTerminalState()) return
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
// src/main/services/llm-prompts.ts
|
||||
// LLM 시스템 프롬프트 SSOT — PremiumLLMService 공용.
|
||||
|
||||
import { getLogger } from './LoggerService'
|
||||
import type { LLMAction } from '@d3ro/core/types'
|
||||
|
||||
const logger = getLogger('llm-prompts')
|
||||
|
||||
/**
|
||||
* 기본 시스템 프롬프트 (NO_THINK prefix 없음).
|
||||
* PremiumLLMService는 NO_THINK prefix 없이 바로 사용.
|
||||
|
|
@ -26,6 +29,88 @@ const BASE_SYSTEM_PROMPTS: Record<string, string> = {
|
|||
확장된 텍스트만 출력하세요.`,
|
||||
}
|
||||
|
||||
/**
|
||||
* 번역 대상 언어 기본값.
|
||||
* `AppConfig`에는 번역 대상 언어 키가 없다 (`language`는 UI 로케일,
|
||||
* `sttLanguage`는 입력 언어라 둘 다 대상 언어가 아니다).
|
||||
*/
|
||||
export const DEFAULT_TARGET_LANGUAGE = 'English'
|
||||
|
||||
/**
|
||||
* 번역 대상 언어를 해석한다. LLM을 호출하는 모든 경로가 이 함수를 쓴다.
|
||||
*
|
||||
* `AppConfig`에는 번역 대상 언어 키가 없다 — `language`는 UI 로케일이고
|
||||
* `sttLanguage`는 입력(원문) 언어라 어느 쪽도 대상 언어로 쓸 수 없다.
|
||||
* (입력 언어로 번역하면 원문 그대로가 되고, UI 로케일은 `'ko'` 같은 코드라
|
||||
* 프롬프트에 그대로 넣으면 문장이 깨진다.)
|
||||
*
|
||||
* 따라서 현재는 {@link DEFAULT_TARGET_LANGUAGE} 고정이다. 사용자가 대상 언어를
|
||||
* 고를 수 있으려면 설정 키가 필요하다.
|
||||
*/
|
||||
export function resolveTargetLanguage(): string {
|
||||
return DEFAULT_TARGET_LANGUAGE
|
||||
}
|
||||
|
||||
/**
|
||||
* `action: 'custom'`인데 시스템 프롬프트가 주어지지 않았을 때 쓰는 액션.
|
||||
* 지시문이 `{{text}}`로 사용자 텍스트 위치를 직접 지정한 하위 호환 경로에서 발생한다.
|
||||
*/
|
||||
const CUSTOM_FALLBACK_ACTION = 'refine'
|
||||
|
||||
/** 지시문이 사용자 텍스트 위치를 직접 지정할 때 쓰는 플레이스홀더. */
|
||||
const TEXT_PLACEHOLDER = /\{\{text\}\}/g
|
||||
|
||||
/** 치환 후에도 남아 있는 플레이스홀더 탐지용. */
|
||||
const ANY_PLACEHOLDER = /\{\{([^{}]+)\}\}/g
|
||||
|
||||
export interface InstructionVars {
|
||||
/** 사용자 음성 텍스트 (스크린 컨텍스트 프리픽스 포함). */
|
||||
text: string
|
||||
/** 번역 대상 언어. 생략 시 {@link DEFAULT_TARGET_LANGUAGE}. */
|
||||
targetLanguage?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 정의 지시문의 플레이스홀더를 치환한다.
|
||||
* 치환되지 않고 남은 `{{...}}`는 그대로 두되 경고를 남긴다 —
|
||||
* 조용히 새어나간 플레이스홀더가 LLM에 그대로 전달되는 사고가 있었다.
|
||||
*/
|
||||
export function renderInstructionPrompt(prompt: string, vars: InstructionVars): string {
|
||||
const rendered = prompt
|
||||
.replace(TEXT_PLACEHOLDER, vars.text)
|
||||
.replace(/\{\{userPrompt\}\}/g, vars.text)
|
||||
.replace(/\{\{targetLanguage\}\}/g, vars.targetLanguage ?? DEFAULT_TARGET_LANGUAGE)
|
||||
|
||||
const leftovers = [...rendered.matchAll(ANY_PLACEHOLDER)].map((m) => m[1])
|
||||
if (leftovers.length > 0) {
|
||||
logger.warn(
|
||||
`Unresolved instruction placeholders passed to the LLM: ${[...new Set(leftovers)].join(', ')}`,
|
||||
)
|
||||
}
|
||||
|
||||
return rendered
|
||||
}
|
||||
|
||||
/**
|
||||
* 지시문과 사용자 텍스트로 `processText(text, action, targetLanguage, customPrompt)` 인자를 만든다.
|
||||
*
|
||||
* - 기본: 지시문은 **시스템 프롬프트**, 사용자 텍스트는 **처리 대상 텍스트**.
|
||||
* - 하위 호환: 지시문에 `{{text}}`가 있으면 사용자가 텍스트 위치를 직접 지정한 것이므로
|
||||
* 치환된 지시문을 처리 대상 텍스트로 넘기고 시스템 프롬프트는 비워 기본 동작을 따른다.
|
||||
*/
|
||||
export function buildInstructionInvocation(
|
||||
instructionPrompt: string,
|
||||
userText: string,
|
||||
targetLanguage?: string,
|
||||
): { text: string; systemPrompt?: string } {
|
||||
const rendered = renderInstructionPrompt(instructionPrompt, { text: userText, targetLanguage })
|
||||
|
||||
if (instructionPrompt.includes('{{text}}')) {
|
||||
return { text: rendered }
|
||||
}
|
||||
return { text: userText, systemPrompt: rendered }
|
||||
}
|
||||
|
||||
/**
|
||||
* 액션 + 옵션으로 시스템 프롬프트를 해석한다.
|
||||
* translate 액션은 targetLanguage 치환, custom 액션은 customPrompt 사용.
|
||||
|
|
@ -35,16 +120,26 @@ export function resolveSystemPrompt(
|
|||
targetLanguage?: string,
|
||||
customPrompt?: string,
|
||||
): string {
|
||||
if (action === 'custom' && customPrompt) {
|
||||
return customPrompt
|
||||
if (action === 'custom') {
|
||||
if (customPrompt && customPrompt.trim().length > 0) {
|
||||
return customPrompt
|
||||
}
|
||||
// BASE_SYSTEM_PROMPTS에 'custom' 키가 없어 조용히 refine으로 떨어지던 자리.
|
||||
// 하위 호환({{text}}) 경로에서는 정상이지만, 지시문을 시스템 프롬프트로
|
||||
// 넘기지 못한 버그도 같은 모양이라 반드시 드러나야 한다.
|
||||
logger.warn(
|
||||
`resolveSystemPrompt: action 'custom' without a custom prompt — ` +
|
||||
`falling back to the '${CUSTOM_FALLBACK_ACTION}' system prompt`,
|
||||
)
|
||||
return BASE_SYSTEM_PROMPTS[CUSTOM_FALLBACK_ACTION]
|
||||
}
|
||||
if (action === 'translate') {
|
||||
return BASE_SYSTEM_PROMPTS.translate.replace(
|
||||
'{{targetLanguage}}',
|
||||
targetLanguage ?? 'English',
|
||||
targetLanguage ?? DEFAULT_TARGET_LANGUAGE,
|
||||
)
|
||||
}
|
||||
return BASE_SYSTEM_PROMPTS[action] ?? BASE_SYSTEM_PROMPTS.refine
|
||||
return BASE_SYSTEM_PROMPTS[action] ?? BASE_SYSTEM_PROMPTS[CUSTOM_FALLBACK_ACTION]
|
||||
}
|
||||
|
||||
export { BASE_SYSTEM_PROMPTS }
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ import {
|
|||
Mic,
|
||||
Cpu,
|
||||
ClipboardCopy,
|
||||
TriangleAlert,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
MetalCard,
|
||||
|
|
@ -68,6 +69,7 @@ export function CommandsPage(): React.ReactElement {
|
|||
// Interactive Pipeline Test State
|
||||
const [testInput, setTestInput] = useState('')
|
||||
const [testResult, setTestResult] = useState<string | null>(null)
|
||||
const [testError, setTestError] = useState<string | null>(null)
|
||||
const [testing, setTesting] = useState(false)
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
|
|
@ -175,23 +177,28 @@ export function CommandsPage(): React.ReactElement {
|
|||
}
|
||||
}
|
||||
|
||||
// 이 벤치는 실제 받아쓰기와 같은 경로(llm.process → processText)를 탄다.
|
||||
// 지시문 원문을 customPrompt로 넘기면 메인 프로세스가 플레이스홀더 치환과
|
||||
// 시스템 프롬프트 배치를 처리한다 — 치환 규칙을 렌더러에 복제하지 않는다.
|
||||
const handleRunPipelineTest = async () => {
|
||||
if (!testInput.trim()) return
|
||||
setTesting(true)
|
||||
setTestResult(null)
|
||||
setTestError(null)
|
||||
try {
|
||||
const activeInst = instructions.find((i) => i.id === activeId)
|
||||
const prompt = activeInst?.prompt || '다음 문장을 자연스럽고 깔끔하게 다듬어주세요:'
|
||||
const res = await window.electronAPI.llm.generate({
|
||||
prompt: `${prompt}\n\n${testInput.trim()}`,
|
||||
})
|
||||
const res = await window.electronAPI.llm.process(
|
||||
activeInst
|
||||
? { text: testInput.trim(), action: 'custom', customPrompt: activeInst.prompt }
|
||||
: { text: testInput.trim(), action: 'refine' },
|
||||
)
|
||||
if (res.success) {
|
||||
setTestResult(res.data.text)
|
||||
setTestResult(res.data.processedText)
|
||||
} else {
|
||||
setTestResult(testInput.trim())
|
||||
setTestError(res.error.message || t('popup.error.default'))
|
||||
}
|
||||
} catch {
|
||||
setTestResult(testInput.trim())
|
||||
} catch (error) {
|
||||
setTestError(error instanceof Error ? error.message : t('popup.error.default'))
|
||||
} finally {
|
||||
setTesting(false)
|
||||
}
|
||||
|
|
@ -543,6 +550,25 @@ export function CommandsPage(): React.ReactElement {
|
|||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{testError && (
|
||||
<Box
|
||||
sx={{
|
||||
p: 2,
|
||||
bgcolor: d3roPalette.status.dangerBg,
|
||||
borderRadius: d3roRadius.inner,
|
||||
border: `1px solid ${d3roPalette.status.danger}`,
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: 1.5,
|
||||
}}
|
||||
>
|
||||
<TriangleAlert size={16} style={{ color: d3roPalette.status.danger, marginTop: 2, flexShrink: 0 }} />
|
||||
<Typography sx={{ fontFamily: d3roFontSans, fontSize: '13.5px', color: d3roPalette.status.danger, lineHeight: 1.6 }}>
|
||||
{testError}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</MetalCard>
|
||||
</Box>
|
||||
|
|
|
|||
163
apps/desktop/tests/main/ipc/llm-handlers.test.ts
Normal file
163
apps/desktop/tests/main/ipc/llm-handlers.test.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
// tests/main/ipc/llm-handlers.test.ts
|
||||
// LLM.PROCESS 핸들러가 지시문 프롬프트를 시스템 프롬프트 자리로 정규화하는지 잠근다.
|
||||
// 명령 화면 테스트 벤치가 이 경로를 타므로, 프로덕션(VoiceModeService)과
|
||||
// 동일한 인자 배치·치환이 적용되어야 한다.
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import type { LLMProcessParams } from '@d3ro/core/types'
|
||||
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
|
||||
}))
|
||||
|
||||
const handlers = vi.hoisted(
|
||||
() => new Map<string, (event: unknown, params: unknown) => Promise<unknown>>()
|
||||
)
|
||||
|
||||
vi.mock('electron', async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>()
|
||||
return {
|
||||
...actual,
|
||||
ipcMain: {
|
||||
handle: vi.fn((channel: string, fn: (event: unknown, params: unknown) => Promise<unknown>) => {
|
||||
handlers.set(channel, fn)
|
||||
}),
|
||||
on: vi.fn(),
|
||||
removeHandler: vi.fn()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||
configGet: vi.fn(() => 'local'),
|
||||
configSet: vi.fn()
|
||||
}))
|
||||
|
||||
const mockLocalLLM = vi.hoisted(() => ({
|
||||
processText: vi.fn(),
|
||||
cancelGeneration: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/LocalLLMService', () => ({
|
||||
getLocalLLMService: () => mockLocalLLM
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/PremiumLLMService', () => ({
|
||||
getPremiumLLMService: () => ({ cancelGeneration: vi.fn(), on: vi.fn(), off: vi.fn() })
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/OnlineLLMService', () => ({
|
||||
getOnlineLLMService: () => mockLocalLLM
|
||||
}))
|
||||
|
||||
async function invokeProcess(params: LLMProcessParams): Promise<unknown> {
|
||||
const handler = handlers.get(IPC_CHANNELS.LLM.PROCESS)
|
||||
if (!handler) throw new Error('LLM.PROCESS handler not registered')
|
||||
return handler({}, params)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
handlers.clear()
|
||||
mockLocalLLM.processText.mockResolvedValue('LLM 결과')
|
||||
|
||||
const mod = await import('../../../src/main/ipc/llm-handlers')
|
||||
mod.registerLLMHandlers()
|
||||
})
|
||||
|
||||
describe('LLM.PROCESS — 지시문 인자 정규화', () => {
|
||||
it('custom 액션의 지시문을 시스템 프롬프트로, 입력 텍스트를 처리 대상으로 넘긴다', async () => {
|
||||
await invokeProcess({
|
||||
text: '오늘 배포 일정을 정했습니다',
|
||||
action: 'custom',
|
||||
customPrompt: '다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.'
|
||||
})
|
||||
|
||||
const [text, action, , systemPrompt] = mockLocalLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('오늘 배포 일정을 정했습니다')
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBe('다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.')
|
||||
})
|
||||
|
||||
it('{{targetLanguage}}를 치환해 시스템 프롬프트로 넘긴다', async () => {
|
||||
await invokeProcess({
|
||||
text: '안녕하세요',
|
||||
action: 'custom',
|
||||
customPrompt: '다음 텍스트를 {{targetLanguage}}로 번역해주세요.'
|
||||
})
|
||||
|
||||
const [text, , , systemPrompt] = mockLocalLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('안녕하세요')
|
||||
expect(systemPrompt).toBe('다음 텍스트를 English로 번역해주세요.')
|
||||
expect(systemPrompt).not.toContain('{{')
|
||||
})
|
||||
|
||||
it('{{userPrompt}}를 입력 텍스트로 치환한다', async () => {
|
||||
await invokeProcess({
|
||||
text: '피보나치 짜줘',
|
||||
action: 'custom',
|
||||
customPrompt: '{{userPrompt}}'
|
||||
})
|
||||
|
||||
const [text, , , systemPrompt] = mockLocalLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('피보나치 짜줘')
|
||||
expect(systemPrompt).toBe('피보나치 짜줘')
|
||||
})
|
||||
|
||||
it('{{text}}를 쓰는 지시문은 치환 결과를 처리 대상 텍스트로 넘긴다', async () => {
|
||||
await invokeProcess({
|
||||
text: '가 나 다',
|
||||
action: 'custom',
|
||||
customPrompt: '아래를 불릿으로 정리해줘:\n{{text}}'
|
||||
})
|
||||
|
||||
const [text, , , systemPrompt] = mockLocalLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('아래를 불릿으로 정리해줘:\n가 나 다')
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('명시적 targetLanguage를 그대로 쓴다', async () => {
|
||||
await invokeProcess({
|
||||
text: '안녕',
|
||||
action: 'custom',
|
||||
customPrompt: '{{targetLanguage}}로 번역해줘.',
|
||||
targetLanguage: '프랑스어'
|
||||
})
|
||||
|
||||
const [, , targetLanguage, systemPrompt] = mockLocalLLM.processText.mock.calls[0]
|
||||
|
||||
expect(targetLanguage).toBe('프랑스어')
|
||||
expect(systemPrompt).toBe('프랑스어로 번역해줘.')
|
||||
})
|
||||
|
||||
it('일반 액션은 지시문 정규화를 거치지 않고 그대로 전달한다', async () => {
|
||||
await invokeProcess({ text: '다듬어줘 이 문장', action: 'refine' })
|
||||
|
||||
const [text, action, targetLanguage, systemPrompt] = mockLocalLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('다듬어줘 이 문장')
|
||||
expect(action).toBe('refine')
|
||||
expect(targetLanguage).toBeUndefined()
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('실패를 성공으로 위장하지 않는다', async () => {
|
||||
mockLocalLLM.processText.mockRejectedValue(new Error('Ollama unreachable'))
|
||||
|
||||
const result = (await invokeProcess({ text: '아무 말', action: 'refine' })) as {
|
||||
success: boolean
|
||||
error: { message: string }
|
||||
}
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error.message).toContain('Ollama unreachable')
|
||||
})
|
||||
})
|
||||
174
apps/desktop/tests/main/services/ChainService.test.ts
Normal file
174
apps/desktop/tests/main/services/ChainService.test.ts
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
// tests/main/services/ChainService.test.ts
|
||||
// 체인 스텝이 지시문을 시스템 프롬프트로 넘기고 플레이스홀더를 치환하는지 잠근다.
|
||||
// 인자 자리는 원래 옳았으나 치환이 없어 {{targetLanguage}} 등이 그대로 새어나갔다.
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import type { LLMChain } from '@d3ro/core/types'
|
||||
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
|
||||
}))
|
||||
|
||||
const config = vi.hoisted(() => ({ values: {} as Record<string, unknown> }))
|
||||
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||
configGet: vi.fn((key: string) => config.values[key]),
|
||||
configSet: vi.fn((key: string, value: unknown) => {
|
||||
config.values[key] = value
|
||||
})
|
||||
}))
|
||||
|
||||
const instructionStore = vi.hoisted(() => ({
|
||||
byId: {} as Record<string, { id: string; name: string; prompt: string }>
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/CustomInstructionService', () => ({
|
||||
getCustomInstructionService: () => ({
|
||||
getById: (id: string) => instructionStore.byId[id] ?? null
|
||||
})
|
||||
}))
|
||||
|
||||
const mockLLM = vi.hoisted(() => ({
|
||||
processText: vi.fn(),
|
||||
cancelGeneration: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/PremiumLLMService', () => ({
|
||||
getPremiumLLMService: () => mockLLM
|
||||
}))
|
||||
|
||||
let getChainService: typeof import('../../../src/main/services/ChainService')['getChainService']
|
||||
|
||||
function chain(steps: Array<{ instructionId: string }>): LLMChain {
|
||||
return {
|
||||
id: 'chain-1',
|
||||
name: '테스트 체인',
|
||||
steps: steps.map((s) => ({ instructionId: s.instructionId, inputSource: 'previous' as const })),
|
||||
createdAt: 0,
|
||||
updatedAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
config.values = {}
|
||||
instructionStore.byId = {}
|
||||
mockLLM.processText.mockResolvedValue('LLM 결과')
|
||||
|
||||
const mod = await import('../../../src/main/services/ChainService')
|
||||
mod.resetChainServiceForTests()
|
||||
getChainService = mod.getChainService
|
||||
})
|
||||
|
||||
describe('ChainService.execute — 지시문 인자 전달', () => {
|
||||
it('지시문을 시스템 프롬프트로, 스텝 입력을 처리 대상 텍스트로 넘긴다', async () => {
|
||||
instructionStore.byId['builtin-summarize'] = {
|
||||
id: 'builtin-summarize',
|
||||
name: '요약',
|
||||
prompt: '다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.'
|
||||
}
|
||||
config.values.llmChains = [chain([{ instructionId: 'builtin-summarize' }])]
|
||||
|
||||
const svc = getChainService()
|
||||
svc.initialize()
|
||||
await svc.execute('chain-1', '오늘 배포 일정을 정했습니다')
|
||||
|
||||
expect(mockLLM.processText).toHaveBeenCalledTimes(1)
|
||||
const [text, action, targetLanguage, systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('오늘 배포 일정을 정했습니다')
|
||||
expect(action).toBe('custom')
|
||||
expect(targetLanguage).toBeUndefined()
|
||||
expect(systemPrompt).toBe('다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.')
|
||||
})
|
||||
|
||||
it('{{targetLanguage}}를 치환해 시스템 프롬프트로 넘긴다', async () => {
|
||||
instructionStore.byId['builtin-translate'] = {
|
||||
id: 'builtin-translate',
|
||||
name: '번역',
|
||||
prompt: '다음 텍스트를 {{targetLanguage}}로 번역해주세요.\n자연스럽고 정확한 번역만 출력하세요.'
|
||||
}
|
||||
config.values.llmChains = [chain([{ instructionId: 'builtin-translate' }])]
|
||||
|
||||
const svc = getChainService()
|
||||
svc.initialize()
|
||||
await svc.execute('chain-1', '안녕하세요')
|
||||
|
||||
const [text, , , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('안녕하세요')
|
||||
expect(systemPrompt).toBe(
|
||||
'다음 텍스트를 English로 번역해주세요.\n자연스럽고 정확한 번역만 출력하세요.'
|
||||
)
|
||||
expect(systemPrompt).not.toContain('{{')
|
||||
})
|
||||
|
||||
it('{{userPrompt}}를 스텝 입력으로 치환한다', async () => {
|
||||
instructionStore.byId['builtin-free-prompt'] = {
|
||||
id: 'builtin-free-prompt',
|
||||
name: '자유 프롬프트',
|
||||
prompt: '{{userPrompt}}'
|
||||
}
|
||||
config.values.llmChains = [chain([{ instructionId: 'builtin-free-prompt' }])]
|
||||
|
||||
const svc = getChainService()
|
||||
svc.initialize()
|
||||
await svc.execute('chain-1', '피보나치 짜줘')
|
||||
|
||||
const [text, , , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('피보나치 짜줘')
|
||||
expect(systemPrompt).toBe('피보나치 짜줘')
|
||||
})
|
||||
|
||||
it('{{text}}를 쓰는 지시문은 치환 결과를 처리 대상 텍스트로 넘긴다', async () => {
|
||||
instructionStore.byId['user-bullets'] = {
|
||||
id: 'user-bullets',
|
||||
name: '불릿 정리',
|
||||
prompt: '아래를 불릿으로 정리해줘:\n{{text}}'
|
||||
}
|
||||
config.values.llmChains = [chain([{ instructionId: 'user-bullets' }])]
|
||||
|
||||
const svc = getChainService()
|
||||
svc.initialize()
|
||||
await svc.execute('chain-1', '가 나 다')
|
||||
|
||||
const [text, action, , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe('아래를 불릿으로 정리해줘:\n가 나 다')
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('두 번째 스텝은 이전 스텝 출력을 처리 대상 텍스트로 받는다', async () => {
|
||||
instructionStore.byId['builtin-summarize'] = {
|
||||
id: 'builtin-summarize',
|
||||
name: '요약',
|
||||
prompt: '요약해줘.'
|
||||
}
|
||||
instructionStore.byId['builtin-translate'] = {
|
||||
id: 'builtin-translate',
|
||||
name: '번역',
|
||||
prompt: '{{targetLanguage}}로 번역해줘.'
|
||||
}
|
||||
config.values.llmChains = [
|
||||
chain([{ instructionId: 'builtin-summarize' }, { instructionId: 'builtin-translate' }])
|
||||
]
|
||||
mockLLM.processText.mockResolvedValueOnce('요약된 텍스트')
|
||||
|
||||
const svc = getChainService()
|
||||
svc.initialize()
|
||||
await svc.execute('chain-1', '긴 원문')
|
||||
|
||||
expect(mockLLM.processText).toHaveBeenCalledTimes(2)
|
||||
|
||||
const [firstText, , , firstSystem] = mockLLM.processText.mock.calls[0]
|
||||
expect(firstText).toBe('긴 원문')
|
||||
expect(firstSystem).toBe('요약해줘.')
|
||||
|
||||
const [secondText, , , secondSystem] = mockLLM.processText.mock.calls[1]
|
||||
expect(secondText).toBe('요약된 텍스트')
|
||||
expect(secondSystem).toBe('English로 번역해줘.')
|
||||
})
|
||||
})
|
||||
|
|
@ -60,15 +60,49 @@ vi.mock('../../../src/main/services/KeyBindingService', () => ({
|
|||
getKeyBindingService: () => mockKeyBinding
|
||||
}))
|
||||
|
||||
const CONFIG_DEFAULTS: Record<string, unknown> = {
|
||||
sttModelId: 'base',
|
||||
defaultLLMAction: 'refine',
|
||||
ollamaServerUrl: 'http://localhost:11434',
|
||||
llmModelId: 'gemma4:e4b'
|
||||
}
|
||||
|
||||
const config = vi.hoisted(() => ({ values: {} as Record<string, unknown> }))
|
||||
|
||||
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]
|
||||
configGet: vi.fn((key: string) => config.values[key])
|
||||
}))
|
||||
|
||||
const instructionStore = vi.hoisted(() => ({
|
||||
byId: {} as Record<string, { id: string; name: string; prompt: string }>
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/CustomInstructionService', () => ({
|
||||
getCustomInstructionService: () => ({
|
||||
getById: (id: string) => instructionStore.byId[id] ?? null
|
||||
})
|
||||
}))
|
||||
|
||||
// 음성 단축키(두 번째 진입점) — 기본은 비활성
|
||||
const voiceCommand = vi.hoisted(() => ({
|
||||
enabled: false,
|
||||
instructionId: null as string | null,
|
||||
cleanedText: ''
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/VoiceCommandService', () => ({
|
||||
getVoiceCommandService: () => ({
|
||||
isEnabled: () => voiceCommand.enabled,
|
||||
match: (text: string) =>
|
||||
voiceCommand.enabled && voiceCommand.instructionId
|
||||
? {
|
||||
matched: true,
|
||||
ruleId: 'rule-1',
|
||||
instructionId: voiceCommand.instructionId,
|
||||
cleanedText: voiceCommand.cleanedText || text,
|
||||
matchedKeyword: '번역'
|
||||
}
|
||||
: { matched: false, ruleId: null, instructionId: null, cleanedText: text, matchedKeyword: null }
|
||||
})
|
||||
}))
|
||||
|
||||
|
|
@ -97,6 +131,11 @@ beforeEach(async () => {
|
|||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
audioBus.removeAllListeners()
|
||||
config.values = { ...CONFIG_DEFAULTS }
|
||||
instructionStore.byId = {}
|
||||
voiceCommand.enabled = false
|
||||
voiceCommand.instructionId = null
|
||||
voiceCommand.cleanedText = ''
|
||||
mockSTT.initialize.mockResolvedValue(undefined as never)
|
||||
mockSTT.transcribe.mockResolvedValue({
|
||||
text: '테스트 전사',
|
||||
|
|
@ -223,6 +262,211 @@ describe('VoiceModeService', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('LLM 후처리 인자 전달', () => {
|
||||
const TRANSCRIPT = '회의 끝나고 배포하자'
|
||||
|
||||
/** 한 세션을 끝까지 돌린다. */
|
||||
async function runSession(): Promise<void> {
|
||||
mockSTT.transcribe.mockResolvedValue({
|
||||
text: TRANSCRIPT,
|
||||
segments: [],
|
||||
language: 'ko',
|
||||
duration: 2,
|
||||
processingTime: 50,
|
||||
} as never)
|
||||
|
||||
const svc = getVoiceModeService()
|
||||
const settled = new Promise<void>((resolve) => {
|
||||
svc.once('session-completed', () => resolve())
|
||||
svc.once('session-cancelled', () => resolve())
|
||||
})
|
||||
|
||||
await svc.startSession('dictation')
|
||||
audioBus.emit('audio-data', { buffer: Buffer.alloc(16000 * 2) })
|
||||
await new Promise((r) => setTimeout(r, 850))
|
||||
await svc.stopSession()
|
||||
await Promise.race([settled, new Promise((r) => setTimeout(r, 2000))])
|
||||
}
|
||||
|
||||
function registerInstruction(inst: { id: string; name: string; prompt: string }): void {
|
||||
instructionStore.byId[inst.id] = inst
|
||||
}
|
||||
|
||||
// ── 고친 경로: 커스텀 지시문 ───────────────────────────
|
||||
describe('커스텀 지시문 경로 (고친 경로)', () => {
|
||||
it('{{text}} 없는 지시문은 시스템 프롬프트로, 전사 텍스트는 처리 대상으로 전달한다', async () => {
|
||||
registerInstruction({
|
||||
id: 'builtin-summarize',
|
||||
name: '요약',
|
||||
prompt: '다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.\n요약문만 출력하세요.',
|
||||
})
|
||||
config.values.defaultLLMAction = 'custom'
|
||||
config.values.activeInstructionId = 'builtin-summarize'
|
||||
|
||||
await runSession()
|
||||
|
||||
expect(mockLLM.processText).toHaveBeenCalledTimes(1)
|
||||
const [text, action, targetLanguage, systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(action).toBe('custom')
|
||||
expect(targetLanguage).toBeUndefined()
|
||||
expect(systemPrompt).toBe(
|
||||
'다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.\n요약문만 출력하세요.',
|
||||
)
|
||||
})
|
||||
|
||||
it('builtin-translate의 {{targetLanguage}}를 치환해 시스템 프롬프트로 전달한다', async () => {
|
||||
registerInstruction({
|
||||
id: 'builtin-translate',
|
||||
name: '번역',
|
||||
prompt:
|
||||
'다음 텍스트를 {{targetLanguage}}로 번역해주세요.\n자연스럽고 정확한 번역만 출력하세요.',
|
||||
})
|
||||
config.values.defaultLLMAction = 'custom'
|
||||
config.values.activeInstructionId = 'builtin-translate'
|
||||
|
||||
await runSession()
|
||||
const [text, , , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(systemPrompt).toContain('English로 번역')
|
||||
expect(systemPrompt).not.toContain('{{')
|
||||
})
|
||||
|
||||
it('builtin-free-prompt의 {{userPrompt}}를 전사 텍스트로 치환한다', async () => {
|
||||
registerInstruction({
|
||||
id: 'builtin-free-prompt',
|
||||
name: '자유 프롬프트',
|
||||
prompt: '{{userPrompt}}',
|
||||
})
|
||||
config.values.defaultLLMAction = 'custom'
|
||||
config.values.activeInstructionId = 'builtin-free-prompt'
|
||||
|
||||
await runSession()
|
||||
const [text, , , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(systemPrompt).toBe(TRANSCRIPT)
|
||||
})
|
||||
|
||||
it('{{text}}를 쓰는 사용자 정의 지시문은 치환 결과를 처리 대상 텍스트로 넘긴다', async () => {
|
||||
registerInstruction({
|
||||
id: 'user-bullets',
|
||||
name: '불릿 정리',
|
||||
prompt: '아래 내용을 불릿으로 정리해줘:\n{{text}}',
|
||||
})
|
||||
config.values.defaultLLMAction = 'custom'
|
||||
config.values.activeInstructionId = 'user-bullets'
|
||||
|
||||
await runSession()
|
||||
const [text, action, , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(`아래 내용을 불릿으로 정리해줘:\n${TRANSCRIPT}`)
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('지시문을 찾지 못하면 전사 텍스트만 전달한다', async () => {
|
||||
config.values.defaultLLMAction = 'custom'
|
||||
config.values.activeInstructionId = 'does-not-exist'
|
||||
|
||||
await runSession()
|
||||
const [text, action, , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// ── 두 번째 진입점: 음성 단축키 ────────────────────────
|
||||
describe('음성 단축키 진입점 (overrideInstructionId)', () => {
|
||||
it('음성 명령으로 지목된 지시문도 시스템 프롬프트로 전달한다', async () => {
|
||||
registerInstruction({
|
||||
id: 'builtin-translate',
|
||||
name: '번역',
|
||||
prompt: '다음 텍스트를 {{targetLanguage}}로 번역해주세요.',
|
||||
})
|
||||
voiceCommand.enabled = true
|
||||
voiceCommand.instructionId = 'builtin-translate'
|
||||
voiceCommand.cleanedText = '회의 끝나고 배포하자'
|
||||
config.values.defaultLLMAction = 'refine'
|
||||
|
||||
await runSession()
|
||||
const [text, action, , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBe('다음 텍스트를 English로 번역해주세요.')
|
||||
})
|
||||
|
||||
it("defaultLLMAction이 'none'이어도 음성 명령은 스킵되지 않는다", async () => {
|
||||
registerInstruction({
|
||||
id: 'builtin-summarize',
|
||||
name: '요약',
|
||||
prompt: '다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.',
|
||||
})
|
||||
voiceCommand.enabled = true
|
||||
voiceCommand.instructionId = 'builtin-summarize'
|
||||
config.values.defaultLLMAction = 'none'
|
||||
|
||||
await runSession()
|
||||
|
||||
expect(mockLLM.processText).toHaveBeenCalledTimes(1)
|
||||
const [text, action, , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBe('다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.')
|
||||
})
|
||||
|
||||
it("음성 명령이 없으면 'none'은 기존대로 LLM을 건너뛴다", async () => {
|
||||
config.values.defaultLLMAction = 'none'
|
||||
|
||||
await runSession()
|
||||
|
||||
expect(mockLLM.processText).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// ── 안 고친 경로: 일반 액션이 원래 맞았고 계속 맞다 ────
|
||||
describe('일반 액션 경로 (수정 대상 아님 — 계속 정상이어야 한다)', () => {
|
||||
it.each(['refine', 'summarize', 'grammar', 'expand'])(
|
||||
"'%s' 액션은 전사 텍스트를 text로 넘기고 customPrompt를 넘기지 않는다",
|
||||
async (action) => {
|
||||
config.values.defaultLLMAction = action
|
||||
// 활성 지시문이 있어도 일반 액션 경로는 지시문을 타지 않아야 한다.
|
||||
registerInstruction({ id: 'builtin-summarize', name: '요약', prompt: '요약해줘' })
|
||||
config.values.activeInstructionId = 'builtin-summarize'
|
||||
|
||||
await runSession()
|
||||
|
||||
expect(mockLLM.processText).toHaveBeenCalledTimes(1)
|
||||
const [text, passedAction, targetLanguage, systemPrompt] =
|
||||
mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(passedAction).toBe(action)
|
||||
expect(targetLanguage).toBeUndefined()
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
},
|
||||
)
|
||||
|
||||
it("'translate' 액션은 대상 언어를 함께 넘긴다", async () => {
|
||||
config.values.defaultLLMAction = 'translate'
|
||||
|
||||
await runSession()
|
||||
const [text, action, targetLanguage, systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(action).toBe('translate')
|
||||
expect(targetLanguage).toBe('English')
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getState', () => {
|
||||
it('현재 상태를 VoiceState 형태로 반환한다', () => {
|
||||
const svc = getVoiceModeService()
|
||||
|
|
|
|||
169
apps/desktop/tests/main/services/llm-prompts.test.ts
Normal file
169
apps/desktop/tests/main/services/llm-prompts.test.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
// tests/main/services/llm-prompts.test.ts
|
||||
// 플레이스홀더 치환 + 지시문 인자 배치 회귀 테스트.
|
||||
// 지시문이 시스템 프롬프트가 아닌 처리 대상 텍스트 자리로 들어가 LLM이
|
||||
// 지시문 자체를 다듬어 반환하던 버그를 막는다.
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
|
||||
const mockLogger = vi.hoisted(() => ({
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => mockLogger,
|
||||
}))
|
||||
|
||||
import {
|
||||
renderInstructionPrompt,
|
||||
buildInstructionInvocation,
|
||||
resolveSystemPrompt,
|
||||
DEFAULT_TARGET_LANGUAGE,
|
||||
BASE_SYSTEM_PROMPTS,
|
||||
} from '../../../src/main/services/llm-prompts'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('renderInstructionPrompt', () => {
|
||||
it('{{text}}를 사용자 텍스트로 치환한다', () => {
|
||||
const result = renderInstructionPrompt('요약해줘:\n{{text}}', { text: '안녕하세요' })
|
||||
expect(result).toBe('요약해줘:\n안녕하세요')
|
||||
})
|
||||
|
||||
it('{{userPrompt}}를 사용자 텍스트로 치환한다 (자유 프롬프트 프리셋)', () => {
|
||||
const result = renderInstructionPrompt('{{userPrompt}}', { text: '오늘 날씨 알려줘' })
|
||||
expect(result).toBe('오늘 날씨 알려줘')
|
||||
})
|
||||
|
||||
it('{{targetLanguage}}를 주어진 대상 언어로 치환한다', () => {
|
||||
const result = renderInstructionPrompt('{{targetLanguage}}로 번역해줘', {
|
||||
text: '안녕',
|
||||
targetLanguage: '일본어',
|
||||
})
|
||||
expect(result).toBe('일본어로 번역해줘')
|
||||
})
|
||||
|
||||
it('대상 언어가 없으면 기본값으로 치환한다', () => {
|
||||
const result = renderInstructionPrompt('{{targetLanguage}}로 번역해줘', { text: '안녕' })
|
||||
expect(result).toBe(`${DEFAULT_TARGET_LANGUAGE}로 번역해줘`)
|
||||
expect(result).not.toContain('{{')
|
||||
})
|
||||
|
||||
it('같은 플레이스홀더가 여러 번 나와도 모두 치환한다', () => {
|
||||
const result = renderInstructionPrompt('{{text}} / {{text}}', { text: 'A' })
|
||||
expect(result).toBe('A / A')
|
||||
})
|
||||
|
||||
it('치환되지 않고 남은 플레이스홀더는 경고로 남기되 동작은 계속한다', () => {
|
||||
const result = renderInstructionPrompt('{{text}}를 {{unknownVar}}로 처리해줘', { text: 'A' })
|
||||
|
||||
expect(result).toBe('A를 {{unknownVar}}로 처리해줘')
|
||||
expect(mockLogger.warn).toHaveBeenCalledTimes(1)
|
||||
expect(mockLogger.warn.mock.calls[0][0]).toContain('unknownVar')
|
||||
})
|
||||
|
||||
it('플레이스홀더가 모두 치환되면 경고하지 않는다', () => {
|
||||
renderInstructionPrompt('{{text}}', { text: 'A' })
|
||||
expect(mockLogger.warn).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInstructionInvocation', () => {
|
||||
it('{{text}}가 없는 지시문은 시스템 프롬프트로, 사용자 텍스트는 처리 대상으로 보낸다', () => {
|
||||
// builtin-summarize 와 같은 모양 — 플레이스홀더 없음
|
||||
const invocation = buildInstructionInvocation(
|
||||
'다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.',
|
||||
'오늘 회의에서 배포 일정을 정했습니다',
|
||||
)
|
||||
|
||||
expect(invocation.text).toBe('오늘 회의에서 배포 일정을 정했습니다')
|
||||
expect(invocation.systemPrompt).toBe('다음 텍스트의 핵심 내용을 3줄 이내로 요약해주세요.')
|
||||
})
|
||||
|
||||
it('builtin-translate 지시문은 대상 언어를 치환해 시스템 프롬프트로 보낸다', () => {
|
||||
const invocation = buildInstructionInvocation(
|
||||
'다음 텍스트를 {{targetLanguage}}로 번역해주세요.\n자연스럽고 정확한 번역만 출력하세요.',
|
||||
'안녕하세요',
|
||||
)
|
||||
|
||||
expect(invocation.text).toBe('안녕하세요')
|
||||
expect(invocation.systemPrompt).toBe(
|
||||
`다음 텍스트를 ${DEFAULT_TARGET_LANGUAGE}로 번역해주세요.\n자연스럽고 정확한 번역만 출력하세요.`,
|
||||
)
|
||||
expect(invocation.systemPrompt).not.toContain('{{')
|
||||
})
|
||||
|
||||
it('builtin-free-prompt는 사용자 텍스트를 시스템 프롬프트로 보낸다', () => {
|
||||
const invocation = buildInstructionInvocation('{{userPrompt}}', '파이썬으로 피보나치 짜줘')
|
||||
|
||||
expect(invocation.text).toBe('파이썬으로 피보나치 짜줘')
|
||||
expect(invocation.systemPrompt).toBe('파이썬으로 피보나치 짜줘')
|
||||
})
|
||||
|
||||
it('{{text}}를 쓰는 지시문은 하위 호환을 위해 치환 결과를 처리 대상 텍스트로 보낸다', () => {
|
||||
const invocation = buildInstructionInvocation('아래를 불릿으로 정리해줘:\n{{text}}', '가 나 다')
|
||||
|
||||
expect(invocation.text).toBe('아래를 불릿으로 정리해줘:\n가 나 다')
|
||||
expect(invocation.systemPrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('명시적 대상 언어를 그대로 사용한다', () => {
|
||||
const invocation = buildInstructionInvocation(
|
||||
'{{targetLanguage}}로 번역해줘',
|
||||
'안녕',
|
||||
'프랑스어',
|
||||
)
|
||||
|
||||
expect(invocation.systemPrompt).toBe('프랑스어로 번역해줘')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveSystemPrompt', () => {
|
||||
it("action 'custom'에 프롬프트가 있으면 그대로 시스템 프롬프트로 쓴다", () => {
|
||||
expect(resolveSystemPrompt('custom', undefined, '전문 용어를 풀어써라')).toBe(
|
||||
'전문 용어를 풀어써라',
|
||||
)
|
||||
expect(mockLogger.warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("action 'custom'인데 프롬프트가 비어 있으면 조용히 떨어지지 않고 경고한다", () => {
|
||||
const result = resolveSystemPrompt('custom', undefined, undefined)
|
||||
|
||||
expect(mockLogger.warn).toHaveBeenCalledTimes(1)
|
||||
expect(mockLogger.warn.mock.calls[0][0]).toContain('custom')
|
||||
expect(result).toBe(resolveSystemPrompt('refine'))
|
||||
})
|
||||
|
||||
it("공백뿐인 custom 프롬프트도 비어 있는 것으로 보고 경고한다", () => {
|
||||
resolveSystemPrompt('custom', undefined, ' ')
|
||||
expect(mockLogger.warn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('translate 액션은 대상 언어를 치환한다', () => {
|
||||
expect(resolveSystemPrompt('translate', '독일어')).toContain('독일어로 번역')
|
||||
expect(resolveSystemPrompt('translate')).toContain(`${DEFAULT_TARGET_LANGUAGE}로 번역`)
|
||||
})
|
||||
|
||||
// 수정 대상이 아닌 일반 액션들이 각자의 프롬프트로 해석되는지 잠근다.
|
||||
// 이들이 refine으로 조용히 폴백하면 커스텀 경로와 같은 사고가 난다.
|
||||
it.each(['refine', 'summarize', 'grammar', 'expand'] as const)(
|
||||
"'%s' 액션은 자기 자신의 시스템 프롬프트로 해석된다",
|
||||
(action) => {
|
||||
const resolved = resolveSystemPrompt(action)
|
||||
|
||||
expect(resolved).toBe(BASE_SYSTEM_PROMPTS[action])
|
||||
expect(resolved).not.toContain('{{')
|
||||
expect(mockLogger.warn).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('refine 이외의 일반 액션이 refine 프롬프트로 폴백하지 않는다', () => {
|
||||
for (const action of ['summarize', 'grammar', 'expand'] as const) {
|
||||
expect(resolveSystemPrompt(action)).not.toBe(BASE_SYSTEM_PROMPTS.refine)
|
||||
}
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue