fix(desktop): prevent modifier key buffer resets, clipboard race on terminal accept, and redundant UIA settle snapshots

This commit is contained in:
Yun Chan 2026-10-31 04:19:53 +09:00
parent 6d909dd0e5
commit 41901c1ec5
10 changed files with 198 additions and 23 deletions

View file

@ -40,6 +40,7 @@ import {
isTerminalApp,
manhattanDistance,
mergeActivityBucket,
normalizeRequestPrefix,
rankFlowWindows,
recommendAppExclusion,
summarizeActivity,
@ -532,8 +533,6 @@ class InputTelemetryService extends EventEmitter {
// ── 이벤트 수집 ────────────────────────────────────────
private _handleKeyDown(event: UiohookKeyboardEvent): void {
// 합성 키도 화면을 바꾼다. 통계 제외 여부와 무관하게 이전 UIA 응답은 무효다.
this._inputRevision += 1
this._syncModifiers(event)
// Win32 SendInput(KEYEVENTF_UNICODE) 가 보내는 합성 유니코드 키는 uiohook 에서 keycode=0 으로 들어온다.
// 사용자 키스트로크나 IME 입력으로 처리하면 버퍼와 타이머를 교란하므로 즉시 무시한다.
@ -553,6 +552,7 @@ class InputTelemetryService extends EventEmitter {
vk === 0xa2 ||
vk === 0xa3
if (isExpectedProgrammaticKey) {
this._inputRevision += 1
this._programmaticKeys -= 1
if (this._programmaticKeys === 0) {
this._scheduleTextSnapshot()
@ -560,6 +560,24 @@ class InputTelemetryService extends EventEmitter {
return
}
}
// 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다.
// 여기서 _inputRevision·_lastKeyAt·스냅샷 타이머를 건드리면 수정자 키를 쥐고 있는 동안
// 진행 중 UIA 스냅샷이 버려지고 유휴 시간(idleMs)과 터미널 버퍼가 리셋된다.
if (vk !== null && classifyKeyStroke(vk, this._modifiers) === 'modifier') {
return
}
// D3RO Voice 전역 제안 탐색/수락 단축키(Ctrl+Alt+방향키/Enter/Space/Backspace)는
// OS globalShortcut 이 가로채므로 대상 앱 텍스트를 바꾸지 않는다.
const isSuggestionChord =
this._modifiers.ctrl &&
this._modifiers.alt &&
!this._modifiers.meta &&
(vk === 0x0d || vk === 0x20 || vk === 0x08 || (vk !== null && vk >= 0x25 && vk <= 0x28))
if (isSuggestionChord) {
return
}
// 실제 키 입력은 화면을 바꾼다 — 이전 UIA 응답은 무효다.
this._inputRevision += 1
this._registerInput(true)
const bucket = this._bucket()
// 한글·일본어 IME 가 켜져 있으면 Windows 는 글자 키를 VK_PROCESSKEY 로 넘기고, uiohook 은 그것을
@ -836,22 +854,27 @@ class InputTelemetryService extends EventEmitter {
}, INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs)
this._textTimer.unref?.()
// 제안 트리거 지연(기본 1000ms)이 스냅샷 디바운스(700ms)보다 크다. 스냅샷이
// 제안 트리거 지연(기본 600ms)이 스냅샷 디바운스(380ms)보다 크다. 스냅샷이
// 디바운스에만 돌면 "타이핑을 멈춘 뒤 N ms" 조건이 결코 충족되지 않아
// 제안이 영원히 요청되지 않는다(실측: debounce 로그만 반복). 그래서
// 트리거 지연을 넘긴 시점에 한 번 더 스냅샷을 돌려 게이트를 연다.
if (this._settleTimer) clearTimeout(this._settleTimer)
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다").
const settleDelay = Math.max(
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60
)
this._settleTimer = setTimeout(() => {
// 실제 글자/편집 입력이 있었고 제안이 켜져 있을 때만 트리거 지연을 넘긴 시점에 한 번 더 스냅샷을 돌린다.
if (this._settleTimer) {
clearTimeout(this._settleTimer)
this._settleTimer = null
void this._captureTextSnapshot()
}, settleDelay)
this._settleTimer.unref?.()
}
if ((!keyClass || TYPING_KEY_CLASSES.has(keyClass)) && configGet('suggestionEnabled') === true) {
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다").
const settleDelay = Math.max(
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60
)
this._settleTimer = setTimeout(() => {
this._settleTimer = null
void this._captureTextSnapshot()
}, settleDelay)
this._settleTimer.unref?.()
}
}
/**
@ -1141,6 +1164,21 @@ class InputTelemetryService extends EventEmitter {
}
this._lastContext = context
if (this._settleTimer) {
const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars
const canTriggerSuggestion =
configGet('suggestionEnabled') === true &&
context.available &&
context.isEditable &&
!context.isPassword &&
context.editedSinceFocus &&
context.typedRecently &&
normalizeRequestPrefix(context.prefix).length + (context.isComposing ? 1 : 0) >= minPrefixChars
if (!canTriggerSuggestion) {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
}
this.emit('typed-context', context)
// 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다).
this._emitState()

View file

@ -86,6 +86,8 @@ export interface SuggestionLearningPort {
recordAccepted(text: string, meta: { appName: string | null; windowTitle: string | null }): void
/** 곧 보낼 프로그램 키 수(교정 수락의 백스페이스 등) — 입력 통계에서 뺀다. */
expectProgrammaticKeys?(count: number): void
/** 터미널 키스트로크 버퍼에 프로그램 치환/삽입을 반영한다. */
applyProgrammaticReplacement?(deleteCount: number, insertText: string, baseLength?: number): void
}
/**
@ -132,6 +134,8 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps {
learning: {
expectProgrammaticInsert: (text) => getInputTelemetryService().expectProgrammaticInsert(text),
expectProgrammaticKeys: (count) => getInputTelemetryService().expectProgrammaticKeys(count),
applyProgrammaticReplacement: (deleteCount, insertText, baseLength) =>
getInputTelemetryService().applyProgrammaticReplacement(deleteCount, insertText, baseLength),
recordAccepted: (text, meta) =>
getInputTelemetryService().recordExternalText(text, { ...meta, source: 'suggestion' })
}
@ -2146,11 +2150,22 @@ export class SuggestionService extends EventEmitter {
const anchorKind = this._anchorKind
const provenance = this._provenance
const composing = this._lastContext?.isComposing === true
const terminalMode = this._lastContext?.terminalMode === true
const appName = this._appName
const windowTitle = this._windowTitle
const targetWindow = this._windowHandle
const sessionRecordId = this._sessionRecordId
// 수락이 시작된 순간 추가 후보 채우기 루프는 즉시 멈춘다 — 손을 떼길 기다리는 동안
// 2/12, 3/12 후보가 계속 스트리밍되면 사용자가 아직 선택 중이라 오인해 Ctrl+Alt 를 계속 쥐고 있게 된다.
if (this._filling) {
this._filling = false
this._fillAbort?.abort()
this._fillAbort = null
if (!this._inFlight) this._generating = false
this.emit('updated', this.getState())
}
// 단축키로 수락했다면 사용자가 아직 키를 쥐고 있다. 그대로 Ctrl+V 를 보내면 대상 앱에 Ctrl+Alt+V 가 들어가
// 붙여넣기가 되지 않는다. 창을 띄워 둔 채 손을 다 뗄 때까지 기다린다(최대 5초) — 창이 먼저 사라지면 사용자는
// "들어가는 중" 이라 여기고 계속 쥐고 있었다(2026-10-25). 클릭 수락은 기다림 없이 바로 지나간다.
@ -2173,6 +2188,7 @@ export class SuggestionService extends EventEmitter {
text,
deleteCount,
composing,
terminalMode,
appName,
windowTitle,
targetWindow,
@ -2222,6 +2238,7 @@ export class SuggestionService extends EventEmitter {
text: string
deleteCount: number
composing: boolean
terminalMode?: boolean
appName: string | null
windowTitle: string | null
targetWindow: number | null
@ -2230,7 +2247,17 @@ export class SuggestionService extends EventEmitter {
/** 수락한 문장을 사용자 문체 표본으로 배운다 (단어 단위 수락은 false) */
learn?: boolean
}): Promise<SuggestionRequestResult> {
const { text, deleteCount, composing, appName, windowTitle, targetWindow, sessionRecordId, candidateText } = params
const {
text,
deleteCount,
composing,
terminalMode = false,
appName,
windowTitle,
targetWindow,
sessionRecordId,
candidateText
} = params
// 붙여넣기(Ctrl+V)는 그 순간의 포그라운드 창으로 간다. 오버레이는 다음 스냅샷이 와야
// 닫히므로, 그사이 다른 앱으로 옮겨 간 뒤 수락하면 엉뚱한 창에 삽입됐다 — 세션을 만든
// 창이 아니면 삽입하지 않는다 (창을 알 수 없으면 기존처럼 진행한다).
@ -2247,7 +2274,10 @@ export class SuggestionService extends EventEmitter {
// 삽입 직후의 텍스트 스냅샷 diff 가 이 텍스트를 "타이핑" 으로 다시 학습하지 않도록 알린다.
const cancelExpectedInsert = this._learning.expectProgrammaticInsert(text)
const method = configGet('insertMethod')
const insertMethod = method === 'keyboard' ? 'keyboard' : 'clipboard'
// 터미널(xterm-helper-textarea, Windows Terminal, Kitedesk 등)에서는 Ctrl+V 붙여넣기가
// 클립보드 복원 타이밍(250ms)과 경합해 이전 클립보드(URL 등)가 대신 붙여넣어지거나 ^V 가 입력될 수 있으므로
// 클립보드를 건드리지 않는 직접 유니코드 키보드 주입('keyboard')을 사용한다.
const insertMethod = method === 'keyboard' || terminalMode ? 'keyboard' : 'clipboard'
try {
if (deleteCount > 0) {
// 확정용 Space(+1)·백스페이스·붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다.
@ -2266,6 +2296,9 @@ export class SuggestionService extends EventEmitter {
logger.warn(`제안 삽입 실패 (method=${result.method}, len=${result.textLength})`)
return { ok: false, reason: 'generation-failed' }
}
if (terminalMode) {
this._learning.applyProgrammaticReplacement?.(deleteCount, text)
}
} catch (error) {
cancelExpectedInsert()
logger.warn(`제안 삽입 예외: ${error instanceof Error ? error.message : String(error)}`)

View file

@ -108,10 +108,15 @@ describe('classifyKeyStroke', () => {
expect(classifyKeyStroke(0xe5, NO_MODS)).toBe('ime')
})
it('수정자 조합은 단축키로 다', () => {
it('수정자 조합은 단축키로 분류하되, 수정자 키 자체(Ctrl/Alt/Shift/Win)는 플래그가 켜져 있어도 modifier 로 분류한다', () => {
expect(classifyKeyStroke(0x41, { ...NO_MODS, ctrl: true })).toBe('shortcut')
expect(classifyKeyStroke(0x41, { ...NO_MODS, alt: true })).toBe('shortcut')
expect(classifyKeyStroke(0x41, { ...NO_MODS, meta: true })).toBe('shortcut')
expect(classifyKeyStroke(0x11, { ...NO_MODS, ctrl: true })).toBe('modifier')
expect(classifyKeyStroke(0xa2, { ...NO_MODS, ctrl: true })).toBe('modifier')
expect(classifyKeyStroke(0x12, { ...NO_MODS, ctrl: true, alt: true })).toBe('modifier')
expect(classifyKeyStroke(0xa4, { ...NO_MODS, alt: true })).toBe('modifier')
expect(classifyKeyStroke(0x5b, { ...NO_MODS, meta: true })).toBe('modifier')
})
it('알 수 없는 키는 other 이며 키 내용을 담지 않는다', () => {

View file

@ -239,4 +239,29 @@ describe('제안 + 오타 교정', () => {
expect(options).toEqual(expect.objectContaining({ raw: true }))
}
})
it('터미널 모드(terminalMode=true)에서 수락하면 클립보드(Ctrl+V)를 건드리지 않고 keyboard 방식으로 넣으며 터미널 버퍼를 동기화한다', async () => {
const expectKeys = vi.fn()
const applyReplacement = vi.fn()
const customDeps = deps(expectKeys)
customDeps.learning.applyProgrammaticReplacement = applyReplacement
const service = new SuggestionService(customDeps)
services.push(service)
service.setTypoProposer(proposer)
const context = typingContext({ terminalMode: true })
const internal = service as unknown as Internal
internal._lastContext = context
await internal._generate(context.prefix, context, 3, 160)
const result = await service.accept()
expect(result).toEqual({ ok: true })
expect(harness.replaceBeforeCaret).toHaveBeenCalledWith(
TYPO.length,
'안녕하세요.? 오늘 회의 자료 공유드립니다.',
'keyboard',
{ commitComposition: false }
)
expect(applyReplacement).toHaveBeenCalledWith(TYPO.length, '안녕하세요.? 오늘 회의 자료 공유드립니다.')
})
})