feat(desktop): propose typo fixes inside the suggestion popup and make suggestions snappier
While suggestions are on, typos are no longer replaced silently. The popup shows the fix next to the candidate and applies it only when the candidate is accepted. The per-minute request cap rises from 6 to 20 so suggestions keep appearing after accepting one and continuing to type.
This commit is contained in:
parent
d63854db67
commit
f5ae4c8c04
38 changed files with 1239 additions and 660 deletions
|
|
@ -12,6 +12,7 @@
|
|||
|
||||
import { EventEmitter } from 'events'
|
||||
import {
|
||||
COMPOSING_IDLE_MULTIPLIER,
|
||||
SUGGESTION_DEFAULTS,
|
||||
SUGGESTION_MAX_OUTPUT_CHARS,
|
||||
buildLocalSuggestionCandidateEntries,
|
||||
|
|
@ -33,6 +34,7 @@ import {
|
|||
type AnchorKind,
|
||||
type PhysicalRect,
|
||||
type SuggestionCandidate,
|
||||
type SuggestionCorrection,
|
||||
type SuggestionPolicyInput,
|
||||
type SuggestionProvenance,
|
||||
type SuggestionSkipReason,
|
||||
|
|
@ -76,6 +78,31 @@ export interface SuggestionLearningPort {
|
|||
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). */
|
||||
|
|
@ -98,6 +125,7 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps {
|
|||
},
|
||||
learning: {
|
||||
expectProgrammaticInsert: (text) => getInputTelemetryService().expectProgrammaticInsert(text),
|
||||
expectProgrammaticKeys: (count) => getInputTelemetryService().expectProgrammaticKeys(count),
|
||||
recordAccepted: (text, meta) =>
|
||||
getInputTelemetryService().recordExternalText(text, { ...meta, source: 'suggestion' })
|
||||
}
|
||||
|
|
@ -205,6 +233,14 @@ interface ModelRequest {
|
|||
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
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -281,6 +317,24 @@ export class SuggestionService extends EventEmitter {
|
|||
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
|
||||
|
|
@ -389,7 +443,7 @@ export class SuggestionService extends EventEmitter {
|
|||
modelId: this.resolveModel(),
|
||||
modelAvailable: getLocalLLMService().isAvailable(),
|
||||
visible: this.isVisible,
|
||||
generating: this._generating,
|
||||
generating: this._generating || this._pending,
|
||||
warmingUp: this._warmingUp,
|
||||
partialText: this._partialText || null,
|
||||
candidates: [...this._candidates],
|
||||
|
|
@ -411,10 +465,16 @@ export class SuggestionService extends EventEmitter {
|
|||
telemetryEnabled: configGet('inputTelemetryEnabled') === true,
|
||||
overlayInteractive: configGet('suggestionOverlayInteractive') !== false,
|
||||
typoAutoCorrect: configGet('typoAutoCorrectEnabled') !== false,
|
||||
provenance: this._provenance
|
||||
provenance: this._provenance,
|
||||
correction: this._correction
|
||||
}
|
||||
}
|
||||
|
||||
/** 제안 창에 오타 교정을 함께 내놓을 포트를 연결한다 (bootstrap). null 이면 교정 없이 제안만 한다. */
|
||||
setTypoProposer(proposer: SuggestionTypoProposer | null): void {
|
||||
this._typoProposer = proposer
|
||||
}
|
||||
|
||||
/** 제안 전용 모델 (설정 없으면 기본 LLM 모델). */
|
||||
resolveModel(): string | null {
|
||||
const dedicated = configGet('suggestionModelId')
|
||||
|
|
@ -605,9 +665,76 @@ export class SuggestionService extends EventEmitter {
|
|||
// 서버가 없을 때 "준비 중" 은 실제 준비 작업(워밍업 루프)이 돌 때만 보여준다.
|
||||
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':
|
||||
|
|
@ -877,9 +1004,9 @@ export class SuggestionService extends EventEmitter {
|
|||
* 미리 넣어 그 글자 바로 뒤부터 쓰게 한다. 모르는 모델이면 예전 지시형 프롬프트를 쓴다.
|
||||
* 두 경로 모두 같은 문맥(문서 첫머리·사실, 이 창의 앞 글, 개인 그래프)을 받는다.
|
||||
*
|
||||
* `preferInstruct`: 다음 문장 모드의 채우기 후보는 지시형을 섞는다. prefill 은 분포가 뾰족해
|
||||
* 온도를 올려도 첫 후보와 같은 문장이 반복됐고, 지시형은 "이미 제안한 문장" 목록을 따라 다른
|
||||
* 내용을 낸다(실측). 마저 쓰기 모드에서는 지시형이 새 문장을 시작해 버려 섞지 않는다.
|
||||
* 채우기 후보도 prefill 로만 만든다. 예전엔 다양성을 위해 다음 문장 모드에서 지시형을 섞었는데,
|
||||
* 지시형 gemma 는 사용자 글에 "대답" 했다(실측 2026-10-17 이력: "혹시 어떤 기능을 염두에 두고 계신지
|
||||
* 설명해 주실 수 있을까요?" — 사용자 신고 "내가 쓴 것에 대한 응답만 나온다"). 후보가 덜 다양한 편이 낫다.
|
||||
*/
|
||||
private _buildModelRequest(
|
||||
model: string,
|
||||
|
|
@ -887,7 +1014,7 @@ export class SuggestionService extends EventEmitter {
|
|||
context: TypingContext,
|
||||
memory: LocalMemoryContext,
|
||||
maxChars: number,
|
||||
options: { avoidCandidates?: readonly string[]; preferInstruct?: boolean } = {}
|
||||
options: { avoidCandidates?: readonly string[] } = {}
|
||||
): ModelRequest {
|
||||
const now = Date.now()
|
||||
const recentWrites = getInputTelemetryService()
|
||||
|
|
@ -919,8 +1046,7 @@ export class SuggestionService extends EventEmitter {
|
|||
assistantPrefix: prompt.assistantPrefix ?? ''
|
||||
})
|
||||
|
||||
const instruct = options.preferInstruct === true && prompt.writing.mode === 'next-sentence'
|
||||
if (rawPrompt !== null && !instruct) {
|
||||
if (rawPrompt !== null) {
|
||||
const written = splitSentences(context.documentBefore ?? prefix)
|
||||
const extract = (raw: string) =>
|
||||
extractContinuation(raw, {
|
||||
|
|
@ -931,10 +1057,35 @@ export class SuggestionService extends EventEmitter {
|
|||
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: rawChatStopSequences(model),
|
||||
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' }
|
||||
|
|
@ -1029,6 +1180,8 @@ export class SuggestionService extends EventEmitter {
|
|||
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
|
||||
|
|
@ -1118,6 +1271,8 @@ export class SuggestionService extends EventEmitter {
|
|||
// 후보가 오기 전에 빈 화면으로 기다리게 하지 않는다 — 즉시 자리를 잡고
|
||||
// "생성 중" 을 보여준 뒤 내용으로 채운다. 실측 5초 지연에서 특히 중요하다.
|
||||
this._candidates = []
|
||||
this._correction = null
|
||||
this._promptContext = null
|
||||
this._sessionRecordId = null
|
||||
this._activeIndex = 0
|
||||
this._anchor = context.anchor
|
||||
|
|
@ -1142,19 +1297,35 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
// 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장,
|
||||
// (2) follows/용어공유 관계로 끌어온 관련 문장.
|
||||
const memory = this._collectMemoryHints(trimmedPrefix, context.appName)
|
||||
const continuationHints = memory.continuationHints
|
||||
// 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자
|
||||
// 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다.
|
||||
const request = this._buildModelRequest(model, trimmedPrefix, context, memory, maxChars)
|
||||
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 temperature = attempt === 0 ? SUGGESTION_DEFAULTS.temperature : FILL_TEMPERATURE
|
||||
const raw = await this._streamModel(request, model, temperature, abort.signal, (partial) => {
|
||||
const raw = await this._streamModel(active, model, temperature, abort.signal, (partial) => {
|
||||
// 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다.
|
||||
// IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다.
|
||||
this._partialText = partial
|
||||
|
|
@ -1165,15 +1336,25 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
})
|
||||
if (abort.signal.aborted) break
|
||||
parsed = request.parse(raw)
|
||||
parsed = active.parse(raw)
|
||||
if (!parsed.candidate) {
|
||||
// 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보.
|
||||
logger.debug(`제안 정제 실패: ${describeRawOutput(raw, request.raw)}`)
|
||||
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
|
||||
}
|
||||
if (parsed.candidate || !parsed.rejected?.startsWith('unsupported-facts')) break
|
||||
logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`)
|
||||
this._partialText = ''
|
||||
}
|
||||
spacedPreferred = active !== request
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
|
|
@ -1264,6 +1445,7 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
|
||||
const first = parsed.candidate
|
||||
this._failedPrefix = first ? '' : this._lastRequestedPrefix
|
||||
if (!first) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`)
|
||||
|
|
@ -1290,6 +1472,9 @@ export class SuggestionService extends EventEmitter {
|
|||
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
|
||||
|
|
@ -1301,7 +1486,7 @@ export class SuggestionService extends EventEmitter {
|
|||
this._lastSkipReason = null
|
||||
this._provenance = {
|
||||
mode: 'local-model',
|
||||
continuationCount: continuationHints.length,
|
||||
continuationCount: memory.continuationHints.length,
|
||||
relatedCount: memory.relatedHints.length + memory.followUpHints.length,
|
||||
phraseCount: memory.phraseHints.length,
|
||||
appPhraseCount: memory.appPhraseCount
|
||||
|
|
@ -1327,6 +1512,28 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/** 이 문맥에 함께 내놓을 오타 교정 — 포트가 없거나 실패하면 교정 없이 간다. */
|
||||
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개) ────────────
|
||||
|
||||
/**
|
||||
|
|
@ -1337,6 +1544,7 @@ export class SuggestionService extends EventEmitter {
|
|||
* 소비하지 않는다(설계). 시간 초과된 채우기 요청은 조용히 다음으로 넘어간다.
|
||||
*/
|
||||
private async _runFillLoop(token: number, context: TypingContext, maxChars: number): Promise<void> {
|
||||
await this._proposeLateCorrection(token, context)
|
||||
let consecutiveEmpty = 0
|
||||
while (
|
||||
token === this._generationToken &&
|
||||
|
|
@ -1354,6 +1562,28 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첫 후보를 보여 준 뒤 모델 오타 검사를 한 번 더 한다 — 낱자 없는 오타("회으에서")는 첫 요청 전에
|
||||
* 묻지 않는다(멈출 때마다 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()
|
||||
|
|
@ -1371,14 +1601,13 @@ export class SuggestionService extends EventEmitter {
|
|||
// 세션이 고정한 접두를 쓴다 — context.prefix 는 그사이 바뀌었을 수 있지만,
|
||||
// 바뀌었다면 이미 위(handleTypingContext)에서 세션이 dismiss 되어 토큰이
|
||||
// 달라져 있으므로 이 루프는 다음 체크에서 멈춘다.
|
||||
const prefix = this._generatedForPrefix
|
||||
// 교정이 있으면 모델에는 고친 글을 보여 준다 (첫 후보와 같은 문맥).
|
||||
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 request = this._buildModelRequest(model, prefix, context, memory, maxChars, {
|
||||
avoidCandidates,
|
||||
preferInstruct: this._candidates.length % 2 === 1
|
||||
})
|
||||
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
|
||||
|
||||
|
|
@ -1630,7 +1859,8 @@ export class SuggestionService extends EventEmitter {
|
|||
this._userDismissedUntil = Date.now() + SUGGESTION_DEFAULTS.userDismissQuietMs
|
||||
logger.info(`사용자가 제안을 닫음 — ${SUGGESTION_DEFAULTS.userDismissQuietMs}ms 동안 재표시하지 않는다`)
|
||||
}
|
||||
const wasVisible = this.isPresentationActive
|
||||
const wasVisible = this.isPresentationActive || this._pending
|
||||
this._clearPending(false)
|
||||
// 진행 중이던 생성을 무효화한다 (닫았는데 잠시 뒤 결과가 다시 뜨는 것을 막는다).
|
||||
this._generationToken += 1
|
||||
this._clearVisibleTtl()
|
||||
|
|
@ -1645,6 +1875,8 @@ export class SuggestionService extends EventEmitter {
|
|||
this._targetTotal = 0
|
||||
this._provenance = null
|
||||
this._sessionRecordId = null
|
||||
this._correction = null
|
||||
this._promptContext = null
|
||||
this._lastSkipReason = reason
|
||||
this._abort?.abort()
|
||||
this._abort = null
|
||||
|
|
@ -1685,7 +1917,16 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
// 후보는 정제 과정에서 앞 공백을 잃는다 — 커서 앞 원문의 마지막 글자를 보고 구분 공백을
|
||||
// 붙인다(joinSuggestion). 세션을 닫기 전에(dismiss 가 세션 접두를 지운다) 계산한다.
|
||||
const text = joinSuggestion(this._acceptPrefix(), candidate.text, candidate.joint ?? 'separate')
|
||||
// 교정이 있으면 커서 앞 오타 구간을 지우고 고친 글 + 후보를 함께 넣는다. 그사이 원문 끝이 달라졌으면
|
||||
// (IME 마지막 글자 교체 등) 교정은 버리고 후보만 넣는다 — 엉뚱한 글자를 지우지 않는다.
|
||||
const acceptPrefix = this._acceptPrefix()
|
||||
const correction = this._correction && acceptPrefix.endsWith(this._correction.from) ? 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
|
||||
|
|
@ -1720,11 +1961,18 @@ export class SuggestionService extends EventEmitter {
|
|||
// 삽입 직후의 텍스트 스냅샷 diff 가 이 텍스트를 "타이핑" 으로 다시 학습하지 않도록 알린다.
|
||||
const cancelExpectedInsert = this._learning.expectProgrammaticInsert(text)
|
||||
const method = configGet('insertMethod')
|
||||
const insertMethod = method === 'keyboard' ? 'keyboard' : 'clipboard'
|
||||
try {
|
||||
const result = await getTextInsertService().insertText(
|
||||
text,
|
||||
method === 'keyboard' ? 'keyboard' : 'clipboard'
|
||||
)
|
||||
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})`)
|
||||
|
|
@ -1736,7 +1984,12 @@ export class SuggestionService extends EventEmitter {
|
|||
return { ok: false, reason: 'generation-failed' }
|
||||
}
|
||||
|
||||
logger.info(`제안 수락: ${text.length}자 삽입 (method=${method === 'keyboard' ? 'keyboard' : 'clipboard'}, app=${appName ?? '-'})`)
|
||||
logger.info(
|
||||
`제안 수락: ${text.length}자 삽입${deleteCount > 0 ? ` (오타 교정 포함, ${deleteCount}자 교체)` : ''} ` +
|
||||
`(method=${insertMethod}, app=${appName ?? '-'})`
|
||||
)
|
||||
// 수락 뒤 이어 쳐서 멈추면 바로 다음 제안이 떠야 한다 — 방금 세션의 요청 간격에 걸리지 않게 푼다.
|
||||
this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs)
|
||||
// 이력은 후보 원문으로 기록돼 있다 — 구분 공백이 붙은 삽입 문자열로는 찾지 못한다.
|
||||
// 세션 행을 알면 그 행을 수락으로 표시한다 — 텍스트로 찾으면 로컬 기억의 2번째 이후 후보는
|
||||
// 행이 없어 사라지거나 같은 문구의 옛 행(다른 앱·다른 날)이 수락으로 잡혔다.
|
||||
|
|
@ -1778,7 +2031,7 @@ export class SuggestionService extends EventEmitter {
|
|||
maxRequestsPerMinute:
|
||||
Math.min(
|
||||
configGet('suggestionMaxRequestsPerMinute') || SUGGESTION_DEFAULTS.maxRequestsPerMinute,
|
||||
12
|
||||
30
|
||||
),
|
||||
dailyBudget: configGet('suggestionDailyBudget') || SUGGESTION_DEFAULTS.dailyBudget,
|
||||
maxCandidates: SUGGESTION_DEFAULTS.maxCandidates,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue