fix(suggestion): place overlay in DIPs, size it to content, and harden suggestion sessions

This commit is contained in:
Yun Chan 2026-09-28 02:16:15 +09:00
parent 75e053d72f
commit 9e5b94ced2
18 changed files with 2178 additions and 558 deletions

View file

@ -14,26 +14,29 @@ import { EventEmitter } from 'events'
import {
SUGGESTION_DEFAULTS,
SUGGESTION_MAX_OUTPUT_CHARS,
buildLocalSuggestionCandidates,
buildLocalSuggestionCandidateEntries,
decideInFlightGeneration,
decideSuggestion,
decideSuggestionRefresh,
decideSuggestionStep,
isAppExcluded,
joinSuggestion,
matchesSessionPrefix,
normalizeRequestPrefix,
normalizeSessionPrefix,
parseSuggestionCandidates,
sanitizeSuggestionLine,
selectPhraseHints,
shouldPersistSuggestionPrefix,
isTerminalApp,
extractTerminalPromptPrefix,
type AnchorKind,
type PhysicalRect,
type SuggestionCandidate,
type SuggestionPolicyInput,
type SuggestionProvenance,
type SuggestionSkipReason,
type SuggestionState,
type SuggestionStep,
type UiRect
type SuggestionStep
} from '@d3ro/core/input-intelligence'
import { configGet, configSet } from './ConfigService'
import { getLogger } from './LoggerService'
@ -143,7 +146,8 @@ const WARM_UP_FAILURE_BACKOFF_MS = SUGGESTION_DEFAULTS.minIntervalMs
export class SuggestionService extends EventEmitter {
private _candidates: SuggestionCandidate[] = []
private _activeIndex = 0
private _anchor: UiRect | null = null
/** 물리 픽셀 그대로 보관한다 — DIP 변환은 창 배치(WindowManager) 한 곳에서만 한다. */
private _anchor: PhysicalRect | null = null
/** anchor 가 케어렛인지 요소 전체인지 — 오버레이가 배치 전략을 고르는 근거 */
private _anchorKind: AnchorKind = null
private _appName: string | null = null
@ -472,7 +476,9 @@ export class SuggestionService extends EventEmitter {
userDismissedQuiet: now < this._userDismissedUntil,
lastRequestedPrefix: this._lastRequestedPrefix,
modelWarm: this._warmth.isWarm(model, now),
warmUpBackoff: this._warmth.isBackingOff(model, now, WARM_UP_FAILURE_BACKOFF_MS)
warmUpBackoff: this._warmth.isBackingOff(model, now, WARM_UP_FAILURE_BACKOFF_MS),
// 서버가 없을 때 "준비 중" 은 실제 준비 작업(워밍업 루프)이 돌 때만 보여준다.
modelStarting: this._warmUpPromise !== null
})
this._executeStep(step, context, config, now)
}
@ -541,8 +547,9 @@ export class SuggestionService extends EventEmitter {
this._showWarming(context)
break
case 'show-warming':
// 모델이 아직 안 떠 있으면 "준비 중" 을 보여준다 — 아무 반응이 없으면
// 사용자는 기능이 죽었다고 판단한다(첫 실행에서 실제로 그랬다).
// 워밍업 루프가 서버를 기다리는 중이면 "준비 중" 을 보여준다 — 아무 반응이 없으면
// 사용자는 기능이 죽었다고 판단한다(첫 실행에서 실제로 그랬다). 준비 작업이 없으면
// core 가 'record' 를 준다(끝나지 않는 스피너 방지).
this._showWarming(context)
break
}
@ -689,13 +696,16 @@ export class SuggestionService extends EventEmitter {
if (!this._isCurrentFallbackContext(prefix, context, token)) return false
const trimmedPrefix = normalizeSessionPrefix(prefix)
const localMemory = memory ?? this._collectMemoryHints(trimmedPrefix, context.appName)
const candidates = buildLocalSuggestionCandidates(trimmedPrefix, localMemory, maxCandidates, maxChars)
if (candidates.length === 0) return false
const entries = buildLocalSuggestionCandidateEntries(trimmedPrefix, localMemory, maxCandidates, maxChars)
if (entries.length === 0) return false
this._partialText = ''
this._generating = false
this._warmingUp = false
this._candidates = candidates.map((text, index) => ({ text, rank: index }))
// 단어 중간에서 이어지는 나머지(예: "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._activeIndex = 0
this._anchor = context.anchor
this._anchorKind = context.anchorKind
@ -703,7 +713,7 @@ export class SuggestionService extends EventEmitter {
this._windowTitle = context.windowTitle
this._windowHandle = context.windowHandle ?? null
this._generatedForPrefix = trimmedPrefix
this._targetTotal = candidates.length
this._targetTotal = entries.length
this._lastSkipReason = null
this._lastLatencyMs = latencyMs
this._provenance = {
@ -715,15 +725,15 @@ export class SuggestionService extends EventEmitter {
}
this._recordSuggestion({
prefix: trimmedPrefix,
text: candidates[0],
text: entries[0].text,
model: 'local-memory',
latencyMs,
candidateCount: candidates.length
candidateCount: entries.length
})
this._armVisibleTtl()
this.emit('updated', this.getState())
this.emit('state-changed', this.getState())
logger.info(`로컬 기억 제안 ${candidates.length}개 생성`)
logger.info(`로컬 기억 제안 ${entries.length}개 생성`)
return true
}
@ -929,6 +939,18 @@ export class SuggestionService extends EventEmitter {
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 candidates = parseSuggestionCandidates(raw, trimmedPrefix, 1, maxChars)
if (candidates.length === 0) {
this._lastSkipReason = 'generation-failed'
@ -1208,7 +1230,8 @@ export class SuggestionService extends EventEmitter {
private _abortStaleGeneration(currentPrefix: string): void {
if (!this._inFlight || !this._abort || this._abort.signal.aborted) return
const refresh = decideSuggestionRefresh(this._lastRequestedPrefix, currentPrefix)
// 세션 규칙과 같은 기준 — 요청 뒤 한 글자라도 자라면 결과는 도착하자마자 stale 이다.
const refresh = decideInFlightGeneration(this._lastRequestedPrefix, currentPrefix)
if (refresh === 'keep') return
this._generationToken += 1
@ -1327,7 +1350,9 @@ export class SuggestionService extends EventEmitter {
logger.info(`제안 수락 무시: 표시 중인 후보 없음 (index=${index ?? 'active'})`)
return { ok: false, reason: 'already-visible' }
}
const text = candidate.text
// 후보는 정제 과정에서 앞 공백을 잃는다 — 커서 앞 원문의 마지막 글자를 보고 구분 공백을
// 붙인다(joinSuggestion). 세션을 닫기 전에(dismiss 가 세션 접두를 지운다) 계산한다.
const text = joinSuggestion(this._acceptPrefix(), candidate.text, candidate.joint ?? 'separate')
const appName = this._appName
const windowTitle = this._windowTitle
const targetWindow = this._windowHandle
@ -1375,12 +1400,25 @@ export class SuggestionService extends EventEmitter {
}
logger.info(`제안 수락: ${text.length}자 삽입 (method=${method === 'keyboard' ? 'keyboard' : 'clipboard'}, app=${appName ?? '-'})`)
this._repository.markAccepted(text)
// 이력은 후보 원문으로 기록돼 있다 — 구분 공백이 붙은 삽입 문자열로는 찾지 못한다.
this._repository.markAccepted(candidate.text)
// 수락한 문장은 사용자 문체의 확실한 표본이다 (학습 동의 시에만 저장됨).
this._learning.recordAccepted(text, { appName, windowTitle })
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)
}
@ -1408,8 +1446,16 @@ export class SuggestionService extends EventEmitter {
}
}
/**
* 제안 이력 기록 — 접두(사용자가 친 글 원문)는 학습 동의가 있고 학습 제외 앱이 아닐 때만
* 남긴다(core shouldPersistSuggestionPrefix). 그 밖에는 빈 문자열로 남겨 개수·수락률만 유지한다.
*/
private _recordSuggestion(input: Omit<SuggestionRecordInput, 'appName'>): void {
this._repository.record({ ...input, appName: this._appName })
const persistPrefix = shouldPersistSuggestionPrefix({
learnTypedText: configGet('inputLearnTypedText') === true,
appName: this._appName
})
this._repository.record({ ...input, prefix: persistPrefix ? input.prefix : '', appName: this._appName })
}
/** 테스트/진단 — 현재 앱이 제외 대상인지. */