fix(desktop): prevent fast correction input races

This commit is contained in:
Yun Chan 2026-11-04 07:06:10 +09:00
parent 5ec063c744
commit 21a684d572
12 changed files with 134 additions and 18 deletions

View file

@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
- Prevent fast Han/Eng auto-correction from interleaving with the next keystroke; defer corrections during continuous bursts and apply the current trailing correction region together after typing pauses.
### Planned
- macOS / Linux support
- Additional Whisper model management UI

View file

@ -823,9 +823,8 @@ class InputTelemetryService extends EventEmitter {
}
private _scheduleTextSnapshot(keyClass?: KeyStrokeClass): void {
// Araso 급 빠른 한영 전환: 공백·문장부호 직후에는 40ms 뒤에 즉시 스냅샷을 찍고,
// 일반 글자 입력 중에는 단어를 치는 도중(예: sometime 의 some 시점) 끼어들어 글자를 삼키지 않도록
// 700ms 디바운스 타이머(_textTimer)에 맡긴다(Vim 명령줄 :wq 등은 160ms).
// 공백·문장부호 뒤의 한영 전환은 140ms 동안 다음 키가 없을 때만 시작한다.
// 더 빠른 연속 입력 중에는 삭제 배치와 다음 키가 섞일 수 있으므로 유휴 스냅샷에서 묶어서 교정한다.
if (this._typoTimer) clearTimeout(this._typoTimer)
if (keyClass && TYPING_KEY_CLASSES.has(keyClass) && configGet('typoAutoCorrectEnabled') !== false) {
const isBoundaryKey =
@ -834,7 +833,7 @@ class InputTelemetryService extends EventEmitter {
(keyClass === 'digit' && this._modifiers.shift)
const quickDelay =
isBoundaryKey && this._shouldRunFastTerminalBoundarySnapshot()
? 40
? 140
: !isBoundaryKey && this._terminalTracker.vimMode === 'command'
? 160
: null

View file

@ -23,6 +23,7 @@ import { EventEmitter } from 'events'
import {
TYPO_IGNORED_WORDS_MAX,
TYPO_MIN_IDLE_MS,
TYPO_REGION_MAX_CHARS,
TYPO_REVERT_WINDOW_MS,
buildVocabulary,
detectJamoNoise,
@ -248,9 +249,11 @@ export class TypoCorrectionService extends EventEmitter {
const keyAtDecision = this._deps.lastKeyAt()
const maxDeterministicSpan =
options.trailingWordOnly === true || context.idleMs < TYPO_MIN_IDLE_MS
? MAX_FAST_DELETE_CHARS
: MAX_INPLACE_DELETE_CHARS
options.trailingWordOnly === true && context.idleMs >= LAYOUT_TRAILING_MIN_IDLE_MS
? TYPO_REGION_MAX_CHARS
: options.trailingWordOnly === true || context.idleMs < TYPO_MIN_IDLE_MS
? MAX_FAST_DELETE_CHARS
: MAX_INPLACE_DELETE_CHARS
const allCorrections = detectTypos(prefix, {
includeTrailingToken: true,
ignoredWords,
@ -259,6 +262,7 @@ export class TypoCorrectionService extends EventEmitter {
terminalMode: isTerminal
})
const baseCorrections: TypoCorrection[] = []
let deferredTrailingCorrections = false
if (options.trailingWordOnly !== true) {
for (const c of allCorrections) {
if (prefix.length - c.start <= maxDeterministicSpan) {
@ -266,11 +270,16 @@ export class TypoCorrectionService extends EventEmitter {
}
}
} else {
// trailingWordOnly: 커서 끝에서 가까운 연속 교정 사슬만 남긴다 (예: "ㅑ ㅊ무'ㅅ " → "I can't ",
// 반면 문장 앞쪽의 이미 지나간 긴 문장은 건드리지 않는다).
// 빠른 연속 입력 뒤 일부만 고치면 다음 스냅샷에서 앞쪽 교정이 누락된다.
// 짧은 유휴에는 꼬리 사슬 전체가 들어올 때까지 기다리고, 충분히 멈추면 현재 검사 영역을 한 번에 교정한다.
for (let i = allCorrections.length - 1; i >= 0; i -= 1) {
const c = allCorrections[i]
if (prefix.length - c.start > maxDeterministicSpan) break
if (prefix.length - c.start > maxDeterministicSpan) {
const nextCorr = baseCorrections[0]
const between = nextCorr ? prefix.slice(c.end, nextCorr.start) : ''
deferredTrailingCorrections = /^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2
break
}
if (baseCorrections.length === 0) {
const tailAfter = prefix.slice(c.end)
const nonSpaceTailLen = tailAfter.replace(/[ \t.,!?;:]/gu, '').length
@ -287,6 +296,7 @@ export class TypoCorrectionService extends EventEmitter {
}
}
}
if (deferredTrailingCorrections && context.idleMs < LAYOUT_TRAILING_MIN_IDLE_MS) return 'pass'
const loneJamoRemovals =
!isTerminal && options.trailingWordOnly !== true && (fullCheckEligible || baseCorrections.length > 0)
? detectJamoNoise(prefix, { ignoredWords }).filter(

View file

@ -162,7 +162,7 @@ export function sendWin32UnicodeText(text: string): boolean {
* (선택적 IME 조합 확정 Space) + 커서 앞 백스페이스 N번 + UTF-16 문자열 입력을
* 단 한 번의 Windows SendInput 호출로 입력 큐에 연속해서 주입한다.
*
* Win32 SendInput 규약상 단일 호출 안의 INPUT 배열 사이에 사용자의 물리 키 입력이 끼어들 수 없으므로,
* 다른 프로세스의 입력이 배치 사이에 섞일 수 있으므로 자동 교정 호출자는 연속 타이핑 중 삭제를 미뤄야 한다.
* 배치 내부의 순서만 보장한다. 이전 스냅샷 이후 바뀐 커서/텍스트, 대상 앱의 처리 시간,
* IME 상태까지 보장하지 않는다. 일부 입력만 성공하면 삭제/입력 배치를 재실행하지 않는다.
*/

View file

@ -100,6 +100,25 @@ describe('TypoCorrectionService', () => {
expect(corrected).toHaveBeenCalledTimes(1)
})
it('빠른 연속 입력의 부분 교정은 미루고 멈춘 뒤 현재 영역 전체를 한 번에 교정한다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
const prefix = 'dkssudgktpdy rkatkgkqslek qksrkqtmqslek '.repeat(3)
const expected = '안녕하세요 감사합니다 반갑습니다 '.repeat(3)
expect(
service.handleTypingContext(typingContext({ prefix, idleMs: 380 }), { trailingWordOnly: true })
).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
expect(
service.handleTypingContext(typingContext({ prefix, idleMs: 650 }), { trailingWordOnly: true })
).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledTimes(1)
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(prefix.length, expected)
})
it('아직 치는 중이면(유휴 부족) 고치지 않는다', () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)

View file

@ -25,6 +25,8 @@ import {
interface Internal {
_handleKeyDown(event: { keycode: number; ctrlKey: boolean; altKey: boolean; metaKey: boolean; shiftKey: boolean }): void
_scheduleTextSnapshot(keyClass?: 'letter' | 'space'): void
_captureTextSnapshot: () => Promise<null>
_lastTypedAt: number
}
@ -53,4 +55,25 @@ describe('IME 글자 키', () => {
service._handleKeyDown(key(0))
expect(service._lastTypedAt).toBe(0)
})
it('단어 경계 교정 스냅샷은 140ms 동안 추가 입력이 없을 때만 실행한다', () => {
vi.useFakeTimers()
try {
const service = getInputTelemetryService() as unknown as Internal
const capture = vi.fn(async () => null)
service._captureTextSnapshot = capture
service._scheduleTextSnapshot('space')
vi.advanceTimersByTime(139)
service._scheduleTextSnapshot('letter')
vi.advanceTimersByTime(1)
expect(capture).not.toHaveBeenCalled()
service._scheduleTextSnapshot('space')
vi.advanceTimersByTime(140)
expect(capture).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
})

View file

@ -0,0 +1,29 @@
# 2026-11-02 Windows GUI verification and typing-race follow-up
All dates below are KST. Runtime artifacts are under `test-results/recovery-2026-11-02/` (ignored). The tested installed application is `C:\Users\encep\AppData\Local\Programs\@d3rodesktop\D3RO Voice.exe`, file version **1.16.0**. No Electron process was launched from the agent shell; the existing installation was restored through its taskbar button.
## Desktop meeting import — PASS
- Restored the existing installation, opened Meetings → **녹음 파일 가져오기**, selected the real 8.498-second `local-speech.wav` through the native file picker, and reached the `local-speech` meeting detail.
- The transcript tab shows `[00:00] Hello. This is a local meeting import test. We will review the project tomorrow.` with the expected timestamp.
- **요약 만들기** used the existing local pipeline and produced a Korean summary plus `내일 프로젝트 검토 진행` as an action item; the Documents tab count is 1. No cloud or paid inference was requested.
- Screenshots: `meeting-list.png`, `meeting-import-transcript.png`, `meeting-summary-progress.png`. The test meeting was left in place; no personal data was deleted or reset.
## Native Korean IME under CPU and model load — PASS with method limits
- `installed-1.16.0-hangul.json`: calibration plus idle/CPU cases at requested 60/30/15 ms pacing, **7/7 exact matches**. All 240/240 injected events per corpus case were accepted. CPU cases used 23 bounded workers and recorded approximately 100% system CPU.
- `installed-1.16.0-hangul-model-load.json`: **7/7 exact matches**, including native IME composition evidence and all 240/240 events per corpus case.
- `/api/ps` was empty before the model test. A direct local `gemma4:e4b` generate request returned HTTP 200 in **9.389 s**, with **9.275 s model-load duration**. Its inferred request interval overlaps the report's `idle-60` and `idle-30` cases, both exact matches. This is direct Ollama cold-load overlap, not a claim about product-triggered warmup.
- The model was explicitly unloaded after the test; final `/api/ps` is empty. Responses: `ollama-cold-generate.json`, `ollama-ps-before.json`, `ollama-ps-after.json`, `ollama-ps-final.json`.
- These are synthetic scan-code tests in the fixture's own WinForms field, not physical-keyboard, Chromium, terminal, or hardware-IME proof. An initial run aborted on the fixture's foreground guard and is not counted as a pass.
## Latin-layout correction control — defect reproduced, source fixed, updated-app GUI still pending
- `installed-1.16.0-latin-control.json` passed only the IME calibration (**1/7**). The six layout-correction cases failed. Examples include `d안녕하세요`, an injected next-word `r` appearing during backspaces, and earlier words remaining unconverted.
- Installed-app logs reported successful `SendInput` replacement counts while the fixture recorded different final text. A single native call therefore does not establish that concurrent input cannot interleave with the replacement.
- Source changes, not yet shipped in the running 1.16.0 installation:
- `InputTelemetryService` waits for a 140 ms gap at a word boundary instead of taking the 40 ms snapshot during a faster burst.
- `TypoCorrectionService` does not partially correct a contiguous trailing chain during the short idle window. At the 650 ms idle checkpoint it corrects the current correction region, up to the existing 120-character core limit, in one replacement. Unrelated earlier text still does not force whole-line rewriting.
- The Win32 comment no longer claims that other processes cannot interleave input.
- Regression coverage: 140 ms rescheduling and deferral of a 120-character burst, followed by one exact Korean replacement. Targeted **48/48**, full desktop **192 files / 2,773 tests**, desktop typecheck, touched-scope lint, `git diff --check`, and production `electron-vite build` all PASS.
- The source fix has **not** been exercised in an updated Electron GUI. Re-run the same Latin control after packaging/installing the change, then expand to physical keyboard and Chromium/terminal surfaces before closing GAP-INPUT-11.

View file

@ -2,7 +2,7 @@
> Status: ACTIVE
> Last full audit: 2026-09-13
> Last update: 2026-11-01 — 미완료 작업 복구·Windows 1.16.0 및 엔진 배포 완료. 회의 import 계정 전환 경합을 수정했고, 입력 A/B는 이전 2/17 → 현재 17/17이다. 공개 엔진을 1.10.0에서 1.16.0으로 올려 CPU/UIA 수정을 전달한다. 모바일 `.3`의 격리 에뮬레이터 auth/signup 2/2 PASS와 기존 Fold6 실패, `.2` 과거 증거를 구분했다. 실제 부하 타이핑과 모바일 운영 배포는 남아 있다. 상세 증거: [completion report](../evidence/2026-11-01-completion.md).
> Last update: 2026-11-02 — Windows 1.16.0 실GUI에서 회의 파일 선택→전사→로컬 요약 생성을 확인했다. 네이티브 한글 IME는 100% CPU 및 `gemma4:e4b` 콜드 로딩 중 7/7 정확히 통과했다. 한영 자판 교정 대조군은 다음 키가 백스페이스에 섞이는 결함을 재현했고, 소스에서는 140ms 입력 간격 게이트와 유휴 후 현재 영역 일괄 교정으로 수정했다. 데스크톱 2,773개 테스트·빌드는 GREEN이지만 수정본 설치 GUI와 모바일 운영 배포는 남아 있다. 상세 증거: [2026-11-02 verification](../evidence/2026-11-02-verification.md).
>
> Previous update: 2026-11-01 — **기존 녹음 파일을 회의로 가져오기(`MTG-13`).** 데스크톱은 기존 ffmpeg 파일 전사를 재사용해 타임스탬프 전사와 재생용 WAV를 회의에 저장하고 일반 기록 중복을 피하며, 모바일은 회의 생성 후 기존 durable meeting import queue로 연결한다. 데스크톱 2,768개·모바일 599개·core 572개 테스트와 실제 MP3/M4A 변환 2개가 GREEN이다. 실제 Electron GUI와 인증 모바일 기기 E2E는 남아 있어 두 표면 모두 `[~]`다 (`04`, `06`, `11` GAP-MTG-03).
>

View file

@ -272,4 +272,6 @@ DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `s
| Path/loopback resolution | `src/main/utils/paths.ts`, `src/main/utils/loopback.ts` |
| Sidecar source / packaging | `sidecar/main.py`, `scripts/setup-sidecar.mjs`, `scripts/build-sidecar.mjs`, `scripts/ci/verify-sidecar-bundle.mjs` |
2026-11-01 verification: source A/B 2/17 before vs 17/17 current; real MP3/M4A conversion 2/2; account-switch regression 3/3 after reproducing all three failures; local packaged STT transcribed the synthetic 8.498 s fixture exactly. Windows 1.16.0 installer, portable and runtime are published; the rebuilt sidecar passed separate-process startup/health and the packaged Windows keyboard N-API binding loaded successfully without starting hooks. Required sidecar minimum 1.16.0 delivers CPU budgeting and terminal UIA changes. Windows GUI/native helper remained unavailable; physical typing/model-load overlap and installation into the user's running app are still unverified. [Recovery evidence](../evidence/2026-11-01-completion.md).
2026-11-01 verification: source A/B 2/17 before vs 17/17 current; real MP3/M4A conversion 2/2; account-switch regression 3/3 after reproducing all three failures; local packaged STT transcribed the synthetic 8.498 s fixture exactly. Windows 1.16.0 installer, portable and runtime are published; the rebuilt sidecar passed separate-process startup/health and the packaged Windows keyboard N-API binding loaded successfully without starting hooks. Required sidecar minimum 1.16.0 delivers CPU budgeting and terminal UIA changes. [Recovery evidence](../evidence/2026-11-01-completion.md).
2026-11-02 verification: installed 1.16.0 passed the actual Electron picker→timestamped transcript→local minutes/action-item journey. Native Korean IME passed 7/7 under bounded 100% CPU and 7/7 with a direct 9.389 s `gemma4:e4b` cold-load request overlapping two typing cases. The Latin-layout control exposed next-key/backspace interleaving; source now waits 140 ms at boundaries and batches the current trailing correction region after a 650 ms pause. Full desktop 2,773 tests and production build pass, but the fixed source still needs an updated-app GUI run. Synthetic WinForms input is not physical-keyboard/Chromium/terminal proof. [Verification evidence](../evidence/2026-11-02-verification.md).

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,3 +1,26 @@
# Session Handoff — 2026-11-02 (Windows 실GUI 검증 & 한영 교정 경합 수정)
> Environment: Windows (ALPACA-HOME)
> Starting point: `main` at `5ec063c`, clean tree. No commit or release was created in this session.
## 완료한 작업
- 설치본 Windows 1.16.0의 실제 Electron GUI에서 회의 **녹음 파일 가져오기 → 타임스탬프 전사 → 로컬 요약·할 일 생성**을 통과시켰다. 데스크톱 MTG-13은 `[x]`, Android file-to-minutes는 미검증으로 남는다.
- 네이티브 한글 IME는 bounded 100% CPU에서 7/7, `gemma4:e4b` direct cold load(9.389초)와 겹친 시험에서도 7/7 정확히 통과했다. Ollama는 시험 전후 `models:[]`로 복원했다.
- 한영 자판 교정 대조군은 1/7만 통과하며 `d안녕하세요`와 다음 키 `r`이 백스페이스에 섞이는 결함을 재현했다.
- 소스 수정: `InputTelemetryService` 경계 스냅샷 40→140ms, `TypoCorrectionService`는 짧은 유휴의 연속 꼬리 부분 교정을 미루고 650ms 유휴 시 현재 교정 영역(최대 core 120자)을 한 번에 교정한다.
- 검증: 표적 48/48, 데스크톱 전체 192 files / 2,773 tests, typecheck, touched lint, production build 모두 PASS.
## 남은 작업
1. 수정본을 패키징·설치한 Electron에서 동일한 Latin layout 대조군을 다시 실행한다. 현재 사용자 설치본은 아직 1.16.0이며 수정본은 커밋·배포되지 않았다.
2. 물리 키보드와 Chromium/terminal에서도 교정 경합을 확인한다. 이번 통과는 WinForms synthetic scan-code 증거이므로 GAP-INPUT-11은 `[~]`다.
3. 모바일 운영 배포와 인증 Android file-to-minutes는 외부 자격 증명·기기 게이트가 남아 있다.
상세 증거: `docs/evidence/2026-11-02-verification.md`, 무시된 런타임 파일은 `test-results/recovery-2026-11-02/`. 회의 GUI 검증에서 만든 `local-speech` 회의는 삭제하지 않고 남겼다.
---
# Session Handoff — 2026-08-19 (Ollama 온보딩 & 데스크톱 윈도우 실행 아키텍처 완료)
> Environment: Windows (ALPACA-HOME)