feat(desktop): propose typo fixes inside the suggestion popup and make suggestions snappier

While suggestions are on, typos are no longer replaced silently. The popup shows
the fix next to the candidate and applies it only when the candidate is accepted.
The per-minute request cap rises from 6 to 20 so suggestions keep appearing after
accepting one and continuing to type.
This commit is contained in:
Yun Chan 2026-10-18 07:06:55 +09:00
parent d63854db67
commit f5ae4c8c04
38 changed files with 1239 additions and 660 deletions

View file

@ -5,16 +5,20 @@ import { describe, expect, it } from 'vitest'
import {
buildVocabulary,
detectHangulTypedLatin,
detectJamoNoise,
detectLatinTypedHangul,
detectTypoRevert,
detectTypos,
fixByVocabulary,
fixKnownMisspelling,
hasSuspiciousTypo,
mergeTypoCorrections,
hangulToLatin,
isPlausibleTypoFix,
latinToHangul,
parseModelTypoPairs,
planTypoReplacement,
validateModelCorrections,
typoRegionStart,
validateModelCorrections
} from '../src/typo-correction'
@ -221,3 +225,33 @@ describe('되돌리기 감지', () => {
expect(detectTypoRevert('그건 됐다 그리고', { from: '됬다', to: '됐다', tailLength: 4 })).toBe(false)
})
})
describe('낱자 잡음 (2026-10-17 실측 입력)', () => {
const fixed = (text: string): string | null => planTypoReplacement(text, detectJamoNoise(text))?.insertText ?? null
it('음절 사이·앞에 끼어든 낱자 하나를 지운다', () => {
expect(fixed('그ㅓ런건 전혀')).toBe('그런건 전혀')
expect(fixed('내 가쓴ㄷ거에 대한')).toBe('가쓴거에 대한')
expect(fixed('파츠가 ㅇ다른 UI')).toBe('다른 UI')
expect(fixed('안ㄴ뇽하세여.?')).toBe('안뇽하세여.?')
})
it('문장 중간에 홀로 남은 낱자는 뒤 공백과 함께 지운다 — 끝의 낱자를 지워도 "아직 " 이 남는다', () => {
expect(fixed('실망스럽고 ㅇ ㅇ이전 까지')).toBe('이전 까지')
expect(fixed('아직 ㅇ')).toBe('')
expect(planTypoReplacement('아직 ㅇ', detectJamoNoise('아직 ㅇ'))?.deleteCount).toBe(1)
})
it('의도한 낱자(ㅋㅋ·ㅠㅠ·끝의 감정 낱자·첫머리 대답)는 두고, 수상하다고 보지도 않는다', () => {
for (const text of ['ㅋㅋ 좋아', '좋아ㅋㅋ', '고마워ㅎ', '미안ㅠ', 'ㅇ 알겠어', 'ㅇㅋ 그럼']) {
expect(detectJamoNoise(text)).toEqual([])
expect(hasSuspiciousTypo(text)).toBe(false)
}
})
it('모델 교정이 같은 단어의 낱자 지우기보다 앞선다', () => {
const text = '안ㄴ뇽하세여.?'
const model = validateModelCorrections(text, [{ from: '안ㄴ뇽하세여', to: '안녕하세요' }])
expect(planTypoReplacement(text, mergeTypoCorrections(model, detectJamoNoise(text)))?.insertText).toBe('안녕하세요.?')
})
})

View file

@ -1212,6 +1212,18 @@ export interface SuggestionCandidate {
joint?: SuggestionJoint
}
/**
* 제안과 함께 내놓는 오타 교정 — 커서 앞 원문 끝의 `from` 을 `to` 로 바꾼 뒤 후보를 잇는다.
*
* 조용히 고치지 않고 제안 창에 "지운 글자 → 고친 글자" 로 보여 주며, 수락할 때만 적용한다.
* `edits` 는 `from` 안의 위치(표시용)다 — 바뀐 단어만 강조하고 나머지는 그대로 보인다.
*/
export interface SuggestionCorrection {
from: string
to: string
edits: Array<{ start: number; end: number; to: string }>
}
/** 현재 제안이 어느 로컬 근거에서 나왔는지 보여 주는 비식별 설명. */
export interface SuggestionProvenance {
mode: 'local-model' | 'local-memory'
@ -1267,6 +1279,8 @@ export interface SuggestionState {
typoAutoCorrect: boolean
/** 후보를 만든 로컬 근거의 수량만 노출한다. */
provenance: SuggestionProvenance | null
/** 이 세션의 후보가 함께 적용하는 오타 교정 (없으면 null) */
correction: SuggestionCorrection | null
}
/** 제안 기본값 — 인라인 컴플리션 실측 중앙값 기준. */
@ -1286,14 +1300,28 @@ export const SUGGESTION_DEFAULTS = {
* 보수적이다.
*/
minPrefixChars: 8,
minIntervalMs: 5000,
/**
* 요청 사이 최소 간격.
*
* 원래 5초였다 — 로컬 모델 첫 후보가 0.8초 안팎인데 5초·분당 6회에 막혀, 제안을 고르고 이어 친 뒤
* 다시 멈추면 rate-limited 로 아무것도 안 떴다(실측 2026-10-17: "나올 때도 있고 안 나올 때도").
* 치는 동안 진행 중 요청은 취소·환불되므로 간격은 짧아도 된다.
*/
minIntervalMs: 1200,
/**
* 손을 멈춘 뒤 "생성 중" 자리를 먼저 띄우는 시점 (ms). 생성은 triggerDelayMs(조합 중이면 배수) 뒤에
* 시작하고, 그 전에 다시 치면 조용히 거둔다 — 반응은 빠르게, 모델 호출은 지금처럼 보수적으로.
*/
presenceDelayMs: 350,
/** 먼저 띄운 자리가 생성으로 이어지지 않으면 이 시간 뒤 스스로 거둔다 (ms) */
presenceMaxMs: 3000,
/**
* 멈춤 판단의 하한. 이보다 짧으면 글자 사이의 순간 멈춤에도 생성이 시작돼,
* 치는 도중 창이 떴다 사라지기를 반복한다(실측 2026-09-27: 100ms 설정에서
* 5~6초마다 생성→소멸 반복).
*/
minTriggerDelayMs: 500,
maxRequestsPerMinute: 6,
maxRequestsPerMinute: 20,
dailyBudget: 500,
/** 로컬 기억 경로(폴백)에서 한 번에 만드는 후보 수 — 채우기 루프가 없다. */
maxCandidates: 3,
@ -1320,7 +1348,7 @@ export const SUGGESTION_DEFAULTS = {
* 오버레이는 "다음 문맥" 이 와야 지워지는데, 타이핑을 멈추면 문맥이 오지 않아
* 창이 무한정 남는다(실측 신고: 아무것도 안 치는데 제안창이 떠 있음).
*/
visibleTtlMs: 20000,
visibleTtlMs: 45000,
/**
* 요청 시작 후 이 시간이 지나면 결과를 폐기한다.
*
@ -1353,7 +1381,7 @@ export const SUGGESTION_DEFAULTS = {
*
* 조합 중에는 손을 멈춘 것으로 보이려면 기본 지연의 이 배수만큼 조용해야 한다.
*/
export const COMPOSING_IDLE_MULTIPLIER = 1.5
export const COMPOSING_IDLE_MULTIPLIER = 1.2
/**
* 접두가 이만큼 더 자라면 재생성한다.
@ -1382,8 +1410,14 @@ export const INPUT_TELEMETRY_DEFAULTS = {
activeWindowSampleMinIntervalMs: 1000,
/** 마지막 입력 후 이 시간이 지나면 활성 시간 누적을 멈춘다 */
activeIdleTimeoutMs: 60000,
/** 텍스트 스냅샷(학습/컨텍스트) 디바운스 */
textSnapshotDebounceMs: 700,
/**
* 텍스트 스냅샷(학습/컨텍스트) 디바운스.
*
* 700ms 였다 — 제안 창은 이 스냅샷이 와야 뜨므로, 잠깐 쉬어도 창이 늦게 떴다("UI 가 빠릿하게, 잠시
* 쉬면 나와야" — 2026-10-17). 이 시점에 "생성 중" 자리를 먼저 띄우고(presenceDelayMs), 생성은
* 트리거 지연 뒤에 시작한다.
*/
textSnapshotDebounceMs: 380,
/** 백그라운드 샘플 주기 (ms) — 타이핑이 이어져도 관측을 멈추지 않는다 */
sampleIntervalMs: 800,
/** 마지막 입력이 이 시간 안에 있었으면 주기 샘플을 돌린다 (ms) */

View file

@ -16,7 +16,7 @@ import { isCommonHangulSyllable } from './hangul-common-syllables'
// 타입
// ============================================================
export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model'
export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model' | 'jamo'
/** 접두(커서 앞 텍스트) 안의 교정 하나. start/end 는 접두 문자열 오프셋(UTF-16)이다. */
export interface TypoCorrection {
@ -591,6 +591,87 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
return out
}
// ============================================================
// 자모 잡음 (낱자가 음절 사이에 끼어든 오타)
// ============================================================
/** 호환 자모 (ㄱ–ㅣ) — 조합되지 못하고 남은 낱자 */
const COMPAT_JAMO = /^[\u3131-\u3163]$/u
/** 일부러 붙이는 감정 낱자 (고마워ㅎ, 좋아ㅋ, 미안ㅠ) — 낱자 하나여도 오타가 아니다 */
const EMOTIVE_JAMO = new Set(['ㅋ', 'ㅎ', 'ㅠ', 'ㅜ'])
/**
* 음절 사이·앞에 끼어든 낱자 하나를 지우는 교정을 찾는다.
*
* 실측(2026-10-17, 사용자 입력 원문): "안ㄴ뇽", "그ㅓ런", "가쓴ㄷ거", "ㅇ다른", "실망스럽고 ㅇ ㅇ이전".
* 빠르게 치다 조합이 깨지면 낱자가 남는다. 낱자 둘 이상(ㅋㅋ, ㅠㅠ, ㅇㅋ)과 끝에 붙인 감정 낱자는
* 의도한 표현이라 두고, 단어 하나가 통째로 낱자 하나인 것(문장 중간의 "ㅇ")은 앞 공백과 함께 지운다.
* 결정적 규칙은 "지우기" 만 한다 — "안ㄴ뇽 → 안녕" 처럼 글자를 바꿔야 하는 것은 모델 검사 몫이다.
*/
export function detectJamoNoise(prefix: string, options: { ignoredWords?: readonly string[] } = {}): TypoCorrection[] {
const regionStart = typoRegionStart(prefix)
const tokens = tokenizeWords(prefix).filter((token) => token.start >= regionStart)
const out: TypoCorrection[] = []
tokens.forEach((token, index) => {
if (isIgnored(token.text, options.ignoredWords)) return
const chars = Array.from(token.text)
if (chars.length === 1 && COMPAT_JAMO.test(chars[0])) {
// 글 첫 단어인 "ㅇ"(응)·"ㄱ"(고) 는 대답이다 — 앞에 한글 단어가 있을 때만 잡음으로 본다.
const previous = tokens[index - 1]
if (!previous || !HANGUL_SYLLABLE.test(previous.text) || EMOTIVE_JAMO.has(chars[0])) return
// 뒤 공백과 함께 지운다 — 앞 공백을 지우면 끝에 남은 낱자("있고 ㅇ")가 "있고" 가 되어, 모델이 끝난
// 단어에 글자를 붙이려 하거나 곧바로 턴을 닫았다(실측 2026-10-17: 교정이 붙은 첫 후보 4번 모두 빈 출력).
const end = /[ \t]/u.test(prefix[token.end] ?? '') ? token.end + 1 : token.end
out.push({ start: token.start, end, from: prefix.slice(token.start, end), to: '', source: 'jamo' })
return
}
if (!HANGUL_SYLLABLE.test(token.text)) return
let changed = false
const kept = chars.filter((char, position) => {
if (!COMPAT_JAMO.test(char)) return true
const lone = !COMPAT_JAMO.test(chars[position - 1] ?? '') && !COMPAT_JAMO.test(chars[position + 1] ?? '')
if (!lone) return true
if (position === chars.length - 1 && EMOTIVE_JAMO.has(char)) return true
changed = true
return false
})
if (!changed) return
const to = kept.join('')
if (!HANGUL_SYLLABLE.test(to)) return
out.push({ start: token.start, end: token.end, from: token.text, to, source: 'jamo' })
})
return out
}
/**
* 모델에 오타 검사를 맡길 만큼 수상한 구간인가 — 낱자가 섞인 한글 단어, 드문 음절, 결정적 탐지 결과.
*
* 제안 창에 교정을 함께 내놓을 때 멈출 때마다 모델 검사(0.5초)를 하면 제안이 그만큼 늦는다.
* 수상한 흔적이 있을 때만 묻는다.
*/
export function hasSuspiciousTypo(region: string): boolean {
if (detectJamoNoise(region).length > 0) return true
return tokenizeWords(region).some((token) =>
Array.from(token.text).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))
)
}
/**
* 같은 구간에 대한 교정을 합친다 — 앞 목록이 우선이고, 겹치는 뒤 목록 항목은 버린다.
* (모델이 "안ㄴ뇽 → 안녕" 을 냈으면 같은 단어의 "낱자 지우기" 는 쓰지 않는다)
*/
export function mergeTypoCorrections(
primary: readonly TypoCorrection[],
secondary: readonly TypoCorrection[]
): TypoCorrection[] {
const out = [...primary]
for (const candidate of secondary) {
if (out.some((existing) => candidate.start < existing.end && existing.start < candidate.end)) continue
out.push(candidate)
}
return out.sort((a, b) => a.start - b.start)
}
// ============================================================
// 모델 교정 검증
// ============================================================