d3ro-voice/apps/desktop/src/main/services/UiaContextService.ts
Yun Chan 7fe49c437e chore: land in-progress workspace changes before 1.16.2
The tree carried uncommitted work from several areas (web push, mobile
screens, admin charts, test-hygiene cleanup, CI and map docs). It is landed
as one commit so the release pipeline can start from a clean tree; the
desktop transcript-correction behaviour shipped in the previous commit and
is unchanged here.
2026-11-05 21:58:44 +09:00

209 lines
6.8 KiB
TypeScript

// src/main/services/UiaContextService.ts
//
// 사이드카의 UIA 브리지(`GET /uia/focus`)를 감싸는 유일한 창구.
//
// 사이드카인가:
// Win32 케어렛 API(GetGUIThreadInfo)는 Chromium/Electron 에서 동작하지 않고,
// Node UIA 바인딩(selection-hook / xa11y)은 케어 rect 나 IsPassword 를 노출하지
// 않는다. 이미 배포 중인 Python 사이드카에 UIA 브리지를 두는 것이 검증된 유일한 경로다.
//
// 안전 규칙:
// - 비밀번호 필드는 브리지가 fail-closed 로 차단하지만, 여기서도 한 번 더 막는다.
// - 읽기 실패/타임아웃은 텍스트를 쓰지 않는다 (available=false).
// - 실패 후에는 백오프를 걸어 매 키입력마다 사이드카를 두드리지 않는다.
import {
emptyFocusSnapshot,
type FocusSnapshot,
type FocusTextSource,
type UiRect
} from '@d3ro/core/input-intelligence'
import { getLogger } from './LoggerService'
import { getLocalSTTService } from './LocalSTTService'
const logger = getLogger('UiaContextService')
const REQUEST_TIMEOUT_MS = 1500
/**
* 실패 후 재시도 대기 (ms).
*
* 최초 실패는 대부분 "사이드카가 아직 포트를 열지 않음" 이다 — 실측: 부팅 0.87초 후 첫 실패,
* 사이드카 준비는 1.1초 후였다. 20초를 통째로 백오프하면 앱을 켠 직후의 입력이 전부 죽으므로
* 일시 실패는 짧게 시작해 배수로 늘리고, 브리지 자체가 없는 경우(미지원 플랫폼)만 길게 잡는다.
*/
const BACKOFF_STEPS_MS = [300, 600, 1200, 2500] as const
/** 영구 실패(브리지 없음) 백오프 */
const BACKOFF_PERMANENT_MS = 5 * 60 * 1000
interface UiaBridgePayload {
available?: boolean
reason?: string
isPassword?: boolean
isEditable?: boolean
isComposing?: boolean
hasSelection?: boolean
controlType?: string | null
controlName?: string | null
className?: string | null
textSource?: string
text?: string
caretOffset?: number | null
caretRect?: UiRect | null
elementRect?: UiRect | null
windowTitle?: string | null
processId?: number | null
capturedAt?: number
}
class UiaContextService {
private _backoffUntil = 0
/** 연속 실패 수 — 백오프 단계 계산용 */
private _failureStreak = 0
private _lastReason = ''
private _inFlight: Promise<FocusSnapshot> | null = null
private _last: FocusSnapshot | null = null
private _lastSuccessAt = 0
get lastSnapshot(): FocusSnapshot | null {
return this._last
}
get lastSuccessAt(): number {
return this._lastSuccessAt
}
/** 브리지 사용 가능 여부 (백오프 상태면 false). */
isAvailable(now = Date.now()): boolean {
return now >= this._backoffUntil
}
get lastReason(): string {
return this._lastReason
}
/**
* 현재 포커스 입력 요소 스냅샷.
*
* 동시 호출은 하나의 요청으로 합친다 — 키 입력마다 부르므로 중복 방지가 중요하다.
*/
async getSnapshot(now = Date.now()): Promise<FocusSnapshot> {
if (!this.isAvailable(now)) {
return emptyFocusSnapshot(this._lastReason || 'backoff', now)
}
if (this._inFlight) return this._inFlight
this._inFlight = this._fetch(now)
try {
return await this._inFlight
} finally {
this._inFlight = null
}
}
/** 테스트/설정 변경 시 상태 초기화. */
reset(): void {
this._backoffUntil = 0
this._failureStreak = 0
this._lastReason = ''
}
private async _fetch(now: number): Promise<FocusSnapshot> {
let baseUrl: string
try {
baseUrl = await getLocalSTTService().ensureSidecar()
} catch (error) {
return this._fail(
`sidecar-unavailable:${error instanceof Error ? error.message : String(error)}`,
now
)
}
let payload: UiaBridgePayload
try {
const response = await fetch(`${baseUrl}/uia/focus`, {
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
})
if (!response.ok) {
return this._fail(`http-${response.status}`, now)
}
payload = (await response.json()) as UiaBridgePayload
} catch (error) {
return this._fail(
`request-failed:${error instanceof Error ? error.message : String(error)}`,
now
)
}
if (!payload.available) {
// 브리지가 없는 환경(미지원 플랫폼/미설치)은 길게 백오프한다.
return this._fail(payload.reason ?? 'unavailable', now)
}
const snapshot: FocusSnapshot = {
available: true,
isPassword: payload.isPassword === true,
isEditable: payload.isEditable === true,
isComposing: payload.isComposing === true,
hasSelection: payload.hasSelection === true,
controlType: payload.controlType ?? undefined,
controlName: payload.controlName ?? undefined,
className: payload.className ?? undefined,
textSource: normalizeTextSource(payload.textSource),
text: typeof payload.text === 'string' ? payload.text : '',
caretOffset: typeof payload.caretOffset === 'number' ? payload.caretOffset : null,
caretRect: payload.caretRect ?? null,
elementRect: payload.elementRect ?? null,
windowTitle: payload.windowTitle ?? null,
appName: null,
processId: typeof payload.processId === 'number' ? payload.processId : null,
capturedAt: typeof payload.capturedAt === 'number' ? payload.capturedAt : now
}
// 2차 방어: 비밀번호로 판정되면 텍스트를 즉시 버린다 (fail-closed).
if (snapshot.isPassword) {
snapshot.text = ''
snapshot.textSource = 'none'
snapshot.caretOffset = null
}
this._last = snapshot
this._lastSuccessAt = now
this._backoffUntil = 0
this._failureStreak = 0
this._lastReason = ''
return snapshot
}
private _fail(reason: string, now: number): FocusSnapshot {
this._lastReason = reason
// 영구적 사용 불가(미지원 플랫폼/미설치)는 길게, 일시 오류는 단계적으로.
const permanent = reason === 'uiautomation-missing' || reason.startsWith('bridge-import')
const waitMs = permanent
? BACKOFF_PERMANENT_MS
: BACKOFF_STEPS_MS[Math.min(this._failureStreak, BACKOFF_STEPS_MS.length - 1)]
this._failureStreak += 1
this._backoffUntil = now + waitMs
logger.warn(
`UIA 스냅샷 사용 불가 (${reason}) — ${waitMs}ms 백오프 (연속 ${this._failureStreak}회)`
)
return emptyFocusSnapshot(reason, now)
}
}
function normalizeTextSource(value: string | undefined): FocusTextSource {
if (value === 'value' || value === 'text' || value === 'legacy') return value
return 'none'
}
let instance: UiaContextService | null = null
export function getUiaContextService(): UiaContextService {
if (!instance) instance = new UiaContextService()
return instance
}
export function resetUiaContextServiceForTests(): void {
instance = null
}