fix(input,core): fix live punctuation typo triggers, expected insert cleanup, and ngram scan
This commit is contained in:
parent
a37dd63909
commit
2a009e421a
8 changed files with 640 additions and 53 deletions
|
|
@ -163,6 +163,8 @@ const PROGRAMMATIC_INSERT_TTL_MS = 10_000
|
||||||
const LEARN_IDLE_FLUSH_MS = 2000
|
const LEARN_IDLE_FLUSH_MS = 2000
|
||||||
/** diff 붙여넣기 판정(200자)에 걸리기 전에 끊어 저장한다. */
|
/** diff 붙여넣기 판정(200자)에 걸리기 전에 끊어 저장한다. */
|
||||||
const LEARN_MAX_PENDING_CHARS = 150
|
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 RETENTION_PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000
|
||||||
const MAX_READABILITY_APPS = 64
|
const MAX_READABILITY_APPS = 64
|
||||||
|
|
||||||
|
|
@ -196,6 +198,8 @@ class InputTelemetryService extends EventEmitter {
|
||||||
private _textTimer: NodeJS.Timeout | null = null
|
private _textTimer: NodeJS.Timeout | null = null
|
||||||
/** 디바운스 이후의 settle 스냅샷 — 제안 게이트는 더 늦게 열린다 */
|
/** 디바운스 이후의 settle 스냅샷 — 제안 게이트는 더 늦게 열린다 */
|
||||||
private _settleTimer: NodeJS.Timeout | null = null
|
private _settleTimer: NodeJS.Timeout | null = null
|
||||||
|
/** 제안 비활성·짧은 접두에서도 오타 장문 정지 교정을 놓치지 않도록 700ms 에 스냅샷을 보장한다. */
|
||||||
|
private _typoSettleTimer: NodeJS.Timeout | null = null
|
||||||
/** 백그라운드 주기 샘플러 — 타이핑이 이어져도 계속 관측한다 */
|
/** 백그라운드 주기 샘플러 — 타이핑이 이어져도 계속 관측한다 */
|
||||||
private _sampleTimer: NodeJS.Timeout | null = null
|
private _sampleTimer: NodeJS.Timeout | null = null
|
||||||
/** 주기 샘플 스냅샷 진행 중 (중복 방지) */
|
/** 주기 샘플 스냅샷 진행 중 (중복 방지) */
|
||||||
|
|
@ -450,6 +454,10 @@ class InputTelemetryService extends EventEmitter {
|
||||||
clearTimeout(this._settleTimer)
|
clearTimeout(this._settleTimer)
|
||||||
this._settleTimer = null
|
this._settleTimer = null
|
||||||
}
|
}
|
||||||
|
if (this._typoSettleTimer) {
|
||||||
|
clearTimeout(this._typoSettleTimer)
|
||||||
|
this._typoSettleTimer = null
|
||||||
|
}
|
||||||
this.setSuggestionPresentationActive(false)
|
this.setSuggestionPresentationActive(false)
|
||||||
this._terminalTracker.reset()
|
this._terminalTracker.reset()
|
||||||
this.flushPendingLearning()
|
this.flushPendingLearning()
|
||||||
|
|
@ -575,7 +583,10 @@ class InputTelemetryService extends EventEmitter {
|
||||||
const vk = uiohookCodeToVk(event.keycode)
|
const vk = uiohookCodeToVk(event.keycode)
|
||||||
// 프로그램이 보낸 키(오타 교정의 백스페이스·확정용 공백·Ctrl+V 붙여넣기)만 통계와 버퍼에서 제외한다.
|
// 프로그램이 보낸 키(오타 교정의 백스페이스·확정용 공백·Ctrl+V 붙여넣기)만 통계와 버퍼에서 제외한다.
|
||||||
// 치환 도중 사용자가 실제로 누른 일반 글자·한글 키까지 삼키면 글자가 빠지거나 밀리는 버그가 생긴다.
|
// 치환 도중 사용자가 실제로 누른 일반 글자·한글 키까지 삼키면 글자가 빠지거나 밀리는 버그가 생긴다.
|
||||||
if (this._programmaticKeys > 0 && Date.now() <= this._programmaticKeysUntil) {
|
if (this._programmaticKeys > 0) {
|
||||||
|
if (Date.now() > this._programmaticKeysUntil) {
|
||||||
|
this._programmaticKeys = 0
|
||||||
|
} else {
|
||||||
const isExpectedProgrammaticKey =
|
const isExpectedProgrammaticKey =
|
||||||
vk === 0x08 ||
|
vk === 0x08 ||
|
||||||
vk === 0x20 ||
|
vk === 0x20 ||
|
||||||
|
|
@ -592,6 +603,7 @@ class InputTelemetryService extends EventEmitter {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다.
|
// 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다.
|
||||||
// 여기서 _inputRevision·_lastKeyAt·스냅샷 타이머를 건드리면 수정자 키를 쥐고 있는 동안
|
// 여기서 _inputRevision·_lastKeyAt·스냅샷 타이머를 건드리면 수정자 키를 쥐고 있는 동안
|
||||||
// 진행 중 UIA 스냅샷이 버려지고 유휴 시간(idleMs)과 터미널 버퍼가 리셋된다.
|
// 진행 중 UIA 스냅샷이 버려지고 유휴 시간(idleMs)과 터미널 버퍼가 리셋된다.
|
||||||
|
|
@ -895,19 +907,43 @@ class InputTelemetryService extends EventEmitter {
|
||||||
clearTimeout(this._settleTimer)
|
clearTimeout(this._settleTimer)
|
||||||
this._settleTimer = null
|
this._settleTimer = null
|
||||||
}
|
}
|
||||||
if ((!keyClass || TYPING_KEY_CLASSES.has(keyClass)) && configGet('suggestionEnabled') === true) {
|
if (this._typoSettleTimer) {
|
||||||
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
|
clearTimeout(this._typoSettleTimer)
|
||||||
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다").
|
this._typoSettleTimer = null
|
||||||
const settleDelay = Math.max(
|
}
|
||||||
|
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,
|
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
|
||||||
Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60
|
Math.ceil(
|
||||||
|
(configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) *
|
||||||
|
COMPOSING_IDLE_MULTIPLIER
|
||||||
|
) + 60
|
||||||
)
|
)
|
||||||
|
: 0
|
||||||
|
if (suggestionEnabled) {
|
||||||
|
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
|
||||||
|
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측: 2026-10-17: "빠릿하지 않다").
|
||||||
this._settleTimer = setTimeout(() => {
|
this._settleTimer = setTimeout(() => {
|
||||||
this._settleTimer = null
|
this._settleTimer = null
|
||||||
void this._captureTextSnapshot()
|
void this._captureTextSnapshot()
|
||||||
}, settleDelay)
|
}, suggestionSettleDelay)
|
||||||
this._settleTimer.unref?.()
|
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)
|
this._pruneExpectedInserts(now)
|
||||||
|
if (this._programmaticKeys > 0 && now > this._programmaticKeysUntil) {
|
||||||
|
this._programmaticKeys = 0
|
||||||
|
}
|
||||||
const programmaticEdit =
|
const programmaticEdit =
|
||||||
this._programmaticKeys > 0 ||
|
this._programmaticKeys > 0 ||
|
||||||
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
|
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
|
||||||
|
|
@ -1197,20 +1236,30 @@ class InputTelemetryService extends EventEmitter {
|
||||||
}
|
}
|
||||||
|
|
||||||
this._lastContext = context
|
this._lastContext = context
|
||||||
if (this._settleTimer) {
|
if (this._settleTimer || this._typoSettleTimer) {
|
||||||
const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars
|
const canTriggerContext =
|
||||||
const canTriggerSuggestion =
|
|
||||||
configGet('suggestionEnabled') === true &&
|
|
||||||
context.available &&
|
context.available &&
|
||||||
context.isEditable &&
|
context.isEditable &&
|
||||||
!context.isPassword &&
|
!context.isPassword &&
|
||||||
context.editedSinceFocus &&
|
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
|
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)
|
clearTimeout(this._settleTimer)
|
||||||
this._settleTimer = null
|
this._settleTimer = null
|
||||||
}
|
}
|
||||||
|
if (this._typoSettleTimer && !canTriggerTypoSettle) {
|
||||||
|
clearTimeout(this._typoSettleTimer)
|
||||||
|
this._typoSettleTimer = null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this.emit('typed-context', context)
|
this.emit('typed-context', context)
|
||||||
// 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다).
|
// 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다).
|
||||||
|
|
@ -1281,8 +1330,14 @@ class InputTelemetryService extends EventEmitter {
|
||||||
bucket.sentences += delta.insertedSentences
|
bucket.sentences += delta.insertedSentences
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!delta.insertedText) return
|
const span =
|
||||||
const typedText = this._withoutExpectedInsert(delta.insertedText)
|
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) {
|
if (typedText !== delta.insertedText) {
|
||||||
// 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친
|
// 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친
|
||||||
// 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다.
|
// 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다.
|
||||||
|
|
@ -1322,6 +1377,7 @@ class InputTelemetryService extends EventEmitter {
|
||||||
this._learnFlushTimer = null
|
this._learnFlushTimer = null
|
||||||
this.flushPendingLearning()
|
this.flushPendingLearning()
|
||||||
}, LEARN_IDLE_FLUSH_MS)
|
}, 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())
|
this._pruneExpectedInserts(Date.now())
|
||||||
const trimmed = inserted.trim()
|
const trimmed = inserted.trim()
|
||||||
if (!trimmed) return inserted
|
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) {
|
for (let i = 0; i < this._expectedInserts.length; i += 1) {
|
||||||
const expected = this._expectedInserts[i]
|
const expected = this._expectedInserts[i]
|
||||||
const index = inserted.indexOf(expected.text)
|
const index = inserted.indexOf(expected.text)
|
||||||
|
|
@ -1397,6 +1461,34 @@ class InputTelemetryService extends EventEmitter {
|
||||||
this._expectedInserts.splice(i, 1)
|
this._expectedInserts.splice(i, 1)
|
||||||
return `${inserted.slice(0, index)} ${inserted.slice(index + expected.text.length)}`.trim()
|
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)) {
|
if (trimmed.length === expected.text.length && `${trimmed}${trimmed}`.includes(expected.text)) {
|
||||||
this._expectedInserts.splice(i, 1)
|
this._expectedInserts.splice(i, 1)
|
||||||
return ''
|
return ''
|
||||||
|
|
@ -2219,6 +2311,28 @@ function sanitizeSample(raw: string): string {
|
||||||
return cleaned.slice(0, MAX_SAMPLE_CHARS)
|
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 {
|
function getDisplayScaleFactor(): number {
|
||||||
try {
|
try {
|
||||||
return screen.getPrimaryDisplay().scaleFactor || 1
|
return screen.getPrimaryDisplay().scaleFactor || 1
|
||||||
|
|
|
||||||
|
|
@ -75,6 +75,11 @@ const MAX_MODEL_DELETE_CHARS = 18
|
||||||
/** 멈춘 뒤에도 인플레이스 교정이 한 번에 지울 수 있는 최대 글자 수 */
|
/** 멈춘 뒤에도 인플레이스 교정이 한 번에 지울 수 있는 최대 글자 수 */
|
||||||
const MAX_INPLACE_DELETE_CHARS = 32
|
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), 미룰지. */
|
/** 'typed-context' 에 대한 판단 — 제안 서비스로 그대로 넘길지(pass), 미룰지. */
|
||||||
export type TypoVerdict = 'pass' | 'correcting' | 'checking'
|
export type TypoVerdict = 'pass' | 'correcting' | 'checking'
|
||||||
|
|
||||||
|
|
@ -190,10 +195,10 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
const canRebaseDelta =
|
const canRebaseDelta =
|
||||||
delta.length > 0 &&
|
delta.length > 0 &&
|
||||||
delta.length <= 6 &&
|
delta.length <= 6 &&
|
||||||
(/^[ \t.,!?;:]{1,4}$/u.test(delta) ||
|
(BOUNDARY_DELTA_RE.test(delta) ||
|
||||||
(!context.isComposing &&
|
(!context.isComposing &&
|
||||||
context.idleMs >= LAYOUT_BOUNDARY_MIN_IDLE_MS &&
|
context.idleMs >= LAYOUT_BOUNDARY_MIN_IDLE_MS &&
|
||||||
/[ \t.,!?;:]$/u.test(delta)))
|
TRAILING_BOUNDARY_RE.test(delta)))
|
||||||
if (canRebaseDelta) {
|
if (canRebaseDelta) {
|
||||||
this._check.context = context
|
this._check.context = context
|
||||||
this._check.latestKeyAt = this._deps.lastKeyAt()
|
this._check.latestKeyAt = this._deps.lastKeyAt()
|
||||||
|
|
@ -211,7 +216,7 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
this._lastCheckedRegion = ''
|
this._lastCheckedRegion = ''
|
||||||
this._lastPostRegion = ''
|
this._lastPostRegion = ''
|
||||||
}
|
}
|
||||||
const hasTrailingBoundary = /[ \t.,!?;:]$/u.test(prefix)
|
const hasTrailingBoundary = TRAILING_BOUNDARY_RE.test(prefix)
|
||||||
const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':')
|
const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':')
|
||||||
const minLayoutIdle = hasTrailingBoundary
|
const minLayoutIdle = hasTrailingBoundary
|
||||||
? LAYOUT_BOUNDARY_MIN_IDLE_MS
|
? LAYOUT_BOUNDARY_MIN_IDLE_MS
|
||||||
|
|
@ -263,6 +268,7 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
})
|
})
|
||||||
const baseCorrections: TypoCorrection[] = []
|
const baseCorrections: TypoCorrection[] = []
|
||||||
let deferredTrailingCorrections = false
|
let deferredTrailingCorrections = false
|
||||||
|
let appliedSpanLimit = maxDeterministicSpan
|
||||||
if (options.trailingWordOnly !== true) {
|
if (options.trailingWordOnly !== true) {
|
||||||
for (const c of allCorrections) {
|
for (const c of allCorrections) {
|
||||||
if (prefix.length - c.start <= maxDeterministicSpan) {
|
if (prefix.length - c.start <= maxDeterministicSpan) {
|
||||||
|
|
@ -272,23 +278,30 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
} else {
|
} else {
|
||||||
// 빠른 연속 입력 뒤 일부만 고치면 다음 스냅샷에서 앞쪽 교정이 누락된다.
|
// 빠른 연속 입력 뒤 일부만 고치면 다음 스냅샷에서 앞쪽 교정이 누락된다.
|
||||||
// 짧은 유휴에는 꼬리 사슬 전체가 들어올 때까지 기다리고, 충분히 멈추면 현재 검사 영역을 한 번에 교정한다.
|
// 짧은 유휴에는 꼬리 사슬 전체가 들어올 때까지 기다리고, 충분히 멈추면 현재 검사 영역을 한 번에 교정한다.
|
||||||
|
// 단, 문장부호로 막 닫힌 단일 꼬리 오타(23~32자 긴 한국어 구문)는 경계에서 즉시 복원한다.
|
||||||
for (let i = allCorrections.length - 1; i >= 0; i -= 1) {
|
for (let i = allCorrections.length - 1; i >= 0; i -= 1) {
|
||||||
const c = allCorrections[i]
|
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 nextCorr = baseCorrections[0]
|
||||||
const between = nextCorr ? prefix.slice(c.end, nextCorr.start) : ''
|
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
|
break
|
||||||
}
|
}
|
||||||
if (baseCorrections.length === 0) {
|
if (baseCorrections.length === 0) {
|
||||||
const tailAfter = prefix.slice(c.end)
|
const nonSpaceTailLen = tailAfter.replace(BOUNDARY_PUNCT_GLOBAL_RE, '').length
|
||||||
const nonSpaceTailLen = tailAfter.replace(/[ \t.,!?;:]/gu, '').length
|
|
||||||
if (nonSpaceTailLen > 2) break
|
if (nonSpaceTailLen > 2) break
|
||||||
baseCorrections.unshift(c)
|
baseCorrections.unshift(c)
|
||||||
|
appliedSpanLimit = allowedSpan
|
||||||
} else {
|
} else {
|
||||||
const nextCorr = baseCorrections[0]
|
const nextCorr = baseCorrections[0]
|
||||||
const between = prefix.slice(c.end, nextCorr.start)
|
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)
|
baseCorrections.unshift(c)
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
|
|
@ -306,7 +319,7 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
const corrections =
|
const corrections =
|
||||||
loneJamoRemovals.length > 0 ? mergeTypoCorrections(baseCorrections, loneJamoRemovals) : baseCorrections
|
loneJamoRemovals.length > 0 ? mergeTypoCorrections(baseCorrections, loneJamoRemovals) : baseCorrections
|
||||||
const plan = planTypoReplacement(prefix, corrections)
|
const plan = planTypoReplacement(prefix, corrections)
|
||||||
if (plan && plan.deleteCount <= maxDeterministicSpan) {
|
if (plan && plan.deleteCount <= appliedSpanLimit) {
|
||||||
this._markRegionChecked(region)
|
this._markRegionChecked(region)
|
||||||
void this._apply(plan, context, keyAtDecision)
|
void this._apply(plan, context, keyAtDecision)
|
||||||
return 'correcting'
|
return 'correcting'
|
||||||
|
|
@ -331,7 +344,10 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
void this._apply(jamoPlan, context, keyAtDecision)
|
void this._apply(jamoPlan, context, keyAtDecision)
|
||||||
return 'correcting'
|
return 'correcting'
|
||||||
}
|
}
|
||||||
if (!worthModel || configGet('typoAutoCorrectUseModel') === false) {
|
if (
|
||||||
|
options.trailingWordOnly !== true &&
|
||||||
|
(!worthModel || configGet('typoAutoCorrectUseModel') === false)
|
||||||
|
) {
|
||||||
this._markRegionChecked(region)
|
this._markRegionChecked(region)
|
||||||
}
|
}
|
||||||
return 'pass'
|
return 'pass'
|
||||||
|
|
@ -444,7 +460,7 @@ export class TypoCorrectionService extends EventEmitter {
|
||||||
if (words.length >= 2) return compact.length >= 4
|
if (words.length >= 2) return compact.length >= 4
|
||||||
if (words.length === 1) {
|
if (words.length === 1) {
|
||||||
if (hasSuspiciousTypo(region)) return true
|
if (hasSuspiciousTypo(region)) return true
|
||||||
return compact.length >= 4 && /[ \t.,!?;:]$/u.test(region)
|
return compact.length >= 4 && TRAILING_BOUNDARY_RE.test(region)
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -642,6 +642,90 @@ describe('TypoCorrectionService', () => {
|
||||||
await flush()
|
await flush()
|
||||||
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅎ샤ㅗㅕㅠ에 '.length, 'github에 ')
|
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅎ샤ㅗㅕㅠ에 '.length, 'github에 ')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('handleTypingContext_문장부호뒤23자단일오타_짧은경계유휴에서즉시교정한다', async () => {
|
||||||
|
const fake = deps()
|
||||||
|
const service = new TypoCorrectionService(fake.deps)
|
||||||
|
const prefix = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwldy?'
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.handleTypingContext(typingContext({ prefix, idleMs: 140 }), { trailingWordOnly: true })
|
||||||
|
).toBe('correcting')
|
||||||
|
await flush()
|
||||||
|
|
||||||
|
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
|
||||||
|
'dbrlgkrhdlTwlsdksgwldy?'.length,
|
||||||
|
'유기하고있진않지요?'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handleTypingContext_물결표및전각부호뒤오타_짧은경계유휴에서즉시교정하고경로는보존한다', async () => {
|
||||||
|
const fake = deps()
|
||||||
|
const service = new TypoCorrectionService(fake.deps)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.handleTypingContext(
|
||||||
|
typingContext({ prefix: '상황 잘 지켜보는중~dbrlgkrhdlTwlsdksgwl~', idleMs: 60 }),
|
||||||
|
{ trailingWordOnly: true }
|
||||||
|
)
|
||||||
|
).toBe('correcting')
|
||||||
|
await flush()
|
||||||
|
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
|
||||||
|
'dbrlgkrhdlTwlsdksgwl~'.length,
|
||||||
|
'유기하고있진않지~'
|
||||||
|
)
|
||||||
|
|
||||||
|
fake.replaceBeforeCaret.mockClear()
|
||||||
|
expect(
|
||||||
|
service.handleTypingContext(
|
||||||
|
typingContext({ prefix: '~/dbrlgkrhdlTwlsdksgwl~', idleMs: 60 }),
|
||||||
|
{ trailingWordOnly: true }
|
||||||
|
)
|
||||||
|
).toBe('pass')
|
||||||
|
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handleTypingContext_620ms경과뒤650ms정지시_장문후행오타가영역선점으로누락되지않는다', async () => {
|
||||||
|
const fake = deps()
|
||||||
|
const service = new TypoCorrectionService(fake.deps)
|
||||||
|
const prefix = '상황 잘 지켜보는중?dkssudgktpdy rkatkgkqslek qksrkqtmqslek?'
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.handleTypingContext(typingContext({ prefix, idleMs: 620 }), { trailingWordOnly: true })
|
||||||
|
).toBe('pass')
|
||||||
|
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.handleTypingContext(typingContext({ prefix, idleMs: 650 }), { trailingWordOnly: true })
|
||||||
|
).toBe('correcting')
|
||||||
|
await flush()
|
||||||
|
|
||||||
|
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
|
||||||
|
'dkssudgktpdy rkatkgkqslek qksrkqtmqslek?'.length,
|
||||||
|
'안녕하세요 감사합니다 반갑습니다?'
|
||||||
|
)
|
||||||
|
|
||||||
|
// trailingWordOnly 620ms 에서 앞쪽 오타('dkssudgktpdy')가 후행 제한으로 통과되더라도
|
||||||
|
// 같은 영역을 checked 로 선점해 후속 전체 검사(trailingWordOnly 없음)를 막아선 안 된다
|
||||||
|
const staleRegionService = new TypoCorrectionService(fake.deps)
|
||||||
|
fake.replaceBeforeCaret.mockClear()
|
||||||
|
const earlierPrefix = 'dkssudgktpdy hello?'
|
||||||
|
expect(
|
||||||
|
staleRegionService.handleTypingContext(typingContext({ prefix: earlierPrefix, idleMs: 620 }), {
|
||||||
|
trailingWordOnly: true
|
||||||
|
})
|
||||||
|
).toBe('pass')
|
||||||
|
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
expect(
|
||||||
|
staleRegionService.handleTypingContext(typingContext({ prefix: earlierPrefix, idleMs: 650 }))
|
||||||
|
).toBe('correcting')
|
||||||
|
await flush()
|
||||||
|
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
|
||||||
|
'dkssudgktpdy hello?'.length,
|
||||||
|
'안녕하세요 hello?'
|
||||||
|
)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => {
|
describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => {
|
||||||
|
|
|
||||||
348
apps/desktop/tests/main/services/typo-live-punctuation.test.ts
Normal file
348
apps/desktop/tests/main/services/typo-live-punctuation.test.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
||||||
|
// apps/desktop/tests/main/services/typo-live-punctuation.test.ts
|
||||||
|
// 실시간 타이핑(InputTelemetryService → TypoCorrectionService → TextInsertService)에서
|
||||||
|
// 문장부호 뒤 띄어쓰기 없는 한영 오타 감지와 후속 학습/커서 추적을 검증한다.
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
const BASE_NOW = Date.UTC(2026, 10, 14, 5, 0, 0)
|
||||||
|
|
||||||
|
const state = vi.hoisted(() => ({
|
||||||
|
now: 0,
|
||||||
|
config: {
|
||||||
|
typoAutoCorrectEnabled: true as boolean,
|
||||||
|
typoAutoCorrectUseModel: false as boolean,
|
||||||
|
typoIgnoredWords: [] as string[],
|
||||||
|
inputExcludedApps: [] as string[],
|
||||||
|
inputTelemetryEnabled: false as boolean,
|
||||||
|
inputTelemetryPaused: false as boolean,
|
||||||
|
inputLearnTypedText: false as boolean,
|
||||||
|
suggestionEnabled: false as boolean,
|
||||||
|
suggestionTriggerDelayMs: 600 as number,
|
||||||
|
suggestionMinPrefixChars: 8 as number
|
||||||
|
},
|
||||||
|
text: '',
|
||||||
|
caretOffset: 0 as number | null,
|
||||||
|
nativeTick: 100,
|
||||||
|
hwnd: 77,
|
||||||
|
appName: 'KakaoTalk.exe',
|
||||||
|
windowTitle: '채팅',
|
||||||
|
listeners: new Map<string, Array<(event: unknown) => void>>(),
|
||||||
|
learnedTexts: [] as string[]
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('electron', () => ({ screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) } }))
|
||||||
|
vi.mock('uiohook-napi', () => ({
|
||||||
|
uIOhook: {
|
||||||
|
on: vi.fn((event: string, listener: (payload: unknown) => void) => {
|
||||||
|
const list = state.listeners.get(event) ?? []
|
||||||
|
list.push(listener)
|
||||||
|
state.listeners.set(event, list)
|
||||||
|
}),
|
||||||
|
removeListener: vi.fn((event: string, listener: (payload: unknown) => void) => {
|
||||||
|
const list = state.listeners.get(event) ?? []
|
||||||
|
state.listeners.set(
|
||||||
|
event,
|
||||||
|
list.filter((entry) => entry !== listener)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/db', () => ({
|
||||||
|
getDatabase: () => ({
|
||||||
|
insert: () => ({
|
||||||
|
values: () => ({
|
||||||
|
run: () => undefined,
|
||||||
|
onConflictDoUpdate: () => ({ run: () => undefined })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||||
|
configGet: vi.fn((key: keyof typeof state.config) => state.config[key]),
|
||||||
|
configSet: vi.fn((key: keyof typeof state.config, value: never) => {
|
||||||
|
state.config[key] = value
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||||
|
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/global-input-hook', () => ({
|
||||||
|
acquireGlobalInputHook: () => () => undefined
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/KeyBindingService', () => ({
|
||||||
|
uiohookCodeToVk: (code: number) => code
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/UiaContextService', () => ({
|
||||||
|
getUiaContextService: () => ({
|
||||||
|
lastReason: null,
|
||||||
|
lastSuccessAt: 0,
|
||||||
|
isAvailable: () => true,
|
||||||
|
getSnapshot: vi.fn(async () => ({
|
||||||
|
available: true,
|
||||||
|
isPassword: false,
|
||||||
|
isEditable: true,
|
||||||
|
isComposing: false,
|
||||||
|
hasSelection: false,
|
||||||
|
controlType: 'Edit',
|
||||||
|
controlName: 'MessageInput',
|
||||||
|
textSource: 'value' as const,
|
||||||
|
text: state.text,
|
||||||
|
caretOffset: state.caretOffset,
|
||||||
|
caretRect: null,
|
||||||
|
elementRect: { x: 100, y: 100, width: 300, height: 40 },
|
||||||
|
windowTitle: state.windowTitle,
|
||||||
|
appName: state.appName,
|
||||||
|
processId: 1234,
|
||||||
|
capturedAt: state.now
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/utils/win32-foreground', () => ({
|
||||||
|
getForegroundWindowInfo: () => ({
|
||||||
|
appName: state.appName,
|
||||||
|
title: state.windowTitle,
|
||||||
|
hwnd: state.hwnd
|
||||||
|
}),
|
||||||
|
isForegroundKoreanIme: () => false
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/utils/win32-input-activity', () => ({
|
||||||
|
getLastNativeInputTick: () => state.nativeTick
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
|
||||||
|
getPersonalGraphService: () => ({
|
||||||
|
indexText: vi.fn((text: string) => {
|
||||||
|
state.learnedTexts.push(text)
|
||||||
|
}),
|
||||||
|
observeTypedText: vi.fn(),
|
||||||
|
learnPhrase: vi.fn()
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/suggestion/PersonalNgramIndex', () => ({
|
||||||
|
getPersonalNgramIndex: () => ({
|
||||||
|
add: vi.fn()
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
vi.mock('../../../src/main/services/text-insert/electron-clipboard-port', () => ({
|
||||||
|
electronClipboardPort: { readText: () => '', writeText: vi.fn() }
|
||||||
|
}))
|
||||||
|
|
||||||
|
import {
|
||||||
|
getInputTelemetryService,
|
||||||
|
resetInputTelemetryServiceForTests
|
||||||
|
} from '../../../src/main/services/InputTelemetryService'
|
||||||
|
import { TypoCorrectionService } from '../../../src/main/services/TypoCorrectionService'
|
||||||
|
import { TextInsertService } from '../../../src/main/services/TextInsertService'
|
||||||
|
|
||||||
|
function emitKeyDown(vk: number, shift = false): void {
|
||||||
|
const handlers = state.listeners.get('keydown') ?? []
|
||||||
|
for (const handler of handlers) {
|
||||||
|
handler({
|
||||||
|
keycode: vk,
|
||||||
|
ctrlKey: false,
|
||||||
|
altKey: false,
|
||||||
|
metaKey: false,
|
||||||
|
shiftKey: shift
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function advance(ms: number): Promise<void> {
|
||||||
|
let remaining = ms
|
||||||
|
while (remaining > 0) {
|
||||||
|
const step = Math.min(50, remaining)
|
||||||
|
state.now += step
|
||||||
|
remaining -= step
|
||||||
|
await vi.advanceTimersByTimeAsync(step)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function wireLivePipeline() {
|
||||||
|
const telemetry = getInputTelemetryService()
|
||||||
|
const keyboard = {
|
||||||
|
type: vi.fn(async () => undefined),
|
||||||
|
paste: vi.fn(async () => undefined),
|
||||||
|
backspace: vi.fn(async (count: number) => {
|
||||||
|
state.text = state.text.slice(0, -count)
|
||||||
|
}),
|
||||||
|
replaceBeforeCaret: vi.fn(async (count: number, insertText: string) => {
|
||||||
|
const idx = state.caretOffset ?? state.text.length
|
||||||
|
state.text = state.text.slice(0, idx - count) + insertText + state.text.slice(idx)
|
||||||
|
if (state.caretOffset !== null) {
|
||||||
|
state.caretOffset = idx - count + insertText.length
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const insert = new TextInsertService({ keyboard })
|
||||||
|
const typo = new TypoCorrectionService({
|
||||||
|
replaceBeforeCaret: async (deleteCount, insertText, options) => {
|
||||||
|
let baseLength = telemetry.currentTerminalPrefixLength()
|
||||||
|
const result = await insert.replaceBeforeCaret(deleteCount, insertText, 'keyboard', {
|
||||||
|
...options,
|
||||||
|
beforeApply: () => {
|
||||||
|
options?.beforeApply?.()
|
||||||
|
baseLength = telemetry.currentTerminalPrefixLength()
|
||||||
|
telemetry.expectProgrammaticKeys(deleteCount + (options?.commitComposition ? 2 : 0))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (result.success) {
|
||||||
|
telemetry.applyProgrammaticReplacement(deleteCount, insertText, baseLength)
|
||||||
|
}
|
||||||
|
return result.success
|
||||||
|
},
|
||||||
|
lastKeyAt: () => telemetry.lastKeyAt,
|
||||||
|
inputRevision: () => telemetry.inputRevision,
|
||||||
|
nativeInputTick: () => state.nativeTick,
|
||||||
|
foregroundHandle: () => state.hwnd,
|
||||||
|
expectProgrammaticKeys: (count) => telemetry.expectProgrammaticKeys(count),
|
||||||
|
expectProgrammaticInsert: (text) => telemetry.expectProgrammaticInsert(text),
|
||||||
|
recentTexts: () => [],
|
||||||
|
warmModel: () => null,
|
||||||
|
generate: async function* () {
|
||||||
|
yield '없음'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const contexts: Array<{ caretReliable?: boolean; prefix: string }> = []
|
||||||
|
telemetry.on('typed-context', (ctx) => {
|
||||||
|
contexts.push({ caretReliable: ctx.caretReliable, prefix: ctx.prefix })
|
||||||
|
typo.handleTypingContext(ctx, { trailingWordOnly: true })
|
||||||
|
})
|
||||||
|
telemetry.start()
|
||||||
|
return { telemetry, typo, insert, keyboard, contexts }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('실시간 타이핑 문장부호 경계 오타 교정 및 추적', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
state.now = BASE_NOW
|
||||||
|
vi.setSystemTime(BASE_NOW)
|
||||||
|
state.config = {
|
||||||
|
typoAutoCorrectEnabled: true,
|
||||||
|
typoAutoCorrectUseModel: false,
|
||||||
|
typoIgnoredWords: [],
|
||||||
|
inputExcludedApps: [],
|
||||||
|
inputTelemetryEnabled: false,
|
||||||
|
inputTelemetryPaused: false,
|
||||||
|
inputLearnTypedText: false,
|
||||||
|
suggestionEnabled: false,
|
||||||
|
suggestionTriggerDelayMs: 600,
|
||||||
|
suggestionMinPrefixChars: 8
|
||||||
|
}
|
||||||
|
state.text = '상황 잘 지켜보는중?'
|
||||||
|
state.caretOffset = state.text.length
|
||||||
|
state.nativeTick = 100
|
||||||
|
state.hwnd = 77
|
||||||
|
state.listeners.clear()
|
||||||
|
state.learnedTexts = []
|
||||||
|
resetInputTelemetryServiceForTests()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
resetInputTelemetryServiceForTests()
|
||||||
|
vi.useRealTimers()
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('liveTyping_제안비활성상태에서물음표뒤공백없는영타멈춤_정지스냅샷으로교정한다', async () => {
|
||||||
|
const { typo, keyboard } = wireLivePipeline()
|
||||||
|
try {
|
||||||
|
// 초기 포커스 기준선: '?' 까지 이미 입력됨 -> 이어서 영타 'dbrlgkrhdlTwlsdksgwl' 입력 후 멈춤
|
||||||
|
state.text = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl'
|
||||||
|
state.caretOffset = state.text.length
|
||||||
|
emitKeyDown(0x4c) // 'L' 키 입력 완료 시점
|
||||||
|
|
||||||
|
// 디바운스(380ms) → 정지 스냅샷(>=650ms)까지 진행
|
||||||
|
await advance(750)
|
||||||
|
|
||||||
|
expect(keyboard.replaceBeforeCaret).toHaveBeenCalledTimes(1)
|
||||||
|
expect(state.text).toBe('상황 잘 지켜보는중?유기하고있진않지')
|
||||||
|
} finally {
|
||||||
|
typo.dispose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('liveTyping_제안활성짧은접두나장문물음표뒤영타_경계와정지스냅샷에서놓치지않는다', async () => {
|
||||||
|
state.config.suggestionEnabled = true
|
||||||
|
state.config.suggestionTriggerDelayMs = 600
|
||||||
|
state.config.suggestionMinPrefixChars = 100
|
||||||
|
|
||||||
|
const { typo, keyboard } = wireLivePipeline()
|
||||||
|
try {
|
||||||
|
// 짧은 접두에서도 ? 뒤 23자 단일 오타는 경계 스냅샷(140ms)에서 즉시 교정된다
|
||||||
|
state.text = '왜?dbrlgkrhdlTwlsdksgwldy?'
|
||||||
|
state.caretOffset = state.text.length
|
||||||
|
emitKeyDown(0xbf, true) // '?'
|
||||||
|
await advance(150)
|
||||||
|
expect(state.text).toBe('왜?유기하고있진않지요?')
|
||||||
|
|
||||||
|
// 다중 단어 장문(>32자)도 minPrefixChars 미달과 무관하게 정지 스냅샷(<=800ms)에서 교정된다
|
||||||
|
keyboard.replaceBeforeCaret.mockClear()
|
||||||
|
state.text = '왜?dkssudgktpdy rkatkgkqslek rkatkgkqslek?'
|
||||||
|
state.caretOffset = state.text.length
|
||||||
|
emitKeyDown(0xbf, true)
|
||||||
|
await advance(850)
|
||||||
|
expect(state.text).toBe('왜?안녕하세요 감사합니다 감사합니다?')
|
||||||
|
expect(keyboard.replaceBeforeCaret).toHaveBeenCalledTimes(1)
|
||||||
|
} finally {
|
||||||
|
typo.dispose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('liveTyping_문장부호로끝나는치환후_잔여물음표로후속문장학습이나중간편집판정을망가뜨리지않는다', async () => {
|
||||||
|
state.config.inputLearnTypedText = true
|
||||||
|
state.caretOffset = null // caret-unknown 표면(RichEdit 등)
|
||||||
|
const { typo, contexts } = wireLivePipeline()
|
||||||
|
try {
|
||||||
|
// 기준선 형성
|
||||||
|
state.text = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?'
|
||||||
|
emitKeyDown(0xbf, true)
|
||||||
|
await advance(200)
|
||||||
|
expect(state.text).toBe('상황 잘 지켜보는중?유기하고있진않지?')
|
||||||
|
|
||||||
|
// 치환 반영 스냅샷 소비 (공통 접미사 '?' 가 남아 diff 는 '유기하고있진않지' 만 잡아냄)
|
||||||
|
await advance(450)
|
||||||
|
emitKeyDown(0x20)
|
||||||
|
state.text = '상황 잘 지켜보는중?유기하고있진않지? '
|
||||||
|
await advance(450)
|
||||||
|
// programmaticKeys TTL(3s) 경과 후 (expectedInserts TTL 10s 이내) 새 문장 입력
|
||||||
|
await advance(3100)
|
||||||
|
|
||||||
|
// 이후 사용자가 새로 '정말 이상한 상황인데?' 를 치면 '?' 가 예고 삽입 잔여물로 뜯겨 나가지 않고 온전히 학습된다
|
||||||
|
state.learnedTexts = []
|
||||||
|
state.text = '상황 잘 지켜보는중?유기하고있진않지? 정말 이상한 상황인데?'
|
||||||
|
emitKeyDown(0xbf, true)
|
||||||
|
await advance(450)
|
||||||
|
expect(state.learnedTexts.join(' ')).toContain('정말 이상한 상황인데?')
|
||||||
|
|
||||||
|
// 이후 문서 중간('상황' 앞)을 편집하면 caretReliable 이 false 여야 한다 ('?' 잔여물이 programmaticEdit 를 계속 true 로 만들지 않음)
|
||||||
|
state.text = '지금 상황 잘 지켜보는중?유기하고있진않지? 정말 이상한 상황인데?'
|
||||||
|
emitKeyDown(0x41)
|
||||||
|
await advance(450)
|
||||||
|
expect(contexts[contexts.length - 1]?.caretReliable).toBe(false)
|
||||||
|
} finally {
|
||||||
|
typo.dispose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('liveTyping_학습비활성상태에서도교정후3초경과시_예고삽입잔존이나만료된키카운트로중간편집판정이망가지지않는다', async () => {
|
||||||
|
state.config.inputLearnTypedText = false
|
||||||
|
state.caretOffset = null // caret-unknown 표면
|
||||||
|
const { typo, contexts } = wireLivePipeline()
|
||||||
|
try {
|
||||||
|
state.text = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?'
|
||||||
|
emitKeyDown(0xbf, true)
|
||||||
|
await advance(200)
|
||||||
|
expect(state.text).toBe('상황 잘 지켜보는중?유기하고있진않지?')
|
||||||
|
|
||||||
|
// 학습 비활성 경로에서도 치환 반영 스냅샷에서 expectedInserts 를 소진해야 한다
|
||||||
|
await advance(450)
|
||||||
|
// programmaticKeys TTL(3s) 경과 후 (expectedInserts TTL 10s 이내) 문서 중간 수정
|
||||||
|
await advance(3100)
|
||||||
|
state.text = '지금 상황 잘 지켜보는중?유기하고있진않지?'
|
||||||
|
emitKeyDown(0x41)
|
||||||
|
await advance(450)
|
||||||
|
expect(contexts[contexts.length - 1]?.caretReliable).toBe(false)
|
||||||
|
} finally {
|
||||||
|
typo.dispose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -734,4 +734,27 @@ describe('Araso 급 한/영 자동 전환 · 합성어 · 잔류 Shift · URL
|
||||||
expect(applyAll('윈도우ㅐㄴ ')).toBe('윈도우OS ')
|
expect(applyAll('윈도우ㅐㄴ ')).toBe('윈도우OS ')
|
||||||
expect(applyAll('새ㅁㅔㅑ를 ')).toBe('새API를 ')
|
expect(applyAll('새ㅁㅔㅑ를 ')).toBe('새API를 ')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('detectTypos_한글말줄임표뒤영타_한글로복원하고코드전개와파일확장자는보존한다', () => {
|
||||||
|
expect(applyAll('상황 잘 지켜보는중...dbrlgkrhdlTwlsdksgwl?')).toBe(
|
||||||
|
'상황 잘 지켜보는중...유기하고있진않지?'
|
||||||
|
)
|
||||||
|
expect(applyAll('어떻게해..dlrj?')).toBe('어떻게해..이거?')
|
||||||
|
expect(applyAll('파일.tsx?raw')).toBe('파일.tsx?raw')
|
||||||
|
expect(applyAll('...props')).toBe('...props')
|
||||||
|
expect(applyAll('return ...opts')).toBe('return ...opts')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('detectTypos_URL쿼리스트링뒤영타_변환하지않는다', () => {
|
||||||
|
expect(applyAll('상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?')).toBe(
|
||||||
|
'상황 잘 지켜보는중?유기하고있진않지?'
|
||||||
|
)
|
||||||
|
expect(applyAll('example.com?dbrlgkrhdlTwlsdksgwl')).toBe('example.com?dbrlgkrhdlTwlsdksgwl')
|
||||||
|
expect(applyAll('site.kr?dbrlgkrhdlTwlsdksgwl')).toBe('site.kr?dbrlgkrhdlTwlsdksgwl')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('detectTypos_물결표및전각부호경계오타_영문과한글모두복원한다', () => {
|
||||||
|
expect(applyAll('상황 잘 지켜보는중~ㅗ디ㅣㅐ~')).toBe('상황 잘 지켜보는중~hello~')
|
||||||
|
expect(applyAll('지금 어디야?dbrlgkrhdlTwlsdksgwl?')).toBe('지금 어디야?유기하고있진않지?')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -947,11 +947,11 @@ export function isUrlOrPathRun(prefix: string, tokenStart: number, tokenEnd: num
|
||||||
if (run.includes('://')) return true
|
if (run.includes('://')) return true
|
||||||
if (/^(?:www\.|~\/|\.\/|\.\.\/|localhost:)/iu.test(run)) return true
|
if (/^(?:www\.|~\/|\.\/|\.\.\/|localhost:)/iu.test(run)) return true
|
||||||
if ((run.match(/\//gu)?.length ?? 0) >= 2) return true
|
if ((run.match(/\//gu)?.length ?? 0) >= 2) return true
|
||||||
if (/[A-Za-z0-9]\.[A-Za-z]{2,}\//u.test(run)) return true
|
if (/[A-Za-z0-9]\.[A-Za-z]{2,}[/?]/u.test(run)) return true
|
||||||
if (/[A-Za-z0-9._+-]@[A-Za-z0-9]/u.test(run)) return true
|
if (/[A-Za-z0-9._+-]@[A-Za-z0-9]/u.test(run)) return true
|
||||||
if (/[\\_$#`<>{}=]/u.test(run)) return true
|
if (/[\\_$#`<>{}=]/u.test(run)) return true
|
||||||
|
|
||||||
// 토큰 바로 앞이나 뒤가 도메인 점(example.com)인 경우 (단, L.A.fh 처럼 대문자 약어 뒤 조사는 허용)
|
// 토큰 바로 앞이나 뒤가 도메인 점(example.com)인 경우 (단, L.A.fh 처럼 대문자 약어 뒤 조사와 한글 말줄임표(...) 뒤 한영 오타는 허용)
|
||||||
const before = prefix[tokenStart - 1] ?? ''
|
const before = prefix[tokenStart - 1] ?? ''
|
||||||
const after = prefix[tokenEnd] ?? ''
|
const after = prefix[tokenEnd] ?? ''
|
||||||
if (after === '.' && /[A-Za-z]/u.test(prefix[tokenEnd + 1] ?? '')) return true
|
if (after === '.' && /[A-Za-z]/u.test(prefix[tokenEnd + 1] ?? '')) return true
|
||||||
|
|
@ -959,7 +959,8 @@ export function isUrlOrPathRun(prefix: string, tokenStart: number, tokenEnd: num
|
||||||
const beforeDot = prefix.slice(runStart, tokenStart)
|
const beforeDot = prefix.slice(runStart, tokenStart)
|
||||||
const tokenText = prefix.slice(tokenStart, tokenEnd)
|
const tokenText = prefix.slice(tokenStart, tokenEnd)
|
||||||
const isAbbrevWithParticle = /^(?:[A-Z]\.){2,}$/u.test(beforeDot) && PARTICLE_KEYS.has(tokenText)
|
const isAbbrevWithParticle = /^(?:[A-Z]\.){2,}$/u.test(beforeDot) && PARTICLE_KEYS.has(tokenText)
|
||||||
if (!isAbbrevWithParticle) return true
|
const isHangulEllipsis = /[가-힣ㄱ-ㆎ][!?~]*\.{2,}$/u.test(beforeDot)
|
||||||
|
if (!isAbbrevWithParticle && !isHangulEllipsis) return true
|
||||||
}
|
}
|
||||||
if (before === ':' || after === ':') {
|
if (before === ':' || after === ':') {
|
||||||
const beforeColon = prefix.slice(runStart, tokenStart)
|
const beforeColon = prefix.slice(runStart, tokenStart)
|
||||||
|
|
|
||||||
|
|
@ -169,8 +169,7 @@ export class PersonalNgramModel {
|
||||||
const extends_ = (word: string) => word.length > partial.length && word.startsWith(partial)
|
const extends_ = (word: string) => word.length > partial.length && word.startsWith(partial)
|
||||||
first = context.length > 0 ? this._next(context, extends_, passes) : null
|
first = context.length > 0 ? this._next(context, extends_, passes) : null
|
||||||
if (!first) {
|
if (!first) {
|
||||||
const unigram = new Map([...this._unigram].filter(([word]) => extends_(word)))
|
const pick = best(this._unigram, extends_)
|
||||||
const pick = best(unigram, () => true)
|
|
||||||
first = passes(pick) ? pick : null
|
first = passes(pick) ? pick : null
|
||||||
}
|
}
|
||||||
joint = 'attach'
|
joint = 'attach'
|
||||||
|
|
|
||||||
|
|
@ -2024,6 +2024,8 @@ function resolveTokenAsEnglishPreview(tokenText: string): string | null {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const WORD_BOUNDARY_AFTER_RE = /[ \t.,!?;:~…?!。]/u
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 커서 앞 구간에서 결정적으로 확실한 오타를 찾는다.
|
* 커서 앞 구간에서 결정적으로 확실한 오타를 찾는다.
|
||||||
*
|
*
|
||||||
|
|
@ -2120,7 +2122,7 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
|
||||||
afterEnglishWord,
|
afterEnglishWord,
|
||||||
nextIsEnglish,
|
nextIsEnglish,
|
||||||
nextEnglishWord,
|
nextEnglishWord,
|
||||||
hasWordBoundaryAfter: /[ \t.,!?;:]/u.test(after),
|
hasWordBoundaryAfter: WORD_BOUNDARY_AFTER_RE.test(after),
|
||||||
vocabulary: options.vocabulary
|
vocabulary: options.vocabulary
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -2199,7 +2201,7 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
|
||||||
!options.terminalMode &&
|
!options.terminalMode &&
|
||||||
/^(?:self|selves)$/iu.test(token.text) &&
|
/^(?:self|selves)$/iu.test(token.text) &&
|
||||||
index > 0 &&
|
index > 0 &&
|
||||||
(/[ \t.,!?;:]/u.test(after) || !options.layoutOnly)
|
(WORD_BOUNDARY_AFTER_RE.test(after) || !options.layoutOnly)
|
||||||
) {
|
) {
|
||||||
const prevToken = tokens[index - 1]
|
const prevToken = tokens[index - 1]
|
||||||
if (
|
if (
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue