The session ignores trailing whitespace but acceptance compared the raw prefix, so typing one more space after the fix appeared made accept drop the correction silently and leave the typo in place.
2099 lines
90 KiB
TypeScript
2099 lines
90 KiB
TypeScript
// src/main/services/SuggestionService.ts
|
||
//
|
||
// 다음 문장 제안(ghost text) — 입력 맥락을 받아 gemma(Ollama)로 후보를 만들고,
|
||
// 수락 시 대상 앱에 삽입한다.
|
||
//
|
||
// 설계 근거 (2025~2026 인라인 컴플리션 실측):
|
||
// - 디바운스는 타이핑 정지 후 600ms(기본)로, 모델 호출 빈도를 보수적으로 제한한다.
|
||
// - 출력 토큰은 극단적으로 작게(기본 64, Tabby 64 / KeyType 4~16) —
|
||
// 인라인 제안은 스트리밍으로 빨리 보여주고 짧게 끊는 것이 정석이다.
|
||
// - 문맥이 stale 이 된 진행 중 생성만 호출자 시그널로 취소하고, 다음 입력 문맥에서 재평가한다.
|
||
// - 후보가 나온 접두와 현재 접두가 달라지면 그 즉시 오버레이를 지운다 (stale).
|
||
|
||
import { EventEmitter } from 'events'
|
||
import {
|
||
COMPOSING_IDLE_MULTIPLIER,
|
||
SUGGESTION_DEFAULTS,
|
||
SUGGESTION_MAX_OUTPUT_CHARS,
|
||
buildLocalSuggestionCandidateEntries,
|
||
decideInFlightGeneration,
|
||
decideSuggestion,
|
||
decideSuggestionStep,
|
||
isAppExcluded,
|
||
joinSuggestion,
|
||
matchesSessionPrefix,
|
||
normalizeRequestPrefix,
|
||
normalizeSessionPrefix,
|
||
parseSuggestionCandidates,
|
||
sanitizeSuggestionLine,
|
||
selectPhraseHints,
|
||
shouldPersistSuggestionPrefix,
|
||
isTerminalApp,
|
||
extractContinuation,
|
||
extractTerminalPromptPrefix,
|
||
type AnchorKind,
|
||
type PhysicalRect,
|
||
type SuggestionCandidate,
|
||
type SuggestionCorrection,
|
||
type SuggestionPolicyInput,
|
||
type SuggestionProvenance,
|
||
type SuggestionSkipReason,
|
||
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 { alignCorrectionToPrefix } from '@d3ro/core/typo-correction'
|
||
import { configGet, configSet } from './ConfigService'
|
||
import { getLogger } from './LoggerService'
|
||
import { getLocalLLMService } from './LocalLLMService'
|
||
import { buildSuggestionPrompt } from './llm-prompts'
|
||
import { getInputTelemetryService, type TypingContext } from './InputTelemetryService'
|
||
import { getPersonalGraphService } from './PersonalGraphService'
|
||
import { getTextInsertService } from './TextInsertService'
|
||
import { waitForModifiersReleased } from './modifier-state'
|
||
import {
|
||
createSqliteSuggestionRepository,
|
||
type SuggestionHistoryEntry,
|
||
type SuggestionRecordInput,
|
||
type SuggestionRepository
|
||
} from './SuggestionRepository'
|
||
import { SuggestionBudget } from './suggestion/SuggestionBudget'
|
||
import { ModelWarmTracker } from './suggestion/ModelWarmTracker'
|
||
import { LOCAL_LLM_KEEP_ALIVE, LOCAL_LLM_KEEP_ALIVE_MS } from './llm/model-residency'
|
||
import { getForegroundWindowInfo } from '../utils/win32-foreground'
|
||
|
||
const logger = getLogger('SuggestionService')
|
||
|
||
export type { SuggestionHistoryEntry }
|
||
|
||
/** 지금 포그라운드 창을 알려 주는 포트 — 수락 직전 대상 창 확인에 쓴다. */
|
||
export interface SuggestionForegroundProbe {
|
||
currentWindowHandle(): number | null
|
||
}
|
||
|
||
/** 수락한 텍스트를 학습 쪽에 알리는 포트. */
|
||
export interface SuggestionLearningPort {
|
||
/** 곧 프로그램이 삽입할 텍스트 — 다음 스냅샷 diff 가 "타이핑" 으로 다시 학습하지 않게 한다. 취소 함수를 돌려준다. */
|
||
expectProgrammaticInsert(text: string): () => void
|
||
/** 수락한 문장을 사용자 문체 표본으로 기록한다 (학습 동의 시에만 저장됨). */
|
||
recordAccepted(text: string, meta: { appName: string | null; windowTitle: string | null }): void
|
||
/** 곧 보낼 프로그램 키 수(교정 수락의 백스페이스 등) — 입력 통계에서 뺀다. */
|
||
expectProgrammaticKeys?(count: number): void
|
||
}
|
||
|
||
/**
|
||
* 제안과 함께 내놓을 오타 교정을 만드는 포트 (TypoCorrectionService.propose — bootstrap 이 연결한다).
|
||
* 커서 앞 원문 끝의 originalText 를 insertText 로 바꾸는 계획을 돌려준다.
|
||
*/
|
||
export interface SuggestionTypoProposer {
|
||
propose(
|
||
context: TypingContext,
|
||
signal: AbortSignal,
|
||
options?: { thorough?: boolean }
|
||
): Promise<{ originalText: string; insertText: string; corrections: Array<{ start: number; end: number; to: string }> } | null>
|
||
}
|
||
|
||
/** 교정을 적용한 문맥 — 모델에는 고친 글을 보여 주고, 세션 비교는 원문으로 한다. */
|
||
function applyCorrectionToContext(context: TypingContext, correction: SuggestionCorrection): TypingContext {
|
||
const replaceTail = (text: string): string =>
|
||
text.endsWith(correction.from) ? text.slice(0, text.length - correction.from.length) + correction.to : text
|
||
return {
|
||
...context,
|
||
prefix: replaceTail(context.prefix),
|
||
documentBefore: context.documentBefore == null ? context.documentBefore : replaceTail(context.documentBefore)
|
||
}
|
||
}
|
||
|
||
/** 서비스 협력자 — 기본값은 getSuggestionService() 가 연결한다 (DIP). */
|
||
export interface SuggestionServiceDeps {
|
||
repository: SuggestionRepository
|
||
budget: SuggestionBudget
|
||
warmth: ModelWarmTracker
|
||
foreground: SuggestionForegroundProbe
|
||
learning: SuggestionLearningPort
|
||
}
|
||
|
||
export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps {
|
||
return {
|
||
repository: createSqliteSuggestionRepository(),
|
||
budget: new SuggestionBudget(),
|
||
// 상주 추정은 로컬 LLM 의 모든 요청(받아쓰기·음성 대화 포함)을 본다.
|
||
warmth: new ModelWarmTracker({ residentUntil: (model) => getLocalLLMService().residency?.residentUntil(model) ?? null }),
|
||
foreground: {
|
||
currentWindowHandle: () => getForegroundWindowInfo()?.hwnd ?? null
|
||
},
|
||
learning: {
|
||
expectProgrammaticInsert: (text) => getInputTelemetryService().expectProgrammaticInsert(text),
|
||
expectProgrammaticKeys: (count) => getInputTelemetryService().expectProgrammaticKeys(count),
|
||
recordAccepted: (text, meta) =>
|
||
getInputTelemetryService().recordExternalText(text, { ...meta, source: 'suggestion' })
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 설정에서 읽은 정책 값 (SSOT 기본값과 상한 적용 후). */
|
||
interface PolicyConfig {
|
||
triggerDelayMs: number
|
||
minPrefixChars: number
|
||
maxRequestsPerMinute: number
|
||
dailyBudget: number
|
||
maxCandidates: number
|
||
maxChars: number
|
||
excludedApps: string[]
|
||
}
|
||
|
||
export interface SuggestionRequestResult {
|
||
ok: boolean
|
||
reason?: SuggestionSkipReason
|
||
}
|
||
|
||
interface SuggestionEvents {
|
||
updated: (state: SuggestionState) => void
|
||
cleared: (payload: { reason: SuggestionSkipReason }) => void
|
||
'state-changed': (state: SuggestionState) => void
|
||
}
|
||
|
||
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
|
||
/**
|
||
* 빈 출력일 때 다시 보낼 변형 — prefill 끝에 공백을 붙여 "다음 단어부터" 쓰게 한다.
|
||
*
|
||
* 실측(2026-10-17, gemma4:e4b): "…잠시 쉬면", "…창이 나왔다가" 처럼 공백 없이 문장 중간에서 끝난
|
||
* prefill 은 모델이 곧바로 턴을 닫아 빈 출력이 됐다(첫 후보 18회 중 15회). 끝에 공백 하나를 붙이면
|
||
* 4문장 모두 이어 썼다. 출력 앞에 공백을 되돌려 붙여 해석하므로 이음새는 '띄어 쓰기' 가 된다.
|
||
*/
|
||
spaced?: ModelRequest
|
||
}
|
||
|
||
/**
|
||
* 모델을 메모리에 유지하는 시간 — 앱 공통 값(LOCAL_LLM_KEEP_ALIVE)을 그대로 쓴다.
|
||
*
|
||
* 예전엔 콜드 리로드(11.4s) 회피용으로 30m 을 따로 썼지만, 다른 기능의 짧은 keep_alive 와
|
||
* 서로 덮어써 리로드를 오히려 부추겼고 유휴 중 RAM 11GB 를 붙잡았다. 쓰는 동안은 아래 연장으로
|
||
* 식지 않게 하고, 콜드 첫 요청은 _keepWarm 의 첫 키 입력 워밍업이 흡수한다.
|
||
*/
|
||
const SUGGESTION_KEEP_ALIVE = LOCAL_LLM_KEEP_ALIVE
|
||
const SUGGESTION_KEEP_ALIVE_MS = LOCAL_LLM_KEEP_ALIVE_MS
|
||
/**
|
||
* 타이핑 중인데 남은 유지 시간이 이보다 짧으면 1토큰 요청으로 유지 시간을 연장한다.
|
||
*
|
||
* 실측(2026-10-03): 50분 자리를 비운 뒤 돌아오자 콜드 로드에 29초가 걸려 그동안 "준비 중" 만
|
||
* 보였다(GPU 메모리 10.6/12GB — 음성 인식 모델과 함께 올라가 있어 로드가 느리다). 쓰는 동안에는
|
||
* 절대 식지 않게, 자리를 비우면 keep-alive 뒤에 내려가게 한다. keep-alive(10m)보다 충분히 작아야
|
||
* 타이핑 중 매분 연장 요청을 쏘지 않는다.
|
||
*/
|
||
const KEEP_WARM_REFRESH_MS = 4 * 60_000
|
||
/** 유지 연장 요청 최소 간격 */
|
||
const KEEP_WARM_MIN_INTERVAL_MS = 60_000
|
||
/** keep-alive 만료 직전 여유 — 경계에서 콜드 모델로 요청하지 않는다. */
|
||
const SUGGESTION_KEEP_ALIVE_MARGIN_MS = 30_000
|
||
/** 워밍업 실패 뒤 같은 모델 재시도를 미루는 시간 — 멈출 때마다 실패 요청을 쏘지 않는다. */
|
||
const WARM_UP_FAILURE_BACKOFF_MS = SUGGESTION_DEFAULTS.minIntervalMs
|
||
|
||
export class SuggestionService extends EventEmitter {
|
||
private _candidates: SuggestionCandidate[] = []
|
||
private _activeIndex = 0
|
||
/** 물리 픽셀 그대로 보관한다 — DIP 변환은 창 배치(WindowManager) 한 곳에서만 한다. */
|
||
private _anchor: PhysicalRect | null = null
|
||
/** anchor 가 케어렛인지 요소 전체인지 — 오버레이가 배치 전략을 고르는 근거 */
|
||
private _anchorKind: AnchorKind = null
|
||
private _appName: string | null = null
|
||
private _windowTitle: string | null = null
|
||
/** 후보를 만든 시점의 접두 — 접두가 달라지면 stale */
|
||
private _generatedForPrefix = ''
|
||
/** 이 세션이 채우려는 후보 총량 (모델 세션 12 / 로컬 기억 세션은 현재 개수) */
|
||
private _targetTotal = 0
|
||
private _lastSkipReason: SuggestionSkipReason | null = null
|
||
private _lastDecisionSignature = ''
|
||
/** 생성 중 — 후보 도착 전에도 오버레이를 띄운다 */
|
||
private _generating = false
|
||
/** 모델 적재 중 — UI 가 "준비 중" 을 표시한다 */
|
||
private _warmingUp = false
|
||
/**
|
||
* 생성 세대 토큰.
|
||
*
|
||
* 사용자가 제안을 닫거나 새로 시작하면 증가한다. 진행 중이던 요청이 나중에
|
||
* 끝나도 토큰이 달라졌으면 결과를 버린다 — "X 로 닫았는데 잠시 뒤 다시 뜨던"
|
||
* 문제를 막는다.
|
||
*/
|
||
private _generationToken = 0
|
||
/** 마지막 문맥 수신 시각 — 늦게 도착한 결과를 판단한다 */
|
||
private _lastContextAt = 0
|
||
/** 표시 수명 타이머 (TTL) */
|
||
private _ttlTimer: NodeJS.Timeout | null = null
|
||
/** 마지막으로 실제 요청한 접두 (같은 텍스트 반복 요청 방지) */
|
||
private _lastRequestedPrefix = ''
|
||
/** 사용자가 X 로 닫은 뒤 재표시를 막는 시각 (ms) */
|
||
private _userDismissedUntil = 0
|
||
/** 스트리밍 누적 텍스트 */
|
||
private _partialText = ''
|
||
/** 마지막 스트리밍 방출 시각 (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
|
||
/** 이 세션의 이력 행 id — 한 세션은 한 행이다(채우기 후보·수락은 이 행을 갱신한다). */
|
||
private _sessionRecordId: string | null = null
|
||
/** 이 세션 후보가 함께 적용하는 오타 교정 */
|
||
private _correction: SuggestionCorrection | null = null
|
||
/** 모델에 보여 준 (교정 적용) 문맥 — 채우기 루프가 같은 문맥으로 더 만든다 */
|
||
private _promptContext: TypingContext | null = null
|
||
private _typoProposer: SuggestionTypoProposer | null = null
|
||
/** 이 세션 첫 후보가 "공백 붙인 prefill" 로 나왔다 — 채우기도 그 변형으로 보낸다 */
|
||
private _spacedPreferred = false
|
||
/**
|
||
* 첫 후보를 못 만든 접두 — 같은 글로 멈춰 있는 동안 다시 생성하지 않는다. 실패할 때마다 다음 스냅샷이
|
||
* 같은 글로 또 생성해 "생성 중" 창이 1초마다 떴다 꺼졌다(실측 2026-10-17).
|
||
*/
|
||
private _failedPrefix = ''
|
||
/**
|
||
* 손을 멈추자마자 먼저 띄운 "생성 중" 자리 — 생성은 아직 시작 전이다. 정책의 "표시 중"(already-visible)
|
||
* 에는 넣지 않는다: 넣으면 정작 생성 시점에 이미 떠 있다고 보고 생성하지 않는다.
|
||
*/
|
||
private _pending = false
|
||
private _pendingTimer: NodeJS.Timeout | null = null
|
||
|
||
/** 요청 예산 (간격 · 분/일 카운트 · 실패 쿨다운) */
|
||
private readonly _budget: SuggestionBudget
|
||
/** 모델별 온기 (keep-alive) · 워밍업 실패 기록 */
|
||
private readonly _warmth: ModelWarmTracker
|
||
private readonly _repository: SuggestionRepository
|
||
private readonly _foreground: SuggestionForegroundProbe
|
||
private readonly _learning: SuggestionLearningPort
|
||
|
||
private _inFlight = false
|
||
private _abort: AbortController | null = null
|
||
/** 채우기 루프(2번째 이후 후보) 진행 중 — _inFlight 와 별개다 (예산/타임아웃 카운트 제외). */
|
||
private _filling = false
|
||
private _fillAbort: AbortController | null = null
|
||
private _timeoutTimer: NodeJS.Timeout | null = null
|
||
private _lastLatencyMs: number | null = null
|
||
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()
|
||
this._budget = deps.budget
|
||
this._warmth = deps.warmth
|
||
this._repository = deps.repository
|
||
this._foreground = deps.foreground
|
||
this._learning = deps.learning
|
||
}
|
||
|
||
// ── 진단 접근자 (기존 진단·테스트가 읽는 예산 필드 이름을 유지한다) ──
|
||
// 예산 상태의 정본은 SuggestionBudget 이다. 새 코드는 _budget 을 직접 쓴다.
|
||
|
||
/** @internal */
|
||
get _lastRequestAt(): number {
|
||
return this._budget.lastRequestAt
|
||
}
|
||
|
||
/** @internal 진행 플래그 누수(watchdog) 재현용 */
|
||
set _lastRequestAt(at: number) {
|
||
this._budget.overrideLastRequestAt(at)
|
||
}
|
||
|
||
/** @internal */
|
||
get _prevRequestAt(): number {
|
||
return this._budget.prevRequestAt
|
||
}
|
||
|
||
/** @internal */
|
||
get _minuteCount(): number {
|
||
return this._budget.minuteCount
|
||
}
|
||
|
||
/** @internal */
|
||
get _dayCount(): number {
|
||
return this._budget.dayCount
|
||
}
|
||
|
||
/** @internal */
|
||
get _consecutiveFailures(): number {
|
||
return this._budget.consecutiveFailures
|
||
}
|
||
|
||
/** @internal */
|
||
get _cooldownUntil(): number {
|
||
return this._budget.cooldownUntil
|
||
}
|
||
|
||
override on<K extends keyof SuggestionEvents>(event: K, listener: SuggestionEvents[K]): this {
|
||
return super.on(event, listener as (...args: unknown[]) => void)
|
||
}
|
||
|
||
override off<K extends keyof SuggestionEvents>(event: K, listener: SuggestionEvents[K]): this {
|
||
return super.off(event, listener as (...args: unknown[]) => void)
|
||
}
|
||
|
||
override emit<K extends keyof SuggestionEvents>(
|
||
event: K,
|
||
...args: Parameters<SuggestionEvents[K]>
|
||
): boolean {
|
||
return super.emit(event, ...args)
|
||
}
|
||
|
||
// ── 상태 ──────────────────────────────────────────────
|
||
|
||
isEnabled(): boolean {
|
||
return configGet('suggestionEnabled') === true
|
||
}
|
||
|
||
get isVisible(): boolean {
|
||
return this._candidates.length > 0
|
||
}
|
||
|
||
get isPresentationActive(): boolean {
|
||
return this.isVisible || this._generating || this._warmingUp || this._partialText.length > 0
|
||
}
|
||
|
||
get activeText(): string | null {
|
||
return this._candidates[this._activeIndex]?.text ?? null
|
||
}
|
||
|
||
getState(): SuggestionState {
|
||
const now = Date.now()
|
||
return {
|
||
enabled: this.isEnabled(),
|
||
modelId: this.resolveModel(),
|
||
modelAvailable: getLocalLLMService().isAvailable(),
|
||
visible: this.isVisible,
|
||
generating: this._generating || this._pending,
|
||
warmingUp: this._warmingUp,
|
||
partialText: this._partialText || null,
|
||
candidates: [...this._candidates],
|
||
activeIndex: this._activeIndex,
|
||
targetTotal: this._targetTotal,
|
||
anchor: this._anchor,
|
||
anchorKind: this._anchorKind,
|
||
appName: this._appName,
|
||
updatedAt: now,
|
||
lastSkipReason: this._lastSkipReason,
|
||
requestsToday: this._budget.requestsToday(now),
|
||
coolingDown: this._budget.isCoolingDown(now),
|
||
dailyBudget: configGet('suggestionDailyBudget') ?? SUGGESTION_DEFAULTS.dailyBudget,
|
||
lastLatencyMs: this._lastLatencyMs,
|
||
triggerDelayMs: this.readPolicyConfig().triggerDelayMs,
|
||
minPrefixChars: this.readPolicyConfig().minPrefixChars,
|
||
requestTimeoutMs: this.readTimeoutMs(),
|
||
learnTypedText: configGet('inputLearnTypedText') === true,
|
||
telemetryEnabled: configGet('inputTelemetryEnabled') === true,
|
||
overlayInteractive: configGet('suggestionOverlayInteractive') !== false,
|
||
typoAutoCorrect: configGet('typoAutoCorrectEnabled') !== false,
|
||
provenance: this._provenance,
|
||
correction: this._correction
|
||
}
|
||
}
|
||
|
||
/** 제안 창에 오타 교정을 함께 내놓을 포트를 연결한다 (bootstrap). null 이면 교정 없이 제안만 한다. */
|
||
setTypoProposer(proposer: SuggestionTypoProposer | null): void {
|
||
this._typoProposer = proposer
|
||
}
|
||
|
||
/** 제안 전용 모델 (설정 없으면 기본 LLM 모델). */
|
||
resolveModel(): string | null {
|
||
const dedicated = configGet('suggestionModelId')
|
||
if (dedicated) return dedicated
|
||
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()) {
|
||
this.dismiss('disabled')
|
||
}
|
||
this.emit('state-changed', this.getState())
|
||
}
|
||
|
||
/**
|
||
* 제안에 쓸 모델이 바뀌었다 (전용 모델 설정 또는 기본 LLM 모델 변경).
|
||
*
|
||
* 새 모델은 콜드일 수 있다 — 첫 멈춤에서 콜드 로드가 타임아웃되기 전에 미리 올린다.
|
||
* 온기는 모델별로 추적하므로 이 호출이 없어도 첫 요청은 워밍업 경로로 간다.
|
||
*/
|
||
handleModelChanged(): void {
|
||
if (!this.isEnabled()) return
|
||
const model = this.resolveModel()
|
||
if (!model || this._warmth.isWarm(model, Date.now())) return
|
||
logger.info(`제안 모델 변경 감지 (model=${model}) — 미리 워밍업한다`)
|
||
void this.warmUp()
|
||
}
|
||
|
||
setEnabled(enabled: boolean): void {
|
||
configSet('suggestionEnabled', enabled)
|
||
if (!enabled) this.dismiss('disabled')
|
||
// 입력 맥락(수집 동의)이 없으면 제안이 뜰 수 없다 — 모델만 데우지 않는다.
|
||
else if (hasInputContextConsent()) void this.warmUp()
|
||
this.emit('state-changed', this.getState())
|
||
}
|
||
|
||
/**
|
||
* 입력 수집 동의·일시정지가 바뀌었다. 입력 맥락이 끊기면 떠 있는 세션·채우기 루프를 닫고
|
||
* 붙잡고 있던 마지막 문맥을 버린다(동의를 철회한 뒤 수동 요청이 옛 접두로 생성하지 않게).
|
||
* 다시 켜지면 제안이 켜져 있을 때만 모델을 데운다.
|
||
*/
|
||
handleInputConsentChanged(): void {
|
||
if (!hasInputContextConsent()) {
|
||
this.dismiss('disabled')
|
||
this._lastContext = null
|
||
this._lastRequestedPrefix = ''
|
||
} else if (this.isEnabled()) {
|
||
void this.warmUp()
|
||
}
|
||
this.emit('state-changed', this.getState())
|
||
}
|
||
|
||
/** 설정에서 명시적으로 제안을 켤 때만 모델을 짧게 준비한다. */
|
||
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
|
||
// 조용한 워밍업(타이핑 중 미리 올리기)은 "준비 중" 표시를 켜지 않는다 — 표시는 정책 게이트가
|
||
// 열려 실제로 제안을 기다릴 때(_showWarming)만 한다.
|
||
if (!options.silent) this._warmingUp = true
|
||
this.emit('state-changed', this.getState())
|
||
const warmUp = this._warmUpUntilReady(abort)
|
||
this._warmUpPromise = warmUp
|
||
void warmUp.finally(() => {
|
||
if (this._warmUpPromise === warmUp) this._warmUpPromise = null
|
||
if (this._warmUpAbort === abort) this._warmUpAbort = null
|
||
})
|
||
return warmUp
|
||
}
|
||
|
||
private async _warmUpUntilReady(abort: AbortController): Promise<void> {
|
||
try {
|
||
for (let attempt = 0; attempt <= 15; attempt += 1) {
|
||
if (abort.signal.aborted || !this.isEnabled()) return
|
||
if (!getLocalLLMService().isAvailable()) {
|
||
if (attempt === 15) return
|
||
await this._waitForWarmUpRetry(abort.signal)
|
||
continue
|
||
}
|
||
|
||
const model = this.resolveModel()
|
||
if (!model) return
|
||
|
||
try {
|
||
const stream = getLocalLLMService().streamGenerate('hi', {
|
||
model,
|
||
maxTokens: 1,
|
||
temperature: 0,
|
||
signal: abort.signal,
|
||
keepAlive: SUGGESTION_KEEP_ALIVE
|
||
})
|
||
for await (const chunk of stream) void chunk
|
||
if (abort.signal.aborted) return
|
||
this._noteModelWarm(model)
|
||
logger.info(`제안 모델 워밍업 완료 (model=${model})`)
|
||
} catch (error) {
|
||
if (!abort.signal.aborted) {
|
||
const message = error instanceof Error ? error.message : String(error)
|
||
logger.warn(`제안 모델 워밍업 실패: ${message}`)
|
||
// 실패한 워밍업도 실패다 — 기록하지 않으면 멈출 때마다 새 워밍업을 쏘며
|
||
// "준비 중" 만 깜빡이고, 쿨다운·예산이 전혀 걸리지 않는다.
|
||
this._warmth.noteWarmUpFailure(model, Date.now())
|
||
this._lastSkipReason = 'generation-failed'
|
||
this._noteFailure(`warm-up: ${message}`)
|
||
}
|
||
}
|
||
return
|
||
}
|
||
} finally {
|
||
this._warmingUp = false
|
||
// 'state-changed' 뿐 아니라 'updated' 도 보내야 한다 — 오버레이는 'updated' 를
|
||
// 듣고 표시 여부를 판단하는데, 이게 빠지면 타이핑이 멈춘 사이 워밍업이 끝나도
|
||
// "준비 중" 오버레이가 20초 TTL 까지 그대로 남는다.
|
||
this.emit('updated', this.getState())
|
||
this.emit('state-changed', this.getState())
|
||
}
|
||
}
|
||
|
||
private _waitForWarmUpRetry(signal: AbortSignal): Promise<void> {
|
||
return new Promise((resolve) => {
|
||
const finish = (): void => {
|
||
signal.removeEventListener('abort', finish)
|
||
if (this._warmUpRetryTimer) {
|
||
clearTimeout(this._warmUpRetryTimer)
|
||
this._warmUpRetryTimer = null
|
||
}
|
||
resolve()
|
||
}
|
||
this._warmUpRetryTimer = setTimeout(finish, 2000)
|
||
this._warmUpRetryTimer.unref?.()
|
||
signal.addEventListener('abort', finish, { once: true })
|
||
})
|
||
}
|
||
|
||
private _cancelWarmUp(): void {
|
||
if (this._warmUpRetryTimer) {
|
||
clearTimeout(this._warmUpRetryTimer)
|
||
this._warmUpRetryTimer = null
|
||
}
|
||
this._warmUpAbort?.abort()
|
||
this._warmingUp = false
|
||
}
|
||
|
||
// ── 입력 텍스트 처리 ────────────────────────────────
|
||
|
||
/**
|
||
* 입력 텔레메트리가 보내는 "지금 치고 있는 것" 이벤트.
|
||
*
|
||
* 판단은 core `decideSuggestionStep` 이 한다(세션 유효성 → 쿨다운 → 사용자 닫기 →
|
||
* 정책 → 모델 온기). 서비스는 그 결과만 실행한다.
|
||
*/
|
||
handleTypingContext(input: TypingContext): void {
|
||
// 터미널은 화면 전체가 읽힌다 — 입력 줄만 접두로 쓴다. 입력 줄이 없으면 빈 접두(제안 안 함).
|
||
const context: TypingContext = isTerminalApp(input.appName) ? this._terminalContext(input) : input
|
||
this._lastContext = context
|
||
const now = Date.now()
|
||
this._lastContextAt = now
|
||
this._watchdog()
|
||
|
||
const config = this.readPolicyConfig()
|
||
this._logDecisionInputs(context)
|
||
this._abortStaleGeneration(context.prefix)
|
||
this._keepWarm(context, now)
|
||
|
||
const model = this.resolveModel()
|
||
const step = decideSuggestionStep({
|
||
policy: this._buildPolicyInput(context, config, now),
|
||
sessionVisible: this.isVisible,
|
||
sessionPrefix: this._generatedForPrefix,
|
||
coolingDown: this._budget.isCoolingDown(now),
|
||
userDismissedQuiet: now < this._userDismissedUntil,
|
||
lastRequestedPrefix: this._lastRequestedPrefix,
|
||
modelWarm: this._warmth.isWarm(model, now),
|
||
warmUpBackoff: this._warmth.isBackingOff(model, now, WARM_UP_FAILURE_BACKOFF_MS),
|
||
// 서버가 없을 때 "준비 중" 은 실제 준비 작업(워밍업 루프)이 돌 때만 보여준다.
|
||
modelStarting: this._warmUpPromise !== null
|
||
})
|
||
if (step.action === 'generate' && this._failedPrefix && step.prefix === this._failedPrefix) {
|
||
// 방금 이 글로 첫 후보를 못 만들었다 — 더 치기 전까지 같은 생성을 되풀이하지 않는다(창 깜빡임 방지).
|
||
this._lastSkipReason = 'unchanged'
|
||
this._clearPending(true)
|
||
return
|
||
}
|
||
this._updatePresence(step, context, now)
|
||
this._executeStep(step, context, config, now)
|
||
}
|
||
|
||
/**
|
||
* 손을 멈춘 순간(presenceDelayMs) "생성 중" 자리를 먼저 띄운다 — 생성은 트리거 지연 뒤에 시작한다.
|
||
* 곧 생성으로 이어질 때만 띄운다(예산·모델 온기·닫기 직후·실패한 같은 글 확인). 다시 치면 거둔다.
|
||
*/
|
||
private _updatePresence(step: SuggestionStep, context: TypingContext, now: number): void {
|
||
if (step.action === 'generate') {
|
||
this._clearPending(false)
|
||
return
|
||
}
|
||
const waiting = step.action === 'settle' && (step.reason === 'debounce' || step.reason === 'composing')
|
||
if (
|
||
waiting &&
|
||
context.idleMs >= SUGGESTION_DEFAULTS.presenceDelayMs &&
|
||
!this.isPresentationActive &&
|
||
this._willGenerateSoon(context, now)
|
||
) {
|
||
if (!this._pending) this._showPending(context)
|
||
return
|
||
}
|
||
this._clearPending(true)
|
||
}
|
||
|
||
private _willGenerateSoon(context: TypingContext, now: number): boolean {
|
||
const model = this.resolveModel()
|
||
if (!model || !this._warmth.isWarm(model, now) || this._budget.isCoolingDown(now)) return false
|
||
if (now < this._userDismissedUntil) return false
|
||
const prefix = normalizeRequestPrefix(context.prefix)
|
||
if (prefix === this._failedPrefix || prefix === this._lastRequestedPrefix) return false
|
||
const config = this.readPolicyConfig()
|
||
const budget = this._budget.snapshot(now)
|
||
// 생성은 조금 뒤(트리거 지연)에 시작한다 — 그때까지 흐를 시간을 쳐서 간격을 본다.
|
||
const untilGenerate = Math.max(0, config.triggerDelayMs * COMPOSING_IDLE_MULTIPLIER - context.idleMs)
|
||
return (
|
||
budget.sinceLastRequestMs + untilGenerate >= SUGGESTION_DEFAULTS.minIntervalMs &&
|
||
budget.requestsThisMinute < config.maxRequestsPerMinute &&
|
||
budget.requestsToday < config.dailyBudget
|
||
)
|
||
}
|
||
|
||
private _showPending(context: TypingContext): void {
|
||
this._pending = true
|
||
this._anchor = context.anchor
|
||
this._anchorKind = context.anchorKind
|
||
this._appName = context.appName
|
||
if (this._pendingTimer) clearTimeout(this._pendingTimer)
|
||
this._pendingTimer = setTimeout(() => this._clearPending(true), SUGGESTION_DEFAULTS.presenceMaxMs)
|
||
this._pendingTimer.unref?.()
|
||
this.emit('updated', this.getState())
|
||
}
|
||
|
||
private _clearPending(notify: boolean): void {
|
||
if (this._pendingTimer) {
|
||
clearTimeout(this._pendingTimer)
|
||
this._pendingTimer = null
|
||
}
|
||
if (!this._pending) return
|
||
this._pending = false
|
||
if (notify && !this.isPresentationActive) this.emit('updated', this.getState())
|
||
}
|
||
|
||
private _executeStep(step: SuggestionStep, context: TypingContext, config: PolicyConfig, now: number): void {
|
||
switch (step.action) {
|
||
case 'end-session':
|
||
// 세션(페이지 넘기며 보는 고정 목록)을 보여주는 중에 다음 문장이 시작됐다 —
|
||
// 이어 치기로 자란 것도 포함, IME 마지막 글자 조합만 예외. 즉시 세션을 끝내고
|
||
// 다음 멈춤에서 정책 게이트를 다시 거쳐 새 세션을 시작한다.
|
||
logger.debug('제안 닫음: 이어서 입력함 — 멈추면 새 문맥으로 다시 만든다')
|
||
this.dismiss(step.reason)
|
||
// 사용자가 고르지 않고 계속 쳤다 — 이 세션 때문에 최소 간격(5초)에 걸려
|
||
// 정작 멈췄을 때 아무것도 안 뜨면 안 된다. 분당·일일 상한은 그대로 둔다.
|
||
this._budget.relaxInterval(now, SUGGESTION_DEFAULTS.minIntervalMs)
|
||
this.emit('state-changed', this.getState())
|
||
return
|
||
case 'generate':
|
||
// 비동기 실패가 조용히 사라지면 기능이 죽은 이유를 알 수 없다.
|
||
void this._generate(step.prefix, context, config.maxCandidates, config.maxChars).catch(
|
||
(error: unknown) => {
|
||
logger.warn(
|
||
`제안 생성 파이프라인 예외: ${error instanceof Error ? error.message : String(error)}`
|
||
)
|
||
this._releaseGeneration()
|
||
}
|
||
)
|
||
return
|
||
case 'settle':
|
||
this._settle(step, context, config)
|
||
return
|
||
}
|
||
}
|
||
|
||
/** 생성하지 않는 결정 — 사유를 남기고, 필요하면 로컬 기억/준비 중/닫기를 수행한다. */
|
||
private _settle(
|
||
step: Extract<SuggestionStep, { action: 'settle' }>,
|
||
context: TypingContext,
|
||
config: PolicyConfig
|
||
): void {
|
||
logger.debug(`제안 보류: ${step.reason} (${step.then})`)
|
||
this._lastSkipReason = step.reason
|
||
|
||
if (
|
||
step.tryLocalMemory &&
|
||
this._publishLocalMemory(
|
||
this._currentPrefix(context),
|
||
context,
|
||
config.maxCandidates,
|
||
config.maxChars,
|
||
0,
|
||
null
|
||
)
|
||
) {
|
||
return
|
||
}
|
||
|
||
switch (step.then) {
|
||
case 'record':
|
||
break
|
||
case 'dismiss':
|
||
if (this.isPresentationActive) this.dismiss(step.reason)
|
||
break
|
||
case 'warm-up':
|
||
void this.warmUp()
|
||
this._showWarming(context)
|
||
break
|
||
case 'show-warming':
|
||
// 워밍업 루프가 서버를 기다리는 중이면 "준비 중" 을 보여준다 — 아무 반응이 없으면
|
||
// 사용자는 기능이 죽었다고 판단한다(첫 실행에서 실제로 그랬다). 준비 작업이 없으면
|
||
// core 가 'record' 를 준다(끝나지 않는 스피너 방지).
|
||
this._showWarming(context)
|
||
break
|
||
}
|
||
this.emit('state-changed', this.getState())
|
||
}
|
||
|
||
/** "준비 중" 오버레이 — 워밍업 안내도 수명이 있어, 갱신이 없으면 스스로 사라진다. */
|
||
private _showWarming(context: TypingContext): void {
|
||
this._warmingUp = true
|
||
this._anchor = context.anchor
|
||
this._anchorKind = context.anchorKind
|
||
this._appName = context.appName
|
||
this._armVisibleTtl()
|
||
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' }
|
||
const context = this._lastContext
|
||
if (!context?.available || !context.isEditable || context.isPassword || context.hasSelection) {
|
||
const reason = context?.isPassword
|
||
? 'password-field'
|
||
: context?.hasSelection
|
||
? 'selection-active'
|
||
: 'not-editable'
|
||
if (this.isPresentationActive) this.dismiss(reason)
|
||
return { ok: false, reason }
|
||
}
|
||
if (context.caretReliable === false) return { ok: false, reason: 'caret-unknown' }
|
||
const prefix = normalizeRequestPrefix(context.prefix)
|
||
if (prefix.length < 1) return { ok: false, reason: 'empty-prefix' }
|
||
|
||
// 명시적 사용자 액션(단축키/설정)이다 — 텔레메트리가 판단한 "최근에 타이핑했는가" 에
|
||
// 좌우되지 않아야 한다. 그대로 넘기면 _generate 실패 경로의 _canUseLocalMemory 가
|
||
// (클릭만 한 뒤 수동 요청 같은 경우) not-typing 으로 막아 버린다.
|
||
const explicitContext: TypingContext = { ...context, editedSinceFocus: true, typedRecently: true }
|
||
const config = this.readPolicyConfig()
|
||
await this._generate(prefix, explicitContext, config.maxCandidates, config.maxChars).catch((error: unknown) => {
|
||
logger.warn(`수동 제안 생성 예외: ${error instanceof Error ? error.message : String(error)}`)
|
||
this._releaseGeneration()
|
||
})
|
||
return this.isVisible ? { ok: true } : { ok: false, reason: this._lastSkipReason ?? 'generation-failed' }
|
||
}
|
||
|
||
/**
|
||
* 정책 입력 조립 — 모든 경로가 이 한 곳에서 만든다.
|
||
*
|
||
* 기본값: 모델 가용성은 실제 값, overlayVisible 은 "생성/워밍업/후보 표시 중" 전체.
|
||
*/
|
||
private _buildPolicyInput(
|
||
context: TypingContext,
|
||
config: PolicyConfig,
|
||
now: number,
|
||
overrides: Partial<Pick<SuggestionPolicyInput, 'modelAvailable' | 'overlayVisible'>> = {}
|
||
): SuggestionPolicyInput {
|
||
const budget = this._budget.snapshot(now)
|
||
return {
|
||
enabled: this.isEnabled(),
|
||
modelAvailable: overrides.modelAvailable ?? getLocalLLMService().isAvailable(),
|
||
overlayVisible: overrides.overlayVisible ?? this.isPresentationActive,
|
||
composing: context.isComposing,
|
||
hasSelection: context.hasSelection,
|
||
isPassword: context.isPassword,
|
||
isEditable: context.isEditable,
|
||
appName: context.appName,
|
||
excludedApps: config.excludedApps,
|
||
editedSinceFocus: context.editedSinceFocus,
|
||
typedRecently: context.typedRecently,
|
||
prefix: context.prefix,
|
||
caretReliable: context.caretReliable !== false,
|
||
idleMs: context.idleMs,
|
||
triggerDelayMs: config.triggerDelayMs,
|
||
minPrefixChars: config.minPrefixChars,
|
||
sinceLastRequestMs: budget.sinceLastRequestMs,
|
||
minIntervalMs: SUGGESTION_DEFAULTS.minIntervalMs,
|
||
requestsThisMinute: budget.requestsThisMinute,
|
||
maxRequestsPerMinute: config.maxRequestsPerMinute,
|
||
requestsToday: budget.requestsToday,
|
||
dailyBudget: config.dailyBudget
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 터미널 문맥 — 화면 전체 대신 입력 줄만 접두로 쓰고, 커서 신뢰도도 입력 줄로 판단한다.
|
||
*
|
||
* 텔레메트리의 "편집이 문서 끝에서 일어났나" 는 화면 전체로 판정한다. 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 (
|
||
decideSuggestion(
|
||
this._buildPolicyInput(context, config, now, { modelAvailable: true, overlayVisible: false })
|
||
).action === 'request'
|
||
)
|
||
}
|
||
|
||
private _collectMemoryHints(prefix: string, appName: string | null): LocalMemoryContext {
|
||
const telemetry = getInputTelemetryService()
|
||
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(
|
||
(phrase) =>
|
||
phrase.appName?.trim().toLowerCase() === requestedApp && phraseHints.includes(phrase.phrase)
|
||
).length
|
||
: 0
|
||
return {
|
||
continuationHints: graphContext.continuations,
|
||
followUpHints: graphContext.followUps ?? [],
|
||
relatedHints: graphContext.related,
|
||
phraseHints,
|
||
fallbackPhraseHints,
|
||
appPhraseCount
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 모델 요청 하나를 만든다.
|
||
*
|
||
* 원형 템플릿을 아는 모델(gemma 계열)이면 prefill 이어 쓰기 — 모델 차례에 사용자가 쓰던 문장을
|
||
* 미리 넣어 그 글자 바로 뒤부터 쓰게 한다. 모르는 모델이면 예전 지시형 프롬프트를 쓴다.
|
||
* 두 경로 모두 같은 문맥(문서 첫머리·사실, 이 창의 앞 글, 개인 그래프)을 받는다.
|
||
*
|
||
* 채우기 후보도 prefill 로만 만든다. 예전엔 다양성을 위해 다음 문장 모드에서 지시형을 섞었는데,
|
||
* 지시형 gemma 는 사용자 글에 "대답" 했다(실측 2026-10-17 이력: "혹시 어떤 기능을 염두에 두고 계신지
|
||
* 설명해 주실 수 있을까요?" — 사용자 신고 "내가 쓴 것에 대한 응답만 나온다"). 후보가 덜 다양한 편이 낫다.
|
||
*/
|
||
private _buildModelRequest(
|
||
model: string,
|
||
prefix: string,
|
||
context: TypingContext,
|
||
memory: LocalMemoryContext,
|
||
maxChars: number,
|
||
options: { avoidCandidates?: readonly string[] } = {}
|
||
): 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 ?? ''
|
||
})
|
||
|
||
if (rawPrompt !== null) {
|
||
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
|
||
})
|
||
const parse = (raw: string): { candidate: SuggestionCandidate | null; rejected: string | null } => {
|
||
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
|
||
}
|
||
}
|
||
const stop = rawChatStopSequences(model)
|
||
const endsWithSpace = /\s$/u.test(prompt.assistantPrefix ?? '')
|
||
return {
|
||
prompt: rawPrompt,
|
||
raw: true,
|
||
stop,
|
||
spaced: endsWithSpace
|
||
? undefined
|
||
: {
|
||
prompt: `${rawPrompt} `,
|
||
raw: true,
|
||
stop,
|
||
parse: (raw) => parse(` ${raw}`),
|
||
partial: (raw) => extract(` ${raw}`)?.text ?? ''
|
||
},
|
||
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,
|
||
token: number | null
|
||
): boolean {
|
||
if (token !== null && token !== this._generationToken) return false
|
||
const current = this._lastContext
|
||
if (
|
||
!current ||
|
||
!current.available ||
|
||
!current.isEditable ||
|
||
current.isPassword ||
|
||
current.isComposing ||
|
||
current.hasSelection
|
||
) {
|
||
return false
|
||
}
|
||
return (
|
||
normalizeSessionPrefix(current.prefix) === normalizeSessionPrefix(prefix) &&
|
||
current.appName === context.appName &&
|
||
current.windowTitle === context.windowTitle
|
||
)
|
||
}
|
||
|
||
private _publishLocalMemory(
|
||
prefix: string,
|
||
context: TypingContext,
|
||
maxCandidates: number,
|
||
maxChars: number,
|
||
latencyMs: number,
|
||
token: number | null,
|
||
memory: LocalMemoryContext | null = null
|
||
): boolean {
|
||
if (!this._isCurrentFallbackContext(prefix, context, token)) return false
|
||
const trimmedPrefix = normalizeSessionPrefix(prefix)
|
||
const localMemory = memory ?? this._collectMemoryHints(trimmedPrefix, context.appName)
|
||
// 원문 뒤 공백(단어를 끝냈는가)은 세션 접두 정규화가 지운다 — 최신 원문에서 읽어 넘긴다.
|
||
const rawPrefix = this._lastContext?.prefix ?? context.prefix
|
||
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
|
||
|
||
this._partialText = ''
|
||
this._generating = false
|
||
this._warmingUp = false
|
||
// 단어 중간에서 이어지는 나머지(예: "Thank yo" + "u for…")는 수락할 때 공백 없이 붙인다.
|
||
this._candidates = entries.map((entry, index) =>
|
||
entry.attachToPrefix ? { text: entry.text, rank: index, joint: 'attach' } : { text: entry.text, rank: index }
|
||
)
|
||
this._correction = null
|
||
this._promptContext = null
|
||
this._activeIndex = 0
|
||
this._anchor = context.anchor
|
||
this._anchorKind = context.anchorKind
|
||
this._appName = context.appName
|
||
this._windowTitle = context.windowTitle
|
||
this._windowHandle = context.windowHandle ?? null
|
||
this._generatedForPrefix = trimmedPrefix
|
||
this._targetTotal = entries.length
|
||
this._lastSkipReason = null
|
||
this._lastLatencyMs = latencyMs
|
||
this._provenance = {
|
||
mode: 'local-memory',
|
||
continuationCount: localMemory.continuationHints.length,
|
||
relatedCount: localMemory.relatedHints.length + localMemory.followUpHints.length,
|
||
phraseCount: localMemory.phraseHints.length,
|
||
appPhraseCount: localMemory.appPhraseCount
|
||
}
|
||
this._recordSuggestion({
|
||
prefix: trimmedPrefix,
|
||
text: entries[0].text,
|
||
model: 'local-memory',
|
||
latencyMs,
|
||
candidateCount: entries.length
|
||
})
|
||
this._armVisibleTtl()
|
||
this.emit('updated', this.getState())
|
||
this.emit('state-changed', this.getState())
|
||
logger.info(`로컬 기억 제안 ${entries.length}개 생성`)
|
||
return true
|
||
}
|
||
|
||
// ── 생성 ──────────────────────────────────────────────
|
||
|
||
private async _generate(
|
||
prefix: string,
|
||
context: TypingContext,
|
||
maxCandidates: number,
|
||
maxChars: number
|
||
): Promise<void> {
|
||
if (this._inFlight) {
|
||
// 침묵하면 "왜 안 뜨는지" 를 알 수 없다 — 진단을 남긴다.
|
||
logger.debug(`제안 건너뜀: 이미 생성 중 (${Date.now() - this._budget.lastRequestAt}ms 경과)`)
|
||
return
|
||
}
|
||
|
||
// 어떤 경로로 끝나든 진행 플래그는 반드시 해제한다.
|
||
// (emit/showOverlay 쪽 예외가 여기로 새면 _inFlight 가 true 로 굳어
|
||
// 이후 모든 제안이 조용히 막힌다 — "한 번 나오고 안 나옴" 의 원인 후보)
|
||
try {
|
||
|
||
const startedAt = Date.now()
|
||
// 세션 접두 — 프롬프트 입력이자 세션 유효성 비교의 기준 (normalizeSessionPrefix 정본)
|
||
const trimmedPrefix = normalizeSessionPrefix(prefix)
|
||
const model = this.resolveModel()
|
||
if (!model) {
|
||
const config = this.readPolicyConfig()
|
||
if (
|
||
this._canUseLocalMemory(context, config, startedAt) &&
|
||
this._publishLocalMemory(
|
||
trimmedPrefix,
|
||
context,
|
||
maxCandidates,
|
||
maxChars,
|
||
Date.now() - startedAt,
|
||
null
|
||
)
|
||
) {
|
||
return
|
||
}
|
||
this._lastSkipReason = 'model-unavailable'
|
||
this.emit('state-changed', this.getState())
|
||
return
|
||
}
|
||
|
||
this._abort?.abort()
|
||
const abort = new AbortController()
|
||
this._abort = abort
|
||
const token = (this._generationToken += 1)
|
||
|
||
this._inFlight = true
|
||
this._generating = true
|
||
this._lastRequestedPrefix = normalizeRequestPrefix(prefix)
|
||
this._warmingUp = false
|
||
this._provenance = null
|
||
this._budget.consume(Date.now())
|
||
|
||
// 후보가 오기 전에 빈 화면으로 기다리게 하지 않는다 — 즉시 자리를 잡고
|
||
// "생성 중" 을 보여준 뒤 내용으로 채운다. 실측 5초 지연에서 특히 중요하다.
|
||
this._candidates = []
|
||
this._correction = null
|
||
this._promptContext = null
|
||
this._sessionRecordId = null
|
||
this._activeIndex = 0
|
||
this._anchor = context.anchor
|
||
this._anchorKind = context.anchorKind
|
||
this._appName = context.appName
|
||
this._windowTitle = context.windowTitle
|
||
this._windowHandle = context.windowHandle ?? null
|
||
this._armVisibleTtl()
|
||
this.emit('updated', this.getState())
|
||
|
||
const timeoutMs = this.readTimeoutMs()
|
||
let timedOut = false
|
||
if (this._timeoutTimer) clearTimeout(this._timeoutTimer)
|
||
this._timeoutTimer = setTimeout(() => {
|
||
// 모델이 하드웨어보다 느릴 때 UI 를 붙잡지 않는다 (다음 타이핑 주기에 재시도).
|
||
if (!abort.signal.aborted) {
|
||
timedOut = true
|
||
abort.abort()
|
||
}
|
||
}, timeoutMs)
|
||
this._timeoutTimer.unref?.()
|
||
|
||
// 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장,
|
||
// (2) follows/용어공유 관계로 끌어온 관련 문장.
|
||
let memory = this._collectMemoryHints(trimmedPrefix, context.appName)
|
||
let spacedPreferred = false
|
||
let correction: SuggestionCorrection | null = null
|
||
let promptContext = context
|
||
|
||
let parsed: { candidate: SuggestionCandidate | null; rejected: string | null } = { candidate: null, rejected: 'empty' }
|
||
try {
|
||
// 오타가 있으면 고친 글로 이어 쓴다 — 낱자 잡음("안ㄴ뇽", "ㅇ다른")이 섞인 글을 그대로 주면 모델이
|
||
// 그 잡음까지 되풀이했다(실측 이력: "아직 ㅇ" → "아직 ㅇ 기능도…"). 교정은 수락할 때만 적용한다.
|
||
correction = await this._proposeCorrection(context, abort.signal)
|
||
if (correction) {
|
||
promptContext = applyCorrectionToContext(context, correction)
|
||
memory = this._collectMemoryHints(normalizeSessionPrefix(promptContext.prefix), context.appName)
|
||
}
|
||
// 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자
|
||
// 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다.
|
||
const request = this._buildModelRequest(
|
||
model,
|
||
normalizeSessionPrefix(promptContext.prefix),
|
||
promptContext,
|
||
memory,
|
||
maxChars
|
||
)
|
||
this._partialText = ''
|
||
// 지어낸 사실(원문에 없는 날짜·이름·숫자)로 버린 첫 후보는 같은 시간 제한 안에서 한 번 더 뽑는다.
|
||
let active = request
|
||
let temperature: number = SUGGESTION_DEFAULTS.temperature
|
||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||
const raw = await this._streamModel(active, 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
|
||
parsed = active.parse(raw)
|
||
if (!parsed.candidate) {
|
||
// 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보.
|
||
logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`)
|
||
}
|
||
if (parsed.candidate) break
|
||
if (raw.trim().length === 0 && active.spaced) {
|
||
// 모델이 곧바로 턴을 닫았다 — prefill 끝에 공백을 붙여 다음 단어부터 쓰게 한다(같은 온도).
|
||
logger.debug('제안 빈 출력 — prefill 끝에 공백을 붙여 다시 뽑는다')
|
||
active = active.spaced
|
||
} else if (parsed.rejected?.startsWith('unsupported-facts')) {
|
||
logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`)
|
||
temperature = FILL_TEMPERATURE
|
||
} else {
|
||
break
|
||
}
|
||
this._partialText = ''
|
||
}
|
||
spacedPreferred = active !== request
|
||
} catch (error) {
|
||
if (!abort.signal.aborted) {
|
||
this._lastSkipReason = 'generation-failed'
|
||
this._noteFailure(error instanceof Error ? error.message : String(error))
|
||
if (
|
||
this._publishLocalMemory(
|
||
trimmedPrefix,
|
||
context,
|
||
maxCandidates,
|
||
maxChars,
|
||
Date.now() - startedAt,
|
||
token,
|
||
memory
|
||
)
|
||
) {
|
||
logger.warn(`모델 제안 실패 후 로컬 기억 제안으로 전환: ${error instanceof Error ? error.message : String(error)}`)
|
||
return
|
||
}
|
||
this.dismiss('generation-failed')
|
||
this.emit('state-changed', this.getState())
|
||
return
|
||
}
|
||
} finally {
|
||
if (this._abort === abort) this._abort = null
|
||
if (this._timeoutTimer) {
|
||
clearTimeout(this._timeoutTimer)
|
||
this._timeoutTimer = null
|
||
}
|
||
}
|
||
|
||
if (abort.signal.aborted) {
|
||
if (token !== this._generationToken) {
|
||
logger.debug(`중단된 제안 결과 폐기 (세대 ${token} ≠ ${this._generationToken})`)
|
||
return
|
||
}
|
||
|
||
if (!timedOut) return
|
||
|
||
this._lastSkipReason = 'generation-failed'
|
||
// warm 이라 믿고 보낸 요청이 시간 초과했다면 모델은 이미 내려갔다(다른 기능의 짧은 keep_alive 등)
|
||
// — 다음 멈춤은 같은 콜드 요청을 되풀이하지 말고 워밍업("준비 중")부터 한다.
|
||
this._warmth.noteCold(model)
|
||
this._noteFailure(`timeout ${timeoutMs}ms`)
|
||
if (
|
||
this._publishLocalMemory(
|
||
trimmedPrefix,
|
||
context,
|
||
maxCandidates,
|
||
maxChars,
|
||
Date.now() - startedAt,
|
||
token,
|
||
memory
|
||
)
|
||
) {
|
||
logger.warn(`모델 제안 시간 초과 후 로컬 기억 제안으로 전환 (${timeoutMs}ms)`)
|
||
return
|
||
}
|
||
this.dismiss('generation-failed')
|
||
this.emit('state-changed', this.getState())
|
||
return
|
||
}
|
||
|
||
// 사용자가 그사이 닫았거나 새 요청이 시작됐다면 이 결과는 버린다.
|
||
if (token !== this._generationToken) {
|
||
logger.debug(`제안 결과 폐기 (세대 ${token} ≠ ${this._generationToken})`)
|
||
return
|
||
}
|
||
|
||
// 타이핑을 멈추고 자리를 뜬 뒤 도착한 결과는 화면에 띄우지 않는다.
|
||
// (아무것도 안 치는데 제안창이 뜨던 신고의 원인 중 하나)
|
||
const staleness = Date.now() - this._lastContextAt
|
||
if (this._lastContextAt > 0 && staleness > SUGGESTION_DEFAULTS.resultMaxStalenessMs) {
|
||
logger.debug(`제안 결과 폐기 (문맥이 ${staleness}ms 지났다)`)
|
||
this.dismiss('stale')
|
||
return
|
||
}
|
||
|
||
// 요청 뒤 사용자가 더 쳤다면 이 결과는 옛 접두용이다 — 게시하면 다음 스냅샷에서 곧바로
|
||
// stale 로 닫히며(깜빡임) 채우기 요청만 낭비하고, 그사이 수락하면 방금 친 말이 빠진
|
||
// 문장이 들어간다. 세션과 같은 기준(matchesSessionPrefix)으로 최신 문맥과 맞춰 본다.
|
||
const latest = this._lastContext
|
||
if (latest && !matchesSessionPrefix(trimmedPrefix, latest.prefix)) {
|
||
logger.debug('제안 결과 폐기 (요청 뒤 접두가 바뀌었다)')
|
||
this.dismiss('stale')
|
||
this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs)
|
||
this.emit('state-changed', this.getState())
|
||
return
|
||
}
|
||
|
||
const first = parsed.candidate
|
||
this._failedPrefix = first ? '' : this._lastRequestedPrefix
|
||
if (!first) {
|
||
this._lastSkipReason = 'generation-failed'
|
||
logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`)
|
||
if (
|
||
this._publishLocalMemory(
|
||
trimmedPrefix,
|
||
context,
|
||
maxCandidates,
|
||
maxChars,
|
||
Date.now() - startedAt,
|
||
token,
|
||
memory
|
||
)
|
||
) {
|
||
return
|
||
}
|
||
this.dismiss('generation-failed')
|
||
this.emit('state-changed', this.getState())
|
||
return
|
||
}
|
||
|
||
const latencyMs = Date.now() - startedAt
|
||
this._lastLatencyMs = latencyMs
|
||
this._budget.noteSuccess()
|
||
this._partialText = ''
|
||
this._candidates = [{ ...first, rank: 0 }]
|
||
this._correction = correction
|
||
this._promptContext = promptContext
|
||
this._spacedPreferred = spacedPreferred
|
||
this._activeIndex = 0
|
||
this._anchor = context.anchor
|
||
this._anchorKind = context.anchorKind
|
||
this._appName = context.appName
|
||
this._windowTitle = context.windowTitle
|
||
this._windowHandle = context.windowHandle ?? null
|
||
this._generatedForPrefix = trimmedPrefix
|
||
this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal
|
||
this._lastSkipReason = null
|
||
this._provenance = {
|
||
mode: 'local-model',
|
||
continuationCount: memory.continuationHints.length,
|
||
relatedCount: memory.relatedHints.length + memory.followUpHints.length,
|
||
phraseCount: memory.phraseHints.length,
|
||
appPhraseCount: memory.appPhraseCount
|
||
}
|
||
|
||
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())
|
||
|
||
// generating 은 계속 true 로 남는다 — 채우기 루프가 백그라운드에서 나머지를
|
||
// 하나씩 청한다("더 온다" 를 UI 에 알린다). _releaseGeneration() 이 이를
|
||
// 지우지 않도록 _filling 을 먼저 켠다.
|
||
this._filling = true
|
||
void this._runFillLoop(token, context, maxChars).catch((error: unknown) => {
|
||
logger.warn(`제안 채우기 루프 예외: ${error instanceof Error ? error.message : String(error)}`)
|
||
this._filling = false
|
||
})
|
||
} finally {
|
||
// 어떤 경로로 끝나든 진행 플래그를 해제한다 —
|
||
// 예외가 어디로 새든 다음 제안이 조용히 막히지 않는다.
|
||
this._releaseGeneration()
|
||
}
|
||
}
|
||
|
||
/** 이 문맥에 함께 내놓을 오타 교정 — 포트가 없거나 실패하면 교정 없이 간다. */
|
||
private async _proposeCorrection(
|
||
context: TypingContext,
|
||
signal: AbortSignal,
|
||
thorough = false
|
||
): Promise<SuggestionCorrection | null> {
|
||
if (!this._typoProposer) return null
|
||
try {
|
||
const plan = await this._typoProposer.propose(context, signal, { thorough })
|
||
if (!plan || !context.prefix.endsWith(plan.originalText)) return null
|
||
const base = plan.corrections[0]?.start ?? 0
|
||
return {
|
||
from: plan.originalText,
|
||
to: plan.insertText,
|
||
edits: plan.corrections.map((edit) => ({ start: edit.start - base, end: edit.end - base, to: edit.to }))
|
||
}
|
||
} catch (error) {
|
||
logger.debug(`제안용 오타 교정 실패 — 교정 없이 제안한다: ${error instanceof Error ? error.message : String(error)}`)
|
||
return null
|
||
}
|
||
}
|
||
|
||
// ── 채우기 루프 (2번째 이후 후보, 최대 12개) ────────────
|
||
|
||
/**
|
||
* 첫 후보 공개 뒤 나머지를 하나씩 순차로 채운다.
|
||
*
|
||
* 종료 조건: 12개 도달, 연속 2번 새 후보 없음, 세대 토큰이 바뀜(세션 종료).
|
||
* `_generate` 의 예산/타임아웃/실패 카운트와 무관하다 — 채우기는 그 어느 것도
|
||
* 소비하지 않는다(설계). 시간 초과된 채우기 요청은 조용히 다음으로 넘어간다.
|
||
*/
|
||
private async _runFillLoop(token: number, context: TypingContext, maxChars: number): Promise<void> {
|
||
await this._proposeLateCorrection(token, context)
|
||
let consecutiveEmpty = 0
|
||
while (
|
||
token === this._generationToken &&
|
||
this._candidates.length < SUGGESTION_DEFAULTS.maxCandidatesTotal &&
|
||
consecutiveEmpty < 2
|
||
) {
|
||
const appended = await this._fillOne(token, context, maxChars)
|
||
if (token !== this._generationToken) break
|
||
consecutiveEmpty = appended ? 0 : consecutiveEmpty + 1
|
||
}
|
||
if (token === this._generationToken) {
|
||
this._filling = false
|
||
this._generating = false
|
||
this.emit('updated', this.getState())
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 첫 후보를 보여 준 뒤 모델 오타 검사를 한 번 더 한다 — 낱자 없는 오타("회으에서")는 첫 요청 전에
|
||
* 묻지 않는다(멈출 때마다 0.5~1초 늦어진다). 찾으면 교정 줄을 붙이고, 남은 후보는 고친 글로 잇는다.
|
||
*/
|
||
private async _proposeLateCorrection(token: number, context: TypingContext): Promise<void> {
|
||
if (this._correction || !this._typoProposer) return
|
||
const abort = new AbortController()
|
||
this._fillAbort = abort
|
||
try {
|
||
const late = await this._proposeCorrection(context, abort.signal, true)
|
||
if (!late || token !== this._generationToken || abort.signal.aborted) return
|
||
// 그사이 원문이 바뀌었으면(세션이 끝났으면 토큰이 달라진다) 붙이지 않는다.
|
||
if (!this._lastContext || !this._lastContext.prefix.endsWith(late.from)) return
|
||
this._correction = late
|
||
this._promptContext = applyCorrectionToContext(context, late)
|
||
this._armVisibleTtl()
|
||
this.emit('updated', this.getState())
|
||
} finally {
|
||
if (this._fillAbort === abort) this._fillAbort = null
|
||
}
|
||
}
|
||
|
||
/** 채우기 루프 한 스텝 — 후보 1개를 요청해 고유하면 덧붙인다. */
|
||
private async _fillOne(token: number, context: TypingContext, maxChars: number): Promise<boolean> {
|
||
const model = this.resolveModel()
|
||
if (!model) return false
|
||
|
||
const abort = new AbortController()
|
||
this._fillAbort = abort
|
||
const timeoutMs = this.readTimeoutMs()
|
||
const timer = setTimeout(() => {
|
||
if (!abort.signal.aborted) abort.abort()
|
||
}, timeoutMs)
|
||
timer.unref?.()
|
||
|
||
try {
|
||
// 세션이 고정한 접두를 쓴다 — context.prefix 는 그사이 바뀌었을 수 있지만,
|
||
// 바뀌었다면 이미 위(handleTypingContext)에서 세션이 dismiss 되어 토큰이
|
||
// 달라져 있으므로 이 루프는 다음 체크에서 멈춘다.
|
||
// 교정이 있으면 모델에는 고친 글을 보여 준다 (첫 후보와 같은 문맥).
|
||
const promptContext = this._promptContext ?? context
|
||
const prefix = normalizeSessionPrefix(promptContext.prefix)
|
||
const memory = this._collectMemoryHints(prefix, context.appName)
|
||
const avoidCandidates = this._candidates.map((candidate) => candidate.text)
|
||
const built = this._buildModelRequest(model, prefix, promptContext, memory, maxChars, { avoidCandidates })
|
||
const request = this._spacedPreferred && built.spaced ? built.spaced : built
|
||
const raw = await this._streamModel(request, model, FILL_TEMPERATURE, abort.signal)
|
||
if (abort.signal.aborted || token !== this._generationToken) 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({ ...candidate, rank: this._candidates.length })
|
||
logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`)
|
||
this._armVisibleTtl()
|
||
this.emit('updated', this.getState())
|
||
// 채우기 후보는 새 행이 아니다 — 세션 행의 후보 수만 늘린다(지연 0 행이 평균·수락률을 망쳤다).
|
||
if (this._sessionRecordId) {
|
||
this._repository.updateSessionCandidates?.(this._sessionRecordId, this._candidates.length)
|
||
}
|
||
return true
|
||
} catch (error) {
|
||
if (!abort.signal.aborted) {
|
||
logger.debug(
|
||
`제안 채우기 요청 실패 — 조용히 다음으로 넘어간다: ${error instanceof Error ? error.message : String(error)}`
|
||
)
|
||
}
|
||
return false
|
||
} finally {
|
||
clearTimeout(timer)
|
||
if (this._fillAbort === abort) this._fillAbort = null
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 모델 요청 하나를 스트리밍으로 받는다.
|
||
*
|
||
* 이어 쓰기는 첫 문장만 쓴다 — 모델이 그 뒤를 더 쓰기 시작하면 거기서 끊어 지연과 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()
|
||
return this._candidates.some((existing) => {
|
||
const existingNormalized = existing.text.replace(/\s+/gu, ' ').trim().toLowerCase()
|
||
return (
|
||
existingNormalized === normalized ||
|
||
existingNormalized.startsWith(normalized) ||
|
||
normalized.startsWith(existingNormalized)
|
||
)
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 생성 플래그를 무조건 해제한다 (누수 감시 포함).
|
||
*
|
||
* 응답 제한 + 여유를 넘겨 진행 중이면 비정상 상태로 보고 스스로 복구한다.
|
||
*/
|
||
private _releaseGeneration(): void {
|
||
this._inFlight = false
|
||
// 채우기 루프가 막 시작됐으면 generating 을 그대로 둔다 — 아직 더 올 게 있다.
|
||
// (루프 자신이 끝날 때 스스로 false 로 내린다)
|
||
if (!this._filling) this._generating = false
|
||
this._partialText = ''
|
||
}
|
||
|
||
/** 마지막 생성 이후 흐른 시간 (ms). */
|
||
get inFlightAgeMs(): number {
|
||
return this._inFlight ? Date.now() - this._budget.lastRequestAt : 0
|
||
}
|
||
|
||
/** 응답 제한 (설정 → SSOT 기본값). */
|
||
private readTimeoutMs(): number {
|
||
const configured = configGet('suggestionRequestTimeoutMs')
|
||
return configured && configured > 0 ? configured : SUGGESTION_DEFAULTS.requestTimeoutMs
|
||
}
|
||
|
||
/** 현재 정책 기준의 접두. */
|
||
private _currentPrefix(context: TypingContext): string {
|
||
return normalizeRequestPrefix(context.prefix)
|
||
}
|
||
|
||
/** 판단 입력을 서명이 바뀔 때만 남긴다. */
|
||
private _logDecisionInputs(context: TypingContext): void {
|
||
const signature = [
|
||
context.available,
|
||
context.isEditable,
|
||
context.isPassword,
|
||
context.isComposing,
|
||
context.anchor ? 'A' : '-',
|
||
context.editedSinceFocus,
|
||
context.typedRecently,
|
||
getLocalLLMService().isAvailable(),
|
||
this.isEnabled()
|
||
].join('|')
|
||
|
||
if (signature === this._lastDecisionSignature) return
|
||
this._lastDecisionSignature = signature
|
||
logger.info(
|
||
`제안 판단 입력: avail=${context.available} edit=${context.isEditable} pw=${context.isPassword} ` +
|
||
`comp=${context.isComposing} edited=${context.editedSinceFocus} typed=${context.typedRecently} ` +
|
||
`prefixLen=${context.prefix.length} idle=${context.idleMs}ms ` +
|
||
`app=${context.appName ?? '-'} enabled=${this.isEnabled()} ` +
|
||
`model=${getLocalLLMService().isAvailable()} anchor=${context.anchor ? 'yes' : 'no'}`
|
||
)
|
||
}
|
||
|
||
/**
|
||
* 생성 실패를 기록하고, 연속 실패면 잠시 쉰다.
|
||
*
|
||
* 실패할 때마다 새 요청이 스피너를 다시 걸면 "끝나지도 꺼지지도 않는" 것처럼 보인다
|
||
* (실측 신고). 임계 도달 시 쿨다운 동안은 요청 자체를 하지 않는다.
|
||
*/
|
||
private _noteFailure(reason: string): void {
|
||
if (!this._budget.noteFailure(Date.now())) return
|
||
logger.warn(
|
||
`제안 생성 연속 실패 (${reason}) — ${Math.round(
|
||
SUGGESTION_DEFAULTS.failureCooldownMs / 1000
|
||
)}초 동안 요청을 쉰다 (모델이 다른 작업으로 바쁠 수 있음)`
|
||
)
|
||
}
|
||
|
||
/** 이 모델이 방금 응답했다 — keep-alive 동안 메모리에 남아 있다고 본다. */
|
||
private _noteModelWarm(model: string): void {
|
||
this._warmth.noteWarm(model, Date.now() + SUGGESTION_KEEP_ALIVE_MS - SUGGESTION_KEEP_ALIVE_MARGIN_MS)
|
||
}
|
||
|
||
private _armVisibleTtl(): void {
|
||
if (this._ttlTimer) clearTimeout(this._ttlTimer)
|
||
this._ttlTimer = setTimeout(() => {
|
||
this._ttlTimer = null
|
||
logger.debug('제안 표시 수명 만료 — 자동으로 닫는다')
|
||
this.dismiss('stale')
|
||
}, SUGGESTION_DEFAULTS.visibleTtlMs)
|
||
this._ttlTimer.unref?.()
|
||
}
|
||
|
||
/** 표시 수명 타이머 해제. */
|
||
private _clearVisibleTtl(): void {
|
||
if (this._ttlTimer) {
|
||
clearTimeout(this._ttlTimer)
|
||
this._ttlTimer = null
|
||
}
|
||
}
|
||
|
||
private _abortStaleGeneration(currentPrefix: string): void {
|
||
if (!this._inFlight || !this._abort || this._abort.signal.aborted) return
|
||
// 세션 규칙과 같은 기준 — 요청 뒤 한 글자라도 자라면 결과는 도착하자마자 stale 이다.
|
||
const refresh = decideInFlightGeneration(this._lastRequestedPrefix, currentPrefix)
|
||
if (refresh === 'keep') return
|
||
|
||
this._generationToken += 1
|
||
this._abort.abort()
|
||
|
||
// 취소된 요청은 속도 제한 예산을 쓰지 않았던 것으로 되돌린다.
|
||
// (IME 조합 중 마지막 글자가 바뀌어 stale 로 잡히면, 취소가 예산을 갉아먹어
|
||
// 정작 사용자가 멈췄을 때 rate-limited 로 막히던 문제)
|
||
this._budget.refund()
|
||
// 보여줄 후보가 없으면 스피너만 남는다 — 오버레이를 지운다.
|
||
if (this._candidates.length === 0) this.dismiss('stale')
|
||
logger.debug(`제안 생성 취소 (${refresh}) — 다음 정상 입력 문맥에서만 재평가`)
|
||
}
|
||
|
||
/**
|
||
* 진행 플래그가 비정상적으로 오래 남았으면 강제 해제한다.
|
||
*
|
||
* 응답 제한(기본 8초) + 5초를 넘긴 in-flight 는 죽은 것으로 본다 —
|
||
* 어떤 예외 경로로든 플래그가 누수되면 제안이 영구히 멈추기 때문이다.
|
||
*/
|
||
private _watchdog(): void {
|
||
if (!this._inFlight) return
|
||
const age = Date.now() - this._budget.lastRequestAt
|
||
if (age < this.readTimeoutMs() + 5000) return
|
||
logger.warn(`제안 생성 플래그 누수 감지 (${age}ms) — 강제 해제`)
|
||
this._generationToken += 1
|
||
this._abort?.abort()
|
||
this._abort = null
|
||
if (this._timeoutTimer) {
|
||
clearTimeout(this._timeoutTimer)
|
||
this._timeoutTimer = null
|
||
}
|
||
this._releaseGeneration()
|
||
this._lastSkipReason = 'stale'
|
||
this.emit('updated', this.getState())
|
||
}
|
||
|
||
// ── 사용자 동작 ───────────────────────────────────────
|
||
|
||
/** 이전 후보로 순환 (전체 후보를 가로질러, 페이지 무관). */
|
||
previous(): SuggestionState {
|
||
if (this._candidates.length > 1) {
|
||
this._moveActive((this._activeIndex - 1 + this._candidates.length) % this._candidates.length)
|
||
}
|
||
return this.getState()
|
||
}
|
||
|
||
/**
|
||
* 다음 후보로 — 페이지는 활성 후보를 따라 넘어간다.
|
||
*
|
||
* 마지막 후보에서 아직 더 만드는 중이면 그 자리에 머문다: 처음으로 돌아가 버리면
|
||
* 곧 도착할 후보를 보려던 사용자가 길을 잃는다. 다 만들었으면 처음으로 돌아간다.
|
||
*/
|
||
next(): SuggestionState {
|
||
const last = this._candidates.length - 1
|
||
if (last < 1) return this.getState()
|
||
if (this._activeIndex < last) this._moveActive(this._activeIndex + 1)
|
||
else if (!this._filling) this._moveActive(0)
|
||
return this.getState()
|
||
}
|
||
|
||
/** 사용자가 후보를 훑는 중에는 표시 수명이 끝나 창이 닫히면 안 된다. */
|
||
private _moveActive(index: number): void {
|
||
this._activeIndex = index
|
||
this._armVisibleTtl()
|
||
this.emit('updated', this.getState())
|
||
}
|
||
|
||
dismiss(reason: SuggestionSkipReason = 'dismissed'): void {
|
||
if (reason === 'dismissed') {
|
||
// 명시적 닫기: 잠깐 조용히 있고, 진행 중 생성은 무효화한다.
|
||
this._userDismissedUntil = Date.now() + SUGGESTION_DEFAULTS.userDismissQuietMs
|
||
logger.info(`사용자가 제안을 닫음 — ${SUGGESTION_DEFAULTS.userDismissQuietMs}ms 동안 재표시하지 않는다`)
|
||
}
|
||
const wasVisible = this.isPresentationActive || this._pending
|
||
this._clearPending(false)
|
||
// 진행 중이던 생성을 무효화한다 (닫았는데 잠시 뒤 결과가 다시 뜨는 것을 막는다).
|
||
this._generationToken += 1
|
||
this._clearVisibleTtl()
|
||
this._candidates = []
|
||
this._generating = false
|
||
this._warmingUp = false
|
||
this._partialText = ''
|
||
this._activeIndex = 0
|
||
this._anchor = null
|
||
this._anchorKind = null
|
||
this._generatedForPrefix = ''
|
||
this._targetTotal = 0
|
||
this._provenance = null
|
||
this._sessionRecordId = null
|
||
this._correction = null
|
||
this._promptContext = null
|
||
this._lastSkipReason = reason
|
||
this._abort?.abort()
|
||
this._abort = null
|
||
// 채우기 루프도 함께 끝낸다 — accept/dismiss/stale 은 전부 세션 종료다(설계).
|
||
this._filling = false
|
||
this._fillAbort?.abort()
|
||
this._fillAbort = null
|
||
if (this._timeoutTimer) {
|
||
clearTimeout(this._timeoutTimer)
|
||
this._timeoutTimer = null
|
||
}
|
||
// 워밍업은 오버레이 표시와 독립된 요청이다 — 포커스 전환/stale 등으로 오버레이를
|
||
// 지울 때마다 취소하면 모델이 영영 안 뜬다. 설정에서 기능을 끌 때만 취소한다.
|
||
if (reason === 'disabled') this._cancelWarmUp()
|
||
if (wasVisible || reason === 'dismissed') {
|
||
this.emit('cleared', { reason })
|
||
}
|
||
}
|
||
|
||
/** 활성 후보를 대상 앱에 삽입하고 수락으로 기록한다. */
|
||
async accept(index?: number): Promise<SuggestionRequestResult> {
|
||
if (index !== undefined && index >= 0 && index < this._candidates.length) {
|
||
this._activeIndex = index
|
||
}
|
||
const candidate = this._candidates[this._activeIndex]
|
||
if (!candidate) {
|
||
// 창이 이미 닫힌 뒤의 클릭·단축키 — 조용히 끝나면 "골라도 안 들어간다" 의 원인이 안 보인다.
|
||
logger.info(`제안 수락 무시: 표시 중인 후보 없음 (index=${index ?? 'active'})`)
|
||
return { ok: false, reason: 'already-visible' }
|
||
}
|
||
// 케어렛을 모르는 필드에서 문서 중간을 고친 뒤다 — 후보는 문서 끝의 이어 쓰기라
|
||
// 실제 커서(문서 중간)에 붙이면 엉뚱한 곳에 문장이 들어간다.
|
||
if (this._lastContext?.caretReliable === false) {
|
||
logger.info('제안 수락 거부: 케어렛 위치를 알 수 없고 마지막 편집이 문서 끝이 아니다')
|
||
this.dismiss('caret-unknown')
|
||
this.emit('state-changed', this.getState())
|
||
return { ok: false, reason: 'caret-unknown' }
|
||
}
|
||
// 후보는 정제 과정에서 앞 공백을 잃는다 — 커서 앞 원문의 마지막 글자를 보고 구분 공백을
|
||
// 붙인다(joinSuggestion). 세션을 닫기 전에(dismiss 가 세션 접두를 지운다) 계산한다.
|
||
// 교정이 있으면 커서 앞 오타 구간을 지우고 고친 글 + 후보를 함께 넣는다. 그사이 원문 끝이 달라졌으면
|
||
// (IME 마지막 글자 교체 등) 교정은 버리고 후보만 넣는다 — 엉뚱한 글자를 지우지 않는다.
|
||
const acceptPrefix = this._acceptPrefix()
|
||
const correction = this._correction ? alignCorrectionToPrefix(acceptPrefix, this._correction) : null
|
||
const basePrefix = correction
|
||
? acceptPrefix.slice(0, acceptPrefix.length - correction.from.length) + correction.to
|
||
: acceptPrefix
|
||
const text = (correction?.to ?? '') + joinSuggestion(basePrefix, candidate.text, candidate.joint ?? 'separate')
|
||
const deleteCount = correction?.from.length ?? 0
|
||
const composing = this._lastContext?.isComposing === true
|
||
const appName = this._appName
|
||
const windowTitle = this._windowTitle
|
||
const targetWindow = this._windowHandle
|
||
const sessionRecordId = this._sessionRecordId
|
||
|
||
// 먼저 창을 닫고 생성을 멈춘다 — 수락은 즉시 반응해야 한다.
|
||
this.dismiss('accepted')
|
||
this.emit('state-changed', this.getState())
|
||
|
||
// 단축키로 수락했다면 사용자가 아직 Ctrl+Alt 를 쥐고 있다. 그대로 Ctrl+V 를 보내면
|
||
// 대상 앱에 Ctrl+Alt+V 가 들어가 붙여넣기가 되지 않는다(실측) — 뗄 때까지 기다린다.
|
||
const modifierWaitStartedAt = Date.now()
|
||
if (!(await waitForModifiersReleased())) {
|
||
logger.warn('수정자 키가 떼어지지 않은 채 제안을 삽입한다 (1.5초 초과)')
|
||
}
|
||
// "붙여넣기가 느리다" 신고 진단 — 수락 지연이 손 떼기 대기인지 삽입 자체인지 가른다.
|
||
logger.debug(`제안 수락: 수정자 키 떼기 대기 ${Date.now() - modifierWaitStartedAt}ms`)
|
||
|
||
// 붙여넣기(Ctrl+V)는 그 순간의 포그라운드 창으로 간다. 오버레이는 다음 스냅샷이 와야
|
||
// 닫히므로, 그사이 다른 앱으로 옮겨 간 뒤 수락하면 엉뚱한 창에 삽입됐다 — 세션을 만든
|
||
// 창이 아니면 삽입하지 않는다 (창을 알 수 없으면 기존처럼 진행한다).
|
||
if (targetWindow !== null) {
|
||
const currentWindow = this._foreground.currentWindowHandle()
|
||
if (currentWindow !== null && currentWindow !== targetWindow) {
|
||
logger.info(`제안 수락 취소: 포커스가 다른 창으로 옮겨 감 (app=${appName ?? '-'})`)
|
||
this._lastSkipReason = 'stale'
|
||
this.emit('state-changed', this.getState())
|
||
return { ok: false, reason: 'stale' }
|
||
}
|
||
}
|
||
|
||
// 삽입 직후의 텍스트 스냅샷 diff 가 이 텍스트를 "타이핑" 으로 다시 학습하지 않도록 알린다.
|
||
const cancelExpectedInsert = this._learning.expectProgrammaticInsert(text)
|
||
const method = configGet('insertMethod')
|
||
const insertMethod = method === 'keyboard' ? 'keyboard' : 'clipboard'
|
||
try {
|
||
if (deleteCount > 0) {
|
||
// 확정용 Space(+1)·백스페이스·붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다.
|
||
this._learning.expectProgrammaticKeys?.(deleteCount + (composing ? 2 : 0) + 2)
|
||
}
|
||
const result =
|
||
deleteCount > 0
|
||
? await getTextInsertService().replaceBeforeCaret(deleteCount, text, insertMethod, {
|
||
commitComposition: composing
|
||
})
|
||
: await getTextInsertService().insertText(text, insertMethod)
|
||
if (!result.success) {
|
||
cancelExpectedInsert()
|
||
logger.warn(`제안 삽입 실패 (method=${result.method}, len=${result.textLength})`)
|
||
return { ok: false, reason: 'generation-failed' }
|
||
}
|
||
} catch (error) {
|
||
cancelExpectedInsert()
|
||
logger.warn(`제안 삽입 예외: ${error instanceof Error ? error.message : String(error)}`)
|
||
return { ok: false, reason: 'generation-failed' }
|
||
}
|
||
|
||
logger.info(
|
||
`제안 수락: ${text.length}자 삽입${deleteCount > 0 ? ` (오타 교정 포함, ${deleteCount}자 교체)` : ''} ` +
|
||
`(method=${insertMethod}, app=${appName ?? '-'})`
|
||
)
|
||
// 수락 뒤 이어 쳐서 멈추면 바로 다음 제안이 떠야 한다 — 방금 세션의 요청 간격에 걸리지 않게 푼다.
|
||
this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs)
|
||
// 이력은 후보 원문으로 기록돼 있다 — 구분 공백이 붙은 삽입 문자열로는 찾지 못한다.
|
||
// 세션 행을 알면 그 행을 수락으로 표시한다 — 텍스트로 찾으면 로컬 기억의 2번째 이후 후보는
|
||
// 행이 없어 사라지거나 같은 문구의 옛 행(다른 앱·다른 날)이 수락으로 잡혔다.
|
||
if (sessionRecordId && this._repository.markSessionAccepted) {
|
||
this._repository.markSessionAccepted(sessionRecordId, candidate.text)
|
||
} else {
|
||
this._repository.markAccepted(candidate.text)
|
||
}
|
||
// 수락한 문장은 사용자 문체의 확실한 표본이다 (학습 동의 시에만 저장됨).
|
||
this._learning.recordAccepted(candidate.text, { appName, windowTitle })
|
||
return { ok: true }
|
||
}
|
||
|
||
/**
|
||
* 수락 시 이음새 판단에 쓸 커서 앞 원문.
|
||
*
|
||
* 세션 접두는 뒤 공백을 걷어낸 값이라, 사용자가 멈추기 전에 공백을 쳤는지 알 수 없다.
|
||
* 최신 문맥이 여전히 이 세션의 것이면(세션 규칙) 그 원문을, 아니면 세션 접두를 쓴다.
|
||
*/
|
||
private _acceptPrefix(): string {
|
||
const latest = this._lastContext
|
||
if (latest && matchesSessionPrefix(this._generatedForPrefix, latest.prefix)) return latest.prefix
|
||
return this._generatedForPrefix
|
||
}
|
||
|
||
getHistory(limit = 50): SuggestionHistoryEntry[] {
|
||
return this._repository.list(limit)
|
||
}
|
||
|
||
// ── 내부 ──────────────────────────────────────────────
|
||
|
||
private readPolicyConfig(): PolicyConfig {
|
||
return {
|
||
triggerDelayMs: Math.max(
|
||
SUGGESTION_DEFAULTS.minTriggerDelayMs,
|
||
configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs
|
||
),
|
||
minPrefixChars: configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars,
|
||
maxRequestsPerMinute:
|
||
Math.min(
|
||
configGet('suggestionMaxRequestsPerMinute') || SUGGESTION_DEFAULTS.maxRequestsPerMinute,
|
||
30
|
||
),
|
||
dailyBudget: configGet('suggestionDailyBudget') || SUGGESTION_DEFAULTS.dailyBudget,
|
||
maxCandidates: SUGGESTION_DEFAULTS.maxCandidates,
|
||
maxChars: SUGGESTION_MAX_OUTPUT_CHARS,
|
||
// 터미널은 셸 프롬프트라 문장 제안이 의미 없다 — 사용자 목록과 무관하게 뺀다.
|
||
// 터미널도 제안한다(입력 줄만 추출). 학습 제외는 InputTelemetryService 가 따로 한다.
|
||
excludedApps: [...configGet('inputExcludedApps')]
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 제안 이력 기록 — 접두(사용자가 친 글 원문)는 학습 동의가 있고 학습 제외 앱이 아닐 때만
|
||
* 남긴다(core shouldPersistSuggestionPrefix). 그 밖에는 빈 문자열로 남겨 개수·수락률만 유지한다.
|
||
*/
|
||
private _recordSuggestion(input: Omit<SuggestionRecordInput, 'appName'>): void {
|
||
const persistPrefix = shouldPersistSuggestionPrefix({
|
||
learnTypedText: configGet('inputLearnTypedText') === true,
|
||
appName: this._appName
|
||
})
|
||
const id = this._repository.record({ ...input, prefix: persistPrefix ? input.prefix : '', appName: this._appName })
|
||
this._sessionRecordId = typeof id === 'string' ? id : null
|
||
}
|
||
|
||
/** 테스트/진단 — 현재 앱이 제외 대상인지. */
|
||
isAppAllowed(appName: string | null): boolean {
|
||
if (!appName) return true
|
||
return !isAppExcluded(appName, configGet('inputExcludedApps'))
|
||
}
|
||
|
||
dispose(): void {
|
||
this.dismiss('disabled')
|
||
this._cancelWarmUp()
|
||
this.removeAllListeners()
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 스트리밍 중간 텍스트 정제 — 번호/불릿/따옴표와 지시문 누출을 화면에 잠깐
|
||
* 보여주지 않도록 줄 단위로 다듬는다.
|
||
*/
|
||
function sanitizePartial(raw: string): string {
|
||
const lines = raw
|
||
.split(/\r?\n/u)
|
||
.map((line) => sanitizeSuggestionLine(line, SUGGESTION_MAX_OUTPUT_CHARS) ?? line.trim())
|
||
.filter((line) => line.length > 0)
|
||
return lines.slice(0, 2).join(' ').slice(0, SUGGESTION_MAX_OUTPUT_CHARS)
|
||
}
|
||
|
||
/** 입력 텔레메트리가 맥락을 보낼 수 있는 상태인가 (수집 동의 + 일시정지 아님). */
|
||
export function hasInputContextConsent(): boolean {
|
||
return configGet('inputTelemetryEnabled') === true && configGet('inputTelemetryPaused') !== true
|
||
}
|
||
|
||
let instance: SuggestionService | null = null
|
||
|
||
export function getSuggestionService(): SuggestionService {
|
||
if (!instance) instance = new SuggestionService()
|
||
return instance
|
||
}
|
||
|
||
export function resetSuggestionServiceForTests(): void {
|
||
instance?.dispose()
|
||
instance = null
|
||
}
|