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

@ -32,6 +32,7 @@ import {
emptyActivityBucket,
extractPhrases,
isLearnablePhrase,
isTerminalApp,
manhattanDistance,
mergeActivityBucket,
rankFlowWindows,
@ -56,6 +57,7 @@ import {
type PhraseSource,
type PhysicalRect
} from '@d3ro/core/input-intelligence'
import { RecentWritesBuffer, type RecentWrite, type RecentWriteMeta } from '@d3ro/core/recent-writes'
import { getDatabase } from '../db'
import { inputActivity, personalPhrases, suggestions as suggestionsTable, typingSamples } from '../db/schema'
import { configGet, configSet } from './ConfigService'
@ -104,8 +106,17 @@ export interface TypingContext {
* 마지막 편집이 문서 끝에서 일어났을 때만 true. 생략하면 true 로 본다(호환).
*/
caretReliable?: boolean
/**
* 커서 앞 문서 전체 (원문, 최대 DOCUMENT_BEFORE_MAX_CHARS). prefix 는 400자 창이라 글 앞쪽의
* 인사·이름·날짜를 모른다 — 제안 프롬프트가 첫머리·사실을 여기서 뽑는다.
* 문서형 컨트롤(터미널 버퍼 등)·비밀번호 칸은 null. 생략하면 prefix 만 쓴다(호환).
*/
documentBefore?: string | null
}
/** 제안 문맥으로 넘길 커서 앞 문서 길이 상한. */
const DOCUMENT_BEFORE_MAX_CHARS = 6000
interface InputTelemetryEvents {
'state-changed': (state: InputTelemetryState) => void
'typed-context': (context: TypingContext) => void
@ -192,6 +203,13 @@ class InputTelemetryService extends EventEmitter {
private _lastEditAtEnd = true
/** 클릭 뒤 첫 스냅샷에서 기준선을 다시 잡는다 */
private _rebaseFocusText = false
/** 포커스 깜빡임 뒤 돌아온 칸 — 키보드로 친 채 돌아왔으므로 이미 편집한 칸으로 본다 */
private _typedIntoFocus = false
/** 직전 스냅샷이 편집 가능한 칸이었는가 / 어느 창이었는가 (포커스 깜빡임 판정) */
private _prevSnapshotEditable = false
private _lastFocusHwnd: number | null = null
/** 이 창에서 조금 전에 쓴(보낸) 글 — 메모리 전용, 제안 문맥용 */
private readonly _recentWrites = new RecentWritesBuffer()
private _lastActiveTickAt = 0
private _lastMouse: { x: number; y: number } | null = null
private _lastClickAt = 0
@ -215,6 +233,11 @@ class InputTelemetryService extends EventEmitter {
/** 곧(또는 방금) 프로그램이 삽입한 텍스트 — 다음 diff 에서 "타이핑" 으로 학습하지 않는다. */
private _expectedInserts: Array<{ id: number; text: string; expiresAt: number }> = []
private _expectedInsertSeq = 0
/** 통계에서 뺄 프로그램 키 남은 수와 유효 시각 */
private _programmaticKeys = 0
/** 진단용 마지막 키 종류 (키 값 아님) */
private _lastKeyDiag = '-'
private _programmaticKeysUntil = 0
private _prunedAt = 0
@ -252,6 +275,20 @@ class InputTelemetryService extends EventEmitter {
return this._lastContext
}
/** 마지막 키보드 입력 시각 (ms) — 오타 교정이 "스냅샷 뒤 사용자가 더 쳤는가" 를 확인한다. */
get lastKeyAt(): number {
return this._lastKeyAt
}
/**
* 곧 프로그램이 키 count 개를 보낸다 — 그 키들은 입력 통계에 넣지 않는다.
* 남은 예고는 ttlMs 뒤 무효다(보내지 못한 키가 사용자 키를 삼키지 않게).
*/
expectProgrammaticKeys(count: number, ttlMs = 3000): void {
this._programmaticKeys = Math.max(0, count)
this._programmaticKeysUntil = Date.now() + ttlMs
}
setSuggestionPresentationActive(active: boolean): void {
this._suggestionPresentationActive = active
if (!active && this._presentationValidationTimer) {
@ -317,6 +354,8 @@ class InputTelemetryService extends EventEmitter {
}
stop(): void {
// 입력 관찰을 끄면 메모리에 잡아 둔 "조금 전에 쓴 글" 도 버린다.
this._recentWrites.clear()
if (!this._running) {
this.setSuggestionPresentationActive(false)
return
@ -360,9 +399,15 @@ class InputTelemetryService extends EventEmitter {
dispose(): void {
this.stop()
this._recentWrites.clear()
this.removeAllListeners()
}
/** 같은 창에서 조금 전에 쓴(보내서 칸이 비워진) 글 — 오래된 것부터. 메모리에만 있다. */
listRecentWrites(meta: RecentWriteMeta, limit = 4): RecentWrite[] {
return this._recentWrites.listFor(meta, Date.now(), limit)
}
private _detachListeners(): void {
if (this._onKeyDown) {
uIOhook.removeListener('keydown', this._onKeyDown)
@ -398,11 +443,28 @@ class InputTelemetryService extends EventEmitter {
private _handleKeyDown(event: UiohookKeyboardEvent): void {
this._syncModifiers(event)
// 프로그램이 보낸 키(오타 교정의 백스페이스·붙여넣기)는 통계에 넣지 않는다 — 사용자의
// 수정 빈도(backspaces)를 부풀린다. 시각·스냅샷 예약은 그대로 해 교정 뒤 문맥을 다시 읽는다.
if (this._programmaticKeys > 0 && Date.now() <= this._programmaticKeysUntil) {
this._programmaticKeys -= 1
this._lastKeyAt = Date.now()
this._scheduleTextSnapshot()
return
}
this._registerInput(true)
const bucket = this._bucket()
// uiohook 키코드는 VK 와 다른 표계다 — 정본(VK)으로 변환해 분류한다.
const vk = uiohookCodeToVk(event.keycode)
const keyClass = vk === null ? 'other' : classifyKeyStroke(vk, this._modifiers)
// 한글·일본어 IME 가 켜져 있으면 Windows 는 글자 키를 VK_PROCESSKEY 로 넘기고, uiohook 은 그것을
// 변환표에 없는 키코드로 보낸다 — 그대로 'other' 로 두면 한글 타이핑 전체가 "타이핑 아님" 이 되어
// 제안이 영영 뜨지 않았다(2026-10-03 실측: 글자 키가 전부 key=other). 수정자 없이 눌린 미지의
// 키는 IME 조합 키로 본다. 실제 텍스트 변화(editedSinceFocus)가 함께 있어야 제안이 열린다.
const keyClass =
vk === null
? this._modifiers.ctrl || this._modifiers.alt || this._modifiers.meta
? 'shortcut'
: 'ime'
: classifyKeyStroke(vk, this._modifiers)
if (keyClass === 'shortcut') bucket.shortcuts += 1
else bucket.keystrokes += 1
@ -410,6 +472,8 @@ class InputTelemetryService extends EventEmitter {
this._lastKeyAt = Date.now()
if (TYPING_KEY_CLASSES.has(keyClass)) this._lastTypedAt = this._lastKeyAt
// 진단: 키 값이 아니라 종류·수정자만 남긴다 (typed 판정이 왜 틀리는지 로그로 보이게)
this._lastKeyDiag = `${keyClass}${vk === null ? `?${event.keycode}` : ''}${this._modifiers.ctrl ? '+C' : ''}${this._modifiers.alt ? '+A' : ''}${this._modifiers.meta ? '+M' : ''}`
this._scheduleTextSnapshot()
}
@ -638,6 +702,14 @@ class InputTelemetryService extends EventEmitter {
: documentLike
? lastLineOf(tail)
: tail
const documentBefore = snapshot.isPassword
? null
: caretKnown
? snapshot.text.slice(0, snapshot.caretOffset ?? snapshot.text.length)
: documentLike
? null
: snapshot.text
context.documentBefore = documentBefore === null ? null : documentBefore.slice(-DOCUMENT_BEFORE_MAX_CHARS)
this._caretFallback = !caretKnown
// 포커스 식별: 칸이 바뀌었거나 클릭이 있었으면 그 시점 텍스트를 기준선으로 저장한다
@ -647,11 +719,34 @@ class InputTelemetryService extends EventEmitter {
const focusKey = computeFocusKey(this._foreground.hwnd, snapshot.controlType ?? null, snapshot.controlName ?? null)
const textForFocus = snapshot.isPassword ? '' : snapshot.text
if (focusKey !== this._lastFocusKey || this._rebaseFocusText) {
// 포커스 깜빡임: 같은 창에서 타이핑하는 동안 UIA 포커스가 입력칸 ↔ 읽을 수 없는 요소(legacy)를
// 오간다(실측 Chrome 2026-10-03: 보류 사유 not-typing 122회). 그때마다 기준선을 다시 잡으면
// 방금 친 글이 "들어올 때부터 있던 글" 이 되어 제안이 영영 안 뜬다. 클릭 없이 키보드로 치다가
// 읽을 수 없는 요소를 거쳐 같은 창의 입력칸으로 돌아온 것이면 이미 편집한 칸으로 본다.
const now = Date.now()
this._typedIntoFocus =
!this._rebaseFocusText &&
this._foreground.hwnd !== null &&
this._foreground.hwnd === this._lastFocusHwnd &&
!this._prevSnapshotEditable &&
this._lastTypedAt > this._lastClickAt &&
now - this._lastTypedAt <= SUGGESTION_DEFAULTS.recentTypingWindowMs
this._lastFocusKey = focusKey
this._textAtFocus = textForFocus
this._rebaseFocusText = false
}
context.editedSinceFocus = textForFocus !== this._textAtFocus
context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus
// 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다.
// 비밀번호·편집 불가·조합 중 칸과 터미널(명령 기록)은 보지 않는다.
if (snapshot.isEditable && !snapshot.isPassword && !snapshot.isComposing && !isTerminalApp(this._foreground.appName)) {
this._recentWrites.observe(
focusKey,
snapshot.text,
{ windowHandle: this._foreground.hwnd, appName: this._foreground.appName, windowTitle: context.windowTitle },
Date.now()
)
}
// 케어렛을 모르면 "문서 끝 = 커서" 가정이 맞는지 마지막 편집 위치로 확인한다.
// 문서 중간을 고쳤다면 접두(문서 끝)는 커서와 무관하다 — 제안·수락을 막는다.
@ -668,6 +763,10 @@ class InputTelemetryService extends EventEmitter {
}
}
// 포커스 깜빡임 판정용 — 이번 스냅샷이 편집 가능한 칸이었는가, 어느 창이었는가.
this._prevSnapshotEditable = snapshot.available && snapshot.isEditable
this._lastFocusHwnd = this._foreground.hwnd
this._recordReadabilityEvidence(snapshot)
// 진단: 왜 제안이 안 뜨는지 로그만으로 판단할 수 있게 스냅샷 요약을 남긴다.
@ -676,7 +775,7 @@ class InputTelemetryService extends EventEmitter {
`pw=${snapshot.isPassword} comp=${snapshot.isComposing} src=${snapshot.textSource} ` +
`len=${snapshot.text.length} caret=${snapshot.caretOffset ?? -1} tail=${this._caretFallback} ` +
`anchor=${context.anchor ? 'yes' : 'no'} app=${this._foreground.appName ?? '-'} ` +
`reason=${snapshot.reason ?? '-'}`
`reason=${snapshot.reason ?? '-'} key=${this._lastKeyDiag}`
)
this._lastSnapshotSummary = {