fix(suggestion): insert accepted suggestions reliably and learn typing as whole sentences

Acceptance waited for modifiers using only the uiohook-tracked set; a missed keyup
made it time out after 1.5 s and paste while Ctrl/Alt counted as held, so nothing
was inserted. Trust GetAsyncKeyState instead, and suppress new suggestions while an
accept is in flight.

Typed deltas were saved per snapshot (every 0.4-0.8 s), storing mid-word fragments.
Buffer them per field and save one diff on idle, sentence end, send or focus change;
drop short pieces, URLs, trailing jamo and truncated emoji.
This commit is contained in:
Yun Chan 2026-10-24 13:15:29 +09:00
parent 006909065f
commit cdeeff4c11
7 changed files with 341 additions and 23 deletions

View file

@ -138,6 +138,14 @@ const MAX_SAMPLE_CHARS = 500
* settle·UIA 조회(최대 1.5초)를 거쳐 온다 — 그 합을 넉넉히 덮는다.
*/
const PROGRAMMATIC_INSERT_TTL_MS = 10_000
/**
* 타이핑 학습은 스냅샷 diff(0.4~0.8초마다)를 바로 저장하지 않고 필드별로 모았다가 문장 단위로 저장한다.
* 바로 저장하면 "찬받고 초콜릿을 받은 아이. 아빠" / "도 잘했으니까…" 처럼 단어 중간에서 잘린
* 조각이 표본·문구로 쌓여 제안 힌트를 오염시켰다(실측 2026-10-24 DB).
*/
const LEARN_IDLE_FLUSH_MS = 2000
/** diff 붙여넣기 판정(200자)에 걸리기 전에 끊어 저장한다. */
const LEARN_MAX_PENDING_CHARS = 150
const RETENTION_PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000
const MAX_READABILITY_APPS = 64
@ -233,6 +241,14 @@ class InputTelemetryService extends EventEmitter {
private _appReadability = new Map<string, AppReadabilityEvidence>()
/** 곧(또는 방금) 프로그램이 삽입한 텍스트 — 다음 diff 에서 "타이핑" 으로 학습하지 않는다. */
private _expectedInserts: Array<{ id: number; text: string; expiresAt: number }> = []
/** 아직 저장하지 않은 타이핑 구간 — 같은 필드에서 baseline → latest 로 바뀐 부분을 한 번에 학습한다. */
private _pendingLearn: {
baseline: string
latest: string
appName: string | null
windowTitle: string | null
} | null = null
private _learnFlushTimer: ReturnType<typeof setTimeout> | null = null
private _expectedInsertSeq = 0
/** 통계에서 뺄 프로그램 키 남은 수와 유효 시각 */
private _programmaticKeys = 0
@ -383,6 +399,7 @@ class InputTelemetryService extends EventEmitter {
this._settleTimer = null
}
this.setSuggestionPresentationActive(false)
this.flushPendingLearning()
this._flush()
this._lastSnapshot = null
this._lastSnapshotKey = ''
@ -833,28 +850,103 @@ class InputTelemetryService extends EventEmitter {
this._lastSnapshot = snapshot
this._lastSnapshotKey = key
// 필드가 바뀌면 이전 텍스트와 diff 할 수 없다 — 기준선만 저장하고 통계는 건너뛴다.
if (focusChanged || !previous) return
// 필드가 바뀌면 이전 텍스트와 diff 할 수 없다 — 모아 둔 학습을 저장하고 기준선만 잡는다.
if (focusChanged || !previous) {
this.flushPendingLearning()
return
}
const delta = computeTypedDelta(previous.text, snapshot.text, {
keepText: configGet('inputLearnTypedText') === true
})
if (delta.replaced) return
if (delta.insertedChars === 0 && delta.insertedWords === 0) return
const keepText = configGet('inputLearnTypedText') === true
const delta = computeTypedDelta(previous.text, snapshot.text, { keepText })
if (delta.replaced) {
// 붙여넣기 — 직접 친 글이 아니다. 그 앞까지 친 것만 저장하고 새로 모은다.
this._flushPendingLearningAt(previous.text)
return
}
if (delta.insertedChars === 0 && delta.insertedWords === 0) {
// 지우기만 했다. 칸이 비었거나 기준선보다 짧아졌으면(메시지 전송 등) 비우기 직전까지가 친 글이다.
const pending = this._pendingLearn
if (pending && (snapshot.text.length === 0 || snapshot.text.length < pending.baseline.length)) {
this._flushPendingLearningAt(previous.text)
} else if (pending) {
pending.latest = snapshot.text
}
return
}
const bucket = this._bucket()
bucket.chars += delta.insertedChars
bucket.words += delta.insertedWords
bucket.sentences += delta.insertedSentences
const typedText = delta.insertedText ? this._withoutExpectedInsert(delta.insertedText) : ''
if (typedText) {
this._learnText(typedText, {
appName: this._foreground.appName,
windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle,
source: 'typed'
})
if (!delta.insertedText) return
const typedText = this._withoutExpectedInsert(delta.insertedText)
if (typedText !== delta.insertedText) {
// 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친
// 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다.
this._flushPendingLearningAt(previous.text)
if (typedText) {
this._learnText(typedText, {
appName: this._foreground.appName,
windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle,
source: 'typed'
})
}
return
}
if (!this._pendingLearn) {
this._pendingLearn = {
baseline: previous.text,
latest: snapshot.text,
appName: this._foreground.appName,
windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle
}
} else {
this._pendingLearn.latest = snapshot.text
}
const grown = snapshot.text.length - this._pendingLearn.baseline.length
if (/[.!?…。?!\n]\s*$/u.test(snapshot.text) || grown >= LEARN_MAX_PENDING_CHARS) {
this.flushPendingLearning()
return
}
this._scheduleLearnFlush()
}
private _scheduleLearnFlush(): void {
if (this._learnFlushTimer) clearTimeout(this._learnFlushTimer)
this._learnFlushTimer = setTimeout(() => {
this._learnFlushTimer = null
this.flushPendingLearning()
}, LEARN_IDLE_FLUSH_MS)
}
/** 모아 둔 타이핑 구간을 지금 학습한다 (멈춤·문장 끝·포커스 이동·종료 시). */
flushPendingLearning(): void {
this._flushPendingLearningAt(null)
}
private _flushPendingLearningAt(latestOverride: string | null): void {
const pending = this._pendingLearn
this._discardPendingLearning()
if (!pending || configGet('inputLearnTypedText') !== true) return
// baseline → latest 를 한 번에 diff 한다 — 친 뒤 지운 오타·IME 가 바꾼 글자는 최종 결과만 남는다.
const delta = computeTypedDelta(pending.baseline, latestOverride ?? pending.latest, { keepText: true })
if (delta.replaced || !delta.insertedText) return
this._learnText(delta.insertedText, {
appName: pending.appName,
windowTitle: pending.windowTitle,
source: 'typed'
})
}
private _discardPendingLearning(): void {
if (this._learnFlushTimer) {
clearTimeout(this._learnFlushTimer)
this._learnFlushTimer = null
}
this._pendingLearn = null
}
/**
@ -944,10 +1036,13 @@ class InputTelemetryService extends EventEmitter {
const text = sanitizeSample(
raw
.split(/\r?\n/u)
.filter((line) => isLearnablePhrase(line))
.map(stripTrailingJamo)
.filter((line) => isLearnablePhrase(line) && !isUrlLike(line))
.join('\n')
)
if (!text) return
// 직접 친 글이 너무 짧으면 문체 표본이 아니다("처음", "pow") — 음성·수락 문장은 이미 문장 단위다.
if (meta.source === 'typed' && text.replace(/\s/gu, '').length < MIN_TYPED_SAMPLE_CHARS) return
try {
const db = getDatabase()
@ -1481,6 +1576,7 @@ class InputTelemetryService extends EventEmitter {
this._sessionTotals = emptyActivityBucket()
this._lastSnapshot = null
this._lastSnapshotKey = ''
this._discardPendingLearning()
logger.info('입력 텔레메트리 데이터 전체 삭제')
} catch (error) {
logger.warn(`입력 데이터 삭제 실패: ${error instanceof Error ? error.message : String(error)}`)
@ -1624,12 +1720,28 @@ function formatLocalDate(date: Date): string {
return `${year}-${month}-${day}`
}
const MIN_TYPED_SAMPLE_CHARS = 4
/** 주소·쿼리 문자열 한 줄은 문체 표본이 아니다. */
function isUrlLike(line: string): boolean {
const trimmed = line.trim()
if (/^(https?:\/\/|www\.)\S*$/iu.test(trimmed)) return true
return !/\s/u.test(trimmed) && /[/=&?#]/u.test(trimmed)
}
/** 조합이 덜 끝난 채 잡힌 끝 자모("아냐 ㅇ")를 뗀다. */
function stripTrailingJamo(line: string): string {
return line.replace(/\s*[\u3131-\u318e]+$/u, '')
}
/** 제어문자 제거 + 공백 정규화. 2자 미만은 버린다. */
function sanitizeSample(raw: string): string {
let stripped = ''
for (const char of raw) {
const code = char.codePointAt(0) ?? 0
// 제어문자(개행/탭 포함)는 공백으로 바다 — 학습 표본에 제어문자를 남기지 않는다.
// 사용 영역(PUA)·짝 잃은 서로게이트는 이모지가 16비트로 잘려 들어온 흔적이다(🍫 → U+F36B) — 버린다.
if ((code >= 0xe000 && code <= 0xf8ff) || (code >= 0xd800 && code <= 0xdfff)) continue
stripped += code < 0x20 || code === 0x7f ? ' ' : char
}
const cleaned = stripped.replace(/\s+/gu, ' ').trim()