feat(desktop): built-in Han/Eng layout auto-switching, terminal/Vim support, and Unicode input
This commit is contained in:
parent
1da04b9e46
commit
a3ac44da2b
109 changed files with 8234 additions and 242 deletions
|
|
@ -13,6 +13,7 @@
|
|||
import { EventEmitter } from 'events'
|
||||
import {
|
||||
COMPOSING_IDLE_MULTIPLIER,
|
||||
isAppScopedLearning,
|
||||
SUGGESTION_DEFAULTS,
|
||||
SUGGESTION_MAX_OUTPUT_CHARS,
|
||||
buildLocalSuggestionCandidateEntries,
|
||||
|
|
@ -43,6 +44,9 @@ import {
|
|||
} from '@d3ro/core/input-intelligence'
|
||||
import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template'
|
||||
import { buildQueryTerms, splitSentences } from '@d3ro/core/personal-graph'
|
||||
import { copiesContext } from '@d3ro/core/suggestion-confidence'
|
||||
import { splitFirstWord } from '@d3ro/core/suggestion-text'
|
||||
import { predictPersonalContinuation } from '@d3ro/core/personal-ngram'
|
||||
import { analyzeWritingContext, findUnsupportedFacts } from '@d3ro/core/writing-context'
|
||||
import { alignCorrectionToPrefix } from '@d3ro/core/typo-correction'
|
||||
import { configGet, configSet } from './ConfigService'
|
||||
|
|
@ -52,7 +56,7 @@ 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 { prepareModifiersForPaste } from './modifier-state'
|
||||
import {
|
||||
createSqliteSuggestionRepository,
|
||||
type SuggestionHistoryEntry,
|
||||
|
|
@ -61,6 +65,7 @@ import {
|
|||
} from './SuggestionRepository'
|
||||
import { SuggestionBudget } from './suggestion/SuggestionBudget'
|
||||
import { ModelWarmTracker } from './suggestion/ModelWarmTracker'
|
||||
import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex'
|
||||
import { LOCAL_LLM_KEEP_ALIVE, LOCAL_LLM_KEEP_ALIVE_MS } from './llm/model-residency'
|
||||
import { getForegroundWindowInfo } from '../utils/win32-foreground'
|
||||
|
||||
|
|
@ -188,6 +193,25 @@ function relatedPromptHints(memory: LocalMemoryContext): string[] {
|
|||
const TERMINAL_TYPING_STEP_CHARS = 8
|
||||
|
||||
/** 모델 출력의 모양 (길이·첫 글자 종류·줄 수) — 로그용, 내용은 담지 않는다. */
|
||||
/** 공백·끝 문장부호를 무시하고 같은 후보인가 */
|
||||
function sameCandidateText(a: string, b: string): boolean {
|
||||
const norm = (text: string) => text.replace(/\s+/gu, ' ').replace(/[.!?。!?…,]+$/u, '').trim()
|
||||
return norm(a) === norm(b)
|
||||
}
|
||||
|
||||
/** 접두 끝 글자 종류 — 진단용(글 내용은 남기지 않는다). */
|
||||
function describePrefixEnd(prefix: string): string {
|
||||
if (/\s$/u.test(prefix)) return 'space'
|
||||
const last = [...prefix].pop() ?? ''
|
||||
if (!last) return 'empty'
|
||||
if (/[\u3131-\u318e]/u.test(last)) return 'jamo'
|
||||
if (/[가-힣]/u.test(last)) return 'hangul'
|
||||
if (/[.!?。!?…~]/u.test(last)) return 'sentence-end'
|
||||
if (/[,;:]/u.test(last)) return 'comma'
|
||||
if (/[A-Za-z0-9]/u.test(last)) return 'ascii'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
function describeRawOutput(raw: string, prefill: boolean): string {
|
||||
const first = raw.charAt(0)
|
||||
const kind =
|
||||
|
|
@ -212,6 +236,8 @@ function commonPrefixLength(a: string, b: string): number {
|
|||
|
||||
/** 이 길이를 넘는 모델 출력은 버린다 (스트리밍 폭주 방지) */
|
||||
const MAX_RAW_OUTPUT_CHARS = 1200
|
||||
/** "제안 사항 없음" 을 보여 주는 시간 */
|
||||
const NO_SUGGESTION_NOTICE_MS = 1000
|
||||
|
||||
/**
|
||||
* 채우기 루프(2번째 이후 후보)의 온도.
|
||||
|
|
@ -304,6 +330,9 @@ export class SuggestionService extends EventEmitter {
|
|||
private _lastRequestedPrefix = ''
|
||||
/** 사용자가 X 로 닫은 뒤 재표시를 막는 시각 (ms) */
|
||||
private _userDismissedUntil = 0
|
||||
/** "제안 사항 없음" 알림 — 생성 중이 떠 있다가 후보 없이 끝났을 때 1초 */
|
||||
private _notice: 'no-suggestion' | null = null
|
||||
private _noticeTimer: ReturnType<typeof setTimeout> | null = null
|
||||
/** 수락 삽입이 진행 중이다(수정자 키 떼기 대기 포함) — 그사이 같은 글로 새 제안 창이 다시 뜨지 않게 한다. */
|
||||
private _acceptInFlight = false
|
||||
/** 스트리밍 누적 텍스트 */
|
||||
|
|
@ -464,6 +493,7 @@ export class SuggestionService extends EventEmitter {
|
|||
triggerDelayMs: this.readPolicyConfig().triggerDelayMs,
|
||||
minPrefixChars: this.readPolicyConfig().minPrefixChars,
|
||||
requestTimeoutMs: this.readTimeoutMs(),
|
||||
notice: this._notice,
|
||||
learnTypedText: configGet('inputLearnTypedText') === true,
|
||||
telemetryEnabled: configGet('inputTelemetryEnabled') === true,
|
||||
overlayInteractive: configGet('suggestionOverlayInteractive') !== false,
|
||||
|
|
@ -644,7 +674,8 @@ export class SuggestionService extends EventEmitter {
|
|||
*/
|
||||
handleTypingContext(input: TypingContext): void {
|
||||
// 터미널은 화면 전체가 읽힌다 — 입력 줄만 접두로 쓴다. 입력 줄이 없으면 빈 접두(제안 안 함).
|
||||
const context: TypingContext = isTerminalApp(input.appName) ? this._terminalContext(input) : input
|
||||
const context: TypingContext =
|
||||
isTerminalApp(input.appName) || input.terminalMode === true ? this._terminalContext(input) : input
|
||||
this._lastContext = context
|
||||
const now = Date.now()
|
||||
this._lastContextAt = now
|
||||
|
|
@ -938,7 +969,13 @@ export class SuggestionService extends EventEmitter {
|
|||
* (끝에서 치거나 지움) 커서는 입력 줄 끝이다. 중간을 고친 모양이면 다음 입력까지 막는다.
|
||||
*/
|
||||
private _terminalContext(input: TypingContext): TypingContext {
|
||||
const prompt = extractTerminalPromptPrefix(input.fullText ?? input.prefix)
|
||||
if (input.vimMode === 'normal' || input.vimMode === 'command') {
|
||||
this._lastTerminalPrompt = ''
|
||||
this._terminalPromptTyped = false
|
||||
return { ...input, prefix: '', documentBefore: null, caretReliable: false }
|
||||
}
|
||||
const extracted = extractTerminalPromptPrefix(input.fullText ?? input.prefix)
|
||||
const prompt = extracted ?? (input.terminalMode ? input.prefix : null)
|
||||
const previous = this._lastTerminalPrompt
|
||||
this._lastTerminalPrompt = prompt
|
||||
let typed: boolean
|
||||
|
|
@ -958,7 +995,12 @@ export class SuggestionService extends EventEmitter {
|
|||
typed = commonPrefixLength(previous, prompt) >= Math.min(previous.length, prompt.length) - 2
|
||||
}
|
||||
this._terminalPromptTyped = typed
|
||||
return { ...input, prefix: prompt ?? '', documentBefore: null, caretReliable: typed }
|
||||
return {
|
||||
...input,
|
||||
prefix: prompt ?? '',
|
||||
documentBefore: null,
|
||||
caretReliable: extracted !== null ? typed : typed && input.caretReliable !== false
|
||||
}
|
||||
}
|
||||
|
||||
/** 로컬 기억은 모델과 무관하다 — 같은 정책을 "모델 있음 · 표시 없음" 으로 평가한다. */
|
||||
|
|
@ -991,8 +1033,13 @@ export class SuggestionService extends EventEmitter {
|
|||
phrase.appName?.trim().toLowerCase() === requestedApp && phraseHints.includes(phrase.phrase)
|
||||
).length
|
||||
: 0
|
||||
// 앱 안에서만 배우는 앱(Agent Switchboard)은 공용 그래프에 그 앱 글이 없다 — 같은 앱 표본에서 이어 쓴 글을 찾는다.
|
||||
const scopedContinuations =
|
||||
appName && isAppScopedLearning(appName)
|
||||
? telemetry.findContinuationHints(writing.currentSentence || writing.lastSentence, 3, { appName })
|
||||
: []
|
||||
return {
|
||||
continuationHints: graphContext.continuations,
|
||||
continuationHints: [...scopedContinuations, ...graphContext.continuations].slice(0, 3),
|
||||
followUpHints: graphContext.followUps ?? [],
|
||||
relatedHints: graphContext.related,
|
||||
phraseHints,
|
||||
|
|
@ -1067,6 +1114,8 @@ export class SuggestionService extends EventEmitter {
|
|||
// 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다.
|
||||
const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource)
|
||||
if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` }
|
||||
// 화면·앞 글을 그대로 베낀 후보는 버린다 (실측 2026-10-25: 앞 대화 문장이 그대로 제안됨)
|
||||
if (copiesContext(continuation.text, prompt.factSource)) return { candidate: null, rejected: 'copied-context' }
|
||||
return {
|
||||
candidate:
|
||||
continuation.joint === 'attach'
|
||||
|
|
@ -1096,6 +1145,7 @@ export class SuggestionService extends EventEmitter {
|
|||
// 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다.
|
||||
const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource)
|
||||
if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` }
|
||||
if (copiesContext(continuation.text, prompt.factSource)) return { candidate: null, rejected: 'copied-context' }
|
||||
return {
|
||||
candidate:
|
||||
continuation.joint === 'attach'
|
||||
|
|
@ -1217,6 +1267,41 @@ export class SuggestionService extends EventEmitter {
|
|||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 내 기록(개인 n-gram)이 확신하는 이어쓰기 — 확실할 때만(core PERSONAL_NGRAM_SETTINGS). 없으면 null.
|
||||
* 단어 중간이면 그 어절의 나머지(수락 시 공백 없이 붙임), 아니면 다음 1~2어절.
|
||||
*/
|
||||
private _personalCandidate(context: TypingContext): SuggestionCandidate | null {
|
||||
const model = getPersonalNgramIndex().model()
|
||||
if (!model) return null
|
||||
const prediction = predictPersonalContinuation(model, this._lastContext?.prefix ?? context.prefix)
|
||||
if (!prediction || prediction.text.trim().length === 0) return null
|
||||
return prediction.joint === 'attach'
|
||||
? { text: prediction.text, rank: 0, joint: 'attach', source: 'personal' }
|
||||
: { text: prediction.text, rank: 0, source: 'personal' }
|
||||
}
|
||||
|
||||
/** 모델이 아무것도 못 냈어도 먼저 띄운 내 기록 후보가 있으면 그것으로 세션을 남긴다. */
|
||||
private _keepPersonalCandidate(trimmedPrefix: string, model: string, startedAt: number): boolean {
|
||||
const personal = this._candidates.find((candidate) => candidate.source === 'personal')
|
||||
if (!personal) return false
|
||||
this._candidates = [{ ...personal, rank: 0 }]
|
||||
this._targetTotal = 1
|
||||
this._generating = false
|
||||
this._filling = false
|
||||
this._recordSuggestion({
|
||||
prefix: trimmedPrefix,
|
||||
text: personal.text,
|
||||
model: 'personal-ngram',
|
||||
latencyMs: Date.now() - startedAt,
|
||||
candidateCount: 1
|
||||
})
|
||||
logger.debug(`모델 후보 없음 — 내 기록 후보만 남긴다 (model=${model})`)
|
||||
this.emit('updated', this.getState())
|
||||
this.emit('state-changed', this.getState())
|
||||
return true
|
||||
}
|
||||
|
||||
// ── 생성 ──────────────────────────────────────────────
|
||||
|
||||
private async _generate(
|
||||
|
|
@ -1265,6 +1350,7 @@ export class SuggestionService extends EventEmitter {
|
|||
this._abort = abort
|
||||
const token = (this._generationToken += 1)
|
||||
|
||||
this._clearNotice()
|
||||
this._inFlight = true
|
||||
this._generating = true
|
||||
this._lastRequestedPrefix = normalizeRequestPrefix(prefix)
|
||||
|
|
@ -1284,6 +1370,15 @@ export class SuggestionService extends EventEmitter {
|
|||
this._appName = context.appName
|
||||
this._windowTitle = context.windowTitle
|
||||
this._windowHandle = context.windowHandle ?? null
|
||||
// 내 기록이 확신하는 이어쓰기가 있으면 모델을 기다리지 않고 1번 후보로 먼저 띄운다 — 모델 후보는 뒤에 붙는다.
|
||||
// (2026-10-25: 모델을 "대신" 하면 제안이 너무 드물어졌다 — 이번엔 더하기만 한다)
|
||||
const instant = this._personalCandidate(context)
|
||||
if (instant) {
|
||||
this._candidates = [instant]
|
||||
this._generatedForPrefix = trimmedPrefix
|
||||
this._targetTotal = SUGGESTION_DEFAULTS.maxCandidatesTotal
|
||||
this._provenance = { mode: 'local-memory', continuationCount: 0, relatedCount: 0, phraseCount: 0, appPhraseCount: 0 }
|
||||
}
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
|
||||
|
|
@ -1301,7 +1396,10 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
// 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장,
|
||||
// (2) follows/용어공유 관계로 끌어온 관련 문장.
|
||||
const memoryStartedAt = Date.now()
|
||||
let memory = this._collectMemoryHints(trimmedPrefix, context.appName)
|
||||
// 지연 분해 진단 — 첫 후보까지의 시간이 기억 조회·오타 교정·모델 중 어디에 쓰이는지 남긴다.
|
||||
const timing = { memoryMs: Date.now() - memoryStartedAt, correctionMs: 0, modelMs: 0, attempts: 0 }
|
||||
let spacedPreferred = false
|
||||
let correction: SuggestionCorrection | null = null
|
||||
let promptContext = context
|
||||
|
|
@ -1310,7 +1408,9 @@ export class SuggestionService extends EventEmitter {
|
|||
try {
|
||||
// 오타가 있으면 고친 글로 이어 쓴다 — 낱자 잡음("안ㄴ뇽", "ㅇ다른")이 섞인 글을 그대로 주면 모델이
|
||||
// 그 잡음까지 되풀이했다(실측 이력: "아직 ㅇ" → "아직 ㅇ 기능도…"). 교정은 수락할 때만 적용한다.
|
||||
const correctionStartedAt = Date.now()
|
||||
correction = await this._proposeCorrection(context, abort.signal)
|
||||
timing.correctionMs = Date.now() - correctionStartedAt
|
||||
if (correction) {
|
||||
promptContext = applyCorrectionToContext(context, correction)
|
||||
memory = this._collectMemoryHints(normalizeSessionPrefix(promptContext.prefix), context.appName)
|
||||
|
|
@ -1328,7 +1428,9 @@ export class SuggestionService extends EventEmitter {
|
|||
// 지어낸 사실(원문에 없는 날짜·이름·숫자)로 버린 첫 후보는 같은 시간 제한 안에서 한 번 더 뽑는다.
|
||||
let active = request
|
||||
let temperature: number = SUGGESTION_DEFAULTS.temperature
|
||||
const modelStartedAt = Date.now()
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
timing.attempts = attempt + 1
|
||||
const raw = await this._streamModel(active, model, temperature, abort.signal, (partial) => {
|
||||
// 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다.
|
||||
// IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다.
|
||||
|
|
@ -1344,6 +1446,13 @@ export class SuggestionService extends EventEmitter {
|
|||
if (!parsed.candidate) {
|
||||
// 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보.
|
||||
logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`)
|
||||
if (raw.trim().length === 0) {
|
||||
// 첫 시도가 비는 조건을 찾는다(실사용 26% — 다시 뽑느라 ~250ms). 글 대신 끝 글자 종류만 남긴다.
|
||||
logger.debug(
|
||||
`제안 빈 출력 조건: app=${context.appName ?? '-'} end=${describePrefixEnd(promptContext.prefix)} ` +
|
||||
`comp=${context.isComposing === true} spaced=${active !== request}`
|
||||
)
|
||||
}
|
||||
}
|
||||
if (parsed.candidate) break
|
||||
if (raw.trim().length === 0 && active.spaced) {
|
||||
|
|
@ -1359,10 +1468,12 @@ export class SuggestionService extends EventEmitter {
|
|||
this._partialText = ''
|
||||
}
|
||||
spacedPreferred = active !== request
|
||||
timing.modelMs = Date.now() - modelStartedAt
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
this._noteFailure(error instanceof Error ? error.message : String(error))
|
||||
if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return
|
||||
if (
|
||||
this._publishLocalMemory(
|
||||
trimmedPrefix,
|
||||
|
|
@ -1402,6 +1513,7 @@ export class SuggestionService extends EventEmitter {
|
|||
// — 다음 멈춤은 같은 콜드 요청을 되풀이하지 말고 워밍업("준비 중")부터 한다.
|
||||
this._warmth.noteCold(model)
|
||||
this._noteFailure(`timeout ${timeoutMs}ms`)
|
||||
if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return
|
||||
if (
|
||||
this._publishLocalMemory(
|
||||
trimmedPrefix,
|
||||
|
|
@ -1453,6 +1565,7 @@ export class SuggestionService extends EventEmitter {
|
|||
if (!first) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`)
|
||||
if (this._keepPersonalCandidate(trimmedPrefix, model, startedAt)) return
|
||||
if (
|
||||
this._publishLocalMemory(
|
||||
trimmedPrefix,
|
||||
|
|
@ -1475,7 +1588,12 @@ export class SuggestionService extends EventEmitter {
|
|||
this._lastLatencyMs = latencyMs
|
||||
this._budget.noteSuccess()
|
||||
this._partialText = ''
|
||||
this._candidates = [{ ...first, rank: 0 }]
|
||||
// 먼저 띄운 내 기록 후보가 있으면 그 뒤에 붙인다(같은 글이면 하나만).
|
||||
const personal = this._candidates.find((candidate) => candidate.source === 'personal')
|
||||
this._candidates =
|
||||
personal && !sameCandidateText(personal.text, first.text)
|
||||
? [{ ...personal, rank: 0 }, { ...first, rank: 1 }]
|
||||
: [{ ...first, rank: 0 }]
|
||||
this._correction = correction
|
||||
this._promptContext = promptContext
|
||||
this._spacedPreferred = spacedPreferred
|
||||
|
|
@ -1498,6 +1616,9 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
this._recordSuggestion({ prefix: trimmedPrefix, text: first.text, model, latencyMs, candidateCount: 1 })
|
||||
logger.info(`제안 첫 후보 생성 (${latencyMs}ms, model=${model}) — 최대 ${SUGGESTION_DEFAULTS.maxCandidatesTotal}개까지 순차로 채운다`)
|
||||
logger.debug(
|
||||
`제안 지연 분해: 기억 ${timing.memoryMs}ms, 교정 ${timing.correctionMs}ms, 모델 ${timing.modelMs}ms (시도 ${timing.attempts}회)`
|
||||
)
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
|
||||
|
|
@ -1858,6 +1979,10 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
|
||||
dismiss(reason: SuggestionSkipReason = 'dismissed'): void {
|
||||
// 알림은 닫히기 직전 자리에 그린다 — 아래에서 세션을 지우기 전에 기억해 둔다.
|
||||
const lastAnchor = this._anchor
|
||||
const lastAnchorKind = this._anchorKind
|
||||
this._clearNotice()
|
||||
if (reason === 'dismissed') {
|
||||
// 명시적 닫기: 잠깐 조용히 있고, 진행 중 생성은 무효화한다.
|
||||
this._userDismissedUntil = Date.now() + SUGGESTION_DEFAULTS.userDismissQuietMs
|
||||
|
|
@ -1895,13 +2020,47 @@ export class SuggestionService extends EventEmitter {
|
|||
// 워밍업은 오버레이 표시와 독립된 요청이다 — 포커스 전환/stale 등으로 오버레이를
|
||||
// 지울 때마다 취소하면 모델이 영영 안 뜬다. 설정에서 기능을 끌 때만 취소한다.
|
||||
if (reason === 'disabled') this._cancelWarmUp()
|
||||
if (wasVisible && reason === 'generation-failed' && lastAnchor) {
|
||||
this._showNoSuggestionNotice(reason, lastAnchor, lastAnchorKind)
|
||||
return
|
||||
}
|
||||
if (wasVisible || reason === 'dismissed') {
|
||||
this.emit('cleared', { reason })
|
||||
}
|
||||
}
|
||||
|
||||
/** "생성 중" 이 보이다 후보 없이 끝났다 — 말없이 닫지 않고 "제안 사항 없음" 을 1초 보여 준 뒤 닫는다. */
|
||||
private _showNoSuggestionNotice(
|
||||
reason: SuggestionSkipReason,
|
||||
anchor: PhysicalRect,
|
||||
anchorKind: AnchorKind
|
||||
): void {
|
||||
this._notice = 'no-suggestion'
|
||||
this._anchor = anchor
|
||||
this._anchorKind = anchorKind
|
||||
this.emit('updated', this.getState())
|
||||
this._noticeTimer = setTimeout(() => {
|
||||
this._noticeTimer = null
|
||||
this._notice = null
|
||||
// 그사이 새 세션이 자리를 잡지 않았을 때만 자리를 비운다.
|
||||
if (!this.isPresentationActive) this._anchor = null
|
||||
this.emit('cleared', { reason })
|
||||
}, NO_SUGGESTION_NOTICE_MS)
|
||||
this._noticeTimer.unref?.()
|
||||
}
|
||||
|
||||
private _clearNotice(): void {
|
||||
if (this._noticeTimer) {
|
||||
clearTimeout(this._noticeTimer)
|
||||
this._noticeTimer = null
|
||||
}
|
||||
this._notice = null
|
||||
}
|
||||
|
||||
/** 활성 후보를 대상 앱에 삽입하고 수락으로 기록한다. */
|
||||
async accept(index?: number): Promise<SuggestionRequestResult> {
|
||||
async accept(index?: number, options: { wordOnly?: boolean } = {}): Promise<SuggestionRequestResult> {
|
||||
// 손을 기다리는 동안(창이 떠 있다) 단축키가 또 눌려도 두 번 넣지 않는다.
|
||||
if (this._acceptInFlight) return { ok: false, reason: 'already-visible' }
|
||||
if (index !== undefined && index >= 0 && index < this._candidates.length) {
|
||||
this._activeIndex = index
|
||||
}
|
||||
|
|
@ -1928,23 +2087,41 @@ export class SuggestionService extends EventEmitter {
|
|||
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')
|
||||
// 단어 단위 수락 — 첫 어절만 넣고 나머지는 창에 남긴다(이어서 한 단어씩, 또는 Enter 로 나머지 전부).
|
||||
const split = options.wordOnly ? splitFirstWord(candidate.text) : null
|
||||
const partial = split !== null && split.rest.length > 0
|
||||
const insertPart = partial ? split.word : candidate.text
|
||||
const joined = joinSuggestion(basePrefix, insertPart, candidate.joint ?? 'separate')
|
||||
const text = (correction?.to ?? '') + joined
|
||||
const deleteCount = correction?.from.length ?? 0
|
||||
const anchor = this._anchor
|
||||
const anchorKind = this._anchorKind
|
||||
const provenance = this._provenance
|
||||
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 가 들어가 붙여넣기가 되지 않는다(실측) — 뗄 때까지 기다린다.
|
||||
// 단축키로 수락했다면 사용자가 아직 키를 쥐고 있다. 그대로 Ctrl+V 를 보내면 대상 앱에 Ctrl+Alt+V 가 들어가
|
||||
// 붙여넣기가 되지 않는다. 창을 띄워 둔 채 손을 다 뗄 때까지 기다린다(최대 5초) — 창이 먼저 사라지면 사용자는
|
||||
// "들어가는 중" 이라 여기고 계속 쥐고 있었다(2026-10-25). 클릭 수락은 기다림 없이 바로 지나간다.
|
||||
this._acceptInFlight = true
|
||||
try {
|
||||
return await this._insertAccepted({
|
||||
const modifierWaitStartedAt = Date.now()
|
||||
const keys = await prepareModifiersForPaste()
|
||||
logger.debug(`제안 수락: 단축키 떼기 ${keys} (${Date.now() - modifierWaitStartedAt}ms)`)
|
||||
if (keys === 'still-held') {
|
||||
logger.warn('제안 수락 취소: 5초 안에 단축키를 떼지 않았다 — 넣으면 Ctrl+Alt+V 가 되므로 넣지 않는다')
|
||||
this.dismiss('stale')
|
||||
this.emit('state-changed', this.getState())
|
||||
return { ok: false, reason: 'stale' }
|
||||
}
|
||||
|
||||
// 이제 창을 닫고 생성을 멈춘 뒤 넣는다.
|
||||
this.dismiss('accepted')
|
||||
this.emit('state-changed', this.getState())
|
||||
const result = await this._insertAccepted({
|
||||
text,
|
||||
deleteCount,
|
||||
composing,
|
||||
|
|
@ -1952,13 +2129,47 @@ export class SuggestionService extends EventEmitter {
|
|||
windowTitle,
|
||||
targetWindow,
|
||||
sessionRecordId,
|
||||
candidateText: candidate.text
|
||||
candidateText: candidate.text,
|
||||
// 한 단어만 받은 것은 그 문장 전체를 사용자 문체로 배우지 않는다.
|
||||
learn: !partial
|
||||
})
|
||||
if (partial && result.ok) this._presentRemainder(`${basePrefix}${joined}`, split.rest, { anchor, anchorKind, appName, windowTitle, targetWindow, provenance })
|
||||
return result
|
||||
} finally {
|
||||
this._acceptInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 단어 단위 수락 뒤 남은 문장을 같은 자리에 다시 띄운다 — 세션 접두는 방금 넣은 글까지로 맞춘다. */
|
||||
private _presentRemainder(
|
||||
prefixAfterInsert: string,
|
||||
rest: string,
|
||||
meta: {
|
||||
anchor: PhysicalRect | null
|
||||
anchorKind: AnchorKind
|
||||
appName: string | null
|
||||
windowTitle: string | null
|
||||
targetWindow: number | null
|
||||
provenance: SuggestionProvenance | null
|
||||
}
|
||||
): void {
|
||||
this._candidates = [{ text: rest, rank: 0 }]
|
||||
this._activeIndex = 0
|
||||
this._targetTotal = 1
|
||||
this._correction = null
|
||||
this._anchor = meta.anchor
|
||||
this._anchorKind = meta.anchorKind
|
||||
this._appName = meta.appName
|
||||
this._windowTitle = meta.windowTitle
|
||||
this._windowHandle = meta.targetWindow
|
||||
this._provenance = meta.provenance
|
||||
this._generatedForPrefix = normalizeSessionPrefix(prefixAfterInsert)
|
||||
this._lastSkipReason = null
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
this.emit('state-changed', this.getState())
|
||||
}
|
||||
|
||||
private async _insertAccepted(params: {
|
||||
text: string
|
||||
deleteCount: number
|
||||
|
|
@ -1968,15 +2179,10 @@ export class SuggestionService extends EventEmitter {
|
|||
targetWindow: number | null
|
||||
sessionRecordId: string | null
|
||||
candidateText: string
|
||||
/** 수락한 문장을 사용자 문체 표본으로 배운다 (단어 단위 수락은 false) */
|
||||
learn?: boolean
|
||||
}): Promise<SuggestionRequestResult> {
|
||||
const { text, deleteCount, composing, appName, windowTitle, targetWindow, sessionRecordId, candidateText } = params
|
||||
const modifierWaitStartedAt = Date.now()
|
||||
if (!(await waitForModifiersReleased())) {
|
||||
logger.warn('수정자 키가 떼어지지 않은 채 제안을 삽입한다 (1.5초 초과)')
|
||||
}
|
||||
// "붙여넣기가 느리다" 신고 진단 — 수락 지연이 손 떼기 대기인지 삽입 자체인지 가른다.
|
||||
logger.debug(`제안 수락: 수정자 키 떼기 대기 ${Date.now() - modifierWaitStartedAt}ms`)
|
||||
|
||||
// 붙여넣기(Ctrl+V)는 그 순간의 포그라운드 창으로 간다. 오버레이는 다음 스냅샷이 와야
|
||||
// 닫히므로, 그사이 다른 앱으로 옮겨 간 뒤 수락하면 엉뚱한 창에 삽입됐다 — 세션을 만든
|
||||
// 창이 아니면 삽입하지 않는다 (창을 알 수 없으면 기존처럼 진행한다).
|
||||
|
|
@ -2031,7 +2237,7 @@ export class SuggestionService extends EventEmitter {
|
|||
this._repository.markAccepted(candidateText)
|
||||
}
|
||||
// 수락한 문장은 사용자 문체의 확실한 표본이다 (학습 동의 시에만 저장됨).
|
||||
this._learning.recordAccepted(candidateText, { appName, windowTitle })
|
||||
if (params.learn !== false) this._learning.recordAccepted(candidateText, { appName, windowTitle })
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue