feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)

This commit is contained in:
Yun Chan 2026-10-31 02:54:54 +09:00
parent f49acf0105
commit 10af20a0ad
157 changed files with 29455 additions and 913 deletions

View file

@ -72,6 +72,7 @@ import { acquireGlobalInputHook } from './global-input-hook'
import { uiohookCodeToVk } from './KeyBindingService'
import { getUiaContextService } from './UiaContextService'
import { getForegroundWindowInfo, isForegroundKoreanIme } from '../utils/win32-foreground'
import { getLastNativeInputTick } from '../utils/win32-input-activity'
import { getPersonalGraphService } from './PersonalGraphService'
import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex'
@ -104,6 +105,10 @@ export interface TypingContext {
windowHandle?: number | null
idleMs: number
capturedAt: number
/** 스냅샷을 읽는 동안 입력/포커스가 바뀌지 않았는지 확인한 단조 증가 번호. */
inputRevision?: number
/** Windows 세션의 마지막 입력 tick. null이면 네이티브 입력 상태 확인 실패, 다른 OS는 생략. */
nativeInputTick?: number | null
/** 포커스가 바뀐 뒤 이 필드에서 실제로 편집이 있었는가 (마우스로 들어오기만 한 경우 false) */
editedSinceFocus: boolean
/** 최근에 실제로 타이핑했는가 (recentTypingWindowMs 이내) */
@ -193,6 +198,10 @@ class InputTelemetryService extends EventEmitter {
private _sampleTimer: NodeJS.Timeout | null = null
/** 주기 샘플 스냅샷 진행 중 (중복 방지) */
private _sampling = false
/** 모든 스냅샷 트리거를 합쳐 같은 UIA 응답을 중복 적용하지 않는다. */
private _snapshotRequest: Promise<TypingContext | null> | null = null
/** 같은 밀리초에 들어온 키·클릭도 서로 다른 편집으로 구분한다. */
private _inputRevision = 0
/** 제안 오버레이가 표시 중일 때만 포커스 이탈/선택을 계속 확인한다. */
private _suggestionPresentationActive = false
private _presentationValidationTimer: NodeJS.Timeout | null = null
@ -227,6 +236,8 @@ class InputTelemetryService extends EventEmitter {
private _typedIntoFocus = false
/** 현재 포커스/클릭 이후 실제로 글자 키를 쳤는가 (첫 스냅샷 전 빠른 입력 보존) */
private _typedInCurrentFocus = false
/** Chromium/Electron 등 UIA GetActiveComposition 미지원 앱을 위한 키스트로크 기반 한글 조합 추정 */
private _imeComposing = false
private _lastTypedHwnd: number | null = null
/** 직전 스냅샷이 편집 가능한 칸이었는가 / 어느 창이었는가 (포커스 깜빡임 판정) */
private _prevSnapshotEditable = false
@ -314,6 +325,10 @@ class InputTelemetryService extends EventEmitter {
return this._lastKeyAt
}
get inputRevision(): number {
return this._inputRevision
}
/**
* 곧 프로그램이 키 count 개를 보낸다 — 그 키들은 입력 통계에 넣지 않는다.
* 남은 예고는 ttlMs 뒤 무효다(보내지 못한 키가 사용자 키를 삼키지 않게).
@ -321,6 +336,7 @@ class InputTelemetryService extends EventEmitter {
expectProgrammaticKeys(count: number, ttlMs = 3000): void {
this._programmaticKeys = Math.max(0, count)
this._programmaticKeysUntil = Date.now() + ttlMs
if (count > 0) this._imeComposing = false
}
/**
@ -334,6 +350,8 @@ class InputTelemetryService extends EventEmitter {
* 프로그램(오타 교정)이 커서 앞 deleteCount 글자를 지우고 insertText 를 넣었을 때 터미널 키 버퍼도 동기화한다.
*/
applyProgrammaticReplacement(deleteCount: number, insertText: string, baseLength?: number): void {
this._inputRevision += 1
this._imeComposing = false
this._terminalTracker.applyReplacement(deleteCount, insertText, baseLength)
}
@ -372,6 +390,7 @@ class InputTelemetryService extends EventEmitter {
this._releaseHook = acquireGlobalInputHook()
this._running = true
this._inputRevision += 1
this._flushTimer = setInterval(
() => this._flush(),
INPUT_TELEMETRY_DEFAULTS.flushIntervalMs
@ -408,6 +427,7 @@ class InputTelemetryService extends EventEmitter {
}
stop(): void {
this._inputRevision += 1
// 입력 관찰을 끄면 메모리에 잡아 둔 "조금 전에 쓴 글" 도 버린다.
this._recentWrites.clear()
if (!this._running) {
@ -511,6 +531,8 @@ class InputTelemetryService extends EventEmitter {
// ── 이벤트 수집 ────────────────────────────────────────
private _handleKeyDown(event: UiohookKeyboardEvent): void {
// 합성 키도 화면을 바꾼다. 통계 제외 여부와 무관하게 이전 UIA 응답은 무효다.
this._inputRevision += 1
this._syncModifiers(event)
// Win32 SendInput(KEYEVENTF_UNICODE) 가 보내는 합성 유니코드 키는 uiohook 에서 keycode=0 으로 들어온다.
// 사용자 키스트로크나 IME 입력으로 처리하면 버퍼와 타이머를 교란하므로 즉시 무시한다.
@ -563,6 +585,13 @@ class InputTelemetryService extends EventEmitter {
} else if (keyClass === 'shortcut') {
this._typedInCurrentFocus = false
}
if (event.keycode === 112 || vk === 0x15) {
this._imeComposing = false
} else if (keyClass === 'ime' || keyClass === 'letter') {
this._imeComposing = true
} else if (keyClass !== 'modifier') {
this._imeComposing = false
}
// 진단: 키 값이 아니라 종류·수정자만 남긴다 (typed 판정이 왜 틀리는지 로그로 보이게)
this._lastKeyDiag = `${keyClass}${vk === null ? `?${event.keycode}` : ''}${this._modifiers.ctrl ? '+C' : ''}${this._modifiers.alt ? '+A' : ''}${this._modifiers.meta ? '+M' : ''}`
@ -594,6 +623,7 @@ class InputTelemetryService extends EventEmitter {
}
private _handleMouseDown(event: UiohookMouseEvent): void {
this._inputRevision += 1
this._registerInput(false)
const now = Date.now()
@ -615,10 +645,12 @@ class InputTelemetryService extends EventEmitter {
// 클릭은 다른 칸으로 옮겨 갔을 수 있다 — 다음 스냅샷의 텍스트를 새 기준으로 삼는다.
this._rebaseFocusText = true
this._typedInCurrentFocus = false
this._imeComposing = false
this._terminalTracker.onPointerOrFocusChange(this._foreground.hwnd)
}
private _handleMouseUp(event: UiohookMouseEvent): void {
this._inputRevision += 1
this._lastMouse = { x: event.x, y: event.y }
if (!this._suggestionPresentationActive) return
if (this._presentationValidationTimer) clearTimeout(this._presentationValidationTimer)
@ -643,6 +675,7 @@ class InputTelemetryService extends EventEmitter {
}
private _handleWheel(event: UiohookWheelEvent): void {
this._inputRevision += 1
const bucket = this._bucket()
bucket.scrollTicks += Math.max(1, Math.abs(Number(event.rotation) || 1))
this._registerInput(false)
@ -698,7 +731,9 @@ class InputTelemetryService extends EventEmitter {
const info = getForegroundWindowInfo()
if (info) {
if (info.hwnd !== this._foreground.hwnd) {
this._inputRevision += 1
this._typedInCurrentFocus = false
this._imeComposing = false
}
this._foreground = {
appName: info.appName || null,
@ -733,9 +768,13 @@ 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) {
return
}
const hasRecentKeyboardInput =
this._lastKeyAt > 0 &&
Date.now() - this._lastKeyAt <= INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs
now - this._lastKeyAt <= INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs
if (!hasRecentKeyboardInput && !this._suggestionPresentationActive) return
this._sampling = true
@ -799,9 +838,38 @@ class InputTelemetryService extends EventEmitter {
*/
private async _captureTextSnapshot(): Promise<TypingContext | null> {
if (!this._running) return null
if (this._snapshotRequest) return this._snapshotRequest
const request = this._readTextSnapshot()
this._snapshotRequest = request
try {
return await request
} finally {
if (this._snapshotRequest === request) this._snapshotRequest = null
}
}
private async _readTextSnapshot(): Promise<TypingContext | null> {
this._sampleForeground(Date.now(), true)
const inputRevision = this._inputRevision
const foregroundHwnd = this._foreground.hwnd
const nativeInputTick = getLastNativeInputTick()
const uia = getUiaContextService()
const snapshot = withoutPlaceholderText(await uia.getSnapshot())
if (!this._running) return null
this._sampleForeground(Date.now(), true)
// CPU 부하/모델 로딩 중 UIA 응답이 늦어질 수 있다. 예전 텍스트를 최신 키 시각과
// 섞으면 자동 교정이 방금 친 글자를 지운다. 기준선·학습·제안 모두 갱신 전에 버린다.
if (
inputRevision !== this._inputRevision ||
foregroundHwnd !== this._foreground.hwnd ||
nativeInputTick !== getLastNativeInputTick() ||
(snapshot.available && snapshot.capturedAt < Math.max(this._lastKeyAt, this._lastClickAt))
) {
logger.debug('입력 스냅샷 버림: UIA 조회 중 입력 또는 포커스 변경')
return null
}
const now = Date.now()
// 유휴 시간은 키보드 기준이다 (마우스 이동/클릭으로는 제안하지 않는다).
const idleMs = this._lastKeyAt > 0 ? now - this._lastKeyAt : Number.MAX_SAFE_INTEGER
@ -824,6 +892,8 @@ class InputTelemetryService extends EventEmitter {
windowHandle: this._foreground.hwnd,
idleMs,
capturedAt: snapshot.capturedAt,
inputRevision,
nativeInputTick: process.platform === 'win32' ? nativeInputTick : undefined,
editedSinceFocus: false,
typedRecently
}
@ -920,10 +990,21 @@ class InputTelemetryService extends EventEmitter {
if (clearedByEnter) {
this._lastTypedAt = 0
this._typedInCurrentFocus = false
this._imeComposing = false
context.typedRecently = false
}
}
context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus
if (
!context.isComposing &&
this._imeComposing &&
context.editedSinceFocus &&
/[가-힣ㄱ-ㅎㅏ-ㅣ]$/u.test(context.prefix)
) {
context.isComposing = true
} else if (context.isComposing && !/[가-힣ㄱ-ㅎㅏ-ㅣ]$/u.test(context.prefix)) {
context.isComposing = false
}
// 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다.
// 비밀번호·편집 불가 칸과 터미널(명령 기록)은 보지 않는다. 조합 중인 칸도 본다 — 한글은 보내기 직전
@ -942,7 +1023,7 @@ class InputTelemetryService extends EventEmitter {
// 단, 방금 프로그램(오타 교정·제안 수락)이 커서 앞 텍스트를 바꾼 경우에는 끝 편집으로 본다.
this._pruneExpectedInserts(now)
const programmaticEdit =
this._programmaticKeyBudget > 0 ||
this._programmaticKeys > 0 ||
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
if (this._editProbe === null || this._editProbe.key !== focusKey || programmaticEdit) {
this._lastEditAtEnd = true