// src/main/services/InputTelemetryService.ts // // 입력 텔레메트리 수집기 — 키보드/마우스 집계 + 포커스 입력창 텍스트 학습. // // 설계 근거 (조사 기반): // - 수집 항목·집계·flush 주기는 ActivityWatch `aw-watcher-input` 따른다: // 카운트(keystrokes/clicks/scroll) + 마우스 이동량(축별 절대값 합)만 남기고 // **키 내용은 저장하지 않는다**. 5초 heartbeat 로 집계를 확정한다. // - 키 이벤트는 uiohook(이미 사용 중) 글로벌 후킹에서 받는다. 후킹은 프로세스 // 전역 글턴이므로 global-input-hook 의 참조 카운트로 KeyBindingService 와 공존한다. // - 이핑한 텍스트는 키코드로 복원하지 않는다 (한/일 IME 는 조합 결과가 텍스트라 // 원리적으로 불가). 대신 UIA 로 커밋된 텍스트를 읽어 스냅샷 diff 로 계산한다. // - 비밀번호 필드(IsPassword)와 IME 조합 중에는 스트를 쓰지 않는다 (fail-closed). // // 동의(consent) 기본값은 모두 OFF 다. `inputTelemetryEnabled` 없이는 아무것도 하지 않는다. import { EventEmitter } from 'events' import { screen } from 'electron' import { uIOhook } from 'uiohook-napi' import type { UiohookKeyboardEvent, UiohookMouseEvent, UiohookWheelEvent } from 'uiohook-napi' 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, isLearnablePhrase, isTerminalApp, manhattanDistance, mergeActivityBucket, normalizeRequestPrefix, rankFlowWindows, recommendAppExclusion, summarizeActivity, textBeforeCaret, withoutPlaceholderText, type AnchorKind, type FocusSnapshot, type InputActivityBucket, type InputAppStat, type InputAppSuggestionStat, type InputDailyStat, type InputHourlyStat, type InputInsightsSummary, type InputPrivacyReceipt, type InputTelemetryState, type InputSnapshotSummary, type AppReadabilityEvidence, type KeyStrokeClass, type PersonalPhrase, type PhraseSource, type PhysicalRect, type TerminalVimMode } from '@d3ro/core/input-intelligence' import { RecentWritesBuffer, type RecentWrite, type RecentWriteMeta } from '@d3ro/core/recent-writes' import { detectTypos } from '@d3ro/core/typo-correction' import { getDatabase } from '../db' import { inputActivity, personalPhrases, suggestions as suggestionsTable, typingSamples } from '../db/schema' import { configGet, configSet } from './ConfigService' import { getLogger } from './LoggerService' import { acquireGlobalInputHook } from './global-input-hook' import { uiohookCodeToVk } from './KeyBindingService' import { getUiaContextService } from './UiaContextService' import { getForegroundWindowInfo, isForegroundKoreanIme } from '../utils/win32-foreground' import { getLastNativeInputTick } from '../utils/win32-input-activity' import { getPersonalGraphService } from './PersonalGraphService' import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex' const logger = getLogger('InputTelemetryService') /** 제안 서비스가 소비하는 "지금 치고 있는 것" 스냅샷. */ export interface TypingContext { /** 어렛 앞 텍스트 (>제안 프롬프트 입력) */ prefix: string fullText: string caretOffset: number | null /** * 오버레이 앵커 — UIA 가 준 물리 픽셀 그대로다(사이드카가 DPI-aware 로 동작). * DIP 변환은 창 배치(WindowManager → ScreenGeometryPort) 한 곳에서만 한다. */ anchor: PhysicalRect | null /** anchor 가 케어렛인지 포커스 요소 전체인지 — 오버레이 배치 전략을 결정한다 */ anchorKind: AnchorKind isPassword: boolean isEditable: boolean isComposing: boolean hasSelection: boolean available: boolean appName: string | null windowTitle: string | null /** * 입력창이 속한 최상위 창 핸들 (HWND). 알 수 없으면 null. * 제안 수락 직전 "아직 같은 창인가" 를 확인하는 기준이다. */ windowHandle?: number | null idleMs: number capturedAt: number /** 스냅샷을 읽는 동안 입력/포커스가 바뀌지 않았는지 확인한 단조 증가 번호. */ inputRevision?: number /** Windows 세션의 마지막 입력 tick. null이면 네이티브 입력 상태 확인 실패, 다른 OS는 생략. */ nativeInputTick?: number | null /** 포커스가 바뀐 뒤 이 필드에서 실제로 편집이 있었는가 (마우스로 들어오기만 한 경우 false) */ editedSinceFocus: boolean /** 최근에 실제로 타이핑했는가 (recentTypingWindowMs 이내) */ typedRecently: boolean /** * prefix 가 실제 커서 앞 텍스트라고 믿을 수 있는가 — 케어렛 오프셋을 알면 true, 모르면 * 마지막 편집이 문서 끝에서 일어났을 때만 true. 생략하면 true 로 본다(호환). */ caretReliable?: boolean /** * 커서 앞 문서 전체 (원문, 최대 DOCUMENT_BEFORE_MAX_CHARS). prefix 는 400자 창이라 글 앞쪽의 * 인사·이름·날짜를 모른다 — 제안 프롬프트가 첫머리·사실을 여기서 뽑는다. * 문서형 컨트롤(터미널 버퍼 등)·비밀번호 칸은 null. 생략하면 prefix 만 쓴다(호환). */ documentBefore?: string | null /** 터미널/캔버스 입력 표면인가 (한영 자판 전환만 허용하고 일반 철자·모델 교정은 억제) */ terminalMode?: boolean /** 터미널 내 Vim 모드 (노멀 모드에서는 자동 교정을 막는다) */ vimMode?: TerminalVimMode } /** 제안 문맥으로 넘길 커서 앞 문서 길이 상한. */ const DOCUMENT_BEFORE_MAX_CHARS = 6000 interface InputTelemetryEvents { 'state-changed': (state: InputTelemetryState) => void 'typed-context': (context: TypingContext) => void activity: (payload: { totals: InputActivityBucket; appName: string | null }) => void } interface ForegroundInfo { appName: string | null windowTitle: string | null hwnd: number | null } const MAX_SAMPLE_CHARS = 500 /** * 프로그램 삽입(제안 수락 등) 예고의 유효 시간. * * 수락은 수정자 키가 떼어지길 최대 1.5초 기다린 뒤 붙여넣고, 스냅샷은 디바운스(700ms)· * settle·UIA 조회(최대 1.5초)를 거쳐 온다 — 그 합을 넉넉히 덮는다. */ const PROGRAMMATIC_INSERT_TTL_MS = 10_000 /** * 타이핑 학습은 스냅샷 diff(0.4~0.8초마다)를 바로 저장하지 않고 필드별로 모았다가 문장 단위로 저장한다. * 바로 저장하면 "찬받고 초콜릿을 받은 아이. 아빠" / "도 잘했으니까…" 처럼 단어 중간에서 잘린 * 조각이 표본·문구로 쌓여 제안 힌트를 오염시켰다(실측 2026-10-24 DB). */ const LEARN_IDLE_FLUSH_MS = 2000 /** diff 붙여넣기 판정(200자)에 걸리기 전에 끊어 저장한다. */ const LEARN_MAX_PENDING_CHARS = 150 const RETENTION_PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000 const MAX_READABILITY_APPS = 64 /** * "실제로 타이핑했다" 로 볼 키 종류. * * 화살표/단축키/기능키/엔터/탭 등은 제외한다 — 필드 이동이나 명령일 뿐 텍스트를 * 치는 게 아니다. IME 조합은 포함한다(한/일 입력은 조합 중이 곧 타이핑이다). */ const TYPING_KEY_CLASSES = new Set([ 'letter', 'digit', 'symbol', 'space', 'backspace', 'delete', 'ime' ]) class InputTelemetryService extends EventEmitter { private _running = false private _releaseHook: (() => void) | null = null /** 아직 DB에 쓰지 않은 버킷 (key = date|hour|appName) */ private _pending: Map = new Map() /** 세션 누적 (라이브 UI 용) */ 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 /** 백그라운드 주기 샘플러 — 타이핑이 이어져도 계속 관측한다 */ private _sampleTimer: NodeJS.Timeout | null = null /** 주기 샘플 스냅샷 진행 중 (중복 방지) */ private _sampling = false /** 모든 스냅샷 트리거를 합쳐 같은 UIA 응답을 중복 적용하지 않는다. */ private _snapshotRequest: Promise | null = null /** 같은 밀리초에 들어온 키·클릭도 서로 다른 편집으로 구분한다. */ private _inputRevision = 0 /** 제안 오버레이가 표시 중일 때만 포커스 이탈/선택을 계속 확인한다. */ private _suggestionPresentationActive = false private _presentationValidationTimer: NodeJS.Timeout | null = null private _lastEventAt = 0 /** * 마지막 키보드 입력 시각. * * 제안 문맥은 키보드 기준으로만 판단한다 — 마우스 클릭만으로 스냅샷이 돌면 * 필드에 이미 있던 텍스트로 제안이 만들어졌다(실측 신고). */ private _lastKeyAt = 0 /** * 마지막 "실제 타이핑" 시각 (TYPING_KEY_CLASSES 에 속하는 키만). * * `_lastKeyAt` 은 화살표/단축키를 포함한 모든 키를 기록해 필드 이동만으로도 * 갱신된다. 제안 게이트는 진짜 타이핑만 기준으로 삼아야 한다(실측: 필드에 * 이미 있던 텍스트를 마우스로 클릭만 했는데 제안이 뜸). */ private _lastTypedAt = 0 /** 현재 포커스된 (창, 컨트롤 종류, 위치)를 식별하는 키 — 바뀌면 새 필드로 본다. */ private _lastFocusKey = '' /** 현재 포커스에 들어왔을 때의 텍스트 (비밀번호는 저장하지 않는다) — 편집 여부 판정 기준선. */ private _textAtFocus = '' /** 직전 스냅샷의 (포커스 키, 텍스트) — 케어렛을 모를 때 편집 위치 판정에 쓴다 */ private _editProbe: { key: string; text: string } | null = null /** 마지막 편집이 문서 끝에서 일어났는가 (케어렛을 모를 때만 의미가 있다) */ private _lastEditAtEnd = true /** 클릭 뒤 첫 스냅샷에서 기준선을 다시 잡는다 */ private _rebaseFocusText = false /** 포커스 깜빡임 뒤 돌아온 칸 — 키보드로 친 채 돌아왔으므로 이미 편집한 칸으로 본다 */ private _typedIntoFocus = false /** 현재 포커스/클릭 이후 실제로 글자 키를 쳤는가 (첫 스냅샷 전 빠른 입력 보존) */ private _typedInCurrentFocus = false /** Chromium/Electron 등 UIA GetActiveComposition 미지원 앱을 위한 키스트로크 기반 한글 조합 추정 */ private _imeComposing = false private _lastTypedHwnd: number | null = null /** 직전 스냅샷이 편집 가능한 칸이었는가 / 어느 창이었는가 (포커스 깜빡임 판정) */ private _prevSnapshotEditable = false 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 private _lastClickButton = -1 private _lastClickPos: { x: number; y: number } | null = null private _modifiers = { ctrl: false, alt: false, shift: false, meta: false } private _foreground: ForegroundInfo = { appName: null, windowTitle: null, hwnd: null } private _foregroundSampledAt = 0 private _lastSnapshot: FocusSnapshot | null = null /** 마지막 스냅샷이 caret 폴백(tail 가정)을 썠는지 — 진단용 */ private _caretFallback = false private _lastSnapshotKey = '' private _lastContext: TypingContext | null = null /** UI 진단용 스냅샷 요약 */ private _lastSnapshotSummary: InputSnapshotSummary | null = null /** 원문 없이 앱별 UIA 읽기 가능성만 누적한다. */ private _appReadability = new Map() /** 곧(또는 방금) 프로그램이 삽입한 텍스트 — 다음 diff 에서 "타이핑" 으로 학습하지 않는다. */ private _expectedInserts: Array<{ id: number; text: string; expiresAt: number }> = [] /** 아직 저장하지 않은 타이핑 구간 — 같은 필드에서 baseline → latest 로 바뀐 부분을 한 번에 학습한다. */ private _pendingLearn: { baseline: string latest: string appName: string | null windowTitle: string | null } | null = null private _learnFlushTimer: ReturnType | null = null private _expectedInsertSeq = 0 /** 통계에서 뺄 프로그램 키 남은 수와 유효 시각 */ private _programmaticKeys = 0 /** 진단용 마지막 키 종류 (키 값 아님) */ private _lastKeyDiag = '-' private _lastKeyClass: KeyStrokeClass | null = null private _programmaticKeysUntil = 0 private _prunedAt = 0 private _onKeyDown: ((e: UiohookKeyboardEvent) => void) | null = null private _onKeyUp: ((e: UiohookKeyboardEvent) => void) | null = null private _onMouseDown: ((e: UiohookMouseEvent) => void) | null = null private _onMouseUp: ((e: UiohookMouseEvent) => void) | null = null private _onMouseMove: ((e: UiohookMouseEvent) => void) | null = null private _onWheel: ((e: UiohookWheelEvent) => void) | null = null // ── 타입 안전한 이벤트 오버로드 ──────────────────────── override on(event: K, listener: InputTelemetryEvents[K]): this { return super.on(event, listener as (...args: unknown[]) => void) } override off( event: K, listener: InputTelemetryEvents[K] ): this { return super.off(event, listener as (...args: unknown[]) => void) } override emit( event: K, ...args: Parameters ): boolean { return super.emit(event, ...args) } get isRunning(): boolean { return this._running } get lastContext(): TypingContext | null { return this._lastContext } /** 마지막 키보드 입력 시각 (ms) — 오타 교정이 "스냅샷 뒤 사용자가 더 쳤는가" 를 확인한다. */ get lastKeyAt(): number { return this._lastKeyAt } get inputRevision(): number { return this._inputRevision } /** * 곧 프로그램이 키 count 개를 보낸다 — 그 키들은 입력 통계에 넣지 않는다. * 남은 예고는 ttlMs 뒤 무효다(보내지 못한 키가 사용자 키를 삼키지 않게). */ expectProgrammaticKeys(count: number, ttlMs = 3000): void { this._programmaticKeys = Math.max(0, count) this._programmaticKeysUntil = Date.now() + ttlMs if (count > 0) this._imeComposing = false } /** * 현재 터미널 키 버퍼의 접두 길이 — 비동기 치환 시작 시점의 길이를 기록해 도중 입력된 키가 밀리지 않게 한다. */ currentTerminalPrefixLength(): number { return this._terminalTracker.currentPrefix().length } /** * 프로그램(오타 교정)이 커서 앞 deleteCount 글자를 지우고 insertText 를 넣었을 때 터미널 키 버퍼도 동기화한다. */ applyProgrammaticReplacement(deleteCount: number, insertText: string, baseLength?: number): void { this._inputRevision += 1 this._imeComposing = false this._terminalTracker.applyReplacement(deleteCount, insertText, baseLength) } setSuggestionPresentationActive(active: boolean): void { this._suggestionPresentationActive = active if (!active && this._presentationValidationTimer) { clearTimeout(this._presentationValidationTimer) this._presentationValidationTimer = null } } // ─ 수명 주기 ────────────────────────────────────────── /** 설정이 허용하면 수집을 시작한다. 실패해도 앱은 계속 돌아간다. */ start(): void { if (!this._isEnabledByConfig()) { logger.info('입력 텔레메트리 비활성 (설정 또는 일시정지)') return } if (this._running) return try { this._onKeyDown = (e: UiohookKeyboardEvent) => this._handleKeyDown(e) this._onKeyUp = (e: UiohookKeyboardEvent) => this._handleKeyUp(e) this._onMouseDown = (e: UiohookMouseEvent) => this._handleMouseDown(e) this._onMouseUp = (e: UiohookMouseEvent) => this._handleMouseUp(e) this._onMouseMove = (e: UiohookMouseEvent) => this._handleMouseMove(e) this._onWheel = (e: UiohookWheelEvent) => this._handleWheel(e) uIOhook.on('keydown', this._onKeyDown) uIOhook.on('keyup', this._onKeyUp) uIOhook.on('mousedown', this._onMouseDown) uIOhook.on('mouseup', this._onMouseUp) uIOhook.on('mousemove', this._onMouseMove) uIOhook.on('wheel', this._onWheel) this._releaseHook = acquireGlobalInputHook() this._running = true this._inputRevision += 1 this._flushTimer = setInterval( () => this._flush(), INPUT_TELEMETRY_DEFAULTS.flushIntervalMs ) this._flushTimer.unref?.() // 주기 샘플러. // // 스냅샷이 "타이핑을 멈춘 뒤" 에만 돌면, 계속 치는 동안에는 디바운스 타이머가 // 계속 리셋돼 샘플이 하나도 만들어지지 않는다(실측: 에이전트 개발처럼 // 끊김 없이 치는 상황에서 제안이 전혀 안 뜸). 최근 입력이 있었으면 // 주기적으로 스냅샷을 만들어, 타이핑 중에도 제안이 계속 갱신되게 한다. this._sampleTimer = setInterval( () => this._sampleWhileTyping(), INPUT_TELEMETRY_DEFAULTS.sampleIntervalMs ) this._sampleTimer.unref?.() if (this._isTelemetryCollectionEnabled()) { this._pruneOldData() } logger.info( this._isTelemetryCollectionEnabled() ? '입력 텔레메트리 시작 (키/마우스 집계)' : '입력 문맥 관찰 시작 (자동 한영·오타 교정 기본 활성, 텔레메트리 저장 없음)' ) this._emitState() } catch (error) { logger.error( `입력 텔레메트리 시작 실패: ${error instanceof Error ? error.message : String(error)}` ) this._detachListeners() } } stop(): void { this._inputRevision += 1 // 입력 관찰을 끄면 메모리에 잡아 둔 "조금 전에 쓴 글" 도 버린다. this._recentWrites.clear() if (!this._running) { this.setSuggestionPresentationActive(false) return } this._detachListeners() this._releaseHook?.() this._releaseHook = null this._running = false if (this._flushTimer) { clearInterval(this._flushTimer) this._flushTimer = null } if (this._sampleTimer) { clearInterval(this._sampleTimer) this._sampleTimer = null } if (this._typoTimer) { clearTimeout(this._typoTimer) this._typoTimer = null } if (this._textTimer) { clearTimeout(this._textTimer) this._textTimer = null } if (this._settleTimer) { clearTimeout(this._settleTimer) this._settleTimer = null } this.setSuggestionPresentationActive(false) this._terminalTracker.reset() this.flushPendingLearning() this._flush() this._lastSnapshot = null this._lastSnapshotKey = '' logger.info('입력 텔레메트리 중지') this._emitState() } /** 설정 변경 반영 (enable/pause/excludedApps). */ applyConfig(): void { const shouldRun = this._isEnabledByConfig() if (shouldRun && !this._running) this.start() else if (!shouldRun && this._running) this.stop() this._emitState() } dispose(): void { this.stop() this._recentWrites.clear() this.removeAllListeners() } /** 같은 창에서 조금 전에 쓴(보내서 칸이 비워진) 글 — 오래된 것부터. 메모리에만 있다. */ listRecentWrites(meta: RecentWriteMeta, limit = 4): RecentWrite[] { return this._recentWrites.listFor(meta, Date.now(), limit) } private _detachListeners(): void { if (this._onKeyDown) { uIOhook.removeListener('keydown', this._onKeyDown) this._onKeyDown = null } if (this._onKeyUp) { uIOhook.removeListener('keyup', this._onKeyUp) this._onKeyUp = null } if (this._onMouseDown) { uIOhook.removeListener('mousedown', this._onMouseDown) this._onMouseDown = null } if (this._onMouseUp) { uIOhook.removeListener('mouseup', this._onMouseUp) this._onMouseUp = null } if (this._onMouseMove) { uIOhook.removeListener('mousemove', this._onMouseMove) this._onMouseMove = null } if (this._onWheel) { uIOhook.removeListener('wheel', this._onWheel) this._onWheel = null } } 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) // 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._inputRevision += 1 this._programmaticKeys -= 1 if (this._programmaticKeys === 0) { this._scheduleTextSnapshot() } return } } // 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다. // 여기서 _inputRevision·_lastKeyAt·스냅샷 타이머를 건드리면 수정자 키를 쥐고 있는 동안 // 진행 중 UIA 스냅샷이 버려지고 유휴 시간(idleMs)과 터미널 버퍼가 리셋된다. if (vk !== null && classifyKeyStroke(vk, this._modifiers) === 'modifier') { return } // D3RO Voice 전역 제안 탐색/수락 단축키(Ctrl+Alt+방향키/Enter/Space/Backspace)는 // OS globalShortcut 이 가로채므로 대상 앱 텍스트를 바꾸지 않는다. const isSuggestionChord = this._modifiers.ctrl && this._modifiers.alt && !this._modifiers.meta && (vk === 0x0d || vk === 0x20 || vk === 0x08 || (vk !== null && vk >= 0x25 && vk <= 0x28)) if (isSuggestionChord) { return } // 실제 키 입력은 화면을 바꾼다 — 이전 UIA 응답은 무효다. this._inputRevision += 1 this._registerInput(true) const bucket = this._bucket() // 한글·일본어 IME 가 켜져 있으면 Windows 는 글자 키를 VK_PROCESSKEY 로 넘기고, uiohook 은 그것을 // 변환표에 없는 키코드로 보낸다 — 그대로 'other' 로 두면 한글 타이핑 전체가 "타이핑 아님" 이 되어 // 제안이 영영 뜨지 않았다(2026-10-03 실측: 글자 키가 전부 key=other). 수정자 없이 눌린 미지의 // 키는 IME 조합 키로 본다. 실제 텍스트 변화(editedSinceFocus)가 함께 있어야 제안이 열린다. const keyClass = vk === null ? this._modifiers.ctrl || this._modifiers.alt || this._modifiers.meta ? 'shortcut' : 'ime' : classifyKeyStroke(vk, this._modifiers) if (keyClass === 'shortcut') bucket.shortcuts += 1 else bucket.keystrokes += 1 if (keyClass === 'backspace') bucket.backspaces += 1 this._lastKeyAt = Date.now() this._lastKeyClass = keyClass if (TYPING_KEY_CLASSES.has(keyClass)) { this._lastTypedAt = this._lastKeyAt this._typedInCurrentFocus = true this._lastTypedHwnd = this._foreground.hwnd } else if (keyClass === 'shortcut') { this._typedInCurrentFocus = false } if (event.keycode === 112 || vk === 0x15) { this._imeComposing = false } else if (keyClass === 'ime' || keyClass === 'letter') { this._imeComposing = true } else if (keyClass !== 'modifier') { this._imeComposing = false } // 진단: 키 값이 아니라 종류·수정자만 남긴다 (typed 판정이 왜 틀리는지 로그로 보이게) this._lastKeyDiag = `${keyClass}${vk === null ? `?${event.keycode}` : ''}${this._modifiers.ctrl ? '+C' : ''}${this._modifiers.alt ? '+A' : ''}${this._modifiers.meta ? '+M' : ''}` // 터미널·Vim·개발 표면에서는 키스트로크 버퍼를 추적해 줄 끝 공백 손실(Windows Terminal)이나 // 캔버스 터미널(len=0)에서도 한영 자동 전환과 Vim 모드가 동작하게 한다. // 주의: 키다운 훅 안에서 대상 창 IME 에 동기 WM_IME_CONTROL(isForegroundKoreanIme)을 보내면 // TSF/Cicero 조합 상태가 깨져 한글이 한 글자씩 씹히므로 훅 안에서는 절대 호출하지 않는다. 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, now: this._lastKeyAt }) this._scheduleTextSnapshot(keyClass) } private _handleKeyUp(event: UiohookKeyboardEvent): void { this._syncModifiers(event) } private _handleMouseDown(event: UiohookMouseEvent): void { this._inputRevision += 1 this._registerInput(false) const now = Date.now() const position = { x: event.x, y: event.y } const button = Number(event.button) const isDoubleClick = now - this._lastClickAt < 400 && this._lastClickButton === button && this._lastClickPos !== null && manhattanDistance(this._lastClickPos, position) < 6 const bucket = this._bucket() if (isDoubleClick) bucket.doubleClicks += 1 else bucket.clicks += 1 this._lastClickAt = now this._lastClickButton = button this._lastClickPos = position // 클릭은 다른 칸으로 옮겨 갔을 수 있다 — 다음 스냅샷의 텍스트를 새 기준으로 삼는다. this._rebaseFocusText = true this._typedInCurrentFocus = false this._imeComposing = false this._terminalTracker.onPointerOrFocusChange(this._foreground.hwnd) } private _handleMouseUp(event: UiohookMouseEvent): void { this._inputRevision += 1 this._lastMouse = { x: event.x, y: event.y } if (!this._suggestionPresentationActive) return if (this._presentationValidationTimer) clearTimeout(this._presentationValidationTimer) this._presentationValidationTimer = setTimeout(() => { this._presentationValidationTimer = null void this._captureTextSnapshot() }, 120) this._presentationValidationTimer.unref?.() } private _handleMouseMove(event: UiohookMouseEvent): void { const position = { x: event.x, y: event.y } if (this._lastMouse) { const distance = manhattanDistance(this._lastMouse, position) // 픽셀 단위 미세抖动 제거 (ActivityWatch 는 전량 누적하지만 노이즈가 크다) if (distance >= 2) { this._bucket().mouseDistancePx += distance this._registerInput(false) } } this._lastMouse = position } private _handleWheel(event: UiohookWheelEvent): void { this._inputRevision += 1 const bucket = this._bucket() bucket.scrollTicks += Math.max(1, Math.abs(Number(event.rotation) || 1)) this._registerInput(false) } /** * 활성 시간 누적 + 포그라운드 샘플링. * * ActivityWatch 처럼 "입력이 있으면 활성" 으로 판단한다. 연속 입력 간격이 * activeIdleTimeoutMs 를 넘으면 그 구간은 활성 시간에서 제외한다. */ private _registerInput(isKeyboard: boolean): void { const now = Date.now() const gap = this._lastEventAt === 0 ? 0 : now - this._lastEventAt if (gap > 0 && gap <= INPUT_TELEMETRY_DEFAULTS.activeIdleTimeoutMs) { this._bucket().activeMs += gap } else if (isKeyboard && this._lastActiveTickAt > 0) { this._bucket().activeMs += 250 } if (isKeyboard) this._lastActiveTickAt = now this._lastEventAt = now this._sampleForeground( now, isKeyboard && (gap >= 250 || this._rebaseFocusText || this._lastKeyClass === 'shortcut') ) } /** * 수정자 상태 — uiohook 이 모든 키 이벤트에 실어 보내는 플래그를 그대로 다. * (별도 상태 머신을 두면 키 반복/포커스 이동에서 어긋난다) */ private _syncModifiers(event: UiohookKeyboardEvent): void { this._modifiers = { ctrl: event.ctrlKey === true, alt: event.altKey === true, shift: event.shiftKey === true, meta: event.metaKey === true } } /** 포그라운드 창 정보 — 기본 1초 간격이되, 창 전환 뒤 첫 키 입력(250ms 이상 공백)에는 즉시 갱신한다 */ private _sampleForeground(now = Date.now(), forceImmediate = false): void { if ( !forceImmediate && now - this._foregroundSampledAt < INPUT_TELEMETRY_DEFAULTS.activeWindowSampleMinIntervalMs ) { return } this._foregroundSampledAt = now const info = getForegroundWindowInfo() if (info) { if (info.hwnd !== this._foreground.hwnd) { this._inputRevision += 1 this._typedInCurrentFocus = false this._imeComposing = false } this._foreground = { appName: info.appName || null, windowTitle: info.title || null, hwnd: info.hwnd } } } /** 이 시각의 (날짜, 시간, 앱) 버킷 */ private _bucket(now = new Date()): InputActivityBucket { const date = formatLocalDate(now) const hour = now.getHours() const appName = this._foreground.appName ?? '' const key = `${date}|${hour}|${appName}` let bucket = this._pending.get(key) if (!bucket) { bucket = emptyActivityBucket() this._pending.set(key, bucket) } return bucket } // ── 텍스트 학습 (UIA 스냅샷 diff) ────────────────────── /** * 최근 입력이 있었으면 주기적으로 스냅샷을 만든다 (백그라운드 관측). * * 입력이 끊긴 뒤에는 굳이 돌리지 않는다 — 그 시점은 디바운스/ settle 타이머가 * 이미 담당한다. */ private async _sampleWhileTyping(): Promise { if (!this._running || this._sampling) return const now = Date.now() if (this._lastKeyAt > 0 && now - this._lastKeyAt < 1000) { return } if ( !this._suggestionPresentationActive && (isTerminalOrDeveloperSurface(this._foreground.appName) || this._lastContext?.terminalMode === true || this._lastKeyAt === 0 || now - this._lastKeyAt > INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs || (this._lastContext !== null && this._lastContext.capturedAt >= this._lastKeyAt)) ) { return } this._sampling = true try { await this._captureTextSnapshot() } finally { this._sampling = false } } private _shouldRunFastTerminalBoundarySnapshot(): boolean { if (!isTerminalOrDeveloperSurface(this._foreground.appName)) return true const tracked = this._terminalTracker.currentPrefix() if (tracked.trim().length === 0) return true if (/[ㄱ-ㅎㅏ-ㅣA-Za-z]/u.test(tracked) || tracked.trimStart().startsWith(':')) { return true } return ( detectTypos(tracked, { includeTrailingToken: true, layoutOnly: true, terminalMode: true }).length > 0 ) } private _scheduleTextSnapshot(keyClass?: KeyStrokeClass): void { // 공백·문장부호 뒤의 한영 전환은 140ms 동안 다음 키가 없을 때만 시작한다. // 더 빠른 연속 입력 중에는 삭제 배치와 다음 키가 섞일 수 있으므로 유휴 스냅샷에서 묶어서 교정한다. 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 && this._shouldRunFastTerminalBoundarySnapshot() ? 140 : !isBoundaryKey && this._terminalTracker.vimMode === 'command' ? 160 : null if (quickDelay !== null) { 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 void this._captureTextSnapshot() }, INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs) this._textTimer.unref?.() // 제안 트리거 지연(기본 600ms)이 스냅샷 디바운스(380ms)보다 크다. 스냅샷이 // 디바운스에만 돌면 "타이핑을 멈춘 뒤 N ms" 조건이 결코 충족되지 않아 // 제안이 영원히 요청되지 않는다(실측: debounce 로그만 반복). 그래서 // 실제 글자/편집 입력이 있었고 제안이 켜져 있을 때만 트리거 지연을 넘긴 시점에 한 번 더 스냅샷을 돌린다. if (this._settleTimer) { 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?.() } } /** * 포커스 입력창 스냅샷을 읽어 (1) 타이핑 통계를 갱신하고 * (2) 제안 서비스에 컨텍스트 이벤트를 보낸다. */ private async _captureTextSnapshot(): Promise { if (!this._running) return null if (this._snapshotRequest) return this._snapshotRequest const request = this._readTextSnapshot() this._snapshotRequest = request try { return await request } finally { if (this._snapshotRequest === request) this._snapshotRequest = null } } private async _readTextSnapshot(): Promise { this._sampleForeground(Date.now(), true) const inputRevision = this._inputRevision const foregroundHwnd = this._foreground.hwnd const nativeInputTick = getLastNativeInputTick() const uia = getUiaContextService() const snapshot = withoutPlaceholderText(await uia.getSnapshot()) if (!this._running) return null this._sampleForeground(Date.now(), true) // CPU 부하/모델 로딩 중 UIA 응답이 늦어질 수 있다. 예전 텍스트를 최신 키 시각과 // 섞으면 자동 교정이 방금 친 글자를 지운다. 기준선·학습·제안 모두 갱신 전에 버린다. if ( inputRevision !== this._inputRevision || foregroundHwnd !== this._foreground.hwnd || nativeInputTick !== getLastNativeInputTick() || (snapshot.available && snapshot.capturedAt < Math.max(this._lastKeyAt, this._lastClickAt)) ) { logger.debug('입력 스냅샷 버림: UIA 조회 중 입력 또는 포커스 변경') return null } const now = Date.now() // 유휴 시간은 키보드 기준이다 (마우스 이동/클릭으로는 제안하지 않는다). const idleMs = this._lastKeyAt > 0 ? now - this._lastKeyAt : Number.MAX_SAFE_INTEGER const typedRecently = this._lastTypedAt > 0 && now - this._lastTypedAt <= SUGGESTION_DEFAULTS.recentTypingWindowMs const context: TypingContext = { prefix: '', fullText: '', caretOffset: null, anchor: null, anchorKind: null, isPassword: snapshot.isPassword, isEditable: snapshot.isEditable, isComposing: snapshot.isComposing, hasSelection: snapshot.hasSelection, available: snapshot.available, appName: this._foreground.appName, windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle, windowHandle: this._foreground.hwnd, idleMs, capturedAt: snapshot.capturedAt, inputRevision, nativeInputTick: process.platform === 'win32' ? nativeInputTick : undefined, editedSinceFocus: false, typedRecently } if ( !snapshot.isPassword && isTerminalOrDeveloperSurface(this._foreground.appName) && !this._terminalTracker.hasObservedImeForHwnd(this._foreground.hwnd) ) { this._terminalTracker.syncKoreanIme(isForegroundKoreanIme(this._foreground.hwnd)) } 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 context.caretOffset = snapshot.caretOffset context.fullText = snapshot.text // 케어렛 오프셋을 못 얻는 제공자가 많다(실측: Notepad — src=value, caret=null). // 그때는 "문서 마지막 = 커서 앞" 으로 가정해 tail 만 쓴다. 문서 전체를 접두로 // 쓰면 프롬프트가 실제 입력 위치와 무관해진다. const caretKnown = snapshot.caretOffset !== null // 문서형 컨트롤(터미널 버퍼 등)은 tail 이 직전 출력/이전 줄까지 포함한다. // "지금 치는 줄" 만 접두로 써야 한다 — 마지막 줄을 취한다. const documentLike = snapshot.textSource === 'text' const tail = snapshot.text.slice(-SUGGESTION_CONTEXT_MAX_CHARS) context.prefix = caretKnown ? textBeforeCaret(snapshot.text, snapshot.caretOffset) : documentLike ? lastLineOf(tail) : tail const documentBefore = snapshot.isPassword ? null : caretKnown ? snapshot.text.slice(0, snapshot.caretOffset ?? snapshot.text.length) : documentLike ? null : snapshot.text context.documentBefore = documentBefore === null ? null : documentBefore.slice(-DOCUMENT_BEFORE_MAX_CHARS) this._caretFallback = !caretKnown // 포커스 식별: 칸이 바뀌었거나 클릭이 있었으면 그 시점 텍스트를 기준선으로 저장한다 // (비밀번호는 비운다). 마우스로 칸에 들어오기만 하고 아무것도 안 쳤으면 기준선과 // 현재 텍스트가 같아 editedSinceFocus 가 false 로 남는다(실측: YouTube 검색창 클릭만 // 했는데 옛 검색어로 제안이 뜸). const focusKey = computeFocusKey(this._foreground.hwnd, snapshot.controlType ?? null, snapshot.controlName ?? null) const textForFocus = snapshot.isPassword ? '' : snapshot.text // 채팅창 등에서 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회). 그때마다 기준선을 다시 잡으면 // 방금 친 글이 "들어올 때부터 있던 글" 이 되어 제안이 영영 안 뜬다. 클릭 없이 키보드로 치다가 // 읽을 수 없는 요소를 거쳐 같은 창의 입력칸으로 돌아온 것이면 이미 편집한 칸으로 본다. const now = Date.now() const typedAfterFocus = this._typedInCurrentFocus && this._foreground.hwnd !== null && this._foreground.hwnd === this._lastTypedHwnd && this._lastTypedAt >= this._lastClickAt && now - this._lastTypedAt <= SUGGESTION_DEFAULTS.recentTypingWindowMs this._typedIntoFocus = !clearedByEnter && (typedAfterFocus || (!this._rebaseFocusText && this._foreground.hwnd !== null && this._foreground.hwnd === this._lastFocusHwnd && !this._prevSnapshotEditable && this._lastTypedAt > this._lastClickAt && now - this._lastTypedAt <= SUGGESTION_DEFAULTS.recentTypingWindowMs)) this._lastFocusKey = focusKey this._textAtFocus = textForFocus this._rebaseFocusText = false if (clearedByEnter) { this._lastTypedAt = 0 this._typedInCurrentFocus = false this._imeComposing = false context.typedRecently = false } } context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus if ( !context.isComposing && this._imeComposing && context.editedSinceFocus && /[가-힣ㄱ-ㅎㅏ-ㅣ]$/u.test(context.prefix) ) { context.isComposing = true } else if (context.isComposing && !/[가-힣ㄱ-ㅎㅏ-ㅣ]$/u.test(context.prefix)) { context.isComposing = false } // 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다. // 비밀번호·편집 불가 칸과 터미널(명령 기록)은 보지 않는다. 조합 중인 칸도 본다 — 한글은 보내기 직전 // 스냅샷이 거의 늘 조합 중이라, 빼면 보낸 글이 하나도 기억되지 않았다(실측 2026-10-17 에이전트 창 comp=true 연속). if (snapshot.isEditable && !snapshot.isPassword && !isTerminalApp(this._foreground.appName)) { this._recentWrites.observe( focusKey, snapshot.text, { windowHandle: this._foreground.hwnd, appName: this._foreground.appName, windowTitle: context.windowTitle }, Date.now() ) } // 케어렛을 모르면 "문서 끝 = 커서" 가정이 맞는지 마지막 편집 위치로 확인한다. // 문서 중간을 고쳤다면 접두(문서 끝)는 커서와 무관하다 — 제안·수락을 막는다. // 단, 방금 프로그램(오타 교정·제안 수락)이 커서 앞 텍스트를 바꾼 경우에는 끝 편집으로 본다. this._pruneExpectedInserts(now) const programmaticEdit = this._programmaticKeys > 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) } 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 this._recordReadabilityEvidence(snapshot) // 진단: 왜 제안이 안 뜨는지 로그만으로 판단할 수 있게 스냅샷 요약을 남긴다. logger.debug( `입력 스냅샷: avail=${snapshot.available} edit=${snapshot.isEditable} ` + `pw=${snapshot.isPassword} comp=${snapshot.isComposing} src=${snapshot.textSource} ` + `len=${snapshot.text.length} caret=${snapshot.caretOffset ?? -1} tail=${this._caretFallback} ` + `anchor=${context.anchor ? 'yes' : 'no'} app=${this._foreground.appName ?? '-'} ` + `reason=${snapshot.reason ?? '-'} key=${this._lastKeyDiag}` ) this._lastSnapshotSummary = { at: context.capturedAt, appName: this._foreground.appName, windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle, editable: snapshot.isEditable, isPassword: snapshot.isPassword, composing: snapshot.isComposing, textSource: snapshot.textSource, textLength: snapshot.text.length, caretFallback: this._caretFallback } this._lastContext = context if (this._settleTimer) { const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars const canTriggerSuggestion = configGet('suggestionEnabled') === true && context.available && context.isEditable && !context.isPassword && context.editedSinceFocus && context.typedRecently && normalizeRequestPrefix(context.prefix).length + (context.isComposing ? 1 : 0) >= minPrefixChars if (!canTriggerSuggestion) { clearTimeout(this._settleTimer) this._settleTimer = null } } this.emit('typed-context', context) // 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다). this._emitState() return context } private _recordReadabilityEvidence(snapshot: FocusSnapshot): void { const appName = this._foreground.appName?.trim() if (!appName || snapshot.isPassword) return let evidence = this._appReadability.get(appName) if (!evidence) { if (this._appReadability.size >= MAX_READABILITY_APPS) { const oldest = this._appReadability.keys().next().value if (oldest) this._appReadability.delete(oldest) } evidence = { appName, samples: 0, readable: 0, unreadable: 0, empty: 0 } this._appReadability.set(appName, evidence) } evidence.samples += 1 if (snapshot.isEditable && snapshot.textSource !== 'none' && snapshot.text.length > 0) { evidence.readable += 1 } else if (snapshot.isEditable && snapshot.textSource !== 'none' && snapshot.text.length === 0) { evidence.empty += 1 } else { evidence.unreadable += 1 } } private _applyTypedDelta(snapshot: FocusSnapshot): void { const key = `${snapshot.windowTitle ?? ''}|${snapshot.controlName ?? ''}|${snapshot.controlType ?? ''}` const previous = this._lastSnapshot const focusChanged = key !== this._lastSnapshotKey this._lastSnapshot = snapshot this._lastSnapshotKey = key // 필드가 바뀌면 이전 텍스트와 diff 할 수 없다 — 모아 둔 학습을 저장하고 기준선만 잡는다. if (focusChanged || !previous) { this.flushPendingLearning() return } const keepText = configGet('inputLearnTypedText') === true const delta = computeTypedDelta(previous.text, snapshot.text, { keepText }) if (delta.replaced) { // 붙여넣기 — 직접 친 글이 아니다. 그 앞까지 친 것만 저장하고 새로 모은다. this._flushPendingLearningAt(previous.text) return } if (delta.insertedChars === 0 && delta.insertedWords === 0) { // 지우기만 했다. 칸이 비었거나 기준선보다 짧아졌으면(메시지 전송 등) 비우기 직전까지가 친 글이다. const pending = this._pendingLearn if (pending && (snapshot.text.length === 0 || snapshot.text.length < pending.baseline.length)) { this._flushPendingLearningAt(previous.text) } else if (pending) { pending.latest = snapshot.text } return } const bucket = this._bucket() bucket.chars += delta.insertedChars bucket.words += delta.insertedWords bucket.sentences += delta.insertedSentences if (!delta.insertedText) return const typedText = this._withoutExpectedInsert(delta.insertedText) if (typedText !== delta.insertedText) { // 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친 // 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다. this._flushPendingLearningAt(previous.text) if (typedText) { this._learnText(typedText, { appName: this._foreground.appName, windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle, source: 'typed' }) } return } if (!this._pendingLearn) { this._pendingLearn = { baseline: previous.text, latest: snapshot.text, appName: this._foreground.appName, windowTitle: snapshot.windowTitle ?? this._foreground.windowTitle } } else { this._pendingLearn.latest = snapshot.text } const grown = snapshot.text.length - this._pendingLearn.baseline.length if (/[.!?…。?!\n]\s*$/u.test(snapshot.text) || grown >= LEARN_MAX_PENDING_CHARS) { this.flushPendingLearning() return } this._scheduleLearnFlush() } private _scheduleLearnFlush(): void { if (this._learnFlushTimer) clearTimeout(this._learnFlushTimer) this._learnFlushTimer = setTimeout(() => { this._learnFlushTimer = null this.flushPendingLearning() }, LEARN_IDLE_FLUSH_MS) } /** 모아 둔 타이핑 구간을 지금 학습한다 (멈춤·문장 끝·포커스 이동·종료 시). */ flushPendingLearning(): void { this._flushPendingLearningAt(null) } private _flushPendingLearningAt(latestOverride: string | null): void { const pending = this._pendingLearn this._discardPendingLearning() if (!pending || configGet('inputLearnTypedText') !== true) return // baseline → latest 를 한 번에 diff 한다 — 친 뒤 지운 오타·IME 가 바꾼 글자는 최종 결과만 남는다. const delta = computeTypedDelta(pending.baseline, latestOverride ?? pending.latest, { keepText: true }) if (delta.replaced || !delta.insertedText) return this._learnText(delta.insertedText, { appName: pending.appName, windowTitle: pending.windowTitle, source: 'typed' }) } private _discardPendingLearning(): void { if (this._learnFlushTimer) { clearTimeout(this._learnFlushTimer) this._learnFlushTimer = null } this._pendingLearn = null } /** * 곧 프로그램이 이 텍스트를 삽입한다 (제안 수락 · 받아쓰기 삽입). * * 삽입된 텍스트는 다음 스냅샷 diff 에 그대로 나타난다. 붙여넣기 판정 임계(200자)보다 * 짧으면 "타이핑" 으로 다시 학습돼, 삽입 경로가 이미 출처(source)를 붙여 기록한 문장이 * 두 번 쌓이고 제안이 자기 출력을 강화했다. 예고된 텍스트는 diff 학습에서 뺀다. * * 삽입이 실패했으면 돌려준 함수로 예고를 취소한다. */ expectProgrammaticInsert(text: string): () => void { const trimmed = text.trim() if (!trimmed) return () => undefined const now = Date.now() this._pruneExpectedInserts(now) this._expectedInsertSeq += 1 const id = this._expectedInsertSeq this._expectedInserts.push({ id, text: trimmed, expiresAt: now + PROGRAMMATIC_INSERT_TTL_MS }) return () => { this._expectedInserts = this._expectedInserts.filter((entry) => entry.id !== id) } } private _pruneExpectedInserts(now: number): void { if (this._expectedInserts.length === 0) return this._expectedInserts = this._expectedInserts.filter((entry) => entry.expiresAt > now) } /** * diff 로 얻은 삽입 텍스트에서 예고된 프로그램 삽입을 뺀 "실제 타이핑" 부분. * * - 삽입 구간이 예고 텍스트를 품으면 그 부분만 빼고 나머지(앞뒤로 직접 친 글)는 남긴다. * - diff 경계가 반복 글자에서 한 칸 밀려 회전된 형태로 잡힌 경우도 같은 텍스트로 본다. * - 삽입 구간이 예고 텍스트의 앞부분이면(키보드 방식으로 치는 도중 잡힌 스냅샷) 전부 * 프로그램 삽입이고, 남은 뒷부분을 계속 기다린다. */ private _withoutExpectedInsert(inserted: string): string { this._pruneExpectedInserts(Date.now()) const trimmed = inserted.trim() if (!trimmed) return inserted for (let i = 0; i < this._expectedInserts.length; i += 1) { const expected = this._expectedInserts[i] const index = inserted.indexOf(expected.text) if (index >= 0) { this._expectedInserts.splice(i, 1) return `${inserted.slice(0, index)} ${inserted.slice(index + expected.text.length)}`.trim() } if (trimmed.length === expected.text.length && `${trimmed}${trimmed}`.includes(expected.text)) { this._expectedInserts.splice(i, 1) return '' } if (expected.text.startsWith(trimmed)) { const remainder = expected.text.slice(trimmed.length).trim() if (remainder) expected.text = remainder else this._expectedInserts.splice(i, 1) return '' } } return inserted } /** * 외부(음성 전사 등)에서 들어온 텍스트를 코퍼스에 넣는다. * * 음성 전사는 이미 사용자가 말한 문장이므로 제안 품질에 가장 강한 신호다. * 학습 동의(`inputLearnTypedText`)가 없으면 아무것도 저장하지 않는다. */ recordExternalText( text: string, meta: { appName?: string | null; windowTitle?: string | null; source: PhraseSource } ): void { if (configGet('inputLearnTypedText') !== true) return this._learnText(text, { appName: meta.appName ?? null, windowTitle: meta.windowTitle ?? null, source: meta.source }) } private _learnText( raw: string, meta: { appName: string | null; windowTitle: string | null; source: PhraseSource } ): void { // 학습 제외 앱은 출처와 무관하다 — 터미널에서 수락한 제안(개발 지시)도 코퍼스에 넣지 않는다. if (!shouldLearnFromApp(meta.appName)) return const text = sanitizeSample( raw .split(/\r?\n/u) .map(stripTrailingJamo) .filter((line) => isLearnablePhrase(line) && !isUrlLike(line)) .join('\n') ) if (!text) return // 직접 친 글만 표본 규칙을 본다 — 음성·수락 문장은 이미 문장 단위다. const typed = meta.source === 'typed' if (typed && !isLearnableTypedText(text)) return try { const db = getDatabase() const now = Date.now() const wordCount = countWords(text) const charCount = text.length db.insert(typingSamples) .values({ id: crypto.randomUUID(), text: text.slice(0, MAX_SAMPLE_CHARS), wordCount, charCount, appName: meta.appName, windowTitle: meta.windowTitle, source: meta.source, 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 }) const phrases = extractPhrases(text).filter( (phrase) => isLearnablePhrase(phrase) && (!typed || isLearnableTypedText(phrase)) ) for (const phrase of phrases) { db.insert(personalPhrases) .values({ id: crypto.randomUUID(), phrase, count: 1, source: meta.source, lastUsedAt: now, createdAt: now, appName: meta.appName }) .onConflictDoUpdate({ target: personalPhrases.phrase, set: { count: sql`${personalPhrases.count} + 1`, lastUsedAt: now, appName: meta.appName } }) .run() } } catch (error) { logger.warn( `텍스트 학습 저장 실패: ${error instanceof Error ? error.message : String(error)}` ) } } // ─ 영속화 ───────────────────────────────────────────── /** 대기 중인 버킷을 DB로 확정한다 (5초 heartbeat). */ flushNow(): void { this._flush() } private _flush(): void { if (this._pending.size === 0) return if (!this._isTelemetryCollectionEnabled()) { this._pending.clear() return } const entries = [...this._pending.entries()] this._pending.clear() const now = Date.now() try { const db = getDatabase() for (const [key, bucket] of entries) { const [date, hourRaw, appName] = key.split('|') const hour = Number(hourRaw) if (!date || Number.isNaN(hour)) continue mergeActivityBucket(this._sessionTotals, bucket) db.insert(inputActivity) .values({ id: crypto.randomUUID(), date, hour, appName: appName ?? '', ...bucket, updatedAt: now }) .onConflictDoUpdate({ target: [inputActivity.date, inputActivity.hour, inputActivity.appName], set: { keystrokes: sql`${inputActivity.keystrokes} + ${bucket.keystrokes}`, shortcuts: sql`${inputActivity.shortcuts} + ${bucket.shortcuts}`, backspaces: sql`${inputActivity.backspaces} + ${bucket.backspaces}`, clicks: sql`${inputActivity.clicks} + ${bucket.clicks}`, doubleClicks: sql`${inputActivity.doubleClicks} + ${bucket.doubleClicks}`, scrollTicks: sql`${inputActivity.scrollTicks} + ${bucket.scrollTicks}`, mouseDistancePx: sql`${inputActivity.mouseDistancePx} + ${bucket.mouseDistancePx}`, chars: sql`${inputActivity.chars} + ${bucket.chars}`, words: sql`${inputActivity.words} + ${bucket.words}`, sentences: sql`${inputActivity.sentences} + ${bucket.sentences}`, activeMs: sql`${inputActivity.activeMs} + ${bucket.activeMs}`, updatedAt: now } }) .run() } this.emit('activity', { totals: { ...this._sessionTotals }, appName: this._foreground.appName }) } catch (error) { logger.warn( `입력 텔레메트리 저장 실패(다음 주기에 재시도): ${ error instanceof Error ? error.message : String(error) }` ) // 저장 실패 시 버킷을 되돌려 유실을 막는다. for (const [key, bucket] of entries) { const existing = this._pending.get(key) if (existing) mergeActivityBucket(existing, bucket) else this._pending.set(key, bucket) } } } // ── 조회 / 관리 ──────────────────────────────────────── getState(): InputTelemetryState { const uia = getUiaContextService() const currentApp = this._foreground.appName const excludedApps = [...configGet('inputExcludedApps')] const evidence = currentApp ? this._appReadability.get(currentApp) : undefined return { enabled: configGet('inputTelemetryEnabled') === true, paused: configGet('inputTelemetryPaused') === true, running: this._running, learnTypedText: configGet('inputLearnTypedText') === true, excludedApps, appName: currentApp, windowTitle: this._foreground.windowTitle, bridgeReason: uia.lastReason, bridgeAvailable: uia.isAvailable(), lastSnapshotAt: uia.lastSuccessAt, lastSnapshot: this._lastSnapshotSummary, exclusionRecommendation: evidence && !excludedApps.some((app) => app.toLowerCase() === currentApp?.toLowerCase()) ? recommendAppExclusion(evidence) : null } } /** 최근 N일 인사이트 (일별/시간대별/앱별). */ getSummary(days = 7): InputInsightsSummary { const safeDays = Math.max(1, Math.min(days, 365)) const since = new Date() since.setHours(0, 0, 0, 0) since.setDate(since.getDate() - (safeDays - 1)) const sinceDate = formatLocalDate(since) const totals = emptyActivityBucket() const daily = new Map() const hourly = new Map() const apps = new Map() try { const db = getDatabase() const rows = db .select() .from(inputActivity) .where(gte(inputActivity.date, sinceDate)) .all() for (const row of rows) { mergeActivityBucket(totals, { keystrokes: row.keystrokes, shortcuts: row.shortcuts, backspaces: row.backspaces, clicks: row.clicks, doubleClicks: row.doubleClicks, scrollTicks: row.scrollTicks, mouseDistancePx: row.mouseDistancePx, chars: row.chars, words: row.words, sentences: row.sentences, activeMs: row.activeMs }) const day = daily.get(row.date) ?? { date: row.date, keystrokes: 0, clicks: 0, words: 0, sentences: 0, mouseDistancePx: 0, activeMs: 0 } day.keystrokes += row.keystrokes day.clicks += row.clicks day.words += row.words day.sentences += row.sentences day.mouseDistancePx += row.mouseDistancePx day.activeMs += row.activeMs daily.set(row.date, day) const hour = hourly.get(row.hour) ?? { hour: row.hour, keystrokes: 0, clicks: 0, chars: 0, backspaces: 0, activeMs: 0 } hour.keystrokes += row.keystrokes hour.clicks += row.clicks hour.chars += row.chars hour.backspaces += row.backspaces hour.activeMs += row.activeMs hourly.set(row.hour, hour) if (row.appName) { const app = apps.get(row.appName) ?? { appName: row.appName, keystrokes: 0, clicks: 0, activeMs: 0 } app.keystrokes += row.keystrokes app.clicks += row.clicks app.activeMs += row.activeMs apps.set(row.appName, app) } } // 24시간 전체 분포 (topHours 는 상위만 잘라 쓴다) const hourlyAll: InputHourlyStat[] = Array.from({ length: 24 }, (_, hour) => ({ hour, keystrokes: 0, clicks: 0, chars: 0, backspaces: 0, activeMs: 0 })) for (const stat of hourly.values()) { if (stat.hour >= 0 && stat.hour < 24) hourlyAll[stat.hour] = stat } const dailySorted = [...daily.values()].sort((a, b) => a.date.localeCompare(b.date)) const activeDays = dailySorted.length const peakDay = dailySorted.reduce( (best, day) => (!best || day.keystrokes > best.keystrokes ? day : best), null ) // 연속 기록 일수 (최장) let longestStreakDays = 0 let currentStreak = 0 let previousDate: string | null = null for (const day of dailySorted) { if (previousDate === null) { currentStreak = 1 } else { const prev = new Date(`${previousDate}T00:00:00`) const gapDays = Math.round( (new Date(`${day.date}T00:00:00`).getTime() - prev.getTime()) / 86400000 ) currentStreak = gapDays === 1 ? currentStreak + 1 : 1 } longestStreakDays = Math.max(longestStreakDays, currentStreak) previousDate = day.date } const suggestionTotals = db .select({ total: sql`count(*)`, accepted: sql`coalesce(sum(case when accepted then 1 else 0 end), 0)`, avgLatency: sql`avg(latency_ms)` }) .from(suggestionsTable) .where(gte(suggestionsTable.createdAt, Date.now() - safeDays * 86400000)) .get() const suggestionStats: InputInsightsSummary['suggestions'] = { total: Number(suggestionTotals?.total ?? 0), accepted: Number(suggestionTotals?.accepted ?? 0), acceptRate: Number(suggestionTotals?.total ?? 0) > 0 ? Number(suggestionTotals?.accepted ?? 0) / Number(suggestionTotals?.total ?? 1) : 0, avgLatencyMs: suggestionTotals?.avgLatency === null || suggestionTotals?.avgLatency === undefined ? null : Math.round(Number(suggestionTotals.avgLatency)) } const suggestionRows = db .select({ appName: suggestionsTable.appName, accepted: suggestionsTable.accepted, latencyMs: suggestionsTable.latencyMs }) .from(suggestionsTable) .where(gte(suggestionsTable.createdAt, Date.now() - safeDays * 86400000)) .all() const suggestionAppsByName = new Map< string, { total: number; accepted: number; latencyTotal: number; latencyCount: number } >() for (const row of suggestionRows) { const appName = row.appName?.trim() if (!appName) continue const stat = suggestionAppsByName.get(appName) ?? { total: 0, accepted: 0, latencyTotal: 0, latencyCount: 0 } stat.total += 1 if (row.accepted) stat.accepted += 1 if (row.latencyMs !== null && row.latencyMs !== undefined) { stat.latencyTotal += row.latencyMs stat.latencyCount += 1 } suggestionAppsByName.set(appName, stat) } const suggestionApps: InputAppSuggestionStat[] = [...suggestionAppsByName.entries()] .map(([appName, stat]) => ({ appName, total: stat.total, accepted: stat.accepted, acceptRate: stat.total > 0 ? stat.accepted / stat.total : 0, avgLatencyMs: stat.latencyCount > 0 ? Math.round(stat.latencyTotal / stat.latencyCount) : null })) .sort((a, b) => b.total - a.total || b.acceptRate - a.acceptRate || a.appName.localeCompare(b.appName)) .slice(0, 12) const phraseCount = db .select({ value: sql`count(*)` }) .from(personalPhrases) .get() const sampleCount = db .select({ value: sql`count(*)` }) .from(typingSamples) .get() return { days: safeDays, totals, daily: dailySorted, topHours: [...hourly.values()].sort((a, b) => b.keystrokes - a.keystrokes).slice(0, 6), topApps: [...apps.values()].sort((a, b) => b.keystrokes - a.keystrokes).slice(0, 12), phraseCount: Number(phraseCount?.value ?? 0), sampleCount: Number(sampleCount?.value ?? 0), averages: summarizeActivity(totals, safeDays, getDisplayScaleFactor()), hourly: hourlyAll, activeDays, longestStreakDays, peakDay, suggestions: suggestionStats, friction: calculateFrictionInsight(totals.chars, totals.backspaces), flowWindows: rankFlowWindows(hourlyAll, activeDays), suggestionApps } } catch (error) { logger.warn( `입력 인사이트 조회 실패: ${error instanceof Error ? error.message : String(error)}` ) return { days: safeDays, totals, daily: [], topHours: [], topApps: [], phraseCount: 0, sampleCount: 0, averages: summarizeActivity(totals, safeDays), hourly: Array.from({ length: 24 }, (_, hour) => ({ hour, keystrokes: 0, clicks: 0, chars: 0, backspaces: 0, activeMs: 0 })), activeDays: 0, longestStreakDays: 0, peakDay: null, suggestions: { total: 0, accepted: 0, acceptRate: 0, avgLatencyMs: null }, friction: calculateFrictionInsight(0, 0), flowWindows: [], suggestionApps: [] } } } /** * 과거에 이 접두 꼬리 뒤에 실제로 이어 쓴 텍스트를 찾는다 (개인 기억). * * 자주 쓰는 문구 목록보다 강한 개인화 신호다: 사용자가 그 문맥에서 실제로 * 어떤 문장을 이어 썼는지가 그대로 들어간다. 임베딩 검색이 아니라 로컬 * 문자열 관계 조회이므로 추가 의존성이나 네트워크가 없다. * * 학습 동의(inputLearnTypedText)가 없으면 저장된 표본이 없어 자연히 빈 배열이다. */ 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(where) .orderBy(desc(typingSamples.createdAt)) .limit(40) .all() const out: string[] = [] for (const row of rows) { const index = row.text.indexOf(tail) if (index < 0) continue const continuation = row.text .slice(index + tail.length) .replace(/\s+/gu, ' ') .trim() // 바로 뒤가 비어 있으면(문장이 그대로 끝) 참고 가치가 없다 if (continuation.length < 3) continue const clipped = continuation.slice(0, 60) if (out.some((existing) => existing === clipped)) continue out.push(clipped) if (out.length >= limit) break } return out } catch (error) { logger.warn( `과거 이어쓰기 조회 실패: ${error instanceof Error ? error.message : String(error)}` ) return [] } } getPrivacyReceipt(): InputPrivacyReceipt { try { const db = getDatabase() const countRows = (table: typeof inputActivity | typeof typingSamples | typeof personalPhrases | typeof suggestionsTable): number => Number(db.select({ value: sql`count(*)` }).from(table).get()?.value ?? 0) const counts = { activityBuckets: countRows(inputActivity), typingSamples: countRows(typingSamples), personalPhrases: countRows(personalPhrases), suggestions: countRows(suggestionsTable) } return { localOnly: true, rawKeyContentStored: false, retention: { activityDays: INPUT_TELEMETRY_DEFAULTS.retentionDays, typingSamplesDays: INPUT_TELEMETRY_DEFAULTS.retentionDays, suggestionDays: INPUT_TELEMETRY_DEFAULTS.retentionDays, personalPhrases: 'until-deleted' }, counts } } catch (error) { logger.warn(`입력 개인정보 영수증 조회 실패: ${error instanceof Error ? error.message : String(error)}`) throw error } } listPhrases(limit = 100): PersonalPhrase[] { try { const db = getDatabase() const rows = db .select() .from(personalPhrases) .orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt)) .limit(Math.max(1, Math.min(limit, 500))) .all() return rows.map((row) => ({ id: row.id, phrase: row.phrase, count: row.count, source: row.source, appName: row.appName, lastUsedAt: row.lastUsedAt, createdAt: row.createdAt })) } catch (error) { logger.warn(`개인 문구 조회 실패: ${error instanceof Error ? error.message : String(error)}`) return [] } } /** * 학습 문구 삭제. * * 그래프 엣지(phrase_edges)는 문장 텍스트를 외래 키 없이 들고 있다 — 문구 행만 지우면 * follows 엣지를 따라 지운 문장이 제안 프롬프트와 그래프 통계에 계속 나온다. * 문구와 그 문장을 가리키는 엣지를 한 트랜잭션에서 함께 지운다. */ deletePhrase(id: string): boolean { try { const db = getDatabase() return db.transaction(() => { const row = db .select({ phrase: personalPhrases.phrase }) .from(personalPhrases) .where(eq(personalPhrases.id, id)) .get() const result = db.delete(personalPhrases).where(eq(personalPhrases.id, id)).run() 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) { logger.warn(`개인 문구 제 실패: ${error instanceof Error ? error.message : String(error)}`) return false } } /** 수집된 모든 입력 데이터 삭제 (동의 철회/초기화). */ clearAll(): void { try { const db = getDatabase() db.delete(inputActivity).run() db.delete(typingSamples).run() db.delete(personalPhrases).run() db.delete(suggestionsTable).run() getPersonalGraphService().clearAll() getPersonalNgramIndex().invalidate() this._pending.clear() this._appReadability.clear() this._sessionTotals = emptyActivityBucket() this._lastSnapshot = null this._lastSnapshotKey = '' this._discardPendingLearning() logger.info('입력 텔레메트리 데이터 전체 삭제') } catch (error) { logger.warn(`입력 데이터 삭제 실패: ${error instanceof Error ? error.message : String(error)}`) throw error } } /** * 지금의 학습 규칙(제외 앱·문장 판정)에 맞지 않는 기존 코퍼스를 걷어낸다. * * 규칙이 생기기 전에 쌓인 터미널 상태줄·개발 지시가 그래프를 개발 쪽으로 끌고 * 있었다 — 규칙을 과거 데이터에도 똑같이 적용해 그래프를 되돌린다. */ private _pruneUnlearnableCorpus(): void { // 학습과 같은 규칙(출처 무관) — 규칙 이전에 쌓인 제외 앱의 수락 제안도 걷어낸다. const excluded = (_source: string, appName: string | null): boolean => !shouldLearnFromApp(appName) try { const db = getDatabase() const phraseIds = db .select({ id: personalPhrases.id, phrase: personalPhrases.phrase, source: personalPhrases.source, appName: personalPhrases.appName }) .from(personalPhrases) .all() .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 .select({ id: typingSamples.id, text: typingSamples.text, source: typingSamples.source, appName: typingSamples.appName }) .from(typingSamples) .all() .filter( (row) => excluded(row.source, row.appName) || !row.text.split(/\r?\n/u).some((line) => isLearnablePhrase(line)) || // 문장 단위 학습 이전에 스냅샷마다 저장된 조각·주소·깨진 이모지도 같은 규칙으로 걷어낸다. (row.source === 'typed' && !isLearnableTypedText(row.text)) ) .map((row) => row.id) for (let i = 0; i < phraseIds.length; i += 200) { db.delete(personalPhrases).where(inArray(personalPhrases.id, phraseIds.slice(i, i + 200))).run() } 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) OR to_phrase NOT IN (SELECT phrase FROM personal_phrases)` ) if (phraseIds.length > 0 || sampleIds.length > 0) { logger.info(`학습 규칙에 맞지 않는 코퍼스 정리: 문구 ${phraseIds.length}개, 표본 ${sampleIds.length}개`) } } catch (error) { logger.warn(`코퍼스 정리 실패: ${error instanceof Error ? error.message : String(error)}`) } } /** 보존 기간 초과 데이터 정리 (ActivityWatch 와 동일한 로컬 보존 정책). */ private _pruneOldData(now = Date.now()): void { if (now - this._prunedAt < RETENTION_PRUNE_INTERVAL_MS) return this._prunedAt = now this._pruneUnlearnableCorpus() // 그래프 유지보수도 같은 주기에 돌린다 (용어 공유 엣지 백필). getPersonalGraphService().runMaintenance() const cutoff = now - INPUT_TELEMETRY_DEFAULTS.retentionDays * 24 * 60 * 60 * 1000 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}일 초과)`) } catch (error) { logger.warn(`보존 정리 실패: ${error instanceof Error ? error.message : String(error)}`) } } /** 일시정지 토글 (동의는 유지). */ setPaused(paused: boolean): void { configSet('inputTelemetryPaused', paused) this.applyConfig() } /** 수집 동의 설정. 끄면 즉시 중지하고 수집분도 지운다. */ setEnabled(enabled: boolean): void { configSet('inputTelemetryEnabled', enabled) if (!enabled) { this.clearAll() configSet('inputLearnTypedText', false) } this.applyConfig() } private _emitState(): void { this.emit('state-changed', this.getState()) } } /** * 마지막 비어 있지 않은 줄을 돌려준다 (터미널/문서형 컨트롤용). * * 터미널 버퍼 전체를 프롬프트로 넘기면 모델이 과거 출력을 이어 쓰려 한다. */ function lastLineOf(text: string): string { const lines = text.split(/\r?\n/u) for (let i = lines.length - 1; i >= 0; i -= 1) { const line = lines[i].trim() if (line.length > 0) return line.slice(-SUGGESTION_CONTEXT_MAX_CHARS) } return text.slice(-SUGGESTION_CONTEXT_MAX_CHARS) } /** * 포커스된 컨트롤 식별 키 — 창(hwnd) + 컨트롤 종류 + 컨트롤 이름. * * 위치·크기는 쓰지 않는다 — 채팅 입력창은 글이 늘면 자라고 움직여, 넣으면 같은 칸인데도 * 칠 때마다 "새 칸" 으로 오인돼 기준선이 리셋되고 제안이 거의 막혔다(실측: Agent * Switchboard 에서 not-typing 반복). 같은 창 안의 칸 이동은 클릭 재기준으로 잡는다. */ function computeFocusKey(hwnd: number | null, controlType: string | null, controlName: string | null): string { return `${hwnd ?? ''}|${controlType ?? ''}|${controlName ?? ''}` } function formatLocalDate(date: Date): string { const year = date.getFullYear() const month = String(date.getMonth() + 1).padStart(2, '0') const day = String(date.getDate()).padStart(2, '0') return `${year}-${month}-${day}` } const MIN_TYPED_SAMPLE_CHARS = 4 /** 주소·경로·쿼리 문자열 한 줄은 문체 표본이 아니다. ?·# 는 보지 않는다 — "언제쯤일까?" 는 문장이다. */ function isUrlLike(line: string): boolean { const trimmed = line.trim() if (/^(https?:\/\/|www\.)\S*$/iu.test(trimmed)) return true return !/\s/u.test(trimmed) && /[/=&]/u.test(trimmed) } /** 한글 호환 자모(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 { 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자 미만은 버린다. */ function sanitizeSample(raw: string): string { let stripped = '' for (const char of raw) { const code = char.codePointAt(0) ?? 0 // 제어문자(개행/탭 포함)는 공백으로 바다 — 학습 표본에 제어문자를 남기지 않는다. if (isBrokenCodePoint(code)) continue stripped += code < 0x20 || code === 0x7f ? ' ' : char } const cleaned = stripped.replace(/\s+/gu, ' ').trim() if (cleaned.length < 2) return '' return cleaned.slice(0, MAX_SAMPLE_CHARS) } function getDisplayScaleFactor(): number { try { return screen.getPrimaryDisplay().scaleFactor || 1 } catch { return 1 } } let instance: InputTelemetryService | null = null export function getInputTelemetryService(): InputTelemetryService { if (!instance) instance = new InputTelemetryService() return instance } export function resetInputTelemetryServiceForTests(): void { instance?.dispose() instance = null } export { formatLocalDate, sanitizeSample } export type { InputTelemetryState }