fix(desktop): prevent Korean character swallowing in terminal and xterm.js surfaces (INPUT-04, INPUT-19)

This commit is contained in:
Yun Chan 2026-10-31 03:38:56 +09:00
parent f18cebaa24
commit 61123b5ad8
11 changed files with 264 additions and 50 deletions

View file

@ -64,6 +64,7 @@ import {
type TerminalVimMode
} from '@d3ro/core/input-intelligence'
import { RecentWritesBuffer, type RecentWrite, type RecentWriteMeta } from '@d3ro/core/recent-writes'
import { detectTypos } from '@d3ro/core/typo-correction'
import { getDatabase } from '../db'
import { inputActivity, personalPhrases, suggestions as suggestionsTable, typingSamples } from '../db/schema'
import { configGet, configSet } from './ConfigService'
@ -595,13 +596,10 @@ class InputTelemetryService extends EventEmitter {
// 진단: 키 값이 아니라 종류·수정자만 남긴다 (typed 판정이 왜 틀리는지 로그로 보이게)
this._lastKeyDiag = `${keyClass}${vk === null ? `?${event.keycode}` : ''}${this._modifiers.ctrl ? '+C' : ''}${this._modifiers.alt ? '+A' : ''}${this._modifiers.meta ? '+M' : ''}`
// 터미널·Vim·개발 표면에서는 키스트로크 버퍼와 IME 상태를 함께 추적해
// 줄 끝 공백 손실(Windows Terminal)이나 캔버스 터미널(len=0)에서도 한영 자동 전환과 Vim 모드가 동작하게 한다.
const onTerminalSurface = isTerminalOrDeveloperSurface(this._foreground.appName)
const koreanIme =
onTerminalSurface && vk !== null && vk >= 0x41 && vk <= 0x5a
? isForegroundKoreanIme(this._foreground.hwnd)
: undefined
// 터미널·Vim·개발 표면에서는 키스트로크 버퍼를 추적해 줄 끝 공백 손실(Windows Terminal)이나
// 캔버스 터미널(len=0)에서도 한영 자동 전환과 Vim 모드가 동작하게 한다.
// 주의: 키다운 훅 안에서 대상 창 IME 에 동기 WM_IME_CONTROL(isForegroundKoreanIme)을 보내면
// TSF/Cicero 조합 상태가 깨져 한글이 한 글자씩 씹히므로 훅 안에서는 절대 호출하지 않는다.
this._terminalTracker.onKeyDown({
hwnd: this._foreground.hwnd,
windowTitle: this._foreground.windowTitle,
@ -611,7 +609,6 @@ class InputTelemetryService extends EventEmitter {
ctrl: this._modifiers.ctrl,
alt: this._modifiers.alt,
meta: this._modifiers.meta,
koreanIme,
now: this._lastKeyAt
})
@ -769,13 +766,19 @@ class InputTelemetryService extends EventEmitter {
private async _sampleWhileTyping(): Promise<void> {
if (!this._running || this._sampling) return
const now = Date.now()
if (!this._suggestionPresentationActive && this._lastKeyAt > 0 && now - this._lastKeyAt < 350) {
if (this._lastKeyAt > 0 && now - this._lastKeyAt < 1000) {
return
}
if (
!this._suggestionPresentationActive &&
(isTerminalOrDeveloperSurface(this._foreground.appName) ||
this._lastContext?.terminalMode === true ||
this._lastKeyAt === 0 ||
now - this._lastKeyAt > INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs ||
(this._lastContext !== null && this._lastContext.capturedAt >= this._lastKeyAt))
) {
return
}
const hasRecentKeyboardInput =
this._lastKeyAt > 0 &&
now - this._lastKeyAt <= INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs
if (!hasRecentKeyboardInput && !this._suggestionPresentationActive) return
this._sampling = true
try {
@ -785,26 +788,45 @@ class InputTelemetryService extends EventEmitter {
}
}
private _shouldRunFastTerminalBoundarySnapshot(): boolean {
if (!isTerminalOrDeveloperSurface(this._foreground.appName)) return true
const tracked = this._terminalTracker.currentPrefix()
if (tracked.trim().length === 0) return true
if (/[ㄱ-ㅎㅏ-ㅣA-Za-z]/u.test(tracked) || tracked.trimStart().startsWith(':')) {
return true
}
return (
detectTypos(tracked, {
includeTrailingToken: true,
layoutOnly: true,
terminalMode: true
}).length > 0
)
}
private _scheduleTextSnapshot(keyClass?: KeyStrokeClass): void {
// Araso 급 빠른 한영 전환: 공백·문장부호 직후에는 40ms 뒤에 즉시 스냅샷을 찍고,
// 일반 글자 입력 중에는 단어를 치는 도중(예: sometime 의 some 시점) 끼어들어 글자를 삼키지 않도록
// 680ms 유휴 뒤에 스냅샷을 찍는다(Vim 명령줄 :wq 등은 160ms).
// 700ms 디바운스 타이머(_textTimer)에 맡긴다(Vim 명령줄 :wq 등은 160ms).
if (this._typoTimer) clearTimeout(this._typoTimer)
if (keyClass && TYPING_KEY_CLASSES.has(keyClass) && configGet('typoAutoCorrectEnabled') !== false) {
const isBoundaryKey =
keyClass === 'space' ||
keyClass === 'symbol' ||
(keyClass === 'digit' && this._modifiers.shift)
const quickDelay = isBoundaryKey
? 40
: this._terminalTracker.vimMode === 'command'
? 160
: 680
this._typoTimer = setTimeout(() => {
this._typoTimer = null
void this._captureTextSnapshot()
}, quickDelay)
this._typoTimer.unref?.()
const quickDelay =
isBoundaryKey && this._shouldRunFastTerminalBoundarySnapshot()
? 40
: !isBoundaryKey && this._terminalTracker.vimMode === 'command'
? 160
: null
if (quickDelay !== null) {
this._typoTimer = setTimeout(() => {
this._typoTimer = null
void this._captureTextSnapshot()
}, quickDelay)
this._typoTimer.unref?.()
}
}
if (this._textTimer) clearTimeout(this._textTimer)
@ -898,6 +920,14 @@ class InputTelemetryService extends EventEmitter {
typedRecently
}
if (
!snapshot.isPassword &&
isTerminalOrDeveloperSurface(this._foreground.appName) &&
!this._terminalTracker.hasObservedImeForHwnd(this._foreground.hwnd)
) {
this._terminalTracker.syncKoreanIme(isForegroundKoreanIme(this._foreground.hwnd))
}
if (snapshot.available && isXtermHelperControl(snapshot) && !snapshot.isPassword) {
const usesCaretRect = snapshot.caretRect !== null
context.anchor = snapshot.caretRect ?? snapshot.elementRect

View file

@ -2145,7 +2145,7 @@ export class SuggestionService extends EventEmitter {
const anchor = this._anchor
const anchorKind = this._anchorKind
const provenance = this._provenance
const composing = this._lastContext?.isComposing === true && /[가-힣]$/u.test(acceptPrefix)
const composing = this._lastContext?.isComposing === true
const appName = this._appName
const windowTitle = this._windowTitle
const targetWindow = this._windowHandle

View file

@ -225,6 +225,12 @@ export class TypoCorrectionService extends EventEmitter {
// 1단계(한영 전환 layoutOnly)는 단어 경계(25ms)와 어절 끝 유휴(650ms)에서 즉시 실행하고,
// 2단계(철자 사전 + Gemma 배경 오타·한영 보정)는 터미널이 아니면서 유휴 조건을 충족했을 때 실행한다.
const isTerminal = context.terminalMode === true || isTerminalApp(context.appName)
// 터미널(xterm.js 등)에서 공백·문장부호 없이 완성형 한글 음절([가-힣])로 끝난 상태는
// 아직 IME 조합 버퍼에 머물러 있어 PTY 로 전달되기 전일 수 있다. 이때 commitComposition(Space+Backspace)을
// 주입하면 xterm.js 의 비동기 조합 확정과 백스페이스가 경합해 앞 글자를 삼키므로 단어 경계(Space 등)까지 기다린다.
if (isTerminal && !hasTrailingBoundary && !isVimCommand && /[가-힣]$/u.test(prefix)) {
return 'pass'
}
const suspicious = hasSuspiciousTypo(region)
const minFullCheckIdle =
hasTrailingBoundary && suspicious