feat(desktop): built-in Han/Eng layout auto-switching, terminal/Vim support, and Unicode input

This commit is contained in:
Yun Chan 2026-10-27 10:48:07 +09:00
parent 1da04b9e46
commit a3ac44da2b
109 changed files with 8234 additions and 242 deletions

View file

@ -0,0 +1,287 @@
// tests/eval/suggestion-replay.eval.test.ts
//
// 문장 예측 재생 평가 — 사용자가 실제로 친 문장을 어절 경계에서 잘라 앞부분으로 제안을 만들고,
// 뒷부분(실제로 이어 친 글)과 비교한다. 앱과 같은 경로(buildSuggestionPrompt → renderRawChatPrompt
// → Ollama raw → extractContinuation → 사실 검사)를 쓴다. 개인 힌트(문구·그래프)는 아직 넣지 않는다.
//
// 평소 테스트에서는 건너뛴다. 실행(앱의 Ollama 가 떠 있어야 한다):
// D3RO_EVAL_DB=<d3ro.db 경로> D3RO_EVAL_OUT=<결과 폴더> [D3RO_EVAL_CASES=120] [D3RO_EVAL_MODEL=gemma4:e4b]
// ELECTRON_RUN_AS_NODE=1 electron vitest run --config vitest.config.ts tests/eval
//
// 결과: cases.json(케이스별 원문·제안·토큰 확률) + summary.json. 토큰 확률을 남겨 두면 게이팅·절단
// 기준값을 모델을 다시 돌리지 않고 오프라인으로 고를 수 있다.
import { mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import Database from 'better-sqlite3'
import { describe, expect, it, vi } from 'vitest'
import { extractContinuation } from '@d3ro/core/input-intelligence'
import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template'
import { splitSentences } from '@d3ro/core/personal-graph'
import { findUnsupportedFacts } from '@d3ro/core/writing-context'
import { PersonalNgramModel, predictPersonalContinuation } from '@d3ro/core/personal-ngram'
import { copiesContext, cutByConfidence } from '@d3ro/core/suggestion-confidence'
import { scoreReplayCase, summarizeReplay, type ReplayCaseResult } from './replay-metrics'
vi.mock('../../src/main/services/LoggerService', () => ({
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })
}))
const DB_PATH = process.env.D3RO_EVAL_DB
const OUT_DIR = process.env.D3RO_EVAL_OUT
const MODEL = process.env.D3RO_EVAL_MODEL ?? 'gemma4:e4b'
const CASES = Number(process.env.D3RO_EVAL_CASES ?? 120)
const OLLAMA = process.env.D3RO_EVAL_OLLAMA ?? 'http://127.0.0.1:11434'
/**
* app — 앱과 같은 지시형 prefill 프롬프트, 문맥은 지금 문장만
* recent — app + 같은 앱에서 15분 안에 먼저 쓴 글(앱의 recentWrites 와 같은 자리)
* plain — 지시문·템플릿 없이 앞 글 + 지금 문장을 그대로 이어 쓰게 한다(순수 언어 모델 이어쓰기)
* ngram — 개인 n-gram 만 (모델 호출 없음). 정답 문장이 든 기록은 빼고 만든다(leave-one-out)
* hybrid — ngram 이 내면 그것, 아니면 recent
*/
const VARIANT = (process.env.D3RO_EVAL_VARIANT ?? 'app') as 'app' | 'recent' | 'plain' | 'ngram' | 'hybrid'
/** word — 어절 경계(단어를 끝내고 멈춤), mid — 단어 중간(치다가 멈춤) */
const CUT = (process.env.D3RO_EVAL_CUT ?? 'word') as 'word' | 'mid'
/** 1 이면 앱처럼 모델 출력을 토큰 확신으로 거르고 자른다 (core cutByConfidence) */
const GATE = process.env.D3RO_EVAL_GATE === '1'
const RECENT_WINDOW_MS = 15 * 60_000
/** 앱 기본값과 같다 (SUGGESTION_DEFAULTS.maxOutputTokens) */
const MAX_TOKENS = 64
interface ReplaySource {
text: string
appName: string | null
createdAt: number
}
interface GenerateResponse {
response: string
total_duration?: number
prompt_eval_count?: number
prompt_eval_cached_count?: number
logprobs?: Array<{ token: string; logprob: number }>
}
/** 결정적 의사 난수 — 실행마다 같은 케이스를 고른다(변경 전후 비교). */
function seeded(seed: number): () => number {
let state = seed
return () => {
state = (state * 1_103_515_245 + 12_345) % 2_147_483_648
return state / 2_147_483_648
}
}
/** 평가할 문장 — 직접 친 글 중 어절 4개 이상, 주소·명령 같은 것은 뺀다. */
function loadSources(dbPath: string): ReplaySource[] {
const db = new Database(dbPath, { readonly: true, fileMustExist: true })
try {
const rows = db
.prepare(
"SELECT text, app_name AS appName, created_at AS createdAt FROM typing_samples WHERE source = 'typed' ORDER BY created_at"
)
.all() as ReplaySource[]
const seen = new Set<string>()
return rows.filter((row) => {
const text = row.text.trim()
if (seen.has(text)) return false
seen.add(text)
const words = text.split(/\s+/u)
return words.length >= 4 && text.length >= 15 && !/https?:|www\.|[/\\=&]/u.test(text) && /[가-힣]/u.test(text)
})
} finally {
db.close()
}
}
/** n-gram 이 배울 기록 전부 — 앱과 같이 출처를 가리지 않는다. */
function loadCorpus(dbPath: string): string[] {
const db = new Database(dbPath, { readonly: true, fileMustExist: true })
try {
return (db.prepare('SELECT text FROM typing_samples ORDER BY created_at').all() as Array<{ text: string }>).map(
(row) => row.text
)
} finally {
db.close()
}
}
function squash(text: string): string {
return text.replace(/\s+/gu, ' ').trim()
}
/**
* 끊을 자리 하나를 골라 (앞부분, 정답) 으로 자른다. 정답이 최소 2어절 남게 한다.
* word 는 공백 바로 뒤, mid 는 두 글자 이상 어절의 첫 글자 뒤(그 어절의 나머지가 정답 첫머리).
*/
function cut(text: string, random: () => number): { prefix: string; truth: string } | null {
const boundaries: number[] = []
for (let index = 1; index < text.length; index += 1) {
if (CUT === 'word') {
if (text[index] === ' ' && text[index - 1] !== ' ') boundaries.push(index + 1)
} else if (text[index - 1] === ' ' && index + 1 < text.length && /\S/u.test(text[index]) && /\S/u.test(text[index + 1])) {
boundaries.push(index + 1)
}
}
const usable = boundaries.filter((at) => at >= 6 && text.slice(at).trim().split(/\s+/u).length >= 2)
if (usable.length === 0) return null
const at = usable[Math.floor(random() * usable.length)]
return { prefix: text.slice(0, at), truth: text.slice(at) }
}
async function generate(prompt: string, stop: string[]): Promise<{ data: GenerateResponse; ms: number }> {
const startedAt = Date.now()
const response = await fetch(`${OLLAMA}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: MODEL,
prompt,
raw: true,
stream: false,
logprobs: true,
top_logprobs: 0,
keep_alive: '10m',
// 앱은 0.3 으로 뽑는다 — 비교 가능하게 하려고 평가는 결정적으로(0) 돌린다.
options: { temperature: 0, num_predict: MAX_TOKENS, stop }
})
})
if (!response.ok) throw new Error(`ollama ${response.status}: ${await response.text()}`)
return { data: (await response.json()) as GenerateResponse, ms: Date.now() - startedAt }
}
describe.skipIf(!DB_PATH || !OUT_DIR)('suggestion replay eval', () => {
it(
'replays typed sentences through the suggestion pipeline',
async () => {
const { buildSuggestionPrompt } = await import('../../src/main/services/llm-prompts')
const sources = loadSources(DB_PATH as string)
const random = seeded(20261024)
const picked: Array<ReplaySource & { prefix: string; truth: string }> = []
const pool = [...sources]
while (picked.length < CASES && pool.length > 0) {
const source = pool.splice(Math.floor(random() * pool.length), 1)[0]
const split = cut(source.text, random)
if (split) picked.push({ ...source, ...split })
}
const corpus = VARIANT === 'ngram' || VARIANT === 'hybrid' ? loadCorpus(DB_PATH as string) : []
const results: ReplayCaseResult[] = []
for (const item of picked) {
if (VARIANT === 'ngram' || VARIANT === 'hybrid') {
// 정답 문장이 든 기록은 빼고 배운다 — 그대로 두면 답을 외워서 맞힌다.
const sentence = squash(item.text)
const ngram = new PersonalNgramModel()
for (const text of corpus) if (!squash(text).includes(sentence)) ngram.addText(text)
const startedAt = Date.now()
// 기준값을 주지 않으면 앱과 같은 값(predictPersonalContinuation)을 쓴다 — 격자 탐색 때만 덮는다.
const prediction = process.env.D3RO_EVAL_NGRAM_SUPPORT
? ngram.predict(item.prefix, {
minSupport: Number(process.env.D3RO_EVAL_NGRAM_SUPPORT),
minConfidence: Number(process.env.D3RO_EVAL_NGRAM_CONFIDENCE ?? 0.25),
maxWords: Number(process.env.D3RO_EVAL_NGRAM_WORDS ?? 3)
})
: predictPersonalContinuation(ngram, item.prefix)
if (prediction || VARIANT === 'ngram') {
results.push(
scoreReplayCase({
appName: item.appName,
prefix: item.prefix,
truth: item.truth,
raw: prediction?.text ?? '',
suggestion: prediction?.text ?? null,
tokens: [],
latencyMs: Date.now() - startedAt,
promptTokens: null,
cachedPromptTokens: null
})
)
continue
}
}
// 앞서 쓴 글 — 같은 앱, 15분 안, 오래된 것부터 최대 4개 (자기 자신·뒤에 쓴 글은 넣지 않는다)
const recent =
VARIANT === 'app'
? []
: sources
.filter(
(other) =>
other.appName === item.appName &&
other.createdAt < item.createdAt &&
item.createdAt - other.createdAt <= RECENT_WINDOW_MS
)
.slice(-4)
const prompt = buildSuggestionPrompt({
prefix: item.prefix,
documentText: item.prefix,
suffix: null,
appName: item.appName,
windowTitle: null,
recentWrites: recent.map((other) => ({ text: other.text, ageMs: item.createdAt - other.createdAt })),
candidates: 1,
maxChars: 160,
prefill: true
})
const rawPrompt =
VARIANT === 'plain'
? [...recent.map((other) => other.text), item.prefix.trimEnd()].join('\n')
: renderRawChatPrompt(MODEL, {
system: prompt.systemPrompt,
user: prompt.text,
assistantPrefix: prompt.assistantPrefix ?? ''
})
if (rawPrompt === null) throw new Error(`model ${MODEL} has no raw template`)
const stop = VARIANT === 'plain' ? ['\n'] : rawChatStopSequences(MODEL)
const { data, ms } = await generate(rawPrompt, stop)
// 앱(SuggestionService keepConfidentPart)과 같은 거르기 — 첫 어절이 자신 없으면 숨긴다.
const tokens = data.logprobs ?? []
const cutResult = GATE && tokens.length > 0 ? cutByConfidence(tokens) : undefined
const joined = tokens.map((entry) => entry.token).join('')
const confidentRaw =
cutResult === undefined
? data.response
: cutResult === null
? ''
: data.response.startsWith(joined.slice(0, cutResult.keepChars))
? joined.slice(0, cutResult.keepChars)
: data.response
const continuation = extractContinuation(confidentRaw, {
mode: prompt.writing.mode,
prefill: prompt.assistantPrefix ?? '',
writtenSentences: splitSentences(item.prefix),
wordFinished: prompt.wordFinished,
allowEmoji: prompt.allowEmoji,
maxChars: 160
})
// 앱과 같은 거부 규칙: 지어낸 사실 · 앞 글 베끼기
const contextText = [...recent.map((other) => other.text), item.prefix, prompt.factSource].join(' ')
const rejected = !continuation
? null
: findUnsupportedFacts(continuation.text, prompt.factSource).length > 0
? 'unsupported-facts'
: copiesContext(continuation.text, contextText)
? 'copied-context'
: null
results.push(
scoreReplayCase({
appName: item.appName,
prefix: item.prefix,
truth: item.truth,
raw: data.response,
suggestion: rejected ? null : continuation?.text ?? null,
tokens: (data.logprobs ?? []).map((entry) => ({ token: entry.token, logprob: entry.logprob })),
latencyMs: ms,
promptTokens: data.prompt_eval_count ?? null,
cachedPromptTokens: data.prompt_eval_cached_count ?? null
})
)
}
mkdirSync(OUT_DIR as string, { recursive: true })
writeFileSync(join(OUT_DIR as string, 'cases.json'), JSON.stringify(results, null, 2))
const summary = { model: MODEL, variant: VARIANT, cut: CUT, gate: GATE, sources: sources.length, ...summarizeReplay(results) }
writeFileSync(join(OUT_DIR as string, 'summary.json'), JSON.stringify(summary, null, 2))
expect(results.length).toBeGreaterThan(0)
},
30 * 60_000
)
})