// tests/integration/suggestion-quality.ollama.test.ts // // 다음 문장 제안 품질 프로브 — 실제 Ollama 모델로 시나리오별 제안을 뽑아 비교한다. // 자동 판정은 최소한(비어 있음·되풀이·사실 위반)만 하고, 결과 표를 사람이 읽는다. // // 실행 (Ollama 에 모델이 떠 있어야 한다): // D3RO_SUGGESTION_PROBE=1 [D3RO_SUGGESTION_PROBE_MODEL=gemma4:e4b] [D3RO_SUGGESTION_PROBE_OUT=결과.md] \ // npx vitest run --config vitest.config.ts tests/integration/suggestion-quality.ollama.test.ts import { describe, it, expect, vi } from 'vitest' import { writeFileSync } from 'fs' vi.mock('../../src/main/services/LoggerService', () => ({ getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) })) import { buildSuggestionPrompt, type RecentWriteHint } from '../../src/main/services/llm-prompts' import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template' import { extractContinuation, joinSuggestion, parseSuggestionCandidates } from '@d3ro/core/input-intelligence' import { splitSentences } from '@d3ro/core/personal-graph' import { findUnsupportedFacts } from '@d3ro/core/writing-context' const ENABLED = process.env.D3RO_SUGGESTION_PROBE === '1' const MODEL = process.env.D3RO_SUGGESTION_PROBE_MODEL ?? 'gemma4:e4b' const OLLAMA = process.env.D3RO_SUGGESTION_PROBE_URL ?? 'http://127.0.0.1:11434' const SESSION_WINDOW = 400 interface Scenario { name: string text: string app?: string title?: string recent?: RecentWriteHint[] followUps?: string[] related?: string[] /** 제안에 들어 있으면 안 되는 표현 (사실 위반 등) */ forbid?: RegExp /** 제안에 들어 있어야 하는 표현 (사실 회상) */ expect?: RegExp } const LONG_PLAN = `D3RO 보이스 2.0 출시 계획 공유드립니다. 출시일은 11월 15일(토)로 확정되었고, 가격은 Pro 월 2,900원, Pro+ 월 8,900원으로 유지합니다. 마케팅은 김민수 대리님이 맡고, 서버 이전은 박준호 책임님이 10월 31일까지 마무리하기로 했습니다. 이번 버전의 핵심은 세 가지입니다. 첫째, 받아쓰기 정확도를 높이기 위해 음성 인식 모델을 large-v3-turbo로 바꿉니다. 둘째, 다음 문장 제안을 정식 기능으로 공개합니다. 셋째, 모바일 앱과 기록을 실시간으로 동기화합니다. 베타 테스트는 다음 주 월요일부터 2주간 진행하며, 참여자는 120명 정도로 예상합니다. 피드백은 매주 금요일 오후 4시에 모아서 정리하겠습니다. 위험 요소로는 GPU 메모리가 부족한 PC에서 모델 로딩이 느린 문제가 있습니다. 이 부분은 경량 모델 옵션을 두는 방향으로 검토 중입니다. ` const SCENARIOS: Scenario[] = [ { name: '긴 문서 사실 회상 (출시일)', text: `${LONG_PLAN}정리하면, 출시는 `, app: 'Notion', title: '2.0 출시 계획', expect: /11월 ?15일/u }, { name: '긴 문서 사실 회상 (담당자)', text: `${LONG_PLAN}마케팅 일정은 `, app: 'Notion', title: '2.0 출시 계획', forbid: /박준호/u }, { name: '격식 메일 마저 쓰기', text: '팀장님 안녕하세요. 어제 말씀하신 분기 보고서 초안을 정리했습니다. 첨부 파일 검토해 보시고', app: 'Outlook', title: '분기 보고서 초안 - 메시지' }, { name: '격식 메일 마저 쓰기 (끝 공백)', text: '팀장님 안녕하세요. 어제 말씀하신 분기 보고서 초안을 정리했습니다. 첨부 파일 검토해 보시고 ', app: 'Outlook', title: '분기 보고서 초안 - 메시지' }, { name: '단어 중간 (회의실)', text: '내일 오후 3시에 회의실', app: 'Slack', title: '#product' }, { name: '카톡 반말 + 앞 메시지', text: 'ㅇㅋ 그럼 나도 ', app: 'KakaoTalk', title: '민수', recent: [ { text: '야 내일 몇 시에 보기로 했지?', ageMs: 240_000 }, { text: '나 3시쯤 강남역 도착할 듯ㅋㅋ', ageMs: 120_000 } ], forbid: /(습니다|세요)/u }, { // 카카오톡 입력칸(RichEdit)은 값 끝에 \r 을 붙여 준다 (2026-10-03 실측: 후보 10회 모두 정제 후 빈 값) name: '카톡 RichEdit 끝 \\r — 마저 쓰기', text: '오늘 저녁에 시간 되면\r', app: 'KakaoTalk.exe', title: '민수' }, { name: '카톡 RichEdit 끝 \\r — 띄어 쓴 뒤', text: 'ㅇㅋ 그럼 나도 \r', app: 'KakaoTalk.exe', title: '민수', recent: [{ text: '야 내일 몇 시에 보기로 했지?', ageMs: 60_000 }] }, { name: '카톡 짧은 채팅 (\\r 없음)', text: '오늘 저녁에 시간 되면', app: 'KakaoTalk.exe', title: '민수' }, { name: '슬랙 개발 마저 쓰기', text: 'PR 올렸습니다. 리뷰 부탁드려요. 테스트는 로컬에서 다 통과했고 CI는 ', app: 'Slack', title: '#dev-desktop' }, { name: '회의록 목록 다음 줄', text: '회의록 - 10월 3일\n참석: 김민수, 이지은, 박준호\n- 배포 일정: 10월 7일 (화)\n- 담당: ', app: 'Notepad', title: '회의록.txt' }, { name: '영어 단어 중간', text: 'Hi Sarah, thanks for the quick re', app: 'Gmail', title: 'Re: Q3 report' }, { name: '영어 다음 문장', text: 'Hi Sarah,\n\nThanks for sending over the Q3 report. I had a chance to review it this morning.', app: 'Gmail', title: 'Re: Q3 report' }, { name: '고객 응대 해요체 다음 문장', text: '안녕하세요 고객님, 문의 주셔서 감사해요. 말씀하신 결제 오류는 확인해 보니 카드사 승인 지연 때문이었어요. ', app: 'Channel Talk', title: '상담 #4821', forbid: /(습니다|했다)\.?$/u }, { name: '검색창', text: '서울 강남 파스타 ', app: 'Chrome', title: 'Google' }, { name: '그래프 follow-up 힌트', text: '오늘 회의 자료 공유드립니다.', app: 'Slack', title: '#team', followUps: ['확인 후 의견 주시면 다음 버전에 반영하겠습니다.'] }, { name: '나열 (첫째/둘째 → 셋째)', text: '이번 개편의 목표는 세 가지입니다. 첫째, 첫 화면을 단순하게 만든다. 둘째, 기록을 빠르게 찾게 한다.', app: 'Notion', title: '디자인 개편' }, { name: '일기 반말 마저 쓰기', text: '오늘은 진짜 피곤했다. 아침부터 회의가 세 개나 있었고 점심도 ', app: 'Obsidian', title: '2026-10-03', forbid: /(습니다|세요|어요)/u } ] interface ProbeResult { scenario: string mode: 'legacy' | 'prefill' inserted: string[] latencyMs: number flags: string[] } async function generate(body: Record): Promise<{ response: string; ms: number }> { const started = Date.now() const response = await fetch(`${OLLAMA}/api/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: MODEL, stream: false, keep_alive: '30m', think: false, ...body }) }) const json = (await response.json()) as { response?: string } return { response: json.response ?? '', ms: Date.now() - started } } /** 문서 원문 → 세션 접두 (서비스와 같은 400자 창) */ function sessionPrefix(text: string): string { return text.replace(/\s+$/u, '').slice(-SESSION_WINDOW) } async function runLegacy(scenario: Scenario): Promise { // 예전 경로: 400자 창만, 지시형 프롬프트, 이어 붙일 때 이음새 정보 없음(separate). const prefix = sessionPrefix(scenario.text) const prompt = buildSuggestionPrompt({ prefix, appName: scenario.app, windowTitle: scenario.title, followUpHints: scenario.followUps, phraseHints: scenario.related, candidates: 1, maxChars: 160 }) const { response, ms } = await generate({ prompt: prompt.text, system: prompt.systemPrompt, options: { temperature: 0.3, num_predict: 64 } }) const parsed = parseSuggestionCandidates(response, prefix, 1, 160) return { scenario: scenario.name, mode: 'legacy', inserted: parsed.map((text) => joinSuggestion(scenario.text, text, 'separate')), latencyMs: ms, flags: [] } } /** 서비스와 같은 규칙: 첫 후보 온도 0.3(지어낸 사실이면 1.0 으로 1회 재시도), 채우기 온도 1.0. */ async function runPrefill(scenario: Scenario, samples: number): Promise { const prefix = sessionPrefix(scenario.text) const inserted: string[] = [] const accepted: string[] = [] let latency = 0 const sample = async (temperature: number): Promise<{ text: string | null; note: string; ms: number }> => { const prompt = buildSuggestionPrompt({ prefix, documentText: scenario.text, appName: scenario.app, windowTitle: scenario.title, recentWrites: scenario.recent, followUpHints: scenario.followUps, phraseHints: scenario.related, avoidCandidates: accepted.length > 0 ? accepted : undefined, maxChars: 160, prefill: true }) const raw = renderRawChatPrompt(MODEL, { system: prompt.systemPrompt, user: prompt.text, assistantPrefix: prompt.assistantPrefix ?? '' }) if (!raw) throw new Error(`원형 템플릿을 모르는 모델: ${MODEL}`) const { response, ms } = await generate({ prompt: raw, raw: true, options: { temperature, num_predict: 64, stop: rawChatStopSequences(MODEL) } }) const continuation = extractContinuation(response, { mode: prompt.writing.mode, prefill: prompt.assistantPrefix ?? '', writtenSentences: splitSentences(scenario.text), wordFinished: prompt.wordFinished, allowEmoji: prompt.allowEmoji, maxChars: 160 }) if (!continuation) return { text: null, note: `∅ (raw=${JSON.stringify(response.slice(0, 60))})`, ms } const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource) if (unsupported.length > 0) return { text: null, note: `✗사실 ${unsupported.join('/')} :: ${continuation.text}`, ms } return { text: joinSuggestion(scenario.text, continuation.text, continuation.joint), note: '', ms } } /** 지시형 프롬프트 + 이미 제안한 문장 목록 — 다양성 비교용 */ const sampleLegacy = async (): Promise<{ text: string | null; note: string; ms: number }> => { const prompt = buildSuggestionPrompt({ prefix, documentText: scenario.text, appName: scenario.app, windowTitle: scenario.title, recentWrites: scenario.recent, followUpHints: scenario.followUps, phraseHints: scenario.related, avoidCandidates: accepted, candidates: 1, maxChars: 160 }) const { response, ms } = await generate({ prompt: prompt.text, system: prompt.systemPrompt, options: { temperature: 0.9, num_predict: 64 } }) const text = parseSuggestionCandidates(response, prefix, 1, 160)[0] if (!text) return { text: null, note: '∅ legacy', ms } const unsupported = findUnsupportedFacts(text, prompt.factSource) if (unsupported.length > 0) return { text: null, note: `✗사실 ${unsupported.join('/')} :: ${text}`, ms } return { text: `[L] ${joinSuggestion(scenario.text, text, 'separate')}`, note: '', ms } } for (let attempt = 0; attempt < 2; attempt += 1) { const result = await sample(attempt === 0 ? 0.3 : 1.0) latency += result.ms if (result.text) { inserted.push(result.text) accepted.push(result.text.trim()) break } inserted.push(result.note) if (!result.note.startsWith('✗')) break } for (let index = 1; index < samples; index += 1) { // service(기본): 서비스와 같다 — 다음 문장 모드에서만 지시형을 번갈아 섞는다. const strategy = process.env.D3RO_SUGGESTION_PROBE_FILL ?? 'service' const mode = buildSuggestionPrompt({ prefix, documentText: scenario.text, prefill: true }).writing.mode const useLegacy = strategy === 'legacy' || (strategy === 'mixed' && index % 2 === 1) || (strategy === 'service' && mode === 'next-sentence' && accepted.length % 2 === 1) const result = useLegacy ? await sampleLegacy() : await sample(1.0) if (result.text && !accepted.includes(result.text.trim())) { inserted.push(`+ ${result.text}`) accepted.push(result.text.trim()) } else inserted.push(`(채우기 버림) ${result.text ?? result.note}`) } return { scenario: scenario.name, mode: 'prefill', inserted, latencyMs: latency, flags: [] } } function judge(scenario: Scenario, result: ProbeResult): void { // 첫 표시 후보 = 지어낸 사실로 버린 시도 다음의 첫 성공 const first = result.inserted.find((text) => !text.startsWith('✗')) ?? '' if (!first || first.startsWith('∅')) result.flags.push('빈 제안') if (scenario.expect && !scenario.expect.test(first)) result.flags.push(`기대 누락 ${scenario.expect}`) if (scenario.forbid && scenario.forbid.test(first)) result.flags.push(`금지 표현 ${scenario.forbid}`) if (/도와드릴|궁금한 점이 있으신가요|무엇을 도와/u.test(first)) result.flags.push('비서 말투') } function visible(text: string): string { return text.replace(/\n/gu, '⏎').replace(/^ /u, '␠') } describe.runIf(ENABLED)('제안 품질 프로브 (실모델)', () => { it( '기존 지시형 vs prefill 이어 쓰기', async () => { const results: ProbeResult[] = [] for (const scenario of SCENARIOS) { const legacy = await runLegacy(scenario) const prefill = await runPrefill(scenario, 4) judge(scenario, legacy) judge(scenario, prefill) results.push(legacy, prefill) } const lines = [`# 제안 품질 프로브 — ${MODEL}`, ''] for (const scenario of SCENARIOS) { lines.push(`## ${scenario.name}`, '', '```', `…${visible(scenario.text.slice(-90))}`, '```') for (const result of results.filter((item) => item.scenario === scenario.name)) { lines.push(`- **${result.mode}** (${result.latencyMs}ms)${result.flags.length ? ` ⚠ ${result.flags.join(', ')}` : ''}`) for (const text of result.inserted) lines.push(` - \`${visible(text)}\``) } lines.push('') } const summary = (mode: ProbeResult['mode']): string => { const rows = results.filter((item) => item.mode === mode) const flagged = rows.filter((item) => item.flags.length > 0).length const avg = Math.round(rows.reduce((sum, item) => sum + item.latencyMs, 0) / rows.length) return `${mode}: 경고 ${flagged}/${rows.length}, 첫 후보 평균 ${avg}ms` } lines.push('## 요약', '', `- ${summary('legacy')}`, `- ${summary('prefill')}`) const report = lines.join('\n') if (process.env.D3RO_SUGGESTION_PROBE_OUT) writeFileSync(process.env.D3RO_SUGGESTION_PROBE_OUT, report, 'utf8') expect(results.length).toBe(SCENARIOS.length * 2) }, 600_000 ) })