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

@ -28,13 +28,16 @@ import {
import { NON_PROSE_GLYPH_PATTERN } from './terminal-prompt'
import type { AnchorKind, PhysicalRect } from './popup-placement'
import { countLexicalWords } from './text-segmentation'
import { extractTerms } from './personal-graph'
export {
SUGGESTION_CONTEXT_MAX_CHARS,
SUGGESTION_MAX_OUTPUT_CHARS,
buildLocalSuggestionCandidateEntries,
buildLocalSuggestionCandidates,
containsEmoji,
endsSentence,
extractContinuation,
joinSuggestion,
normalizeRequestPrefix,
normalizeSessionPrefix,
@ -43,7 +46,13 @@ export {
sanitizeSuggestionLine,
stripModelArtifacts
} from './suggestion-text'
export type { LocalSuggestionCandidate, LocalSuggestionHints, SuggestionJoint } from './suggestion-text'
export type {
ContinuationOptions,
ExtractedContinuation,
LocalSuggestionCandidate,
LocalSuggestionHints,
SuggestionJoint
} from './suggestion-text'
export { extractTerminalPromptPrefix } from './terminal-prompt'
// ============================================================
@ -193,7 +202,11 @@ export const PASTE_INSERTION_THRESHOLD_CHARS = 200
* computeTypedDelta 와 같은 공통 접두/접미 분해를 쓴다. 바뀐 구간 뒤에 남은 공통 접미가 없으면
* 끝에서 쓰거나 지운 것이다. 같으면(편집 없음) true.
*/
export function isEditAtTextEnd(prevText: string, nextText: string): boolean {
export function isEditAtTextEnd(prevRaw: string, nextRaw: string): boolean {
// RichEdit 계열(카카오톡 등)은 값 끝에 줄끝 문자(\r)를 붙여 돌려준다. 그대로 비교하면 모든 편집이
// "뒤에 기존 글이 남은 중간 편집" 이 되어 caret-unknown 으로 막혔다(실측 2026-10-03, 카톡 79회).
const prevText = prevRaw.replace(/[\r\n\u200b\ufeff]+$/u, '')
const nextText = nextRaw.replace(/[\r\n\u200b\ufeff]+$/u, '')
if (prevText === nextText) return true
let prefix = 0
const maxPrefix = Math.min(prevText.length, nextText.length)
@ -827,9 +840,24 @@ export function isLearnablePhrase(text: string): boolean {
* 텍스트가 컨트롤 이름과 같으면 빈 칸으로 취급한다.
*/
export function withoutPlaceholderText(snapshot: FocusSnapshot): FocusSnapshot {
const name = snapshot.controlName?.trim()
if (!name || snapshot.text.trim() !== name) return snapshot
return { ...snapshot, text: '', caretOffset: null }
const trimmedEnd = withoutRichEditEndMark(snapshot)
const name = trimmedEnd.controlName?.trim()
if (!name || trimmedEnd.text.trim() !== name) return trimmedEnd
return { ...trimmedEnd, text: '', caretOffset: null }
}
/**
* RichEdit 계열 입력칸(카카오톡 등)이 값 끝에 붙이는 문단 끝 표시(\r 하나)를 걷어낸다.
*
* 그대로 두면 커서 앞 글이 공백으로 끝난 것처럼 보여, 수락한 제안이 띄어쓰기 없이 들러붙었다
* (실측 2026-10-03: "오늘 저녁에 시간 되면\r" + "같이 저녁 먹을래?" → "되면같이"). 사용자가 넣은
* 줄바꿈은 그 앞에 \r 이 하나 더 있으므로("…\r\r") 하나만 지운다. 표준 줄바꿈(\r\n)은 건드리지 않는다.
*/
export function withoutRichEditEndMark(snapshot: FocusSnapshot): FocusSnapshot {
if (!snapshot.text.endsWith('\r')) return snapshot
const text = snapshot.text.slice(0, -1)
const caretOffset = snapshot.caretOffset === null ? null : Math.min(snapshot.caretOffset, text.length)
return { ...snapshot, text, caretOffset }
}
// ============================================================
@ -1092,6 +1120,22 @@ export interface PhraseHintOptions {
appName?: string | null
now?: number
halfLifeDays?: number
/**
* 지금 쓰는 글의 용어(어간화된 것). 주면 겹치는 용어가 많은 문구를 앞세우고,
* 겹치는 용어도 없고 같은 앱도 아닌 문구는 뺀다 — 문맥과 무관한 "자주 쓰는 말" 이
* 프롬프트를 흐리지 않게 한다. 생략하면 예전처럼 빈도·최근·앱만 본다.
*/
relevanceTerms?: ReadonlySet<string>
}
/** 문구가 주어진 용어 중 몇 개를 품는가 (문구 쪽도 같은 규칙으로 어간화). */
function countSharedTerms(phrase: string, terms: ReadonlySet<string>): number {
if (terms.size === 0) return 0
let shared = 0
for (const term of new Set(extractTerms(phrase, 16))) {
if (terms.has(term)) shared += 1
}
return shared
}
/**
@ -1130,6 +1174,7 @@ export function selectPhraseHints(
? (options.halfLifeDays as number)
: 30
const requestedApp = options.appName?.trim().toLowerCase() ?? null
const relevanceTerms = options.relevanceTerms ?? null
const candidates = phrases
.filter((p) => p.phrase.length <= SUGGESTION_MAX_OUTPUT_CHARS)
.filter((p) => !tail || !p.phrase.toLowerCase().endsWith(tail))
@ -1138,13 +1183,17 @@ export function selectPhraseHints(
const ageDays = Math.max(0, (now - timestamp) / (24 * 60 * 60 * 1000))
const appMatches =
requestedApp !== null && phrase.appName !== null && phrase.appName.trim().toLowerCase() === requestedApp
const relevance = relevanceTerms ? countSharedTerms(phrase.phrase, relevanceTerms) : 0
const score =
(1 + Math.log2(Math.max(1, phrase.count))) *
Math.pow(0.5, ageDays / halfLifeDays) *
(appMatches ? 1.75 : 1)
(appMatches ? 1.75 : 1) *
(1 + relevance * 1.5)
return { phrase, score, timestamp }
return { phrase, score, timestamp, relevance, appMatches }
})
// 문맥 용어가 주어지면, 지금 글과 겹치는 용어가 없고 다른 앱에서 쓴 문구는 프롬프트 잡음이다.
.filter((entry) => !relevanceTerms || relevanceTerms.size === 0 || entry.relevance > 0 || entry.appMatches)
.sort(
(a, b) =>
b.score - a.score ||
@ -1214,6 +1263,8 @@ export interface SuggestionState {
telemetryEnabled: boolean
/** 오버레이 클릭 허용 여부 (false → 완전 클릭 통과) */
overlayInteractive: boolean
/** 입력 중 오타 자동 교정 켜짐 (설정 UI 표시) */
typoAutoCorrect: boolean
/** 후보를 만든 로컬 근거의 수량만 노출한다. */
provenance: SuggestionProvenance | null
}