feat(desktop): typo auto-correct and context-aware sentence prediction
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Has been cancelled
deploy-site / deploy (push) Has been cancelled
ci / 워크스페이스 빌드 검증 (push) Has been cancelled
ci / 모바일 린트·타입·Jest (push) Has been cancelled
ci / Supabase Edge Functions + Cloudflare Worker (push) Has been cancelled
ci / .NET API 서버 테스트 (push) Has been cancelled

Typo auto-correct (INPUT-19)
- TypoCorrectionService + core typo-correction: 2-set Korean layout
  mistypes both ways, always-wrong spellings, near-misses of the user's
  frequent words, optional model check re-validated in core; applied by
  backspace N + paste and cancelled on new keys or window change.

Prediction quality (INPUT-20/21)
- gemma models are sent raw with the user's unfinished sentence pre-filled
  into the model turn, so the model truly continues the text (mid-word
  joins and spacing exact). Other models keep the instruction prompt.
- Context: text before the caret (opening lines and a fact list of names,
  dates, amounts outside the 400-char window), messages just sent in the
  same chat window (memory only, 30 min), personal-graph follow-ups and
  IDF-ranked related sentences with Korean stemming.
- Guards: first sentence only, restated-prefix stripping (also fixes the
  instruction path), repeat drop, no invented dates/names/numbers
  (one retry), plain -다 register, no emoji unless the user uses them,
  search-box keywords. Fill loop mixes instruction prompts for variety.
- Opt-in real-model probe: tests/integration/suggestion-quality.ollama.test.ts

Suggestions now actually show up
- Terminal (Claude Code): caret trust from the input line, not the whole
  screen (status line below the box blocked every keystroke); Korean
  composition counts as typing at the end; a grey placeholder filling the
  empty box at once is not user text.
- Chrome: UIA focus flicker while typing no longer resets "edited".
- KakaoTalk/RichEdit: trailing paragraph mark ignored for edit position
  and stripped so accepted text keeps its separating space.
- While the overlay is visible the suggestion shortcuts are captured so
  Ctrl+Alt+Enter no longer also types a newline; released when hidden.
- nut-js preloaded after boot (first accept waited 4.8 s).
This commit is contained in:
Yun Chan 2026-10-03 21:48:28 +09:00
parent 5ca3709b32
commit 3cac14f668
56 changed files with 4700 additions and 258 deletions

View file

@ -0,0 +1,370 @@
// 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<string, unknown>): 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<ProbeResult> {
// 예전 경로: 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<ProbeResult> {
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
)
})

View file

@ -30,7 +30,7 @@ vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => localLlm
}))
vi.mock('../../../src/main/services/InputTelemetryService', () => ({
getInputTelemetryService: () => ({ listPhrases: vi.fn(() => []), recordExternalText: vi.fn() })
getInputTelemetryService: () => ({ listPhrases: vi.fn(() => []), listRecentWrites: vi.fn(() => []), recordExternalText: vi.fn() })
}))
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
getPersonalGraphService: () => ({ retrieveContext: vi.fn(() => ({ continuations: [], related: [] })) })
@ -115,7 +115,7 @@ afterEach(async () => {
})
describe('SuggestionService warm-up', () => {
it('동시 warm-up 호출을 하나의 1토큰 요청으로 합치고 10분간 유지한다', async () => {
it('동시 warm-up 호출을 하나의 1토큰 요청으로 합치고 30분간 유지한다', async () => {
localLlm.streamGenerate.mockImplementation(async function* () {
yield 'ok'
})
@ -129,7 +129,7 @@ describe('SuggestionService warm-up', () => {
expect(localLlm.streamGenerate).toHaveBeenCalledTimes(1)
expect(localLlm.streamGenerate).toHaveBeenCalledWith(
'hi',
expect.objectContaining({ maxTokens: 1, keepAlive: '10m' })
expect.objectContaining({ maxTokens: 1, keepAlive: '30m' })
)
expect(warmingStates).toEqual([true, false])
})
@ -156,6 +156,25 @@ describe('SuggestionService warm-up', () => {
await internal._warmUpPromise
})
it('타이핑 중이면(아직 멈추지 않았어도) 식은 모델을 "준비 중" 표시 없이 미리 올린다', async () => {
localLlm.streamGenerate.mockImplementation(async function* () {
yield 'ok'
})
const { getSuggestionService } = await import('../../../src/main/services/SuggestionService')
const service = getSuggestionService()
const internal = service as unknown as InternalSuggestionService & {
_warmUpPromise: Promise<void> | null
}
// 치는 중(유휴 100ms) — 정책상 아직 제안할 때가 아니다
service.handleTypingContext({ ...context, idleMs: 100 })
expect(localLlm.streamGenerate).toHaveBeenCalledWith('hi', expect.objectContaining({ maxTokens: 1 }))
expect(service.getState().warmingUp).toBe(false)
expect(service.isPresentationActive).toBe(false)
await internal._warmUpPromise
})
it('dismiss(stale)는 진행 중인 워밍업을 취소하지 않는다', async () => {
let resolveChunk: (() => void) | null = null
localLlm.streamGenerate.mockImplementation((_text: string, options: { signal?: AbortSignal }) => {
@ -413,7 +432,8 @@ describe('SuggestionService 세션 채우기 (최대 12개, 순차 · 페이지)
it('첫 요청은 1개만 청하고, 성공하면 채우기 루프가 하나씩 최대 12개까지 채운다', async () => {
// 접두/확장 중복 판정 때문에 숫자 접미사(1, 10, 11…)는 서로를 중복으로 오판한다
// ("이어지는 문장 1" 이 "이어지는 문장 10" 의 접두이므로) — 서로소인 글자를 쓴다.
const LETTERS = 'ABCDEFGHIJKL'
// 영문 한 글자("A")는 원문에 없는 식별자로 보고 사실 검사가 버리므로 한글을 쓴다.
const LETTERS = '가나다라마바사아자차카타'
let call = 0
localLlm.streamGenerate.mockImplementation(async function* () {
const letter = LETTERS[call % LETTERS.length]
@ -426,9 +446,10 @@ describe('SuggestionService 세션 채우기 (최대 12개, 순차 · 페이지)
await internal._generate(PREFIX, context, 3, 240)
// 세션의 첫 요청은 정확히 1개만 청한다 (한꺼번에 여러 개를 청하면 느리다 — 사용자 요청).
// gemma 는 원형 템플릿 prefill 이어 쓰기 — 모델 차례에 사용자 글을 넣어 한 문장만 잇게 한다.
expect(localLlm.streamGenerate).toHaveBeenCalledWith(
expect.stringContaining('1개'),
expect.anything()
expect.stringContaining('<|turn>model\n'),
expect.objectContaining({ raw: true, stop: expect.arrayContaining(['<turn|>']) })
)
await vi.waitFor(() => {
@ -508,7 +529,7 @@ describe('SuggestionService 세션 채우기 (최대 12개, 순차 · 페이지)
})
it('세션의 첫 요청만 분당/일일 예산을 쓴다 — 채우기 요청은 쓰지 않는다', async () => {
const LETTERS = 'ABCDEFGHIJKL'
const LETTERS = '가나다라마바사아자차카타'
let call = 0
localLlm.streamGenerate.mockImplementation(async function* () {
const letter = LETTERS[call % LETTERS.length]
@ -570,3 +591,57 @@ describe('SuggestionService 세션 채우기 (최대 12개, 순차 · 페이지)
expect(cleared).not.toContain('stale')
})
})
describe('SuggestionService 터미널 문맥 (Claude Code 입력 상자)', () => {
const screen = (input: string): string =>
['● 이전 답변 출력', '╭──────────────╮', `│ > ${input}`, '╰──────────────╯', ' ⏵⏵ bypass permissions on · 1 shell'].join('\n')
it('입력 상자 아래 상태줄 때문에 텔레메트리가 caret 미상이라 해도, 입력 줄 끝에서 치는 중이면 커서를 믿는다', async () => {
const { getSuggestionService } = await import('../../../src/main/services/SuggestionService')
const internal = getSuggestionService() as unknown as {
_terminalContext(input: typeof context & { caretReliable?: boolean }): typeof context & { caretReliable?: boolean }
}
const base = { ...context, appName: 'WindowsTerminal.exe', caretReliable: false }
const first = internal._terminalContext({ ...base, fullText: screen('제안 창이 왜') })
expect(first.prefix).toBe('제안 창이 왜')
expect(first.caretReliable).toBe(true)
// 끝에서 더 침 / 끝에서 지움 → 믿는다
expect(internal._terminalContext({ ...base, fullText: screen('제안 창이 왜 잘') }).caretReliable).toBe(true)
expect(internal._terminalContext({ ...base, fullText: screen('제안 창이 왜') }).caretReliable).toBe(true)
// 중간을 고친 모양 → 막는다
expect(internal._terminalContext({ ...base, fullText: screen('추천 창이 왜') }).caretReliable).toBe(false)
// 입력 줄을 못 찾으면 제안하지 않는다
expect(internal._terminalContext({ ...base, fullText: '빌드 출력만 있음' }).caretReliable).toBe(false)
})
it('빈 입력칸에 한꺼번에 나타난 회색 추천 문구는 사용자 글로 보지 않는다 — 치기 시작하면 다시 믿는다', async () => {
const { getSuggestionService } = await import('../../../src/main/services/SuggestionService')
const internal = getSuggestionService() as unknown as {
_terminalContext(input: typeof context & { caretReliable?: boolean }): typeof context & { caretReliable?: boolean }
}
const base = { ...context, appName: 'WindowsTerminal.exe', caretReliable: false }
expect(internal._terminalContext({ ...base, fullText: screen('') }).caretReliable).toBe(true)
// 빈 칸 → 29자 추천 문구가 한 번에 (그대로 머물러도 계속 믿지 않는다)
expect(internal._terminalContext({ ...base, fullText: screen('run the full desktop test suite') }).caretReliable).toBe(false)
expect(internal._terminalContext({ ...base, fullText: screen('run the full desktop test suite') }).caretReliable).toBe(false)
// 사용자가 치기 시작하면 추천 문구가 사라지고 친 글만 남는다
expect(internal._terminalContext({ ...base, fullText: screen('해') }).caretReliable).toBe(true)
expect(internal._terminalContext({ ...base, fullText: screen('해봤어') }).caretReliable).toBe(true)
})
it('한글 조합으로 마지막 글자가 바뀌어도(늘지 않아도) 끝에서 치는 중으로 보고, 멈춘 뒤에도 유지한다', async () => {
const { getSuggestionService } = await import('../../../src/main/services/SuggestionService')
const internal = getSuggestionService() as unknown as {
_terminalContext(input: typeof context & { caretReliable?: boolean }): typeof context & { caretReliable?: boolean }
}
const base = { ...context, appName: 'WindowsTerminal.exe', caretReliable: false }
internal._terminalContext({ ...base, fullText: screen('') })
expect(internal._terminalContext({ ...base, fullText: screen('오늘 회의 자') }).caretReliable).toBe(true)
expect(internal._terminalContext({ ...base, fullText: screen('오늘 회의 잘') }).caretReliable).toBe(true)
expect(internal._terminalContext({ ...base, fullText: screen('오늘 회의 자료') }).caretReliable).toBe(true)
// 멈춤 — 같은 입력 줄이 계속 와도 믿음을 유지한다
expect(internal._terminalContext({ ...base, fullText: screen('오늘 회의 자료') }).caretReliable).toBe(true)
// 긴 글 붙여넣기(빈 칸이 아닌 곳에서 끝에 덧붙임)도 끝에서 친 것이다
expect(internal._terminalContext({ ...base, fullText: screen('오늘 회의 자료 정리해서 내일 오전까지 공유') }).caretReliable).toBe(true)
})
})

View file

@ -0,0 +1,265 @@
// tests/main/services/TypoCorrectionService.test.ts
// 입력 중 오타 자동 교정 — 판단 게이트 · 즉시 교체 · 모델 검사 · 취소 · 되돌리기 학습.
import { beforeEach, describe, expect, it, vi } from 'vitest'
const config = vi.hoisted(() => ({
typoAutoCorrectEnabled: true as boolean,
typoAutoCorrectUseModel: true as boolean,
typoIgnoredWords: [] as string[],
inputExcludedApps: [] as string[]
}))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: keyof typeof config) => config[key]),
configSet: vi.fn((key: keyof typeof config, value: never) => {
config[key] = value
})
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
}))
import { TypoCorrectionService, type TypoCorrectionDeps } from '../../../src/main/services/TypoCorrectionService'
import type { TypingContext } from '../../../src/main/services/InputTelemetryService'
function typingContext(overrides: Partial<TypingContext> = {}): TypingContext {
const prefix = overrides.prefix ?? '오늘 회의는 잘 됬어요 '
return {
prefix,
fullText: prefix,
caretOffset: prefix.length,
anchor: null,
anchorKind: null,
isPassword: false,
isEditable: true,
isComposing: false,
hasSelection: false,
available: true,
appName: 'slack.exe',
windowTitle: 'Slack',
windowHandle: 7,
idleMs: 800,
capturedAt: Date.now(),
editedSinceFocus: true,
typedRecently: true,
caretReliable: true,
...overrides
}
}
function deps(overrides: Partial<TypoCorrectionDeps> = {}) {
const state = { lastKeyAt: 1000 }
const replaceBeforeCaret = vi.fn(async () => true)
const base: TypoCorrectionDeps = {
replaceBeforeCaret,
lastKeyAt: () => state.lastKeyAt,
expectProgrammaticKeys: vi.fn(),
expectProgrammaticInsert: vi.fn(() => () => undefined),
foregroundHandle: () => 7,
recentTexts: () => [],
warmModel: () => null,
generate: vi.fn(async function* () {
yield '없음'
}),
...overrides
}
return { deps: base, state, replaceBeforeCaret }
}
async function flush(): Promise<void> {
for (let index = 0; index < 5; index += 1) await Promise.resolve()
}
describe('TypoCorrectionService', () => {
beforeEach(() => {
config.typoAutoCorrectEnabled = true
config.typoAutoCorrectUseModel = true
config.typoIgnoredWords = []
config.inputExcludedApps = []
})
it('멈췄을 때 결정적 오타를 바로 교체하고 제안으로 넘기지 않는다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
const corrected = vi.fn()
service.on('corrected', corrected)
expect(service.handleTypingContext(typingContext())).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('됬어요 '.length, '됐어요 ')
expect(fake.deps.expectProgrammaticKeys).toHaveBeenCalledWith('됬어요 '.length + 2)
expect(corrected).toHaveBeenCalledTimes(1)
})
it('아직 치는 중이면(유휴 부족) 고치지 않는다', () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
expect(service.handleTypingContext(typingContext({ idleMs: 100 }))).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
})
it('비밀번호·조합 중·선택·터미널·에디터·제외 앱·클릭만 한 칸은 건드리지 않는다', () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
config.inputExcludedApps = ['notes.exe']
for (const overrides of [
{ isPassword: true },
{ isComposing: true },
{ hasSelection: true },
{ appName: 'WindowsTerminal.exe' },
{ appName: 'Code.exe' },
{ appName: 'notes.exe' },
{ editedSinceFocus: false },
{ caretReliable: false }
] satisfies Array<Partial<TypingContext>>) {
expect(service.handleTypingContext(typingContext(overrides))).toBe('pass')
}
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
})
it('설정으로 끌 수 있다', () => {
config.typoAutoCorrectEnabled = false
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
expect(service.handleTypingContext(typingContext())).toBe('pass')
})
it('판단 뒤 사용자가 한 키라도 더 쳤으면 교체하지 않는다', async () => {
const fake = deps()
const replaceBeforeCaret = vi.fn(async () => true)
fake.deps.replaceBeforeCaret = replaceBeforeCaret
fake.deps.lastKeyAt = vi
.fn<() => number>()
.mockReturnValueOnce(1000)
.mockReturnValue(1001)
const service = new TypoCorrectionService(fake.deps)
service.handleTypingContext(typingContext())
await flush()
expect(replaceBeforeCaret).not.toHaveBeenCalled()
})
it('포커스가 다른 창으로 옮겨 갔으면 교체하지 않는다', async () => {
const fake = deps({ foregroundHandle: () => 99 })
const service = new TypoCorrectionService(fake.deps)
service.handleTypingContext(typingContext())
await flush()
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
})
it('같은 구간은 두 번 검사하지 않는다', async () => {
const fake = deps({ warmModel: () => 'gemma' })
const service = new TypoCorrectionService(fake.deps)
const context = typingContext({ prefix: '내일 회의 자료를 미리 공유해 주세요 ' })
expect(service.handleTypingContext(context)).toBe('checking')
await flush()
expect(service.handleTypingContext(context)).toBe('pass')
expect(fake.deps.generate).toHaveBeenCalledTimes(1)
})
it('모델 검사: 오타가 없으면 settled 로 미뤄 둔 문맥을 넘긴다', async () => {
const fake = deps({ warmModel: () => 'gemma' })
const service = new TypoCorrectionService(fake.deps)
const settled = vi.fn()
service.on('settled', settled)
const context = typingContext({ prefix: '내일 회의 자료를 미리 공유해 주세요 ' })
expect(service.handleTypingContext(context)).toBe('checking')
await flush()
expect(settled).toHaveBeenCalledWith({ context })
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
})
it('모델 검사: 검증을 통과한 오타만 교체한다 (단어 교체는 거른다)', async () => {
const fake = deps({
warmModel: () => 'gemma',
generate: vi.fn(async function* () {
yield '공유드립니디 => 공유드립니다\n자료 => 문서'
})
})
const service = new TypoCorrectionService(fake.deps)
const settled = vi.fn()
service.on('settled', settled)
service.handleTypingContext(typingContext({ prefix: '회의 자료 공유드립니디' }))
await flush()
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('공유드립니디'.length, '공유드립니다')
expect(settled).not.toHaveBeenCalled()
})
it('모델이 콜드면 검사하지 않고 바로 넘긴다', () => {
const fake = deps({ warmModel: () => null })
const service = new TypoCorrectionService(fake.deps)
expect(service.handleTypingContext(typingContext({ prefix: '내일 회의 자료를 미리 공유해 주세요 ' }))).toBe('pass')
expect(fake.deps.generate).not.toHaveBeenCalled()
})
it('검사 중 접두가 바뀌면 검사를 버리고 새 문맥은 그대로 넘긴다', async () => {
let release: (() => void) | null = null
const fake = deps({
warmModel: () => 'gemma',
generate: vi.fn(async function* (_prompt: string, options: { signal: AbortSignal }) {
await new Promise<void>((resolve) => {
release = resolve
options.signal.addEventListener('abort', () => resolve())
})
yield '회으 => 회의'
})
})
const service = new TypoCorrectionService(fake.deps)
const settled = vi.fn()
service.on('settled', settled)
expect(service.handleTypingContext(typingContext({ prefix: '오늘 회으 자료를 정리했습니다 ' }))).toBe('checking')
expect(service.handleTypingContext(typingContext({ prefix: '오늘 회으 자료를 정리했습니다 그', idleMs: 50 }))).toBe(
'pass'
)
release?.()
await flush()
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
expect(settled).not.toHaveBeenCalled()
})
it('교정을 되돌리면 그 단어를 무시 목록에 올리고 다시 고치지 않는다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
const reverted = vi.fn()
service.on('reverted', reverted)
service.handleTypingContext(typingContext({ prefix: '그건 됬어요 ' }))
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledTimes(1)
// 사용자가 원래대로 되돌림 (교정 뒤 찍힌 스냅샷)
service.handleTypingContext(typingContext({ prefix: '그건 됬어요 ', capturedAt: Date.now() + 1000, idleMs: 50 }))
expect(reverted).toHaveBeenCalledWith({ word: '됬어요' })
expect(config.typoIgnoredWords).toEqual(['됬어요'])
service.handleTypingContext(typingContext({ prefix: '그건 됬어요 정말 ', capturedAt: Date.now() + 2000 }))
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledTimes(1)
})
it('한참 더 쓴 뒤 같은 오타를 새로 친 것은 되돌림으로 보지 않는다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
const reverted = vi.fn()
service.on('reverted', reverted)
service.handleTypingContext(typingContext({ prefix: '그건 됬어요 ' }))
await flush()
service.handleTypingContext(
typingContext({
prefix: '그건 됐어요 그리고 다음 회의 일정도 정리해서 공유드릴게요 그건 됬어요 ',
capturedAt: Date.now() + 1000,
idleMs: 50
})
)
expect(reverted).not.toHaveBeenCalled()
expect(config.typoIgnoredWords).toEqual([])
})
it('한영 전환 오타를 바로 한글로 바꾼다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
service.handleTypingContext(typingContext({ prefix: '오늘 회의 dkssudgktpdy' }))
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('dkssudgktpdy'.length, '안녕하세요')
})
})

View file

@ -0,0 +1,105 @@
// tests/main/services/input-telemetry-focus-flicker.test.ts
// 타이핑 중 UIA 포커스가 입력칸 ↔ 읽을 수 없는 요소(legacy)를 오가도 "편집한 칸" 판정을 잃지 않는다
// (2026-10-03 실측: Chrome 보류 사유 not-typing 122회).
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { FocusSnapshot } from '@d3ro/core/input-intelligence'
const uia = vi.hoisted(() => ({ next: null as FocusSnapshot | null }))
vi.mock('electron', () => ({ screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) } }))
vi.mock('uiohook-napi', () => ({ uIOhook: { on: vi.fn(), removeListener: vi.fn() } }))
vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() }))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: (key: string) => (key === 'inputExcludedApps' ? [] : undefined),
configSet: vi.fn()
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })
}))
vi.mock('../../../src/main/services/global-input-hook', () => ({ acquireGlobalInputHook: () => () => undefined }))
vi.mock('../../../src/main/services/KeyBindingService', () => ({ uiohookCodeToVk: () => 0x41 }))
vi.mock('../../../src/main/services/UiaContextService', () => ({
getUiaContextService: () => ({
getSnapshot: async () => uia.next,
isAvailable: () => true,
lastReason: null,
lastSuccessAt: 0
})
}))
vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null }))
import {
getInputTelemetryService,
resetInputTelemetryServiceForTests,
type TypingContext
} from '../../../src/main/services/InputTelemetryService'
interface Internal {
_running: boolean
_lastTypedAt: number
_lastClickAt: number
_foreground: { appName: string | null; windowTitle: string | null; hwnd: number | null }
_captureTextSnapshot(): Promise<TypingContext | null>
}
function snapshot(partial: Partial<FocusSnapshot>): FocusSnapshot {
return {
available: true,
isPassword: false,
isEditable: true,
isComposing: false,
hasSelection: false,
controlType: 'Edit',
controlName: '메시지',
textSource: 'value',
text: '',
caretOffset: null,
caretRect: null,
elementRect: null,
windowTitle: '채팅',
appName: 'chrome.exe',
processId: 1,
capturedAt: Date.now(),
...partial
}
}
describe('포커스 깜빡임', () => {
let service: Internal
beforeEach(() => {
resetInputTelemetryServiceForTests()
service = getInputTelemetryService() as unknown as Internal
service._running = true
service._foreground = { appName: 'chrome.exe', windowTitle: '채팅', hwnd: 42 }
})
async function capture(next: FocusSnapshot): Promise<TypingContext | null> {
uia.next = next
return service._captureTextSnapshot()
}
it('키보드로 치는 동안 읽을 수 없는 요소를 거쳐 같은 창 입력칸으로 돌아오면 편집한 칸으로 본다', async () => {
await capture(snapshot({ text: '' }))
await capture(snapshot({ isEditable: false, textSource: 'legacy', controlType: 'Document', controlName: '' }))
service._lastTypedAt = Date.now()
const context = await capture(snapshot({ text: '내일 회의 자료는 오늘 저녁까지' }))
expect(context?.editedSinceFocus).toBe(true)
})
it('클릭해서 들어온 칸은 예전처럼 기준선을 다시 잡는다 (옛 글로 제안하지 않는다)', async () => {
await capture(snapshot({ isEditable: false, textSource: 'legacy', controlType: 'Document', controlName: '' }))
service._lastTypedAt = Date.now() - 1000
service._lastClickAt = Date.now()
const context = await capture(snapshot({ controlName: '검색', text: '옛 검색어' }))
expect(context?.editedSinceFocus).toBe(false)
})
it('다른 창으로 옮겨 온 칸도 기준선을 다시 잡는다', async () => {
await capture(snapshot({ isEditable: false, textSource: 'legacy', controlType: 'Document', controlName: '' }))
service._lastTypedAt = Date.now()
service._foreground = { appName: 'notepad.exe', windowTitle: '메모', hwnd: 7 }
const context = await capture(snapshot({ appName: 'notepad.exe', text: '원래 있던 글' }))
expect(context?.editedSinceFocus).toBe(false)
})
})

View file

@ -0,0 +1,49 @@
// tests/main/services/input-telemetry-ime-keys.test.ts
// 한글 IME 가 켜진 글자 키(VK_PROCESSKEY → uiohook 미지 키코드)도 "타이핑" 으로 본다 (2026-10-03 회귀).
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({ screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) } }))
vi.mock('uiohook-napi', () => ({ uIOhook: { on: vi.fn(), removeListener: vi.fn() } }))
vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() }))
vi.mock('../../../src/main/services/ConfigService', () => ({ configGet: () => undefined, configSet: vi.fn() }))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })
}))
vi.mock('../../../src/main/services/global-input-hook', () => ({ acquireGlobalInputHook: () => () => undefined }))
// 매핑 없는 키코드(0) = IME 처리 키
vi.mock('../../../src/main/services/KeyBindingService', () => ({
uiohookCodeToVk: (code: number) => (code === 0 ? null : 0x41)
}))
vi.mock('../../../src/main/services/UiaContextService', () => ({ getUiaContextService: () => ({}) }))
vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null }))
import {
getInputTelemetryService,
resetInputTelemetryServiceForTests
} from '../../../src/main/services/InputTelemetryService'
interface Internal {
_handleKeyDown(event: { keycode: number; ctrlKey: boolean; altKey: boolean; metaKey: boolean; shiftKey: boolean }): void
_lastTypedAt: number
}
function key(keycode: number, modifiers: Partial<{ ctrlKey: boolean; altKey: boolean }> = {}) {
return { keycode, ctrlKey: false, altKey: false, metaKey: false, shiftKey: false, ...modifiers }
}
describe('IME 글자 키', () => {
beforeEach(() => resetInputTelemetryServiceForTests())
it('변환표에 없는 키(IME 처리 키)를 수정자 없이 누르면 타이핑으로 본다', () => {
const service = getInputTelemetryService() as unknown as Internal
expect(service._lastTypedAt).toBe(0)
service._handleKeyDown(key(0))
expect(service._lastTypedAt).toBeGreaterThan(0)
})
it('Ctrl/Alt 와 함께면 단축키다 — 타이핑이 아니다', () => {
const service = getInputTelemetryService() as unknown as Internal
service._handleKeyDown(key(0, { ctrlKey: true }))
expect(service._lastTypedAt).toBe(0)
})
})

View file

@ -160,6 +160,36 @@ describe('KeyBindingService — globalShortcut 예약 · 마우스 release', ()
expect(registeredAccelerators()).toEqual(['Control+Shift+V', 'Control+Shift+C'])
})
it('Windows 에서 제안 창이 떠 있는 동안만 제안 단축키를 잡고, 사라지면 푼다 (Ctrl+Alt+Enter 개행 방지)', () => {
setPlatform('win32')
configSet('suggestionEnabled', true)
const service = getKeyBindingService()
service.loadFromConfig()
service.start()
expect(globalShortcut.register).not.toHaveBeenCalled()
service.setSuggestionCaptureActive(true)
expect(registeredAccelerators()).toEqual(
expect.arrayContaining(['Control+Alt+Return', 'Control+Alt+Down', 'Control+Alt+Up', 'Control+Alt+Backspace'])
)
expect(registeredAccelerators()).not.toContain('Control+Shift+V')
service.setSuggestionCaptureActive(false)
const released = vi.mocked(globalShortcut.unregister).mock.calls.map((call) => String(call[0]))
expect(released).toEqual(expect.arrayContaining(['Control+Alt+Return', 'Control+Alt+Down']))
})
it('제안 기능이 꺼져 있으면 제안 창 상태와 무관하게 아무것도 잡지 않는다', () => {
setPlatform('win32')
configSet('suggestionEnabled', false)
const service = getKeyBindingService()
service.loadFromConfig()
service.start()
service.setSuggestionCaptureActive(true)
expect(globalShortcut.register).not.toHaveBeenCalled()
service.setSuggestionCaptureActive(false)
})
it('X1 hold 중 Alt 를 더 누른 채 버튼을 놓아도 dictation 이 released 된다', () => {
setPlatform('win32')
const map = createDefaultBindingMap()

View file

@ -27,7 +27,7 @@ import {
SUGGESTION_SYSTEM_PROMPT,
FREE_PROMPT_SYSTEM_PROMPT,
} from '../../../src/main/services/llm-prompts'
import { buildCaptionRefinePrompt } from '../../../src/main/services/llm-prompts'
import { buildCaptionRefinePrompt, buildTypoCheckPrompt } from '../../../src/main/services/llm-prompts'
beforeEach(() => {
vi.clearAllMocks()
@ -249,6 +249,52 @@ describe('buildSuggestionPrompt', () => {
const { text } = buildSuggestionPrompt({ prefix: 'abc' })
expect(text).not.toContain('이미 제안한 문장')
})
it('접두를 직전 문장과 지금 쓰는 문장으로 나누고 마저 쓰기·언어·말투를 지시한다', () => {
const { text } = buildSuggestionPrompt({
prefix: '어제 배포는 잘 끝났습니다. 오늘은 모니터링 결과를'
})
expect(text).toContain('[직전 문장]\n어제 배포는 잘 끝났습니다.')
expect(text).toContain('[지금 쓰는 문장 — 아직 끝나지 않음]\n오늘은 모니터링 결과를')
expect(text).toContain('나머지 부분만')
expect(text).toContain('언어: 한국어')
expect(text).toContain('말투: 격식체')
})
it('문장이 끝났으면 다음 문장을 지시한다', () => {
const { text } = buildSuggestionPrompt({ prefix: 'Thanks for the update. ' })
expect(text).toContain('새 문장 하나')
expect(text).toContain('언어: 영어')
expect(text).not.toContain('말투:')
})
it('그래프 근거(직전 문장 뒤 이어 쓴 문장)와 커서 뒤 텍스트를 데이터로 넣는다', () => {
const { systemPrompt, text } = buildSuggestionPrompt({
prefix: '회의록 정리했습니다.',
suffix: '감사합니다.',
followUpHints: ['검토 후 의견 주세요']
})
expect(text).toContain('[사용자가 평소 직전 문장 같은 말 뒤에 이어 쓴 문장]\n- 검토 후 의견 주세요')
expect(text).toContain('[커서 뒤에 이미 있는 텍스트 — 이것과 겹치지 않게]\n감사합니다.')
expect(systemPrompt).not.toContain('검토 후 의견 주세요')
})
it('프롬프트에 깨진 글자(빈 자리)가 없다', () => {
const { systemPrompt, text } = buildSuggestionPrompt({ prefix: '안녕하세요. 오늘' })
expect(systemPrompt).toContain('사용자가 쓴 언어와 같은 언어')
expect(systemPrompt).toContain('머리말')
expect(systemPrompt).not.toMatch(/ {2}[가-힣]/u)
expect(text).not.toMatch(/\[[^\]]* {2}[^\]]*\]/u)
})
})
describe('buildTypoCheckPrompt', () => {
it('지시문은 시스템 프롬프트에, 검사할 문장과 앞 문맥만 본문에', () => {
const { systemPrompt, text } = buildTypoCheckPrompt({ sentence: '회으 자료 공유', previous: '오늘 회의 끝났습니다.' })
expect(systemPrompt).toContain('=>')
expect(systemPrompt).toContain('없음')
expect(text).toBe('[앞 문맥]\n오늘 회의 끝났습니다.\n\n[검사할 문장]\n회으 자료 공유')
})
})
describe('buildCaptionRefinePrompt', () => {
@ -268,3 +314,58 @@ describe('buildCaptionRefinePrompt', () => {
expect(buildCaptionRefinePrompt({ text: '안녕', previous: [] }).text).toBe(['[다듬을 자막]', '안녕'].join('\n'))
})
})
describe('buildSuggestionPrompt — prefill 이어 쓰기', () => {
it('마저 쓰기: 지금 문장을 모델 차례에 넣고(끝 공백 제외) 단어를 끝냈는지 알려 준다', () => {
const prompt = buildSuggestionPrompt({ prefix: '안녕하세요. 첨부 파일 검토해 보시고 ', prefill: true })
expect(prompt.assistantPrefix).toBe('첨부 파일 검토해 보시고')
expect(prompt.wordFinished).toBe(true)
expect(prompt.writing.mode).toBe('complete-sentence')
expect(prompt.systemPrompt).toContain('당신의 차례에는 사용자가 쓰던 글의 끝부분')
expect(prompt.systemPrompt).not.toContain(SUGGESTION_NO_THINK_PREFIX)
})
it('다음 문장: 직전 문장을 넣고, 새 줄에서 멈췄으면 줄바꿈을 남긴다', () => {
expect(buildSuggestionPrompt({ prefix: '자료 공유드립니다.', prefill: true }).assistantPrefix).toBe('자료 공유드립니다.')
expect(buildSuggestionPrompt({ prefix: '- 일정: 10월 7일\n', prefill: true }).assistantPrefix).toBe('- 일정: 10월 7일\n')
})
it('400자 창 밖의 첫머리와 사실을 문서 원문에서 뽑아 보여 준다', () => {
const documentText = `팀장님 안녕하세요. 출시일은 11월 15일로 확정됐습니다.\n${'세부 내용입니다. '.repeat(150)}정리하면 출시는 `
const prompt = buildSuggestionPrompt({ prefix: documentText.slice(-400), documentText, prefill: true })
expect(prompt.text).toContain('[글의 첫머리]\n팀장님 안녕하세요. 출시일은 11월 15일로 확정됐습니다.')
expect(prompt.text).toMatch(/\[글에 나온 사실\]\n.*11월 15일/u)
expect(prompt.factSource).toContain('11월 15일')
})
it('이 창에서 조금 전에 쓴 글을 오래된 것부터 보여 주고 사실 검사 원문에도 넣는다', () => {
const prompt = buildSuggestionPrompt({
prefix: 'ㅇㅋ 그럼 나도 ',
recentWrites: [
{ text: '야 내일 몇 시에 보기로 했지?', ageMs: 240_000 },
{ text: '나 3시쯤 강남역 도착할 듯', ageMs: 30_000 }
],
prefill: true
})
expect(prompt.text).toContain('[이 창에서 조금 전에 쓴 글 — 오래된 것부터]\n- (4분 전) 야 내일 몇 시에 보기로 했지?\n- (방금) 나 3시쯤 강남역 도착할 듯')
expect(prompt.factSource).toContain('3시쯤 강남역')
})
it('검색 페이지의 짧은 입력은 검색어로 잇게 한다', () => {
const prompt = buildSuggestionPrompt({ prefix: '서울 강남 파스타 ', appName: 'Chrome', windowTitle: 'Google', prefill: true })
expect(prompt.text).toContain('입력: 검색어입니다.')
expect(buildSuggestionPrompt({ prefix: '서울 강남 파스타 ', appName: 'Slack', windowTitle: '#food' }).text).not.toContain(
'입력: 검색어'
)
})
it('일기체(-다)는 반말과 구분된 평서체로 지시한다', () => {
const prompt = buildSuggestionPrompt({ prefix: '오늘은 진짜 피곤했다. 점심도 ', prefill: true })
expect(prompt.text).toContain('말투: 평서체')
})
it('이모지는 사용자가 쓸 때만 허용한다', () => {
expect(buildSuggestionPrompt({ prefix: '좋아요 👍 내일 ', prefill: true }).allowEmoji).toBe(true)
expect(buildSuggestionPrompt({ prefix: '좋아요 내일 ', prefill: true }).allowEmoji).toBe(false)
})
})

View file

@ -0,0 +1,77 @@
// tests/main/services/personal-graph-context.test.ts
// 개인 그래프 문맥 조회 (실제 SQLite) — 직전 문장 follows · 조사 무관 용어 매칭 · 짧은 꼬리 물러나기.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestDb } from '../../helpers/createTestDb'
const holder = vi.hoisted(() => ({ db: null as unknown }))
vi.mock('../../../src/main/db', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/main/db')>()),
getDatabase: () => holder.db
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })
}))
import {
getPersonalGraphService,
resetPersonalGraphServiceForTests
} from '../../../src/main/services/PersonalGraphService'
let testDb: ReturnType<typeof createTestDb>
beforeEach(() => {
testDb = createTestDb()
holder.db = testDb.db
resetPersonalGraphServiceForTests()
})
afterEach(() => {
testDb.close()
})
describe('PersonalGraphService.retrieveContext', () => {
it('직전 문장 뒤에 사용자가 실제로 이어 쓴 문장을 followUps 로 준다', () => {
const graph = getPersonalGraphService()
graph.indexText('배포 끝났습니다. 모니터링 대시보드 확인 부탁드립니다.', { source: 'typed' })
graph.indexText('배포 끝났습니다. 모니터링 대시보드 확인 부탁드립니다.', { source: 'typed' })
const context = graph.retrieveContext('오전 작업 공유드립니다. 배포 끝났습니다. ')
expect(context.followUps).toEqual(['모니터링 대시보드 확인 부탁드립니다'])
})
it('직전 문장이 조금 달라도 용어가 거의 같으면 그 노드의 follows 를 쓴다', () => {
const graph = getPersonalGraphService()
graph.indexText('주간 보고서 초안 작성했습니다. 피드백은 금요일까지 부탁드려요.', { source: 'typed' })
const context = graph.retrieveContext('주간 보고서 초안을 작성했습니다! ')
expect(context.followUps).toEqual(['피드백은 금요일까지 부탁드려요'])
})
it('조사가 달라도 같은 주제의 문장을 관련 문장으로 끌어온다', () => {
const graph = getPersonalGraphService()
graph.indexText('금요일 배포를 위해 회귀 테스트를 끝내야 합니다', { source: 'typed' })
graph.indexText('점심은 김치찌개 어때요', { source: 'typed' })
const context = graph.retrieveContext('이번 배포는 회귀 테스트가')
expect(context.related).toContain('금요일 배포를 위해 회귀 테스트를 끝내야 합니다')
expect(context.related).not.toContain('점심은 김치찌개 어때요')
})
it('긴 꼬리가 맞지 않으면 짧은 어절 꼬리로 물러나 이어쓰기를 찾는다', () => {
const graph = getPersonalGraphService()
graph.indexText('회의록은 내일 오전까지 공유드리겠습니다', { source: 'typed' })
const context = graph.retrieveContext('지난번 논의한 안건의 회의록은')
expect(context.continuations).toEqual(['내일 오전까지 공유드리겠습니다'])
})
it('이미 접두에 쓴 문장은 다시 주지 않는다', () => {
const graph = getPersonalGraphService()
graph.indexText('배포 끝났습니다. 배포 로그 확인했습니다.', { source: 'typed' })
const context = graph.retrieveContext('배포 끝났습니다. 배포 로그 확인했습니다. ')
expect(context.related).not.toContain('배포 로그 확인했습니다')
expect(context.followUps).not.toContain('배포 로그 확인했습니다')
})
})

View file

@ -33,7 +33,7 @@ vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => ({ isAvailable: harness.isAvailable, streamGenerate: harness.streamGenerate })
}))
vi.mock('../../../src/main/services/InputTelemetryService', () => ({
getInputTelemetryService: () => ({ listPhrases: () => [] })
getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] })
}))
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
getPersonalGraphService: () => ({

View file

@ -34,7 +34,7 @@ vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => ({ isAvailable: harness.isAvailable, streamGenerate: harness.streamGenerate })
}))
vi.mock('../../../src/main/services/InputTelemetryService', () => ({
getInputTelemetryService: () => ({ listPhrases: () => harness.phrases })
getInputTelemetryService: () => ({ listPhrases: () => harness.phrases, listRecentWrites: () => [] })
}))
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) })

View file

@ -43,7 +43,7 @@ vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => ({ isAvailable: harness.isAvailable, streamGenerate: harness.streamGenerate })
}))
vi.mock('../../../src/main/services/InputTelemetryService', () => ({
getInputTelemetryService: () => ({ listPhrases: () => harness.phrases })
getInputTelemetryService: () => ({ listPhrases: () => harness.phrases, listRecentWrites: () => [] })
}))
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) })

View file

@ -92,6 +92,7 @@ class MemoryClipboard implements ClipboardPort<ClipboardImage> {
function makeKeyboard(clip: MemoryClipboard, pasted: string[], typed: string[]): KeyboardPort {
return {
backspace: vi.fn(async () => undefined),
paste: vi.fn(async () => {
pasted.push(clip.readText())
}),
@ -185,6 +186,7 @@ describe('TextInsertService 클립보드 복원 (redteam r1-2)', () => {
const clip = new MemoryClipboard()
clip.text = 'old'
const keyboard: KeyboardPort = {
backspace: vi.fn(async () => undefined),
paste: vi.fn(async () => {
clip.writeText('user copied meanwhile')
}),
@ -207,6 +209,7 @@ describe('TextInsertService 클립보드 복원 (redteam r1-2)', () => {
clip.text = 'keep me'
clip.html = '<p>keep me</p>'
const keyboard: KeyboardPort = {
backspace: vi.fn(async () => undefined),
paste: vi.fn(async () => {
throw new Error('SendInput failed')
}),
@ -245,6 +248,7 @@ describe('TextInsertService 클립보드 복원 (redteam r1-2)', () => {
clip.text = 'original'
let calls = 0
const keyboard: KeyboardPort = {
backspace: vi.fn(async () => undefined),
paste: vi.fn(async () => {
calls++
if (calls === 1) throw new Error('boom')