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

@ -251,7 +251,41 @@ def _caret_rect_and_offset(auto: Any, control: Any) -> tuple[Optional[dict], Opt
_woken_hwnds: dict[int, float] = {}
_WAKE_TTL_SECONDS = 60.0
_WAKE_TTL_SECONDS = 86400.0
def _foreground_window_meta() -> tuple[Optional[str], Optional[dict]]:
"""Win32 API 로 포그라운드 창 제목과 사각형을 즉시 읽는다 (UIA 부모 트리 순회 COM 호출 제거)."""
try:
import ctypes # noqa: PLC0415
from ctypes import wintypes # noqa: PLC0415
user32 = ctypes.windll.user32
hwnd = int(user32.GetForegroundWindow() or 0)
if not hwnd:
return (None, None)
title: Optional[str] = None
buf = ctypes.create_unicode_buffer(302)
length = int(user32.GetWindowTextW(wintypes.HWND(hwnd), buf, 300) or 0)
if length > 0:
title = buf.value[:300]
rect = wintypes.RECT()
rect_dict: Optional[dict] = None
if user32.GetWindowRect(wintypes.HWND(hwnd), ctypes.byref(rect)):
width = int(rect.right) - int(rect.left)
height = int(rect.bottom) - int(rect.top)
if width >= 0 and height >= 0:
rect_dict = {
"x": int(rect.left),
"y": int(rect.top),
"width": width,
"height": height,
}
return (title, rect_dict)
except Exception:
return (None, None)
def _wake_chromium_accessibility(force: bool = False) -> bool:
@ -366,13 +400,29 @@ def _snapshot() -> dict:
except Exception:
result["processId"] = None
try:
top = control.GetTopLevelControl()
if top is not None:
result["windowTitle"] = str(top.Name or "")[:300]
result["elementRect"] = _rect_to_dict(top.BoundingRectangle) or result["elementRect"]
except Exception:
pass
fg_title, fg_rect = _foreground_window_meta()
if fg_title:
result["windowTitle"] = fg_title
if fg_rect is not None:
result["elementRect"] = fg_rect
class_name_lower = str(result["className"] or "").lower()
control_name_lower = str(result["controlName"] or "").strip().lower()
is_xterm_helper = (
"xterm-helper-textarea" in class_name_lower
or control_name_lower in ("terminal input", "터미널 입력")
)
if not is_xterm_helper and (result["windowTitle"] is None or result["elementRect"] is None):
try:
top = control.GetTopLevelControl()
if top is not None:
if result["windowTitle"] is None:
result["windowTitle"] = str(top.Name or "")[:300]
if result["elementRect"] is None:
result["elementRect"] = _rect_to_dict(top.BoundingRectangle) or result["elementRect"]
except Exception:
pass
try:
result["elementRect"] = _rect_to_dict(control.BoundingRectangle) or result["elementRect"]
@ -383,6 +433,19 @@ def _snapshot() -> dict:
result["textSource"] = source
result["text"] = text
if is_xterm_helper:
# xterm.js 의 숨김 IME 입력창(xterm-helper-textarea)에서 TextPattern 선택·문자 확장·TextEditPattern
# 조합 조회를 호출하면 Chromium 렌더러 스레드가 블로킹(최대 1500ms 타임아웃)되고 한글 조합 중인
# 글자가 삼켜진다. ValuePattern 값과 편집 가능 여부만 즉시 반환한다.
result["isEditable"] = True
result["caretRect"] = None
result["caretOffset"] = None
result["isComposing"] = False
result["hasSelection"] = False
result["capturedAt"] = int(time.time() * 1000)
result["elapsedMs"] = int((time.monotonic() - started) * 1000)
return result
is_readonly = False
try:
if value_pattern is not None:

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

View file

@ -589,6 +589,40 @@ describe('TypoCorrectionService', () => {
).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
})
it('터미널에서 공백 없이 끝난 한글 음절(예: ㅎ샤ㅗㅕㅠ에)은 조합 중 글자를 삼키지 않도록 공백 확정 전까지 치환하지 않는다', async () => {
const fake = deps({ warmModel: () => null })
const service = new TypoCorrectionService(fake.deps)
// 공백 전(조합 중인 마지막 음절 '에' 가 아직 xterm-helper-textarea 안에 있을 때)에는 건드리지 않는다.
expect(
service.handleTypingContext(
typingContext({
prefix: 'ㅎ샤ㅗㅕㅠ에',
appName: 'Agent Switchboard.exe',
terminalMode: true,
isComposing: true,
idleMs: 1200
})
)
).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
// 공백으로 어절이 확정된 뒤('ㅎ샤ㅗㅕㅠ에 ')에는 'github에 ' 로 정상 치환한다.
expect(
service.handleTypingContext(
typingContext({
prefix: 'ㅎ샤ㅗㅕㅠ에 ',
appName: 'Agent Switchboard.exe',
terminalMode: true,
isComposing: false,
idleMs: 80
})
)
).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅎ샤ㅗㅕㅠ에 '.length, 'github에 ')
})
})
describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => {