From a3ac44da2bd1d73f569a0b02cdfa5b4e73a4f4a6 Mon Sep 17 00:00:00 2001 From: Yun Chan Date: Tue, 27 Oct 2026 10:48:07 +0900 Subject: [PATCH] feat(desktop): built-in Han/Eng layout auto-switching, terminal/Vim support, and Unicode input --- .gitignore | 4 + CHANGELOG.md | 55 + apps/desktop/sidecar/uia_bridge.py | 26 +- apps/desktop/src/main/bootstrap.ts | 28 +- .../src/main/ipc/app-update-handlers.ts | 58 ++ apps/desktop/src/main/ipc/index.ts | 2 + .../src/main/ipc/suggestion-handlers.ts | 2 + .../main/services/InputTelemetryService.ts | 334 +++++- .../src/main/services/LocalLLMService.ts | 12 + .../src/main/services/SuggestionService.ts | 254 ++++- .../src/main/services/TextInsertService.ts | 11 +- .../main/services/TypoCorrectionService.ts | 98 +- .../src/main/services/UiaContextService.ts | 3 +- .../src/main/services/UpdateService.ts | 83 +- .../services/keybinding-accelerator-policy.ts | 1 + apps/desktop/src/main/services/llm-prompts.ts | 3 +- .../src/main/services/modifier-state.ts | 27 +- .../services/suggestion/PersonalNgramIndex.ts | 71 ++ .../services/text-insert/nut-keyboard-port.ts | 4 + .../src/main/utils/win32-foreground.ts | 120 ++- .../desktop/src/main/utils/win32-key-state.ts | 28 +- .../src/main/utils/win32-unicode-input.ts | 118 +++ .../desktop/src/main/windows/WindowManager.ts | 13 +- .../windows/suggestion-overlay-geometry.ts | 4 +- .../windows/suggestion-overlay-presenter.ts | 13 +- apps/desktop/src/preload/index.ts | 10 + .../src/renderer/components/SettingsModal.tsx | 3 + .../src/renderer/components/TitleBar.tsx | 4 + .../input-insights/InputConsentPanel.tsx | 4 +- .../components/settings/UpdateSection.tsx | 89 ++ .../settings/update-status-model.ts | 75 ++ .../renderer/components/shell/UpdateChip.tsx | 54 + .../src/renderer/hooks/useAppUpdateStatus.ts | 48 + .../popups/suggestion-overlay/script.js | 13 +- .../popups/suggestion-overlay/style.css | 9 + .../tests/eval/analysis/hybrid_eval.py | 78 ++ .../desktop/tests/eval/analysis/ngram_eval.py | 63 ++ .../tests/eval/analysis/simulate_gating.py | 74 ++ .../desktop/tests/eval/replay-metrics.test.ts | 46 + apps/desktop/tests/eval/replay-metrics.ts | 166 +++ .../eval/suggestion-latency.eval.test.ts | 125 +++ .../tests/eval/suggestion-replay.eval.test.ts | 287 ++++++ .../services/TypoCorrectionService.test.ts | 143 ++- .../main/services/input-flow-services.test.ts | 21 + .../main/services/input-intelligence.test.ts | 7 +- .../input-telemetry-redteam-r1-1.test.ts | 93 +- .../services/keybinding-redteam-r2-16.test.ts | 1 + .../main/services/modifier-state.test.ts | 23 +- .../services/suggestion-accept-hold.test.ts | 172 ++++ .../services/suggestion-accept-word.test.ts | 176 ++++ .../suggestion-app-scoped-learning.test.ts | 153 +++ .../services/suggestion-copy-guard.test.ts | 147 +++ .../suggestion-instant-personal.test.ts | 183 ++++ .../suggestion-no-suggestion-notice.test.ts | 165 +++ .../main/services/suggestion-presence.test.ts | 2 +- .../services/suggestion-redteam-r1-1.test.ts | 2 +- .../services/suggestion-redteam-r2-3.test.ts | 2 +- .../services/suggestion-redteam-r3-1.test.ts | 2 +- .../suggestion-typo-correction.test.ts | 4 +- .../services/update-service-status.test.ts | 122 +++ .../renderer/update-status-model.test.ts | 58 ++ ...2026-10-24-suggestion-accuracy-research.md | 135 +++ docs/map/00-index.md | 6 +- docs/map/03-shared-packages.md | 1 + docs/map/04-desktop-app.md | 7 +- docs/map/10-feature-catalog.md | 10 +- docs/map/11-gap-backlog.md | 4 +- packages/core/__tests__/address-input.test.ts | 34 + .../input-suggestion-redteam-r3-1.test.ts | 4 +- .../core/__tests__/personal-ngram.test.ts | 54 + .../__tests__/suggestion-confidence.test.ts | 56 + .../__tests__/suggestion-continuation.test.ts | 12 + .../core/__tests__/terminal-prompt.test.ts | 293 +++++- .../core/__tests__/typo-correction.test.ts | 248 +++++ packages/core/package.json | 8 + packages/core/src/araso-layout.ts | 970 ++++++++++++++++++ packages/core/src/errors.ts | 2 + packages/core/src/input-intelligence.ts | 104 +- packages/core/src/ipc-channels.ts | 10 + packages/core/src/keybinding.ts | 11 + packages/core/src/personal-ngram.ts | 192 ++++ packages/core/src/suggestion-confidence.ts | 72 ++ packages/core/src/suggestion-text.ts | 16 +- packages/core/src/terminal-prompt.ts | 885 +++++++++++++++- packages/core/src/types.ts | 26 + packages/core/src/typo-correction.ts | 950 ++++++++++++++++- packages/i18n/src/locales/de.json | 27 +- packages/i18n/src/locales/en.json | 31 +- packages/i18n/src/locales/es.json | 27 +- packages/i18n/src/locales/fr.json | 27 +- packages/i18n/src/locales/ja.json | 27 +- packages/i18n/src/locales/ko.json | 31 +- packages/i18n/src/locales/pt.json | 27 +- packages/i18n/src/locales/ru.json | 27 +- packages/i18n/src/locales/th.json | 27 +- packages/i18n/src/locales/vi.json | 27 +- packages/i18n/src/locales/zh-TW.json | 27 +- packages/i18n/src/locales/zh.json | 27 +- release/update-policy.json | 2 +- site/src/i18n/locales/de.ts | 2 +- site/src/i18n/locales/en.ts | 8 +- site/src/i18n/locales/es.ts | 2 +- site/src/i18n/locales/fr.ts | 2 +- site/src/i18n/locales/ja.ts | 2 +- site/src/i18n/locales/ko.ts | 12 +- site/src/i18n/locales/pt.ts | 2 +- site/src/i18n/locales/ru.ts | 2 +- site/src/i18n/locales/vi.ts | 2 +- site/src/i18n/locales/zh.ts | 2 +- 109 files changed, 8234 insertions(+), 242 deletions(-) create mode 100644 apps/desktop/src/main/ipc/app-update-handlers.ts create mode 100644 apps/desktop/src/main/services/suggestion/PersonalNgramIndex.ts create mode 100644 apps/desktop/src/main/utils/win32-unicode-input.ts create mode 100644 apps/desktop/src/renderer/components/settings/UpdateSection.tsx create mode 100644 apps/desktop/src/renderer/components/settings/update-status-model.ts create mode 100644 apps/desktop/src/renderer/components/shell/UpdateChip.tsx create mode 100644 apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts create mode 100644 apps/desktop/tests/eval/analysis/hybrid_eval.py create mode 100644 apps/desktop/tests/eval/analysis/ngram_eval.py create mode 100644 apps/desktop/tests/eval/analysis/simulate_gating.py create mode 100644 apps/desktop/tests/eval/replay-metrics.test.ts create mode 100644 apps/desktop/tests/eval/replay-metrics.ts create mode 100644 apps/desktop/tests/eval/suggestion-latency.eval.test.ts create mode 100644 apps/desktop/tests/eval/suggestion-replay.eval.test.ts create mode 100644 apps/desktop/tests/main/services/suggestion-accept-hold.test.ts create mode 100644 apps/desktop/tests/main/services/suggestion-accept-word.test.ts create mode 100644 apps/desktop/tests/main/services/suggestion-app-scoped-learning.test.ts create mode 100644 apps/desktop/tests/main/services/suggestion-copy-guard.test.ts create mode 100644 apps/desktop/tests/main/services/suggestion-instant-personal.test.ts create mode 100644 apps/desktop/tests/main/services/suggestion-no-suggestion-notice.test.ts create mode 100644 apps/desktop/tests/main/services/update-service-status.test.ts create mode 100644 apps/desktop/tests/renderer/update-status-model.test.ts create mode 100644 docs/evidence/2026-10-24-suggestion-accuracy-research.md create mode 100644 packages/core/__tests__/address-input.test.ts create mode 100644 packages/core/__tests__/personal-ngram.test.ts create mode 100644 packages/core/__tests__/suggestion-confidence.test.ts create mode 100644 packages/core/src/araso-layout.ts create mode 100644 packages/core/src/personal-ngram.ts create mode 100644 packages/core/src/suggestion-confidence.ts diff --git a/.gitignore b/.gitignore index 3b8bf18..5d2919a 100644 --- a/.gitignore +++ b/.gitignore @@ -131,3 +131,7 @@ D3RO-Voice-Setup-*.exe # site 빌드 중간 산출물(서버 렌더링 번들) site/dist-ssr/ + +# Local reference clones +/araso/ +/.codex/ diff --git a/CHANGELOG.md b/CHANGELOG.md index efb74a5..70e9b8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Additional Whisper model management UI - Plugin system for custom pipelines +## [1.11.0] - 2026-10-27 + +> Published from an annotated tag. Installer and update metadata are served by the +> canonical Forgejo feed; no binaries are committed to this repository. + +### Added +- **Built-in instant Korean/English keyboard layout auto-switching (한영 자판 자동 전환 기본 탑재).** + Words typed while the IME is in the wrong layout are converted in place as soon as you + press Space or pause — even when input telemetry collection and sentence suggestions + are turned off: + - English keys → Korean (`dkssudgktpdy` → `안녕하세요`, `rkatkgkqslek` → `감사합니다`). + - Korean jamo → English (`ㅗ디ㅣㅐ 재깅` → `hello world`, `내ㅡㄷ샤ㅡㄷ` → `sometime`, + `내ㅡㄷ유ㅐ요` → `somebody`, `ㅑㄹ ㅑ 쇼ㅔㄷ ㅗ디ㅣㅐ` → `if I type hello`). + - Mixed English/Acronym/CamelCase + Korean particles & compound nouns (`githubdp` → + `github에`, `ㅎ샤ㅗㅕㅠ에` → `github에`, `ㅠㅕㅎ가` → `bug가`, `PDFvkdlf` / `ㅖㅇㄹ파일` → + `PDF파일`, `Reactzjavhsjsxm` → `React컴포넌트`, `dhsmfdmsgoogledptj` → `오늘은google에서`, + `1:1ansdml` → `1:1문의`, batchim-aware 2-letter acronyms `TMdms` → `TM은` vs + `TMsms` → `쓰는`, single-letter + particle `ㄴ가` → `s가`, `ㄴ은` → `s은`). + - Lingering Shift on double consonants (`djEJs` → `어떤`, `qkRNjTdj` → `바꿨어`) and + sentence-context Hangul conversion (`Stay hungry, stay foolishsms wkqtmdml akfdlek.` + → `Stay hungry, stay foolish는 잡스의 말이다.`). +- **Terminal, Vim / Neovim, and xterm.js support (터미널·Vim·xterm.js 한영 전환 지원).** + - Converts wrong-layout shell commands (`퍄ㅡ ` → `vim `, `ㅜ퍄ㅡ ` → `nvim `, `ㅎ샤 ` → + `git `, `ㅣㄴ ` → `ls `, `채ㅜㄴㅅ ` → `const `) and Vim ex-commands (`:ㅈㅂ` → `:wq`, + `:ㅈㅂ!` → `:wq!`, `:ㅂ!` → `:q!`, `:ㅈ` → `:w`, `:ㅂ` → `:q`) across Windows Terminal, + PowerShell, cmd, Neovide, Kitedesk, WezTerm, Alacritty, and xterm.js terminals + (Agent Switchboard, VS Code, Cursor). + - Suppresses auto-correction in Vim Normal mode (`vimMode === 'normal'`) so motions + (`hjkl`, `dd`, `ciw`) are never altered, and tracks Korean IME conversion state on + Windows TSF (`IMC_GETCONVERSIONMODE`). +- **Word-by-word suggestion acceptance & instant personal n-gram candidate.** + - Press `Ctrl+Alt+Space` to insert only the first word of the active suggestion and + keep the remainder visible. + +### Changed +- **Direct Unicode typing (`SendInput` `KEYEVENTF_UNICODE`) instead of clipboard paste.** + Typo replacements and text insertion on Windows now type Unicode characters directly + without touching your `Win+V` clipboard history or colliding with background clipboard + locks (`ClipboardSvcGroup`). +- **No mid-word interruption while typing.** Boundary keys (Space, punctuation) trigger + layout conversion immediately (`25–40 ms`), while mid-word pauses wait `650 ms` so + compound words (`some` → `sometime` / `somebody`) are never split or swallowed. + +### Fixed +- **Characters are no longer dropped, duplicated, or preceded by phantom spaces during fast typing.** + - Synthetic `KEYEVENTF_UNICODE` key events (`keycode=0`) are ignored by the global input + hook, and programmatic key suppression only matches synthetic `Backspace`/`Space`/`Ctrl+V` + so physical letter keys pressed during async replacement are never swallowed. + - `commitComposition` (`Space` before `Backspace`) is sent only when the character before + the caret is a composed Hangul syllable (`[가-힣]`), never on a single compatibility + jamo (`ㅎ` in `ㅠㅕㅎ`, `ㄷ` in `내ㅡㄷ`, `ㅂ` in `:ㅈㅂ`). + - `TerminalKeystrokeTracker.applyReplacement` preserves keys typed after replacement + started (`baseLength`) and reconciles `xterm-helper-textarea` buffers without + re-correcting previously replaced tokens. + ## [1.10.1] - 2026-10-24 > Urgent fix release. Installs older than 1.10.1 receive this update automatically. diff --git a/apps/desktop/sidecar/uia_bridge.py b/apps/desktop/sidecar/uia_bridge.py index 53605fa..3b808cc 100644 --- a/apps/desktop/sidecar/uia_bridge.py +++ b/apps/desktop/sidecar/uia_bridge.py @@ -132,8 +132,8 @@ def _read_text(auto: Any, control: Any) -> tuple[str, str, Optional[Any]]: if value_pattern is not None: try: - text = value_pattern.Value or "" - return (str(text)[:MAX_TEXT_CHARS], "value", value_pattern) + text = str(value_pattern.Value or "") + return (text[-MAX_TEXT_CHARS:], "value", value_pattern) except Exception: pass @@ -143,8 +143,20 @@ def _read_text(auto: Any, control: Any) -> tuple[str, str, Optional[Any]]: text_pattern = None if text_pattern is not None: try: - text = text_pattern.DocumentRange.GetText(-1) or "" - return (str(text)[:MAX_TEXT_CHARS], "text", value_pattern) + raw_text = str(text_pattern.DocumentRange.GetText(-1) or "") + trimmed = raw_text.rstrip("\r\n ") + if len(trimmed) > MAX_TEXT_CHARS: + try: + visible = text_pattern.GetVisibleRanges() + if visible: + vis_text = "\n".join( + str(r.GetText(-1) or "").rstrip("\r\n ") for r in visible + ).rstrip("\r\n ") + if vis_text: + return (vis_text[-MAX_TEXT_CHARS:], "text", value_pattern) + except Exception: + pass + return ((trimmed or raw_text)[-MAX_TEXT_CHARS:], "text", value_pattern) except Exception: # Chromium/CEF 입력창에서 COMError 가 나는 사례가 보고돼 있다 (issue #135/#138). pass @@ -152,8 +164,8 @@ def _read_text(auto: Any, control: Any) -> tuple[str, str, Optional[Any]]: try: legacy = control.GetLegacyIAccessiblePattern() if legacy is not None: - text = legacy.Value or "" - return (str(text)[:MAX_TEXT_CHARS], "legacy", value_pattern) + text = str(legacy.Value or "") + return (text[-MAX_TEXT_CHARS:], "legacy", value_pattern) except Exception: pass @@ -205,7 +217,7 @@ def _caret_rect_and_offset(auto: Any, control: Any) -> tuple[Optional[dict], Opt # 문자 단위로 확장한 뒤 다시 시도한다 (Windows Terminal 레시피). try: expanded = caret_range.Clone() - expanded.ExpandToEnclosingUnit(auto.TextUnit.Character) + expanded.ExpandToEnclosingUnit(auto.TextUnit.Character, waitTime=0) caret_rect = _first_rect(expanded.GetBoundingRectangles()) except Exception: caret_rect = None diff --git a/apps/desktop/src/main/bootstrap.ts b/apps/desktop/src/main/bootstrap.ts index 113883f..8aa6c7b 100644 --- a/apps/desktop/src/main/bootstrap.ts +++ b/apps/desktop/src/main/bootstrap.ts @@ -168,6 +168,9 @@ async function initConfigEffects(): Promise { effects.register('theme', () => reapplyThemeToAllPopups()) // 팝업 문서 lang 도 같은 재주입에서 맞춘다 effects.register('language', () => reapplyThemeToAllPopups()) + // 자동 한영·오타 교정이나 제안 설정이 바뀌면 입력 문맥 관찰기 실행 여부도 동기화한다 + effects.register('typoAutoCorrectEnabled', () => getInputTelemetryService().applyConfig()) + effects.register('suggestionEnabled', () => getInputTelemetryService().applyConfig()) effects.start() getShutdownRegistry().register({ name: 'config-effects', dispose: () => effects.dispose() }) } @@ -213,9 +216,18 @@ async function initInputIntelligence(): Promise { // 스냅샷이 온다), 모델로 검사 중이면 끝날 때('settled') 넘긴다. 제안이 고친 문장을 기준으로 // 만들어지고, 두 요청이 같은 모델을 두고 경쟁하지 않는다. const typo = initTypoCorrectionService({ - replaceBeforeCaret: async (deleteCount, text) => { - const method = configGet('insertMethod') === 'keyboard' ? 'keyboard' : 'clipboard' - const result = await getTextInsertService().replaceBeforeCaret(deleteCount, text, method) + replaceBeforeCaret: async (deleteCount, text, options) => { + // Windows 에서는 KEYEVENTF_UNICODE 직접 타이핑('keyboard')을 기본으로 써서 + // 사용자의 클립보드(Win+V)를 오염시키거나 ClipboardSvcGroup 의 OpenClipboard 잠금과 충돌하지 않게 한다. + const method = process.platform === 'win32' || configGet('insertMethod') === 'keyboard' ? 'keyboard' : 'clipboard' + const baseLength = telemetry.currentTerminalPrefixLength() + if (method === 'keyboard') { + telemetry.expectProgrammaticKeys(deleteCount + (options?.commitComposition ? 2 : 0)) + } + const result = await getTextInsertService().replaceBeforeCaret(deleteCount, text, method, options) + if (result.success) { + telemetry.applyProgrammaticReplacement(deleteCount, text, baseLength) + } return result.success }, lastKeyAt: () => telemetry.lastKeyAt, @@ -237,12 +249,13 @@ async function initInputIntelligence(): Promise { typo.on('corrected', () => { if (suggestion.isPresentationActive) suggestion.dismiss('stale') }) - // 제안이 켜져 있으면 오타를 조용히 고치지 않고 제안 창에 "지운 글자 → 고친 글자" 로 함께 내놓는다 - // (수락할 때만 적용 — 2026-10-17 사용자 요청). 제안이 꺼져 있을 때만 위 자동 교정이 돈다. + // 제안이 켜져 있을 때도 한영 전환(Araso 방식 영→한·한→영·혼합어)은 기본 기능으로 즉시 고치고, + // 일반 철자·모델 오타는 제안 창에 "지운 글자 → 고친 글자" 로 함께 내놓는다. suggestion.setTypoProposer({ propose: (context, signal, options) => typo.propose(context, signal, options) }) telemetry.on('typed-context', (context) => { if (suggestion.isEnabled()) { - suggestion.handleTypingContext(context) + const layoutVerdict = typo.handleTypingContext(context, { layoutOnly: true }) + if (layoutVerdict === 'pass') suggestion.handleTypingContext(context) return } const verdict = typo.handleTypingContext(context) @@ -285,6 +298,7 @@ async function initInputIntelligence(): Promise { getKeyBindingService().on('triggered', (payload) => { if (payload.type !== 'pressed') return if (payload.actionId === 'suggestion-accept') void suggestion.accept() + else if (payload.actionId === 'suggestion-accept-word') void suggestion.accept(undefined, { wordOnly: true }) else if (payload.actionId === 'suggestion-next') suggestion.next() else if (payload.actionId === 'suggestion-prev') suggestion.previous() else if (payload.actionId === 'suggestion-dismiss') suggestion.dismiss('dismissed') @@ -357,6 +371,8 @@ async function initAutoLaunch(): Promise { async function initAutoUpdate(): Promise { const { getUpdateService } = await import('./services/UpdateService') const updates = getUpdateService() + // 설정 정보 탭·타이틀바 칩이 업데이트 진행을 따라가게 한다 + updates.on('status-changed', (status) => sendToMainWindow(IPC_CHANNELS.APP_UPDATE.STATUS_CHANGED, status)) updates.initialize() getShutdownRegistry().register({ name: 'auto-update', dispose: () => updates.dispose() }) } diff --git a/apps/desktop/src/main/ipc/app-update-handlers.ts b/apps/desktop/src/main/ipc/app-update-handlers.ts new file mode 100644 index 0000000..6ff4358 --- /dev/null +++ b/apps/desktop/src/main/ipc/app-update-handlers.ts @@ -0,0 +1,58 @@ +// src/main/ipc/app-update-handlers.ts +// 앱 업데이트 상태 조회 · 수동 확인 · 다운로드 · 재시작 설치 (설정 정보 탭, 타이틀바 칩). +// 상태 변화 알림(APP_UPDATE.STATUS_CHANGED)은 bootstrap 의 initAutoUpdate 가 메인 창으로 중계한다. +// UpdateService 는 bootstrap 과 같이 지연 로드한다 — electron-updater 를 시작 경로에 올리지 않는다. + +import { ipcMain } from 'electron' +import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' +import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' +import type { UpdateService } from '../services/UpdateService' + +async function updateService(): Promise { + const { getUpdateService } = await import('../services/UpdateService') + return getUpdateService() +} + +function failure(error: unknown) { + return ipcError(ErrorCode.AppUpdateFailed, error instanceof Error ? error.message : String(error)) +} + +export function registerAppUpdateHandlers(): void { + ipcMain.handle(IPC_CHANNELS.APP_UPDATE.GET_STATUS, async () => { + try { + return ipcSuccess((await updateService()).getStatus()) + } catch (error) { + return failure(error) + } + }) + + ipcMain.handle(IPC_CHANNELS.APP_UPDATE.CHECK, async () => { + try { + const service = await updateService() + await service.checkForUpdates() + return ipcSuccess(service.getStatus()) + } catch (error) { + return failure(error) + } + }) + + ipcMain.handle(IPC_CHANNELS.APP_UPDATE.DOWNLOAD, async () => { + try { + const service = await updateService() + await service.startDownload() + return ipcSuccess(service.getStatus()) + } catch (error) { + return failure(error) + } + }) + + ipcMain.handle(IPC_CHANNELS.APP_UPDATE.INSTALL, async () => { + try { + const service = await updateService() + await service.installNow() + return ipcSuccess(service.getStatus()) + } catch (error) { + return failure(error) + } + }) +} diff --git a/apps/desktop/src/main/ipc/index.ts b/apps/desktop/src/main/ipc/index.ts index 99822ce..d817505 100644 --- a/apps/desktop/src/main/ipc/index.ts +++ b/apps/desktop/src/main/ipc/index.ts @@ -30,6 +30,7 @@ import { registerAdsHandlers } from './ads-handlers' import { registerSupportHandlers } from './support-handlers' import { registerInputTelemetryHandlers } from './input-telemetry-handlers' import { registerSuggestionHandlers } from './suggestion-handlers' +import { registerAppUpdateHandlers } from './app-update-handlers' import { registerUnifiedSearchHandlers } from './unified-search-handlers' import { getLogger } from '../services/LoggerService' @@ -67,5 +68,6 @@ export function registerAllIpcHandlers(): void { registerSupportHandlers() registerInputTelemetryHandlers() registerSuggestionHandlers() + registerAppUpdateHandlers() logger.info('All IPC handlers registered') } diff --git a/apps/desktop/src/main/ipc/suggestion-handlers.ts b/apps/desktop/src/main/ipc/suggestion-handlers.ts index 9c8a9bd..15ee1f3 100644 --- a/apps/desktop/src/main/ipc/suggestion-handlers.ts +++ b/apps/desktop/src/main/ipc/suggestion-handlers.ts @@ -5,6 +5,7 @@ import { ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' import { getSuggestionService } from '../services/SuggestionService' +import { getInputTelemetryService } from '../services/InputTelemetryService' import { configSet } from '../services/ConfigService' import { applySuggestionOverlayConfig, hideSuggestionOverlay } from '../windows/WindowManager' @@ -81,6 +82,7 @@ export function registerSuggestionHandlers(): void { } service.applyConfig() + getInputTelemetryService().applyConfig() // 새 모델은 콜드일 수 있다 — 첫 멈춤에서 타임아웃되기 전에 미리 올린다. if (modelChangeRequested && service.resolveModel() !== previousModel) service.handleModelChanged() return ipcSuccess(service.getState()) diff --git a/apps/desktop/src/main/services/InputTelemetryService.ts b/apps/desktop/src/main/services/InputTelemetryService.ts index 340bee9..2095938 100644 --- a/apps/desktop/src/main/services/InputTelemetryService.ts +++ b/apps/desktop/src/main/services/InputTelemetryService.ts @@ -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() diff --git a/apps/desktop/src/main/services/LocalLLMService.ts b/apps/desktop/src/main/services/LocalLLMService.ts index f332062..ec65ea5 100644 --- a/apps/desktop/src/main/services/LocalLLMService.ts +++ b/apps/desktop/src/main/services/LocalLLMService.ts @@ -89,7 +89,10 @@ interface OllamaGenerateResponse { done: boolean total_duration?: number prompt_eval_count?: number + prompt_eval_cached_count?: number + prompt_eval_duration?: number eval_count?: number + eval_duration?: number } /** @d3ro/core/llm-chat 공통 옵션 + Ollama 전용 keep_alive. */ @@ -537,6 +540,15 @@ class LocalLLMService extends EventEmitter { completionTokens: lastChunk?.eval_count ?? 0, totalDuration: lastChunk?.total_duration ? lastChunk.total_duration / 1e6 : 0 } + // 지연 분해 진단 — 어디서 시간이 새는지(프롬프트 읽기·캐시 재사용·생성) 로그만으로 가른다. 글은 남기지 않는다. + if (lastChunk) { + const ms = (value: number | undefined) => Math.round((value ?? 0) / 1e6) + logger.debug( + `LLM 스트림 완료 (${model}): 프롬프트 ${lastChunk.prompt_eval_count ?? 0}토큰` + + ` (캐시 ${lastChunk.prompt_eval_cached_count ?? 0}) ${ms(lastChunk.prompt_eval_duration)}ms,` + + ` 생성 ${lastChunk.eval_count ?? 0}토큰 ${ms(lastChunk.eval_duration)}ms, 총 ${ms(lastChunk.total_duration)}ms` + ) + } this.emit('complete', { result }) return result } diff --git a/apps/desktop/src/main/services/SuggestionService.ts b/apps/desktop/src/main/services/SuggestionService.ts index 4a89e91..aa8ba97 100644 --- a/apps/desktop/src/main/services/SuggestionService.ts +++ b/apps/desktop/src/main/services/SuggestionService.ts @@ -13,6 +13,7 @@ import { EventEmitter } from 'events' import { COMPOSING_IDLE_MULTIPLIER, + isAppScopedLearning, SUGGESTION_DEFAULTS, SUGGESTION_MAX_OUTPUT_CHARS, buildLocalSuggestionCandidateEntries, @@ -43,6 +44,9 @@ import { } from '@d3ro/core/input-intelligence' import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template' import { buildQueryTerms, splitSentences } from '@d3ro/core/personal-graph' +import { copiesContext } from '@d3ro/core/suggestion-confidence' +import { splitFirstWord } from '@d3ro/core/suggestion-text' +import { predictPersonalContinuation } from '@d3ro/core/personal-ngram' import { analyzeWritingContext, findUnsupportedFacts } from '@d3ro/core/writing-context' import { alignCorrectionToPrefix } from '@d3ro/core/typo-correction' import { configGet, configSet } from './ConfigService' @@ -52,7 +56,7 @@ import { buildSuggestionPrompt } from './llm-prompts' import { getInputTelemetryService, type TypingContext } from './InputTelemetryService' import { getPersonalGraphService } from './PersonalGraphService' import { getTextInsertService } from './TextInsertService' -import { waitForModifiersReleased } from './modifier-state' +import { prepareModifiersForPaste } from './modifier-state' import { createSqliteSuggestionRepository, type SuggestionHistoryEntry, @@ -61,6 +65,7 @@ import { } from './SuggestionRepository' import { SuggestionBudget } from './suggestion/SuggestionBudget' import { ModelWarmTracker } from './suggestion/ModelWarmTracker' +import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex' import { LOCAL_LLM_KEEP_ALIVE, LOCAL_LLM_KEEP_ALIVE_MS } from './llm/model-residency' import { getForegroundWindowInfo } from '../utils/win32-foreground' @@ -188,6 +193,25 @@ function relatedPromptHints(memory: LocalMemoryContext): string[] { const TERMINAL_TYPING_STEP_CHARS = 8 /** 모델 출력의 모양 (길이·첫 글자 종류·줄 수) — 로그용, 내용은 담지 않는다. */ +/** 공백·끝 문장부호를 무시하고 같은 후보인가 */ +function sameCandidateText(a: string, b: string): boolean { + const norm = (text: string) => text.replace(/\s+/gu, ' ').replace(/[.!?。!?…,]+$/u, '').trim() + return norm(a) === norm(b) +} + +/** 접두 끝 글자 종류 — 진단용(글 내용은 남기지 않는다). */ +function describePrefixEnd(prefix: string): string { + if (/\s$/u.test(prefix)) return 'space' + const last = [...prefix].pop() ?? '' + if (!last) return 'empty' + if (/[\u3131-\u318e]/u.test(last)) return 'jamo' + if (/[가-힣]/u.test(last)) return 'hangul' + if (/[.!?。!?…~]/u.test(last)) return 'sentence-end' + if (/[,;:]/u.test(last)) return 'comma' + if (/[A-Za-z0-9]/u.test(last)) return 'ascii' + return 'other' +} + function describeRawOutput(raw: string, prefill: boolean): string { const first = raw.charAt(0) const kind = @@ -212,6 +236,8 @@ function commonPrefixLength(a: string, b: string): number { /** 이 길이를 넘는 모델 출력은 버린다 (스트리밍 폭주 방지) */ const MAX_RAW_OUTPUT_CHARS = 1200 +/** "제안 사항 없음" 을 보여 주는 시간 */ +const NO_SUGGESTION_NOTICE_MS = 1000 /** * 채우기 루프(2번째 이후 후보)의 온도. @@ -304,6 +330,9 @@ export class SuggestionService extends EventEmitter { private _lastRequestedPrefix = '' /** 사용자가 X 로 닫은 뒤 재표시를 막는 시각 (ms) */ private _userDismissedUntil = 0 + /** "제안 사항 없음" 알림 — 생성 중이 떠 있다가 후보 없이 끝났을 때 1초 */ + private _notice: 'no-suggestion' | null = null + private _noticeTimer: ReturnType | null = null /** 수락 삽입이 진행 중이다(수정자 키 떼기 대기 포함) — 그사이 같은 글로 새 제안 창이 다시 뜨지 않게 한다. */ private _acceptInFlight = false /** 스트리밍 누적 텍스트 */ @@ -464,6 +493,7 @@ export class SuggestionService extends EventEmitter { triggerDelayMs: this.readPolicyConfig().triggerDelayMs, minPrefixChars: this.readPolicyConfig().minPrefixChars, requestTimeoutMs: this.readTimeoutMs(), + notice: this._notice, learnTypedText: configGet('inputLearnTypedText') === true, telemetryEnabled: configGet('inputTelemetryEnabled') === true, overlayInteractive: configGet('suggestionOverlayInteractive') !== false, @@ -644,7 +674,8 @@ export class SuggestionService extends EventEmitter { */ handleTypingContext(input: TypingContext): void { // 터미널은 화면 전체가 읽힌다 — 입력 줄만 접두로 쓴다. 입력 줄이 없으면 빈 접두(제안 안 함). - const context: TypingContext = isTerminalApp(input.appName) ? this._terminalContext(input) : input + const context: TypingContext = + isTerminalApp(input.appName) || input.terminalMode === true ? this._terminalContext(input) : input this._lastContext = context const now = Date.now() this._lastContextAt = now @@ -938,7 +969,13 @@ export class SuggestionService extends EventEmitter { * (끝에서 치거나 지움) 커서는 입력 줄 끝이다. 중간을 고친 모양이면 다음 입력까지 막는다. */ private _terminalContext(input: TypingContext): TypingContext { - const prompt = extractTerminalPromptPrefix(input.fullText ?? input.prefix) + if (input.vimMode === 'normal' || input.vimMode === 'command') { + this._lastTerminalPrompt = '' + this._terminalPromptTyped = false + return { ...input, prefix: '', documentBefore: null, caretReliable: false } + } + const extracted = extractTerminalPromptPrefix(input.fullText ?? input.prefix) + const prompt = extracted ?? (input.terminalMode ? input.prefix : null) const previous = this._lastTerminalPrompt this._lastTerminalPrompt = prompt let typed: boolean @@ -958,7 +995,12 @@ export class SuggestionService extends EventEmitter { typed = commonPrefixLength(previous, prompt) >= Math.min(previous.length, prompt.length) - 2 } this._terminalPromptTyped = typed - return { ...input, prefix: prompt ?? '', documentBefore: null, caretReliable: typed } + return { + ...input, + prefix: prompt ?? '', + documentBefore: null, + caretReliable: extracted !== null ? typed : typed && input.caretReliable !== false + } } /** 로컬 기억은 모델과 무관하다 — 같은 정책을 "모델 있음 · 표시 없음" 으로 평가한다. */ @@ -991,8 +1033,13 @@ export class SuggestionService extends EventEmitter { phrase.appName?.trim().toLowerCase() === requestedApp && phraseHints.includes(phrase.phrase) ).length : 0 + // 앱 안에서만 배우는 앱(Agent Switchboard)은 공용 그래프에 그 앱 글이 없다 — 같은 앱 표본에서 이어 쓴 글을 찾는다. + const scopedContinuations = + appName && isAppScopedLearning(appName) + ? telemetry.findContinuationHints(writing.currentSentence || writing.lastSentence, 3, { appName }) + : [] return { - continuationHints: graphContext.continuations, + continuationHints: [...scopedContinuations, ...graphContext.continuations].slice(0, 3), followUpHints: graphContext.followUps ?? [], relatedHints: graphContext.related, phraseHints, @@ -1067,6 +1114,8 @@ export class SuggestionService extends EventEmitter { // 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다. const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource) if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } + // 화면·앞 글을 그대로 베낀 후보는 버린다 (실측 2026-10-25: 앞 대화 문장이 그대로 제안됨) + if (copiesContext(continuation.text, prompt.factSource)) return { candidate: null, rejected: 'copied-context' } return { candidate: continuation.joint === 'attach' @@ -1096,6 +1145,7 @@ export class SuggestionService extends EventEmitter { // 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다. const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource) if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` } + if (copiesContext(continuation.text, prompt.factSource)) return { candidate: null, rejected: 'copied-context' } return { candidate: continuation.joint === 'attach' @@ -1217,6 +1267,41 @@ export class SuggestionService extends EventEmitter { return true } + /** + * 내 기록(개인 n-gram)이 확신하는 이어쓰기 — 확실할 때만(core PERSONAL_NGRAM_SETTINGS). 없으면 null. + * 단어 중간이면 그 어절의 나머지(수락 시 공백 없이 붙임), 아니면 다음 1~2어절. + */ + private _personalCandidate(context: TypingContext): SuggestionCandidate | null { + const model = getPersonalNgramIndex().model() + if (!model) return null + const prediction = predictPersonalContinuation(model, this._lastContext?.prefix ?? context.prefix) + if (!prediction || prediction.text.trim().length === 0) return null + return prediction.joint === 'attach' + ? { text: prediction.text, rank: 0, joint: 'attach', source: 'personal' } + : { text: prediction.text, rank: 0, source: 'personal' } + } + + /** 모델이 아무것도 못 냈어도 먼저 띄운 내 기록 후보가 있으면 그것으로 세션을 남긴다. */ + private _keepPersonalCandidate(trimmedPrefix: string, model: string, startedAt: number): boolean { + const personal = this._candidates.find((candidate) => candidate.source === 'personal') + if (!personal) return false + this._candidates = [{ ...personal, rank: 0 }] + this._targetTotal = 1 + this._generating = false + this._filling = false + this._recordSuggestion({ + prefix: trimmedPrefix, + text: personal.text, + model: 'personal-ngram', + latencyMs: Date.now() - startedAt, + candidateCount: 1 + }) + logger.debug(`모델 후보 없음 — 내 기록 후보만 남긴다 (model=${model})`) + this.emit('updated', this.getState()) + this.emit('state-changed', this.getState()) + return true + } + // ── 생성 ────────────────────────────────────────────── private async _generate( @@ -1265,6 +1350,7 @@ export class SuggestionService extends EventEmitter { this._abort = abort const token = (this._generationToken += 1) + this._clearNotice() this._inFlight = true this._generating = true this._lastRequestedPrefix = normalizeRequestPrefix(prefix) @@ -1284,6 +1370,15 @@ export class SuggestionService extends EventEmitter { this._appName = context.appName this._windowTitle = context.windowTitle this._windowHandle = context.windowHandle ?? null + // 내 기록이 확신하는 이어쓰기가 있으면 모델을 기다리지 않고 1번 후보로 먼저 띄운다 — 모델 후보는 뒤에 붙는다. + // (2026-10-25: 모델을 "대신" 하면 제안이 너무 드물어졌다 — 이번엔 더하기만 한다) + const instant = this._personalCandidate(context) + if (instant) { + this._candidates = [instant] + this._generatedForPrefix = trimmedPrefix + this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal + this._provenance = { mode: 'local-memory', continuationCount: 0, relatedCount: 0, phraseCount: 0, appPhraseCount: 0 } + } this._armVisibleTtl() this.emit('updated', this.getState()) @@ -1301,7 +1396,10 @@ export class SuggestionService extends EventEmitter { // 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장, // (2) follows/용어공유 관계로 끌어온 관련 문장. + const memoryStartedAt = Date.now() let memory = this._collectMemoryHints(trimmedPrefix, context.appName) + // 지연 분해 진단 — 첫 후보까지의 시간이 기억 조회·오타 교정·모델 중 어디에 쓰이는지 남긴다. + const timing = { memoryMs: Date.now() - memoryStartedAt, correctionMs: 0, modelMs: 0, attempts: 0 } let spacedPreferred = false let correction: SuggestionCorrection | null = null let promptContext = context @@ -1310,7 +1408,9 @@ export class SuggestionService extends EventEmitter { try { // 오타가 있으면 고친 글로 이어 쓴다 — 낱자 잡음("안ㄴ뇽", "ㅇ다른")이 섞인 글을 그대로 주면 모델이 // 그 잡음까지 되풀이했다(실측 이력: "아직 ㅇ" → "아직 ㅇ 기능도…"). 교정은 수락할 때만 적용한다. + const correctionStartedAt = Date.now() correction = await this._proposeCorrection(context, abort.signal) + timing.correctionMs = Date.now() - correctionStartedAt if (correction) { promptContext = applyCorrectionToContext(context, correction) memory = this._collectMemoryHints(normalizeSessionPrefix(promptContext.prefix), context.appName) @@ -1328,7 +1428,9 @@ export class SuggestionService extends EventEmitter { // 지어낸 사실(원문에 없는 날짜·이름·숫자)로 버린 첫 후보는 같은 시간 제한 안에서 한 번 더 뽑는다. let active = request let temperature: number = SUGGESTION_DEFAULTS.temperature + const modelStartedAt = Date.now() for (let attempt = 0; attempt < 2; attempt += 1) { + timing.attempts = attempt + 1 const raw = await this._streamModel(active, model, temperature, abort.signal, (partial) => { // 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다. // IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다. @@ -1344,6 +1446,13 @@ export class SuggestionService extends EventEmitter { if (!parsed.candidate) { // 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보. logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`) + if (raw.trim().length === 0) { + // 첫 시도가 비는 조건을 찾는다(실사용 26% — 다시 뽑느라 ~250ms). 글 대신 끝 글자 종류만 남긴다. + logger.debug( + `제안 빈 출력 조건: app=${context.appName ?? '-'} end=${describePrefixEnd(promptContext.prefix)} ` + + `comp=${context.isComposing === true} spaced=${active !== request}` + ) + } } if (parsed.candidate) break if (raw.trim().length === 0 && active.spaced) { @@ -1359,10 +1468,12 @@ export class SuggestionService extends EventEmitter { this._partialText = '' } spacedPreferred = active !== request + timing.modelMs = Date.now() - modelStartedAt } catch (error) { if (!abort.signal.aborted) { this._lastSkipReason = 'generation-failed' this._noteFailure(error instanceof Error ? error.message : String(error)) + if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return if ( this._publishLocalMemory( trimmedPrefix, @@ -1402,6 +1513,7 @@ export class SuggestionService extends EventEmitter { // — 다음 멈춤은 같은 콜드 요청을 되풀이하지 말고 워밍업("준비 중")부터 한다. this._warmth.noteCold(model) this._noteFailure(`timeout ${timeoutMs}ms`) + if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return if ( this._publishLocalMemory( trimmedPrefix, @@ -1453,6 +1565,7 @@ export class SuggestionService extends EventEmitter { if (!first) { this._lastSkipReason = 'generation-failed' logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`) + if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return if ( this._publishLocalMemory( trimmedPrefix, @@ -1475,7 +1588,12 @@ export class SuggestionService extends EventEmitter { this._lastLatencyMs = latencyMs this._budget.noteSuccess() this._partialText = '' - this._candidates = [{ ...first, rank: 0 }] + // 먼저 띄운 내 기록 후보가 있으면 그 뒤에 붙인다(같은 글이면 하나만). + const personal = this._candidates.find((candidate) => candidate.source === 'personal') + this._candidates = + personal && !sameCandidateText(personal.text, first.text) + ? [{ ...personal, rank: 0 }, { ...first, rank: 1 }] + : [{ ...first, rank: 0 }] this._correction = correction this._promptContext = promptContext this._spacedPreferred = spacedPreferred @@ -1498,6 +1616,9 @@ export class SuggestionService extends EventEmitter { this._recordSuggestion({ prefix: trimmedPrefix, text: first.text, model, latencyMs, candidateCount: 1 }) logger.info(`제안 첫 후보 생성 (${latencyMs}ms, model=${model}) — 최대 ${SUGGESTION_DEFAULTS.maxCandidatesTotal}개까지 순차로 채운다`) + logger.debug( + `제안 지연 분해: 기억 ${timing.memoryMs}ms, 교정 ${timing.correctionMs}ms, 모델 ${timing.modelMs}ms (시도 ${timing.attempts}회)` + ) this._armVisibleTtl() this.emit('updated', this.getState()) @@ -1858,6 +1979,10 @@ export class SuggestionService extends EventEmitter { } dismiss(reason: SuggestionSkipReason = 'dismissed'): void { + // 알림은 닫히기 직전 자리에 그린다 — 아래에서 세션을 지우기 전에 기억해 둔다. + const lastAnchor = this._anchor + const lastAnchorKind = this._anchorKind + this._clearNotice() if (reason === 'dismissed') { // 명시적 닫기: 잠깐 조용히 있고, 진행 중 생성은 무효화한다. this._userDismissedUntil = Date.now() + SUGGESTION_DEFAULTS.userDismissQuietMs @@ -1895,13 +2020,47 @@ export class SuggestionService extends EventEmitter { // 워밍업은 오버레이 표시와 독립된 요청이다 — 포커스 전환/stale 등으로 오버레이를 // 지울 때마다 취소하면 모델이 영영 안 뜬다. 설정에서 기능을 끌 때만 취소한다. if (reason === 'disabled') this._cancelWarmUp() + if (wasVisible && reason === 'generation-failed' && lastAnchor) { + this._showNoSuggestionNotice(reason, lastAnchor, lastAnchorKind) + return + } if (wasVisible || reason === 'dismissed') { this.emit('cleared', { reason }) } } + /** "생성 중" 이 보이다 후보 없이 끝났다 — 말없이 닫지 않고 "제안 사항 없음" 을 1초 보여 준 뒤 닫는다. */ + private _showNoSuggestionNotice( + reason: SuggestionSkipReason, + anchor: PhysicalRect, + anchorKind: AnchorKind + ): void { + this._notice = 'no-suggestion' + this._anchor = anchor + this._anchorKind = anchorKind + this.emit('updated', this.getState()) + this._noticeTimer = setTimeout(() => { + this._noticeTimer = null + this._notice = null + // 그사이 새 세션이 자리를 잡지 않았을 때만 자리를 비운다. + if (!this.isPresentationActive) this._anchor = null + this.emit('cleared', { reason }) + }, NO_SUGGESTION_NOTICE_MS) + this._noticeTimer.unref?.() + } + + private _clearNotice(): void { + if (this._noticeTimer) { + clearTimeout(this._noticeTimer) + this._noticeTimer = null + } + this._notice = null + } + /** 활성 후보를 대상 앱에 삽입하고 수락으로 기록한다. */ - async accept(index?: number): Promise { + async accept(index?: number, options: { wordOnly?: boolean } = {}): Promise { + // 손을 기다리는 동안(창이 떠 있다) 단축키가 또 눌려도 두 번 넣지 않는다. + if (this._acceptInFlight) return { ok: false, reason: 'already-visible' } if (index !== undefined && index >= 0 && index < this._candidates.length) { this._activeIndex = index } @@ -1928,23 +2087,41 @@ export class SuggestionService extends EventEmitter { const basePrefix = correction ? acceptPrefix.slice(0, acceptPrefix.length - correction.from.length) + correction.to : acceptPrefix - const text = (correction?.to ?? '') + joinSuggestion(basePrefix, candidate.text, candidate.joint ?? 'separate') + // 단어 단위 수락 — 첫 어절만 넣고 나머지는 창에 남긴다(이어서 한 단어씩, 또는 Enter 로 나머지 전부). + const split = options.wordOnly ? splitFirstWord(candidate.text) : null + const partial = split !== null && split.rest.length > 0 + const insertPart = partial ? split.word : candidate.text + const joined = joinSuggestion(basePrefix, insertPart, candidate.joint ?? 'separate') + const text = (correction?.to ?? '') + joined const deleteCount = correction?.from.length ?? 0 + const anchor = this._anchor + const anchorKind = this._anchorKind + const provenance = this._provenance const composing = this._lastContext?.isComposing === true const appName = this._appName const windowTitle = this._windowTitle const targetWindow = this._windowHandle const sessionRecordId = this._sessionRecordId - // 먼저 창을 닫고 생성을 멈춘다 — 수락은 즉시 반응해야 한다. - this.dismiss('accepted') - this.emit('state-changed', this.getState()) - - // 단축키로 수락했다면 사용자가 아직 Ctrl+Alt 를 쥐고 있다. 그대로 Ctrl+V 를 보내면 - // 대상 앱에 Ctrl+Alt+V 가 들어가 붙여넣기가 되지 않는다(실측) — 뗄 때까지 기다린다. + // 단축키로 수락했다면 사용자가 아직 키를 쥐고 있다. 그대로 Ctrl+V 를 보내면 대상 앱에 Ctrl+Alt+V 가 들어가 + // 붙여넣기가 되지 않는다. 창을 띄워 둔 채 손을 다 뗄 때까지 기다린다(최대 5초) — 창이 먼저 사라지면 사용자는 + // "들어가는 중" 이라 여기고 계속 쥐고 있었다(2026-10-25). 클릭 수락은 기다림 없이 바로 지나간다. this._acceptInFlight = true try { - return await this._insertAccepted({ + const modifierWaitStartedAt = Date.now() + const keys = await prepareModifiersForPaste() + logger.debug(`제안 수락: 단축키 떼기 ${keys} (${Date.now() - modifierWaitStartedAt}ms)`) + if (keys === 'still-held') { + logger.warn('제안 수락 취소: 5초 안에 단축키를 떼지 않았다 — 넣으면 Ctrl+Alt+V 가 되므로 넣지 않는다') + this.dismiss('stale') + this.emit('state-changed', this.getState()) + return { ok: false, reason: 'stale' } + } + + // 이제 창을 닫고 생성을 멈춘 뒤 넣는다. + this.dismiss('accepted') + this.emit('state-changed', this.getState()) + const result = await this._insertAccepted({ text, deleteCount, composing, @@ -1952,13 +2129,47 @@ export class SuggestionService extends EventEmitter { windowTitle, targetWindow, sessionRecordId, - candidateText: candidate.text + candidateText: candidate.text, + // 한 단어만 받은 것은 그 문장 전체를 사용자 문체로 배우지 않는다. + learn: !partial }) + if (partial && result.ok) this._presentRemainder(`${basePrefix}${joined}`, split.rest, { anchor, anchorKind, appName, windowTitle, targetWindow, provenance }) + return result } finally { this._acceptInFlight = false } } + /** 단어 단위 수락 뒤 남은 문장을 같은 자리에 다시 띄운다 — 세션 접두는 방금 넣은 글까지로 맞춘다. */ + private _presentRemainder( + prefixAfterInsert: string, + rest: string, + meta: { + anchor: PhysicalRect | null + anchorKind: AnchorKind + appName: string | null + windowTitle: string | null + targetWindow: number | null + provenance: SuggestionProvenance | null + } + ): void { + this._candidates = [{ text: rest, rank: 0 }] + this._activeIndex = 0 + this._targetTotal = 1 + this._correction = null + this._anchor = meta.anchor + this._anchorKind = meta.anchorKind + this._appName = meta.appName + this._windowTitle = meta.windowTitle + this._windowHandle = meta.targetWindow + this._provenance = meta.provenance + this._generatedForPrefix = normalizeSessionPrefix(prefixAfterInsert) + this._lastSkipReason = null + this._armVisibleTtl() + this.emit('updated', this.getState()) + this.emit('state-changed', this.getState()) + } + private async _insertAccepted(params: { text: string deleteCount: number @@ -1968,15 +2179,10 @@ export class SuggestionService extends EventEmitter { targetWindow: number | null sessionRecordId: string | null candidateText: string + /** 수락한 문장을 사용자 문체 표본으로 배운다 (단어 단위 수락은 false) */ + learn?: boolean }): Promise { const { text, deleteCount, composing, appName, windowTitle, targetWindow, sessionRecordId, candidateText } = params - const modifierWaitStartedAt = Date.now() - if (!(await waitForModifiersReleased())) { - logger.warn('수정자 키가 떼어지지 않은 채 제안을 삽입한다 (1.5초 초과)') - } - // "붙여넣기가 느리다" 신고 진단 — 수락 지연이 손 떼기 대기인지 삽입 자체인지 가른다. - logger.debug(`제안 수락: 수정자 키 떼기 대기 ${Date.now() - modifierWaitStartedAt}ms`) - // 붙여넣기(Ctrl+V)는 그 순간의 포그라운드 창으로 간다. 오버레이는 다음 스냅샷이 와야 // 닫히므로, 그사이 다른 앱으로 옮겨 간 뒤 수락하면 엉뚱한 창에 삽입됐다 — 세션을 만든 // 창이 아니면 삽입하지 않는다 (창을 알 수 없으면 기존처럼 진행한다). @@ -2031,7 +2237,7 @@ export class SuggestionService extends EventEmitter { this._repository.markAccepted(candidateText) } // 수락한 문장은 사용자 문체의 확실한 표본이다 (학습 동의 시에만 저장됨). - this._learning.recordAccepted(candidateText, { appName, windowTitle }) + if (params.learn !== false) this._learning.recordAccepted(candidateText, { appName, windowTitle }) return { ok: true } } diff --git a/apps/desktop/src/main/services/TextInsertService.ts b/apps/desktop/src/main/services/TextInsertService.ts index 0207294..e014f9d 100644 --- a/apps/desktop/src/main/services/TextInsertService.ts +++ b/apps/desktop/src/main/services/TextInsertService.ts @@ -122,7 +122,9 @@ export class TextInsertService extends EventEmitter { ) } // 앱이 지우기를 처리할 시간 — 붙여넣기가 지우기보다 먼저 처리되면 순서가 꼬인다. - await this._sleep(15) + // 긴 문장 교정(예: 30~40자 백스페이스)에서는 대상 앱 메시지 큐가 백스페이스를 소화할 시간을 비례해서 준다. + const settleMs = Math.min(90, Math.max(20, deleteCount * 2)) + await this._sleep(settleMs) return this._insertNow(text, method) }) this._tail = run.then( @@ -195,9 +197,10 @@ export class TextInsertService extends EventEmitter { // 3. Paste 단축키 시뮬레이션 — 플랫폼별 modifier await this._keyboard.paste() - // 4. 붙여넣기 완료 대기 — 앱이 paste 이벤트를 처리할 시간 - // macOS는 비동기 처리가 좀 더 느린 경우가 있어 250ms로 잡음 - await this._sleep(this._platform === 'darwin' ? 250 : 150) + // 4. 붙여넣기 완료 대기 — 대상 앱의 메시지 큐가 백스페이스 뒤 WM_PASTE(Ctrl+V)에서 + // 클립보드를 읽을 때까지 충분히 기다린 뒤 클립보드를 복원/비운다. + // (Ctrl+V 키 이벤트는 이미 위에서 전송되었으므로 화면 반영은 즉시 일어난다.) + await this._sleep(250) // 5. 클립보드 복원 (원래 내용으로 되돌림) if (this._restoreIfStillOurs(text, snapshot)) { diff --git a/apps/desktop/src/main/services/TypoCorrectionService.ts b/apps/desktop/src/main/services/TypoCorrectionService.ts index 41b6809..e95eea8 100644 --- a/apps/desktop/src/main/services/TypoCorrectionService.ts +++ b/apps/desktop/src/main/services/TypoCorrectionService.ts @@ -57,13 +57,19 @@ const VOCABULARY_TTL_MS = 60_000 const PROPOSAL_CHECK_TIMEOUT_MS = 1500 /** 모델 검사 최소 구간 길이 (글자) */ const MODEL_CHECK_MIN_CHARS = 6 +/** 공백·문장부호로 단어가 끝난 직후 한영 전환(Araso) 최소 유휴 시간 (ms) */ +const LAYOUT_BOUNDARY_MIN_IDLE_MS = 25 +/** Vim 명령줄(:wq 등)에서 공백 없이 엔터를 치기 전 한영 전환 최소 유휴 시간 (ms) */ +const LAYOUT_VIM_CMD_MIN_IDLE_MS = 135 +/** 공백 없이 단어 끝에서 멈췄을 때 한영 전환(Araso) 최소 유휴 시간 (ms) — 단어 입력 도중(some->sometime) 끼어들지 않게 함 */ +const LAYOUT_TRAILING_MIN_IDLE_MS = 650 /** 'typed-context' 에 대한 판단 — 제안 서비스로 그대로 넘길지(pass), 미룰지. */ export type TypoVerdict = 'pass' | 'correcting' | 'checking' export interface TypoCorrectionDeps { /** 커서 앞 deleteCount 글자를 지우고 text 를 넣는다. 성공 여부. */ - replaceBeforeCaret(deleteCount: number, text: string): Promise + replaceBeforeCaret(deleteCount: number, text: string, options?: { commitComposition?: boolean }): Promise /** 마지막 키보드 입력 시각 */ lastKeyAt(): number /** 곧 보낼 프로그램 키 수 (입력 통계 제외) */ @@ -96,6 +102,9 @@ interface AppliedCorrection { tailLength: number /** 교정 직후 접두 길이 — 되돌림은 이 근처에서만 본다 */ prefixLength: number + /** 교정된 구간 앞의 텍스트 — 새 문장을 치거나 칸을 비운 뒤에는 되돌림으로 오인하지 않는다 */ + prefixBefore: string + windowHandle: number | null } /** @@ -141,8 +150,11 @@ export class TypoCorrectionService extends EventEmitter { * * 'pass' 면 호출자가 이 문맥을 제안 서비스로 넘긴다. 'correcting' 이면 곧 텍스트가 바뀌므로 * 넘기지 않는다(교정 뒤 새 스냅샷이 온다). 'checking' 이면 모델 검사가 끝날 때 'settled' 로 넘긴다. + * + * `layoutOnly`: 한영 전환(Araso 방식 영→한·한→영·혼합어 자동 변환)만 즉시 교정하고, + * 일반 철자·모델 오타는 제안 오버레이(`propose()`)에 맡긴다. */ - handleTypingContext(context: TypingContext): TypoVerdict { + handleTypingContext(context: TypingContext, options: { layoutOnly?: boolean } = {}): TypoVerdict { this._watchRevert(context) if (this._applying) return 'correcting' @@ -155,13 +167,34 @@ export class TypoCorrectionService extends EventEmitter { this._cancelCheck() } - if (!this._eligible(context)) return 'pass' - if (context.idleMs < TYPO_MIN_IDLE_MS) return 'pass' + if (!this._eligible(context, { allowComposing: true })) return 'pass' const prefix = context.prefix + const hasTrailingBoundary = /[ \t.,!?;:]$/u.test(prefix) + const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':') + const minLayoutIdle = hasTrailingBoundary + ? LAYOUT_BOUNDARY_MIN_IDLE_MS + : isVimCommand + ? LAYOUT_VIM_CMD_MIN_IDLE_MS + : LAYOUT_TRAILING_MIN_IDLE_MS + if (context.idleMs < minLayoutIdle) return 'pass' + const region = prefix.slice(typoRegionStart(prefix)) if (!region.trim() || region === this._lastCheckedRegion) return 'pass' + // Chromium/Discord 등은 영문 입력·공백 뒤에도 comp=true 를 유지하고, 한글 자판에서 ㅎ샤ㅗㅕㅠ에 를 치고 + // 멈췄을 때도 마지막 음절이 조합 중이다. 한영 전환(layoutOnly)은 조합 여부와 짧은 유휴에서도 즉시 허용하고, + // 일반 철자·모델 검사는 터미널·개발 도구가 아니고 조합이 없으며 TYPO_MIN_IDLE_MS 이상 멈췄을 때만 실행한다. + const isTerminalOrDev = + context.terminalMode === true || + isTerminalApp(context.appName) || + !shouldLearnFromApp(context.appName) + const fullCheckEligible = + options.layoutOnly !== true && + !isTerminalOrDev && + !context.isComposing && + context.idleMs >= TYPO_MIN_IDLE_MS + const ignoredWords = configGet('typoIgnoredWords') ?? [] const vocabulary = this._loadVocabulary() const keyAtDecision = this._deps.lastKeyAt() @@ -169,7 +202,9 @@ export class TypoCorrectionService extends EventEmitter { const corrections = detectTypos(prefix, { includeTrailingToken: true, ignoredWords, - vocabulary: vocabulary.latin + vocabulary: vocabulary.latin, + layoutOnly: !fullCheckEligible, + terminalMode: context.terminalMode === true || isTerminalApp(context.appName) }) const plan = planTypoReplacement(prefix, corrections) if (plan) { @@ -177,6 +212,9 @@ export class TypoCorrectionService extends EventEmitter { void this._apply(plan, context, keyAtDecision) return 'correcting' } + if (!fullCheckEligible) { + return 'pass' + } const model = configGet('typoAutoCorrectUseModel') !== false ? this._deps.warmModel() : null if (!model || !this._worthModelCheck(region)) { @@ -209,7 +247,7 @@ export class TypoCorrectionService extends EventEmitter { ): Promise { if (!this.isEnabled()) return null if (!context.available || !context.isEditable || context.isPassword || context.hasSelection) return null - if (isTerminalApp(context.appName)) return null + if (context.terminalMode === true || isTerminalApp(context.appName)) return null if (context.appName && isAppExcluded(context.appName, configGet('inputExcludedApps'))) return null const prefix = context.prefix @@ -262,15 +300,15 @@ export class TypoCorrectionService extends EventEmitter { // ── 판단 ─────────────────────────────────────────────── - private _eligible(context: TypingContext): boolean { + private _eligible(context: TypingContext, options: { allowComposing?: boolean } = {}): boolean { if (!this.isEnabled()) return false if (!context.available || !context.isEditable || context.isPassword) return false - if (context.isComposing || context.hasSelection) return false + if (context.hasSelection) return false + if (context.vimMode === 'normal') return false + if (!options.allowComposing && context.isComposing) return false if (context.caretReliable === false) return false // 사용자가 이 칸에서 방금 친 글만 고친다 — 클릭만 한 칸의 옛 텍스트는 건드리지 않는다. if (!context.editedSinceFocus || !context.typedRecently) return false - // 코드·명령어를 "교정" 하면 안 된다 — 터미널·에디터(학습 제외 앱)와 사용자 제외 앱은 뺀다. - if (isTerminalApp(context.appName) || !shouldLearnFromApp(context.appName)) return false if (context.appName && isAppExcluded(context.appName, configGet('inputExcludedApps'))) return false return true } @@ -369,25 +407,34 @@ export class TypoCorrectionService extends EventEmitter { private async _apply(plan: TypoReplacementPlan, context: TypingContext, keyAtDecision: number): Promise { if (this._deps.lastKeyAt() !== keyAtDecision) { + this._lastCheckedRegion = '' logger.debug('오타 교정 취소: 판단 뒤 키 입력이 있었다') return false } if (context.windowHandle != null) { const current = this._deps.foregroundHandle() if (current !== null && current !== context.windowHandle) { + this._lastCheckedRegion = '' logger.debug('오타 교정 취소: 포커스가 다른 창으로 옮겨 갔다') return false } } this._applying = true - // 백스페이스 + 붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다. - this._deps.expectProgrammaticKeys(plan.deleteCount + 2) + // 커서 바로 앞 글자가 완성형 한글 음절([가-힣])이고 조합 중일 때만 Space 로 조합을 확정한 뒤 지운다. + // 낱자 자모([ㄱ-ㅎㅏ-ㅣ], 예: ㅠㅕㅎ 의 ㅎ, 내ㅡㄷ 의 ㄷ, :ㅈㅂ 의 ㅂ)는 백스페이스 1번에 바로 지워지므로 + // 불필요한 Space 를 보내 앞의 글자까지 지우거나 유령 공백을 남기지 않는다. + const commitComposition = context.isComposing === true && /[가-힣]$/u.test(context.prefix) + // 확정용 Space(+2)·백스페이스 + 붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다. + this._deps.expectProgrammaticKeys(plan.deleteCount + (commitComposition ? 2 : 0) + 2) const cancelInsert = this._deps.expectProgrammaticInsert(plan.insertText) try { - const ok = await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText) + const ok = commitComposition + ? await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText, { commitComposition: true }) + : await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText) if (!ok) { cancelInsert() + this._lastCheckedRegion = '' logger.warn('오타 교정 삽입 실패') return false } @@ -395,9 +442,12 @@ export class TypoCorrectionService extends EventEmitter { corrections: plan.corrections, completedAt: Date.now(), tailLength: plan.insertText.length, - prefixLength: context.prefix.length - plan.deleteCount + plan.insertText.length + prefixLength: context.prefix.length - plan.deleteCount + plan.insertText.length, + prefixBefore: context.prefix.slice(0, Math.max(0, context.prefix.length - plan.deleteCount)), + windowHandle: context.windowHandle ?? null } - this._lastCheckedRegion = '' + // 교정에 성공한 경우에는 _lastCheckedRegion 을 비우지 않는다 — xterm-helper-textarea 등 + // 교정 뒤에도 UIA 원문이 그대로 남는 컨트롤에서 같은 구간을 무한 재교정하는 루프를 막는다. const sources = [...new Set(plan.corrections.map((correction) => correction.source))].join(',') // 사용자가 친 원문은 로그에 남기지 않는다 — 개수와 근거만. logger.info(`오타 교정 ${plan.corrections.length}건 (${sources}, app=${context.appName ?? '-'})`) @@ -405,6 +455,7 @@ export class TypoCorrectionService extends EventEmitter { return true } catch (error) { cancelInsert() + this._lastCheckedRegion = '' logger.warn(`오타 교정 예외: ${error instanceof Error ? error.message : String(error)}`) return false } finally { @@ -425,8 +476,24 @@ export class TypoCorrectionService extends EventEmitter { return } if (context.capturedAt <= applied.completedAt + 200 || !context.available) return + if (applied.windowHandle !== null && context.windowHandle != null && context.windowHandle !== applied.windowHandle) { + this._lastApplied = null + return + } + if (context.prefix.length === 0 || !context.prefix.startsWith(applied.prefixBefore)) { + this._lastApplied = null + return + } if (Math.abs(context.prefix.length - applied.prefixLength) > REVERT_LENGTH_TOLERANCE) return + const suffixAfterBefore = context.prefix.slice(applied.prefixBefore.length) for (const correction of applied.corrections) { + // 낱자로 풀린 한글 오타(ㅗ디ㅣㅐ, ㅎ샤ㅗㅕㅠ 등)는 다시 쳤더라도 영구 무시 목록에 넣지 않는다. + if (/[ㄱ-ㆎ]/u.test(correction.from) && !/^[ㅋㅎㅠㅜㅇ]+$/u.test(correction.from)) { + continue + } + if (!suffixAfterBefore.trimStart().startsWith(correction.from)) { + continue + } if (!detectTypoRevert(context.prefix, { from: correction.from, to: correction.to, tailLength: applied.tailLength })) { continue } @@ -439,6 +506,7 @@ export class TypoCorrectionService extends EventEmitter { } private _ignoreWord(word: string): void { + if (/[ㄱ-ㆎ]/u.test(word) && !/^[ㅋㅎㅠㅜㅇ]+$/u.test(word)) return const current = configGet('typoIgnoredWords') ?? [] if (current.some((entry) => entry.toLowerCase() === word.toLowerCase())) return configSet('typoIgnoredWords', [...current, word].slice(-TYPO_IGNORED_WORDS_MAX)) diff --git a/apps/desktop/src/main/services/UiaContextService.ts b/apps/desktop/src/main/services/UiaContextService.ts index c22afd3..acb412d 100644 --- a/apps/desktop/src/main/services/UiaContextService.ts +++ b/apps/desktop/src/main/services/UiaContextService.ts @@ -32,7 +32,7 @@ const REQUEST_TIMEOUT_MS = 1500 * 사이드카 준비는 1.1초 후였다. 20초를 통째로 백오프하면 앱을 켠 직후의 입력이 전부 죽으므로 * 일시 실패는 짧게 시작해 배수로 늘리고, 브리지 자체가 없는 경우(미지원 플랫폼)만 길게 잡는다. */ -const BACKOFF_STEPS_MS = [1500, 3000, 6000, 12000, 30000] as const +const BACKOFF_STEPS_MS = [300, 600, 1200, 2500] as const /** 영구 실패(브리지 없음) 백오프 */ const BACKOFF_PERMANENT_MS = 5 * 60 * 1000 @@ -170,6 +170,7 @@ class UiaContextService { this._last = snapshot this._lastSuccessAt = now this._backoffUntil = 0 + this._failureStreak = 0 this._lastReason = '' return snapshot } diff --git a/apps/desktop/src/main/services/UpdateService.ts b/apps/desktop/src/main/services/UpdateService.ts index 7992e16..ee532de 100644 --- a/apps/desktop/src/main/services/UpdateService.ts +++ b/apps/desktop/src/main/services/UpdateService.ts @@ -21,6 +21,7 @@ import { EventEmitter } from 'events' import { randomUUID } from 'node:crypto' import { app } from 'electron' +import type { AppUpdateStatus } from '@d3ro/core/types' import { getLogger } from './LoggerService' import { configGet, configGetAll, configSet } from './ConfigService' import { UPDATE_FEED_URL, isUpdateChannel, type UpdateChannel } from '../update-feed' @@ -100,6 +101,8 @@ export interface UpdateServiceEvents { 'download-progress': UpdateProgressPayload 'update-downloaded': { version: string } 'update-error': { message: string } + /** 설정 화면·타이틀바가 보여 줄 현재 상태 — 위 이벤트가 날 때마다 함께 나간다 */ + 'status-changed': AppUpdateStatus } export interface UpdateServiceDeps { @@ -131,6 +134,7 @@ class UpdateService extends EventEmitter { private _offeredVersion: string | null = null /** 재시작 대화상자 중복 방지 */ private _restartPrompting = false + private _status: AppUpdateStatus private readonly _deps: UpdateServiceDeps constructor(deps: Partial = {}) { @@ -142,6 +146,17 @@ class UpdateService extends EventEmitter { currentVersion: deps.currentVersion ?? (() => app.getVersion()), now: deps.now ?? (() => Date.now()), } + this._status = { + phase: 'idle', + currentVersion: this._deps.currentVersion(), + channel: this._channel, + version: null, + isMandatory: false, + skipped: false, + progress: null, + lastCheckedAt: null, + error: null, + } } /** 자동 업데이트 시작. 비활성 조건이면 로그만 남기고 no-op. */ @@ -153,6 +168,8 @@ class UpdateService extends EventEmitter { onChecking: () => { logger.info('업데이트 확인 중...') this.emit('checking-for-update', undefined as unknown as void) + // 받는 중·받아 둔 상태는 확인 중이라고 덮지 않는다 + if (!this._session.payload) this._setStatus({ phase: 'checking', error: null }) }, onAvailable: (info) => { logger.info(`업데이트 발견: v${info.version} (채널 ${this._channel})`) @@ -161,12 +178,17 @@ class UpdateService extends EventEmitter { onNotAvailable: (version) => { logger.info(`최신 버전 사용 중: v${version}`) this.emit('update-not-available', { version }) + this._setStatus({ phase: 'up-to-date', version: null, isMandatory: false, skipped: false, lastCheckedAt: this._deps.now() }) + }, + onProgress: (progress) => { + this.emit('download-progress', progress) + this._setStatus({ phase: 'downloading', progress }) }, - onProgress: (progress) => this.emit('download-progress', progress), onDownloaded: (version) => { this._dispatch({ type: 'download-finished', version }) logger.info(`업데이트 다운로드 완료: v${version}`) this.emit('update-downloaded', { version }) + this._setStatus({ phase: 'downloaded', version, progress: null, error: null }) // 동기로 판단해야 한다 — electron-updater 는 이 이벤트 직후 autoInstallOnAppQuit 를 보고 종료 핸들러를 건다. this._run({ type: 'download-finished' }) }, @@ -174,9 +196,13 @@ class UpdateService extends EventEmitter { this._failDownload() logger.warn(`업데이트 체크 또는 다운로드 실패: ${message}`) this.emit('update-error', { message }) + this._setStatus({ phase: 'error', error: message, progress: null, lastCheckedAt: this._deps.now() }) }, }) - if (!this._updater) return + if (!this._updater) { + this._setStatus({ phase: 'disabled' }) + return + } this._applyChannel(this._resolveChannel(DEFAULT_UPDATE_POLICY)) this._initialTimer = setTimeout(() => void this.checkForUpdates(), INITIAL_CHECK_DELAY_MS) @@ -195,6 +221,7 @@ class UpdateService extends EventEmitter { this._run({ type: 'policy-refreshed' }) if (this._policy.killSwitch) { logger.info('원격 킬 스위치 활성 — 업데이트 확인 중단') + if (!this._session.payload) this._setStatus({ phase: 'up-to-date', lastCheckedAt: this._deps.now() }) return } if (this._session.payload?.phase === 'downloading') return @@ -213,9 +240,24 @@ class UpdateService extends EventEmitter { /** 사용자 수락 시 업데이트 다운로드 시작 — 업데이터가 마지막으로 알린 버전에 대한 동의로 본다. */ async startDownload(): Promise { if (!this._offeredVersion) return + // 설정 화면에서 직접 받기를 눌렀다 — 예전에 건너뛴 버전이어도 이번엔 받겠다는 뜻이다. + if (this._skippedVersion() === this._offeredVersion) configSet('skippedUpdateVersion', null) await this._consent(this._offeredVersion) } + /** 받아 둔 업데이트를 지금 설치한다(재시작). 설치 직전에 정책을 다시 받는다 — 킬 스위치가 켜졌을 수 있다. */ + async installNow(): Promise { + const payload = this._session.payload + if (!this._updater || payload?.phase !== 'downloaded') return + await this._refreshPolicy() + this._run({ type: 'restart-answered', answer: 'restart' }) + } + + /** 설정 화면·타이틀바용 현재 상태 */ + getStatus(): AppUpdateStatus { + return { ...this._status, channel: this._channel, currentVersion: this._deps.currentVersion() } + } + /** 이번 버전 건너뛰기 설정 */ skipVersion(version: string): void { configSet('skippedUpdateVersion', version) @@ -260,6 +302,17 @@ class UpdateService extends EventEmitter { if (offer.action === 'ignore') { logger.info(`v${info.version} 제안 무시 — ${this._describeBlock(offer.reason)}`) + // 사용자가 건너뛴 버전만 화면에 남긴다(직접 받을 수 있게). 운영 정책으로 막힌 버전은 최신으로 보인다. + const skipped = offer.reason === 'skipped' + if (!this._session.payload) { + this._setStatus({ + phase: skipped ? 'available' : 'up-to-date', + version: skipped ? info.version : null, + isMandatory: false, + skipped, + lastCheckedAt: this._deps.now(), + }) + } return } @@ -274,6 +327,16 @@ class UpdateService extends EventEmitter { isFullDownload: decision.forceFull, reason: decision.reason, }) + if (!this._session.payload) { + this._setStatus({ + phase: 'available', + version: info.version, + isMandatory: decision.mandatory, + skipped: false, + error: null, + lastCheckedAt: this._deps.now(), + }) + } // 이미 받아 둔 버전은 다시 묻지 않는다. 다시 물으면 '건너뛰기'를 골라도 종료 시 설치돼 버린다. const pending = this._session.payload @@ -357,6 +420,13 @@ class UpdateService extends EventEmitter { // major 승격 또는 버전 갭이면 차분 패치를 시도하지 않는다 (받는 시점의 정책·버전으로 정한다). updater.setDifferentialDisabled(decision.forceFull) this._dispatch({ type: 'download-started', version }) + this._setStatus({ + phase: 'downloading', + version, + isMandatory: decision.mandatory, + error: null, + progress: { percent: 0, transferred: 0, total: 0, bytesPerSecond: 0 }, + }) logger.info( decision.forceFull ? `v${version} 전체 설치자 다운로드 시작 (major/버전갭)` @@ -366,7 +436,9 @@ class UpdateService extends EventEmitter { await updater.downloadUpdate() } catch (err) { this._failDownload() - logger.warn(`업데이트 다운로드 실패: ${err instanceof Error ? err.message : String(err)}`) + const message = err instanceof Error ? err.message : String(err) + logger.warn(`업데이트 다운로드 실패: ${message}`) + this._setStatus({ phase: 'error', error: message, progress: null }) } } @@ -391,6 +463,11 @@ class UpdateService extends EventEmitter { } } + private _setStatus(patch: Partial): void { + this._status = { ...this._status, ...patch } + this.emit('status-changed', this.getStatus()) + } + // ── 내부: 정책 · 설정 ── private async _refreshPolicy(): Promise { diff --git a/apps/desktop/src/main/services/keybinding-accelerator-policy.ts b/apps/desktop/src/main/services/keybinding-accelerator-policy.ts index 491c459..9b214a7 100644 --- a/apps/desktop/src/main/services/keybinding-accelerator-policy.ts +++ b/apps/desktop/src/main/services/keybinding-accelerator-policy.ts @@ -18,6 +18,7 @@ const RESERVING_PLATFORMS: ReadonlySet = new Set(['darwin']) /** 제안 오버레이 전용 액션. 제안 기능이 꺼져 있으면 예약하지 않는다. */ const SUGGESTION_ACTIONS: ReadonlySet = new Set([ 'suggestion-accept', + 'suggestion-accept-word', 'suggestion-next', 'suggestion-prev', 'suggestion-dismiss' diff --git a/apps/desktop/src/main/services/llm-prompts.ts b/apps/desktop/src/main/services/llm-prompts.ts index 8a36822..4e09528 100644 --- a/apps/desktop/src/main/services/llm-prompts.ts +++ b/apps/desktop/src/main/services/llm-prompts.ts @@ -325,7 +325,8 @@ const SEARCH_CONTEXT = /(google|naver|네이버|daum|다음 검색|bing|duckduck function looksLikeSearchInput(input: SuggestionPromptInput, raw: string): boolean { const where = `${input.appName ?? ''} ${input.windowTitle ?? ''}` const text = raw.trim() - return SEARCH_CONTEXT.test(where) && text.length > 0 && text.length <= 60 && !/[.!?。\n]/u.test(text) + if (/[.!?。\n@/]/u.test(text)) return false + return SEARCH_CONTEXT.test(where) && text.length > 0 && text.length <= 60 } function formatAge(ageMs: number): string { diff --git a/apps/desktop/src/main/services/modifier-state.ts b/apps/desktop/src/main/services/modifier-state.ts index 3b9a68f..7bdacb9 100644 --- a/apps/desktop/src/main/services/modifier-state.ts +++ b/apps/desktop/src/main/services/modifier-state.ts @@ -9,7 +9,7 @@ import { uIOhook, type UiohookKeyboardEvent } from 'uiohook-napi' import { acquireGlobalInputHook } from './global-input-hook' -import { isAnyModifierPhysicallyDown } from '../utils/win32-key-state' +import { isAnyChordKeyPhysicallyDown, isAnyModifierPhysicallyDown } from '../utils/win32-key-state' /** uiohook 키 코드 (UiohookKey.Ctrl/CtrlRight/Alt/AltRight/Shift/ShiftRight/Meta/MetaRight) */ const MODIFIER_KEYCODES: ReadonlySet = new Set([29, 3613, 56, 3640, 42, 54, 3675, 3676]) @@ -64,3 +64,28 @@ export async function waitForModifiersReleased( held.clear() return false } + +/** + * 단축키 수락 뒤 손을 기다리는 최대 시간. 사용자는 글이 들어오는 걸 보려고 키를 쥔 채 기다리기도 한다 — + * 그동안 제안 창은 그대로 떠 있고, 손을 떼는 순간 넣는다. 이 시간을 넘기면 넣지 않는다. + */ +const PASTE_RELEASE_WAIT_MS = 5000 + +export type ModifierPreparation = 'released' | 'still-held' + +/** + * 붙여넣기(Ctrl+V)를 보내기 전에 사용자가 단축키(수정자 + Enter/Space)를 모두 뗄 때까지 기다린다. + * + * 키 상태는 절대 꾸미지 않는다 — 2026-10-25 에 수정자를 "뗀 것으로" 보냈더니 아직 눌린 Enter 가 그냥 Enter 가 + * 되어 채팅 앱이 쓰던 메시지를 보냈다. 끝내 안 떼면 'still-held' — 호출자는 넣지 않고 취소한다(Ctrl+Alt+V 금지). + */ +export async function prepareModifiersForPaste( + deps: { + readPhysicalState?: () => boolean | null + timeoutMs?: number + } = {} +): Promise { + const read = deps.readPhysicalState ?? isAnyChordKeyPhysicallyDown + const released = await waitForModifiersReleased(deps.timeoutMs ?? PASTE_RELEASE_WAIT_MS, read) + return released ? 'released' : 'still-held' +} diff --git a/apps/desktop/src/main/services/suggestion/PersonalNgramIndex.ts b/apps/desktop/src/main/services/suggestion/PersonalNgramIndex.ts new file mode 100644 index 0000000..90b5776 --- /dev/null +++ b/apps/desktop/src/main/services/suggestion/PersonalNgramIndex.ts @@ -0,0 +1,71 @@ +// src/main/services/suggestion/PersonalNgramIndex.ts +// +// 개인 n-gram 예측기(core PersonalNgramModel)를 typing_samples 로 만들어 메모리에 들고 있는다. +// +// - 처음 쓸 때 만든다(표본 수천 개 — 수십 ms). 학습이 표본을 넣으면 add 로 바로 반영한다. +// - 표본·문구를 지우면(문구 삭제·전체 삭제·보존 정리·코퍼스 정리) invalidate — 다음 사용 때 다시 만든다. +// 지운 글이 제안으로 다시 나오면 안 된다. +// - 계정을 바꾸면 DB 가 바뀐다 — 만든 DB 가 지금 DB 가 아니면 다시 만든다(다른 계정 글이 섞이지 않게). + +import { PersonalNgramModel } from '@d3ro/core/personal-ngram' +import { getDatabase } from '../../db' +import { typingSamples } from '../../db/schema' +import { getLogger } from '../LoggerService' + +const logger = getLogger('PersonalNgramIndex') + +type Database = ReturnType + +export class PersonalNgramIndex { + private _model: PersonalNgramModel | null = null + private _builtFor: Database | null = null + + constructor( + private readonly _database: () => Database = getDatabase, + private readonly _now: () => number = () => Date.now() + ) {} + + /** 지금 DB 의 예측기. DB 를 못 열면 null (제안은 LLM 경로로 간다). */ + model(): PersonalNgramModel | null { + let db: Database + try { + db = this._database() + } catch { + return null + } + if (this._model && this._builtFor === db) return this._model + const startedAt = this._now() + try { + const model = new PersonalNgramModel() + for (const row of db.select({ text: typingSamples.text }).from(typingSamples).all()) model.addText(row.text) + this._model = model + this._builtFor = db + logger.info(`개인 n-gram 생성: 표본 ${model.textCount}개 (${this._now() - startedAt}ms)`) + return model + } catch (error) { + logger.warn(`개인 n-gram 생성 실패: ${error instanceof Error ? error.message : String(error)}`) + return null + } + } + + /** 새로 저장한 표본을 반영한다 — 아직 만들기 전이면 다음 생성 때 DB 에서 읽힌다. */ + add(text: string): void { + this._model?.addText(text) + } + + invalidate(): void { + this._model = null + this._builtFor = null + } +} + +let instance: PersonalNgramIndex | null = null + +export function getPersonalNgramIndex(): PersonalNgramIndex { + if (!instance) instance = new PersonalNgramIndex() + return instance +} + +export function resetPersonalNgramIndexForTests(): void { + instance = null +} diff --git a/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts b/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts index 22bf20e..3d7ebe2 100644 --- a/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts +++ b/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts @@ -4,6 +4,7 @@ import type { Key as NutKey } from '@nut-tree-fork/nut-js' import { getLogger } from '../LoggerService' +import { sendWin32UnicodeText } from '../../utils/win32-unicode-input' import { D3ROError, ErrorCode } from '@d3ro/core/errors' const logger = getLogger('TextInsertService') @@ -99,6 +100,9 @@ export class NutKeyboardPort implements KeyboardPort { /** 텍스트 전체를 네이티브 호출 한 번으로 타이핑한다 (글자 사이 JS 대기 없음). */ async type(text: string): Promise { if (!text) return + if (this._platform === 'win32' && this._load === loadNutModule && sendWin32UnicodeText(text)) { + return + } const nut = await this._ensureNut() await nut.native.type(text) } diff --git a/apps/desktop/src/main/utils/win32-foreground.ts b/apps/desktop/src/main/utils/win32-foreground.ts index 6d1bb34..21e139a 100644 --- a/apps/desktop/src/main/utils/win32-foreground.ts +++ b/apps/desktop/src/main/utils/win32-foreground.ts @@ -37,20 +37,46 @@ interface KoffiRect { bottom: number } +interface KoffiGuiThreadInfo { + cbSize: number + flags: number + hwndActive: number | bigint | null + hwndFocus: number | bigint | null + hwndCapture: number | bigint | null + hwndMenuOwner: number | bigint | null + hwndMoveSize: number | bigint | null + hwndCaret: number | bigint | null + rcCaretLeft: number + rcCaretTop: number + rcCaretRight: number + rcCaretBottom: number +} + type AnyFunc = (...args: unknown[]) => unknown interface Win32Api { - koffi: { decode: (buffer: Buffer, type: string, length: number) => string } + koffi: { + decode: (buffer: Buffer, type: string, length: number) => string + sizeof: (type: unknown) => number + } + guiThreadInfoType: unknown GetForegroundWindow: AnyFunc GetWindowTextW: AnyFunc GetWindowThreadProcessId: AnyFunc + GetGUIThreadInfo: AnyFunc GetWindowRect: AnyFunc + ImmGetDefaultIMEWnd: AnyFunc + SendMessageTimeoutW: AnyFunc OpenProcess: AnyFunc QueryFullProcessImageNameW: AnyFunc CloseHandle: AnyFunc } const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 +const WM_IME_CONTROL = 0x0283 +const IMC_GETCONVERSIONMODE = 0x0001 +const IME_CMODE_NATIVE = 0x0001 +const SMTO_ABORTIFHUNG = 0x0002 const TITLE_BUFFER_CHARS = 512 const PATH_BUFFER_CHARS = 1024 @@ -71,13 +97,30 @@ function loadApi(): Win32Api | null { load: (lib: string) => { func: (signature: string) => AnyFunc } struct: (name: string, fields: Record) => unknown decode: (buffer: Buffer, type: string, length: number) => string + sizeof: (type: unknown) => number } const user32 = koffi.load('user32.dll') const kernel32 = koffi.load('kernel32.dll') + const imm32 = koffi.load('imm32.dll') koffi.struct('RECT', { left: 'long', top: 'long', right: 'long', bottom: 'long' }) + const guiThreadInfoType = koffi.struct('D3RO_GUITHREADINFO', { + cbSize: 'uint32_t', + flags: 'uint32_t', + hwndActive: 'void *', + hwndFocus: 'void *', + hwndCapture: 'void *', + hwndMenuOwner: 'void *', + hwndMoveSize: 'void *', + hwndCaret: 'void *', + rcCaretLeft: 'long', + rcCaretTop: 'long', + rcCaretRight: 'long', + rcCaretBottom: 'long' + }) api = { - koffi: { decode: koffi.decode }, + koffi: { decode: koffi.decode, sizeof: koffi.sizeof }, + guiThreadInfoType, GetForegroundWindow: user32.func('void *GetForegroundWindow()'), GetWindowTextW: user32.func( 'int GetWindowTextW(void *hWnd, _Out_ uint16_t *lpString, int nMaxCount)' @@ -85,7 +128,14 @@ function loadApi(): Win32Api | null { GetWindowThreadProcessId: user32.func( 'uint32_t GetWindowThreadProcessId(void *hWnd, _Out_ uint32_t *lpdwProcessId)' ), + GetGUIThreadInfo: user32.func( + 'bool GetGUIThreadInfo(uint32_t idThread, _Inout_ D3RO_GUITHREADINFO *pgui)' + ), GetWindowRect: user32.func('bool GetWindowRect(void *hWnd, _Out_ RECT *rect)'), + ImmGetDefaultIMEWnd: imm32.func('void *ImmGetDefaultIMEWnd(void *hWnd)'), + SendMessageTimeoutW: user32.func( + 'intptr_t SendMessageTimeoutW(void *hWnd, uint32_t Msg, uintptr_t wParam, intptr_t lParam, uint32_t fuFlags, uint32_t uTimeout, _Out_ uintptr_t *lpdwResult)' + ), OpenProcess: kernel32.func('void *OpenProcess(uint32_t access, bool inherit, uint32_t pid)'), QueryFullProcessImageNameW: kernel32.func( 'bool QueryFullProcessImageNameW(void *hProcess, uint32_t flags, _Out_ uint16_t *lpExeName, _Inout_ uint32_t *size)' @@ -173,6 +223,72 @@ export function getForegroundWindowInfo(): ForegroundWindowInfo | null { } } +/** + * 포그라운드(또는 지정 HWND)의 Windows IME 가 현재 한글(Native) 상태인지 확인한다. + * - true: 한글 입력 상태 (openStatus != 0 && (conversionMode & IME_CMODE_NATIVE) != 0) + * - false: 영문 입력 상태 + * - null: 비-Windows 또는 조회 불가 + */ +export function isForegroundKoreanIme(foregroundHwnd?: number | null): boolean | null { + const a = loadApi() + if (!a) return null + + try { + const rawFg = + foregroundHwnd && foregroundHwnd > 0 + ? foregroundHwnd + : (a.GetForegroundWindow() as bigint | number | null) + const fg = Number(rawFg ?? 0) + if (!Number.isFinite(fg) || fg <= 0) return null + + const pidBuffer = Buffer.alloc(4) + const tid = Number(a.GetWindowThreadProcessId(fg, pidBuffer) ?? 0) + let targetHwnd = fg + if (tid > 0) { + const gui: KoffiGuiThreadInfo = { + cbSize: a.koffi.sizeof(a.guiThreadInfoType), + flags: 0, + hwndActive: null, + hwndFocus: null, + hwndCapture: null, + hwndMenuOwner: null, + hwndMoveSize: null, + hwndCaret: null, + rcCaretLeft: 0, + rcCaretTop: 0, + rcCaretRight: 0, + rcCaretBottom: 0 + } + if (a.GetGUIThreadInfo(tid, gui)) { + const focus = Number(gui.hwndFocus ?? 0) + const active = Number(gui.hwndActive ?? 0) + if (focus > 0) targetHwnd = focus + else if (active > 0) targetHwnd = active + } + } + + const imeWnd = Number((a.ImmGetDefaultIMEWnd(targetHwnd) as bigint | number | null) ?? 0) + if (!Number.isFinite(imeWnd) || imeWnd <= 0) return null + + const convOut = [0] + const convRes = a.SendMessageTimeoutW( + imeWnd, + WM_IME_CONTROL, + IMC_GETCONVERSIONMODE, + 0, + SMTO_ABORTIFHUNG, + 30, + convOut + ) + if (Number(convRes) === 0) return null + // Windows 한국어 IME(TSF/Chromium 포함)는 한/영('가'/'A') 상태를 IMC_GETOPENSTATUS 가 아니라 + // IMC_GETCONVERSIONMODE 의 IME_CMODE_NATIVE(0x0001) 비트로 나타낸다. + return (Number(convOut[0]) & IME_CMODE_NATIVE) !== 0 + } catch { + return null + } +} + /** 테스트 전용 — 지연 로드 상태 초기화. */ export function resetWin32ForegroundForTests(): void { api = null diff --git a/apps/desktop/src/main/utils/win32-key-state.ts b/apps/desktop/src/main/utils/win32-key-state.ts index a7e104c..fdbbf38 100644 --- a/apps/desktop/src/main/utils/win32-key-state.ts +++ b/apps/desktop/src/main/utils/win32-key-state.ts @@ -1,11 +1,12 @@ // src/main/utils/win32-key-state.ts // -// koffi(FFI)로 OS 가 보는 실제 수정자 키 눌림 상태를 읽는다 (GetAsyncKeyState). +// koffi(FFI)로 OS 가 보는 실제 키 눌림 상태를 읽는다 (GetAsyncKeyState). // -// 왜 필요한가: uiohook 은 떼는 이벤트를 놓칠 수 있다(관리자 권한 창에서 뗀 키, 보안 데스크톱 등). -// 그러면 추적 집합에 키가 눌린 채 남아 제안 수락이 매번 1.5초 시간 초과까지 기다렸고, -// 그 사이 사용자가 실제로 쥐고 있던 키와 섞여 Ctrl+V 가 Ctrl+Alt+V 로 들어가 삽입되지 않았다 -// (실측 2026-10-24: 대기 1505ms 후 "삽입 성공" 로그, 입력창 길이는 그대로). +// 왜 필요한가: 단축키(Ctrl+Alt+Enter)로 제안을 수락하면 그 순간 사용자는 키를 쥐고 있다. 그대로 Ctrl+V 를 +// 보내면 대상 앱에는 Ctrl+Alt+V 가 들어가 붙여넣기가 되지 않는다. +// - 1차(2026-10-24): uiohook 이 keyup 을 놓쳐 추적 상태가 눌린 채 남았다 → OS 상태를 정본으로. +// - 2차(2026-10-25): 수정자를 앱이 "뗀 것으로" 보내 봤다 → Enter 가 아직 눌려 있으면 그냥 Enter 가 되어 +// 채팅 앱이 쓰던 메시지를 보내 버렸다(실측 2회). 키 상태는 절대 꾸미지 않는다 — 사용자가 뗄 때까지 기다린다. // // 실패(비 Windows, 모듈 로드 실패)는 null — 호출자는 uiohook 추적으로 돌아간다. @@ -15,6 +16,8 @@ const logger = getLogger('win32-key-state') /** VK_SHIFT, VK_CONTROL, VK_MENU(Alt), VK_LWIN, VK_RWIN */ const MODIFIER_VKS = [0x10, 0x11, 0x12, 0x5b, 0x5c] as const +/** 제안 단축키의 본 키 — 이것도 떼야 한다(쥔 채면 자동 반복이 앱에 들어갈 수 있다): Enter, Space */ +const CHORD_KEY_VKS = [0x0d, 0x20] as const type GetAsyncKeyState = (vk: number) => number @@ -46,14 +49,23 @@ function load(): GetAsyncKeyState | null { } } -/** 수정자 키(Ctrl/Alt/Shift/Win) 중 하나라도 지금 물리적으로 눌려 있는지. 알 수 없으면 null. */ -export function isAnyModifierPhysicallyDown(): boolean | null { +function anyDown(vks: readonly number[]): boolean | null { const read = load() if (!read) return null try { // 최상위 비트(0x8000)가 "지금 눌림" — int16 이라 음수로 온다. - return MODIFIER_VKS.some((vk) => (read(vk) & 0x8000) !== 0) + return vks.some((vk) => (read(vk) & 0x8000) !== 0) } catch { return null } } + +/** 수정자 키(Ctrl/Alt/Shift/Win) 중 하나라도 지금 물리적으로 눌려 있는지. 알 수 없으면 null. */ +export function isAnyModifierPhysicallyDown(): boolean | null { + return anyDown(MODIFIER_VKS) +} + +/** 수정자 + 제안 단축키 본 키(Enter/Space) 중 하나라도 눌려 있는지. 알 수 없으면 null. */ +export function isAnyChordKeyPhysicallyDown(): boolean | null { + return anyDown([...MODIFIER_VKS, ...CHORD_KEY_VKS]) +} diff --git a/apps/desktop/src/main/utils/win32-unicode-input.ts b/apps/desktop/src/main/utils/win32-unicode-input.ts new file mode 100644 index 0000000..858bcbb --- /dev/null +++ b/apps/desktop/src/main/utils/win32-unicode-input.ts @@ -0,0 +1,118 @@ +// src/main/utils/win32-unicode-input.ts +// +// Windows SendInput(KEYEVENTF_UNICODE) 기반 유니코드 직접 타이핑. +// +// 왜 필요한가: +// 1) @nut-tree-fork/libnut 의 typeString 은 ASCII(a-z)에 VkKeyScan 을 써서 한글 IME 가 켜져 있으면 +// 'hello' 가 다시 'ㅗ디ㅣㅐ' 로 입력된다. +// 2) 클립보드(Ctrl+V) 방식은 Windows ClipboardSvcGroup(WM_CLIPBOARDUPDATE) 이 클립보드를 여는 +// ~15-35ms 동안 대상 앱의 WM_PASTE(OpenClipboard 재시도 없음)가 간헐적으로 실패하고, 사용자의 +// 클립보드 히스토리(Win+V)를 오염시킨다. +// 3) KEYEVENTF_UNICODE(wVk=0, wScan=utf16CodeUnit) 는 VK_PACKET -> WM_CHAR 로 전달되어 한글/영문 +// IME 상태를 타지 않고 클립보드도 전혀 건드리지 않는다. + +import { getLogger } from '../services/LoggerService' + +const logger = getLogger('win32-unicode-input') + +const INPUT_KEYBOARD = 1 +const KEYEVENTF_KEYUP = 0x0002 +const KEYEVENTF_UNICODE = 0x0004 + +type SendInputFn = (cInputs: number, pInputs: Buffer, cbSize: number) => number + +let sendInputFn: SendInputFn | null = null +let inputStructSize = 0 +let unionOffset = 0 +let loadFailed = false + +function ensureLoaded(): SendInputFn | null { + if (sendInputFn) return sendInputFn + if (loadFailed) return null + if (process.platform !== 'win32') { + loadFailed = true + return null + } + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const koffi = require('koffi') as { + struct: (name: string, fields: Record) => unknown + union: (name: string, fields: Record) => unknown + sizeof: (type: unknown) => number + offsetof: (type: unknown, field: string) => number + load: (lib: string) => { func: (signature: string) => SendInputFn } + } + const KEYBDINPUT = koffi.struct('Win32KeybdInput', { + wVk: 'uint16', + wScan: 'uint16', + dwFlags: 'uint32', + time: 'uint32', + dwExtraInfo: 'uintptr_t' + }) + const MOUSEINPUT = koffi.struct('Win32MouseInput', { + dx: 'int32', + dy: 'int32', + mouseData: 'uint32', + dwFlags: 'uint32', + time: 'uint32', + dwExtraInfo: 'uintptr_t' + }) + const INPUT_UNION = koffi.union('Win32InputUnion', { + mi: MOUSEINPUT, + ki: KEYBDINPUT + }) + const INPUT = koffi.struct('Win32Input', { + type: 'uint32', + u: INPUT_UNION + }) + inputStructSize = koffi.sizeof(INPUT) + unionOffset = koffi.offsetof(INPUT, 'u') + sendInputFn = koffi.load('user32.dll').func('uint32 SendInput(uint32 cInputs, void *pInputs, int cbSize)') + return sendInputFn + } catch (error) { + loadFailed = true + logger.warn( + `SendInput(KEYEVENTF_UNICODE) 로드 실패 — nut-js 경로로 폴백 (${ + error instanceof Error ? error.message : String(error) + })` + ) + return null + } +} + +/** + * UTF-16 문자열을 Windows SendInput(KEYEVENTF_UNICODE) 호출 한 번으로 입력 큐에 넣는다. + * 성공 시 true, 지원하지 않거나 실패 시 false 를 반환한다. + */ +export function sendWin32UnicodeText(text: string): boolean { + if (!text) return true + const sendInput = ensureLoaded() + if (!sendInput || inputStructSize <= 0) return false + + try { + const codeUnits = text.length + const totalEvents = codeUnits * 2 + const buffer = Buffer.alloc(totalEvents * inputStructSize) + + for (let i = 0; i < codeUnits; i += 1) { + const code = text.charCodeAt(i) + const downBase = i * 2 * inputStructSize + buffer.writeUInt32LE(INPUT_KEYBOARD, downBase) + buffer.writeUInt16LE(0, downBase + unionOffset) + buffer.writeUInt16LE(code, downBase + unionOffset + 2) + buffer.writeUInt32LE(KEYEVENTF_UNICODE, downBase + unionOffset + 4) + + const upBase = (i * 2 + 1) * inputStructSize + buffer.writeUInt32LE(INPUT_KEYBOARD, upBase) + buffer.writeUInt16LE(0, upBase + unionOffset) + buffer.writeUInt16LE(code, upBase + unionOffset + 2) + buffer.writeUInt32LE(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, upBase + unionOffset + 4) + } + + const sent = sendInput(totalEvents, buffer, inputStructSize) + return sent === totalEvents + } catch (error) { + logger.warn(`SendInput(KEYEVENTF_UNICODE) 실행 실패: ${error instanceof Error ? error.message : String(error)}`) + return false + } +} diff --git a/apps/desktop/src/main/windows/WindowManager.ts b/apps/desktop/src/main/windows/WindowManager.ts index 232234a..0873323 100644 --- a/apps/desktop/src/main/windows/WindowManager.ts +++ b/apps/desktop/src/main/windows/WindowManager.ts @@ -100,6 +100,7 @@ function getPopupI18nStrings(): Record { suggestionLoading: t('popup.suggestion.loading'), // 경과 초가 붙는 "생성 중 {{s}}초" — 빠져 있어 script.js 가 loading 으로 떨어졌다(2026-09-28) suggestionGenerating: t('popup.suggestion.generating'), + suggestionNone: t('popup.suggestion.none'), suggestionSourceModel: t('popup.suggestion.sourceModel'), suggestionSourceMemory: t('popup.suggestion.sourceMemory'), suggestionContinuations: t('popup.suggestion.continuations'), @@ -109,6 +110,7 @@ function getPopupI18nStrings(): Record { // 키 힌트 줄 (동작 낱말 — 실제 키는 사용자 바인딩에서 매번 계산해 붙인다) suggestionHintMoveLabel: t('popup.suggestion.hintMove'), suggestionHintAcceptLabel: t('popup.suggestion.hintAccept'), + suggestionHintWordLabel: t('popup.suggestion.hintWord'), suggestionCorrectionLabel: t('popup.suggestion.correctionLabel'), suggestionHintCloseLabel: t('popup.suggestion.hintDismiss'), suggestionHintGeneratingMore: t('popup.suggestion.hintGeneratingMore'), @@ -141,6 +143,8 @@ export interface SuggestionKeyHints { shared: string | null move: string | null accept: string | null + /** 첫 단어만 받기 */ + word: string | null close: string } @@ -163,6 +167,7 @@ function buildSuggestionKeyHints(): SuggestionKeyHints { const prev = splitOf('suggestion-prev') const next = splitOf('suggestion-next') const accept = splitOf('suggestion-accept') + const word = splitOf('suggestion-accept-word') const present = [prev, next, accept].filter((b): b is SplitBinding => b !== null) const common = present[0]?.modifiers ?? [] @@ -181,6 +186,8 @@ function buildSuggestionKeyHints(): SuggestionKeyHints { shared: shareAll ? joinBindingSegments(common, platform) : null, move: pair(prev, next), accept: accept ? label(accept) : null, + // 같은 수정자를 쓰면 키만 보인다 — Space 는 "Space" 로 읽히게 그대로 둔다. + word: word ? (shareAll && sameModifiers(word.modifiers, common) ? word.key : joinBindingSegments([...word.modifiers, word.key], platform)) : null, close: 'Esc' } } @@ -858,6 +865,8 @@ interface SuggestionOverlayContent { provenance?: SuggestionOverlayProvenance | null /** 후보와 함께 적용되는 오타 교정 — 팝업이 "지운 글자 → 고친 글자" 줄을 그린다 */ correction?: SuggestionCorrection | null + /** 후보 없이 끝났음을 잠깐 알린다 ("제안 사항 없음") */ + notice?: 'no-suggestion' | null } /** 현재 세션의 배치(최대 높이 기준) — 내용이 바뀌면 이 자리에서 높이만 맞춘다. */ @@ -886,7 +895,8 @@ function fitSuggestionOverlay(win: BrowserWindow, content: SuggestionOverlayCont generating: content.generating === true, warmingUp: content.warmingUp === true, hasPartialText: !!content.partialText, - hasCorrection: !!content.correction + hasCorrection: !!content.correction, + hasNotice: !!content.notice }) ) const previous = suggestionOverlayBounds @@ -936,6 +946,7 @@ export function showSuggestionOverlay( appName: payload.appName, provenance: payload.provenance ?? null, correction: payload.correction ?? null, + notice: payload.notice ?? null, _i18n: getPopupI18nStrings(), _keyHints: buildSuggestionKeyHints() })) diff --git a/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts b/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts index 7042f18..071c228 100644 --- a/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts +++ b/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts @@ -38,12 +38,14 @@ export interface SuggestionPanelLayoutInput { hasPartialText: boolean /** 오타 교정 줄이 보이는가 (후보가 있을 때만 그린다) */ hasCorrection?: boolean + /** "제안 사항 없음" 알림 줄 — 상태 줄 자리를 쓴다 */ + hasNotice?: boolean } /** 지금 그려지는 패널(+root 패딩) 높이 — script.js render() 와 같은 규칙으로 센다. */ export function suggestionPanelHeight(input: SuggestionPanelLayoutInput): number { const count = Math.max(0, Math.floor(input.candidateCount)) - const busy = input.warmingUp || (input.generating && count === 0) + const busy = input.warmingUp || (input.generating && count === 0) || (input.hasNotice === true && count === 0) let items = 0 if (count === 0) { diff --git a/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts b/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts index 2fb365d..ebdf350 100644 --- a/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts +++ b/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts @@ -18,7 +18,15 @@ import { /** 오버레이 내용 — show 와 update 가 같이 쓴다 */ export type SuggestionOverlayContentPayload = Pick< SuggestionState, - 'candidates' | 'activeIndex' | 'targetTotal' | 'generating' | 'warmingUp' | 'partialText' | 'provenance' | 'correction' + | 'candidates' + | 'activeIndex' + | 'targetTotal' + | 'generating' + | 'warmingUp' + | 'partialText' + | 'provenance' + | 'correction' + | 'notice' > /** 새로 띄울 때만 필요한 배치 정보를 더한 payload */ @@ -39,6 +47,7 @@ export function toSuggestionOverlayContent(state: SuggestionState): SuggestionOv partialText: state.partialText, provenance: state.provenance, correction: state.correction, + notice: state.notice, } } @@ -55,7 +64,7 @@ export function toSuggestionOverlayShowPayload(state: SuggestionState): Suggesti /** 보여 줄 것(후보·생성 중·준비 중·부분 텍스트)이 있고 붙을 앵커가 있으면 표시한다. */ export function shouldPresentSuggestion(state: SuggestionState): boolean { const hasSomethingToShow = - state.candidates.length > 0 || state.generating || state.warmingUp || !!state.partialText + state.candidates.length > 0 || state.generating || state.warmingUp || !!state.partialText || !!state.notice return hasSomethingToShow && !!state.anchor } diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index fa0488f..fd6186f 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -1020,6 +1020,16 @@ const electronAPI = { onStateChanged: (cb: (state: import('@d3ro/core/input-intelligence').SuggestionState) => void): Unsubscribe => on(IPC_CHANNELS.SUGGESTION.STATE_CHANGED, cb), }, + + // ── App Update ── + appUpdate: { + getStatus: () => invoke(IPC_CHANNELS.APP_UPDATE.GET_STATUS), + check: () => invoke(IPC_CHANNELS.APP_UPDATE.CHECK), + download: () => invoke(IPC_CHANNELS.APP_UPDATE.DOWNLOAD), + install: () => invoke(IPC_CHANNELS.APP_UPDATE.INSTALL), + onStatusChanged: (cb: (status: import('@d3ro/core/types').AppUpdateStatus) => void): Unsubscribe => + on(IPC_CHANNELS.APP_UPDATE.STATUS_CHANGED, cb), + }, } as const contextBridge.exposeInMainWorld('electronAPI', electronAPI) diff --git a/apps/desktop/src/renderer/components/SettingsModal.tsx b/apps/desktop/src/renderer/components/SettingsModal.tsx index 7c7977a..bf56b01 100644 --- a/apps/desktop/src/renderer/components/SettingsModal.tsx +++ b/apps/desktop/src/renderer/components/SettingsModal.tsx @@ -28,6 +28,7 @@ import { InputConsentPanel } from './input-insights/InputConsentPanel' import { KeyBindingField } from './keybinding/KeyBindingField' import { asTranslationKey } from './keybinding/translation-key' import { SettingNote, SettingRow, SettingsSection, SETTING_CONTROL_WIDTH } from './settings/SettingsRows' +import { UpdateSection } from './settings/UpdateSection' import { useI18n, LOCALE_META } from '@d3ro/i18n' import type { Locale } from '@d3ro/i18n' import type { KeyBindingActionGroup } from '@d3ro/core/keybinding' @@ -872,6 +873,8 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose {/* ── 정보 탭 ──────────────────────────────── */} + + + {/* 업데이트 알림 — 새 버전·받는 중·설치 대기일 때만 보인다 */} + + {/* Window Controls — macOS는 네이티브 교통신호 사용 */} {!isDarwin && ( - {/* 오타 교정은 입력 맥락(수집 동의)만 있으면 제안과 따로 동작한다. */} + {/* 자동 한영 변환 및 오타 교정은 통계 수집 동의와 무관하게 기본 기능으로 동작한다. */} { + if (action === 'download') { + return ( + + ) + } + if (action === 'install') { + return ( + + ) + } + return ( + + ) + })() + + return ( + + + {message && ( + + {t(message.key, message.params)} + + )} + {status?.phase === 'downloading' && ( + + + + )} + + + ) +} diff --git a/apps/desktop/src/renderer/components/settings/update-status-model.ts b/apps/desktop/src/renderer/components/settings/update-status-model.ts new file mode 100644 index 0000000..c56ef05 --- /dev/null +++ b/apps/desktop/src/renderer/components/settings/update-status-model.ts @@ -0,0 +1,75 @@ +// src/renderer/components/settings/update-status-model.ts +// 업데이트 상태 → 화면 문구·버튼·칩 결정 (순수 로직 — 컴포넌트 테스트 환경 없이 검증한다). + +import type { AppUpdateStatus } from '@d3ro/core/types' +import type { TranslationKey } from '@d3ro/i18n' + +export interface UpdateMessage { + key: TranslationKey + params?: Record + tone: 'normal' | 'accent' | 'danger' +} + +export type UpdateAction = 'check' | 'download' | 'install' + +export function describeUpdateStatus(status: AppUpdateStatus): UpdateMessage { + const version = status.version ?? '' + switch (status.phase) { + case 'disabled': + return { key: 'update.status.disabled', tone: 'normal' } + case 'idle': + return { key: 'update.status.idle', tone: 'normal' } + case 'checking': + return { key: 'update.status.checking', tone: 'normal' } + case 'up-to-date': + return { key: 'update.status.upToDate', tone: 'normal' } + case 'available': + if (status.skipped) return { key: 'update.status.skipped', params: { version }, tone: 'accent' } + return status.isMandatory + ? { key: 'update.status.availableMandatory', params: { version }, tone: 'accent' } + : { key: 'update.status.available', params: { version }, tone: 'accent' } + case 'downloading': + return { key: 'update.status.downloading', params: { version, percent: progressPercent(status) }, tone: 'accent' } + case 'downloaded': + return { key: 'update.status.downloaded', params: { version }, tone: 'accent' } + case 'error': + return { key: 'update.status.error', params: { message: status.error ?? '' }, tone: 'danger' } + } +} + +/** 지금 누를 수 있는 주 동작. 받는 중·비활성 빌드는 없다. */ +export function primaryUpdateAction(status: AppUpdateStatus): UpdateAction | null { + switch (status.phase) { + case 'disabled': + case 'downloading': + case 'checking': + return null + case 'available': + return 'download' + case 'downloaded': + return 'install' + default: + return 'check' + } +} + +/** 타이틀바 칩 — 사용자가 알아야 할 때(새 버전·받는 중·설치 대기)만 보인다. */ +export function updateChipMessage(status: AppUpdateStatus | null): UpdateMessage | null { + if (!status) return null + const version = status.version ?? '' + switch (status.phase) { + case 'available': + return { key: 'update.chip.available', params: { version }, tone: 'accent' } + case 'downloading': + return { key: 'update.chip.downloading', params: { percent: progressPercent(status) }, tone: 'normal' } + case 'downloaded': + return { key: 'update.chip.downloaded', tone: 'accent' } + default: + return null + } +} + +export function progressPercent(status: AppUpdateStatus): number { + const percent = status.progress?.percent ?? 0 + return Math.max(0, Math.min(100, Math.round(percent))) +} diff --git a/apps/desktop/src/renderer/components/shell/UpdateChip.tsx b/apps/desktop/src/renderer/components/shell/UpdateChip.tsx new file mode 100644 index 0000000..fcdf25c --- /dev/null +++ b/apps/desktop/src/renderer/components/shell/UpdateChip.tsx @@ -0,0 +1,54 @@ +// src/renderer/components/shell/UpdateChip.tsx +// 타이틀바 오른쪽 업데이트 알림 — 새 버전·받는 중·설치 대기일 때만 보인다. 누르면 설정 → 정보 탭. +// 업데이트가 네이티브 대화상자로만 알려져 놓치기 쉬웠다(2026-10-24 사용자 지적). + +import { Box, Tooltip } from '@mui/material' +import { ArrowDownCircle, RotateCcw } from 'lucide-react' +import { d3roPalette, d3roRadius, typoSx } from '@d3ro/ui/theme' +import { useI18n } from '@d3ro/i18n' +import { useAppUpdateStatus } from '../../hooks/useAppUpdateStatus' +import { updateChipMessage } from '../settings/update-status-model' +import { openSettings } from '../../navigation/settingsTabs' + +export function UpdateChip(): React.ReactElement | null { + const { t } = useI18n() + const { status } = useAppUpdateStatus() + const message = updateChipMessage(status) + if (!message) return null + + const accent = message.tone === 'accent' + const label = t(message.key, message.params) + return ( + + openSettings('about')} + aria-label={`${label} — ${t('update.chip.tooltip')}`} + sx={{ + ...typoSx('small'), + display: 'flex', + alignItems: 'center', + gap: 0.75, + height: 26, + px: 1.25, + mr: 1, + border: `1px solid ${accent ? d3roPalette.accent.main : d3roPalette.glass.hairlineStrong}`, + borderRadius: d3roRadius.small, + bgcolor: accent ? d3roPalette.accent.solid : 'transparent', + color: accent ? d3roPalette.accent.ink : d3roPalette.text.secondary, + cursor: 'pointer', + fontVariantNumeric: 'tabular-nums', + whiteSpace: 'nowrap', + WebkitAppRegion: 'no-drag', + transition: 'background-color 0.12s ease', + '&:hover': { bgcolor: accent ? d3roPalette.accent.solidHover : d3roPalette.glass.raised }, + '&:focus-visible': { outline: `2px solid ${d3roPalette.accent.main}`, outlineOffset: 2 }, + }} + > + {status?.phase === 'downloaded' ? : } + {label} + + + ) +} diff --git a/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts b/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts new file mode 100644 index 0000000..500176f --- /dev/null +++ b/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts @@ -0,0 +1,48 @@ +// src/renderer/hooks/useAppUpdateStatus.ts +// 앱 업데이트 상태 구독 — 설정 정보 탭(UpdateSection)과 타이틀바 칩(UpdateChip)이 같이 쓴다. + +import { useCallback, useEffect, useState } from 'react' +import type { AppUpdateStatus } from '@d3ro/core/types' + +export interface AppUpdateControls { + status: AppUpdateStatus | null + /** 확인·다운로드·설치 요청이 진행 중이다 (버튼 중복 클릭 방지) */ + busy: boolean + check: () => void + download: () => void + install: () => void +} + +export function useAppUpdateStatus(): AppUpdateControls { + const [status, setStatus] = useState(null) + const [busy, setBusy] = useState(false) + + useEffect(() => { + let alive = true + void window.electronAPI.appUpdate.getStatus().then((result) => { + if (alive && result.success) setStatus(result.data) + }) + const unsubscribe = window.electronAPI.appUpdate.onStatusChanged((next) => setStatus(next)) + return () => { + alive = false + unsubscribe() + } + }, []) + + const run = useCallback((request: () => ReturnType) => { + setBusy(true) + void request() + .then((result) => { + if (result.success) setStatus(result.data) + }) + .finally(() => setBusy(false)) + }, []) + + return { + status, + busy, + check: useCallback(() => run(() => window.electronAPI.appUpdate.check()), [run]), + download: useCallback(() => run(() => window.electronAPI.appUpdate.download()), [run]), + install: useCallback(() => run(() => window.electronAPI.appUpdate.install()), [run]), + } +} diff --git a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js index 7ba6f76..c807254 100644 --- a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js +++ b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js @@ -39,6 +39,8 @@ var correction = null var generatingSince = 0 var tickTimer = null + // 후보 없이 끝났을 때 잠깐 보이는 알림 ('no-suggestion') — 메인이 1초 뒤 창을 닫는다 + var notice = null function render() { candidatesContainer.textContent = '' @@ -46,9 +48,13 @@ // 후보가 이미 있으면(채우기 루프가 배경에서 더 만드는 중이어도) 헤더 스피너는 // 끈다 — 진행률 줄의 작은 표시가 그 역할을 대신한다(중복 표시 방지). var busy = warmingUp || (generating && candidates.length === 0) - if (statusRow) statusRow.hidden = !busy + var showNotice = !busy && notice === 'no-suggestion' && candidates.length === 0 + if (statusRow) statusRow.hidden = !busy && !showNotice + if (statusRow) statusRow.classList.toggle('notice', showNotice) if (statusText) { - if (warmingUp) { + if (showNotice) { + statusText.textContent = i18nStrings.suggestionNone || '' + } else if (warmingUp) { statusText.textContent = i18nStrings.suggestionWarming || '...' } else if (busy) { // 경과 시간을 보여준다 — 모델이 바쁘면 몇 초 걸리는지 보이는 편이 덜 답답하다. @@ -197,6 +203,7 @@ var entries = [ [keyHints.move, i18nStrings.suggestionHintMoveLabel, ''], [keyHints.accept, i18nStrings.suggestionHintAcceptLabel, ''], + [keyHints.word, i18nStrings.suggestionHintWordLabel, ''], [keyHints.close, i18nStrings.suggestionHintCloseLabel, ' close-hint'] ] for (var i = 0; i < entries.length; i++) { @@ -252,6 +259,7 @@ if (payload.partialText !== undefined) partialText = payload.partialText || null if (payload.provenance !== undefined) provenance = payload.provenance || null if (payload.correction !== undefined) correction = payload.correction || null + if (payload.notice !== undefined) notice = payload.notice || null } function startTick() { @@ -296,6 +304,7 @@ partialText = null provenance = null correction = null + notice = null candidates = [] activeIndex = 0 targetTotal = 0 diff --git a/apps/desktop/src/renderer/popups/suggestion-overlay/style.css b/apps/desktop/src/renderer/popups/suggestion-overlay/style.css index effd3b8..e9152d4 100644 --- a/apps/desktop/src/renderer/popups/suggestion-overlay/style.css +++ b/apps/desktop/src/renderer/popups/suggestion-overlay/style.css @@ -129,6 +129,15 @@ body { font-size: 12px; } +/* 후보 없이 끝났을 때의 "제안 사항 없음" — 같은 자리에 스피너 없이 1초 */ +.status.notice .spinner { + display: none; +} + +.status.notice .status-text { + color: var(--d3-text-tertiary); +} + /* ── 후보 (한 페이지 = 3개, 각 최대 2줄, 고정 높이라 채워져도 창이 흔들리지 않는다) ── */ .candidates { display: flex; diff --git a/apps/desktop/tests/eval/analysis/hybrid_eval.py b/apps/desktop/tests/eval/analysis/hybrid_eval.py new file mode 100644 index 0000000..7a7027a --- /dev/null +++ b/apps/desktop/tests/eval/analysis/hybrid_eval.py @@ -0,0 +1,78 @@ +"""Hybrid: LLM first word vs personal n-gram guess on identical cases. + +Reports exact first-word hits and 'useful' hits (guess is a prefix of the true first word: Korean stem + ending). +""" +import json +import re +import sqlite3 +import sys +from collections import Counter, defaultdict + +db_path, cases_path, out_path = sys.argv[1], sys.argv[2], sys.argv[3] +db = sqlite3.connect('file:' + db_path + '?mode=ro', uri=True) +texts = [r[0] for r in db.execute("select text from typing_samples where source in ('typed','voice')")] +texts += [r[0] for r in db.execute( + "select coalesce(polished_text, original_text) from history where coalesce(polished_text, original_text) is not null")] +cases = json.load(open(cases_path, encoding='utf-8')) +out = open(out_path, 'w', encoding='utf-8') +TRAIL = re.compile(r'[\s.!?。!?…~,"\')]+$') + + +def words(text): + return [TRAIL.sub('', w) for w in re.sub(r'\s+', ' ', text or '').strip().split(' ') if w] + + +def ngram_guess(prefix_words, exclude): + bi, tri = defaultdict(Counter), defaultdict(Counter) + for text in texts: + if exclude in re.sub(r'\s+', ' ', text): + continue + ws = words(text) + for i in range(1, len(ws)): + bi[ws[i - 1]][ws[i]] += 1 + if i >= 2: + tri[(ws[i - 2], ws[i - 1])][ws[i]] += 1 + if len(prefix_words) >= 2 and tri.get((prefix_words[-2], prefix_words[-1])): + word, n = tri[(prefix_words[-2], prefix_words[-1])].most_common(1)[0] + return word, n, 'tri' + if prefix_words and bi.get(prefix_words[-1]): + word, n = bi[prefix_words[-1]].most_common(1)[0] + return word, n, 'bi' + return None, 0, None + + +stats = Counter() +for c in cases: + truth = words(c['truth']) + if not truth: + continue + t0 = truth[0] + full = re.sub(r'\s+', ' ', c['prefix'] + c['truth']).strip() + g, n, kind = ngram_guess(words(c['prefix']), full) + llm = words(c['suggestion']) + l0 = llm[0] if llm else None + stats['cases'] += 1 + for name, guess in (('llm', l0), ('ngram', g)): + if guess: + stats[f'{name}_shown'] += 1 + stats[f'{name}_exact'] += guess == t0 + stats[f'{name}_useful'] += len(guess) >= 1 and t0.startswith(guess) + if g and l0: + stats['both'] += 1 + if g == l0 or l0.startswith(g): + stats['agree'] += 1 + stats['agree_exact'] += g == t0 + stats['agree_useful'] += t0.startswith(g) + # hybrid policy: ngram when it has a guess, otherwise LLM + h = g or l0 + if h: + stats['hyb_shown'] += 1 + stats['hyb_useful'] += t0.startswith(h) + stats['hyb_exact'] += h == t0 + +N = stats['cases'] +p = lambda k, d: f"{stats[k]}/{stats[d]} = {stats[k]/stats[d]:.3f}" if stats[d] else '-' +print(f'cases {N}', file=out) +for name in ('llm', 'ngram', 'hyb'): + print(f"{name:6} shown {stats[name + '_shown']/N:.3f} exact|shown {p(name + '_exact', name + '_shown')} useful|shown {p(name + '_useful', name + '_shown')}", file=out) +print(f"agree (ngram==LLM first word) {p('agree', 'both')} exact {p('agree_exact', 'agree')} useful {p('agree_useful', 'agree')}", file=out) diff --git a/apps/desktop/tests/eval/analysis/ngram_eval.py b/apps/desktop/tests/eval/analysis/ngram_eval.py new file mode 100644 index 0000000..392defa --- /dev/null +++ b/apps/desktop/tests/eval/analysis/ngram_eval.py @@ -0,0 +1,63 @@ +"""Personal n-gram next-word predictor on the same replay cases (leave-one-out). + +Compares with the LLM on identical cases: does the user's own history predict the next word better? +""" +import json +import re +import sqlite3 +import sys +from collections import Counter, defaultdict + +db_path, cases_path, out_path = sys.argv[1], sys.argv[2], sys.argv[3] +db = sqlite3.connect('file:' + db_path + '?mode=ro', uri=True) +texts = [r[0] for r in db.execute("select text from typing_samples where source in ('typed','voice')")] +texts += [r[0] for r in db.execute("select coalesce(polished_text, original_text) from history where coalesce(polished_text, original_text) is not null")] if db.execute("select count(*) from sqlite_master where name='history'").fetchone()[0] else [] +cases = json.load(open(cases_path, encoding='utf-8')) +out = open(out_path, 'w', encoding='utf-8') +TRAIL = re.compile(r'[\s.!?。!?…~,]+$') + + +def words(text): + return [w for w in re.sub(r'\s+', ' ', text).strip().split(' ') if w] + + +def build(exclude): + bi, tri = defaultdict(Counter), defaultdict(Counter) + for text in texts: + if exclude and exclude in re.sub(r'\s+', ' ', text): + continue + ws = [TRAIL.sub('', w) for w in words(text)] + for i in range(1, len(ws)): + bi[ws[i - 1]][ws[i]] += 1 + if i >= 2: + tri[(ws[i - 2], ws[i - 1])][ws[i]] += 1 + return bi, tri + + +shown = hits = 0 +min_count = int(sys.argv[4]) if len(sys.argv) > 4 else 2 +examples = [] +for c in cases: + full = re.sub(r'\s+', ' ', (c['prefix'] + c['truth'])).strip() + bi, tri = build(full) + pw = [TRAIL.sub('', w) for w in words(c['prefix'])] + truth_first = TRAIL.sub('', words(c['truth'])[0]) if words(c['truth']) else '' + guess = None + if len(pw) >= 2 and tri.get((pw[-2], pw[-1])): + word, n = tri[(pw[-2], pw[-1])].most_common(1)[0] + if n >= min_count: + guess = word + if guess is None and pw and bi.get(pw[-1]): + word, n = bi[pw[-1]].most_common(1)[0] + if n >= min_count: + guess = word + if guess: + shown += 1 + hit = guess == truth_first + hits += hit + if len(examples) < 20: + examples.append((c['prefix'][-25:], guess, truth_first, hit)) +print(f'corpus texts {len(texts)}; cases {len(cases)}; min_count {min_count}', file=out) +print(f'ngram coverage {shown/len(cases):.3f} hit|shown {hits/shown if shown else 0:.3f} hits {hits}', file=out) +for e in examples: + print(' ', e, file=out) diff --git a/apps/desktop/tests/eval/analysis/simulate_gating.py b/apps/desktop/tests/eval/analysis/simulate_gating.py new file mode 100644 index 0000000..cffc4d6 --- /dev/null +++ b/apps/desktop/tests/eval/analysis/simulate_gating.py @@ -0,0 +1,74 @@ +import json +import math +import re +import sys + +cases = json.load(open(sys.argv[1], encoding='utf-8')) +out = open(sys.argv[2], 'w', encoding='utf-8') +END = re.compile(r'[.!?。!?…\n]') +TRAIL = re.compile(r'[\s.!?。!?…~,]+$') + + +def norm(text): + return re.sub(r'\s+', ' ', text).strip() + + +def truncate(tokens, tau): + """Keep tokens while each logprob >= tau; stop at sentence end. Drop a trailing partial word.""" + text = '' + first_word_lp = 0.0 + first_word_done = False + started = False + for tok in tokens: + t, lp = tok['token'], tok['logprob'] + if '<' in t: + break + if lp < tau: + # partial word cut: if this token continues a word (no leading space), drop the tail of the last word + if text and not t.startswith(' ') and not text.endswith(' '): + text = text[: text.rfind(' ') + 1] if ' ' in text.strip() else '' + break + text += t + if text.strip(): + started = True + if started and not first_word_done: + first_word_lp += lp + if ' ' in text.strip(): + first_word_done = True + if END.search(t): + break + return norm(text), first_word_lp + + +def score(sugg, truth): + truth = norm(truth) + sw, tw = sugg.split(' ') if sugg else [], truth.split(' ') + m = 0 + while m < min(len(sw), len(tw)) and TRAIL.sub('', sw[m]) == TRAIL.sub('', tw[m]): + m += 1 + bare = TRAIL.sub('', sugg) + full = bool(bare) and truth.startswith(bare) + acc = bare if full else ' '.join(sw[:m]) + return m, full, max(0, len(acc) - 1) if acc else 0 + + +total_truth = sum(len(norm(c['truth'])) for c in cases) +print('cases', len(cases), file=out) +print('tau gate coverage hit|shown full|shown savedRate meanLen', file=out) +for tau in (-0.5, -1.0, -1.5, -2.0, -3.0, -99): + for gate in (-0.1, -0.3, -0.5, -1.0, -99): + shown = hits = full_n = saved = length = 0 + for c in cases: + if not c['tokens']: + continue + sugg, fw = truncate(c['tokens'], tau) + if not sugg or fw < gate: + continue + shown += 1 + m, full, s = score(sugg, c['truth']) + hits += m >= 1 + full_n += full + saved += s + length += len(sugg) + if shown: + print(f'{tau:5} {gate:5} {shown/len(cases):.3f} {hits/shown:.3f} {full_n/shown:.3f} {saved/total_truth:.4f} {length/shown:.1f}', file=out) diff --git a/apps/desktop/tests/eval/replay-metrics.test.ts b/apps/desktop/tests/eval/replay-metrics.test.ts new file mode 100644 index 0000000..ce0bb96 --- /dev/null +++ b/apps/desktop/tests/eval/replay-metrics.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { scoreReplayCase, summarizeReplay, type ReplayCaseInput } from './replay-metrics' + +function input(suggestion: string | null, truth: string, logprobs: number[] = [-0.1]): ReplayCaseInput { + return { + appName: 'Discord.exe', + prefix: '오늘 회의는 ', + truth, + raw: suggestion ?? '', + suggestion, + tokens: logprobs.map((logprob, index) => ({ token: `t${index}`, logprob })), + latencyMs: 300, + promptTokens: 100, + cachedPromptTokens: 80 + } +} + +describe('replay-metrics', () => { + it('맞은 어절까지 수락했다고 보고 아낀 글자를 센다', () => { + const result = scoreReplayCase(input('내일 오후 세 시에 해요', '내일 오후 네 시로 옮겼어')) + expect(result).toMatchObject({ shown: true, matchedWords: 2, firstWordHit: true, fullAccept: false }) + expect(result.savedChars).toBe('내일 오후'.length - 1) + }) + + it('제안 전체가 실제 글 앞부분이면 통째로 수락한 것으로 본다 (끝 문장부호 무시)', () => { + const result = scoreReplayCase(input('내일 오후.', '내일 오후 세 시야')) + expect(result.fullAccept).toBe(true) + expect(result.savedChars).toBe('내일 오후'.length - 1) + }) + + it('첫 어절부터 다르면 아낀 글자는 0', () => { + const result = scoreReplayCase(input('다음 주에 다시 잡자', '내일 오후 세 시야')) + expect(result).toMatchObject({ firstWordHit: false, savedChars: 0 }) + }) + + it('요약: 노출률·적중률·게이팅 곡선', () => { + const summary = summarizeReplay([ + scoreReplayCase(input('내일 오후', '내일 오후 세 시야', [-0.05])), + scoreReplayCase(input('다음 주에', '내일 오후 세 시야', [-2.5])), + scoreReplayCase(input(null, '내일 오후 세 시야', [])) + ]) + expect(summary).toMatchObject({ cases: 3, coverage: 0.667, firstWordHitAmongShown: 0.5, cachedPromptShare: 0.8 }) + const strict = summary.gatingCurve.find((point) => point.minMeanLogprob === -0.1) + expect(strict).toMatchObject({ coverage: 0.333, firstWordHitAmongShown: 1 }) + }) +}) diff --git a/apps/desktop/tests/eval/replay-metrics.ts b/apps/desktop/tests/eval/replay-metrics.ts new file mode 100644 index 0000000..b0f1325 --- /dev/null +++ b/apps/desktop/tests/eval/replay-metrics.ts @@ -0,0 +1,166 @@ +// tests/eval/replay-metrics.ts +// 재생 평가 점수 — 제안과 실제로 이어 친 글을 비교한다 (순수 함수, replay-metrics.test.ts 가 검증). +// +// 지표 (ChaI-TeA 2024 · Smart Compose 2019 참고): +// - coverage: 제안을 보여 준 비율 +// - firstWordHit: 첫 어절이 정확히 맞음 +// - fullAccept: 제안 전체가 실제 글의 앞부분과 같음 (통째로 수락해도 고칠 게 없음) +// - savedChars: 맞은 어절까지 수락했다고 보고 아낀 글자 수 − 수락 키 1회 +// - savedRate: Σ savedChars / Σ 정답 글자 수 + +export interface ReplayToken { + token: string + logprob: number +} + +export interface ReplayCaseInput { + appName: string | null + prefix: string + truth: string + raw: string + suggestion: string | null + tokens: ReplayToken[] + latencyMs: number + promptTokens: number | null + cachedPromptTokens: number | null +} + +export interface ReplayCaseResult extends ReplayCaseInput { + shown: boolean + matchedWords: number + commonPrefixChars: number + firstWordHit: boolean + fullAccept: boolean + savedChars: number + truthChars: number + firstTokenLogprob: number | null + meanLogprob: number | null + minLogprob: number | null +} + +const TRAILING_PUNCTUATION = /[\s.!?。!?…~,]+$/u + +function normalize(text: string): string { + return text.replace(/\s+/gu, ' ').trim() +} + +function words(text: string): string[] { + const normalized = normalize(text) + return normalized ? normalized.split(' ') : [] +} + +export function scoreReplayCase(input: ReplayCaseInput): ReplayCaseResult { + const truth = normalize(input.truth) + const suggestion = input.suggestion ? normalize(input.suggestion) : '' + const shown = suggestion.length > 0 + + let commonPrefixChars = 0 + while ( + commonPrefixChars < Math.min(truth.length, suggestion.length) && + truth[commonPrefixChars] === suggestion[commonPrefixChars] + ) { + commonPrefixChars += 1 + } + + const truthWords = words(truth) + const suggestionWords = words(suggestion) + let matchedWords = 0 + while ( + matchedWords < Math.min(truthWords.length, suggestionWords.length) && + truthWords[matchedWords].replace(TRAILING_PUNCTUATION, '') === + suggestionWords[matchedWords].replace(TRAILING_PUNCTUATION, '') + ) { + matchedWords += 1 + } + + const bareSuggestion = suggestion.replace(TRAILING_PUNCTUATION, '') + const fullAccept = shown && bareSuggestion.length > 0 && truth.startsWith(bareSuggestion) + const acceptedText = fullAccept ? bareSuggestion : suggestionWords.slice(0, matchedWords).join(' ') + const savedChars = acceptedText.length > 0 ? Math.max(0, acceptedText.length - 1) : 0 + + const logprobs = input.tokens.map((token) => token.logprob) + return { + ...input, + shown, + matchedWords, + commonPrefixChars, + firstWordHit: matchedWords >= 1, + fullAccept, + savedChars, + truthChars: truth.length, + firstTokenLogprob: logprobs[0] ?? null, + meanLogprob: logprobs.length > 0 ? logprobs.reduce((sum, value) => sum + value, 0) / logprobs.length : null, + minLogprob: logprobs.length > 0 ? Math.min(...logprobs) : null + } +} + +function percentile(values: number[], p: number): number | null { + if (values.length === 0) return null + const sorted = [...values].sort((a, b) => a - b) + return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))] +} + +function rate(part: number, whole: number): number { + return whole === 0 ? 0 : Math.round((part / whole) * 1000) / 1000 +} + +export interface ReplaySummary { + cases: number + coverage: number + firstWordHitRate: number + firstWordHitAmongShown: number + fullAcceptRate: number + meanCommonPrefixChars: number + savedRate: number + latencyP50: number | null + latencyP90: number | null + cachedPromptShare: number | null + /** 평균 logprob 기준값별 노출률·첫 어절 적중률 — 게이팅 기준을 고르는 곡선 */ + gatingCurve: Array<{ minMeanLogprob: number; coverage: number; firstWordHitAmongShown: number; savedRate: number }> +} + +export function summarizeReplay(results: ReplayCaseResult[]): ReplaySummary { + const shown = results.filter((result) => result.shown) + const truthChars = results.reduce((sum, result) => sum + result.truthChars, 0) + const promptTokens = results.reduce((sum, result) => sum + (result.promptTokens ?? 0), 0) + const cached = results.reduce((sum, result) => sum + (result.cachedPromptTokens ?? 0), 0) + + const gatingCurve = [-0.1, -0.2, -0.3, -0.5, -0.75, -1, -1.5, -2, -Infinity].map((threshold) => { + const kept = shown.filter((result) => (result.meanLogprob ?? -Infinity) >= threshold) + return { + minMeanLogprob: threshold, + coverage: rate(kept.length, results.length), + firstWordHitAmongShown: rate(kept.filter((result) => result.firstWordHit).length, kept.length), + savedRate: rate( + kept.reduce((sum, result) => sum + result.savedChars, 0), + truthChars + ) + } + }) + + return { + cases: results.length, + coverage: rate(shown.length, results.length), + firstWordHitRate: rate(results.filter((result) => result.firstWordHit).length, results.length), + firstWordHitAmongShown: rate(shown.filter((result) => result.firstWordHit).length, shown.length), + fullAcceptRate: rate(results.filter((result) => result.fullAccept).length, results.length), + meanCommonPrefixChars: + shown.length === 0 + ? 0 + : Math.round((shown.reduce((sum, result) => sum + result.commonPrefixChars, 0) / shown.length) * 100) / 100, + savedRate: rate( + results.reduce((sum, result) => sum + result.savedChars, 0), + truthChars + ), + latencyP50: percentile( + results.map((result) => result.latencyMs), + 50 + ), + latencyP90: percentile( + results.map((result) => result.latencyMs), + 90 + ), + cachedPromptShare: promptTokens === 0 ? null : rate(cached, promptTokens), + gatingCurve + } +} diff --git a/apps/desktop/tests/eval/suggestion-latency.eval.test.ts b/apps/desktop/tests/eval/suggestion-latency.eval.test.ts new file mode 100644 index 0000000..99d6992 --- /dev/null +++ b/apps/desktop/tests/eval/suggestion-latency.eval.test.ts @@ -0,0 +1,125 @@ +// tests/eval/suggestion-latency.eval.test.ts +// +// 첫 후보 지연 분해 — 실제 타이핑처럼 문장을 어절 단위로 늘려 가며 앱과 같은 프롬프트로 연달아 요청하고, +// 시간이 어디에 쓰이는지(프롬프트 읽기 / 캐시 재사용 / 생성)를 잰다. 프롬프트 순서를 바꿀 가치가 있는지 판단용. +// +// 실행: D3RO_EVAL_DB= D3RO_EVAL_OUT=<폴더> [D3RO_EVAL_SENTENCES=15] +// ELECTRON_RUN_AS_NODE=1 electron vitest run --config vitest.config.ts tests/eval/suggestion-latency.eval.test.ts + +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import Database from 'better-sqlite3' +import { describe, expect, it, vi } from 'vitest' +import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template' + +vi.mock('../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }) +})) + +const DB_PATH = process.env.D3RO_EVAL_DB +const OUT_DIR = process.env.D3RO_EVAL_OUT +const MODEL = process.env.D3RO_EVAL_MODEL ?? 'gemma4:e4b' +const SENTENCES = Number(process.env.D3RO_EVAL_SENTENCES ?? 15) +const OLLAMA = process.env.D3RO_EVAL_OLLAMA ?? 'http://127.0.0.1:11434' + +interface Timing { + sentence: number + step: number + promptTokens: number + cachedTokens: number + promptMs: number + evalMs: number + totalMs: number + wallMs: number +} + +const ns = (value: number | undefined) => Math.round((value ?? 0) / 1e6) + +describe.skipIf(!DB_PATH || !OUT_DIR)('suggestion latency breakdown', () => { + it( + 'replays word-by-word typing', + async () => { + const { buildSuggestionPrompt } = await import('../../src/main/services/llm-prompts') + const db = new Database(DB_PATH as string, { readonly: true, fileMustExist: true }) + const rows = db + .prepare("SELECT text FROM typing_samples WHERE source = 'typed' ORDER BY created_at DESC LIMIT 400") + .all() as Array<{ text: string }> + db.close() + const sentences = rows + .map((row) => row.text.trim()) + .filter((text) => text.split(/\s+/u).length >= 6 && /[가-힣]/u.test(text) && !/https?:|[/\\=&]/u.test(text)) + .slice(0, SENTENCES) + + const timings: Timing[] = [] + for (const [sentenceIndex, text] of sentences.entries()) { + const words = text.split(/\s+/u) + for (let step = 2; step < words.length; step += 1) { + const prefix = `${words.slice(0, step).join(' ')} ` + const prompt = buildSuggestionPrompt({ + prefix, + documentText: prefix, + suffix: null, + appName: 'Discord.exe', + windowTitle: null, + recentWrites: [], + candidates: 1, + maxChars: 160, + prefill: true + }) + const raw = renderRawChatPrompt(MODEL, { + system: prompt.systemPrompt, + user: prompt.text, + assistantPrefix: prompt.assistantPrefix ?? '' + }) + const startedAt = Date.now() + const response = await fetch(`${OLLAMA}/api/generate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + model: MODEL, + prompt: raw, + raw: true, + stream: false, + keep_alive: '10m', + options: { temperature: 0.3, num_predict: 64, stop: rawChatStopSequences(MODEL) } + }) + }) + const data = (await response.json()) as { + prompt_eval_count?: number + prompt_eval_cached_count?: number + prompt_eval_duration?: number + eval_duration?: number + total_duration?: number + } + timings.push({ + sentence: sentenceIndex, + step, + promptTokens: data.prompt_eval_count ?? 0, + cachedTokens: data.prompt_eval_cached_count ?? 0, + promptMs: ns(data.prompt_eval_duration), + evalMs: ns(data.eval_duration), + totalMs: ns(data.total_duration), + wallMs: Date.now() - startedAt + }) + } + } + + const avg = (pick: (t: Timing) => number) => + Math.round(timings.reduce((sum, t) => sum + pick(t), 0) / Math.max(1, timings.length)) + const summary = { + requests: timings.length, + avgPromptTokens: avg((t) => t.promptTokens), + avgCachedTokens: avg((t) => t.cachedTokens), + cachedShare: Math.round((avg((t) => t.cachedTokens) / Math.max(1, avg((t) => t.promptTokens))) * 1000) / 1000, + avgPromptMs: avg((t) => t.promptMs), + avgEvalMs: avg((t) => t.evalMs), + avgTotalMs: avg((t) => t.totalMs), + avgWallMs: avg((t) => t.wallMs) + } + mkdirSync(OUT_DIR as string, { recursive: true }) + writeFileSync(join(OUT_DIR as string, 'latency.json'), JSON.stringify({ summary, timings }, null, 2)) + expect(timings.length).toBeGreaterThan(0) + }, + 30 * 60_000 + ) +}) diff --git a/apps/desktop/tests/eval/suggestion-replay.eval.test.ts b/apps/desktop/tests/eval/suggestion-replay.eval.test.ts new file mode 100644 index 0000000..3eb258a --- /dev/null +++ b/apps/desktop/tests/eval/suggestion-replay.eval.test.ts @@ -0,0 +1,287 @@ +// tests/eval/suggestion-replay.eval.test.ts +// +// 문장 예측 재생 평가 — 사용자가 실제로 친 문장을 어절 경계에서 잘라 앞부분으로 제안을 만들고, +// 뒷부분(실제로 이어 친 글)과 비교한다. 앱과 같은 경로(buildSuggestionPrompt → renderRawChatPrompt +// → Ollama raw → extractContinuation → 사실 검사)를 쓴다. 개인 힌트(문구·그래프)는 아직 넣지 않는다. +// +// 평소 테스트에서는 건너뛴다. 실행(앱의 Ollama 가 떠 있어야 한다): +// D3RO_EVAL_DB= D3RO_EVAL_OUT=<결과 폴더> [D3RO_EVAL_CASES=120] [D3RO_EVAL_MODEL=gemma4:e4b] +// ELECTRON_RUN_AS_NODE=1 electron vitest run --config vitest.config.ts tests/eval +// +// 결과: cases.json(케이스별 원문·제안·토큰 확률) + summary.json. 토큰 확률을 남겨 두면 게이팅·절단 +// 기준값을 모델을 다시 돌리지 않고 오프라인으로 고를 수 있다. + +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import Database from 'better-sqlite3' +import { describe, expect, it, vi } from 'vitest' +import { extractContinuation } from '@d3ro/core/input-intelligence' +import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template' +import { splitSentences } from '@d3ro/core/personal-graph' +import { findUnsupportedFacts } from '@d3ro/core/writing-context' +import { PersonalNgramModel, predictPersonalContinuation } from '@d3ro/core/personal-ngram' +import { copiesContext, cutByConfidence } from '@d3ro/core/suggestion-confidence' +import { scoreReplayCase, summarizeReplay, type ReplayCaseResult } from './replay-metrics' + +vi.mock('../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }) +})) + +const DB_PATH = process.env.D3RO_EVAL_DB +const OUT_DIR = process.env.D3RO_EVAL_OUT +const MODEL = process.env.D3RO_EVAL_MODEL ?? 'gemma4:e4b' +const CASES = Number(process.env.D3RO_EVAL_CASES ?? 120) +const OLLAMA = process.env.D3RO_EVAL_OLLAMA ?? 'http://127.0.0.1:11434' +/** + * app — 앱과 같은 지시형 prefill 프롬프트, 문맥은 지금 문장만 + * recent — app + 같은 앱에서 15분 안에 먼저 쓴 글(앱의 recentWrites 와 같은 자리) + * plain — 지시문·템플릿 없이 앞 글 + 지금 문장을 그대로 이어 쓰게 한다(순수 언어 모델 이어쓰기) + * ngram — 개인 n-gram 만 (모델 호출 없음). 정답 문장이 든 기록은 빼고 만든다(leave-one-out) + * hybrid — ngram 이 내면 그것, 아니면 recent + */ +const VARIANT = (process.env.D3RO_EVAL_VARIANT ?? 'app') as 'app' | 'recent' | 'plain' | 'ngram' | 'hybrid' +/** word — 어절 경계(단어를 끝내고 멈춤), mid — 단어 중간(치다가 멈춤) */ +const CUT = (process.env.D3RO_EVAL_CUT ?? 'word') as 'word' | 'mid' +/** 1 이면 앱처럼 모델 출력을 토큰 확신으로 거르고 자른다 (core cutByConfidence) */ +const GATE = process.env.D3RO_EVAL_GATE === '1' +const RECENT_WINDOW_MS = 15 * 60_000 +/** 앱 기본값과 같다 (SUGGESTION_DEFAULTS.maxOutputTokens) */ +const MAX_TOKENS = 64 + +interface ReplaySource { + text: string + appName: string | null + createdAt: number +} + +interface GenerateResponse { + response: string + total_duration?: number + prompt_eval_count?: number + prompt_eval_cached_count?: number + logprobs?: Array<{ token: string; logprob: number }> +} + +/** 결정적 의사 난수 — 실행마다 같은 케이스를 고른다(변경 전후 비교). */ +function seeded(seed: number): () => number { + let state = seed + return () => { + state = (state * 1_103_515_245 + 12_345) % 2_147_483_648 + return state / 2_147_483_648 + } +} + +/** 평가할 문장 — 직접 친 글 중 어절 4개 이상, 주소·명령 같은 것은 뺀다. */ +function loadSources(dbPath: string): ReplaySource[] { + const db = new Database(dbPath, { readonly: true, fileMustExist: true }) + try { + const rows = db + .prepare( + "SELECT text, app_name AS appName, created_at AS createdAt FROM typing_samples WHERE source = 'typed' ORDER BY created_at" + ) + .all() as ReplaySource[] + const seen = new Set() + return rows.filter((row) => { + const text = row.text.trim() + if (seen.has(text)) return false + seen.add(text) + const words = text.split(/\s+/u) + return words.length >= 4 && text.length >= 15 && !/https?:|www\.|[/\\=&]/u.test(text) && /[가-힣]/u.test(text) + }) + } finally { + db.close() + } +} + +/** n-gram 이 배울 기록 전부 — 앱과 같이 출처를 가리지 않는다. */ +function loadCorpus(dbPath: string): string[] { + const db = new Database(dbPath, { readonly: true, fileMustExist: true }) + try { + return (db.prepare('SELECT text FROM typing_samples ORDER BY created_at').all() as Array<{ text: string }>).map( + (row) => row.text + ) + } finally { + db.close() + } +} + +function squash(text: string): string { + return text.replace(/\s+/gu, ' ').trim() +} + +/** + * 끊을 자리 하나를 골라 (앞부분, 정답) 으로 자른다. 정답이 최소 2어절 남게 한다. + * word 는 공백 바로 뒤, mid 는 두 글자 이상 어절의 첫 글자 뒤(그 어절의 나머지가 정답 첫머리). + */ +function cut(text: string, random: () => number): { prefix: string; truth: string } | null { + const boundaries: number[] = [] + for (let index = 1; index < text.length; index += 1) { + if (CUT === 'word') { + if (text[index] === ' ' && text[index - 1] !== ' ') boundaries.push(index + 1) + } else if (text[index - 1] === ' ' && index + 1 < text.length && /\S/u.test(text[index]) && /\S/u.test(text[index + 1])) { + boundaries.push(index + 1) + } + } + const usable = boundaries.filter((at) => at >= 6 && text.slice(at).trim().split(/\s+/u).length >= 2) + if (usable.length === 0) return null + const at = usable[Math.floor(random() * usable.length)] + return { prefix: text.slice(0, at), truth: text.slice(at) } +} + +async function generate(prompt: string, stop: string[]): Promise<{ data: GenerateResponse; ms: number }> { + const startedAt = Date.now() + const response = await fetch(`${OLLAMA}/api/generate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + model: MODEL, + prompt, + raw: true, + stream: false, + logprobs: true, + top_logprobs: 0, + keep_alive: '10m', + // 앱은 0.3 으로 뽑는다 — 비교 가능하게 하려고 평가는 결정적으로(0) 돌린다. + options: { temperature: 0, num_predict: MAX_TOKENS, stop } + }) + }) + if (!response.ok) throw new Error(`ollama ${response.status}: ${await response.text()}`) + return { data: (await response.json()) as GenerateResponse, ms: Date.now() - startedAt } +} + +describe.skipIf(!DB_PATH || !OUT_DIR)('suggestion replay eval', () => { + it( + 'replays typed sentences through the suggestion pipeline', + async () => { + const { buildSuggestionPrompt } = await import('../../src/main/services/llm-prompts') + const sources = loadSources(DB_PATH as string) + const random = seeded(20261024) + const picked: Array = [] + const pool = [...sources] + while (picked.length < CASES && pool.length > 0) { + const source = pool.splice(Math.floor(random() * pool.length), 1)[0] + const split = cut(source.text, random) + if (split) picked.push({ ...source, ...split }) + } + + const corpus = VARIANT === 'ngram' || VARIANT === 'hybrid' ? loadCorpus(DB_PATH as string) : [] + const results: ReplayCaseResult[] = [] + for (const item of picked) { + if (VARIANT === 'ngram' || VARIANT === 'hybrid') { + // 정답 문장이 든 기록은 빼고 배운다 — 그대로 두면 답을 외워서 맞힌다. + const sentence = squash(item.text) + const ngram = new PersonalNgramModel() + for (const text of corpus) if (!squash(text).includes(sentence)) ngram.addText(text) + const startedAt = Date.now() + // 기준값을 주지 않으면 앱과 같은 값(predictPersonalContinuation)을 쓴다 — 격자 탐색 때만 덮는다. + const prediction = process.env.D3RO_EVAL_NGRAM_SUPPORT + ? ngram.predict(item.prefix, { + minSupport: Number(process.env.D3RO_EVAL_NGRAM_SUPPORT), + minConfidence: Number(process.env.D3RO_EVAL_NGRAM_CONFIDENCE ?? 0.25), + maxWords: Number(process.env.D3RO_EVAL_NGRAM_WORDS ?? 3) + }) + : predictPersonalContinuation(ngram, item.prefix) + if (prediction || VARIANT === 'ngram') { + results.push( + scoreReplayCase({ + appName: item.appName, + prefix: item.prefix, + truth: item.truth, + raw: prediction?.text ?? '', + suggestion: prediction?.text ?? null, + tokens: [], + latencyMs: Date.now() - startedAt, + promptTokens: null, + cachedPromptTokens: null + }) + ) + continue + } + } + // 앞서 쓴 글 — 같은 앱, 15분 안, 오래된 것부터 최대 4개 (자기 자신·뒤에 쓴 글은 넣지 않는다) + const recent = + VARIANT === 'app' + ? [] + : sources + .filter( + (other) => + other.appName === item.appName && + other.createdAt < item.createdAt && + item.createdAt - other.createdAt <= RECENT_WINDOW_MS + ) + .slice(-4) + const prompt = buildSuggestionPrompt({ + prefix: item.prefix, + documentText: item.prefix, + suffix: null, + appName: item.appName, + windowTitle: null, + recentWrites: recent.map((other) => ({ text: other.text, ageMs: item.createdAt - other.createdAt })), + candidates: 1, + maxChars: 160, + prefill: true + }) + const rawPrompt = + VARIANT === 'plain' + ? [...recent.map((other) => other.text), item.prefix.trimEnd()].join('\n') + : renderRawChatPrompt(MODEL, { + system: prompt.systemPrompt, + user: prompt.text, + assistantPrefix: prompt.assistantPrefix ?? '' + }) + if (rawPrompt === null) throw new Error(`model ${MODEL} has no raw template`) + const stop = VARIANT === 'plain' ? ['\n'] : rawChatStopSequences(MODEL) + const { data, ms } = await generate(rawPrompt, stop) + // 앱(SuggestionService keepConfidentPart)과 같은 거르기 — 첫 어절이 자신 없으면 숨긴다. + const tokens = data.logprobs ?? [] + const cutResult = GATE && tokens.length > 0 ? cutByConfidence(tokens) : undefined + const joined = tokens.map((entry) => entry.token).join('') + const confidentRaw = + cutResult === undefined + ? data.response + : cutResult === null + ? '' + : data.response.startsWith(joined.slice(0, cutResult.keepChars)) + ? joined.slice(0, cutResult.keepChars) + : data.response + const continuation = extractContinuation(confidentRaw, { + mode: prompt.writing.mode, + prefill: prompt.assistantPrefix ?? '', + writtenSentences: splitSentences(item.prefix), + wordFinished: prompt.wordFinished, + allowEmoji: prompt.allowEmoji, + maxChars: 160 + }) + // 앱과 같은 거부 규칙: 지어낸 사실 · 앞 글 베끼기 + const contextText = [...recent.map((other) => other.text), item.prefix, prompt.factSource].join(' ') + const rejected = !continuation + ? null + : findUnsupportedFacts(continuation.text, prompt.factSource).length > 0 + ? 'unsupported-facts' + : copiesContext(continuation.text, contextText) + ? 'copied-context' + : null + results.push( + scoreReplayCase({ + appName: item.appName, + prefix: item.prefix, + truth: item.truth, + raw: data.response, + suggestion: rejected ? null : continuation?.text ?? null, + tokens: (data.logprobs ?? []).map((entry) => ({ token: entry.token, logprob: entry.logprob })), + latencyMs: ms, + promptTokens: data.prompt_eval_count ?? null, + cachedPromptTokens: data.prompt_eval_cached_count ?? null + }) + ) + } + + mkdirSync(OUT_DIR as string, { recursive: true }) + writeFileSync(join(OUT_DIR as string, 'cases.json'), JSON.stringify(results, null, 2)) + const summary = { model: MODEL, variant: VARIANT, cut: CUT, gate: GATE, sources: sources.length, ...summarizeReplay(results) } + writeFileSync(join(OUT_DIR as string, 'summary.json'), JSON.stringify(summary, null, 2)) + expect(results.length).toBeGreaterThan(0) + }, + 30 * 60_000 + ) +}) diff --git a/apps/desktop/tests/main/services/TypoCorrectionService.test.ts b/apps/desktop/tests/main/services/TypoCorrectionService.test.ts index 9a52054..a045a45 100644 --- a/apps/desktop/tests/main/services/TypoCorrectionService.test.ts +++ b/apps/desktop/tests/main/services/TypoCorrectionService.test.ts @@ -125,18 +125,23 @@ describe('TypoCorrectionService', () => { expect(service.handleTypingContext(typingContext())).toBe('pass') }) - it('판단 뒤 사용자가 한 키라도 더 쳤으면 교체하지 않는다', async () => { + it('판단 뒤 사용자가 한 키라도 더 쳤으면 교체하지 않고, 다음 멈춤 스냅샷에서 같은 구간을 다시 교정한다', async () => { const fake = deps() const replaceBeforeCaret = vi.fn(async () => true) fake.deps.replaceBeforeCaret = replaceBeforeCaret fake.deps.lastKeyAt = vi .fn<() => number>() .mockReturnValueOnce(1000) + .mockReturnValueOnce(1001) .mockReturnValue(1001) const service = new TypoCorrectionService(fake.deps) service.handleTypingContext(typingContext()) await flush() expect(replaceBeforeCaret).not.toHaveBeenCalled() + + expect(service.handleTypingContext(typingContext())).toBe('correcting') + await flush() + expect(replaceBeforeCaret).toHaveBeenCalledTimes(1) }) it('포커스가 다른 창으로 옮겨 갔으면 교체하지 않는다', async () => { @@ -262,6 +267,142 @@ describe('TypoCorrectionService', () => { await flush() expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('dkssudgktpdy'.length, '안녕하세요') }) + + it('Araso 방식 혼합어(영어+조사, 대문자 약어+단어, 한→영 역변환)를 즉시 교정한다', async () => { + const fake = deps() + const service = new TypoCorrectionService(fake.deps) + expect(service.handleTypingContext(typingContext({ prefix: 'githubdp PDFvkdlf ㅎ샤ㅗㅕㅠ에' }))).toBe('correcting') + await flush() + expect(fake.replaceBeforeCaret).toHaveBeenCalledWith( + 'githubdp PDFvkdlf ㅎ샤ㅗㅕㅠ에'.length, + 'github에 PDF파일 github에' + ) + }) + + it('layoutOnly 모드에서는 한영 전환만 즉시 교정하고 일반 철자·모델 오타는 제안 쪽으로 넘긴다(pass)', async () => { + const fake = deps({ warmModel: () => 'gemma' }) + const service = new TypoCorrectionService(fake.deps) + + // 철자 오타만 있는 문장은 layoutOnly 에서 건드리지 않고 pass 반환 (모델 호출도 없음) + expect(service.handleTypingContext(typingContext({ prefix: '오늘 회의는 잘 됬어요 ' }), { layoutOnly: true })).toBe( + 'pass' + ) + expect(fake.replaceBeforeCaret).not.toHaveBeenCalled() + expect(fake.deps.generate).not.toHaveBeenCalled() + + // 한영 전환이 있으면 layoutOnly 에서도 즉시 교정 + expect( + service.handleTypingContext(typingContext({ prefix: 'dlrjs github dp commit gkf rjdi' }), { layoutOnly: true }) + ).toBe('correcting') + await flush() + expect(fake.replaceBeforeCaret).toHaveBeenCalledWith( + 'dlrjs github dp commit gkf rjdi'.length, + '이건 github 에 commit 할 거야' + ) + }) + + it('Discord/Chromium 처럼 comp=true 가 계속 켜져 있거나 스페이스 직후 짧은 유휴(60ms)여도 한영 전환은 즉시 교정한다', async () => { + const fake = deps() + const service = new TypoCorrectionService(fake.deps) + + expect( + service.handleTypingContext( + typingContext({ prefix: 'dkssudgktpdy ', isComposing: true, idleMs: 60, appName: 'Discord.exe' }), + { layoutOnly: true } + ) + ).toBe('correcting') + await flush() + expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('dkssudgktpdy '.length, '안녕하세요 ') + + fake.replaceBeforeCaret.mockClear() + // 공백 없이 단어 입력 도중(예: 내ㅡㄷ -> 내ㅡㄷ샤ㅡㄷ)에는 짧은 유휴(250ms)에서 끼어들지 않는다 + expect( + service.handleTypingContext( + typingContext({ prefix: '내ㅡㄷ', isComposing: true, idleMs: 250, appName: 'Discord.exe' }), + { layoutOnly: true } + ) + ).toBe('pass') + expect(fake.replaceBeforeCaret).not.toHaveBeenCalled() + + // 커서 앞이 실제 한글 음절(에)이고 충분히 멈췄을 때(700ms)는 commitComposition 옵션으로 조합 확정 후 지운다 + expect( + service.handleTypingContext( + typingContext({ prefix: 'ㅎ샤ㅗㅕㅠ에', isComposing: true, idleMs: 700, appName: 'Discord.exe' }), + { layoutOnly: true } + ) + ).toBe('correcting') + await flush() + expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅎ샤ㅗㅕㅠ에'.length, 'github에', { + commitComposition: true + }) + }) + + it('터미널(WindowsTerminal, Kitedesk)과 Vim 모드에서 한영 전환·:ㅈㅂ 명령만 교정하고 노멀 모드는 건드리지 않는다', async () => { + const fake = deps({ warmModel: () => 'gemma' }) + const service = new TypoCorrectionService(fake.deps) + + // 1. Vim 노멀 모드에서는 어떤 입력도 건드리지 않는다 + expect( + service.handleTypingContext( + typingContext({ + prefix: 'dkssudgktpdy ', + appName: 'WindowsTerminal.exe', + terminalMode: true, + vimMode: 'normal', + idleMs: 60 + }) + ) + ).toBe('pass') + expect(fake.replaceBeforeCaret).not.toHaveBeenCalled() + + // 2. Vim 입력 모드(또는 셸)에서는 한영 자판 오타를 즉시 변환한다 + expect( + service.handleTypingContext( + typingContext({ + prefix: 'dkssudgktpdy ', + appName: 'WindowsTerminal.exe', + terminalMode: true, + vimMode: 'insert', + idleMs: 60 + }) + ) + ).toBe('correcting') + await flush() + expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('dkssudgktpdy '.length, '안녕하세요 ') + + // 3. Vim 명령줄 모드에서는 ':' 를 남기고 'ㅈㅂ' 만 'wq' 로 바꾼다 (낱자 자모 'ㅂ' 은 불필요한 commitComposition Space 없이 지움) + fake.replaceBeforeCaret.mockClear() + expect( + service.handleTypingContext( + typingContext({ + prefix: ':ㅈㅂ', + appName: 'Kitedesk.exe', + terminalMode: true, + vimMode: 'command', + isComposing: true, + idleMs: 160 + }) + ) + ).toBe('correcting') + await flush() + expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅈㅂ'.length, 'wq') + + // 4. 교정 성공 뒤 xterm-helper-textarea 등이 같은 원문을 다시 돌려줘도 무한 재교정하지 않는다 + fake.replaceBeforeCaret.mockClear() + expect( + service.handleTypingContext( + typingContext({ + prefix: ':ㅈㅂ', + appName: 'Agent Switchboard.exe', + terminalMode: true, + vimMode: 'command', + isComposing: true, + idleMs: 400 + }) + ) + ).toBe('pass') + expect(fake.replaceBeforeCaret).not.toHaveBeenCalled() + }) }) describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => { diff --git a/apps/desktop/tests/main/services/input-flow-services.test.ts b/apps/desktop/tests/main/services/input-flow-services.test.ts index 4626bc2..d03abee 100644 --- a/apps/desktop/tests/main/services/input-flow-services.test.ts +++ b/apps/desktop/tests/main/services/input-flow-services.test.ts @@ -586,4 +586,25 @@ describe('입력 플로우 서비스', () => { ).toBe(false) expect(getSuggestionService().getState().visible).toBe(false) }) + + it('통계 수집(inputTelemetryEnabled)이 꺼져 있어도 기본 한영·오타 교정이 켜져 있으면 관찰기는 돌되 활동 DB에는 저장하지 않는다', () => { + harness.config.set('inputTelemetryEnabled', false) + harness.config.set('inputTelemetryPaused', false) + harness.config.set('typoAutoCorrectEnabled', true) + harness.config.set('suggestionEnabled', false) + + const telemetry = getInputTelemetryService() as unknown as { + start: () => void + isRunning: boolean + _pending: Map + flushNow: () => void + } + telemetry.start() + expect(telemetry.isRunning).toBe(true) + + telemetry._pending.set('2026-10-26|12|Slack.exe', activity({ keystrokes: 10 })) + telemetry.flushNow() + expect(telemetry._pending.size).toBe(0) + expect(harness.rows.activity).toHaveLength(0) + }) }) diff --git a/apps/desktop/tests/main/services/input-intelligence.test.ts b/apps/desktop/tests/main/services/input-intelligence.test.ts index 4853ef7..8a99c4a 100644 --- a/apps/desktop/tests/main/services/input-intelligence.test.ts +++ b/apps/desktop/tests/main/services/input-intelligence.test.ts @@ -40,6 +40,7 @@ import { } from '@d3ro/core/input-intelligence' import { LEARNING_EXCLUDED_APPS, + isAppScopedLearning, TERMINAL_APPS, isAppExcluded, isLearnablePhrase, @@ -69,9 +70,11 @@ describe('개인 코퍼스 학습 규칙', () => { } }) - it('터미널·에디터·코딩 에이전트는 학습에서 빠지고, 터미널만 제안에서도 빠진다', () => { + it('터미널·에디터는 학습에서 빠지고, Agent Switchboard 는 그 앱 안에서만 배우며, 터미널만 제안에서도 빠진다', () => { expect(isAppExcluded('WindowsTerminal.exe', LEARNING_EXCLUDED_APPS)).toBe(true) - expect(isAppExcluded('Agent Switchboard.exe', LEARNING_EXCLUDED_APPS)).toBe(true) + expect(isAppExcluded('Agent Switchboard.exe', LEARNING_EXCLUDED_APPS)).toBe(false) + expect(isAppScopedLearning('Agent Switchboard.exe')).toBe(true) + expect(isAppScopedLearning('KakaoTalk.exe')).toBe(false) expect(isAppExcluded('Code.exe', LEARNING_EXCLUDED_APPS)).toBe(true) expect(isAppExcluded('KakaoTalk.exe', LEARNING_EXCLUDED_APPS)).toBe(false) expect(isAppExcluded('WindowsTerminal.exe', TERMINAL_APPS)).toBe(true) diff --git a/apps/desktop/tests/main/services/input-telemetry-redteam-r1-1.test.ts b/apps/desktop/tests/main/services/input-telemetry-redteam-r1-1.test.ts index 9f6d4c8..fe5c060 100644 --- a/apps/desktop/tests/main/services/input-telemetry-redteam-r1-1.test.ts +++ b/apps/desktop/tests/main/services/input-telemetry-redteam-r1-1.test.ts @@ -181,11 +181,102 @@ describe('타이핑 학습은 스냅샷 조각이 아니라 문장 단위로 저 telemetry.flushPendingLearning() } internal._applyTypedDelta(snapshot('')) - internal._applyTypedDelta(snapshot('마음은 고마운데 아빠 표정이 ')) + internal._applyTypedDelta(snapshot('마음은 고마운데 아빠 표정이 \uf602')) telemetry.flushPendingLearning() expect(typedSamples()).toEqual(['마음은 고마운데 아빠 표정이']) }) + + it('띄어쓰기 없는 질문과 ㅋㅋ·ㅠㅠ 같은 말투는 남긴다', () => { + const telemetry = getInputTelemetryService() + const internal = telemetry as unknown as TelemetryInternal + for (const text of ['언제쯤일까요?', '서버실 소음 ㅠㅠㅠ', '오늘 진짜 웃겼다 ㅋㅋ']) { + internal._applyTypedDelta(snapshot('')) + internal._applyTypedDelta(snapshot(text)) + telemetry.flushPendingLearning() + } + + expect(typedSamples()).toEqual(['언제쯤일까요?', '서버실 소음 ㅠㅠㅠ', '오늘 진짜 웃겼다 ㅋㅋ']) + }) + + it('이미 쌓인 조각·주소·깨진 이모지 표본과 문구를 정리하고 음성 표본은 건드리지 않는다', () => { + const now = Date.now() + const row = (text: string, source: 'typed' | 'voice') => ({ + id: crypto.randomUUID(), + text, + wordCount: 1, + charCount: text.length, + appName: 'Slack.exe', + windowTitle: null, + source, + createdAt: now + }) + testDb.db + .insert(typingSamples) + .values([ + row('처음', 'typed'), + row('mail.google.com/mail/u/0/#inbox', 'typed'), + row('겠당ㅇ', 'typed'), + row('아빠 표정이 \uf602', 'typed'), + row('언제쯤일까요?', 'typed'), + row('네 확인했습니다', 'typed'), + row('처음', 'voice') + ]) + .run() + const phrase = (text: string) => ({ + id: crypto.randomUUID(), + phrase: text, + count: 1, + source: 'typed' as const, + lastUsedAt: now, + createdAt: now, + appName: 'Slack.exe' + }) + testDb.db + .insert(personalPhrases) + .values([phrase('램 가격이 다시 낮아질 ㅇ'), phrase('회의 자료 공유드립니다')]) + .run() + + ;(getInputTelemetryService() as unknown as { _pruneUnlearnableCorpus(): void })._pruneUnlearnableCorpus() + + const left = testDb.db.select().from(typingSamples).all().map((r) => `${r.source}:${r.text}`) + expect(left.sort()).toEqual(['typed:네 확인했습니다', 'typed:언제쯤일까요?', 'voice:처음']) + expect(testDb.db.select().from(personalPhrases).all().map((r) => r.phrase)).toEqual(['회의 자료 공유드립니다']) + }) +}) + +describe('앱 안에서만 배우는 앱 (Agent Switchboard, 2026-10-25)', () => { + it('표본에는 앱 이름과 함께 남지만 공용 문구·그래프에는 들어가지 않는다', () => { + const telemetry = getInputTelemetryService() + const internal = telemetry as unknown as TelemetryInternal + internal._foreground.appName = 'Agent Switchboard.exe' + internal._applyTypedDelta(snapshot('')) + internal._applyTypedDelta(snapshot('그래서 말인데 개발자 도구로 열어서 확인해 줄래.')) + + const rows = testDb.db.select().from(typingSamples).all() + expect(rows.map((row) => [row.appName, row.text])).toEqual([ + ['Agent Switchboard.exe', '그래서 말인데 개발자 도구로 열어서 확인해 줄래.'] + ]) + expect(testDb.db.select().from(personalPhrases).all()).toEqual([]) + expect(testDb.db.select().from(phraseEdges).all()).toEqual([]) + }) + + it('이어 쓴 글 찾기는 앱을 주면 그 앱 표본에서만 찾는다', () => { + const telemetry = getInputTelemetryService() + const internal = telemetry as unknown as TelemetryInternal + for (const [app, text] of [ + ['Agent Switchboard.exe', '그래서 말인데 개발자 도구로 열어서 확인해 줄래.'], + ['KakaoTalk.exe', '그래서 말인데 내일 저녁에 만나자.'] + ]) { + internal._foreground.appName = app + internal._applyTypedDelta(snapshot('')) + internal._applyTypedDelta(snapshot(text)) + } + expect(telemetry.findContinuationHints('그래서 말인데', 3, { appName: 'Agent Switchboard.exe' })).toEqual([ + '개발자 도구로 열어서 확인해 줄래.' + ]) + expect(telemetry.findContinuationHints('그래서 말인데', 3)).toHaveLength(2) + }) }) describe('버그 9: 문구 삭제는 그 문장의 그래프 엣지도 지운다', () => { diff --git a/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts b/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts index 5ca6272..76c4d56 100644 --- a/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts +++ b/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts @@ -77,6 +77,7 @@ describe('acceleratorsToReserve', () => { 'Control+Shift+V', 'Control+Shift+C', 'Control+Alt+Return', + 'Control+Alt+Space', 'Control+Alt+Down', 'Control+Alt+Up', 'Control+Alt+Backspace' diff --git a/apps/desktop/tests/main/services/modifier-state.test.ts b/apps/desktop/tests/main/services/modifier-state.test.ts index 96285b9..d256e75 100644 --- a/apps/desktop/tests/main/services/modifier-state.test.ts +++ b/apps/desktop/tests/main/services/modifier-state.test.ts @@ -7,9 +7,12 @@ vi.mock('uiohook-napi', () => ({ uIOhook: { on: (name: string, listener: KeyListener) => listeners[name]?.push(listener) } })) vi.mock('../../../src/main/services/global-input-hook', () => ({ acquireGlobalInputHook: () => () => {} })) -vi.mock('../../../src/main/utils/win32-key-state', () => ({ isAnyModifierPhysicallyDown: () => null })) +vi.mock('../../../src/main/utils/win32-key-state', () => ({ + isAnyModifierPhysicallyDown: () => null, + isAnyChordKeyPhysicallyDown: () => null +})) -const { trackModifierKeys, waitForModifiersReleased, forgetHeldModifiers } = await import( +const { trackModifierKeys, waitForModifiersReleased, forgetHeldModifiers, prepareModifiersForPaste } = await import( '../../../src/main/services/modifier-state' ) @@ -49,3 +52,19 @@ describe('waitForModifiersReleased', () => { expect(await waitForModifiersReleased(40, () => null)).toBe(false) }) }) + +describe('prepareModifiersForPaste (단축키 수락 — 사용자가 키를 쥔 채 기다린다)', () => { + it('단축키(수정자 + Enter/Space)를 다 뗄 때까지 기다린다 — 키 상태는 꾸미지 않는다', async () => { + let down = true + setTimeout(() => { + down = false + }, 80) + const startedAt = Date.now() + expect(await prepareModifiersForPaste({ readPhysicalState: () => down, timeoutMs: 2000 })).toBe('released') + expect(Date.now() - startedAt).toBeGreaterThanOrEqual(70) + }) + + it('끝내 안 떼면 still-held — 호출자는 넣지 않는다', async () => { + expect(await prepareModifiersForPaste({ readPhysicalState: () => true, timeoutMs: 40 })).toBe('still-held') + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-accept-hold.test.ts b/apps/desktop/tests/main/services/suggestion-accept-hold.test.ts new file mode 100644 index 0000000..2d2b0aa --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-accept-hold.test.ts @@ -0,0 +1,172 @@ +// 단축키 수락 — 키 상태를 꾸미지 않고 손을 뗄 때까지 기다린다(꾸몄더니 Enter 가 새어 메시지가 보내졌다, 2026-10-25). + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const keys = vi.hoisted(() => ({ prepare: vi.fn(async () => 'released' as 'released' | 'still-held') })) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: keys.prepare })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +beforeEach(() => { + harness.streamGenerate.mockReset() + harness.insertText.mockClear() + keys.prepare.mockReset() + harness.streamGenerate.mockImplementation(async function* () { + yield ' 내일 다시 볼게.' + }) +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] +}) + +async function session(): Promise { + const service = create() + const context = typingContext() + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(PREFIX, context, 1, 160) + return service +} + +describe('단축키 수락 — 손을 뗄 때까지 창을 띄워 두고 기다린다 (2026-10-25)', () => { + it('기다리는 동안 창(후보)이 남아 있고, 떼면 넣는다', async () => { + let release: (value: 'released') => void = () => undefined + keys.prepare.mockImplementation(() => new Promise((resolve) => (release = resolve))) + const service = await session() + const pending = service.accept() + await vi.waitFor(() => expect(keys.prepare).toHaveBeenCalled()) + expect(service.getState().candidates.length).toBe(1) + expect(harness.insertText).not.toHaveBeenCalled() + + release('released') + expect((await pending).ok).toBe(true) + expect(harness.insertText).toHaveBeenCalledTimes(1) + }) + + it('끝내 안 떼면 넣지 않고 창을 닫는다 (Ctrl+Alt+V 금지)', async () => { + keys.prepare.mockResolvedValue('still-held') + const service = await session() + const result = await service.accept() + expect(result).toEqual({ ok: false, reason: 'stale' }) + expect(harness.insertText).not.toHaveBeenCalled() + expect(service.getState().candidates).toEqual([]) + }) + + it('기다리는 중에 또 눌려도 한 번만 넣는다', async () => { + let release: (value: 'released') => void = () => undefined + keys.prepare.mockImplementation(() => new Promise((resolve) => (release = resolve))) + const service = await session() + const first = service.accept() + await vi.waitFor(() => expect(keys.prepare).toHaveBeenCalled()) + expect((await service.accept()).ok).toBe(false) + release('released') + await first + expect(harness.insertText).toHaveBeenCalledTimes(1) + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-accept-word.test.ts b/apps/desktop/tests/main/services/suggestion-accept-word.test.ts new file mode 100644 index 0000000..d1abb41 --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-accept-word.test.ts @@ -0,0 +1,176 @@ +// 단어 단위 수락 — 앞은 맞고 뒤에서 갈라지는 제안이 많아 첫 단어만 받는 키를 더한다(2026-10-25). + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +const learning = vi.hoisted(() => ({ recordAccepted: vi.fn() })) + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: learning.recordAccepted } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +beforeEach(() => { + harness.streamGenerate.mockReset() + harness.insertText.mockClear() + learning.recordAccepted.mockClear() + harness.streamGenerate.mockImplementation(async function* () { + yield ' 내일 오후에 다시 확인해 볼게.' + }) +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] +}) + +const PREFIX_WORD = '그건 일단' + +function contextFor(prefix: string): TypingContext { + return typingContext({ prefix, documentBefore: prefix, fullText: prefix, caretOffset: prefix.length }) +} + +async function sessionWithSuggestion(): Promise { + const service = create() + const context = contextFor(PREFIX_WORD) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(PREFIX_WORD, context, 1, 160) + expect(service.getState().candidates[0]?.text).toBe('내일 오후에 다시 확인해 볼게.') + return service +} + +describe('단어 단위 수락 (Ctrl+Alt+Space)', () => { + it('첫 단어만 넣고 나머지는 창에 남긴다 — 문장 전체를 배우지는 않는다', async () => { + const service = await sessionWithSuggestion() + const result = await service.accept(undefined, { wordOnly: true }) + + expect(result.ok).toBe(true) + expect(harness.insertText).toHaveBeenLastCalledWith(' 내일', expect.anything()) + expect(service.getState().candidates).toEqual([{ text: '오후에 다시 확인해 볼게.', rank: 0 }]) + expect(learning.recordAccepted).not.toHaveBeenCalled() + }) + + it('넣은 글이 화면에 반영돼도 세션이 이어지고, 다음 단어도 받을 수 있다', async () => { + const service = await sessionWithSuggestion() + await service.accept(undefined, { wordOnly: true }) + service.handleTypingContext(contextFor(`${PREFIX_WORD} 내일`)) + expect(service.getState().candidates[0]?.text).toBe('오후에 다시 확인해 볼게.') + + await service.accept(undefined, { wordOnly: true }) + expect(harness.insertText).toHaveBeenLastCalledWith(' 오후에', expect.anything()) + expect(service.getState().candidates[0]?.text).toBe('다시 확인해 볼게.') + }) + + it('남은 단어가 하나면 평소 수락처럼 넣고 닫으며 배운다', async () => { + const service = await sessionWithSuggestion() + for (let i = 0; i < 4; i += 1) await service.accept(undefined, { wordOnly: true }) + expect(service.getState().candidates[0]?.text).toBe('볼게.') + await service.accept(undefined, { wordOnly: true }) + expect(harness.insertText).toHaveBeenLastCalledWith(' 볼게.', expect.anything()) + expect(service.getState().candidates).toEqual([]) + expect(learning.recordAccepted).toHaveBeenCalledTimes(1) + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-app-scoped-learning.test.ts b/apps/desktop/tests/main/services/suggestion-app-scoped-learning.test.ts new file mode 100644 index 0000000..72a2782 --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-app-scoped-learning.test.ts @@ -0,0 +1,153 @@ +// 앱 안에서만 배우는 앱(Agent Switchboard) — 그 앱 표본이 그 앱 제안의 재료가 된다(2026-10-25). + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + findContinuationHints: vi.fn((_tail: string, _limit?: number, _options?: { appName?: string | null }) => [] as string[]), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ + listPhrases: () => [], + listRecentWrites: () => [], + findContinuationHints: harness.findContinuationHints + }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +beforeEach(() => { + harness.streamGenerate.mockReset() + harness.findContinuationHints.mockClear() + harness.streamGenerate.mockImplementation(async function* () { + yield ' 확인해 줄래.' + }) +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] +}) + +async function promptFor(appName: string): Promise { + const prefix = '그래서 말인데 개발자 도구로 열어서' + const service = create() + const context = typingContext({ prefix, documentBefore: prefix, fullText: prefix, caretOffset: prefix.length, appName }) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(prefix, context, 3, 160) + return String(harness.streamGenerate.mock.calls[0]?.[0] ?? '') +} + +describe('앱 안에서만 배우는 앱의 제안 재료 (Agent Switchboard)', () => { + it('같은 앱 표본에서 이어 쓴 글을 찾아 프롬프트 힌트로 넣는다', async () => { + harness.findContinuationHints.mockReturnValue(['확인해 줄래.']) + const prompt = await promptFor('Agent Switchboard.exe') + expect(harness.findContinuationHints).toHaveBeenCalledWith(expect.any(String), 3, { appName: 'Agent Switchboard.exe' }) + expect(prompt).toContain('확인해 줄래.') + }) + + it('다른 앱에서는 이 경로를 쓰지 않는다', async () => { + await promptFor('KakaoTalk.exe') + expect(harness.findContinuationHints).not.toHaveBeenCalled() + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-copy-guard.test.ts b/apps/desktop/tests/main/services/suggestion-copy-guard.test.ts new file mode 100644 index 0000000..088c918 --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-copy-guard.test.ts @@ -0,0 +1,147 @@ +// 앞 글 베끼기 차단 — 실측 2026-10-25: 앞 대화 문장이 그대로 제안됐다(베낀 글은 모델이 높은 확률을 준다). + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +beforeEach(() => { + harness.streamGenerate.mockReset() +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] +}) + +describe('앞 글 베끼기 차단', () => { + it('모델 후보가 화면·앞 글을 그대로 베꼈으면 버린다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield ' 러스트 데스크는 완전히 드러내고 해야 돼' + }) + const prefix = '러스트 데스크는 완전히 드러내고 해야 돼. 그리고' + const service = create() + const context = typingContext({ prefix, documentBefore: prefix, fullText: prefix, caretOffset: prefix.length }) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(prefix, context, 3, 160) + expect(service.getState().candidates).toEqual([]) + }) + + it('새 문장은 그대로 낸다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield ' 내일 다시 확인해 볼게.' + }) + const prefix = '러스트 데스크는 완전히 드러내고 해야 돼. 그리고' + const service = create() + const context = typingContext({ prefix, documentBefore: prefix, fullText: prefix, caretOffset: prefix.length }) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(prefix, context, 3, 160) + expect(service.getState().candidates[0]?.text).toBe('내일 다시 확인해 볼게.') + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-instant-personal.test.ts b/apps/desktop/tests/main/services/suggestion-instant-personal.test.ts new file mode 100644 index 0000000..03dfaaa --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-instant-personal.test.ts @@ -0,0 +1,183 @@ +// 내 기록(개인 n-gram) 후보를 모델보다 먼저 1번으로 띄우고 모델 후보는 뒤에 붙인다 — 대신하지 않고 더한다. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const ngram = vi.hoisted(() => ({ model: null as import('@d3ro/core/personal-ngram').PersonalNgramModel | null })) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/services/suggestion/PersonalNgramIndex', () => ({ + getPersonalNgramIndex: () => ({ model: () => ngram.model }) +})) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +import { PersonalNgramModel } from '@d3ro/core/personal-ngram' + +beforeEach(() => { + harness.streamGenerate.mockReset() + const model = new PersonalNgramModel() + for (const text of ['링크에서 확인할 수 있어요', '앱에서 확인할 수 있어요', '여기서 확인할 수 있어요']) model.addText(text) + ngram.model = model +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] +}) + +const PREFIX_N = '설정에서 확인할 ' + +async function run(prefix: string, until: (service: SuggestionService) => boolean): Promise<{ service: SuggestionService; seen: string[][] }> { + const service = create() + const seen: string[][] = [] + service.on('updated', (state) => seen.push(state.candidates.map((candidate) => candidate.text))) + const context = typingContext({ prefix, documentBefore: prefix, fullText: prefix, caretOffset: prefix.length }) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(prefix, context, 3, 160) + await vi.waitFor(() => expect(until(service)).toBe(true)) + return { service, seen } +} + +describe('내 기록 후보를 먼저 하나 더 (2026-10-25)', () => { + it('모델을 기다리지 않고 1번으로 뜨고, 모델 후보는 뒤에 붙는다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield ' 수 있는지 한번 볼게요.' + }) + const { service, seen } = await run(PREFIX_N, (s) => s.getState().candidates.length >= 2) + expect(seen[0]).toEqual(['수 있어요']) + expect(service.getState().candidates.slice(0, 2).map((candidate) => candidate.text)).toEqual([ + '수 있어요', + '수 있는지 한번 볼게요.' + ]) + }) + + it('모델 후보가 같은 글이면 하나만 남긴다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield ' 수 있어요.' + }) + const { service } = await run(PREFIX_N, (s) => s.getState().candidates.length >= 1 && !s.getState().candidates[0].source) + expect(service.getState().candidates[0].text).toBe('수 있어요.') + }) + + it('모델이 빈 결과로 끝나도 내 기록 후보는 남고 "제안 사항 없음" 은 뜨지 않는다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield '' + }) + const { service } = await run(PREFIX_N, (s) => !s.getState().generating) + expect(service.getState()).toMatchObject({ notice: null }) + expect(service.getState().candidates.map((candidate) => candidate.text)).toEqual(['수 있어요']) + }) + + it('내 기록이 모르면 예전처럼 모델 후보만 나온다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield ' 김치찌개 먹자.' + }) + const { service, seen } = await run('오늘 저녁은 뭐 먹을까 ', (s) => s.getState().candidates.length >= 1) + expect(seen[0]).toEqual([]) + expect(service.getState().candidates[0].text).toBe('김치찌개 먹자.') + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-no-suggestion-notice.test.ts b/apps/desktop/tests/main/services/suggestion-no-suggestion-notice.test.ts new file mode 100644 index 0000000..5a5f805 --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-no-suggestion-notice.test.ts @@ -0,0 +1,165 @@ +// 후보 없이 끝났을 때 말없이 닫지 않고 "제안 사항 없음" 을 1초 보여 준다. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +import { shouldPresentSuggestion } from '../../../src/main/windows/suggestion-overlay-presenter' +import { suggestionPanelHeight } from '../../../src/main/windows/suggestion-overlay-geometry' + +beforeEach(() => { + harness.streamGenerate.mockReset() +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] + vi.useRealTimers() +}) + +describe('"제안 사항 없음" 알림 (2026-10-25 사용자 요청)', () => { + it('생성 중이 보이다 후보 없이 끝나면 알림을 1초 보여 주고 닫는다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield '' + }) + const service = create() + const cleared: string[] = [] + service.on('cleared', ({ reason }) => cleared.push(reason)) + ;(service as unknown as Internal)._lastContext = typingContext() + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + await (service as unknown as Internal)._generate(PREFIX, typingContext(), 3, 160) + + expect(service.getState()).toMatchObject({ notice: 'no-suggestion', candidates: [], generating: false }) + expect(shouldPresentSuggestion(service.getState())).toBe(true) + expect(cleared).toEqual([]) + + vi.advanceTimersByTime(1000) + expect(service.getState().notice).toBeNull() + expect(cleared).toEqual(['generation-failed']) + }) + + it('사용자가 닫거나 새로 생성하면 알림은 바로 사라진다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield '' + }) + const service = create() + ;(service as unknown as Internal)._lastContext = typingContext() + await (service as unknown as Internal)._generate(PREFIX, typingContext(), 3, 160) + expect(service.getState().notice).toBe('no-suggestion') + + service.dismiss('dismissed') + expect(service.getState().notice).toBeNull() + }) + + it('알림 줄은 상태 줄 자리를 쓴다 (창 높이)', () => { + const base = { candidateCount: 0, activeIndex: 0, generating: false, warmingUp: false, hasPartialText: false } + expect(suggestionPanelHeight({ ...base, hasNotice: true })).toBe(suggestionPanelHeight({ ...base, generating: true })) + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-presence.test.ts b/apps/desktop/tests/main/services/suggestion-presence.test.ts index 8d7c286..5d0dcc9 100644 --- a/apps/desktop/tests/main/services/suggestion-presence.test.ts +++ b/apps/desktop/tests/main/services/suggestion-presence.test.ts @@ -49,7 +49,7 @@ vi.mock('../../../src/main/services/PersonalGraphService', () => ({ vi.mock('../../../src/main/services/TextInsertService', () => ({ getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) })) -vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) diff --git a/apps/desktop/tests/main/services/suggestion-redteam-r1-1.test.ts b/apps/desktop/tests/main/services/suggestion-redteam-r1-1.test.ts index 11359bf..92958c5 100644 --- a/apps/desktop/tests/main/services/suggestion-redteam-r1-1.test.ts +++ b/apps/desktop/tests/main/services/suggestion-redteam-r1-1.test.ts @@ -43,7 +43,7 @@ vi.mock('../../../src/main/services/PersonalGraphService', () => ({ vi.mock('../../../src/main/services/TextInsertService', () => ({ getTextInsertService: () => ({ insertText: harness.insertText }) })) -vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) diff --git a/apps/desktop/tests/main/services/suggestion-redteam-r2-3.test.ts b/apps/desktop/tests/main/services/suggestion-redteam-r2-3.test.ts index 8a33b8e..81ca950 100644 --- a/apps/desktop/tests/main/services/suggestion-redteam-r2-3.test.ts +++ b/apps/desktop/tests/main/services/suggestion-redteam-r2-3.test.ts @@ -42,7 +42,7 @@ vi.mock('../../../src/main/services/PersonalGraphService', () => ({ vi.mock('../../../src/main/services/TextInsertService', () => ({ getTextInsertService: () => ({ insertText: harness.insertText }) })) -vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) diff --git a/apps/desktop/tests/main/services/suggestion-redteam-r3-1.test.ts b/apps/desktop/tests/main/services/suggestion-redteam-r3-1.test.ts index 709b8a7..7c879ff 100644 --- a/apps/desktop/tests/main/services/suggestion-redteam-r3-1.test.ts +++ b/apps/desktop/tests/main/services/suggestion-redteam-r3-1.test.ts @@ -51,7 +51,7 @@ vi.mock('../../../src/main/services/PersonalGraphService', () => ({ vi.mock('../../../src/main/services/TextInsertService', () => ({ getTextInsertService: () => ({ insertText: harness.insertText }) })) -vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) diff --git a/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts b/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts index 47d9c4e..b4a08bd 100644 --- a/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts +++ b/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts @@ -41,7 +41,7 @@ vi.mock('../../../src/main/services/LocalLLMService', () => ({ getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) })) vi.mock('../../../src/main/services/InputTelemetryService', () => ({ - getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [], findContinuationHints: () => [] }) })) vi.mock('../../../src/main/services/PersonalGraphService', () => ({ getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) @@ -49,7 +49,7 @@ vi.mock('../../../src/main/services/PersonalGraphService', () => ({ vi.mock('../../../src/main/services/TextInsertService', () => ({ getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) })) -vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/services/modifier-state', () => ({ prepareModifiersForPaste: async () => 'released' })) vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) diff --git a/apps/desktop/tests/main/services/update-service-status.test.ts b/apps/desktop/tests/main/services/update-service-status.test.ts new file mode 100644 index 0000000..0fe52eb --- /dev/null +++ b/apps/desktop/tests/main/services/update-service-status.test.ts @@ -0,0 +1,122 @@ +// tests/main/services/update-service-status.test.ts +// 설정 정보 탭·타이틀바 칩이 보는 업데이트 상태(getStatus / status-changed)와 수동 다운로드·설치. + +import { describe, it, expect, beforeEach, vi } from 'vitest' +import type { AppUpdateStatus } from '@d3ro/core/types' +import { DEFAULT_UPDATE_POLICY, type UpdatePolicy } from '../../../src/main/update-policy' +import type { UpdaterEventHandlers, UpdaterPort } from '../../../src/main/services/UpdateService' + +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }), +})) + +const store = vi.hoisted(() => ({ values: {} as Record })) +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: string) => store.values[key]), + configSet: vi.fn((key: string, value: unknown) => { + store.values[key] = value + }), + configGetAll: vi.fn(() => store.values), +})) + +type ServiceModule = typeof import('../../../src/main/services/UpdateService') +let UpdateService: ServiceModule['UpdateService'] + +function harness(opts: { policy?: Partial; noUpdater?: boolean } = {}) { + let handlers: UpdaterEventHandlers | null = null + const updater: UpdaterPort = { + checkForUpdates: vi.fn(async () => undefined), + downloadUpdate: vi.fn(async () => undefined), + quitAndInstall: vi.fn(), + setChannel: vi.fn(), + setDifferentialDisabled: vi.fn(), + setAutoInstallOnQuit: vi.fn(), + } + const statuses: AppUpdateStatus[] = [] + const service = new UpdateService({ + createUpdater: (h) => { + handlers = h + return opts.noUpdater ? null : updater + }, + policySource: { load: vi.fn(async () => ({ ...DEFAULT_UPDATE_POLICY, ...opts.policy })) }, + prompter: { askConsent: vi.fn(async () => 'later' as const), askRestart: vi.fn(async () => 'later' as const) }, + currentVersion: () => '1.10.0', + now: () => 5_000, + }) + service.on('status-changed', (status) => statuses.push(status)) + service.initialize() + service.dispose() + return { service, updater, statuses, handlers: () => handlers as UpdaterEventHandlers } +} + +beforeEach(async () => { + vi.resetModules() + store.values = { updateDeviceId: 'device-1' } + UpdateService = (await import('../../../src/main/services/UpdateService')).UpdateService +}) + +describe('UpdateService 상태', () => { + it('업데이터를 만들 수 없는 빌드는 disabled 로 보인다', () => { + const h = harness({ noUpdater: true }) + expect(h.service.getStatus().phase).toBe('disabled') + }) + + it('확인 중 → 최신 버전, 마지막 확인 시각을 남긴다', () => { + const h = harness() + h.handlers().onChecking() + expect(h.service.getStatus().phase).toBe('checking') + h.handlers().onNotAvailable('1.10.0') + expect(h.service.getStatus()).toMatchObject({ phase: 'up-to-date', lastCheckedAt: 5_000, currentVersion: '1.10.0' }) + }) + + it('새 버전 → 다운로드 → 진행률 → 설치 대기 → 재시작 설치', async () => { + const h = harness() + await h.service.handleUpdateAvailable({ version: '1.10.2' }) + expect(h.service.getStatus()).toMatchObject({ phase: 'available', version: '1.10.2', isMandatory: false }) + + await h.service.startDownload() + expect(h.updater.downloadUpdate).toHaveBeenCalledTimes(1) + expect(h.service.getStatus().phase).toBe('downloading') + + h.handlers().onProgress({ percent: 42.4, bytesPerSecond: 1, transferred: 42, total: 100 }) + expect(h.service.getStatus().progress?.percent).toBe(42.4) + + h.handlers().onDownloaded('1.10.2') + expect(h.service.getStatus()).toMatchObject({ phase: 'downloaded', version: '1.10.2', progress: null }) + + await h.service.installNow() + expect(h.updater.quitAndInstall).toHaveBeenCalledTimes(1) + }) + + it('건너뛴 버전도 화면에 남기고, 직접 받기를 누르면 건너뛰기를 풀고 받는다', async () => { + store.values.skippedUpdateVersion = '1.10.2' + const h = harness() + await h.service.handleUpdateAvailable({ version: '1.10.2' }) + expect(h.service.getStatus()).toMatchObject({ phase: 'available', skipped: true, version: '1.10.2' }) + + await h.service.startDownload() + expect(store.values.skippedUpdateVersion).toBeNull() + expect(h.updater.downloadUpdate).toHaveBeenCalledTimes(1) + }) + + it('강제 설치 하한 아래면 묻지 않고 받는 중으로 바뀐다', async () => { + const h = harness({ policy: { forceInstallBelow: '1.10.1' } }) + await h.service.checkForUpdates() + await h.service.handleUpdateAvailable({ version: '1.10.2' }) + await vi.waitFor(() => expect(h.updater.downloadUpdate).toHaveBeenCalledTimes(1)) + expect(h.service.getStatus()).toMatchObject({ phase: 'downloading', isMandatory: true }) + }) + + it('받기 전이면 설치 요청은 아무것도 하지 않는다', async () => { + const h = harness() + await h.service.installNow() + expect(h.updater.quitAndInstall).not.toHaveBeenCalled() + }) + + it('오류는 메시지와 함께 error 단계로, 상태가 바뀔 때마다 알린다', () => { + const h = harness() + h.handlers().onError('net::ERR_INTERNET_DISCONNECTED') + expect(h.service.getStatus()).toMatchObject({ phase: 'error', error: 'net::ERR_INTERNET_DISCONNECTED' }) + expect(h.statuses.at(-1)?.phase).toBe('error') + }) +}) diff --git a/apps/desktop/tests/renderer/update-status-model.test.ts b/apps/desktop/tests/renderer/update-status-model.test.ts new file mode 100644 index 0000000..59a9ea7 --- /dev/null +++ b/apps/desktop/tests/renderer/update-status-model.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import type { AppUpdateStatus } from '@d3ro/core/types' +import { + describeUpdateStatus, + primaryUpdateAction, + progressPercent, + updateChipMessage, +} from '../../src/renderer/components/settings/update-status-model' + +function status(patch: Partial): AppUpdateStatus { + return { + phase: 'idle', + currentVersion: '1.10.1', + channel: 'latest', + version: null, + isMandatory: false, + skipped: false, + progress: null, + lastCheckedAt: null, + error: null, + ...patch, + } +} + +describe('update-status-model', () => { + it('단계마다 문구와 주 동작을 고른다', () => { + expect(primaryUpdateAction(status({ phase: 'up-to-date' }))).toBe('check') + expect(primaryUpdateAction(status({ phase: 'error' }))).toBe('check') + expect(primaryUpdateAction(status({ phase: 'available', version: '1.10.2' }))).toBe('download') + expect(primaryUpdateAction(status({ phase: 'downloaded', version: '1.10.2' }))).toBe('install') + expect(primaryUpdateAction(status({ phase: 'downloading' }))).toBeNull() + expect(primaryUpdateAction(status({ phase: 'disabled' }))).toBeNull() + + expect(describeUpdateStatus(status({ phase: 'available', version: '1.10.2', isMandatory: true })).key).toBe( + 'update.status.availableMandatory' + ) + expect(describeUpdateStatus(status({ phase: 'available', version: '1.10.2', skipped: true })).key).toBe( + 'update.status.skipped' + ) + expect(describeUpdateStatus(status({ phase: 'error', error: 'x' }))).toMatchObject({ tone: 'danger', params: { message: 'x' } }) + }) + + it('칩은 새 버전·받는 중·설치 대기일 때만 보인다', () => { + expect(updateChipMessage(null)).toBeNull() + expect(updateChipMessage(status({ phase: 'up-to-date' }))).toBeNull() + expect(updateChipMessage(status({ phase: 'checking' }))).toBeNull() + expect(updateChipMessage(status({ phase: 'error' }))).toBeNull() + expect(updateChipMessage(status({ phase: 'available', version: '1.10.2' }))?.key).toBe('update.chip.available') + expect(updateChipMessage(status({ phase: 'downloaded' }))?.key).toBe('update.chip.downloaded') + }) + + it('진행률은 0~100 정수로 자른다', () => { + const progress = (percent: number) => ({ percent, transferred: 0, total: 0, bytesPerSecond: 0 }) + expect(progressPercent(status({ progress: progress(42.6) }))).toBe(43) + expect(progressPercent(status({ progress: progress(130) }))).toBe(100) + expect(progressPercent(status({ progress: null }))).toBe(0) + }) +}) diff --git a/docs/evidence/2026-10-24-suggestion-accuracy-research.md b/docs/evidence/2026-10-24-suggestion-accuracy-research.md new file mode 100644 index 0000000..76b6263 --- /dev/null +++ b/docs/evidence/2026-10-24-suggestion-accuracy-research.md @@ -0,0 +1,135 @@ +# 문장 예측 정확도·속도 개선 — 실측 + 리서치 (2026-10-24) + +## 1. 실측 (개발 PC `_local` DB, 10일치) + +- 제안 1,806건, 수락 31건(1.7%). 첫 후보 지연 중앙값 572 ms, p90 968 ms. 제안 길이 중앙값 22자. +- 재생 비교: 제안 시점 접두 뒤에 실제로 친 글을 찾을 수 있던 67건 기준(표본 작음, 샘플이 조각나 있어 잡음 큼) + - 첫 어절 일치 9% (6/67), 앞 2글자 이상 일치 10%, 평균 공통 접두 1.2자. +- 실패 유형 + 1. **주소·경로 입력 중에도 문장을 제안** — `haramlog.app/ja/beta` 에 고객센터식 문장 12개, 실제는 `?utm_source=…`. + 2. **사용자 대신 상대방처럼 답함** — 반말 채팅("그럼 이")에 존댓말 안내문·상대 답장 같은 문장. + 3. **너무 김** — "문장을 자연스럽게 끝맺으세요" 지시로 완성 문장을 내지만, 실제 글은 첫 어절부터 갈라진다. + 4. **4B 모델에 프롬프트가 무거움** — 앱·첫머리·사실·최근 글 4개·앞 문맥 900자·힌트 최대 11줄·이미 제안한 문장 최대 12개. + 5. **계산 낭비** — 화면에는 대부분 1~2개만 보이는데 후보를 최대 12개까지 순차 생성. +- Ollama 0.40.5 (번들) 는 `/api/generate` 에서 `logprobs`·`top_logprobs` 와 `prompt_eval_cached_count` 를 돌려준다(직접 호출로 확인). + +## 2. 리서치 요약 (근거·날짜는 아래 출처) + +| 기법 | 근거 | 기대 효과 | 비용 | +|---|---|---|---| +| 신뢰도 게이팅 — 길이 정규화 logprob 이 임계값 미만이면 안 보임, 1순위 1개만 | Gmail Smart Compose (KDD 2019), Intuit 2023 | 노출 대비 수락률 큰 폭 상승 | 낮음 | +| 확률 급락 지점에서 자르기(짧은 구 단위) + 어절 단위 부분 수락 | Smart Compose 종료 규칙, Cotypist(1~2 단어, Tab 단어 수락) | 맞는 글자 비율 상승 | 낮음 | +| 어절 경계에서만 호출(조합 중·글자마다 호출 금지) | ChaI-TeA 2024: 글자마다 제안 시 수락률 약 -60%, 절약 +3% 뿐 | 수락률↑·호출↓ | 낮음 | +| 학습형 표시 필터(앱·입력 속도·최근 수락/무시·첫 토큰 확률) | JetBrains 2025-26: 수락률 +33~48%, Cursor Tab RL: 제안 -21%·수락률 +28% | 큼 | 중간 (로그 먼저) | +| 사용자 n-gram/구문 그래프 점수로 재순위 (`LM logprob + λ·log P_user`) | Smart Compose 개인 n-gram 보간 α=0.4: CTR +6%, ExactMatch +10% | 개인화가 보이게 됨 | 중간 | +| 힌트를 접두와 가장 비슷한 2~3개로 축소 | 소형 모델 문맥 활용 한계(arXiv 2603.11513), ChaI-TeA 짧은 이력 | 정확도·지연 | 낮음 | +| 프롬프트 앞부분 고정 → KV 캐시 재사용 | Ollama `prompt_eval_cached_count` 로 실측 가능, Gemma 4 SWA 캐시 이슈(llama.cpp #21468) 주의 | 지연 | 낮음 | +| 투기적 디코딩(MTP 드래프터) | llama.cpp 에서 E4B 1.5~1.7x, Ollama 는 MLX 위주·Windows 미확인 | 지연(상한 낮음: 출력 8~12 토큰) | 중간 | +| 소형 한국어 모델 비교(HyperCLOVAX-SEED 1.5B, Gemma 4 E2B, Qwen3-1.7B) | 지식형 벤치마크만 있음 — 자체 평가 필요. EXAONE 은 NC 라이선스 | 지연·메모리 | 중간 | +| LoRA 개인화 | 데이터 수천 문장, 근거 약함 | 불확실 | 높음 → 보류 | + +평가: 재생 하네스(어절 경계마다 접두 → 실제 이어 쓴 글과 비교), 지표는 saved@k(수락 길이 − 수락 횟수)/(전체 길이 − 1), 첫 어절 일치, **coverage(노출률)를 맞춘 상태에서** 비교. 수락률만 보면 사소한 제안으로 쏠린다. + +## 3. 출처 + +- Smart Compose, KDD 2019: https://ar5iv.labs.arxiv.org/html/1906.00080 +- Intuit 예측 작문, 2023-08: https://arxiv.org/html/2308.13576 +- Sequential Decision-Making for Inline Autocomplete, 2024-03: https://arxiv.org/html/2403.15502v1 +- ChaI-TeA, 2024-12: https://arxiv.org/html/2412.18377v3 +- JetBrains "less is more", 2025-03: https://blog.jetbrains.com/ai/2025/03/ai-code-completion-less-is-more/ +- JetBrains Control Models, 2026-01: https://arxiv.org/html/2601.20223v1 +- Cursor Tab RL, 2025-09: https://cursor.com/blog/tab-rl +- 사전 필터링, 2025-11: https://arxiv.org/html/2511.18849v1 +- 소형 모델 문맥 활용, 2026-03: https://arxiv.org/pdf/2603.11513 +- Gboard 합성·연합 학습, 2025-07: https://research.google/blog/synthetic-and-federated-privacy-preserving-domain-adaptation-with-llms-for-mobile-applications/ +- Ollama generate API(logprobs): https://docs.ollama.com/api/generate +- llama.cpp speculative: https://github.com/ggml-org/llama.cpp/blob/master/docs/speculative.md +- Gemma 4 드래프터 실측: https://dev.to/gde/do-drafters-work-on-small-models-gemma-4-e2b-and-e4b-on-two-small-gpus-1b4g +- llama.cpp Gemma 4 캐시 이슈: https://github.com/ggml-org/llama.cpp/issues/21468 +- VS Code Copilot 인라인 모델, 2026-09: https://code.visualstudio.com/blogs/2026/09/16/building-the-github-copilot-inline-suggestions-model-part-one +- Cotypist press: https://cotypist.app/press +- HyperCLOVAX-SEED 1.5B: https://huggingface.co/naver-hyperclovax/HyperCLOVAX-SEED-Text-Instruct-1.5B + +검색 요약에만 의존한 수치가 섞여 있다. 한국어 구어체 이어쓰기에 대한 직접 근거는 찾지 못했으므로 재생 하네스 실측으로 확인한다. + +## 4. 재생 평가 결과 (2026-10-24, `tests/eval/suggestion-replay.eval.test.ts`) + +입력: 개발 PC `_local` DB 의 직접 친 문장 352개 중 120개를 어절 경계에서 잘라 재생(결정적, temperature 0, gemma4:e4b, 개인 힌트 없음). +정답 문장 일부가 학습 버퍼링 이전의 조각이라 절대값은 낮게 나온다 — 변형 간 비교용이다. + +| 방식 | 노출 | 첫 어절 정확(노출 중) | 단어 앞부분까지 맞음(노출 중) | 지연 p50 | +|---|---|---|---|---| +| 앱 프롬프트 그대로 (`app`) | 76% | 3.3% | 3.3% | 212 ms | +| + 같은 앱 15분 내 앞 글 (`recent`) | 79% | 5.3% | 5.3% | 215 ms | +| 지시·템플릿 없는 순수 이어쓰기 (`plain`) | 61% | 5.5% | 5.5% | 142 ms | +| **개인 n-gram (트라이→바이그램, 정답 문장 제외)** | 58% | **14.3%** | **24.3%** | ~0 ms | +| n-gram 우선, 없으면 LLM | 83~92% | 9~11% | 16~18% | — | + +- logprob 게이팅만으로는 정밀도가 오르지만(최대 25%) 노출이 6% 로 줄고 제안이 1~2자뿐이라 아낀 글자가 거의 0이다. +- LLM 첫 어절과 n-gram 이 일치하면 거의 다 맞지만 120건 중 2~4건뿐 — LLM 이 사용자 말투와 거의 겹치지 않는다. +- 표본: n-gram 유효 적중 17/70 — 오차 ±10%p 수준. 그래도 24% 대 4% 는 우연으로 보기 어렵다. +- 분석 스크립트: `apps/desktop/tests/eval/analysis/*.py` (simulate_gating · ngram_eval · hybrid_eval — `cases.json` 을 입력으로 받는다). + +## 5. 적용 결과 (같은 120건, 앱 기준값 그대로) + +적용: ① 개인 n-gram 우선(`core/personal-ngram.ts`, `PERSONAL_NGRAM_SETTINGS`) ② 주소·경로 입력 중 제안 끔(`isAddressInput`, 사유 `address-input`) +③ 모델 후보는 첫 어절 로그 확률 합 −0.5 미만이면 숨기고, 토큰 확률 −1.0 미만에서 자름(`core/suggestion-confidence.ts`) ④ 생성 중 글자 흘려보내기 끔(대부분 버려져 깜빡임만 남음). + +| 상황 | 지표 | 이전 (앱 LLM) | 적용 후 | +|---|---|---|---| +| 단어 끝에서 멈춤 | 노출 | 76% | 17% | +| | 첫 어절 적중(노출 중) | 3.3% | **25%** | +| | 통째로 맞음(전체 중) | 0% | 4.2% | +| | 아낀 글자 비율 | 0.2% | 0.7% | +| 단어 중간에서 멈춤 | 노출 | 90% | 58% | +| | 첫 어절 적중(노출 중) | 6.5% | **35%** | +| | 통째로 맞음(전체 중) | 0% | **9.2%** | +| | 아낀 글자 비율 | 0.1% | 2.0% | +| | 지연 p50 | 208 ms | 1 ms | + +틀린 제안이 크게 줄었다(단어 끝 기준 노출 중 오답 97% → 75%). 노출은 줄었지만 보이는 제안의 품질이 7~10배 올랐다. +남은 한계: 단어 끝의 다음 어절 예측은 여전히 약하다(노출 17%). 실사용 확인 전이다. +재현: `D3RO_EVAL_VARIANT=hybrid D3RO_EVAL_CUT=word|mid D3RO_EVAL_GATE=1 …` (파일 머리말 참고). + +## 6. 실사용 피드백 반영 (2026-10-25) + +- 1차 "생성 중만 뜨고 꺼짐": n-gram 경로가 IME 조합 중이면 막혀 한 번도 안 돌았다(평가가 조합 상태를 흉내 내지 않아 못 잡음). 조합 중 허용, "생성 중" 자리 제거. +- 2차·3차 "상관없는 아무말, 문맥 무시": LLM 이 화면의 앞 대화를 그대로 베꼈고(베낀 글은 확률이 높아 확신 검사를 통과), 느슨하게 푼 n-gram(지지 1)은 근거 약한 어절을 냈다. + → 사용자 결정 A→B→C. A: 타이핑 중 LLM 제안 끔(`suggestionInlineModel` 기본 false), n-gram 단어 끝은 지지 2·비율 0.5, LLM 경로에 앞 글 베끼기 차단(`copiesContext`). + A 실측(n-gram 만): 단어 끝 노출 12.5%·적중 33%, 단어 중간 노출 62.5%·적중 35%·통째로 맞음 23%. + +## 7. B — 모델을 키우면 나아지는가 (2026-10-25) + +같은 120건, 템플릿 없는 이어쓰기(`plain`, 같은 앱 15분 내 앞 글 포함), 거르기 없음, 베끼기 차단 적용. RTX 3080 Ti 12GB. + +| 모델 | 단어 끝 적중(노출 중) | 단어 중간 적중(노출 중) | 지연 p50 (단어 끝) | +|---|---|---|---| +| gemma4:e4b (현재) | 3.5% | 9.1% | 223 ms | +| gemma3:12b | 4.9% | 11.9% | 235 ms | +| qwen3:8b | 5.1% | 11.8% | 2363 ms | +| exaone3.5:7.8b | 2.6% | 4.3% | 114 ms | +| (참고) 개인 n-gram | **33%** | **35%** | ~0 ms | + +결론: 모델을 3배 키워도 적중은 1~3%p 오를 뿐이다. 병목은 모델 크기가 아니라 "이 사람이 다음에 칠 말"이 일반 언어 지식으로는 예측되지 않는다는 점이다. 타이핑 중 자동 LLM 제안은 크기를 키워도 쓸 만해지지 않는다. + +## 8. C — 정체성 결정과 두 단계 제안 (2026-10-25) + +사용자 결정: 입력 제안은 **"알아서 오는 앱"** 이다(단축키 호출형은 정체성에 맞지 않음). 기다릴 시간은 사용자가 정한다. + +- 짧은 멈춤(`suggestionTriggerDelayMs`, 기본 600 ms) → 개인 n-gram (확실할 때만, 지연 0). +- n-gram 이 비었고 **생각하는 시간**(`suggestionModelDelayMs`, 기본 2500 ms, 1~10초)만큼 멈췄을 때만 → LLM 문장 후보(+오타 교정, 확신 검사, 앞 글 베끼기 차단). +- `suggestionInlineModel`(기본 켜짐)을 끄면 n-gram 만 쓰고 모델을 올리지 않는다(RAM ~11GB 절약). 설정 → 입력 패널에 스위치·숫자 칸. +- 생각하는 시간을 0 으로 두면 예전 동작(n-gram 이 비면 바로 LLM). 모델 준비 여부는 두 단계 모드에서 n-gram 단계를 막지 않는다. +- LLM 단계의 적중률 자체는 오르지 않는다(§7). "오래 멈췄을 때만" 이 노이즈를 줄이는 핵심이며, 체감 효과는 실사용으로 확인해야 한다. + +## 9. 결론 — 되돌림과 교훈 (2026-10-25) + +실사용 평가: "이전보다 몇십배 안 좋은 앱". 제안 동작을 v1.10.1 로 되돌렸다(§5~§8 의 n-gram 우선·확신 게이팅·짧게 자르기·두 단계 설정 모두 철회. 백업: `scratch/experiment-2026-10-25/`, 저장소 밖). + +교훈 +1. **지표가 가치를 대신하지 못했다.** 첫 어절 적중(정밀도)은 올랐지만 노출이 76%→12% 로 줄었다. 사용자에게 가치는 자주·문장 단위·여러 후보 중 고르기였다(이전 방식에서도 31회 수락). +2. **한 번에 여러 가지를 바꿨다.** 무엇이 체감을 망쳤는지 가를 수 없었다. 다음부터 변경 하나 → 실사용 확인 → 다음. +3. **재생 평가의 사각지대:** IME 조합 상태 없음(조합 중이면 막히는 버그를 못 잡음), 조각난 정답 문장, 실제 화면 문맥 없음(LLM 의 앞 글 베끼기를 못 봄). +4. **모델 크기는 다음 말 적중의 병목이 아니다**(§7). 개인 n-gram 은 정밀하지만 재료(학습 표본 ~1,500개, 주 입력 앱 Agent Switchboard 가 학습 제외)가 빈약하다. + +유지한 것: `copiesContext`(앞 글 베끼기 차단), `isAddressInput`(주소·경로 입력 중 제안 끔), 학습 표본 문장 단위 저장·오염 정리, 문구 삭제 시 그 문구가 든 표본도 삭제, 재생 평가 도구(보조 지표로만). diff --git a/docs/map/00-index.md b/docs/map/00-index.md index f13fdb3..b995502 100644 --- a/docs/map/00-index.md +++ b/docs/map/00-index.md @@ -2,14 +2,16 @@ > Status: ACTIVE > Last full audit: 2026-09-13 -> Last update: 2026-09-27 — **v1.7.0·v1.8.0·v1.9.0 릴리스 + 기기 간 동기화 재작성 + 운영 DB 정렬.** 데스크톱↔모바일·웹 동기화를 outbox·서버시각 커서·삭제 기록(`sync_tombstones`)·실시간(`ws`) 엔진으로 다시 만들고, 이력·사전·회의·메모 태그·명령·템플릿·지식베이스·녹음·공통 설정·기기 등록까지 넓혔다(MEM-13, ACC-08/09, MEM-05). 운영 Supabase가 `0028`에 멈춰 있던 것을 발견해 `0029`–`0035`를 적용하고 함수 23개를 재배포했다(GAP-OPS-01 — 사용자가 자기 tier를 올릴 수 있던 권한 구멍 포함). 모바일 기기 목록·데이터 내보내기 결함도 고쳤다(GAP-SYNC-03/04). 무서명 로컬 게시 예외(GAP-REL-06) 유지. +> Last update: 2026-10-27 — **v1.11.0 릴리스 + Araso 방식 한영 자동 변환·터미널/Vim/xterm.js 지원 완성 (`INPUT-19`, `GAP-INPUT-08`).** `nyttastudio/araso`를 분석해 `@d3ro/core/araso-layout` 및 `@d3ro/core/typo-correction`을 대폭 업그레이드하고 터미널·Vim·xterm.js(`Agent Switchboard`)까지 확장했다: 영어·약어·CamelCase+한국어 조사/단어 혼합어 분리(`githubdp`→`github에`, `PDFvkdlf`/`ㅖㅇㄹ파일`→`PDF파일`, `Reactzjavhsjsxm`→`React컴포넌트`, `dhsmfdmsgoogledptj`→`오늘은google에서`, `1:1ansdml`→`1:1문의`, 2글자 약어 받침 호응 `TMdms`→`TM은` vs `TMsms`→`쓰는`), 쌍자음 잔여 Shift 정규화(`djEJs`→`어떤`, `qkRNjTdj`→`바꿨어`), 한글 자판 상태 영어/혼합어 역변환(`ㅗ디ㅣㅐ 재깅`→`hello world`, `내ㅡㄷ샤ㅡㄷ`→`sometime`, `ㅎ샤ㅗㅕㅠ에`→`github에`, `ㅠㅕㅎ가`→`bug가`, 알파벳+조사 `ㄴ가`→`s가`, `ㄴ은`→`s은`), 문장 문맥 한영 전환(`Stay hungry, stay foolishsms wkqtmdml akfdlek.`), URL·경로·이메일 보호(`isUrlOrPathRun`), 터미널·Vim 명령(`:ㅈㅂ`→`:wq`, `:ㅂ!`→`:q!`, `퍄ㅡ `→`vim `, Vim 노멀 모드 교정 억제), `SendInput(KEYEVENTF_UNICODE)` 직접 유니코드 타이핑(클립보드 무접촉), 단어 경계(`25ms`)와 어절 내부(`650ms`) 유휴 분리 및 완성형 음절(`[가-힣]`) 한정 `commitComposition`으로 고속 타이핑 시 글자 삼킴·유령 공백·앞글자 중복을 완전히 해소했다. 통계 수집 동의(`inputTelemetryEnabled`)가 꺼져 있어도 기본 기능(`typoAutoCorrectEnabled: true`)으로 즉시 동작한다. +> +> Previous update: 2026-09-27 — **v1.7.0·v1.8.0·v1.9.0 릴리스 + 기기 간 동기화 재작성 + 운영 DB 정렬.** 데스크톱↔모바일·웹 동기화를 outbox·서버시각 커서·삭제 기록(`sync_tombstones`)·실시간(`ws`) 엔진으로 다시 만들고, 이력·사전·회의·메모 태그·명령·템플릿·지식베이스·녹음·공통 설정·기기 등록까지 넓혔다(MEM-13, ACC-08/09, MEM-05). 운영 Supabase가 `0028`에 멈춰 있던 것을 발견해 `0029`–`0035`를 적용하고 함수 23개를 재배포했다(GAP-OPS-01 — 사용자가 자기 tier를 올릴 수 있던 권한 구멍 포함). 모바일 기기 목록·데이터 내보내기 결함도 고쳤다(GAP-SYNC-03/04). 무서명 로컬 게시 예외(GAP-REL-06) 유지. > > Previous update: 2026-09-24 — **v1.6.0 릴리스.** 버전 SSOT를 1.6.0(android/iOS 1060000)으로 올렸다. 다음 문장 제안을 1개씩 순차 생성해 최대 12개·3개씩 페이지로 보여 주고(Ctrl+Alt+↑↓ 이동, ←→ 페이지, Enter 수락, Esc 닫기; 기존 기본 단축키는 revision 5에서 이관), 오버레이를 재설계했다(`INPUT-06`/`INPUT-07`). 개인 문구 코퍼스는 터미널·에디터·코딩 에이전트와 비문장·플레이스홀더를 학습하지 않고 기존 데이터도 같은 규칙으로 정리한다(`INPUT-04`/`INPUT-05`). 제안 단축키가 받아쓰기를 켜던 버그, 구버전 사이드카가 `/uia/focus` 없이 남던 버그(런타임 최소 버전 1.5.0), Ollama 러너 콘솔 창, 사이드카 이중 기동을 고쳤다. 실시간 자막 창은 끌어서 옮길 수 있고 첫 자막 전까지 준비 안내를 보인다. 무서명 로컬 게시 예외(GAP-REL-06)를 유지한다. > > Previous update: 2026-09-22 — **Gemma/Ollama 폭주 방어 계약을 기록했다.** 19:14:12 부팅 워밍업이 `keep_alive: 30m`으로 `gemma4:e4b`를 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 강제 상주시킨 것이 관측됐으며, 같은 시점 Windows GPU Engine PID 표본에는 Ollama의 활성 compute가 없었다. 즉 당시 상태는 무한 추론이 아니라 강제 residency였다. 19:11:17~19:11:58의 자동 제안 연속 생성은 기존 900 ms·12/min·5 candidates·128 tokens·한 글자 재생성 정책이 허용한 burst였다. 현재 구현 계약은 부팅 warmup 제거, `keep_alive: 2m`, 제안 600 ms / 최소 5 s 간격 / 기본 6회·hard max 12회 per min / 3 candidates / 64 tokens / 12-char growth / 8 s timeout, 그리고 요청별 취소·상한·종료 정리다. 독립 표적 검증은 6 test files / 69 tests passed / 0 failed, 변경 코드·테스트 ESLint와 `git diff --check`도 exit 0이다. Raw Ollama에서는 cold bounded 요청이 client hard timeout 15.044 s에 취소된 뒤 `/api/ps`가 비었고 `/api/version`은 80 ms에 회복했다. 명시 warmup은 HTTP 200 / 16.639 s, 후속 warm 요청은 body `options.num_predict=1`, `keep_alive='2m'`로 553 ms HTTP 200 / `done:true` / `eval_count:1` / `done_reason:length`였고 `/api/ps` expiry는 약 119.9 s였다. **19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 한 번의 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다.** 이는 raw API 수준의 expiry 뒤 unload 확인일 뿐 앱 재시작·GUI·실제 타이핑 증거는 아니므로 상태는 `[~]`로 유지한다 (`11` GAP-LLM-04, GAP-INPUT-06). > > Previous update: 2026-09-21 — **Input intelligence (입력 레메트리 + 다음 문장 제안) 신규**. 데스크톱에 입력 수집기(`InputTelemetryService`), UIA 컨텍스트 브리지(사이드카 `GET /uia/focus`), 제안 서비스(`SuggestionService`), 어렛 커 오버레이, 설정 > 입력 탭(동의·정책·주간 인사이트·개인 문구)을 추가했다. 카탈로그에 `INPUT-01`~`INPUT-08`(전부 데스크톱 `[~]` — 유닛 48건은 GREEN 이지만 **실앱 타이핑 검증 전**), 백로그에 GAP-INPUT-01~05 + GAP-LLM-03, §7 에 CONSTRAINT-INPUT-01(키 내용 미저장 — ActivityWatch 정책 채택)을 기록. 설계 근거는 조사 기반이다: 어렛은 `GetGUIThreadInfo` 가 아니라 UIA `TextPattern.GetSelection`(Chromium 은 `TextPattern2` 미구현), 타이핑 스트는 키코드 복원이 아니라 UIA 스냅샷 diff(한/일 IME 대응), 디바운스/토큰 한도는 인라인 컴플리션 실측값(Continue 350 / Tabby 250 / twinny 300 ms, 출력 64~256 토큰). 의존성: `koffi` 3.3.1(포그라운드 창 FFI), 사이드카 `uiautomation` 2.0.29 + `comtypes`. 데스크톱 유닛 총계 1409(+49), Electron ABI 실행에서 신규 실패 0건. 당시의 24.7초/4.9초 지연 설명과 `keep_alive: 30m`·부팅 워밍업 처방은 **현재 상태가 아닌 과거 가설/완화 이력**이며, 최신 운영 결론은 위 2026-09-22 항목과 `11` GAP-LLM-04를 따른다. 직전: LLM instruction-prompt fix (`9c2b4d4`): the custom-instruction path inserted the instruction's own wording instead of the processed result and had **never worked in any shipped release** (`v0.1.0-alpha`..`v1.4.0`, introduced `fea923d` 2026-04-05, not a regression). `llm-prompts.ts` is now the SSOT for prompt resolution and placeholder substitution, shared by `VoiceModeService` / `ChainService` / `LLM.PROCESS`. AI-04/05/06/07 are demoted to `[~]` on desktop — fixed with unit tests, but **not verified in a running app** and the four related `tests/red/*.usecase.test.ts` could not execute (`better-sqlite3` ABI). New: GAP-LLM-01 (no target-language setting), GAP-LLM-02 (this fix unverified); GAP-INFRA-06 amended (the ABI masks verification, not just dev-env switching cost); GAP-I18N-01 amended (`popup.error.default` missing in 10 locales). Earlier the same day: CAP-16 (desktop key bindings rebuilt on one `@d3ro/core/keybinding` SSOT — multiple bindings per action, mouse buttons, `HOTKEY` → `KEYBINDING` IPC group), verified on Windows by a manual run, so CAP-16 and CAP-02 are `[x]` and GAP-KEY-01 is closed. Still open: GAP-KEY-02/03, GAP-QA-02, GAP-I18N-01/02, GAP-INFRA-06, GAP-LLM-01/02, GAP-INPUT-01~05; `11` §7 holds accepted design constraints (things deliberately kept, not gaps) -> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.9.0` (`release/product-version.json`, released 2026-09-27) +> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.11.0` (`release/product-version.json`, released 2026-10-27) > Purpose: let any agent (or human) answer two questions in under a minute: > 1. **What infrastructure exists?** (build, CI, services, APIs, data, packages, deploy) > 2. **How far is each feature developed?** (per surface, with file anchors and status) diff --git a/docs/map/03-shared-packages.md b/docs/map/03-shared-packages.md index 1b13a5d..7dca238 100644 --- a/docs/map/03-shared-packages.md +++ b/docs/map/03-shared-packages.md @@ -18,6 +18,7 @@ The canonical place for types and cross-surface logic. Both desktop and web/mobi | IPC channels | `./ipc-channels` | `IPC_CHANNELS` object + `IPCChannel` union. **SSOT** for every desktop IPC channel (VOICE, AUDIO, STT, TTS, LLM, KEYBINDING, CONFIG, HISTORY, UNIFIED_SEARCH, DICTIONARY, WINDOW, SYSTEM, STATS, MEMO, VOICE_COMMAND, CONTEXT, CHAIN, CAPTION, FILE_TRANSCRIPTION, MEETING_SUMMARY, DICTATION_TEMPLATE, VOICE_CONVERSATION, RAG, VOICE_ACTION, MEETING_MODE, MEETING_DOC_TEMPLATE, MEETING_CHAT, LICENSE, CLOUD_SYNC, INSTRUCTION, SYSTEM_AUDIO, POPUP_RESULT, POPUP_HISTORY, POPUP_COMMAND, POPUP_CAPTION, VOICE_PARTIAL, CLIPBOARD, APP, ONLINE_AUTH, ADS, SUPPORT, INPUT_TELEMETRY, SUGGESTION, POPUP_SUGGESTION) | | Key bindings | `./keybinding` | **SSOT** for every global shortcut in the app: `KeyBinding` (`device`/`code`/`ctrl`/`alt`/`shift`/`meta`), `KEY_CATALOG` (10 selectable groups incl. mouse), `KEYBINDING_ACTIONS` (9 rebindable actions incl. the three suggestion actions), `bindingKey`/`normalizeBinding`/`validateBinding`/`detectBindingConflicts`/`formatBindingSegments`/`searchKeyCatalog`/`parseBindingMap`. Persisted as `AppConfig.keyBindings`. i18n keys are exposed as plain `string` so core stays independent of `@d3ro/i18n`; consumers narrow at the boundary (`asTranslationKey`) and a contract test guards the keys — accepted constraint, `11` §7 CONSTRAINT-I18N-01. Tests: `__tests__/keybinding*.test.ts` via `vitest.config.ts` (`npm run test --workspace=@d3ro/core`), 117 cases as of 2026-09-21 | | Input intelligence | `./input-intelligence` | **SSOT** for the input-telemetry and next-sentence-suggestion domain (added 2026-09-21): key classification (`classifyKeyStroke`), text metrics (`countWords`/`countSentences`/`endsSentence`/`textBeforeCaret`), `computeTypedDelta` (UIA snapshot diff — the IME-safe way to count typed text), `decideSuggestion` + `isAppExcluded` (when to request / skip / clear), `parseSuggestionCandidates`/`sanitizeSuggestionLine` (prompt-leak and prefix-echo defence), `anchorFloatingPanel` (caret-anchored overlay placement), `mergeActivityBucket`/`summarizeActivity`/`pixelsToMeters`, `extractPhrases`/`selectPhraseHints`, `INPUT_TELEMETRY_DEFAULTS`/`SUGGESTION_DEFAULTS` | +| Typo correction & Araso layout | `./typo-correction`, `./araso-layout` | **SSOT** for built-in automatic Han/Eng conversion and typo auto-correction (upgraded 2026-10-26): 2-set Korean/English layout conversion (`engToHangul`/`hangulToEng`), lingering Shift normalization (`normalizeLingeringShift`/`lingersAfterKoreanShift`), mixed-word splitting with Korean particle batchim agreement (`splitMixedWord`/`particleAgrees`), reverse Hangul-to-English/mixed restoration, URL/path/email run protection (`isUrlOrPathRun`), deterministic spelling & jamo-noise rules (`detectTypos`/`detectJamoNoise`), and LLM typo validation (`validateModelCorrections`). | | Constants | `./constants` | Shared constants | | Crypto license | `./utils/crypto-license` | Ed25519 license sign/verify (used by admin issuer + desktop verifier) | | PII | `pii-redactor`, `secure-memory` | Redaction + secure memory helpers | diff --git a/docs/map/04-desktop-app.md b/docs/map/04-desktop-app.md index 22ed609..a8f0eef 100644 --- a/docs/map/04-desktop-app.md +++ b/docs/map/04-desktop-app.md @@ -83,12 +83,13 @@ Singleton + `EventEmitter` pattern (`getXService()` accessors). ### Input intelligence (2026-09-21; Local Flow Intelligence extension 2026-09-22) | Service / file | Purpose | |---|---| -| `InputTelemetryService` | Global input telemetry: keystroke/click/scroll counters, mouse travel (Manhattan sum of per-axis deltas), active time, per-hour-per-app buckets flushed every 5 s; typed-text learning via UIA snapshot diffs. It extends the existing telemetry store with Flow Radar (hourly activity density + chars + edit stability; a potential-focus score, **not** a real session), Edit Friction (chars/backspaces; edits per 100 chars), App Quality (per-app suggestion total/accepted/accept rate/average latency), Privacy Receipt (actual row counts and retention), and Smart Exclusion evidence. Raw key events, key codes and content streams are never retained; separately, opt-in learned text may be retained in `typing_samples` and `personal_phrases` under the stated receipt policy. Consent is opt-in (`inputTelemetryEnabled`, `inputLearnTypedText`). | +| `InputTelemetryService` | Global input telemetry and context observer: keystroke/click/scroll counters, mouse travel (Manhattan sum of per-axis deltas), active time, per-hour-per-app buckets flushed every 5 s; typed-text learning via UIA snapshot diffs. **Since 2026-10-26**, the UIA context observer runs by default whenever `typoAutoCorrectEnabled !== false` (or `suggestionEnabled === true`), while SQLite `input_activity` persistence only runs when `inputTelemetryEnabled === true` (opt-in). **Since 2026-10-27**, includes `TerminalKeystrokeTracker` (`@d3ro/core/input-intelligence`) + `isForegroundKoreanIme` (`utils/win32-foreground.ts`) to reconstruct the active terminal/Vim line (`reconcileWithScreen` for UIA screen buffers like Windows Terminal/pwsh/cmd, `reconcileWithXtermValue` for `xterm.js` `