feat(desktop): built-in Han/Eng layout auto-switching, terminal/Vim support, and Unicode input

This commit is contained in:
Yun Chan 2026-10-27 10:48:07 +09:00
parent 1da04b9e46
commit a3ac44da2b
109 changed files with 8234 additions and 242 deletions

View file

@ -18,17 +18,21 @@ import { EventEmitter } from 'events'
import { screen } from 'electron'
import { uIOhook } from 'uiohook-napi'
import type { UiohookKeyboardEvent, UiohookMouseEvent, UiohookWheelEvent } from 'uiohook-napi'
import { sql, gte, eq, desc, inArray } from 'drizzle-orm'
import { and, sql, gte, eq, desc, inArray } from 'drizzle-orm'
import {
INPUT_TELEMETRY_DEFAULTS,
SUGGESTION_CONTEXT_MAX_CHARS,
COMPOSING_IDLE_MULTIPLIER,
SUGGESTION_DEFAULTS,
TerminalKeystrokeTracker,
calculateFrictionInsight,
classifyKeyStroke,
computeTypedDelta,
isEditAtTextEnd,
shouldLearnFromApp,
isAppScopedLearning,
isTerminalOrDeveloperSurface,
isXtermHelperControl,
countWords,
emptyActivityBucket,
extractPhrases,
@ -56,7 +60,8 @@ import {
type KeyStrokeClass,
type PersonalPhrase,
type PhraseSource,
type PhysicalRect
type PhysicalRect,
type TerminalVimMode
} from '@d3ro/core/input-intelligence'
import { RecentWritesBuffer, type RecentWrite, type RecentWriteMeta } from '@d3ro/core/recent-writes'
import { getDatabase } from '../db'
@ -66,8 +71,9 @@ import { getLogger } from './LoggerService'
import { acquireGlobalInputHook } from './global-input-hook'
import { uiohookCodeToVk } from './KeyBindingService'
import { getUiaContextService } from './UiaContextService'
import { getForegroundWindowInfo } from '../utils/win32-foreground'
import { getForegroundWindowInfo, isForegroundKoreanIme } from '../utils/win32-foreground'
import { getPersonalGraphService } from './PersonalGraphService'
import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex'
const logger = getLogger('InputTelemetryService')
@ -113,6 +119,10 @@ export interface TypingContext {
* 문서형 컨트롤(터미널 버퍼 등)·비밀번호 칸은 null. 생략하면 prefix 만 쓴다(호환).
*/
documentBefore?: string | null
/** 터미널/캔버스 입력 표면인가 (한영 자판 전환만 허용하고 일반 철자·모델 교정은 억제) */
terminalMode?: boolean
/** 터미널 내 Vim 모드 (노멀 모드에서는 자동 교정을 막는다) */
vimMode?: TerminalVimMode
}
/** 제안 문맥으로 넘길 커서 앞 문서 길이 상한. */
@ -175,6 +185,7 @@ class InputTelemetryService extends EventEmitter {
private _sessionTotals: InputActivityBucket = emptyActivityBucket()
private _flushTimer: NodeJS.Timeout | null = null
private _typoTimer: NodeJS.Timeout | null = null
private _textTimer: NodeJS.Timeout | null = null
/** 디바운스 이후의 settle 스냅샷 — 제안 게이트는 더 늦게 열린다 */
private _settleTimer: NodeJS.Timeout | null = null
@ -219,6 +230,8 @@ class InputTelemetryService extends EventEmitter {
private _lastFocusHwnd: number | null = null
/** 이 창에서 조금 전에 쓴(보낸) 글 — 메모리 전용, 제안 문맥용 */
private readonly _recentWrites = new RecentWritesBuffer()
/** 터미널·Vim 키스트로크 및 화면 줄 추적기 */
private readonly _terminalTracker = new TerminalKeystrokeTracker()
private _lastActiveTickAt = 0
private _lastMouse: { x: number; y: number } | null = null
private _lastClickAt = 0
@ -254,6 +267,7 @@ class InputTelemetryService extends EventEmitter {
private _programmaticKeys = 0
/** 진단용 마지막 키 종류 (키 값 아님) */
private _lastKeyDiag = '-'
private _lastKeyClass: KeyStrokeClass | null = null
private _programmaticKeysUntil = 0
private _prunedAt = 0
@ -306,6 +320,20 @@ class InputTelemetryService extends EventEmitter {
this._programmaticKeysUntil = Date.now() + ttlMs
}
/**
* 현재 터미널 키 버퍼의 접두 길이 — 비동기 치환 시작 시점의 길이를 기록해 도중 입력된 키가 밀리지 않게 한다.
*/
currentTerminalPrefixLength(): number {
return this._terminalTracker.currentPrefix().length
}
/**
* 프로그램(오타 교정)이 커서 앞 deleteCount 글자를 지우고 insertText 를 넣었을 때 터미널 키 버퍼도 동기화한다.
*/
applyProgrammaticReplacement(deleteCount: number, insertText: string, baseLength?: number): void {
this._terminalTracker.applyReplacement(deleteCount, insertText, baseLength)
}
setSuggestionPresentationActive(active: boolean): void {
this._suggestionPresentationActive = active
if (!active && this._presentationValidationTimer) {
@ -359,8 +387,14 @@ class InputTelemetryService extends EventEmitter {
)
this._sampleTimer.unref?.()
this._pruneOldData()
logger.info('입력 텔레메트리 시작 (키/마우스 집계)')
if (this._isTelemetryCollectionEnabled()) {
this._pruneOldData()
}
logger.info(
this._isTelemetryCollectionEnabled()
? '입력 텔레메트리 시작 (키/마우스 집계)'
: '입력 문맥 관찰 시작 (자동 한영·오타 교정 기본 활성, 텔레메트리 저장 없음)'
)
this._emitState()
} catch (error) {
logger.error(
@ -390,6 +424,10 @@ class InputTelemetryService extends EventEmitter {
clearInterval(this._sampleTimer)
this._sampleTimer = null
}
if (this._typoTimer) {
clearTimeout(this._typoTimer)
this._typoTimer = null
}
if (this._textTimer) {
clearTimeout(this._textTimer)
this._textTimer = null
@ -399,6 +437,7 @@ class InputTelemetryService extends EventEmitter {
this._settleTimer = null
}
this.setSuggestionPresentationActive(false)
this._terminalTracker.reset()
this.flushPendingLearning()
this._flush()
this._lastSnapshot = null
@ -453,26 +492,50 @@ class InputTelemetryService extends EventEmitter {
}
}
private _isEnabledByConfig(): boolean {
private _isTelemetryCollectionEnabled(): boolean {
return configGet('inputTelemetryEnabled') === true && configGet('inputTelemetryPaused') !== true
}
private _isEnabledByConfig(): boolean {
if (configGet('inputTelemetryPaused') === true) return false
return (
configGet('inputTelemetryEnabled') === true ||
configGet('typoAutoCorrectEnabled') !== false ||
configGet('suggestionEnabled') === true
)
}
// ── 이벤트 수집 ────────────────────────────────────────
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()
// Win32 SendInput(KEYEVENTF_UNICODE) 가 보내는 합성 유니코드 키는 uiohook 에서 keycode=0 으로 들어온다.
// 사용자 키스트로크나 IME 입력으로 처리하면 버퍼와 타이머를 교란하므로 즉시 무시한다.
if (event.keycode === 0) {
return
}
// uiohook 키코드는 VK 와 다른 표계다 — 정본(VK)으로 변환해 분류한다.
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._programmaticKeys -= 1
if (this._programmaticKeys === 0) {
this._scheduleTextSnapshot()
}
return
}
}
this._registerInput(true)
const bucket = this._bucket()
// uiohook 키코드는 VK 와 다른 표계다 — 정본(VK)으로 변환해 분류한다.
const vk = uiohookCodeToVk(event.keycode)
// 한글·일본어 IME 가 켜져 있으면 Windows 는 글자 키를 VK_PROCESSKEY 로 넘기고, uiohook 은 그것을
// 변환표에 없는 키코드로 보낸다 — 그대로 'other' 로 두면 한글 타이핑 전체가 "타이핑 아님" 이 되어
// 제안이 영영 뜨지 않았다(2026-10-03 실측: 글자 키가 전부 key=other). 수정자 없이 눌린 미지의
@ -489,11 +552,32 @@ class InputTelemetryService extends EventEmitter {
if (keyClass === 'backspace') bucket.backspaces += 1
this._lastKeyAt = Date.now()
this._lastKeyClass = keyClass
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()
// 터미널·Vim·개발 표면에서는 키스트로크 버퍼와 IME 상태를 함께 추적해
// 줄 끝 공백 손실(Windows Terminal)이나 캔버스 터미널(len=0)에서도 한영 자동 전환과 Vim 모드가 동작하게 한다.
const onTerminalSurface = isTerminalOrDeveloperSurface(this._foreground.appName)
const koreanIme =
onTerminalSurface && vk !== null && vk >= 0x41 && vk <= 0x5a
? isForegroundKoreanIme(this._foreground.hwnd)
: undefined
this._terminalTracker.onKeyDown({
hwnd: this._foreground.hwnd,
windowTitle: this._foreground.windowTitle,
vk,
rawKeycode: event.keycode,
shift: this._modifiers.shift,
ctrl: this._modifiers.ctrl,
alt: this._modifiers.alt,
meta: this._modifiers.meta,
koreanIme,
now: this._lastKeyAt
})
this._scheduleTextSnapshot(keyClass)
}
private _handleKeyUp(event: UiohookKeyboardEvent): void {
@ -521,6 +605,7 @@ class InputTelemetryService extends EventEmitter {
this._lastClickPos = position
// 클릭은 다른 칸으로 옮겨 갔을 수 있다 — 다음 스냅샷의 텍스트를 새 기준으로 삼는다.
this._rebaseFocusText = true
this._terminalTracker.onPointerOrFocusChange(this._foreground.hwnd)
}
private _handleMouseUp(event: UiohookMouseEvent): void {
@ -571,7 +656,7 @@ class InputTelemetryService extends EventEmitter {
if (isKeyboard) this._lastActiveTickAt = now
this._lastEventAt = now
this._sampleForeground(now)
this._sampleForeground(now, isKeyboard && gap >= 250)
}
/**
@ -587,9 +672,12 @@ class InputTelemetryService extends EventEmitter {
}
}
/** 포그라운드 창 정보 — 1초에 한 번만 갱신 (FFI 호출 비용) */
private _sampleForeground(now = Date.now()): void {
if (now - this._foregroundSampledAt < INPUT_TELEMETRY_DEFAULTS.activeWindowSampleMinIntervalMs) {
/** 포그라운드 창 정보 — 기본 1초 간격이되, 창 전환 뒤 첫 키 입력(250ms 이상 공백)에는 즉시 갱신한다 */
private _sampleForeground(now = Date.now(), forceImmediate = false): void {
if (
!forceImmediate &&
now - this._foregroundSampledAt < INPUT_TELEMETRY_DEFAULTS.activeWindowSampleMinIntervalMs
) {
return
}
this._foregroundSampledAt = now
@ -642,7 +730,28 @@ class InputTelemetryService extends EventEmitter {
}
}
private _scheduleTextSnapshot(): void {
private _scheduleTextSnapshot(keyClass?: KeyStrokeClass): void {
// Araso 급 빠른 한영 전환: 공백·문장부호 직후에는 40ms 뒤에 즉시 스냅샷을 찍고,
// 일반 글자 입력 중에는 단어를 치는 도중(예: sometime 의 some 시점) 끼어들어 글자를 삼키지 않도록
// 680ms 유휴 뒤에 스냅샷을 찍는다(Vim 명령줄 :wq 등은 160ms).
if (this._typoTimer) clearTimeout(this._typoTimer)
if (keyClass && TYPING_KEY_CLASSES.has(keyClass) && configGet('typoAutoCorrectEnabled') !== false) {
const isBoundaryKey =
keyClass === 'space' ||
keyClass === 'symbol' ||
(keyClass === 'digit' && this._modifiers.shift)
const quickDelay = isBoundaryKey
? 40
: this._terminalTracker.vimMode === 'command'
? 160
: 680
this._typoTimer = setTimeout(() => {
this._typoTimer = null
void this._captureTextSnapshot()
}, quickDelay)
this._typoTimer.unref?.()
}
if (this._textTimer) clearTimeout(this._textTimer)
this._textTimer = setTimeout(() => {
this._textTimer = null
@ -703,7 +812,27 @@ class InputTelemetryService extends EventEmitter {
typedRecently
}
if (snapshot.available) {
if (snapshot.available && isXtermHelperControl(snapshot) && !snapshot.isPassword) {
const usesCaretRect = snapshot.caretRect !== null
context.anchor = snapshot.caretRect ?? snapshot.elementRect
context.anchorKind = usesCaretRect ? 'caret' : snapshot.elementRect ? 'element' : null
const termSnap = this._terminalTracker.reconcileWithXtermValue(
snapshot.text,
this._foreground.hwnd,
context.windowTitle
)
context.available = true
context.isEditable = true
context.prefix = termSnap.prefix
context.fullText = termSnap.prefix
context.caretOffset = termSnap.prefix.length
context.caretReliable = termSnap.caretReliable
context.isComposing =
termSnap.isComposing || (snapshot.isComposing && /[ㄱ-ㅎㅏ-ㅣ가-힣]$/u.test(termSnap.prefix))
context.editedSinceFocus = termSnap.prefix.length > 0 && typedRecently
context.vimMode = termSnap.vimMode
context.terminalMode = true
} else if (snapshot.available) {
const usesCaretRect = snapshot.caretRect !== null
context.anchor = snapshot.caretRect ?? snapshot.elementRect
context.anchorKind = usesCaretRect ? 'caret' : snapshot.elementRect ? 'element' : null
@ -738,7 +867,17 @@ 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) {
// 채팅창 등에서 Enter 로 메시지를 전송해 입력칸이 비워졌거나 툴바 문구("탭 추가 @ 기호" 등)만 남은 경우
// 기준선을 즉시 재설정해 전송 직후 빈 칸/툴바 텍스트에 제안이 뜨지 않게 한다.
const clearedByEnter =
this._lastKeyClass === 'enter' &&
this._editProbe !== null &&
this._editProbe.key === focusKey &&
(textForFocus.length === 0 ||
(textForFocus.length < this._editProbe.text.length &&
!textForFocus.includes('\n') &&
!this._editProbe.text.startsWith(textForFocus)))
if (focusKey !== this._lastFocusKey || this._rebaseFocusText || clearedByEnter) {
// 포커스 깜빡임: 같은 창에서 타이핑하는 동안 UIA 포커스가 입력칸 ↔ 읽을 수 없는 요소(legacy)를
// 오간다(실측 Chrome 2026-10-03: 보류 사유 not-typing 122회). 그때마다 기준선을 다시 잡으면
// 방금 친 글이 "들어올 때부터 있던 글" 이 되어 제안이 영영 안 뜬다. 클릭 없이 키보드로 치다가
@ -746,6 +885,7 @@ class InputTelemetryService extends EventEmitter {
const now = Date.now()
this._typedIntoFocus =
!this._rebaseFocusText &&
!clearedByEnter &&
this._foreground.hwnd !== null &&
this._foreground.hwnd === this._lastFocusHwnd &&
!this._prevSnapshotEditable &&
@ -754,6 +894,10 @@ class InputTelemetryService extends EventEmitter {
this._lastFocusKey = focusKey
this._textAtFocus = textForFocus
this._rebaseFocusText = false
if (clearedByEnter) {
this._lastTypedAt = 0
context.typedRecently = false
}
}
context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus
@ -771,7 +915,12 @@ class InputTelemetryService extends EventEmitter {
// 케어렛을 모르면 "문서 끝 = 커서" 가정이 맞는지 마지막 편집 위치로 확인한다.
// 문서 중간을 고쳤다면 접두(문서 끝)는 커서와 무관하다 — 제안·수락을 막는다.
if (this._editProbe === null || this._editProbe.key !== focusKey) {
// 단, 방금 프로그램(오타 교정·제안 수락)이 커서 앞 텍스트를 바꾼 경우에는 끝 편집으로 본다.
this._pruneExpectedInserts(now)
const programmaticEdit =
this._programmaticKeyBudget > 0 ||
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
if (this._editProbe === null || this._editProbe.key !== focusKey || programmaticEdit) {
this._lastEditAtEnd = true
} else if (this._editProbe.text !== textForFocus) {
this._lastEditAtEnd = isEditAtTextEnd(this._editProbe.text, textForFocus)
@ -779,11 +928,56 @@ class InputTelemetryService extends EventEmitter {
this._editProbe = { key: focusKey, text: textForFocus }
context.caretReliable = caretKnown || this._lastEditAtEnd
// 터미널(Windows Terminal, pwsh, cmd 등)이나 다중 줄 Vim 버퍼에서는 화면 하단 상태줄(-- INSERT --,
// 1,13 All 등) 때문에 문서 전체의 isEditAtTextEnd 가 거짓이 되고, 줄 끝 공백도 UIA 에서 잘린다.
// 화면 줄 diff 와 키스트로크 버퍼를 결합해 실제 편집 중인 줄과 Vim 모드를 복원한다.
const isMultiLineVimBuffer =
snapshot.text.includes('\n') &&
(snapshot.text.includes('-- INSERT --') ||
snapshot.text.includes('-- NORMAL --') ||
/(?:^|\n):\S+/u.test(snapshot.text))
if (
!snapshot.isPassword &&
((isTerminalApp(this._foreground.appName) && (documentLike || snapshot.text.includes('\n'))) ||
isMultiLineVimBuffer)
) {
const termCtx = this._terminalTracker.reconcileWithScreen(snapshot.text, context.windowTitle)
context.prefix = termCtx.prefix
context.caretReliable = termCtx.caretReliable
context.isComposing = snapshot.isComposing || termCtx.isComposing
context.editedSinceFocus =
context.editedSinceFocus || (termCtx.prefix.length > 0 && typedRecently)
context.vimMode = termCtx.vimMode
context.terminalMode = true
} else if (isTerminalApp(this._foreground.appName)) {
context.terminalMode = true
context.vimMode = this._terminalTracker.vimMode
}
if (snapshot.isEditable && !snapshot.isPassword && !snapshot.isComposing) {
this._applyTypedDelta(snapshot)
}
}
// 캔버스·원격·레거시 터미널(Kitedesk, WezTerm, Alacritty, xterm.js 등: UIA 가 텍스트를 전혀 돌려주지 않는 표면)에서는
// 키스트로크 추적기의 현재 줄 문맥을 사용해 한영 자동 전환과 Vim 명령(:ㅈㅂ → :wq)이 동작하게 한다.
if (
!snapshot.isPassword &&
isTerminalOrDeveloperSurface(this._foreground.appName) &&
(!snapshot.available || (!snapshot.isEditable && snapshot.text.length === 0))
) {
const termSnap = this._terminalTracker.getSnapshot(this._foreground.hwnd, context.windowTitle)
context.available = true
context.isEditable = true
context.prefix = termSnap.prefix
context.fullText = termSnap.prefix
context.caretReliable = termSnap.caretReliable
context.isComposing = termSnap.isComposing
context.editedSinceFocus = termSnap.prefix.length > 0 && typedRecently
context.vimMode = termSnap.vimMode
context.terminalMode = true
}
// 포커스 깜빡임 판정용 — 이번 스냅샷이 편집 가능한 칸이었는가, 어느 창이었는가.
this._prevSnapshotEditable = snapshot.available && snapshot.isEditable
this._lastFocusHwnd = this._foreground.hwnd
@ -1041,8 +1235,9 @@ class InputTelemetryService extends EventEmitter {
.join('\n')
)
if (!text) return
// 직접 친 글이 너무 짧으면 문체 표본이 아니다("처음", "pow") — 음성·수락 문장은 이미 문장 단위다.
if (meta.source === 'typed' && text.replace(/\s/gu, '').length < MIN_TYPED_SAMPLE_CHARS) return
// 직접 친 글만 표본 규칙을 본다 — 음성·수락 문장은 이미 문장 단위다.
const typed = meta.source === 'typed'
if (typed && !isLearnableTypedText(text)) return
try {
const db = getDatabase()
@ -1062,15 +1257,23 @@ class InputTelemetryService extends EventEmitter {
createdAt: now
})
.run()
// 앱 안에서만 배우는 앱의 글은 공용 n-gram 에도 넣지 않는다(다른 앱 제안으로 번지지 않게).
if (!isAppScopedLearning(meta.appName)) getPersonalNgramIndex().add(text.slice(0, MAX_SAMPLE_CHARS))
// 개인 그래프에 반영 (문장 노드 + follows/용어공유 엣지)
// 앱 안에서만 배우는 앱은 표본만 남긴다 — 공용 문구·그래프에 들어가면 다른 앱 제안으로 번진다.
if (isAppScopedLearning(meta.appName)) return
getPersonalGraphService().indexText(text, {
source: meta.source,
appName: meta.appName,
at: now
})
for (const phrase of extractPhrases(text).filter(isLearnablePhrase)) {
const phrases = extractPhrases(text).filter(
(phrase) => isLearnablePhrase(phrase) && (!typed || isLearnableTypedText(phrase))
)
for (const phrase of phrases) {
db.insert(personalPhrases)
.values({
id: crypto.randomUUID(),
@ -1107,6 +1310,10 @@ class InputTelemetryService extends EventEmitter {
private _flush(): void {
if (this._pending.size === 0) return
if (!this._isTelemetryCollectionEnabled()) {
this._pending.clear()
return
}
const entries = [...this._pending.entries()]
this._pending.clear()
@ -1445,17 +1652,21 @@ class InputTelemetryService extends EventEmitter {
*
* 학습 동의(inputLearnTypedText)가 없으면 저장된 표본이 없어 자연히 빈 배열이다.
*/
findContinuationHints(prefixTail: string, limit = 3): string[] {
findContinuationHints(prefixTail: string, limit = 3, options: { appName?: string | null } = {}): string[] {
const tail = prefixTail.trim()
if (tail.length < 4) return []
try {
const db = getDatabase()
const pattern = `%${tail.replace(/[%_\\]/gu, '')}%`
// appName 을 주면 그 앱에서 쓴 표본만 본다 (앱 안에서만 배우는 앱의 글이 밖으로 새지 않게).
const where = options.appName
? and(sql`${typingSamples.text} LIKE ${pattern}`, eq(typingSamples.appName, options.appName))
: sql`${typingSamples.text} LIKE ${pattern}`
const rows = db
.select({ text: typingSamples.text })
.from(typingSamples)
.where(sql`${typingSamples.text} LIKE ${pattern}`)
.where(where)
.orderBy(desc(typingSamples.createdAt))
.limit(40)
.all()
@ -1553,7 +1764,12 @@ class InputTelemetryService extends EventEmitter {
.where(eq(personalPhrases.id, id))
.get()
const result = db.delete(personalPhrases).where(eq(personalPhrases.id, id)).run()
if (row) getPersonalGraphService().removePhrase(row.phrase)
if (row) {
getPersonalGraphService().removePhrase(row.phrase)
// 제안 프롬프트는 표본에서도 이어 쓴 글을 찾는다 — 지운 문구가 든 표본도 지워야 제안으로 다시 나오지 않는다.
db.delete(typingSamples).where(sql`instr(${typingSamples.text}, ${row.phrase}) > 0`).run()
}
getPersonalNgramIndex().invalidate()
return Number(result.changes ?? 0) > 0
})
} catch (error) {
@ -1571,6 +1787,7 @@ class InputTelemetryService extends EventEmitter {
db.delete(personalPhrases).run()
db.delete(suggestionsTable).run()
getPersonalGraphService().clearAll()
getPersonalNgramIndex().invalidate()
this._pending.clear()
this._appReadability.clear()
this._sessionTotals = emptyActivityBucket()
@ -1606,7 +1823,13 @@ class InputTelemetryService extends EventEmitter {
})
.from(personalPhrases)
.all()
.filter((row) => excluded(row.source, row.appName) || !isLearnablePhrase(row.phrase))
.filter(
(row) =>
excluded(row.source, row.appName) ||
isAppScopedLearning(row.appName) ||
!isLearnablePhrase(row.phrase) ||
(row.source === 'typed' && !isLearnableTypedText(row.phrase))
)
.map((row) => row.id)
const sampleIds = db
@ -1621,7 +1844,9 @@ class InputTelemetryService extends EventEmitter {
.filter(
(row) =>
excluded(row.source, row.appName) ||
!row.text.split(/\r?\n/u).some((line) => isLearnablePhrase(line))
!row.text.split(/\r?\n/u).some((line) => isLearnablePhrase(line)) ||
// 문장 단위 학습 이전에 스냅샷마다 저장된 조각·주소·깨진 이모지도 같은 규칙으로 걷어낸다.
(row.source === 'typed' && !isLearnableTypedText(row.text))
)
.map((row) => row.id)
@ -1631,6 +1856,7 @@ class InputTelemetryService extends EventEmitter {
for (let i = 0; i < sampleIds.length; i += 200) {
db.delete(typingSamples).where(inArray(typingSamples.id, sampleIds.slice(i, i + 200))).run()
}
if (sampleIds.length > 0) getPersonalNgramIndex().invalidate()
db.run(
sql`DELETE FROM phrase_edges
WHERE from_phrase NOT IN (SELECT phrase FROM personal_phrases)
@ -1659,6 +1885,7 @@ class InputTelemetryService extends EventEmitter {
try {
const db = getDatabase()
db.delete(typingSamples).where(sql`${typingSamples.createdAt} < ${cutoff}`).run()
getPersonalNgramIndex().invalidate()
db.delete(inputActivity).where(sql`${inputActivity.updatedAt} < ${cutoff}`).run()
db.delete(suggestionsTable).where(sql`${suggestionsTable.createdAt} < ${cutoff}`).run()
logger.info(`입력 데이터 보존 정리 완료 (${INPUT_TELEMETRY_DEFAULTS.retentionDays}일 초과)`)
@ -1722,16 +1949,50 @@ function formatLocalDate(date: Date): string {
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)
return !/\s/u.test(trimmed) && /[/=&]/u.test(trimmed)
}
/** 조합이 덜 끝난 채 잡힌 끝 자모("아냐 ㅇ")를 뗀다. */
/** 한글 호환 자모(U+3131–U+318E) */
function isCompatibilityJamo(char: string): boolean {
const code = char.codePointAt(0) ?? 0
return code >= 0x3131 && code <= 0x318e
}
/** "ㅋㅋ"·"ㅠㅠ"·"ㅇㅇ" 처럼 일부러 친 자모 — 말투라서 남긴다. */
function isExpressiveJamo(run: string): boolean {
const chars = [...run]
if (chars.length < 2) return false
return chars.every((char) => 'ㅋㅎㅠㅜ'.includes(char)) || chars.every((char) => char === chars[0])
}
/** 조합이 덜 끝난 채 잡힌 끝 자모("반ㄷ", "아냐 ㅇ")를 뗀다. 말투 자모는 둔다. */
function stripTrailingJamo(line: string): string {
return line.replace(/\s*[\u3131-\u318e]+$/u, '')
const chars = [...line]
let start = chars.length
while (start > 0 && isCompatibilityJamo(chars[start - 1])) start -= 1
if (start === chars.length || isExpressiveJamo(chars.slice(start).join(''))) return line
return chars.slice(0, start).join('').trimEnd()
}
/** 사용 영역(PUA)·짝 잃은 서로게이트 — 이모지가 16비트로 잘려 들어온 흔적이다(🍫 → U+F36B). */
function isBrokenCodePoint(code: number): boolean {
return (code >= 0xe000 && code <= 0xf8ff) || (code >= 0xd800 && code <= 0xdfff)
}
/**
* 직접 친 글이 문체 표본이 될 만한가 — 새로 배울 때와 이미 쌓인 코퍼스를 정리할 때 같은 규칙이다.
* 짧은 조각("처음", "pow"), 주소, 덜 조합된 끝 자모, 깨진 이모지는 표본이 아니다.
*/
function isLearnableTypedText(text: string): boolean {
for (const char of text) {
if (isBrokenCodePoint(char.codePointAt(0) ?? 0)) return false
}
if (isUrlLike(text) || stripTrailingJamo(text) !== text) return false
return text.replace(/\s/gu, '').length >= MIN_TYPED_SAMPLE_CHARS
}
/** 제어문자 제거 + 공백 정규화. 2자 미만은 버린다. */
@ -1740,8 +2001,7 @@ function sanitizeSample(raw: string): string {
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
if (isBrokenCodePoint(code)) continue
stripped += code < 0x20 || code === 0x7f ? ' ' : char
}
const cleaned = stripped.replace(/\s+/gu, ' ').trim()