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

@ -115,6 +115,34 @@ export function sanitizeSuggestionLine(line: string, maxChars = SUGGESTION_MAX_O
return stripped === null ? null : normalizeSuggestionText(stripped, maxChars)
}
const WORD_BOUNDARY_AFTER = /^[\s.,!?;:。、,!?…"'”’)\]]/u
/**
* 후보 머리가 접두(지금 문장) 꼬리를 되풀이하면 그 부분을 걷어낸다.
*
* 되풀이로 보는 조건: 접두의 지금 문장 안에서 어절 경계부터 시작하는 꼬리(2자 이상)가 후보의
* 머리와 같고, 후보 쪽에서도 그 뒤가 어절 경계다. "회의실" + "실에서" 같은 우연한 글자 겹침은
* 어절 경계 조건에 걸려 그대로 둔다. 되풀이 말고 남는 것이 없으면 '' 를 돌려준다.
*/
export function stripRestatedPrefix(candidate: string, prefix: string): string {
const sentenceStart = Math.max(
...['.', '!', '?', '。', '!', '?', '…', '\n'].map((mark) => prefix.lastIndexOf(mark) + 1)
)
const sentence = prefix.slice(sentenceStart).replace(/\s+/gu, ' ').trim()
if (sentence.length < 2) return candidate
const lowerCandidate = candidate.toLowerCase()
const lowerSentence = sentence.toLowerCase()
for (let start = 0; start <= lowerSentence.length - 2; start += 1) {
if (start > 0 && lowerSentence[start - 1] !== ' ') continue
const tail = lowerSentence.slice(start)
if (!lowerCandidate.startsWith(tail)) continue
const rest = candidate.slice(tail.length)
if (rest.length > 0 && !WORD_BOUNDARY_AFTER.test(rest)) continue
return rest.trim()
}
return candidate
}
/**
* 모델 출력에서 후보 목록을 뽑아 정제한다.
*
@ -128,13 +156,16 @@ export function parseSuggestionCandidates(
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string[] {
if (!raw) return []
const prefixTail = normalizeRequestPrefix(prefix).slice(-24).toLowerCase()
const normalizedPrefix = normalizeRequestPrefix(prefix)
const out: string[] = []
for (const line of raw.split(/\r?\n/u)) {
const cleaned = sanitizeSuggestionLine(line, maxChars)
if (!cleaned) continue
if (prefixTail && cleaned.toLowerCase().startsWith(prefixTail)) continue
const sanitized = sanitizeSuggestionLine(line, maxChars)
if (!sanitized) continue
// 지금 문장의 앞부분을 다시 쓰고 이어 간 후보는 되풀이한 부분만 걷어낸다 — 그대로 넣으면
// "CI는 CI는 통과했고…" 처럼 같은 말이 두 번 들어간다(실측). 되풀이뿐이면 버린다.
const cleaned = stripRestatedPrefix(sanitized, normalizedPrefix)
if (!cleaned || cleaned.length < 2) continue
if (out.some((existing) => existing.toLowerCase() === cleaned.toLowerCase())) continue
out.push(cleaned)
if (out.length >= maxCandidates) break
@ -308,3 +339,104 @@ export function joinSuggestion(rawPrefix: string, candidate: string, joint: Sugg
if (UNSPACED_JOIN_SCRIPT.test(before) || UNSPACED_JOIN_SCRIPT.test(after)) return candidate
return ` ${candidate}`
}
// ============================================================
// 이어 쓰기(prefill) 출력 정제
// ============================================================
export interface ContinuationOptions {
/** 지금 문장 마저 쓰기인가, 다음 문장인가 */
mode: 'complete-sentence' | 'next-sentence'
/** 모델 차례 앞에 미리 넣은 사용자 글 (모델은 이 바로 뒤부터 쓴다) */
prefill: string
/** 이미 쓴 문장들 — 모델이 같은 문장을 되풀이하면 버린다 */
writtenSentences?: readonly string[]
/**
* 사용자가 친 원문이 공백으로 끝났는가(단어를 끝냈는가). prefill 은 끝 공백을 빼고 보낸다 —
* 끝 공백 하나만 남은 토큰 상태는 모델 분포를 흔들어 엉뚱한 말을 만든다(실측). 그 대신 모델이
* 끝난 단어에 글자를 붙여 쓰면(공백 없이 시작) 버린다.
*/
wordFinished?: boolean
/** 사용자가 이모지를 쓰는가 — 아니면 모델이 붙인 이모지를 지운다 */
allowEmoji?: boolean
maxChars?: number
}
export interface ExtractedContinuation {
text: string
joint: SuggestionJoint
}
const EMOJI_PATTERN = /\p{Extended_Pictographic}|[\u{1F3FB}-\u{1F3FF}]|\u200d|\ufe0f/gu
const LEADING_LIST_MARKER = /^(?:[-*•]|\d{1,3}[.)])\s+/u
/** 텍스트에 이모지가 있는가 (사용자 습관 판별). */
export function containsEmoji(text: string): boolean {
return /\p{Extended_Pictographic}/u.test(text)
}
/** 원형 템플릿 응답에 섞일 수 있는 특수 토큰·마크다운 강조. */
const SPECIAL_TOKEN_PATTERN = /<\|?\/?(?:turn|start_of_turn|end_of_turn|eos|bos|im_start|im_end|channel|message)\|?>|<(?:turn|end_of_turn|eos)\|>/gu
const MARKDOWN_EMPHASIS_PATTERN = /\*\*|__/gu
/** 첫 문장의 끝 — 종결 부호(+닫는 따옴표/괄호) 뒤가 공백이거나 끝. "3.5", "v1.2" 의 점은 아니다. */
const FIRST_SENTENCE_END = /[.!?。!?…]+["'”’)\]]*(?=\s|$)/u
function comparable(text: string): string {
return text.replace(/[\s.!?。!?…,"'“”‘’]+/gu, '').toLowerCase()
}
/**
* prefill 한 응답(모델이 사용자 글 바로 뒤부터 쓴 텍스트)에서 삽입할 이어 쓰기를 뽑는다.
*
* 응답 원문은 사용자 글과 이음새까지 그대로 이어진다 — 첫 글자가 공백이면 새 단어이고, 아니면
* 단어 중간("회의실" + "에서")이다. 그 정보를 joint 로 보존한 뒤 첫 줄·첫 문장만 남긴다.
* 사용자 글이 이어지는 것이므로 목록 표지·따옴표는 지우지 않는다(사용자가 목록을 쓰는 중일 수 있다).
*/
export function extractContinuation(raw: string, options: ContinuationOptions): ExtractedContinuation | null {
const maxChars = options.maxChars ?? SUGGESTION_MAX_OUTPUT_CHARS
let text = raw.replace(SPECIAL_TOKEN_PATTERN, '').replace(MARKDOWN_EMPHASIS_PATTERN, '')
if (options.mode === 'complete-sentence') {
// 줄바꿈부터 시작하면 모델은 지금 문장이 이미 끝났다고 본 것이다 — 이어 쓸 것이 없다.
if (/^[ \t]*\n/u.test(text)) return null
} else {
text = text.replace(/^\s*\n/u, ' ')
}
const startsNewWord = /^\s/u.test(text)
if (!options.allowEmoji) text = text.replace(EMOJI_PATTERN, '')
// 끝난 단어 뒤에 모델이 글자를 붙였다("회의실 " + "에서") — 그대로 넣으면 띄어 쓴 조사가 된다.
if (options.wordFinished && !startsNewWord && /^[\p{L}\p{N}]/u.test(text)) return null
text = text.replace(/^\s+/u, '').split(/\r?\n/u)[0] ?? ''
// 목록 줄이 아닌데 "- " 로 시작하면 힌트 목록 형식을 베낀 것이다.
const prefillLastLine = options.prefill.split('\n').pop() ?? ''
const onListLine = LEADING_LIST_MARKER.test(prefillLastLine.trim()) || /\n$/u.test(options.prefill)
if (!onListLine) text = text.replace(LEADING_LIST_MARKER, '')
// 모델이 지금 문장을 처음부터 다시 쓴 경우 — 이미 쓴 부분을 걷어낸다.
const prefill = options.prefill.replace(/\s+/gu, ' ').trim()
if (options.mode === 'complete-sentence' && prefill.length >= 4) {
const normalized = text.replace(/\s+/gu, ' ')
if (normalized.startsWith(prefill)) text = normalized.slice(prefill.length).replace(/^\s+/u, '')
}
const end = FIRST_SENTENCE_END.exec(text)
if (end) text = text.slice(0, end.index + end[0].length)
if (INSTRUCTION_ECHO_PATTERN.test(text) || TEMPLATE_ECHO_PATTERN.test(text)) return null
const normalized = normalizeSuggestionText(text, maxChars)
// 마저 쓰기에서는 마침표 하나("뵙겠습니다" + ".")도 정당한 나머지다 — 글자 수 하한을 따로 둔다.
const result = normalized ?? (options.mode === 'complete-sentence' && text.trim().length > 0 ? text.trim() : null)
if (!result || !/[\p{L}\p{N}]/u.test(result)) return null
// 이미 쓴 문장 되풀이
const key = comparable(result)
if (key.length >= 6 && (options.writtenSentences ?? []).some((sentence) => comparable(sentence) === key)) return null
const joint: SuggestionJoint =
options.mode === 'complete-sentence' && !startsNewWord && !options.wordFinished && !/\s$/u.test(options.prefill)
? 'attach'
: 'separate'
return { text: result, joint }
}