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

@ -11,19 +11,20 @@
import {
SHARES_TERMS_MIN_SIMILARITY,
buildQueryTerms,
buildSequenceEdges,
continuationsFrom,
extractTerms,
jaccard,
rankRelated,
scoreRelatedNodes,
splitSentences,
type GraphContext,
type PersonalGraphQuery,
type PersonalGraphStats,
type PhraseSource,
type RelatedCandidate
type PhraseSource
} from '@d3ro/core/personal-graph'
import { isLearnablePhrase, prefixTail } from '@d3ro/core/input-intelligence'
import { SUGGESTION_MEMORY_TAIL_CHARS, isLearnablePhrase, prefixTail } from '@d3ro/core/input-intelligence'
import { analyzeWritingContext } from '@d3ro/core/writing-context'
import { and, desc, eq, gte, inArray, or, sql } from 'drizzle-orm'
import { getDatabase } from '../db'
import { personalPhrases, phraseEdges } from '../db/schema'
@ -127,93 +128,186 @@ class PersonalGraphService {
/**
* 제안 문맥을 그래프에서 끌어온다.
*
* 1) 접두 꼬리를 포함하는 노드를 찾고 그 뒤에 실제로 이어 쓴 텍스트를 뽑는다.
* 2) 그 노드들의 follows 이웃과 용어를 공유하는 노드를 순위화해 관련 문장으로 준다.
* 1) followUps — 직전 완결 문장(정확히 같거나 용어가 거의 같은 노드) 뒤에 실제로 이어 쓴 문장.
* "다음 문장" 의 가장 강한 근거다(follows 엣지 가중치 순).
* 2) continuations — 접두 꼬리를 품은 문장에서 그 꼬리 뒤에 이어 쓴 텍스트. 긴 꼬리부터
* 짧은 꼬리(어절 경계)로 물러나며 찾는다 — 14자 고정 꼬리는 새 문장에서 거의 맞지 않았다.
* 3) related — 지금 문장·직전 문장·앞 문맥의 용어를 IDF 로 가중해 고른 관련 문장과,
* 그 문장들 뒤에 이어 쓴 문장(follows 1단계 확장).
*/
retrieveContext(prefix: string, limit = 4): GraphContext {
const tail = prefixTail(prefix)
if (tail.length < 4) return { continuations: [], related: [] }
retrieveContext(prefix: string, limit = 4, options: { appName?: string | null } = {}): GraphContext {
const empty: GraphContext = { continuations: [], related: [], followUps: [] }
const normalizedPrefix = prefix.replace(/\s+/gu, ' ').trim()
if (normalizedPrefix.length < 2) return empty
try {
const db = getDatabase()
const pattern = `%${tail.replace(/[%_\\]/gu, '')}%`
const context = analyzeWritingContext(prefix)
const inPrefix = (text: string): boolean => normalizedPrefix.includes(text)
const anchorRows = db
.select()
.from(personalPhrases)
.where(sql`${personalPhrases.phrase} LIKE ${pattern}`)
.orderBy(desc(personalPhrases.lastUsedAt))
.limit(20)
.all()
// (1) 직전 문장 뒤에 이어 쓴 문장
const followUps = this._followUpsAfter(context.lastSentence, context.currentSentence ? 2 : 3, inPrefix)
if (anchorRows.length === 0) return { continuations: [], related: [] }
// (2) 꼬리 이어쓰기 — 지금 문장 안에서만 찾는다 (앞 문장 끝과 섞이지 않게)
const tailSource = context.currentSentence || context.lastSentence
const continuations = this._continuationsForTail(tailSource)
const anchorTexts = anchorRows.map((row) => row.phrase)
const continuations = continuationsFrom(anchorTexts, tail, 3)
const anchorTerms = new Set<string>()
for (const row of anchorRows) {
for (const term of parseTerms(row.terms)) anchorTerms.add(term)
}
const candidates: RelatedCandidate[] = []
const seen = new Set<string>(anchorTexts)
// (a) follows 이웃 — 가장 강한 관계
const edgeRows = db
.select()
.from(phraseEdges)
.where(
and(inArray(phraseEdges.fromPhrase, anchorTexts), eq(phraseEdges.kind, 'follows'))
)
.orderBy(desc(phraseEdges.weight))
.limit(40)
.all()
for (const edge of edgeRows) {
if (seen.has(edge.toPhrase)) continue
seen.add(edge.toPhrase)
candidates.push({
text: edge.toPhrase,
terms: [],
weight: edge.weight * 2,
lastUsedAt: null
})
}
// (b) 용어 공유 — 최근 노드를 훑어 유사도가 높은 것
// (3) 관련 문장 — IDF 가중 용어 겹침 + follows 1단계 확장
const queryTerms = buildQueryTerms([
{ text: context.currentSentence, weight: 2 },
{ text: context.lastSentence, weight: 1.5 },
{ text: context.earlierText.slice(-200), weight: 1 }
])
const recentNodes = db
.select()
.from(personalPhrases)
.orderBy(desc(personalPhrases.lastUsedAt))
.limit(TERM_SCAN_LIMIT)
.all()
const scored = scoreRelatedNodes(
{
terms: queryTerms,
appName: options.appName ?? null,
exclude: (text) => inPrefix(text) || followUps.includes(text)
},
recentNodes.map((row) => ({
text: row.phrase,
terms: parseTerms(row.terms),
count: row.count,
lastUsedAt: row.lastUsedAt,
appName: row.appName
})),
limit + 2
)
for (const node of recentNodes) {
if (seen.has(node.phrase)) continue
const terms = parseTerms(node.terms)
if (terms.length === 0) continue
const similarity = jaccard([...anchorTerms], terms)
if (similarity < SHARES_TERMS_MIN_SIMILARITY) continue
seen.add(node.phrase)
candidates.push({
text: node.phrase,
terms,
weight: 0,
lastUsedAt: node.lastUsedAt
})
const related: string[] = []
const push = (text: string): void => {
if (related.length >= limit || related.includes(text) || followUps.includes(text) || inPrefix(text)) return
related.push(text)
}
const related = rankRelated([...anchorTerms], candidates, limit)
return { continuations, related }
// 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 2개만 확장한다.
const anchors = scored.slice(0, 2).map((item) => item.text)
const hops = anchors.length
? db
.select()
.from(phraseEdges)
.where(and(inArray(phraseEdges.fromPhrase, anchors), eq(phraseEdges.kind, 'follows')))
.orderBy(desc(phraseEdges.weight))
.limit(6)
.all()
: []
for (const item of scored) {
push(item.text)
const hop = hops.find((edge) => edge.fromPhrase === item.text)
if (hop) push(hop.toPhrase)
}
return { continuations, related, followUps }
} catch (error) {
logger.warn(
`그래프 문맥 조회 실패: ${error instanceof Error ? error.message : String(error)}`
)
return { continuations: [], related: [] }
return empty
}
}
/** 문장 뒤에 이어 쓴 문장 (follows). 같은 노드가 없으면 용어가 가장 많이 겹치는 노드로 대신한다. */
private _followUpsAfter(sentence: string, limit: number, exclude: (text: string) => boolean): string[] {
const normalized = sentence.replace(/[.!?。!?…]+$/u, '').replace(/\s+/gu, ' ').trim()
if (normalized.length < 4) return []
const db = getDatabase()
let sources = [normalized]
const exact = db
.select({ phrase: personalPhrases.phrase })
.from(personalPhrases)
.where(eq(personalPhrases.phrase, normalized))
.get()
if (!exact) {
const terms = buildQueryTerms([{ text: normalized, weight: 1 }])
if (terms.size < 2) return []
const near = scoreRelatedNodes(
{ terms },
db
.select()
.from(personalPhrases)
.orderBy(desc(personalPhrases.lastUsedAt))
.limit(TERM_SCAN_LIMIT)
.all()
.map((row) => ({
text: row.phrase,
terms: parseTerms(row.terms),
count: row.count,
lastUsedAt: row.lastUsedAt,
appName: row.appName
})),
2
).filter((item) => item.sharedTerms >= Math.max(2, Math.ceil(terms.size * 0.6)))
if (near.length === 0) return []
sources = near.map((item) => item.text)
}
const edges = db
.select()
.from(phraseEdges)
.where(and(inArray(phraseEdges.fromPhrase, sources), eq(phraseEdges.kind, 'follows')))
.orderBy(desc(phraseEdges.weight), desc(phraseEdges.updatedAt))
.limit(limit * 2)
.all()
const out: string[] = []
for (const edge of edges) {
if (out.includes(edge.toPhrase) || exclude(edge.toPhrase)) continue
out.push(edge.toPhrase)
if (out.length >= limit) break
}
return out
}
/** 최근 문장 노드 원문과 사용 횟수 — 오타 교정의 개인 어휘 근거. */
listRecentTexts(limit = TERM_SCAN_LIMIT): Array<{ text: string; count: number }> {
try {
return getDatabase()
.select({ text: personalPhrases.phrase, count: personalPhrases.count })
.from(personalPhrases)
.orderBy(desc(personalPhrases.lastUsedAt))
.limit(limit)
.all()
} catch (error) {
logger.warn(`그래프 원문 조회 실패: ${error instanceof Error ? error.message : String(error)}`)
return []
}
}
/** 꼬리 뒤 이어쓰기 — 긴 꼬리부터 어절 경계의 짧은 꼬리로 물러난다. */
private _continuationsForTail(text: string): string[] {
const normalized = text.replace(/\s+/gu, ' ').trim()
if (normalized.length < 4) return []
const db = getDatabase()
const tails: string[] = []
for (const length of [SUGGESTION_MEMORY_TAIL_CHARS, 10, 7]) {
let tail = prefixTail(normalized, length)
// 어절 중간에서 시작하지 않게 — 첫 공백 뒤로 민다(공백이 없으면 그대로).
if (tail.length < normalized.length && tail.includes(' ')) tail = tail.slice(tail.indexOf(' ') + 1)
if (tail.length >= 4 && !tails.includes(tail)) tails.push(tail)
}
for (const tail of tails) {
const pattern = `%${tail.replace(/[%_\\]/gu, '')}%`
const rows = db
.select({ phrase: personalPhrases.phrase })
.from(personalPhrases)
.where(sql`${personalPhrases.phrase} LIKE ${pattern}`)
.orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt))
.limit(20)
.all()
const found = continuationsFrom(
rows.map((row) => row.phrase),
tail,
3
)
if (found.length > 0) return found
}
return []
}
/** 용어 공유 엣지를 백필한다 (기존 노드들 사이 관계 보강). */
runMaintenance(limit = MAINTENANCE_NODE_LIMIT): number {
try {