feat(desktop): typo auto-correct and context-aware sentence prediction
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Has been cancelled
deploy-site / deploy (push) Has been cancelled
ci / 워크스페이스 빌드 검증 (push) Has been cancelled
ci / 모바일 린트·타입·Jest (push) Has been cancelled
ci / Supabase Edge Functions + Cloudflare Worker (push) Has been cancelled
ci / .NET API 서버 테스트 (push) Has been cancelled
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Has been cancelled
deploy-site / deploy (push) Has been cancelled
ci / 워크스페이스 빌드 검증 (push) Has been cancelled
ci / 모바일 린트·타입·Jest (push) Has been cancelled
ci / Supabase Edge Functions + Cloudflare Worker (push) Has been cancelled
ci / .NET API 서버 테스트 (push) Has been cancelled
Typo auto-correct (INPUT-19) - TypoCorrectionService + core typo-correction: 2-set Korean layout mistypes both ways, always-wrong spellings, near-misses of the user's frequent words, optional model check re-validated in core; applied by backspace N + paste and cancelled on new keys or window change. Prediction quality (INPUT-20/21) - gemma models are sent raw with the user's unfinished sentence pre-filled into the model turn, so the model truly continues the text (mid-word joins and spacing exact). Other models keep the instruction prompt. - Context: text before the caret (opening lines and a fact list of names, dates, amounts outside the 400-char window), messages just sent in the same chat window (memory only, 30 min), personal-graph follow-ups and IDF-ranked related sentences with Korean stemming. - Guards: first sentence only, restated-prefix stripping (also fixes the instruction path), repeat drop, no invented dates/names/numbers (one retry), plain -다 register, no emoji unless the user uses them, search-box keywords. Fill loop mixes instruction prompts for variety. - Opt-in real-model probe: tests/integration/suggestion-quality.ollama.test.ts Suggestions now actually show up - Terminal (Claude Code): caret trust from the input line, not the whole screen (status line below the box blocked every keystroke); Korean composition counts as typing at the end; a grey placeholder filling the empty box at once is not user text. - Chrome: UIA focus flicker while typing no longer resets "edited". - KakaoTalk/RichEdit: trailing paragraph mark ignored for edit position and stripped so accepted text keeps its separating space. - While the overlay is visible the suggestion shortcuts are captured so Ctrl+Alt+Enter no longer also types a newline; released when hidden. - nut-js preloaded after boot (first accept waited 4.8 s).
This commit is contained in:
parent
5ca3709b32
commit
3cac14f668
56 changed files with 4700 additions and 258 deletions
|
|
@ -22,6 +22,9 @@ import { getCustomInstructionService } from './services/CustomInstructionService
|
|||
import { getVoiceCommandService } from './services/VoiceCommandService'
|
||||
import { getInputTelemetryService } from './services/InputTelemetryService'
|
||||
import { getSuggestionService, hasInputContextConsent } from './services/SuggestionService'
|
||||
import { initTypoCorrectionService } from './services/TypoCorrectionService'
|
||||
import { getPersonalGraphService } from './services/PersonalGraphService'
|
||||
import { getForegroundWindowInfo } from './utils/win32-foreground'
|
||||
import { getSoundEffectService } from './services/SoundEffectService'
|
||||
import { getAutoLaunchService } from './services/AutoLaunchService'
|
||||
import { getAudioCaptureService } from './services/AudioCaptureService'
|
||||
|
|
@ -199,7 +202,44 @@ async function initInputIntelligence(): Promise<void> {
|
|||
const telemetry = getInputTelemetryService()
|
||||
const suggestion = getSuggestionService()
|
||||
|
||||
telemetry.on('typed-context', (context) => suggestion.handleTypingContext(context))
|
||||
// 첫 제안 수락·받아쓰기 삽입이 키 입력 모듈 로딩(수 초)을 기다리지 않게, 부팅이 끝난 뒤 미리 불러 둔다.
|
||||
setTimeout(() => {
|
||||
void getTextInsertService().preload()
|
||||
}, 5_000).unref?.()
|
||||
|
||||
// 오타 교정이 먼저 본다 — 고치는 중이면 텍스트가 곧 바뀌니 제안으로 넘기지 않고(교정 뒤 새
|
||||
// 스냅샷이 온다), 모델로 검사 중이면 끝날 때('settled') 넘긴다. 제안이 고친 문장을 기준으로
|
||||
// 만들어지고, 두 요청이 같은 모델을 두고 경쟁하지 않는다.
|
||||
const typo = initTypoCorrectionService({
|
||||
replaceBeforeCaret: async (deleteCount, text) => {
|
||||
const method = configGet('insertMethod') === 'keyboard' ? 'keyboard' : 'clipboard'
|
||||
const result = await getTextInsertService().replaceBeforeCaret(deleteCount, text, method)
|
||||
return result.success
|
||||
},
|
||||
lastKeyAt: () => telemetry.lastKeyAt,
|
||||
expectProgrammaticKeys: (count) => telemetry.expectProgrammaticKeys(count),
|
||||
expectProgrammaticInsert: (text) => telemetry.expectProgrammaticInsert(text),
|
||||
foregroundHandle: () => getForegroundWindowInfo()?.hwnd ?? null,
|
||||
recentTexts: () => getPersonalGraphService().listRecentTexts(),
|
||||
warmModel: () => suggestion.warmModel(),
|
||||
generate: (prompt, options) =>
|
||||
getLocalLLMService().streamGenerate(prompt, {
|
||||
model: options.model,
|
||||
systemPrompt: options.systemPrompt,
|
||||
temperature: 0,
|
||||
maxTokens: options.maxTokens,
|
||||
signal: options.signal,
|
||||
keepAlive: '10m'
|
||||
})
|
||||
})
|
||||
typo.on('settled', ({ context }) => suggestion.handleTypingContext(context))
|
||||
typo.on('corrected', () => {
|
||||
if (suggestion.isPresentationActive) suggestion.dismiss('stale')
|
||||
})
|
||||
telemetry.on('typed-context', (context) => {
|
||||
const verdict = typo.handleTypingContext(context)
|
||||
if (verdict === 'pass') suggestion.handleTypingContext(context)
|
||||
})
|
||||
telemetry.on('state-changed', (state) =>
|
||||
sendToMainWindow(IPC_CHANNELS.INPUT_TELEMETRY.STATE_CHANGED, state)
|
||||
)
|
||||
|
|
@ -214,17 +254,24 @@ async function initInputIntelligence(): Promise<void> {
|
|||
setPresentationActive: (active) => telemetry.setSuggestionPresentationActive(active),
|
||||
warn: (message) => logger.warn(message),
|
||||
})
|
||||
// 제안 창이 떠 있는 동안만 제안 단축키를 OS 에서 잡는다 — Ctrl+Alt+Enter 가 앱에도 전달돼
|
||||
// 개행이 들어가던 문제(2026-10-03). 창이 사라지면 바로 푼다.
|
||||
const syncSuggestionKeyCapture = (): void =>
|
||||
getKeyBindingService().setSuggestionCaptureActive(suggestion.isPresentationActive)
|
||||
suggestion.on('updated', (state) => {
|
||||
overlay.onUpdated(state)
|
||||
syncSuggestionKeyCapture()
|
||||
sendToMainWindow(IPC_CHANNELS.SUGGESTION.UPDATED, state)
|
||||
})
|
||||
suggestion.on('cleared', (payload) => {
|
||||
overlay.onCleared()
|
||||
syncSuggestionKeyCapture()
|
||||
sendToMainWindow(IPC_CHANNELS.SUGGESTION.CLEARED, payload)
|
||||
})
|
||||
suggestion.on('state-changed', (state) =>
|
||||
suggestion.on('state-changed', (state) => {
|
||||
syncSuggestionKeyCapture()
|
||||
sendToMainWindow(IPC_CHANNELS.SUGGESTION.STATE_CHANGED, state)
|
||||
)
|
||||
})
|
||||
|
||||
// 제안 수락/순환/닫기는 전역 키바인딩으로만 들어온다 — 오버레이는 포커스를 갖지 않는다.
|
||||
getKeyBindingService().on('triggered', (payload) => {
|
||||
|
|
@ -274,6 +321,7 @@ async function initInputIntelligence(): Promise<void> {
|
|||
|
||||
// 전역 입력 훅·제안 타이머는 종료 시 풀어야 한다
|
||||
const registry = getShutdownRegistry()
|
||||
registry.register({ name: 'typo-correction', dispose: () => typo.dispose() })
|
||||
registry.register({ name: 'suggestion', dispose: () => suggestion.dispose() })
|
||||
registry.register({ name: 'input-telemetry', dispose: () => telemetry.dispose() })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ export interface SetSuggestionConfigParams {
|
|||
learnTypedText?: boolean
|
||||
excludedApps?: string[]
|
||||
requestTimeoutMs?: number
|
||||
typoAutoCorrect?: boolean
|
||||
}
|
||||
|
||||
export interface SuggestionAcceptParams {
|
||||
|
|
@ -69,6 +70,9 @@ export function registerSuggestionHandlers(): void {
|
|||
configSet('suggestionOverlayInteractive', params.overlayInteractive === true)
|
||||
applySuggestionOverlayConfig()
|
||||
}
|
||||
if (params.typoAutoCorrect !== undefined) {
|
||||
configSet('typoAutoCorrectEnabled', params.typoAutoCorrect === true)
|
||||
}
|
||||
if (params.learnTypedText !== undefined) {
|
||||
configSet('inputLearnTypedText', params.learnTypedText === true)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -215,6 +215,9 @@ const CONFIG_DEFAULTS: AppConfig = {
|
|||
suggestionOverlayInteractive: true,
|
||||
suggestionRequestTimeoutMs: 8000,
|
||||
suggestionTuningRevision: 5,
|
||||
typoAutoCorrectEnabled: true,
|
||||
typoAutoCorrectUseModel: true,
|
||||
typoIgnoredWords: [],
|
||||
}
|
||||
|
||||
let store: ElectronStore<AppConfig> | null = null
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import {
|
|||
emptyActivityBucket,
|
||||
extractPhrases,
|
||||
isLearnablePhrase,
|
||||
isTerminalApp,
|
||||
manhattanDistance,
|
||||
mergeActivityBucket,
|
||||
rankFlowWindows,
|
||||
|
|
@ -56,6 +57,7 @@ import {
|
|||
type PhraseSource,
|
||||
type PhysicalRect
|
||||
} from '@d3ro/core/input-intelligence'
|
||||
import { RecentWritesBuffer, type RecentWrite, type RecentWriteMeta } from '@d3ro/core/recent-writes'
|
||||
import { getDatabase } from '../db'
|
||||
import { inputActivity, personalPhrases, suggestions as suggestionsTable, typingSamples } from '../db/schema'
|
||||
import { configGet, configSet } from './ConfigService'
|
||||
|
|
@ -104,8 +106,17 @@ export interface TypingContext {
|
|||
* 마지막 편집이 문서 끝에서 일어났을 때만 true. 생략하면 true 로 본다(호환).
|
||||
*/
|
||||
caretReliable?: boolean
|
||||
/**
|
||||
* 커서 앞 문서 전체 (원문, 최대 DOCUMENT_BEFORE_MAX_CHARS). prefix 는 400자 창이라 글 앞쪽의
|
||||
* 인사·이름·날짜를 모른다 — 제안 프롬프트가 첫머리·사실을 여기서 뽑는다.
|
||||
* 문서형 컨트롤(터미널 버퍼 등)·비밀번호 칸은 null. 생략하면 prefix 만 쓴다(호환).
|
||||
*/
|
||||
documentBefore?: string | null
|
||||
}
|
||||
|
||||
/** 제안 문맥으로 넘길 커서 앞 문서 길이 상한. */
|
||||
const DOCUMENT_BEFORE_MAX_CHARS = 6000
|
||||
|
||||
interface InputTelemetryEvents {
|
||||
'state-changed': (state: InputTelemetryState) => void
|
||||
'typed-context': (context: TypingContext) => void
|
||||
|
|
@ -192,6 +203,13 @@ class InputTelemetryService extends EventEmitter {
|
|||
private _lastEditAtEnd = true
|
||||
/** 클릭 뒤 첫 스냅샷에서 기준선을 다시 잡는다 */
|
||||
private _rebaseFocusText = false
|
||||
/** 포커스 깜빡임 뒤 돌아온 칸 — 키보드로 친 채 돌아왔으므로 이미 편집한 칸으로 본다 */
|
||||
private _typedIntoFocus = false
|
||||
/** 직전 스냅샷이 편집 가능한 칸이었는가 / 어느 창이었는가 (포커스 깜빡임 판정) */
|
||||
private _prevSnapshotEditable = false
|
||||
private _lastFocusHwnd: number | null = null
|
||||
/** 이 창에서 조금 전에 쓴(보낸) 글 — 메모리 전용, 제안 문맥용 */
|
||||
private readonly _recentWrites = new RecentWritesBuffer()
|
||||
private _lastActiveTickAt = 0
|
||||
private _lastMouse: { x: number; y: number } | null = null
|
||||
private _lastClickAt = 0
|
||||
|
|
@ -215,6 +233,11 @@ class InputTelemetryService extends EventEmitter {
|
|||
/** 곧(또는 방금) 프로그램이 삽입한 텍스트 — 다음 diff 에서 "타이핑" 으로 학습하지 않는다. */
|
||||
private _expectedInserts: Array<{ id: number; text: string; expiresAt: number }> = []
|
||||
private _expectedInsertSeq = 0
|
||||
/** 통계에서 뺄 프로그램 키 남은 수와 유효 시각 */
|
||||
private _programmaticKeys = 0
|
||||
/** 진단용 마지막 키 종류 (키 값 아님) */
|
||||
private _lastKeyDiag = '-'
|
||||
private _programmaticKeysUntil = 0
|
||||
|
||||
private _prunedAt = 0
|
||||
|
||||
|
|
@ -252,6 +275,20 @@ class InputTelemetryService extends EventEmitter {
|
|||
return this._lastContext
|
||||
}
|
||||
|
||||
/** 마지막 키보드 입력 시각 (ms) — 오타 교정이 "스냅샷 뒤 사용자가 더 쳤는가" 를 확인한다. */
|
||||
get lastKeyAt(): number {
|
||||
return this._lastKeyAt
|
||||
}
|
||||
|
||||
/**
|
||||
* 곧 프로그램이 키 count 개를 보낸다 — 그 키들은 입력 통계에 넣지 않는다.
|
||||
* 남은 예고는 ttlMs 뒤 무효다(보내지 못한 키가 사용자 키를 삼키지 않게).
|
||||
*/
|
||||
expectProgrammaticKeys(count: number, ttlMs = 3000): void {
|
||||
this._programmaticKeys = Math.max(0, count)
|
||||
this._programmaticKeysUntil = Date.now() + ttlMs
|
||||
}
|
||||
|
||||
setSuggestionPresentationActive(active: boolean): void {
|
||||
this._suggestionPresentationActive = active
|
||||
if (!active && this._presentationValidationTimer) {
|
||||
|
|
@ -317,6 +354,8 @@ class InputTelemetryService extends EventEmitter {
|
|||
}
|
||||
|
||||
stop(): void {
|
||||
// 입력 관찰을 끄면 메모리에 잡아 둔 "조금 전에 쓴 글" 도 버린다.
|
||||
this._recentWrites.clear()
|
||||
if (!this._running) {
|
||||
this.setSuggestionPresentationActive(false)
|
||||
return
|
||||
|
|
@ -360,9 +399,15 @@ class InputTelemetryService extends EventEmitter {
|
|||
|
||||
dispose(): void {
|
||||
this.stop()
|
||||
this._recentWrites.clear()
|
||||
this.removeAllListeners()
|
||||
}
|
||||
|
||||
/** 같은 창에서 조금 전에 쓴(보내서 칸이 비워진) 글 — 오래된 것부터. 메모리에만 있다. */
|
||||
listRecentWrites(meta: RecentWriteMeta, limit = 4): RecentWrite[] {
|
||||
return this._recentWrites.listFor(meta, Date.now(), limit)
|
||||
}
|
||||
|
||||
private _detachListeners(): void {
|
||||
if (this._onKeyDown) {
|
||||
uIOhook.removeListener('keydown', this._onKeyDown)
|
||||
|
|
@ -398,11 +443,28 @@ class InputTelemetryService extends EventEmitter {
|
|||
|
||||
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()
|
||||
return
|
||||
}
|
||||
this._registerInput(true)
|
||||
const bucket = this._bucket()
|
||||
// uiohook 키코드는 VK 와 다른 표계다 — 정본(VK)으로 변환해 분류한다.
|
||||
const vk = uiohookCodeToVk(event.keycode)
|
||||
const keyClass = vk === null ? 'other' : classifyKeyStroke(vk, this._modifiers)
|
||||
// 한글·일본어 IME 가 켜져 있으면 Windows 는 글자 키를 VK_PROCESSKEY 로 넘기고, uiohook 은 그것을
|
||||
// 변환표에 없는 키코드로 보낸다 — 그대로 'other' 로 두면 한글 타이핑 전체가 "타이핑 아님" 이 되어
|
||||
// 제안이 영영 뜨지 않았다(2026-10-03 실측: 글자 키가 전부 key=other). 수정자 없이 눌린 미지의
|
||||
// 키는 IME 조합 키로 본다. 실제 텍스트 변화(editedSinceFocus)가 함께 있어야 제안이 열린다.
|
||||
const keyClass =
|
||||
vk === null
|
||||
? this._modifiers.ctrl || this._modifiers.alt || this._modifiers.meta
|
||||
? 'shortcut'
|
||||
: 'ime'
|
||||
: classifyKeyStroke(vk, this._modifiers)
|
||||
|
||||
if (keyClass === 'shortcut') bucket.shortcuts += 1
|
||||
else bucket.keystrokes += 1
|
||||
|
|
@ -410,6 +472,8 @@ class InputTelemetryService extends EventEmitter {
|
|||
|
||||
this._lastKeyAt = Date.now()
|
||||
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()
|
||||
}
|
||||
|
|
@ -638,6 +702,14 @@ class InputTelemetryService extends EventEmitter {
|
|||
: documentLike
|
||||
? lastLineOf(tail)
|
||||
: tail
|
||||
const documentBefore = snapshot.isPassword
|
||||
? null
|
||||
: caretKnown
|
||||
? snapshot.text.slice(0, snapshot.caretOffset ?? snapshot.text.length)
|
||||
: documentLike
|
||||
? null
|
||||
: snapshot.text
|
||||
context.documentBefore = documentBefore === null ? null : documentBefore.slice(-DOCUMENT_BEFORE_MAX_CHARS)
|
||||
this._caretFallback = !caretKnown
|
||||
|
||||
// 포커스 식별: 칸이 바뀌었거나 클릭이 있었으면 그 시점 텍스트를 기준선으로 저장한다
|
||||
|
|
@ -647,11 +719,34 @@ 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) {
|
||||
// 포커스 깜빡임: 같은 창에서 타이핑하는 동안 UIA 포커스가 입력칸 ↔ 읽을 수 없는 요소(legacy)를
|
||||
// 오간다(실측 Chrome 2026-10-03: 보류 사유 not-typing 122회). 그때마다 기준선을 다시 잡으면
|
||||
// 방금 친 글이 "들어올 때부터 있던 글" 이 되어 제안이 영영 안 뜬다. 클릭 없이 키보드로 치다가
|
||||
// 읽을 수 없는 요소를 거쳐 같은 창의 입력칸으로 돌아온 것이면 이미 편집한 칸으로 본다.
|
||||
const now = Date.now()
|
||||
this._typedIntoFocus =
|
||||
!this._rebaseFocusText &&
|
||||
this._foreground.hwnd !== null &&
|
||||
this._foreground.hwnd === this._lastFocusHwnd &&
|
||||
!this._prevSnapshotEditable &&
|
||||
this._lastTypedAt > this._lastClickAt &&
|
||||
now - this._lastTypedAt <= SUGGESTION_DEFAULTS.recentTypingWindowMs
|
||||
this._lastFocusKey = focusKey
|
||||
this._textAtFocus = textForFocus
|
||||
this._rebaseFocusText = false
|
||||
}
|
||||
context.editedSinceFocus = textForFocus !== this._textAtFocus
|
||||
context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus
|
||||
|
||||
// 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다.
|
||||
// 비밀번호·편집 불가·조합 중 칸과 터미널(명령 기록)은 보지 않는다.
|
||||
if (snapshot.isEditable && !snapshot.isPassword && !snapshot.isComposing && !isTerminalApp(this._foreground.appName)) {
|
||||
this._recentWrites.observe(
|
||||
focusKey,
|
||||
snapshot.text,
|
||||
{ windowHandle: this._foreground.hwnd, appName: this._foreground.appName, windowTitle: context.windowTitle },
|
||||
Date.now()
|
||||
)
|
||||
}
|
||||
|
||||
// 케어렛을 모르면 "문서 끝 = 커서" 가정이 맞는지 마지막 편집 위치로 확인한다.
|
||||
// 문서 중간을 고쳤다면 접두(문서 끝)는 커서와 무관하다 — 제안·수락을 막는다.
|
||||
|
|
@ -668,6 +763,10 @@ class InputTelemetryService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
// 포커스 깜빡임 판정용 — 이번 스냅샷이 편집 가능한 칸이었는가, 어느 창이었는가.
|
||||
this._prevSnapshotEditable = snapshot.available && snapshot.isEditable
|
||||
this._lastFocusHwnd = this._foreground.hwnd
|
||||
|
||||
this._recordReadabilityEvidence(snapshot)
|
||||
|
||||
// 진단: 왜 제안이 안 뜨는지 로그만으로 판단할 수 있게 스냅샷 요약을 남긴다.
|
||||
|
|
@ -676,7 +775,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
`pw=${snapshot.isPassword} comp=${snapshot.isComposing} src=${snapshot.textSource} ` +
|
||||
`len=${snapshot.text.length} caret=${snapshot.caretOffset ?? -1} tail=${this._caretFallback} ` +
|
||||
`anchor=${context.anchor ? 'yes' : 'no'} app=${this._foreground.appName ?? '-'} ` +
|
||||
`reason=${snapshot.reason ?? '-'}`
|
||||
`reason=${snapshot.reason ?? '-'} key=${this._lastKeyDiag}`
|
||||
)
|
||||
|
||||
this._lastSnapshotSummary = {
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import type { UiohookKeyboardEvent, UiohookMouseEvent } from 'uiohook-napi'
|
|||
import { getLogger } from './LoggerService'
|
||||
import { acquireGlobalInputHook } from './global-input-hook'
|
||||
import { configGet, loadKeyBindings, onConfigChanged } from './ConfigService'
|
||||
import { acceleratorsToReserve } from './keybinding-accelerator-policy'
|
||||
import { acceleratorsToReserve, suggestionCaptureAccelerators } from './keybinding-accelerator-policy'
|
||||
import type { ReservableBinding } from './keybinding-accelerator-policy'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import {
|
||||
|
|
@ -275,6 +275,9 @@ class KeyBindingService extends EventEmitter {
|
|||
|
||||
/** 이 서비스가 직접 등록한 accelerator만 추적한다 (다른 곳의 등록을 해제하지 않기 위해) */
|
||||
private _ownedAccelerators: Set<string> = new Set()
|
||||
/** 제안 창이 떠 있는 동안만 잡는 제안 단축키 (키를 앱에 넘기지 않으려고) */
|
||||
private _suggestionCaptureWanted = false
|
||||
private _capturedAccelerators: Set<string> = new Set()
|
||||
|
||||
/** 상태 머신에 등록한 바인딩과 액션 — accelerator 예약 정책의 입력 */
|
||||
private _reservable: ReservableBinding[] = []
|
||||
|
|
@ -480,9 +483,51 @@ class KeyBindingService extends EventEmitter {
|
|||
)
|
||||
}
|
||||
}
|
||||
// 바인딩·기능 스위치가 바뀌었다 — 제안 창이 떠 있으면 새 바인딩으로 다시 잡는다.
|
||||
this._syncSuggestionCapture()
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안 창이 보이는 동안 제안 단축키(수락·이동·닫기)를 OS 에 noop 으로 등록해 포커스된 앱에
|
||||
* 전달되지 않게 한다. 실제 동작은 여전히 uiohook 경로가 맡는다(저수준 훅은 핫키 처리보다 먼저
|
||||
* 키를 본다). 창이 사라지면 바로 풀어 평소에는 다른 앱의 같은 단축키를 빼앗지 않는다.
|
||||
*/
|
||||
setSuggestionCaptureActive(active: boolean): void {
|
||||
if (active === this._suggestionCaptureWanted) return
|
||||
this._suggestionCaptureWanted = active
|
||||
this._syncSuggestionCapture()
|
||||
}
|
||||
|
||||
private _syncSuggestionCapture(): void {
|
||||
this._releaseSuggestionCapture()
|
||||
if (!this._suggestionCaptureWanted || !this._isRunning || configGet('suggestionEnabled') !== true) return
|
||||
for (const accelerator of suggestionCaptureAccelerators(this._reservable, process.platform, this._ownedAccelerators)) {
|
||||
try {
|
||||
const ok = globalShortcut.register(accelerator, () => {
|
||||
// noop — 동작은 uiohook 이 낸다. 등록 목적은 키를 앱에 넘기지 않는 것이다.
|
||||
})
|
||||
if (ok) this._capturedAccelerators.add(accelerator)
|
||||
else logger.debug(`제안 단축키를 잡지 못함 (다른 곳에서 사용 중): ${accelerator}`)
|
||||
} catch (err) {
|
||||
logger.warn(`제안 단축키 등록 실패 "${accelerator}": ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _releaseSuggestionCapture(): void {
|
||||
for (const accelerator of this._capturedAccelerators) {
|
||||
try {
|
||||
globalShortcut.unregister(accelerator)
|
||||
} catch (err) {
|
||||
logger.warn(`제안 단축키 해제 실패 "${accelerator}": ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
this._capturedAccelerators.clear()
|
||||
}
|
||||
|
||||
private _unregisterOwnedAccelerators(): void {
|
||||
// 상시 예약을 풀면 제안 창 동안의 잡기도 함께 푼다 — 바인딩이 바뀌면 _syncAccelerators 가 다시 잡는다.
|
||||
this._releaseSuggestionCapture()
|
||||
for (const accelerator of this._ownedAccelerators) {
|
||||
try {
|
||||
globalShortcut.unregister(accelerator)
|
||||
|
|
|
|||
|
|
@ -62,6 +62,13 @@ interface GenerateOptions {
|
|||
* 콜드 로딩(실측 20초+)을 다시 문다.
|
||||
*/
|
||||
keepAlive?: string
|
||||
/**
|
||||
* true 면 prompt 를 템플릿 없이 그대로 보낸다 (Ollama `raw`) — 호출자가 모델 템플릿을 직접
|
||||
* 그린 경우(인라인 제안의 prefill). systemPrompt 는 무시된다.
|
||||
*/
|
||||
raw?: boolean
|
||||
/** 정지 문자열 (Ollama options.stop) */
|
||||
stop?: string[]
|
||||
}
|
||||
|
||||
interface GenerateResult {
|
||||
|
|
@ -495,13 +502,14 @@ class LocalLLMService extends EventEmitter {
|
|||
body: JSON.stringify({
|
||||
model,
|
||||
prompt,
|
||||
system: options?.systemPrompt,
|
||||
...(options?.raw ? { raw: true } : { system: options?.systemPrompt }),
|
||||
stream: true,
|
||||
keep_alive: options?.keepAlive,
|
||||
think: false,
|
||||
options: {
|
||||
temperature: options?.temperature ?? 0.3,
|
||||
num_predict: maxTokens
|
||||
num_predict: maxTokens,
|
||||
...(options?.stop && options.stop.length > 0 ? { stop: options.stop } : {})
|
||||
}
|
||||
}),
|
||||
signal: request.controller.signal
|
||||
|
|
|
|||
|
|
@ -11,19 +11,20 @@
|
|||
|
||||
import {
|
||||
SHARES_TERMS_MIN_SIMILARITY,
|
||||
buildQueryTerms,
|
||||
buildSequenceEdges,
|
||||
continuationsFrom,
|
||||
extractTerms,
|
||||
jaccard,
|
||||
rankRelated,
|
||||
scoreRelatedNodes,
|
||||
splitSentences,
|
||||
type GraphContext,
|
||||
type PersonalGraphQuery,
|
||||
type PersonalGraphStats,
|
||||
type PhraseSource,
|
||||
type RelatedCandidate
|
||||
type PhraseSource
|
||||
} from '@d3ro/core/personal-graph'
|
||||
import { isLearnablePhrase, prefixTail } from '@d3ro/core/input-intelligence'
|
||||
import { SUGGESTION_MEMORY_TAIL_CHARS, isLearnablePhrase, prefixTail } from '@d3ro/core/input-intelligence'
|
||||
import { analyzeWritingContext } from '@d3ro/core/writing-context'
|
||||
import { and, desc, eq, gte, inArray, or, sql } from 'drizzle-orm'
|
||||
import { getDatabase } from '../db'
|
||||
import { personalPhrases, phraseEdges } from '../db/schema'
|
||||
|
|
@ -127,93 +128,186 @@ class PersonalGraphService {
|
|||
/**
|
||||
* 제안 문맥을 그래프에서 끌어온다.
|
||||
*
|
||||
* 1) 접두 꼬리를 포함하는 노드를 찾고 그 뒤에 실제로 이어 쓴 텍스트를 뽑는다.
|
||||
* 2) 그 노드들의 follows 이웃과 용어를 공유하는 노드를 순위화해 관련 문장으로 준다.
|
||||
* 1) followUps — 직전 완결 문장(정확히 같거나 용어가 거의 같은 노드) 뒤에 실제로 이어 쓴 문장.
|
||||
* "다음 문장" 의 가장 강한 근거다(follows 엣지 가중치 순).
|
||||
* 2) continuations — 접두 꼬리를 품은 문장에서 그 꼬리 뒤에 이어 쓴 텍스트. 긴 꼬리부터
|
||||
* 짧은 꼬리(어절 경계)로 물러나며 찾는다 — 14자 고정 꼬리는 새 문장에서 거의 맞지 않았다.
|
||||
* 3) related — 지금 문장·직전 문장·앞 문맥의 용어를 IDF 로 가중해 고른 관련 문장과,
|
||||
* 그 문장들 뒤에 이어 쓴 문장(follows 1단계 확장).
|
||||
*/
|
||||
retrieveContext(prefix: string, limit = 4): GraphContext {
|
||||
const tail = prefixTail(prefix)
|
||||
if (tail.length < 4) return { continuations: [], related: [] }
|
||||
retrieveContext(prefix: string, limit = 4, options: { appName?: string | null } = {}): GraphContext {
|
||||
const empty: GraphContext = { continuations: [], related: [], followUps: [] }
|
||||
const normalizedPrefix = prefix.replace(/\s+/gu, ' ').trim()
|
||||
if (normalizedPrefix.length < 2) return empty
|
||||
|
||||
try {
|
||||
const db = getDatabase()
|
||||
const pattern = `%${tail.replace(/[%_\\]/gu, '')}%`
|
||||
const context = analyzeWritingContext(prefix)
|
||||
const inPrefix = (text: string): boolean => normalizedPrefix.includes(text)
|
||||
|
||||
const anchorRows = db
|
||||
.select()
|
||||
.from(personalPhrases)
|
||||
.where(sql`${personalPhrases.phrase} LIKE ${pattern}`)
|
||||
.orderBy(desc(personalPhrases.lastUsedAt))
|
||||
.limit(20)
|
||||
.all()
|
||||
// (1) 직전 문장 뒤에 이어 쓴 문장
|
||||
const followUps = this._followUpsAfter(context.lastSentence, context.currentSentence ? 2 : 3, inPrefix)
|
||||
|
||||
if (anchorRows.length === 0) return { continuations: [], related: [] }
|
||||
// (2) 꼬리 이어쓰기 — 지금 문장 안에서만 찾는다 (앞 문장 끝과 섞이지 않게)
|
||||
const tailSource = context.currentSentence || context.lastSentence
|
||||
const continuations = this._continuationsForTail(tailSource)
|
||||
|
||||
const anchorTexts = anchorRows.map((row) => row.phrase)
|
||||
const continuations = continuationsFrom(anchorTexts, tail, 3)
|
||||
|
||||
const anchorTerms = new Set<string>()
|
||||
for (const row of anchorRows) {
|
||||
for (const term of parseTerms(row.terms)) anchorTerms.add(term)
|
||||
}
|
||||
|
||||
const candidates: RelatedCandidate[] = []
|
||||
const seen = new Set<string>(anchorTexts)
|
||||
|
||||
// (a) follows 이웃 — 가장 강한 관계
|
||||
const edgeRows = db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(
|
||||
and(inArray(phraseEdges.fromPhrase, anchorTexts), eq(phraseEdges.kind, 'follows'))
|
||||
)
|
||||
.orderBy(desc(phraseEdges.weight))
|
||||
.limit(40)
|
||||
.all()
|
||||
|
||||
for (const edge of edgeRows) {
|
||||
if (seen.has(edge.toPhrase)) continue
|
||||
seen.add(edge.toPhrase)
|
||||
candidates.push({
|
||||
text: edge.toPhrase,
|
||||
terms: [],
|
||||
weight: edge.weight * 2,
|
||||
lastUsedAt: null
|
||||
})
|
||||
}
|
||||
|
||||
// (b) 용어 공유 — 최근 노드를 훑어 유사도가 높은 것
|
||||
// (3) 관련 문장 — IDF 가중 용어 겹침 + follows 1단계 확장
|
||||
const queryTerms = buildQueryTerms([
|
||||
{ text: context.currentSentence, weight: 2 },
|
||||
{ text: context.lastSentence, weight: 1.5 },
|
||||
{ text: context.earlierText.slice(-200), weight: 1 }
|
||||
])
|
||||
const recentNodes = db
|
||||
.select()
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.lastUsedAt))
|
||||
.limit(TERM_SCAN_LIMIT)
|
||||
.all()
|
||||
const scored = scoreRelatedNodes(
|
||||
{
|
||||
terms: queryTerms,
|
||||
appName: options.appName ?? null,
|
||||
exclude: (text) => inPrefix(text) || followUps.includes(text)
|
||||
},
|
||||
recentNodes.map((row) => ({
|
||||
text: row.phrase,
|
||||
terms: parseTerms(row.terms),
|
||||
count: row.count,
|
||||
lastUsedAt: row.lastUsedAt,
|
||||
appName: row.appName
|
||||
})),
|
||||
limit + 2
|
||||
)
|
||||
|
||||
for (const node of recentNodes) {
|
||||
if (seen.has(node.phrase)) continue
|
||||
const terms = parseTerms(node.terms)
|
||||
if (terms.length === 0) continue
|
||||
const similarity = jaccard([...anchorTerms], terms)
|
||||
if (similarity < SHARES_TERMS_MIN_SIMILARITY) continue
|
||||
seen.add(node.phrase)
|
||||
candidates.push({
|
||||
text: node.phrase,
|
||||
terms,
|
||||
weight: 0,
|
||||
lastUsedAt: node.lastUsedAt
|
||||
})
|
||||
const related: string[] = []
|
||||
const push = (text: string): void => {
|
||||
if (related.length >= limit || related.includes(text) || followUps.includes(text) || inPrefix(text)) return
|
||||
related.push(text)
|
||||
}
|
||||
|
||||
const related = rankRelated([...anchorTerms], candidates, limit)
|
||||
return { continuations, related }
|
||||
// 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 2개만 확장한다.
|
||||
const anchors = scored.slice(0, 2).map((item) => item.text)
|
||||
const hops = anchors.length
|
||||
? db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(and(inArray(phraseEdges.fromPhrase, anchors), eq(phraseEdges.kind, 'follows')))
|
||||
.orderBy(desc(phraseEdges.weight))
|
||||
.limit(6)
|
||||
.all()
|
||||
: []
|
||||
for (const item of scored) {
|
||||
push(item.text)
|
||||
const hop = hops.find((edge) => edge.fromPhrase === item.text)
|
||||
if (hop) push(hop.toPhrase)
|
||||
}
|
||||
return { continuations, related, followUps }
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`그래프 문맥 조회 실패: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
return { continuations: [], related: [] }
|
||||
return empty
|
||||
}
|
||||
}
|
||||
|
||||
/** 문장 뒤에 이어 쓴 문장 (follows). 같은 노드가 없으면 용어가 가장 많이 겹치는 노드로 대신한다. */
|
||||
private _followUpsAfter(sentence: string, limit: number, exclude: (text: string) => boolean): string[] {
|
||||
const normalized = sentence.replace(/[.!?。!?…]+$/u, '').replace(/\s+/gu, ' ').trim()
|
||||
if (normalized.length < 4) return []
|
||||
const db = getDatabase()
|
||||
|
||||
let sources = [normalized]
|
||||
const exact = db
|
||||
.select({ phrase: personalPhrases.phrase })
|
||||
.from(personalPhrases)
|
||||
.where(eq(personalPhrases.phrase, normalized))
|
||||
.get()
|
||||
if (!exact) {
|
||||
const terms = buildQueryTerms([{ text: normalized, weight: 1 }])
|
||||
if (terms.size < 2) return []
|
||||
const near = scoreRelatedNodes(
|
||||
{ terms },
|
||||
db
|
||||
.select()
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.lastUsedAt))
|
||||
.limit(TERM_SCAN_LIMIT)
|
||||
.all()
|
||||
.map((row) => ({
|
||||
text: row.phrase,
|
||||
terms: parseTerms(row.terms),
|
||||
count: row.count,
|
||||
lastUsedAt: row.lastUsedAt,
|
||||
appName: row.appName
|
||||
})),
|
||||
2
|
||||
).filter((item) => item.sharedTerms >= Math.max(2, Math.ceil(terms.size * 0.6)))
|
||||
if (near.length === 0) return []
|
||||
sources = near.map((item) => item.text)
|
||||
}
|
||||
|
||||
const edges = db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(and(inArray(phraseEdges.fromPhrase, sources), eq(phraseEdges.kind, 'follows')))
|
||||
.orderBy(desc(phraseEdges.weight), desc(phraseEdges.updatedAt))
|
||||
.limit(limit * 2)
|
||||
.all()
|
||||
const out: string[] = []
|
||||
for (const edge of edges) {
|
||||
if (out.includes(edge.toPhrase) || exclude(edge.toPhrase)) continue
|
||||
out.push(edge.toPhrase)
|
||||
if (out.length >= limit) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 최근 문장 노드 원문과 사용 횟수 — 오타 교정의 개인 어휘 근거. */
|
||||
listRecentTexts(limit = TERM_SCAN_LIMIT): Array<{ text: string; count: number }> {
|
||||
try {
|
||||
return getDatabase()
|
||||
.select({ text: personalPhrases.phrase, count: personalPhrases.count })
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.lastUsedAt))
|
||||
.limit(limit)
|
||||
.all()
|
||||
} catch (error) {
|
||||
logger.warn(`그래프 원문 조회 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** 꼬리 뒤 이어쓰기 — 긴 꼬리부터 어절 경계의 짧은 꼬리로 물러난다. */
|
||||
private _continuationsForTail(text: string): string[] {
|
||||
const normalized = text.replace(/\s+/gu, ' ').trim()
|
||||
if (normalized.length < 4) return []
|
||||
const db = getDatabase()
|
||||
const tails: string[] = []
|
||||
for (const length of [SUGGESTION_MEMORY_TAIL_CHARS, 10, 7]) {
|
||||
let tail = prefixTail(normalized, length)
|
||||
// 어절 중간에서 시작하지 않게 — 첫 공백 뒤로 민다(공백이 없으면 그대로).
|
||||
if (tail.length < normalized.length && tail.includes(' ')) tail = tail.slice(tail.indexOf(' ') + 1)
|
||||
if (tail.length >= 4 && !tails.includes(tail)) tails.push(tail)
|
||||
}
|
||||
for (const tail of tails) {
|
||||
const pattern = `%${tail.replace(/[%_\\]/gu, '')}%`
|
||||
const rows = db
|
||||
.select({ phrase: personalPhrases.phrase })
|
||||
.from(personalPhrases)
|
||||
.where(sql`${personalPhrases.phrase} LIKE ${pattern}`)
|
||||
.orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt))
|
||||
.limit(20)
|
||||
.all()
|
||||
const found = continuationsFrom(
|
||||
rows.map((row) => row.phrase),
|
||||
tail,
|
||||
3
|
||||
)
|
||||
if (found.length > 0) return found
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
/** 용어 공유 엣지를 백필한다 (기존 노드들 사이 관계 보강). */
|
||||
runMaintenance(limit = MAINTENANCE_NODE_LIMIT): number {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
selectPhraseHints,
|
||||
shouldPersistSuggestionPrefix,
|
||||
isTerminalApp,
|
||||
extractContinuation,
|
||||
extractTerminalPromptPrefix,
|
||||
type AnchorKind,
|
||||
type PhysicalRect,
|
||||
|
|
@ -38,6 +39,9 @@ import {
|
|||
type SuggestionState,
|
||||
type SuggestionStep
|
||||
} from '@d3ro/core/input-intelligence'
|
||||
import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template'
|
||||
import { buildQueryTerms, splitSentences } from '@d3ro/core/personal-graph'
|
||||
import { analyzeWritingContext, findUnsupportedFacts } from '@d3ro/core/writing-context'
|
||||
import { configGet, configSet } from './ConfigService'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { getLocalLLMService } from './LocalLLMService'
|
||||
|
|
@ -123,22 +127,103 @@ interface SuggestionEvents {
|
|||
|
||||
interface LocalMemoryContext {
|
||||
continuationHints: string[]
|
||||
/** 직전 문장 뒤에 사용자가 실제로 이어 쓴 문장 (그래프 follows) */
|
||||
followUpHints: string[]
|
||||
relatedHints: string[]
|
||||
/** 지금 글과 용어가 겹치는(또는 같은 앱) 개인 문구 — 프롬프트용 */
|
||||
phraseHints: string[]
|
||||
/** 관련성과 무관한 자주 쓰는 문구 — 모델 없이 로컬 기억만으로 후보를 만들 때 뒤를 채운다 */
|
||||
fallbackPhraseHints: string[]
|
||||
appPhraseCount: number
|
||||
}
|
||||
|
||||
/** 커서 뒤 텍스트 — 케어렛을 알 때만 (문서 중간에서 쓸 때 겹치지 않게). */
|
||||
function suffixAfterCaret(context: TypingContext): string | null {
|
||||
if (context.caretOffset === null || context.caretOffset >= context.fullText.length) return null
|
||||
const suffix = context.fullText.slice(context.caretOffset, context.caretOffset + 200).trim()
|
||||
return suffix.length > 0 ? suffix : null
|
||||
}
|
||||
|
||||
/** 프롬프트의 [관련해서 사용자가 쓴 문장] — 그래프 관련 문장 먼저, 그다음 문맥과 겹치는 개인 문구. */
|
||||
function relatedPromptHints(memory: LocalMemoryContext): string[] {
|
||||
return [...memory.relatedHints, ...memory.phraseHints]
|
||||
.filter((value, index, list) => list.indexOf(value) === index && !memory.followUpHints.includes(value))
|
||||
.slice(0, 5)
|
||||
}
|
||||
|
||||
/**
|
||||
* 스냅샷 한 번(약 0.8초) 사이에 사람이 칠 수 있는 글자 수 상한. 빈 터미널 입력칸이 이보다 크게
|
||||
* 한 번에 채워지면 타이핑이 아니다(Claude Code 의 회색 추천 문구).
|
||||
*/
|
||||
const TERMINAL_TYPING_STEP_CHARS = 8
|
||||
|
||||
/** 모델 출력의 모양 (길이·첫 글자 종류·줄 수) — 로그용, 내용은 담지 않는다. */
|
||||
function describeRawOutput(raw: string, prefill: boolean): string {
|
||||
const first = raw.charAt(0)
|
||||
const kind =
|
||||
raw.length === 0
|
||||
? 'empty'
|
||||
: first === '\n' || first === '\r'
|
||||
? 'newline'
|
||||
: /\s/u.test(first)
|
||||
? 'space'
|
||||
: /[\p{L}\p{N}]/u.test(first)
|
||||
? 'letter'
|
||||
: 'symbol'
|
||||
return `mode=${prefill ? 'prefill' : 'instruct'} len=${raw.length} first=${kind} lines=${raw.split('\n').length}`
|
||||
}
|
||||
|
||||
function commonPrefixLength(a: string, b: string): number {
|
||||
const max = Math.min(a.length, b.length)
|
||||
let index = 0
|
||||
while (index < max && a[index] === b[index]) index += 1
|
||||
return index
|
||||
}
|
||||
|
||||
/** 이 길이를 넘는 모델 출력은 버린다 (스트리밍 폭주 방지) */
|
||||
const MAX_RAW_OUTPUT_CHARS = 1200
|
||||
|
||||
/**
|
||||
* 채우기 루프(2번째 이후 후보)의 온도.
|
||||
*
|
||||
* prefill 이어 쓰기는 분포가 뾰족해 0.8 에서도 첫 후보와 같은 문장이 자주 나왔다(실측) —
|
||||
* 다른 후보를 얻으려면 더 넓게 뽑는다. 사실 검사·중복 검사가 뒤에서 거른다.
|
||||
*/
|
||||
const FILL_TEMPERATURE = 1.0
|
||||
|
||||
/** 이어 쓰기 출력이 첫 문장(또는 첫 줄)을 끝내고 다음 글자를 쓰기 시작했는가. */
|
||||
const FIRST_SENTENCE_DONE = /\S[\s\S]*?(?:[.!?。!?…]["'”’)\]]*\s+\S|\n\s*\S)/u
|
||||
|
||||
/** 모델 요청 하나 — 프롬프트, 전송 옵션, 출력 해석기. */
|
||||
interface ModelRequest {
|
||||
prompt: string
|
||||
systemPrompt?: string
|
||||
raw: boolean
|
||||
stop?: string[]
|
||||
/** 완성된 출력 → 후보 (못 쓰면 null, 이유는 rejected) */
|
||||
parse(raw: string): { candidate: SuggestionCandidate | null; rejected: string | null }
|
||||
/** 스트리밍 중간 표시용 텍스트 */
|
||||
partial(raw: string): string
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델을 메모리에 유지하는 시간.
|
||||
*
|
||||
* 콜드 리로드 실측(11.4s)이 요청 타임아웃(8s)보다 길어, 짧은 유휴 유지 시간은
|
||||
* 유휴 후 첫 요청을 항상 타임아웃시켰다 — 충분히 길게 유지한다.
|
||||
*/
|
||||
const SUGGESTION_KEEP_ALIVE = '10m'
|
||||
const SUGGESTION_KEEP_ALIVE_MS = 10 * 60_000
|
||||
const SUGGESTION_KEEP_ALIVE = '30m'
|
||||
const SUGGESTION_KEEP_ALIVE_MS = 30 * 60_000
|
||||
/**
|
||||
* 타이핑 중인데 남은 유지 시간이 이보다 짧으면 1토큰 요청으로 유지 시간을 연장한다.
|
||||
*
|
||||
* 실측(2026-10-03): 50분 자리를 비운 뒤 돌아오자 콜드 로드에 29초가 걸려 그동안 "준비 중" 만
|
||||
* 보였다(GPU 메모리 10.6/12GB — 음성 인식 모델과 함께 올라가 있어 로드가 느리다). 쓰는 동안에는
|
||||
* 절대 식지 않게, 자리를 비우면 keep-alive 뒤에 내려가게 한다.
|
||||
*/
|
||||
const KEEP_WARM_REFRESH_MS = 10 * 60_000
|
||||
/** 유지 연장 요청 최소 간격 */
|
||||
const KEEP_WARM_MIN_INTERVAL_MS = 60_000
|
||||
/** keep-alive 만료 직전 여유 — 경계에서 콜드 모델로 요청하지 않는다. */
|
||||
const SUGGESTION_KEEP_ALIVE_MARGIN_MS = 30_000
|
||||
/** 워밍업 실패 뒤 같은 모델 재시도를 미루는 시간 — 멈출 때마다 실패 요청을 쏘지 않는다. */
|
||||
|
|
@ -184,6 +269,10 @@ export class SuggestionService extends EventEmitter {
|
|||
/** 마지막 스트리밍 방출 시각 (IPC 과다 방출 방지) */
|
||||
private _lastPartialEmitAt = 0
|
||||
private _lastContext: TypingContext | null = null
|
||||
/** 직전 터미널 입력 줄 — 끝에서 치는 중인지 판단한다 */
|
||||
private _lastTerminalPrompt: string | null = null
|
||||
/** 지금 터미널 입력 줄이 사용자가 끝에서 쳐 온 글인가 (회색 추천 문구·붙여넣기 덩어리가 아님) */
|
||||
private _terminalPromptTyped = false
|
||||
private _provenance: SuggestionProvenance | null = null
|
||||
/** 세션을 만든 입력창의 최상위 창 핸들 — 수락 직전 포커스가 그대로인지 확인한다. */
|
||||
private _windowHandle: number | null = null
|
||||
|
|
@ -208,6 +297,7 @@ export class SuggestionService extends EventEmitter {
|
|||
private _warmUpPromise: Promise<void> | null = null
|
||||
private _warmUpAbort: AbortController | null = null
|
||||
private _warmUpRetryTimer: NodeJS.Timeout | null = null
|
||||
private _lastKeepWarmAt = 0
|
||||
|
||||
constructor(deps: SuggestionServiceDeps = createDefaultSuggestionServiceDeps()) {
|
||||
super()
|
||||
|
|
@ -317,6 +407,7 @@ export class SuggestionService extends EventEmitter {
|
|||
learnTypedText: configGet('inputLearnTypedText') === true,
|
||||
telemetryEnabled: configGet('inputTelemetryEnabled') === true,
|
||||
overlayInteractive: configGet('suggestionOverlayInteractive') !== false,
|
||||
typoAutoCorrect: configGet('typoAutoCorrectEnabled') !== false,
|
||||
provenance: this._provenance
|
||||
}
|
||||
}
|
||||
|
|
@ -328,6 +419,16 @@ export class SuggestionService extends EventEmitter {
|
|||
return configGet('llmModelId') ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* 지금 메모리에 올라와 있는 제안 모델 (아니면 null).
|
||||
* 오타 교정의 모델 검사는 콜드 모델로 하지 않는다 — 콜드 로드가 제안까지 붙잡는다.
|
||||
*/
|
||||
warmModel(): string | null {
|
||||
const model = this.resolveModel()
|
||||
if (!model || !getLocalLLMService().isAvailable()) return null
|
||||
return this._warmth.isWarm(model, Date.now()) ? model : null
|
||||
}
|
||||
|
||||
/** 설정 변경 반영 — 꺼지면 즉시 오버레이를 내린다. */
|
||||
applyConfig(): void {
|
||||
if (!this.isEnabled()) {
|
||||
|
|
@ -375,13 +476,15 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
|
||||
/** 설정에서 명시적으로 제안을 켤 때만 모델을 짧게 준비한다. */
|
||||
warmUp(): Promise<void> {
|
||||
warmUp(options: { silent?: boolean } = {}): Promise<void> {
|
||||
if (!this.isEnabled()) return Promise.resolve()
|
||||
if (this._warmUpPromise) return this._warmUpPromise
|
||||
|
||||
const abort = new AbortController()
|
||||
this._warmUpAbort = abort
|
||||
this._warmingUp = true
|
||||
// 조용한 워밍업(타이핑 중 미리 올리기)은 "준비 중" 표시를 켜지 않는다 — 표시는 정책 게이트가
|
||||
// 열려 실제로 제안을 기다릴 때(_showWarming)만 한다.
|
||||
if (!options.silent) this._warmingUp = true
|
||||
this.emit('state-changed', this.getState())
|
||||
const warmUp = this._warmUpUntilReady(abort)
|
||||
this._warmUpPromise = warmUp
|
||||
|
|
@ -475,9 +578,7 @@ export class SuggestionService extends EventEmitter {
|
|||
*/
|
||||
handleTypingContext(input: TypingContext): void {
|
||||
// 터미널은 화면 전체가 읽힌다 — 입력 줄만 접두로 쓴다. 입력 줄이 없으면 빈 접두(제안 안 함).
|
||||
const context: TypingContext = isTerminalApp(input.appName)
|
||||
? { ...input, prefix: extractTerminalPromptPrefix(input.fullText ?? input.prefix) ?? '' }
|
||||
: input
|
||||
const context: TypingContext = isTerminalApp(input.appName) ? this._terminalContext(input) : input
|
||||
this._lastContext = context
|
||||
const now = Date.now()
|
||||
this._lastContextAt = now
|
||||
|
|
@ -486,6 +587,7 @@ export class SuggestionService extends EventEmitter {
|
|||
const config = this.readPolicyConfig()
|
||||
this._logDecisionInputs(context)
|
||||
this._abortStaleGeneration(context.prefix)
|
||||
this._keepWarm(context, now)
|
||||
|
||||
const model = this.resolveModel()
|
||||
const step = decideSuggestionStep({
|
||||
|
|
@ -586,6 +688,46 @@ export class SuggestionService extends EventEmitter {
|
|||
this.emit('updated', this.getState())
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자가 타이핑 중이면 모델을 따뜻하게 유지한다.
|
||||
*
|
||||
* - 식어 있으면 첫 키 입력 때 바로 조용히 워밍업을 시작한다 — 문장을 다 쓰고 멈춘 뒤에야
|
||||
* 올리기 시작하면 그만큼 "준비 중" 이 길어진다(표시는 정책 게이트가 열릴 때만).
|
||||
* - 따뜻하지만 유지 시간이 얼마 안 남았으면 1토큰 요청으로 연장한다.
|
||||
*/
|
||||
private _keepWarm(context: TypingContext, now: number): void {
|
||||
if (!this.isEnabled() || !context.typedRecently || !context.isEditable || context.isPassword) return
|
||||
if (this._warmUpPromise || this._inFlight || this._filling) return
|
||||
const model = this.resolveModel()
|
||||
if (!model || !getLocalLLMService().isAvailable()) return
|
||||
if (!this._warmth.isWarm(model, now)) {
|
||||
if (this._warmth.isBackingOff(model, now, WARM_UP_FAILURE_BACKOFF_MS)) return
|
||||
logger.info(`타이핑 감지 — 식은 제안 모델을 미리 올린다 (model=${model})`)
|
||||
void this.warmUp({ silent: true })
|
||||
return
|
||||
}
|
||||
if (this._warmth.warmUntil - now > KEEP_WARM_REFRESH_MS) return
|
||||
if (now - this._lastKeepWarmAt < KEEP_WARM_MIN_INTERVAL_MS) return
|
||||
this._lastKeepWarmAt = now
|
||||
void this._refreshKeepAlive(model)
|
||||
}
|
||||
|
||||
private async _refreshKeepAlive(model: string): Promise<void> {
|
||||
try {
|
||||
const stream = getLocalLLMService().streamGenerate('hi', {
|
||||
model,
|
||||
maxTokens: 1,
|
||||
temperature: 0,
|
||||
keepAlive: SUGGESTION_KEEP_ALIVE
|
||||
})
|
||||
for await (const chunk of stream) void chunk
|
||||
this._noteModelWarm(model)
|
||||
logger.debug(`제안 모델 유지 시간 연장 (model=${model})`)
|
||||
} catch (error) {
|
||||
logger.debug(`제안 모델 유지 연장 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 수동 요청 (설정/단축키 경로). 디바운스를 건너뛴다. */
|
||||
async requestNow(): Promise<SuggestionRequestResult> {
|
||||
if (!this.isEnabled()) return { ok: false, reason: 'disabled' }
|
||||
|
|
@ -653,6 +795,38 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 터미널 문맥 — 화면 전체 대신 입력 줄만 접두로 쓰고, 커서 신뢰도도 입력 줄로 판단한다.
|
||||
*
|
||||
* 텔레메트리의 "편집이 문서 끝에서 일어났나" 는 화면 전체로 판정한다. Claude Code 같은 TUI 는
|
||||
* 입력 상자 아래에 상태줄이 있어 모든 입력이 "문서 중간 편집" 이 되고 caret-unknown 으로 전부
|
||||
* 막혔다(실측 2026-10-03: 보류 721회, 최다). 입력 줄이 이전 입력 줄을 늘리거나 줄인 모양이면
|
||||
* (끝에서 치거나 지움) 커서는 입력 줄 끝이다. 중간을 고친 모양이면 다음 입력까지 막는다.
|
||||
*/
|
||||
private _terminalContext(input: TypingContext): TypingContext {
|
||||
const prompt = extractTerminalPromptPrefix(input.fullText ?? input.prefix)
|
||||
const previous = this._lastTerminalPrompt
|
||||
this._lastTerminalPrompt = prompt
|
||||
let typed: boolean
|
||||
if (prompt === null) typed = false
|
||||
else if (prompt.length === 0) typed = true
|
||||
else if (previous === null) typed = prompt.length <= TERMINAL_TYPING_STEP_CHARS
|
||||
else if (prompt === previous) typed = this._terminalPromptTyped
|
||||
else if (previous.length === 0 && prompt.length > TERMINAL_TYPING_STEP_CHARS) {
|
||||
// 빈 입력칸이 한 번에 긴 글로 바뀌었다 — Claude Code 의 회색 "추천 문구" 다. UIA 는 그것도
|
||||
// 입력 글자로 준다(실측 2026-10-03: 빈 칸 → 28·29자, 그 뒤에 이어 쓴 ", ready for next test
|
||||
// cycle." 이 사용자 메시지 앞에 삽입됐다). 사용자가 치기 시작하면 다음 판정에서 다시 믿는다.
|
||||
typed = false
|
||||
} else {
|
||||
// 바뀐 곳이 끝부분뿐이면 끝에서 치는 중이다: 늘어남·줄어듦, 그리고 한글 조합처럼 마지막
|
||||
// 한두 글자가 바뀌는 것("자ㄹ" → "자료"). 조합을 "중간 편집" 으로 보던 탓에 멈춘 뒤에도
|
||||
// 막혀 있었다(실측: 30초 동안 치는데 내내 caret-unknown).
|
||||
typed = commonPrefixLength(previous, prompt) >= Math.min(previous.length, prompt.length) - 2
|
||||
}
|
||||
this._terminalPromptTyped = typed
|
||||
return { ...input, prefix: prompt ?? '', documentBefore: null, caretReliable: typed }
|
||||
}
|
||||
|
||||
/** 로컬 기억은 모델과 무관하다 — 같은 정책을 "모델 있음 · 표시 없음" 으로 평가한다. */
|
||||
private _canUseLocalMemory(context: TypingContext, config: PolicyConfig, now: number): boolean {
|
||||
return (
|
||||
|
|
@ -664,9 +838,18 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
private _collectMemoryHints(prefix: string, appName: string | null): LocalMemoryContext {
|
||||
const telemetry = getInputTelemetryService()
|
||||
const graphContext = getPersonalGraphService().retrieveContext(prefix, 4)
|
||||
const phrases = telemetry.listPhrases(60)
|
||||
const phraseHints = selectPhraseHints(phrases, prefix, 5, { appName })
|
||||
const graphContext = getPersonalGraphService().retrieveContext(prefix, 4, { appName })
|
||||
const phrases = telemetry.listPhrases(120)
|
||||
// 지금 글과 용어가 겹치는 문구만 — 문맥과 무관한 "자주 쓰는 말" 은 프롬프트를 흐린다.
|
||||
const writing = analyzeWritingContext(prefix)
|
||||
const relevanceTerms = new Set(
|
||||
buildQueryTerms([
|
||||
{ text: writing.currentSentence, weight: 2 },
|
||||
{ text: writing.lastSentence, weight: 1 }
|
||||
]).keys()
|
||||
)
|
||||
const phraseHints = selectPhraseHints(phrases, prefix, 5, { appName, relevanceTerms })
|
||||
const fallbackPhraseHints = selectPhraseHints(phrases, prefix, 5, { appName })
|
||||
const requestedApp = appName?.trim().toLowerCase()
|
||||
const appPhraseCount = requestedApp
|
||||
? phrases.filter(
|
||||
|
|
@ -676,12 +859,113 @@ export class SuggestionService extends EventEmitter {
|
|||
: 0
|
||||
return {
|
||||
continuationHints: graphContext.continuations,
|
||||
followUpHints: graphContext.followUps ?? [],
|
||||
relatedHints: graphContext.related,
|
||||
phraseHints,
|
||||
fallbackPhraseHints,
|
||||
appPhraseCount
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델 요청 하나를 만든다.
|
||||
*
|
||||
* 원형 템플릿을 아는 모델(gemma 계열)이면 prefill 이어 쓰기 — 모델 차례에 사용자가 쓰던 문장을
|
||||
* 미리 넣어 그 글자 바로 뒤부터 쓰게 한다. 모르는 모델이면 예전 지시형 프롬프트를 쓴다.
|
||||
* 두 경로 모두 같은 문맥(문서 첫머리·사실, 이 창의 앞 글, 개인 그래프)을 받는다.
|
||||
*
|
||||
* `preferInstruct`: 다음 문장 모드의 채우기 후보는 지시형을 섞는다. prefill 은 분포가 뾰족해
|
||||
* 온도를 올려도 첫 후보와 같은 문장이 반복됐고, 지시형은 "이미 제안한 문장" 목록을 따라 다른
|
||||
* 내용을 낸다(실측). 마저 쓰기 모드에서는 지시형이 새 문장을 시작해 버려 섞지 않는다.
|
||||
*/
|
||||
private _buildModelRequest(
|
||||
model: string,
|
||||
prefix: string,
|
||||
context: TypingContext,
|
||||
memory: LocalMemoryContext,
|
||||
maxChars: number,
|
||||
options: { avoidCandidates?: readonly string[]; preferInstruct?: boolean } = {}
|
||||
): ModelRequest {
|
||||
const now = Date.now()
|
||||
const recentWrites = getInputTelemetryService()
|
||||
.listRecentWrites({
|
||||
windowHandle: context.windowHandle ?? null,
|
||||
appName: context.appName,
|
||||
windowTitle: context.windowTitle
|
||||
})
|
||||
.map((entry) => ({ text: entry.text, ageMs: now - entry.at }))
|
||||
const promptInput = {
|
||||
prefix,
|
||||
documentText: context.documentBefore ?? null,
|
||||
suffix: suffixAfterCaret(context),
|
||||
appName: context.appName,
|
||||
windowTitle: context.windowTitle,
|
||||
recentWrites,
|
||||
phraseHints: relatedPromptHints(memory),
|
||||
continuationHints: memory.continuationHints,
|
||||
followUpHints: memory.followUpHints,
|
||||
avoidCandidates: options.avoidCandidates,
|
||||
candidates: 1,
|
||||
maxChars
|
||||
}
|
||||
|
||||
const prompt = buildSuggestionPrompt({ ...promptInput, prefill: true })
|
||||
const rawPrompt = renderRawChatPrompt(model, {
|
||||
system: prompt.systemPrompt,
|
||||
user: prompt.text,
|
||||
assistantPrefix: prompt.assistantPrefix ?? ''
|
||||
})
|
||||
|
||||
const instruct = options.preferInstruct === true && prompt.writing.mode === 'next-sentence'
|
||||
if (rawPrompt !== null && !instruct) {
|
||||
const written = splitSentences(context.documentBefore ?? prefix)
|
||||
const extract = (raw: string) =>
|
||||
extractContinuation(raw, {
|
||||
mode: prompt.writing.mode,
|
||||
prefill: prompt.assistantPrefix ?? '',
|
||||
writtenSentences: written,
|
||||
wordFinished: prompt.wordFinished,
|
||||
allowEmoji: prompt.allowEmoji,
|
||||
maxChars
|
||||
})
|
||||
return {
|
||||
prompt: rawPrompt,
|
||||
raw: true,
|
||||
stop: rawChatStopSequences(model),
|
||||
parse: (raw) => {
|
||||
const continuation = extract(raw)
|
||||
if (!continuation) return { candidate: null, rejected: 'empty' }
|
||||
// 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다.
|
||||
const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource)
|
||||
if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` }
|
||||
return {
|
||||
candidate:
|
||||
continuation.joint === 'attach'
|
||||
? { text: continuation.text, rank: 0, joint: 'attach' }
|
||||
: { text: continuation.text, rank: 0 },
|
||||
rejected: null
|
||||
}
|
||||
},
|
||||
partial: (raw) => extract(raw)?.text ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
const legacy = buildSuggestionPrompt(promptInput)
|
||||
return {
|
||||
prompt: legacy.text,
|
||||
systemPrompt: legacy.systemPrompt,
|
||||
raw: false,
|
||||
parse: (raw) => {
|
||||
const text = parseSuggestionCandidates(raw, prefix, 1, maxChars)[0]
|
||||
if (!text) return { candidate: null, rejected: 'empty' }
|
||||
const unsupported = findUnsupportedFacts(text, legacy.factSource)
|
||||
if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` }
|
||||
return { candidate: { text, rank: 0 }, rejected: null }
|
||||
},
|
||||
partial: sanitizePartial
|
||||
}
|
||||
}
|
||||
|
||||
private _isCurrentFallbackContext(
|
||||
prefix: string,
|
||||
context: TypingContext,
|
||||
|
|
@ -720,7 +1004,17 @@ export class SuggestionService extends EventEmitter {
|
|||
const localMemory = memory ?? this._collectMemoryHints(trimmedPrefix, context.appName)
|
||||
// 원문 뒤 공백(단어를 끝냈는가)은 세션 접두 정규화가 지운다 — 최신 원문에서 읽어 넘긴다.
|
||||
const rawPrefix = this._lastContext?.prefix ?? context.prefix
|
||||
const entries = buildLocalSuggestionCandidateEntries(trimmedPrefix, localMemory, maxCandidates, maxChars, {
|
||||
const entries = buildLocalSuggestionCandidateEntries(
|
||||
trimmedPrefix,
|
||||
{
|
||||
continuationHints: localMemory.continuationHints,
|
||||
// 직전 문장 뒤에 실제로 이어 쓴 문장이 "다음 문장" 후보로 가장 강하다.
|
||||
relatedHints: [...localMemory.followUpHints, ...localMemory.relatedHints],
|
||||
phraseHints: [...localMemory.phraseHints, ...localMemory.fallbackPhraseHints]
|
||||
},
|
||||
maxCandidates,
|
||||
maxChars,
|
||||
{
|
||||
wordFinished: /\s$/u.test(rawPrefix)
|
||||
})
|
||||
if (entries.length === 0) return false
|
||||
|
|
@ -745,7 +1039,7 @@ export class SuggestionService extends EventEmitter {
|
|||
this._provenance = {
|
||||
mode: 'local-memory',
|
||||
continuationCount: localMemory.continuationHints.length,
|
||||
relatedCount: localMemory.relatedHints.length,
|
||||
relatedCount: localMemory.relatedHints.length + localMemory.followUpHints.length,
|
||||
phraseCount: localMemory.phraseHints.length,
|
||||
appPhraseCount: localMemory.appPhraseCount
|
||||
}
|
||||
|
|
@ -847,50 +1141,35 @@ export class SuggestionService extends EventEmitter {
|
|||
// (2) follows/용어공유 관계로 끌어온 관련 문장.
|
||||
const memory = this._collectMemoryHints(trimmedPrefix, context.appName)
|
||||
const continuationHints = memory.continuationHints
|
||||
const hints = [...memory.relatedHints, ...memory.phraseHints]
|
||||
.filter((value, index, list) => list.indexOf(value) === index)
|
||||
.slice(0, 5)
|
||||
// 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자
|
||||
// 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다.
|
||||
const { systemPrompt, text } = buildSuggestionPrompt({
|
||||
prefix: trimmedPrefix,
|
||||
appName: context.appName,
|
||||
windowTitle: context.windowTitle,
|
||||
phraseHints: hints,
|
||||
continuationHints,
|
||||
candidates: 1,
|
||||
maxChars
|
||||
})
|
||||
const request = this._buildModelRequest(model, trimmedPrefix, context, memory, maxChars)
|
||||
|
||||
let raw = ''
|
||||
let parsed: { candidate: SuggestionCandidate | null; rejected: string | null } = { candidate: null, rejected: 'empty' }
|
||||
try {
|
||||
this._partialText = ''
|
||||
|
||||
const stream = getLocalLLMService().streamGenerate(text, {
|
||||
model,
|
||||
systemPrompt,
|
||||
temperature: SUGGESTION_DEFAULTS.temperature,
|
||||
maxTokens: SUGGESTION_DEFAULTS.maxOutputTokens,
|
||||
signal: abort.signal,
|
||||
keepAlive: SUGGESTION_KEEP_ALIVE
|
||||
})
|
||||
|
||||
for await (const chunk of stream) {
|
||||
// 지어낸 사실(원문에 없는 날짜·이름·숫자)로 버린 첫 후보는 같은 시간 제한 안에서 한 번 더 뽑는다.
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const temperature = attempt === 0 ? SUGGESTION_DEFAULTS.temperature : FILL_TEMPERATURE
|
||||
const raw = await this._streamModel(request, model, temperature, abort.signal, (partial) => {
|
||||
// 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다.
|
||||
// IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다.
|
||||
this._partialText = partial
|
||||
const now = Date.now()
|
||||
if (now - this._lastPartialEmitAt >= 120) {
|
||||
this._lastPartialEmitAt = now
|
||||
this.emit('updated', this.getState())
|
||||
}
|
||||
})
|
||||
if (abort.signal.aborted) break
|
||||
raw += chunk
|
||||
// 최소 한 청크라도 도착했으면 모델이 메모리에 올라온 것 — 유지 시각을 갱신한다.
|
||||
this._noteModelWarm(model)
|
||||
|
||||
// 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다.
|
||||
// IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다.
|
||||
this._partialText = sanitizePartial(raw)
|
||||
const now = Date.now()
|
||||
if (now - this._lastPartialEmitAt >= 120) {
|
||||
this._lastPartialEmitAt = now
|
||||
this.emit('updated', this.getState())
|
||||
parsed = request.parse(raw)
|
||||
if (!parsed.candidate) {
|
||||
// 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보.
|
||||
logger.debug(`제안 정제 실패: ${describeRawOutput(raw, request.raw)}`)
|
||||
}
|
||||
|
||||
if (raw.length >= MAX_RAW_OUTPUT_CHARS) break
|
||||
if (parsed.candidate || !parsed.rejected?.startsWith('unsupported-facts')) break
|
||||
logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`)
|
||||
this._partialText = ''
|
||||
}
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
|
|
@ -981,10 +1260,10 @@ export class SuggestionService extends EventEmitter {
|
|||
return
|
||||
}
|
||||
|
||||
const candidates = parseSuggestionCandidates(raw, trimmedPrefix, 1, maxChars)
|
||||
if (candidates.length === 0) {
|
||||
const first = parsed.candidate
|
||||
if (!first) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
logger.info('제안 후보가 비어 있음 (모델 출력 정제 후)')
|
||||
logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`)
|
||||
if (
|
||||
this._publishLocalMemory(
|
||||
trimmedPrefix,
|
||||
|
|
@ -1007,7 +1286,7 @@ export class SuggestionService extends EventEmitter {
|
|||
this._lastLatencyMs = latencyMs
|
||||
this._budget.noteSuccess()
|
||||
this._partialText = ''
|
||||
this._candidates = candidates.map((candidate, index) => ({ text: candidate, rank: index }))
|
||||
this._candidates = [{ ...first, rank: 0 }]
|
||||
this._activeIndex = 0
|
||||
this._anchor = context.anchor
|
||||
this._anchorKind = context.anchorKind
|
||||
|
|
@ -1020,12 +1299,12 @@ export class SuggestionService extends EventEmitter {
|
|||
this._provenance = {
|
||||
mode: 'local-model',
|
||||
continuationCount: continuationHints.length,
|
||||
relatedCount: memory.relatedHints.length,
|
||||
relatedCount: memory.relatedHints.length + memory.followUpHints.length,
|
||||
phraseCount: memory.phraseHints.length,
|
||||
appPhraseCount: memory.appPhraseCount
|
||||
}
|
||||
|
||||
this._recordSuggestion({ prefix: trimmedPrefix, text: candidates[0], model, latencyMs, candidateCount: candidates.length })
|
||||
this._recordSuggestion({ prefix: trimmedPrefix, text: first.text, model, latencyMs, candidateCount: 1 })
|
||||
logger.info(`제안 첫 후보 생성 (${latencyMs}ms, model=${model}) — 최대 ${SUGGESTION_DEFAULTS.maxCandidatesTotal}개까지 순차로 채운다`)
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
|
|
@ -1091,44 +1370,24 @@ export class SuggestionService extends EventEmitter {
|
|||
// 달라져 있으므로 이 루프는 다음 체크에서 멈춘다.
|
||||
const prefix = this._generatedForPrefix
|
||||
const memory = this._collectMemoryHints(prefix, context.appName)
|
||||
const hints = [...memory.relatedHints, ...memory.phraseHints]
|
||||
.filter((value, index, list) => list.indexOf(value) === index)
|
||||
.slice(0, 5)
|
||||
const avoidCandidates = this._candidates.map((candidate) => candidate.text)
|
||||
const { systemPrompt, text } = buildSuggestionPrompt({
|
||||
prefix,
|
||||
appName: context.appName,
|
||||
windowTitle: context.windowTitle,
|
||||
phraseHints: hints,
|
||||
continuationHints: memory.continuationHints,
|
||||
// 홀수 번째 채우기는 (다음 문장 모드일 때) 지시형으로 — 후보 다양성.
|
||||
const request = this._buildModelRequest(model, prefix, context, memory, maxChars, {
|
||||
avoidCandidates,
|
||||
candidates: 1,
|
||||
maxChars
|
||||
preferInstruct: this._candidates.length % 2 === 1
|
||||
})
|
||||
|
||||
let raw = ''
|
||||
const stream = getLocalLLMService().streamGenerate(text, {
|
||||
model,
|
||||
systemPrompt,
|
||||
temperature: SUGGESTION_DEFAULTS.temperature,
|
||||
maxTokens: SUGGESTION_DEFAULTS.maxOutputTokens,
|
||||
signal: abort.signal,
|
||||
keepAlive: SUGGESTION_KEEP_ALIVE
|
||||
})
|
||||
for await (const chunk of stream) {
|
||||
if (abort.signal.aborted) break
|
||||
raw += chunk
|
||||
this._noteModelWarm(model)
|
||||
if (raw.length >= MAX_RAW_OUTPUT_CHARS) break
|
||||
}
|
||||
const raw = await this._streamModel(request, model, FILL_TEMPERATURE, abort.signal)
|
||||
if (abort.signal.aborted || token !== this._generationToken) return false
|
||||
|
||||
const parsed = parseSuggestionCandidates(raw, prefix, 1, maxChars)
|
||||
if (parsed.length === 0) return false
|
||||
const candidateText = parsed[0]
|
||||
if (token !== this._generationToken || this._isDuplicateCandidate(candidateText)) return false
|
||||
const parsed = request.parse(raw)
|
||||
if (!parsed.candidate) {
|
||||
if (parsed.rejected && parsed.rejected !== 'empty') logger.debug(`제안 채우기 후보 버림 (${parsed.rejected})`)
|
||||
return false
|
||||
}
|
||||
const candidate = parsed.candidate
|
||||
if (token !== this._generationToken || this._isDuplicateCandidate(candidate.text)) return false
|
||||
|
||||
this._candidates.push({ text: candidateText, rank: this._candidates.length })
|
||||
this._candidates.push({ ...candidate, rank: this._candidates.length })
|
||||
logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`)
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
|
|
@ -1150,6 +1409,41 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델 요청 하나를 스트리밍으로 받는다.
|
||||
*
|
||||
* 이어 쓰기는 첫 문장만 쓴다 — 모델이 그 뒤를 더 쓰기 시작하면 거기서 끊어 지연과 GPU 시간을 아낀다.
|
||||
*/
|
||||
private async _streamModel(
|
||||
request: ModelRequest,
|
||||
model: string,
|
||||
temperature: number,
|
||||
signal: AbortSignal,
|
||||
onPartial?: (partial: string) => void
|
||||
): Promise<string> {
|
||||
let raw = ''
|
||||
const stream = getLocalLLMService().streamGenerate(request.prompt, {
|
||||
model,
|
||||
systemPrompt: request.systemPrompt,
|
||||
raw: request.raw,
|
||||
stop: request.stop,
|
||||
temperature,
|
||||
maxTokens: SUGGESTION_DEFAULTS.maxOutputTokens,
|
||||
signal,
|
||||
keepAlive: SUGGESTION_KEEP_ALIVE
|
||||
})
|
||||
for await (const chunk of stream) {
|
||||
if (signal.aborted) break
|
||||
raw += chunk
|
||||
// 최소 한 청크라도 도착했으면 모델이 메모리에 올라온 것 — 유지 시각을 갱신한다.
|
||||
this._noteModelWarm(model)
|
||||
onPartial?.(request.partial(raw))
|
||||
if (raw.length >= MAX_RAW_OUTPUT_CHARS) break
|
||||
if (request.raw && FIRST_SENTENCE_DONE.test(raw)) break
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
/** 정규화 후 완전 중복이거나 기존 후보의 접두/확장이면 중복으로 본다. */
|
||||
private _isDuplicateCandidate(candidate: string): boolean {
|
||||
const normalized = candidate.replace(/\s+/gu, ' ').trim().toLowerCase()
|
||||
|
|
@ -1400,9 +1694,12 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
// 단축키로 수락했다면 사용자가 아직 Ctrl+Alt 를 쥐고 있다. 그대로 Ctrl+V 를 보내면
|
||||
// 대상 앱에 Ctrl+Alt+V 가 들어가 붙여넣기가 되지 않는다(실측) — 뗄 때까지 기다린다.
|
||||
const modifierWaitStartedAt = Date.now()
|
||||
if (!(await waitForModifiersReleased())) {
|
||||
logger.warn('수정자 키가 떼어지지 않은 채 제안을 삽입한다 (1.5초 초과)')
|
||||
}
|
||||
// "붙여넣기가 느리다" 신고 진단 — 수락 지연이 손 떼기 대기인지 삽입 자체인지 가른다.
|
||||
logger.debug(`제안 수락: 수정자 키 떼기 대기 ${Date.now() - modifierWaitStartedAt}ms`)
|
||||
|
||||
// 붙여넣기(Ctrl+V)는 그 순간의 포그라운드 창으로 간다. 오버레이는 다음 스냅샷이 와야
|
||||
// 닫히므로, 그사이 다른 앱으로 옮겨 간 뒤 수락하면 엉뚱한 창에 삽입됐다 — 세션을 만든
|
||||
|
|
|
|||
|
|
@ -72,6 +72,11 @@ export class TextInsertService extends EventEmitter {
|
|||
this._sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
|
||||
}
|
||||
|
||||
/** 키 입력 모듈을 미리 불러 둔다 (부팅 뒤 백그라운드) — 첫 삽입 지연 제거. */
|
||||
async preload(): Promise<void> {
|
||||
await this._keyboard.preload?.()
|
||||
}
|
||||
|
||||
/**
|
||||
* 텍스트를 현재 활성 앱에 삽입한다.
|
||||
* 기본 전략: clipboard save → set → Ctrl+V → restore
|
||||
|
|
@ -86,6 +91,35 @@ export class TextInsertService extends EventEmitter {
|
|||
return run
|
||||
}
|
||||
|
||||
/**
|
||||
* 커서 앞 deleteCount 글자를 지우고 text 를 넣는다 (입력 중 오타 교정).
|
||||
*
|
||||
* 커서를 옮기지 않고 백스페이스로만 지운다 — 앱마다 다른 단어 이동/선택 동작에 기대지 않는다.
|
||||
* 다른 삽입과 같은 직렬화 꼬리를 탄다(클립보드 save/restore 가 엇갈리지 않게).
|
||||
*/
|
||||
replaceBeforeCaret(deleteCount: number, text: string, method: InsertMethod = 'clipboard'): Promise<InsertResult> {
|
||||
const run = this._tail.then(async () => {
|
||||
try {
|
||||
await this._keyboard.backspace(deleteCount)
|
||||
} catch (error) {
|
||||
throw error instanceof D3ROError
|
||||
? error
|
||||
: new D3ROError(
|
||||
ErrorCode.TextInsertKeySimulationFailed,
|
||||
`Backspace failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
// 앱이 지우기를 처리할 시간 — 붙여넣기가 지우기보다 먼저 처리되면 순서가 꼬인다.
|
||||
await this._sleep(15)
|
||||
return this._insertNow(text, method)
|
||||
})
|
||||
this._tail = run.then(
|
||||
() => undefined,
|
||||
() => undefined
|
||||
)
|
||||
return run
|
||||
}
|
||||
|
||||
private async _insertNow(text: string, method: InsertMethod): Promise<InsertResult> {
|
||||
const start = performance.now()
|
||||
this.emit('insert-started', { text, method })
|
||||
|
|
|
|||
386
apps/desktop/src/main/services/TypoCorrectionService.ts
Normal file
386
apps/desktop/src/main/services/TypoCorrectionService.ts
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
// src/main/services/TypoCorrectionService.ts
|
||||
//
|
||||
// 입력 중 오타 자동 교정 — 사용자가 멈춘 순간 커서 앞 구간의 오타를 바로 고친다.
|
||||
//
|
||||
// 흐름 (입력 텔레메트리의 'typed-context' 마다):
|
||||
// 1) 결정적 규칙(core detectTypos: 한영 전환·늘 틀린 철자·개인 어휘 근접)으로 찾으면 즉시 교체.
|
||||
// 2) 없으면 로컬 모델(제안 모델, 이미 메모리에 올라와 있을 때만)로 지금 문장의 오타를 묻고,
|
||||
// core validateModelCorrections 로 다시 거른 것만 교체.
|
||||
// 3) 교체는 "커서 앞 N 글자 백스페이스 → 고친 구간 붙여넣기" 한 번이다.
|
||||
//
|
||||
// 안전장치: 멈춤(유휴 600ms) 뒤에만, 스냅샷 뒤 사용자가 한 키라도 더 쳤으면 취소, 포그라운드 창이
|
||||
// 바뀌었으면 취소, 터미널·에디터·제외 앱·비밀번호·선택·조합 중에는 하지 않는다. 사용자가 교정을
|
||||
// 되돌리면 그 단어는 무시 목록에 올려 다시 고치지 않는다.
|
||||
//
|
||||
// 모델 검사 중에는 제안 생성을 미룬다(bootstrap 배선) — 같은 모델을 두고 경쟁하지 않고, 제안이
|
||||
// 고친 문장을 기준으로 만들어지게 한다.
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import {
|
||||
TYPO_IGNORED_WORDS_MAX,
|
||||
TYPO_MIN_IDLE_MS,
|
||||
TYPO_REVERT_WINDOW_MS,
|
||||
buildVocabulary,
|
||||
detectTypoRevert,
|
||||
detectTypos,
|
||||
parseModelTypoPairs,
|
||||
planTypoReplacement,
|
||||
tokenizeWords,
|
||||
typoRegionStart,
|
||||
validateModelCorrections,
|
||||
type TypoCorrection,
|
||||
type TypoReplacementPlan
|
||||
} from '@d3ro/core/typo-correction'
|
||||
import { isAppExcluded, isTerminalApp, shouldLearnFromApp } from '@d3ro/core/input-intelligence'
|
||||
import { analyzeWritingContext } from '@d3ro/core/writing-context'
|
||||
import { configGet, configSet } from './ConfigService'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { buildTypoCheckPrompt } from './llm-prompts'
|
||||
import type { TypingContext } from './InputTelemetryService'
|
||||
|
||||
const logger = getLogger('TypoCorrectionService')
|
||||
|
||||
/** 모델 검사 응답 제한 — 이보다 늦으면 제안이 너무 밀린다. */
|
||||
const MODEL_CHECK_TIMEOUT_MS = 2500
|
||||
/** 모델 검사 출력 상한 (토큰) */
|
||||
const MODEL_CHECK_MAX_TOKENS = 48
|
||||
/** 개인 어휘 캐시 수명 */
|
||||
const VOCABULARY_TTL_MS = 60_000
|
||||
/** 모델 검사 최소 구간 길이 (글자) */
|
||||
const MODEL_CHECK_MIN_CHARS = 6
|
||||
|
||||
/** 'typed-context' 에 대한 판단 — 제안 서비스로 그대로 넘길지(pass), 미룰지. */
|
||||
export type TypoVerdict = 'pass' | 'correcting' | 'checking'
|
||||
|
||||
export interface TypoCorrectionDeps {
|
||||
/** 커서 앞 deleteCount 글자를 지우고 text 를 넣는다. 성공 여부. */
|
||||
replaceBeforeCaret(deleteCount: number, text: string): Promise<boolean>
|
||||
/** 마지막 키보드 입력 시각 */
|
||||
lastKeyAt(): number
|
||||
/** 곧 보낼 프로그램 키 수 (입력 통계 제외) */
|
||||
expectProgrammaticKeys(count: number): void
|
||||
/** 곧 삽입할 텍스트 (학습 제외). 취소 함수를 돌려준다. */
|
||||
expectProgrammaticInsert(text: string): () => void
|
||||
/** 지금 포그라운드 창 핸들 */
|
||||
foregroundHandle(): number | null
|
||||
/** 개인 문장 원문과 횟수 (개인 어휘) */
|
||||
recentTexts(): Array<{ text: string; count: number }>
|
||||
/** 지금 메모리에 올라와 있는 제안 모델 id (아니면 null — 콜드 모델로 검사하지 않는다) */
|
||||
warmModel(): string | null
|
||||
/** 모델 스트림 생성 */
|
||||
generate(
|
||||
prompt: string,
|
||||
options: { model: string; systemPrompt: string; maxTokens: number; signal: AbortSignal }
|
||||
): AsyncIterable<string>
|
||||
}
|
||||
|
||||
interface TypoCorrectionEvents {
|
||||
corrected: (payload: { corrections: TypoCorrection[]; appName: string | null }) => void
|
||||
/** 모델 검사가 끝나 미뤄 둔 문맥을 제안 쪽으로 넘겨도 된다 (교정이 없었을 때만). */
|
||||
settled: (payload: { context: TypingContext }) => void
|
||||
reverted: (payload: { word: string }) => void
|
||||
}
|
||||
|
||||
interface AppliedCorrection {
|
||||
corrections: TypoCorrection[]
|
||||
completedAt: number
|
||||
tailLength: number
|
||||
/** 교정 직후 접두 길이 — 되돌림은 이 근처에서만 본다 */
|
||||
prefixLength: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 되돌림으로 볼 접두 길이 차이 상한. 한참 더 쓴 뒤 같은 오타를 새로 친 것을 "되돌림" 으로 오인해
|
||||
* 무시 목록에 올리지 않게 한다.
|
||||
*/
|
||||
const REVERT_LENGTH_TOLERANCE = 12
|
||||
|
||||
export class TypoCorrectionService extends EventEmitter {
|
||||
private _applying = false
|
||||
private _check: { abort: AbortController; prefix: string; context: TypingContext } | null = null
|
||||
/** 마지막으로 결정적·모델 검사를 마친 구간 — 같은 구간을 되풀이해 묻지 않는다. */
|
||||
private _lastCheckedRegion = ''
|
||||
private _lastApplied: AppliedCorrection | null = null
|
||||
private _vocabulary: { at: number; latin: Map<string, number>; known: Set<string> } | null = null
|
||||
|
||||
constructor(private readonly _deps: TypoCorrectionDeps) {
|
||||
super()
|
||||
}
|
||||
|
||||
override on<K extends keyof TypoCorrectionEvents>(event: K, listener: TypoCorrectionEvents[K]): this {
|
||||
return super.on(event, listener as (...args: unknown[]) => void)
|
||||
}
|
||||
|
||||
override emit<K extends keyof TypoCorrectionEvents>(
|
||||
event: K,
|
||||
...args: Parameters<TypoCorrectionEvents[K]>
|
||||
): boolean {
|
||||
return super.emit(event, ...args)
|
||||
}
|
||||
|
||||
isEnabled(): boolean {
|
||||
return configGet('typoAutoCorrectEnabled') !== false
|
||||
}
|
||||
|
||||
/** 모델 검사 진행 중인가 */
|
||||
get checking(): boolean {
|
||||
return this._check !== null
|
||||
}
|
||||
|
||||
/**
|
||||
* 입력 문맥 하나를 처리한다.
|
||||
*
|
||||
* 'pass' 면 호출자가 이 문맥을 제안 서비스로 넘긴다. 'correcting' 이면 곧 텍스트가 바뀌므로
|
||||
* 넘기지 않는다(교정 뒤 새 스냅샷이 온다). 'checking' 이면 모델 검사가 끝날 때 'settled' 로 넘긴다.
|
||||
*/
|
||||
handleTypingContext(context: TypingContext): TypoVerdict {
|
||||
this._watchRevert(context)
|
||||
if (this._applying) return 'correcting'
|
||||
|
||||
// 진행 중 모델 검사 — 같은 접두면 계속 기다리고, 달라졌으면(더 쳤다) 버린다.
|
||||
if (this._check) {
|
||||
if (this._check.prefix === context.prefix) {
|
||||
this._check.context = context
|
||||
return 'checking'
|
||||
}
|
||||
this._cancelCheck()
|
||||
}
|
||||
|
||||
if (!this._eligible(context)) return 'pass'
|
||||
if (context.idleMs < TYPO_MIN_IDLE_MS) return 'pass'
|
||||
|
||||
const prefix = context.prefix
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
if (!region.trim() || region === this._lastCheckedRegion) return 'pass'
|
||||
|
||||
const ignoredWords = configGet('typoIgnoredWords') ?? []
|
||||
const vocabulary = this._loadVocabulary()
|
||||
const keyAtDecision = this._deps.lastKeyAt()
|
||||
|
||||
const corrections = detectTypos(prefix, {
|
||||
includeTrailingToken: true,
|
||||
ignoredWords,
|
||||
vocabulary: vocabulary.latin
|
||||
})
|
||||
const plan = planTypoReplacement(prefix, corrections)
|
||||
if (plan) {
|
||||
this._lastCheckedRegion = region
|
||||
void this._apply(plan, context, keyAtDecision)
|
||||
return 'correcting'
|
||||
}
|
||||
|
||||
const model = configGet('typoAutoCorrectUseModel') !== false ? this._deps.warmModel() : null
|
||||
if (!model || !this._worthModelCheck(region)) {
|
||||
this._lastCheckedRegion = region
|
||||
return 'pass'
|
||||
}
|
||||
|
||||
this._lastCheckedRegion = region
|
||||
const abort = new AbortController()
|
||||
this._check = { abort, prefix, context }
|
||||
void this._runModelCheck(model, context, abort, keyAtDecision, ignoredWords, vocabulary.known)
|
||||
return 'checking'
|
||||
}
|
||||
|
||||
/** 설정에서 끌 때·종료할 때 */
|
||||
dispose(): void {
|
||||
this._cancelCheck()
|
||||
this.removeAllListeners()
|
||||
}
|
||||
|
||||
// ── 판단 ───────────────────────────────────────────────
|
||||
|
||||
private _eligible(context: TypingContext): boolean {
|
||||
if (!this.isEnabled()) return false
|
||||
if (!context.available || !context.isEditable || context.isPassword) return false
|
||||
if (context.isComposing || context.hasSelection) 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
|
||||
}
|
||||
|
||||
/** 모델에 물어볼 만한 구간인가 — 끝난 단어가 2개 이상인 글. */
|
||||
private _worthModelCheck(region: string): boolean {
|
||||
if (region.replace(/\s+/gu, '').length < MODEL_CHECK_MIN_CHARS) return false
|
||||
return tokenizeWords(region).length >= 2
|
||||
}
|
||||
|
||||
private _loadVocabulary(): { latin: Map<string, number>; known: Set<string> } {
|
||||
const now = Date.now()
|
||||
if (this._vocabulary && now - this._vocabulary.at < VOCABULARY_TTL_MS) return this._vocabulary
|
||||
const texts = this._deps.recentTexts()
|
||||
const latin = buildVocabulary(texts)
|
||||
// 사용자가 여러 번 쓴 어절은 의도한 표기다 — 모델이 고치자고 해도 두지 않는다.
|
||||
const counts = new Map<string, number>()
|
||||
for (const { text, count } of texts) {
|
||||
for (const token of tokenizeWords(text)) {
|
||||
const key = token.text.toLowerCase()
|
||||
counts.set(key, (counts.get(key) ?? 0) + Math.max(1, count))
|
||||
}
|
||||
}
|
||||
const known = new Set([...counts].filter(([, count]) => count >= 3).map(([word]) => word))
|
||||
this._vocabulary = { at: now, latin, known }
|
||||
return this._vocabulary
|
||||
}
|
||||
|
||||
// ── 모델 검사 ──────────────────────────────────────────
|
||||
|
||||
private async _runModelCheck(
|
||||
model: string,
|
||||
context: TypingContext,
|
||||
abort: AbortController,
|
||||
keyAtDecision: number,
|
||||
ignoredWords: readonly string[],
|
||||
knownWords: ReadonlySet<string>
|
||||
): Promise<void> {
|
||||
const timer = setTimeout(() => abort.abort(), MODEL_CHECK_TIMEOUT_MS)
|
||||
timer.unref?.()
|
||||
let corrected = false
|
||||
try {
|
||||
const prefix = context.prefix
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
const writing = analyzeWritingContext(prefix.slice(0, typoRegionStart(prefix)))
|
||||
const { systemPrompt, text } = buildTypoCheckPrompt({
|
||||
sentence: region,
|
||||
previous: [writing.earlierText, writing.lastSentence, writing.currentSentence].filter(Boolean).join(' ')
|
||||
})
|
||||
let raw = ''
|
||||
for await (const chunk of this._deps.generate(text, {
|
||||
model,
|
||||
systemPrompt,
|
||||
maxTokens: MODEL_CHECK_MAX_TOKENS,
|
||||
signal: abort.signal
|
||||
})) {
|
||||
if (abort.signal.aborted) break
|
||||
raw += chunk
|
||||
if (raw.length > 400) break
|
||||
}
|
||||
if (abort.signal.aborted || this._check?.abort !== abort) return
|
||||
|
||||
const corrections = validateModelCorrections(prefix, parseModelTypoPairs(raw), { ignoredWords, knownWords })
|
||||
const plan = planTypoReplacement(prefix, corrections)
|
||||
if (!plan) return
|
||||
// 검사하는 사이 사용자가 더 쳤으면 접두가 달라져 위에서 취소됐다. 여기서 한 번 더 키를 본다.
|
||||
this._check = null
|
||||
corrected = await this._apply(plan, context, keyAtDecision)
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
logger.debug(`모델 오타 검사 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
const pending = this._check?.abort === abort ? this._check : null
|
||||
if (pending) this._check = null
|
||||
// 교정하지 않았으면(오타 없음·시간 초과·실패) 미뤄 둔 최신 문맥을 제안 쪽으로 넘긴다.
|
||||
// 새 문맥 때문에 취소된 검사는 pending 이 없다 — 그 문맥은 이미 제안 쪽으로 넘어갔다.
|
||||
if (!corrected && pending) this.emit('settled', { context: pending.context })
|
||||
}
|
||||
}
|
||||
|
||||
private _cancelCheck(): void {
|
||||
if (!this._check) return
|
||||
this._check.abort.abort()
|
||||
this._check = null
|
||||
}
|
||||
|
||||
// ── 적용 ───────────────────────────────────────────────
|
||||
|
||||
private async _apply(plan: TypoReplacementPlan, context: TypingContext, keyAtDecision: number): Promise<boolean> {
|
||||
if (this._deps.lastKeyAt() !== keyAtDecision) {
|
||||
logger.debug('오타 교정 취소: 판단 뒤 키 입력이 있었다')
|
||||
return false
|
||||
}
|
||||
if (context.windowHandle != null) {
|
||||
const current = this._deps.foregroundHandle()
|
||||
if (current !== null && current !== context.windowHandle) {
|
||||
logger.debug('오타 교정 취소: 포커스가 다른 창으로 옮겨 갔다')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
this._applying = true
|
||||
// 백스페이스 + 붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다.
|
||||
this._deps.expectProgrammaticKeys(plan.deleteCount + 2)
|
||||
const cancelInsert = this._deps.expectProgrammaticInsert(plan.insertText)
|
||||
try {
|
||||
const ok = await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText)
|
||||
if (!ok) {
|
||||
cancelInsert()
|
||||
logger.warn('오타 교정 삽입 실패')
|
||||
return false
|
||||
}
|
||||
this._lastApplied = {
|
||||
corrections: plan.corrections,
|
||||
completedAt: Date.now(),
|
||||
tailLength: plan.insertText.length,
|
||||
prefixLength: context.prefix.length - plan.deleteCount + plan.insertText.length
|
||||
}
|
||||
this._lastCheckedRegion = ''
|
||||
const sources = [...new Set(plan.corrections.map((correction) => correction.source))].join(',')
|
||||
// 사용자가 친 원문은 로그에 남기지 않는다 — 개수와 근거만.
|
||||
logger.info(`오타 교정 ${plan.corrections.length}건 (${sources}, app=${context.appName ?? '-'})`)
|
||||
this.emit('corrected', { corrections: plan.corrections, appName: context.appName })
|
||||
return true
|
||||
} catch (error) {
|
||||
cancelInsert()
|
||||
logger.warn(`오타 교정 예외: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return false
|
||||
} finally {
|
||||
this._applying = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 교정 직후 사용자가 원래 단어로 되돌렸는지 본다 — 되돌렸으면 그 단어를 무시 목록에 올린다.
|
||||
* 교정 직전에 찍힌 스냅샷(교정 전 텍스트)을 되돌림으로 오인하지 않도록 완료 시각 뒤 것만 본다.
|
||||
*/
|
||||
private _watchRevert(context: TypingContext): void {
|
||||
const applied = this._lastApplied
|
||||
if (!applied) return
|
||||
const now = Date.now()
|
||||
if (now - applied.completedAt > TYPO_REVERT_WINDOW_MS) {
|
||||
this._lastApplied = null
|
||||
return
|
||||
}
|
||||
if (context.capturedAt <= applied.completedAt + 200 || !context.available) return
|
||||
if (Math.abs(context.prefix.length - applied.prefixLength) > REVERT_LENGTH_TOLERANCE) return
|
||||
for (const correction of applied.corrections) {
|
||||
if (!detectTypoRevert(context.prefix, { from: correction.from, to: correction.to, tailLength: applied.tailLength })) {
|
||||
continue
|
||||
}
|
||||
this._ignoreWord(correction.from)
|
||||
logger.info('오타 교정을 사용자가 되돌림 — 그 단어는 앞으로 고치지 않는다')
|
||||
this.emit('reverted', { word: correction.from })
|
||||
this._lastApplied = null
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private _ignoreWord(word: string): void {
|
||||
const current = configGet('typoIgnoredWords') ?? []
|
||||
if (current.some((entry) => entry.toLowerCase() === word.toLowerCase())) return
|
||||
configSet('typoIgnoredWords', [...current, word].slice(-TYPO_IGNORED_WORDS_MAX))
|
||||
}
|
||||
}
|
||||
|
||||
let instance: TypoCorrectionService | null = null
|
||||
|
||||
/** 기본 협력자는 bootstrap 이 연결한다 (서비스끼리 직접 import 하지 않는다). */
|
||||
export function initTypoCorrectionService(deps: TypoCorrectionDeps): TypoCorrectionService {
|
||||
instance?.dispose()
|
||||
instance = new TypoCorrectionService(deps)
|
||||
return instance
|
||||
}
|
||||
|
||||
export function getTypoCorrectionService(): TypoCorrectionService | null {
|
||||
return instance
|
||||
}
|
||||
|
||||
export function resetTypoCorrectionServiceForTests(): void {
|
||||
instance?.dispose()
|
||||
instance = null
|
||||
}
|
||||
|
|
@ -129,3 +129,27 @@ export function acceleratorsToReserve(
|
|||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안 창이 떠 있는 동안에만 잡을 accelerator (중복 없음).
|
||||
*
|
||||
* Windows 는 평소 아무것도 예약하지 않는다(위). 그런데 uiohook 은 키를 엿듣기만 해서
|
||||
* Ctrl+Alt+Enter 수락이 포커스된 앱에도 그대로 전달돼 개행이 들어갔다(실측 2026-10-03,
|
||||
* Claude Code 입력창). 제안 창이 보이는 동안만 제안 단축키를 noop 으로 등록해 OS 가 삼키게
|
||||
* 하고, 창이 사라지면 바로 푼다 — 평소에는 다른 앱의 같은 단축키를 빼앗지 않는다.
|
||||
* 이미 상시 예약된 것(macOS)은 `alreadyReserved` 로 빼서 이중 등록하지 않는다.
|
||||
*/
|
||||
export function suggestionCaptureAccelerators(
|
||||
bindings: readonly ReservableBinding[],
|
||||
platform: string,
|
||||
alreadyReserved: ReadonlySet<string> = new Set()
|
||||
): string[] {
|
||||
const out: string[] = []
|
||||
for (const { actionId, binding } of bindings) {
|
||||
if (!SUGGESTION_ACTIONS.has(actionId)) continue
|
||||
const accelerator = bindingToAccelerator(binding, platform)
|
||||
if (accelerator === null || alreadyReserved.has(accelerator) || out.includes(accelerator)) continue
|
||||
out.push(accelerator)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,14 @@ import {
|
|||
renderInstruction,
|
||||
type RenderedInstruction,
|
||||
} from '@d3ro/core/instruction-template'
|
||||
import {
|
||||
analyzeDocumentContext,
|
||||
analyzeWritingContext,
|
||||
type WritingContext,
|
||||
type WritingLanguage,
|
||||
type WritingRegister
|
||||
} from '@d3ro/core/writing-context'
|
||||
import { containsEmoji } from '@d3ro/core/input-intelligence'
|
||||
|
||||
const logger = getLogger('llm-prompts')
|
||||
|
||||
|
|
@ -174,7 +182,7 @@ export { BASE_SYSTEM_PROMPTS }
|
|||
// ============================================================
|
||||
|
||||
/**
|
||||
* 추론 모델이 `thinking` 블록을 지 않게 하는 prefix.
|
||||
* 추론 모델이 `thinking` 블록을 쓰지 않게 하는 prefix.
|
||||
*
|
||||
* `LocalLLMService.processText` 가 같은 목적으로 쓰는 값과 같다. 제안 경로는
|
||||
* `streamGenerate` 를 직접 부르므로 여기서 직접 붙인다.
|
||||
|
|
@ -182,31 +190,71 @@ export { BASE_SYSTEM_PROMPTS }
|
|||
export const SUGGESTION_NO_THINK_PREFIX = '/no_think'
|
||||
|
||||
/**
|
||||
* 제안 시스템 프롬프트.
|
||||
* 제안 시스템 프롬프트 (지시형 — 템플릿을 모르는 모델용).
|
||||
*
|
||||
* 지시문은 **시스템 프롬프트에만** 둔다. 지시문이 처리 대상 텍스트 자리에 들어가
|
||||
* 지시문 자체를 다듬어 돌려주던 회귀(밋 9c2b4d4)와 같은 부류의 사고를 막는다.
|
||||
* 지시문 자체를 다듬어 돌려주던 회귀(커밋 9c2b4d4)와 같은 부류의 사고를 막는다.
|
||||
*/
|
||||
const SUGGESTION_SYSTEM_PROMPT = `사용자가 지금 입력창에 글을 쓰는 중입니다. 사용자가 마지막으로 쓴 글 뒤에 이어질 다음 문장을 제안하세요.
|
||||
const SUGGESTION_SYSTEM_PROMPT = `사용자가 지금 입력창에 글을 쓰는 중입니다. 사용자 메시지의 [이어 쓰기 지시]에 따라, 커서 바로 뒤에 이어질 다음 문장(또는 지금 쓰는 문장의 나머지)을 제안하세요.
|
||||
|
||||
규칙:
|
||||
- 당신은 사용자와 대화하는 비서가 아닙니다. 사용자 본인이 다음에 직접 칠 문장만, 사용자 자신의 목소리로 쓰세요.
|
||||
- 당신은 사용자와 대화하는 비서가 아닙니다. 사용자 본인이 다음에 직접 칠 글만, 사용자 자신의 목소리로 쓰세요.
|
||||
- 사용자에게 질문하지 말고, 도와주겠다고 제안하지 말고, 사용자를 부르듯 말하지 마세요. ("궁금한 점이 있으신가요?", "도와드릴까요?" 같은 응답 금지)
|
||||
- [지금 쓰는 문장]이 있으면 그 문장의 나머지만 쓰세요. 이미 쓴 부분을 되풀이하지 말고, 바로 이어 붙일 수 있게 쓰세요.
|
||||
- 앞 문맥의 주제·대상·사실(이름, 날짜, 숫자, 용어)과 어긋나지 않게 쓰고, 앞에서 이미 한 말은 반복하지 마세요. [글에 나온 사실]의 이름·날짜·숫자는 그대로 쓰고 새로 지어내지 마세요.
|
||||
- [이 창에서 조금 전에 쓴 글]은 같은 대화·문서에서 사용자가 앞서 쓴 글입니다. 흐름을 이어 가는 데 쓰세요.
|
||||
- 입력이 검색어나 폼 입력처럼 보이면(문장이 아니라 키워드 나열 등), 같은 종류의 텍스트로 짧게 이어 쓰세요.
|
||||
- 사용자가 언어와 같은 언어로 쓰세요.
|
||||
- 사용자가 쓴 언어와 같은 언어로 쓰세요.
|
||||
- 사용자의 말투와 문체를 유지하세요. 존댓말/반말, 격식/비격식을 바꾸지 마세요.
|
||||
- 이미 나온 단어를 되풀이하지 말고 이어지는 내용만 쓰세요.
|
||||
- [사용자가 평소 이어 쓴 문장]과 [관련해서 사용자가 쓴 문장]은 사용자의 실제 글입니다. 내용이 지금 문맥과 맞으면 그 표현과 흐름을 적극적으로 따르세요. 맞지 않으면 무시하세요.
|
||||
- 후보를 한 줄에 하나씩, 번호나 따옴표, 설명 없이 출력하세요.
|
||||
- 각 후보는 한 문장, 최대 {{maxChars}}자입니다.
|
||||
- 확신이 없으면 짧게 쓰세요. 리말, 요약, 빈 줄을 출력하지 마세요.`
|
||||
- 확신이 없으면 짧게 쓰세요. 머리말, 요약, 빈 줄을 출력하지 마세요.`
|
||||
|
||||
/**
|
||||
* 제안 시스템 프롬프트 (이어 쓰기형 — 모델 차례에 사용자 글을 미리 넣는 prefill 경로).
|
||||
*
|
||||
* 모델은 "답변" 이 아니라 사용자 글의 다음 글자부터 쓴다. 지시형보다 문장 이음새·말투·단어 중간
|
||||
* 이어 쓰기가 정확하다(실측 2026-10-03, gemma4:e4b).
|
||||
*/
|
||||
const SUGGESTION_CONTINUE_SYSTEM_PROMPT = `사용자가 지금 입력창에 직접 글을 쓰고 있습니다. 당신의 차례에는 사용자가 쓰던 글의 끝부분이 이미 적혀 있습니다. 그 바로 뒤를, 사용자 본인이 이어서 치는 것처럼 이어 쓰세요.
|
||||
|
||||
규칙:
|
||||
- 사용자 본인의 목소리로 씁니다. 비서처럼 대답하거나, 사용자에게 질문하거나, 설명을 붙이지 마세요.
|
||||
- 문장이 끝나지 않았으면 그 문장만 자연스럽게 끝맺고 멈추세요. 문장이 이미 끝났으면 다음 문장 하나만 쓰고 멈추세요.
|
||||
- 단어 중간에서 끊겼으면 그 단어의 나머지부터 쓰세요. 이미 쓴 부분을 되풀이하지 마세요.
|
||||
- 이름·날짜·시각·숫자·용어는 [글에 나온 사실]과 앞 문맥에 있는 그대로 쓰세요. 사람 이름은 앞 글에 나온 이름만 쓰세요.
|
||||
- 앞 글에 없는 날짜·시각·숫자·이름이 필요하면 지어내지 말고, 그 사실 없이 쓸 수 있는 말로 쓰세요.
|
||||
- 앞에서 이미 한 말은 다시 하지 마세요. 글의 흐름(인사 → 용건 → 세부 → 요청 → 맺음)에서 바로 다음에 올 내용을 쓰세요.
|
||||
- 언어와 말투(존댓말/반말, 격식/비격식, ㅋㅋ 같은 습관)를 앞 글과 똑같이 유지하세요. 앞 글에 이모지가 없으면 이모지를 쓰지 마세요.
|
||||
- [이 창에서 조금 전에 쓴 글]은 같은 대화·문서에서 사용자가 앞서 쓴 글입니다. 대화가 이어지는 흐름을 잡는 데 쓰세요.
|
||||
- [사용자가 …] 로 시작하는 항목은 사용자의 실제 글입니다. 지금 문맥과 맞으면 그 표현을 그대로 따르고, 맞지 않으면 무시하세요.
|
||||
- 검색창·폼처럼 문장이 아닌 입력이면 같은 종류로 짧게 이어 쓰세요.
|
||||
- 최대 {{maxChars}}자. 이어지는 글만 쓰고 따옴표·머리말·설명을 붙이지 마세요.`
|
||||
|
||||
/** 이 창에서 조금 전에 쓴 글 — 채팅처럼 보내고 나면 입력칸이 비는 곳의 앞 대화. */
|
||||
export interface RecentWriteHint {
|
||||
text: string
|
||||
/** 쓴 지 얼마나 지났나 (ms) */
|
||||
ageMs: number
|
||||
}
|
||||
|
||||
export interface SuggestionPromptInput {
|
||||
/** 어렛 앞까지의 텍스트 */
|
||||
/** 커서 앞까지의 텍스트 (세션 접두) */
|
||||
prefix: string
|
||||
/** 활성 앱/창 (맥락 트) */
|
||||
/**
|
||||
* 커서 앞 문서 전체 (원문 — 뒤 공백 포함). 있으면 앞 문맥·첫머리·사실을 여기서 읽는다.
|
||||
* 세션 접두는 400자 창이라 글 앞쪽의 이름·날짜·인사를 모델이 못 본다.
|
||||
*/
|
||||
documentText?: string | null
|
||||
/** 커서 뒤 텍스트 (문서 중간에서 쓸 때) — 겹치지 않게 참고만 한다 */
|
||||
suffix?: string | null
|
||||
/** 활성 앱/창 (맥락 힌트) */
|
||||
appName?: string | null
|
||||
windowTitle?: string | null
|
||||
/** 사용자가 자주 쓰는 표현 (개인화 힌트) */
|
||||
/** 같은 창에서 조금 전에 쓴(보낸) 글 — 오래된 것부터 */
|
||||
recentWrites?: readonly RecentWriteHint[]
|
||||
/** 사용자가 자주 쓰는 표현 (개인화 힌트 — 지금 문맥과 용어가 겹치는 것) */
|
||||
phraseHints?: readonly string[]
|
||||
/**
|
||||
* 과거에 같은 꼬리 뒤에 실제로 이어 쓴 문장 (개인 기억).
|
||||
|
|
@ -214,6 +262,8 @@ export interface SuggestionPromptInput {
|
|||
* 자주 쓰는 표현보다 훨씬 강한 문맥 신호다 — 사용자 자신의 실제 이어쓰기다.
|
||||
*/
|
||||
continuationHints?: readonly string[]
|
||||
/** 직전 문장 뒤에 사용자가 실제로 이어 쓴 문장 (개인 그래프 follows) */
|
||||
followUpHints?: readonly string[]
|
||||
/**
|
||||
* 이미 이 세션에서 제안한 문장들 — 채우기 루프가 중복을 피하려고 넘긴다.
|
||||
* 지시문이 아니라 데이터 섹션으로만 들어간다(기존 continuationHints 와 같은 방식).
|
||||
|
|
@ -223,61 +273,210 @@ export interface SuggestionPromptInput {
|
|||
candidates?: number
|
||||
/** 후보당 최대 길이 */
|
||||
maxChars?: number
|
||||
/**
|
||||
* true 면 이어 쓰기형(prefill) 요청을 만든다 — `assistantPrefix` 를 모델 차례 앞에 넣어
|
||||
* 원형 템플릿으로 보내야 한다. 후보는 1개다.
|
||||
*/
|
||||
prefill?: boolean
|
||||
}
|
||||
|
||||
export interface SuggestionPrompt {
|
||||
systemPrompt: string
|
||||
text: string
|
||||
/** prefill 경로에서 모델 차례 앞에 넣을 사용자 글 (지시형이면 null) */
|
||||
assistantPrefix: string | null
|
||||
/** 접두 분석 결과 — 후처리(extractContinuation)가 같은 분해를 쓴다 */
|
||||
writing: WritingContext
|
||||
/** 사용자가 친 원문이 공백으로 끝났는가 (단어를 끝냈는가) */
|
||||
wordFinished: boolean
|
||||
/** 사용자가 이모지를 쓰는가 (앞 글·이 창의 앞 글 기준) */
|
||||
allowEmoji: boolean
|
||||
/** 사실 검사용 원문 — 문서 + 창 제목 + 이 창에서 조금 전에 쓴 글 + 개인 힌트 */
|
||||
factSource: string
|
||||
}
|
||||
|
||||
const LANGUAGE_LABEL: Record<WritingLanguage, string> = {
|
||||
ko: '한국어',
|
||||
en: '영어',
|
||||
ja: '일본어',
|
||||
zh: '중국어',
|
||||
other: '사용자가 쓴 언어'
|
||||
}
|
||||
|
||||
const REGISTER_LABEL: Record<WritingRegister, string> = {
|
||||
formal: '격식체 존댓말 (-습니다/-ㅂ니다)',
|
||||
polite: '해요체 존댓말 (-요)',
|
||||
plain: '평서체 (-다, -었다 — 일기·메모·문서체. 반말 -어/-야 를 섞지 말 것)',
|
||||
casual: '반말 (-어, -야, -지)'
|
||||
}
|
||||
|
||||
/** 프롬프트에 원문으로 보여 줄 앞 문맥 길이. 모델 문맥(4096 토큰)과 지연 사이의 절충. */
|
||||
const PROMPT_EARLIER_CHARS = 900
|
||||
/** 원문 창 — 앞 문맥 + 직전 문장 + 지금 문장이 대략 이 안에 든다. 첫머리는 이 밖일 때만 보여 준다. */
|
||||
const PROMPT_WINDOW_CHARS = 1200
|
||||
|
||||
const SEARCH_CONTEXT = /(google|naver|네이버|daum|다음 검색|bing|duckduckgo|youtube|검색|search)/iu
|
||||
|
||||
/**
|
||||
* 검색창 입력인가 — 검색 페이지·검색 창 제목이고, 짧고, 문장 부호가 없다.
|
||||
*
|
||||
* 실측: "서울 강남 파스타" 뒤에 "맛집 추천 좀 해주세요." 같은 문장을 붙였다. 검색어는 키워드로 잇는다.
|
||||
*/
|
||||
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)
|
||||
}
|
||||
|
||||
function formatAge(ageMs: number): string {
|
||||
return ageMs < 60_000 ? '방금' : `${Math.round(ageMs / 60_000)}분 전`
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안 요청용 (systemPrompt, text) 를 만든다.
|
||||
* prefill 할 사용자 글 — 지금 문장(마저 쓰기) 또는 직전 문장(다음 문장), 원문의 끝 공백·줄바꿈 포함.
|
||||
*
|
||||
* 시스템 프롬프트에 지시문, 사용자 메시지에는 **지금까지 쓴 텍스트와 맥락**만 는다.
|
||||
* 끝 공백은 "단어를 끝냈다" 는 신호다. 지우면 모델이 그 단어에 글자를 붙여 쓴다.
|
||||
*/
|
||||
export function buildSuggestionPrompt(input: SuggestionPromptInput): {
|
||||
systemPrompt: string
|
||||
text: string
|
||||
} {
|
||||
const candidates = Math.max(1, Math.min(input.candidates ?? 3, 5))
|
||||
function buildAssistantPrefix(writing: WritingContext, raw: string): string {
|
||||
const body = writing.currentSentence || writing.lastSentence
|
||||
// 줄바꿈은 남긴다(새 줄·목록 다음 항목). 끝 공백은 뺀다 — 공백 하나로 끝난 토큰 상태가 모델을
|
||||
// 흔든다(실측: "검토해 보시고 " → "긍정적인 피드백 부탁드립니다."). 대신 wordFinished 로 거른다.
|
||||
return /\n[ \t]*$/u.test(raw) && writing.mode === 'next-sentence' ? `${body}\n` : body
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안 요청용 (systemPrompt, text[, assistantPrefix]) 를 만든다.
|
||||
*
|
||||
* 시스템 프롬프트에 지시문, 사용자 메시지에는 **지금까지 쓴 텍스트와 맥락**만 넣는다.
|
||||
* 접두는 "앞 문맥 · 직전 문장 · 지금 쓰는 문장" 으로 나눠 보여 주고, 문장을 마저 쓸지
|
||||
* 다음 문장을 쓸지, 어떤 언어·말투인지를 명시한다 — 소형 모델은 이걸 스스로 잘 못 읽는다.
|
||||
* 400자 창 밖의 글 첫머리와 이름·날짜·숫자는 따로 뽑아 보여 준다.
|
||||
*/
|
||||
export function buildSuggestionPrompt(input: SuggestionPromptInput): SuggestionPrompt {
|
||||
const prefill = input.prefill === true
|
||||
const candidates = prefill ? 1 : Math.max(1, Math.min(input.candidates ?? 3, 5))
|
||||
const maxChars = Math.max(20, Math.min(input.maxChars ?? 160, 400))
|
||||
const rawSource = input.documentText && input.documentText.trim().length > 0 ? input.documentText : input.prefix
|
||||
const writing = analyzeWritingContext(rawSource.slice(-PROMPT_WINDOW_CHARS * 2), PROMPT_EARLIER_CHARS)
|
||||
const documentContext = analyzeDocumentContext(rawSource, PROMPT_WINDOW_CHARS)
|
||||
|
||||
const sections: string[] = ['[지금까지 텍스트]', input.prefix]
|
||||
|
||||
if (input.phraseHints && input.phraseHints.length > 0) {
|
||||
sections.push('', '[자주 쓰는 표현]')
|
||||
for (const hint of input.phraseHints.slice(0, 5)) {
|
||||
sections.push(`- ${hint}`)
|
||||
}
|
||||
}
|
||||
const sections: string[] = []
|
||||
|
||||
if (input.appName || input.windowTitle) {
|
||||
sections.push('', '[현재 앱]')
|
||||
const app = [input.appName, input.windowTitle].filter(Boolean).join(' — ')
|
||||
sections.push(app)
|
||||
sections.push('[현재 앱]', app, '')
|
||||
}
|
||||
|
||||
if (documentContext.opening) sections.push('[글의 첫머리]', documentContext.opening, '')
|
||||
if (documentContext.facts.length > 0) sections.push('[글에 나온 사실]', documentContext.facts.join(', '), '')
|
||||
|
||||
const recent = (input.recentWrites ?? []).filter((item) => item.text.trim().length > 0).slice(-4)
|
||||
if (recent.length > 0) {
|
||||
sections.push('[이 창에서 조금 전에 쓴 글 — 오래된 것부터]')
|
||||
for (const item of recent) {
|
||||
const text = item.text.replace(/\s+/gu, ' ').trim()
|
||||
sections.push(`- (${formatAge(item.ageMs)}) ${text.length > 240 ? `…${text.slice(-240)}` : text}`)
|
||||
}
|
||||
sections.push('')
|
||||
}
|
||||
|
||||
if (writing.earlierText) sections.push('[앞 문맥]', writing.earlierText, '')
|
||||
if (writing.lastSentence) sections.push('[직전 문장]', writing.lastSentence, '')
|
||||
if (writing.currentSentence) sections.push('[지금 쓰는 문장 — 아직 끝나지 않음]', writing.currentSentence, '')
|
||||
|
||||
const suffix = input.suffix?.replace(/\s+/gu, ' ').trim()
|
||||
if (suffix) sections.push('[커서 뒤에 이미 있는 텍스트 — 이것과 겹치지 않게]', suffix.slice(0, 160), '')
|
||||
|
||||
if (input.followUpHints && input.followUpHints.length > 0) {
|
||||
sections.push('[사용자가 평소 직전 문장 같은 말 뒤에 이어 쓴 문장]')
|
||||
for (const hint of input.followUpHints.slice(0, 3)) sections.push(`- ${hint}`)
|
||||
sections.push('')
|
||||
}
|
||||
|
||||
if (input.continuationHints && input.continuationHints.length > 0) {
|
||||
sections.push('', '[과거에 사용자가 비슷한 문장 뒤에 실제로 이어 쓴 내용]')
|
||||
for (const hint of input.continuationHints.slice(0, 3)) {
|
||||
sections.push(`- ${hint}`)
|
||||
}
|
||||
sections.push('위 내용은 문체와 맥락 참고용입니다. 그대로 복사하지 말고 이어질 문장을 새로 쓰세요.')
|
||||
sections.push('[사용자가 같은 표현 뒤에 실제로 이어 쓴 내용]')
|
||||
for (const hint of input.continuationHints.slice(0, 3)) sections.push(`- ${hint}`)
|
||||
sections.push('')
|
||||
}
|
||||
|
||||
if (input.phraseHints && input.phraseHints.length > 0) {
|
||||
sections.push('[관련해서 사용자가 쓴 문장]')
|
||||
for (const hint of input.phraseHints.slice(0, 5)) sections.push(`- ${hint}`)
|
||||
sections.push('')
|
||||
}
|
||||
|
||||
if (input.avoidCandidates && input.avoidCandidates.length > 0) {
|
||||
sections.push('', '[이미 제안한 문장 — 아래와 겹치지 않는 다른 문장을 쓰세요]')
|
||||
for (const avoid of input.avoidCandidates.slice(0, 12)) {
|
||||
sections.push(`- ${avoid}`)
|
||||
}
|
||||
sections.push('[이미 제안한 문장 — 아래와 겹치지 않는 다른 문장을 쓰세요]')
|
||||
for (const avoid of input.avoidCandidates.slice(0, 12)) sections.push(`- ${avoid}`)
|
||||
sections.push('')
|
||||
}
|
||||
|
||||
sections.push('', `이어질 다음 문장 ${candidates}개를 한 줄씩 출력하세요.`)
|
||||
const directives: string[] = []
|
||||
directives.push(
|
||||
writing.mode === 'complete-sentence'
|
||||
? '[지금 쓰는 문장]의 나머지 부분만 쓰세요. 문장을 자연스럽게 끝맺으세요.'
|
||||
: '[직전 문장] 다음에 이어질 새 문장 하나를 쓰세요.'
|
||||
)
|
||||
if (looksLikeSearchInput(input, rawSource)) {
|
||||
directives.push('입력: 검색어입니다. 문장이 아니라 검색어 키워드 몇 개로만 짧게 이어 쓰세요.')
|
||||
}
|
||||
directives.push(`언어: ${LANGUAGE_LABEL[writing.language]}`)
|
||||
if (writing.language === 'ko' && writing.register) directives.push(`말투: ${REGISTER_LABEL[writing.register]}`)
|
||||
directives.push(prefill ? '당신의 차례에 적힌 사용자 글 바로 뒤부터 이어 쓰세요.' : `후보 ${candidates}개를 한 줄씩 출력하세요.`)
|
||||
sections.push('[이어 쓰기 지시]', ...directives)
|
||||
|
||||
const systemPrompt = `${SUGGESTION_NO_THINK_PREFIX}\n${SUGGESTION_SYSTEM_PROMPT.replace(
|
||||
'{{maxChars}}',
|
||||
String(maxChars)
|
||||
)}`
|
||||
|
||||
return { systemPrompt, text: sections.join('\n') }
|
||||
const template = prefill ? SUGGESTION_CONTINUE_SYSTEM_PROMPT : SUGGESTION_SYSTEM_PROMPT
|
||||
const body = template.replace('{{maxChars}}', String(maxChars))
|
||||
return {
|
||||
// 원형 템플릿(gemma4)은 생각 모드를 켜지 않으면 생각하지 않는다 — /no_think 는 지시형 경로에만.
|
||||
systemPrompt: prefill ? body : `${SUGGESTION_NO_THINK_PREFIX}\n${body}`,
|
||||
text: sections.join('\n'),
|
||||
assistantPrefix: prefill ? buildAssistantPrefix(writing, rawSource) : null,
|
||||
writing,
|
||||
wordFinished: /[ \t]$/u.test(rawSource),
|
||||
allowEmoji: containsEmoji(rawSource) || recent.some((item) => containsEmoji(item.text)),
|
||||
factSource: [
|
||||
rawSource,
|
||||
input.windowTitle ?? '',
|
||||
...recent.map((item) => item.text),
|
||||
...(input.followUpHints ?? []),
|
||||
...(input.continuationHints ?? []),
|
||||
...(input.phraseHints ?? [])
|
||||
].join('\n')
|
||||
}
|
||||
}
|
||||
|
||||
export { SUGGESTION_SYSTEM_PROMPT }
|
||||
export { SUGGESTION_SYSTEM_PROMPT, SUGGESTION_CONTINUE_SYSTEM_PROMPT }
|
||||
|
||||
/**
|
||||
* 입력 중 오타 검사 — 방금 친 문장에서 명백한 오타만 "틀린말 => 고친말" 줄로 받는다.
|
||||
*
|
||||
* 띄어쓰기·문체·단어 선택은 고치지 않는다. 호출자는 core `validateModelCorrections` 로
|
||||
* 결과를 다시 거른다(모델 출력은 신뢰하지 않는다).
|
||||
*/
|
||||
const TYPO_CHECK_SYSTEM_PROMPT = `사용자가 입력창에 방금 친 문장에서 오타만 찾습니다.
|
||||
|
||||
규칙:
|
||||
- 잘못 누른 글자, 빠지거나 겹친 글자, 자모가 뒤바뀐 글자, 틀린 맞춤법 철자처럼 명백한 오타만 고르세요.
|
||||
- 띄어쓰기, 문장부호, 말투, 단어 선택, 어순은 고치지 마세요.
|
||||
- 고유명사, 약어, 신조어, 외래어, 일부러 쓴 줄임말·구어체(ㅋㅋ, 넘, 젤 등)는 그대로 두세요.
|
||||
- 확실하지 않으면 고치지 마세요.
|
||||
- 오타마다 한 줄에 "틀린단어 => 고친단어" 형식으로 출력하세요. 단어는 문장에 나온 어절 그대로 쓰세요.
|
||||
- 오타가 없으면 "없음" 한 단어만 출력하세요. 다른 설명은 쓰지 마세요.`
|
||||
|
||||
export function buildTypoCheckPrompt(input: { sentence: string; previous?: string | null }): {
|
||||
systemPrompt: string
|
||||
text: string
|
||||
} {
|
||||
const sections: string[] = []
|
||||
const previous = input.previous?.replace(/\s+/gu, ' ').trim()
|
||||
if (previous) sections.push('[앞 문맥]', previous.slice(-200), '')
|
||||
sections.push('[검사할 문장]', input.sentence.replace(/\s+/gu, ' ').trim())
|
||||
return {
|
||||
systemPrompt: `${SUGGESTION_NO_THINK_PREFIX}\n${TYPO_CHECK_SYSTEM_PROMPT}`,
|
||||
text: sections.join('\n')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 실시간 자막 문맥 다듬기 — 확정된 자막 한 줄을 앞 문맥에 맞게 고친다.
|
||||
|
|
|
|||
|
|
@ -57,6 +57,11 @@ export class ModelWarmTracker {
|
|||
return model !== null && model === this._failedModel && now - this._failedAt < backoffMs
|
||||
}
|
||||
|
||||
/** warm 으로 믿는 마지막 시각 (ms) — 유지 연장 판단용. */
|
||||
get warmUntil(): number {
|
||||
return this._warmUntil
|
||||
}
|
||||
|
||||
/** 가장 최근 warm 으로 기록된 모델 (진단용). */
|
||||
get warmModel(): string | null {
|
||||
return this._warmModel
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@ export interface KeyboardPort {
|
|||
paste(): Promise<void>
|
||||
/** 글자 단위 타이핑 (클립보드 비파괴) */
|
||||
type(text: string): Promise<void>
|
||||
/** 커서 앞 글자를 count 번 지운다 (오타 교정) */
|
||||
backspace(count: number): Promise<void>
|
||||
/** 네이티브 키 모듈을 미리 불러 둔다 — 첫 삽입이 로딩을 기다리지 않게 (선택) */
|
||||
preload?(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -43,7 +47,7 @@ export interface NutKeyboardModule {
|
|||
hasKeyboard(): boolean
|
||||
getKeyboard(): NutNativeKeyboard
|
||||
}
|
||||
Key: Pick<typeof NutKey, 'LeftControl' | 'LeftSuper' | 'V'>
|
||||
Key: Pick<typeof NutKey, 'LeftControl' | 'LeftSuper' | 'V' | 'Backspace'>
|
||||
}
|
||||
|
||||
export type NutModuleLoader = () => Promise<NutKeyboardModule>
|
||||
|
|
@ -94,6 +98,27 @@ export class NutKeyboardPort implements KeyboardPort {
|
|||
await nut.native.type(text)
|
||||
}
|
||||
|
||||
/** 백스페이스를 count 번 — 키마다 네이티브 keyTap 한 번이다. */
|
||||
async backspace(count: number): Promise<void> {
|
||||
if (count <= 0) return
|
||||
const nut = await this._ensureNut()
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
await nut.native.click(nut.Key.Backspace)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* nut-js 를 미리 불러 둔다. 첫 로딩이 수 초 걸려(실측 2026-10-03: 재시작 뒤 첫 제안 수락이 4.9초,
|
||||
* 그중 nut-js 로딩 4.8초) 사용자가 수락하고 한참 기다렸다. 실패는 여기서 삼키고 실제 삽입 때 다시 알린다.
|
||||
*/
|
||||
async preload(): Promise<void> {
|
||||
try {
|
||||
await this._ensureNut()
|
||||
} catch {
|
||||
// _ensureNut 이 이미 로그를 남겼다.
|
||||
}
|
||||
}
|
||||
|
||||
private async _ensureNut(): Promise<LoadedNut> {
|
||||
if (this._nut) return this._nut
|
||||
|
||||
|
|
|
|||
|
|
@ -982,6 +982,7 @@ const electronAPI = {
|
|||
learnTypedText?: boolean
|
||||
excludedApps?: string[]
|
||||
requestTimeoutMs?: number
|
||||
typoAutoCorrect?: boolean
|
||||
}) =>
|
||||
invoke<import('@d3ro/core/input-intelligence').SuggestionState>(
|
||||
IPC_CHANNELS.SUGGESTION.SET_CONFIG,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
// 상세 통계(요약/키보드/마우스/앱/문구)는 지식 베이스 화면의 "입력 인사이트" 탭에 있다.
|
||||
// 이 패널은 "무엇을 수집하고, 언제 멈추고, 어떻게 지우는가" 만 다룬다.
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
|
|
@ -52,12 +52,54 @@ export function InputConsentPanel(): React.ReactElement {
|
|||
|
||||
// 설정 파일에 굳은 실제 값을 그대로 보여준다 (하드코딩 기본값을 표시하면
|
||||
// 사용자가 보는 값과 동작이 어긋난다 — 실측: 트리거가 3008ms 로 저장돼 있었다).
|
||||
// 제안 상태는 입력 스냅샷마다(초당 여러 번) 새로 온다 — 매번 칸을 덮어쓰면 사용자가 지우고 새로
|
||||
// 치는 도중에 값이 계속 되돌아갔다(실측: 600 이 다시 채워짐). 저장된 값이 실제로 바뀐 칸만 맞춘다.
|
||||
const syncedRef = useRef<{ triggerDelayMs?: number; minPrefixChars?: number; requestTimeoutMs?: number }>({})
|
||||
const triggerDelaySaved = suggestion?.triggerDelayMs
|
||||
const minPrefixSaved = suggestion?.minPrefixChars
|
||||
const requestTimeoutSaved = suggestion?.requestTimeoutMs
|
||||
useEffect(() => {
|
||||
if (!suggestion) return
|
||||
setTriggerDelayMs(String(suggestion.triggerDelayMs))
|
||||
setMinPrefixChars(String(suggestion.minPrefixChars))
|
||||
setRequestTimeoutMs(String(suggestion.requestTimeoutMs))
|
||||
}, [suggestion])
|
||||
const synced = syncedRef.current
|
||||
if (triggerDelaySaved !== undefined && synced.triggerDelayMs !== triggerDelaySaved) {
|
||||
synced.triggerDelayMs = triggerDelaySaved
|
||||
setTriggerDelayMs(String(triggerDelaySaved))
|
||||
}
|
||||
if (minPrefixSaved !== undefined && synced.minPrefixChars !== minPrefixSaved) {
|
||||
synced.minPrefixChars = minPrefixSaved
|
||||
setMinPrefixChars(String(minPrefixSaved))
|
||||
}
|
||||
if (requestTimeoutSaved !== undefined && synced.requestTimeoutMs !== requestTimeoutSaved) {
|
||||
synced.requestTimeoutMs = requestTimeoutSaved
|
||||
setRequestTimeoutMs(String(requestTimeoutSaved))
|
||||
}
|
||||
}, [triggerDelaySaved, minPrefixSaved, requestTimeoutSaved])
|
||||
|
||||
/**
|
||||
* 숫자 칸 저장 — 비었거나 숫자가 아니면 저장하지 않고 저장된 값으로 되돌린다. 서버가 범위를 맞춰
|
||||
* 다른 값을 저장했으면(예: 최소 500ms) 칸도 그 값으로 맞춘다.
|
||||
*/
|
||||
const commitNumber = useCallback(
|
||||
async (
|
||||
raw: string,
|
||||
key: 'triggerDelayMs' | 'minPrefixChars' | 'requestTimeoutMs',
|
||||
reset: (value: string) => void
|
||||
): Promise<void> => {
|
||||
const value = Number(raw)
|
||||
const saved = syncedRef.current[key]
|
||||
if (raw.trim() === '' || !Number.isFinite(value)) {
|
||||
if (saved !== undefined) reset(String(saved))
|
||||
return
|
||||
}
|
||||
const result = await window.electronAPI.suggestion.setConfig({ [key]: Math.round(value) })
|
||||
if (result.success) {
|
||||
const stored = result.data[key]
|
||||
syncedRef.current[key] = stored
|
||||
reset(String(stored))
|
||||
}
|
||||
await refresh()
|
||||
},
|
||||
[refresh]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
|
@ -114,6 +156,14 @@ export function InputConsentPanel(): React.ReactElement {
|
|||
[refresh]
|
||||
)
|
||||
|
||||
const handleTypoAutoCorrect = useCallback(
|
||||
async (next: boolean): Promise<void> => {
|
||||
await window.electronAPI.suggestion.setConfig({ typoAutoCorrect: next })
|
||||
await refresh()
|
||||
},
|
||||
[refresh]
|
||||
)
|
||||
|
||||
const handleModel = useCallback(
|
||||
async (modelId: string): Promise<void> => {
|
||||
await window.electronAPI.suggestion.setConfig({ modelId: modelId || null })
|
||||
|
|
@ -423,11 +473,7 @@ export function InputConsentPanel(): React.ReactElement {
|
|||
label={t('input.suggestion.delay')}
|
||||
value={triggerDelayMs}
|
||||
onChange={(e) => setTriggerDelayMs(e.target.value)}
|
||||
onBlur={() =>
|
||||
void window.electronAPI.suggestion
|
||||
.setConfig({ triggerDelayMs: Number(triggerDelayMs) })
|
||||
.then(() => refresh())
|
||||
}
|
||||
onBlur={() => void commitNumber(triggerDelayMs, 'triggerDelayMs', setTriggerDelayMs)}
|
||||
sx={{ width: 150 }}
|
||||
/>
|
||||
<TextField
|
||||
|
|
@ -437,11 +483,7 @@ export function InputConsentPanel(): React.ReactElement {
|
|||
label={t('input.suggestion.minPrefix')}
|
||||
value={minPrefixChars}
|
||||
onChange={(e) => setMinPrefixChars(e.target.value)}
|
||||
onBlur={() =>
|
||||
void window.electronAPI.suggestion
|
||||
.setConfig({ minPrefixChars: Number(minPrefixChars) })
|
||||
.then(() => refresh())
|
||||
}
|
||||
onBlur={() => void commitNumber(minPrefixChars, 'minPrefixChars', setMinPrefixChars)}
|
||||
sx={{ width: 150 }}
|
||||
/>
|
||||
<TextField
|
||||
|
|
@ -451,11 +493,7 @@ export function InputConsentPanel(): React.ReactElement {
|
|||
label={t('input.suggestion.timeout')}
|
||||
value={requestTimeoutMs}
|
||||
onChange={(e) => setRequestTimeoutMs(e.target.value)}
|
||||
onBlur={() =>
|
||||
void window.electronAPI.suggestion
|
||||
.setConfig({ requestTimeoutMs: Number(requestTimeoutMs) })
|
||||
.then(() => refresh())
|
||||
}
|
||||
onBlur={() => void commitNumber(requestTimeoutMs, 'requestTimeoutMs', setRequestTimeoutMs)}
|
||||
sx={{ width: 150 }}
|
||||
/>
|
||||
<Select
|
||||
|
|
@ -491,6 +529,24 @@ export function InputConsentPanel(): React.ReactElement {
|
|||
}
|
||||
/>
|
||||
|
||||
{/* 오타 교정은 입력 맥락(수집 동의)만 있으면 제안과 따로 동작한다. */}
|
||||
<FormControlLabel
|
||||
disabled={!enabled}
|
||||
control={
|
||||
<Switch
|
||||
size="small"
|
||||
checked={suggestion?.typoAutoCorrect ?? true}
|
||||
onChange={(e) => void handleTypoAutoCorrect(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={
|
||||
<Typography sx={{ ...typoSx('label'), color: d3roPalette.text.secondary }}>
|
||||
{t('input.suggestion.typoAutoCorrect')}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
<Typography sx={{ ...HINT_SX, pl: 6 }}>{t('input.suggestion.typoAutoCorrectHint')}</Typography>
|
||||
|
||||
{/* 상태 표시 — 스위치로 두면 설정처럼 보여서 "왜 못 켜지?" 가 된다. */}
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<Typography sx={{ ...typoSx('label'), color: d3roPalette.text.tertiary }}>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue