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
|
|
@ -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)는 그 순간의 포그라운드 창으로 간다. 오버레이는 다음 스냅샷이 와야
|
||||
// 닫히므로, 그사이 다른 앱으로 옮겨 간 뒤 수락하면 엉뚱한 창에 삽입됐다 — 세션을 만든
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue