fix(input,core): fix live punctuation typo triggers, expected insert cleanup, and ngram scan

This commit is contained in:
Yun Chan 2026-11-14 15:14:53 +09:00
parent a37dd63909
commit 2a009e421a
8 changed files with 640 additions and 53 deletions

View file

@ -163,6 +163,8 @@ const PROGRAMMATIC_INSERT_TTL_MS = 10_000
const LEARN_IDLE_FLUSH_MS = 2000
/** diff 붙여넣기 판정(200자)에 걸리기 전에 끊어 저장한다. */
const LEARN_MAX_PENDING_CHARS = 150
/** 오타 자동 교정의 어절 끝/조합 정지 판정(650~690ms)을 넘긴 직후 UIA 스냅샷을 찍는다. */
const TYPO_SETTLE_DELAY_MS = 700
const RETENTION_PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000
const MAX_READABILITY_APPS = 64
@ -196,6 +198,8 @@ class InputTelemetryService extends EventEmitter {
private _textTimer: NodeJS.Timeout | null = null
/** 디바운스 이후의 settle 스냅샷 — 제안 게이트는 더 늦게 열린다 */
private _settleTimer: NodeJS.Timeout | null = null
/** 제안 비활성·짧은 접두에서도 오타 장문 정지 교정을 놓치지 않도록 700ms 에 스냅샷을 보장한다. */
private _typoSettleTimer: NodeJS.Timeout | null = null
/** 백그라운드 주기 샘플러 — 타이핑이 이어져도 계속 관측한다 */
private _sampleTimer: NodeJS.Timeout | null = null
/** 주기 샘플 스냅샷 진행 중 (중복 방지) */
@ -450,6 +454,10 @@ class InputTelemetryService extends EventEmitter {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
if (this._typoSettleTimer) {
clearTimeout(this._typoSettleTimer)
this._typoSettleTimer = null
}
this.setSuggestionPresentationActive(false)
this._terminalTracker.reset()
this.flushPendingLearning()
@ -575,21 +583,25 @@ class InputTelemetryService extends EventEmitter {
const vk = uiohookCodeToVk(event.keycode)
// 프로그램이 보낸 키(오타 교정의 백스페이스·확정용 공백·Ctrl+V 붙여넣기)만 통계와 버퍼에서 제외한다.
// 치환 도중 사용자가 실제로 누른 일반 글자·한글 키까지 삼키면 글자가 빠지거나 밀리는 버그가 생긴다.
if (this._programmaticKeys > 0 && Date.now() <= this._programmaticKeysUntil) {
const isExpectedProgrammaticKey =
vk === 0x08 ||
vk === 0x20 ||
this._modifiers.ctrl ||
vk === 0x11 ||
vk === 0xa2 ||
vk === 0xa3
if (isExpectedProgrammaticKey) {
this._inputRevision += 1
this._programmaticKeys -= 1
if (this._programmaticKeys === 0) {
this._scheduleTextSnapshot()
if (this._programmaticKeys > 0) {
if (Date.now() > this._programmaticKeysUntil) {
this._programmaticKeys = 0
} else {
const isExpectedProgrammaticKey =
vk === 0x08 ||
vk === 0x20 ||
this._modifiers.ctrl ||
vk === 0x11 ||
vk === 0xa2 ||
vk === 0xa3
if (isExpectedProgrammaticKey) {
this._inputRevision += 1
this._programmaticKeys -= 1
if (this._programmaticKeys === 0) {
this._scheduleTextSnapshot()
}
return
}
return
}
}
// 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다.
@ -895,18 +907,42 @@ class InputTelemetryService extends EventEmitter {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
if ((!keyClass || TYPING_KEY_CLASSES.has(keyClass)) && configGet('suggestionEnabled') === true) {
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다").
const settleDelay = Math.max(
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60
)
this._settleTimer = setTimeout(() => {
this._settleTimer = null
void this._captureTextSnapshot()
}, settleDelay)
this._settleTimer.unref?.()
if (this._typoSettleTimer) {
clearTimeout(this._typoSettleTimer)
this._typoSettleTimer = null
}
if (!keyClass || TYPING_KEY_CLASSES.has(keyClass)) {
const suggestionEnabled = configGet('suggestionEnabled') === true
const typoEnabled = configGet('typoAutoCorrectEnabled') !== false
const suggestionSettleDelay = suggestionEnabled
? Math.max(
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
Math.ceil(
(configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) *
COMPOSING_IDLE_MULTIPLIER
) + 60
)
: 0
if (suggestionEnabled) {
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측: 2026-10-17: "빠릿하지 않다").
this._settleTimer = setTimeout(() => {
this._settleTimer = null
void this._captureTextSnapshot()
}, suggestionSettleDelay)
this._settleTimer.unref?.()
}
// 기본 제안 settle(750ms)이 오타 정지 임계(650~690ms)를 덮을 때는 중복 UIA 조회를 피한다.
if (
typoEnabled &&
(!suggestionEnabled || suggestionSettleDelay < TYPO_SETTLE_DELAY_MS || suggestionSettleDelay > 800)
) {
this._typoSettleTimer = setTimeout(() => {
this._typoSettleTimer = null
void this._captureTextSnapshot()
}, TYPO_SETTLE_DELAY_MS)
this._typoSettleTimer.unref?.()
}
}
}
@ -1108,6 +1144,9 @@ class InputTelemetryService extends EventEmitter {
// 문서 중간을 고쳤다면 접두(문서 끝)는 커서와 무관하다 — 제안·수락을 막는다.
// 단, 방금 프로그램(오타 교정·제안 수락)이 커서 앞 텍스트를 바꾼 경우에는 끝 편집으로 본다.
this._pruneExpectedInserts(now)
if (this._programmaticKeys > 0 && now > this._programmaticKeysUntil) {
this._programmaticKeys = 0
}
const programmaticEdit =
this._programmaticKeys > 0 ||
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
@ -1197,20 +1236,30 @@ class InputTelemetryService extends EventEmitter {
}
this._lastContext = context
if (this._settleTimer) {
const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars
const canTriggerSuggestion =
configGet('suggestionEnabled') === true &&
if (this._settleTimer || this._typoSettleTimer) {
const canTriggerContext =
context.available &&
context.isEditable &&
!context.isPassword &&
context.editedSinceFocus &&
context.typedRecently &&
context.typedRecently
const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars
const canTriggerSuggestion =
configGet('suggestionEnabled') === true &&
canTriggerContext &&
normalizeRequestPrefix(context.prefix).length + (context.isComposing ? 1 : 0) >= minPrefixChars
if (!canTriggerSuggestion) {
const canTriggerTypoSettle =
configGet('typoAutoCorrectEnabled') !== false &&
canTriggerContext &&
context.prefix.trim().length > 0
if (this._settleTimer && !canTriggerSuggestion && !canTriggerTypoSettle) {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
if (this._typoSettleTimer && !canTriggerTypoSettle) {
clearTimeout(this._typoSettleTimer)
this._typoSettleTimer = null
}
}
this.emit('typed-context', context)
// 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다).
@ -1281,8 +1330,14 @@ class InputTelemetryService extends EventEmitter {
bucket.sentences += delta.insertedSentences
}
if (!delta.insertedText) return
const typedText = this._withoutExpectedInsert(delta.insertedText)
const span =
keepText || this._expectedInserts.length > 0
? diffInsertionSpan(previous.text, snapshot.text)
: null
const rawInserted = delta.insertedText || span?.text || ''
if (!rawInserted) return
const typedText = this._withoutExpectedInsert(rawInserted, previous.text, snapshot.text, span)
if (!keepText) return
if (typedText !== delta.insertedText) {
// 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친
// 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다.
@ -1322,6 +1377,7 @@ class InputTelemetryService extends EventEmitter {
this._learnFlushTimer = null
this.flushPendingLearning()
}, LEARN_IDLE_FLUSH_MS)
this._learnFlushTimer.unref?.()
}
/** 모아 둔 타이핑 구간을 지금 학습한다 (멈춤·문장 끝·포커스 이동·종료 시). */
@ -1386,10 +1442,18 @@ class InputTelemetryService extends EventEmitter {
* - 삽입 구간이 예고 텍스트의 앞부분이면(키보드 방식으로 치는 도중 잡힌 스냅샷) 전부
* 프로그램 삽입이고, 남은 뒷부분을 계속 기다린다.
*/
private _withoutExpectedInsert(inserted: string): string {
private _withoutExpectedInsert(
inserted: string,
prevText?: string,
nextText?: string,
span?: { start: number; end: number; text: string } | null
): string {
this._pruneExpectedInserts(Date.now())
const trimmed = inserted.trim()
if (!trimmed) return inserted
const activeSpan =
span ??
(prevText !== undefined && nextText !== undefined ? diffInsertionSpan(prevText, nextText) : null)
for (let i = 0; i < this._expectedInserts.length; i += 1) {
const expected = this._expectedInserts[i]
const index = inserted.indexOf(expected.text)
@ -1397,6 +1461,34 @@ class InputTelemetryService extends EventEmitter {
this._expectedInserts.splice(i, 1)
return `${inserted.slice(0, index)} ${inserted.slice(index + expected.text.length)}`.trim()
}
if (
activeSpan &&
activeSpan.text.length > 0 &&
prevText !== undefined &&
nextText !== undefined
) {
// 치환 앞뒤(예: 문장부호 '?' 접미사)가 공통 접두/접미사로 잘려 diff 가 부분만 잡아냈더라도
// 새 스냅샷에 예고된 전체 문자열이 diff 구간을 덮어 들어왔으면 잔여물('?' 등) 없이 소비한다.
let searchPos = Math.max(0, activeSpan.start - expected.text.length)
while (searchPos < activeSpan.end) {
const matchStart = nextText.indexOf(expected.text, searchPos)
if (matchStart < 0 || matchStart >= activeSpan.end) break
const matchEnd = matchStart + expected.text.length
if (
matchEnd > activeSpan.start &&
(matchStart >= activeSpan.start ||
prevText.slice(matchStart, matchEnd) !== expected.text)
) {
this._expectedInserts.splice(i, 1)
const beforeDiff =
matchStart > activeSpan.start ? nextText.slice(activeSpan.start, matchStart) : ''
const afterDiff =
matchEnd < activeSpan.end ? nextText.slice(matchEnd, activeSpan.end) : ''
return `${beforeDiff} ${afterDiff}`.trim()
}
searchPos = matchStart + 1
}
}
if (trimmed.length === expected.text.length && `${trimmed}${trimmed}`.includes(expected.text)) {
this._expectedInserts.splice(i, 1)
return ''
@ -2219,6 +2311,28 @@ function sanitizeSample(raw: string): string {
return cleaned.slice(0, MAX_SAMPLE_CHARS)
}
/** 두 스냅샷 사이 공통 접두/접미를 제외한 실제 변경 구간과 추가 문자열을 구한다. */
function diffInsertionSpan(
prevText: string,
nextText: string
): { start: number; end: number; text: string } {
let prefix = 0
const maxPrefix = Math.min(prevText.length, nextText.length)
while (prefix < maxPrefix && prevText[prefix] === nextText[prefix]) prefix += 1
let suffix = 0
const maxSuffix = Math.min(prevText.length - prefix, nextText.length - prefix)
while (
suffix < maxSuffix &&
prevText[prevText.length - 1 - suffix] === nextText[nextText.length - 1 - suffix]
) {
suffix += 1
}
const end = nextText.length - suffix
return { start: prefix, end, text: nextText.slice(prefix, end) }
}
function getDisplayScaleFactor(): number {
try {
return screen.getPrimaryDisplay().scaleFactor || 1

View file

@ -75,6 +75,11 @@ const MAX_MODEL_DELETE_CHARS = 18
/** 멈춘 뒤에도 인플레이스 교정이 한 번에 지울 수 있는 최대 글자 수 */
const MAX_INPLACE_DELETE_CHARS = 32
const TRAILING_BOUNDARY_RE = /[ \t.,!?;:~…?!。]$/u
const BOUNDARY_ONLY_RUN_RE = /^[ \t.,!?;:~…?!。]*$/u
const BOUNDARY_DELTA_RE = /^[ \t.,!?;:~…?!。]{1,4}$/u
const BOUNDARY_PUNCT_GLOBAL_RE = /[ \t.,!?;:~…?!。]/gu
/** 'typed-context' 에 대한 판단 — 제안 서비스로 그대로 넘길지(pass), 미룰지. */
export type TypoVerdict = 'pass' | 'correcting' | 'checking'
@ -190,10 +195,10 @@ export class TypoCorrectionService extends EventEmitter {
const canRebaseDelta =
delta.length > 0 &&
delta.length <= 6 &&
(/^[ \t.,!?;:]{1,4}$/u.test(delta) ||
(BOUNDARY_DELTA_RE.test(delta) ||
(!context.isComposing &&
context.idleMs >= LAYOUT_BOUNDARY_MIN_IDLE_MS &&
/[ \t.,!?;:]$/u.test(delta)))
TRAILING_BOUNDARY_RE.test(delta)))
if (canRebaseDelta) {
this._check.context = context
this._check.latestKeyAt = this._deps.lastKeyAt()
@ -211,7 +216,7 @@ export class TypoCorrectionService extends EventEmitter {
this._lastCheckedRegion = ''
this._lastPostRegion = ''
}
const hasTrailingBoundary = /[ \t.,!?;:]$/u.test(prefix)
const hasTrailingBoundary = TRAILING_BOUNDARY_RE.test(prefix)
const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':')
const minLayoutIdle = hasTrailingBoundary
? LAYOUT_BOUNDARY_MIN_IDLE_MS
@ -263,6 +268,7 @@ export class TypoCorrectionService extends EventEmitter {
})
const baseCorrections: TypoCorrection[] = []
let deferredTrailingCorrections = false
let appliedSpanLimit = maxDeterministicSpan
if (options.trailingWordOnly !== true) {
for (const c of allCorrections) {
if (prefix.length - c.start <= maxDeterministicSpan) {
@ -272,23 +278,30 @@ export class TypoCorrectionService extends EventEmitter {
} else {
// 빠른 연속 입력 뒤 일부만 고치면 다음 스냅샷에서 앞쪽 교정이 누락된다.
// 짧은 유휴에는 꼬리 사슬 전체가 들어올 때까지 기다리고, 충분히 멈추면 현재 검사 영역을 한 번에 교정한다.
// 단, 문장부호로 막 닫힌 단일 꼬리 오타(23~32자 긴 한국어 구문)는 경계에서 즉시 복원한다.
for (let i = allCorrections.length - 1; i >= 0; i -= 1) {
const c = allCorrections[i]
if (prefix.length - c.start > maxDeterministicSpan) {
const tailAfter = prefix.slice(c.end)
const isSingleBoundaryCompleted =
baseCorrections.length === 0 && hasTrailingBoundary && BOUNDARY_ONLY_RUN_RE.test(tailAfter)
const allowedSpan = isSingleBoundaryCompleted
? Math.max(maxDeterministicSpan, MAX_INPLACE_DELETE_CHARS)
: maxDeterministicSpan
if (prefix.length - c.start > allowedSpan) {
const nextCorr = baseCorrections[0]
const between = nextCorr ? prefix.slice(c.end, nextCorr.start) : ''
deferredTrailingCorrections = /^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2
deferredTrailingCorrections = BOUNDARY_ONLY_RUN_RE.test(between) || between.trim().length <= 2
break
}
if (baseCorrections.length === 0) {
const tailAfter = prefix.slice(c.end)
const nonSpaceTailLen = tailAfter.replace(/[ \t.,!?;:]/gu, '').length
const nonSpaceTailLen = tailAfter.replace(BOUNDARY_PUNCT_GLOBAL_RE, '').length
if (nonSpaceTailLen > 2) break
baseCorrections.unshift(c)
appliedSpanLimit = allowedSpan
} else {
const nextCorr = baseCorrections[0]
const between = prefix.slice(c.end, nextCorr.start)
if (/^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2) {
if (BOUNDARY_ONLY_RUN_RE.test(between) || between.trim().length <= 2) {
baseCorrections.unshift(c)
} else {
break
@ -306,7 +319,7 @@ export class TypoCorrectionService extends EventEmitter {
const corrections =
loneJamoRemovals.length > 0 ? mergeTypoCorrections(baseCorrections, loneJamoRemovals) : baseCorrections
const plan = planTypoReplacement(prefix, corrections)
if (plan && plan.deleteCount <= maxDeterministicSpan) {
if (plan && plan.deleteCount <= appliedSpanLimit) {
this._markRegionChecked(region)
void this._apply(plan, context, keyAtDecision)
return 'correcting'
@ -331,7 +344,10 @@ export class TypoCorrectionService extends EventEmitter {
void this._apply(jamoPlan, context, keyAtDecision)
return 'correcting'
}
if (!worthModel || configGet('typoAutoCorrectUseModel') === false) {
if (
options.trailingWordOnly !== true &&
(!worthModel || configGet('typoAutoCorrectUseModel') === false)
) {
this._markRegionChecked(region)
}
return 'pass'
@ -444,7 +460,7 @@ export class TypoCorrectionService extends EventEmitter {
if (words.length >= 2) return compact.length >= 4
if (words.length === 1) {
if (hasSuspiciousTypo(region)) return true
return compact.length >= 4 && /[ \t.,!?;:]$/u.test(region)
return compact.length >= 4 && TRAILING_BOUNDARY_RE.test(region)
}
return false
}