From 3e6cfd1ba8023877c12e325cc86fc195b60d4972 Mon Sep 17 00:00:00 2001 From: Yun Chan Date: Wed, 21 Oct 2026 00:28:40 +0900 Subject: [PATCH] fix(keybinding): release held shortcuts and modifiers when the screen locks or the PC sleeps The lock desktop swallows keyup, so a hold-to-talk recording never ended, the first shortcut after unlocking was dropped as auto-repeat, and Win from Win+L made the next suggestion accept wait out the full 1.5s modifier timeout. On powerMonitor lock-screen/suspend the chord machine now emits released for emitted triggers and clears its state, and modifier tracking forgets held keys. --- .../src/main/services/KeyBindingService.ts | 24 ++++++++++++- .../src/main/services/modifier-state.ts | 5 +++ .../services/keybinding-redteam-r2-16.test.ts | 36 ++++++++++++++++++- apps/desktop/tests/setup.ts | 4 +++ .../core/__tests__/keybinding-runtime.test.ts | 11 ++++++ packages/core/src/keybinding-runtime.ts | 16 +++++++++ 6 files changed, 94 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/main/services/KeyBindingService.ts b/apps/desktop/src/main/services/KeyBindingService.ts index 741ed1a..09bbd60 100644 --- a/apps/desktop/src/main/services/KeyBindingService.ts +++ b/apps/desktop/src/main/services/KeyBindingService.ts @@ -10,11 +10,12 @@ // (예약 정책 — 플랫폼 · 기능 게이트 — 은 keybinding-accelerator-policy.ts 의 순수 함수) import { EventEmitter } from 'events' -import { globalShortcut } from 'electron' +import { globalShortcut, powerMonitor } from 'electron' import { uIOhook, UiohookKey } from 'uiohook-napi' import type { UiohookKeyboardEvent, UiohookMouseEvent } from 'uiohook-napi' import { getLogger } from './LoggerService' import { acquireGlobalInputHook } from './global-input-hook' +import { forgetHeldModifiers } from './modifier-state' import { configGet, loadKeyBindings, onConfigChanged } from './ConfigService' import { acceleratorsToReserve, suggestionCaptureAccelerators } from './keybinding-accelerator-policy' import type { ReservableBinding } from './keybinding-accelerator-policy' @@ -284,6 +285,7 @@ class KeyBindingService extends EventEmitter { /** 기능 스위치(제안 on/off) 변경 시 accelerator 를 다시 맞추는 구독 해제자 */ private _offConfigChanged: (() => void) | null = null + private _offSessionLock: (() => void) | null = null private _onKeyDown: ((e: UiohookKeyboardEvent) => void) | null = null private _onKeyUp: ((e: UiohookKeyboardEvent) => void) | null = null @@ -337,6 +339,7 @@ class KeyBindingService extends EventEmitter { if (event.key === 'suggestionEnabled') this._syncAccelerators() }) this._syncAccelerators() + this._watchSessionLock() logger.info('Key binding listeners attached to global input hook') } catch (error) { const d3roError = new D3ROError( @@ -378,6 +381,8 @@ class KeyBindingService extends EventEmitter { this._offConfigChanged = null this._clearRuntimeState() this._unregisterOwnedAccelerators() + this._offSessionLock?.() + this._offSessionLock = null logger.info('uiohook stopped') } catch (error) { @@ -540,6 +545,23 @@ class KeyBindingService extends EventEmitter { this._ownedAccelerators.clear() } + /** + * 화면 잠금·절전 중에는 잠금 데스크톱이 keyup 을 가져가 훅이 받지 못한다. + * 그대로 두면 hold 녹음이 안 끝나고, 잠금을 푼 뒤 첫 단축키가 auto-repeat 로 버려진다. + */ + private _watchSessionLock(): void { + const releaseHeld = (): void => { + this._machine.releaseAll() + this._altGr.reset() + forgetHeldModifiers() + } + const events = ['lock-screen', 'suspend'] as const + for (const event of events) powerMonitor.on(event, releaseHeld) + this._offSessionLock = () => { + for (const event of events) powerMonitor.removeListener(event, releaseHeld) + } + } + /** 눌림 · 더블프레스 · AltGr 보류 타이머를 모두 비운다. */ private _clearRuntimeState(): void { this._machine.reset() diff --git a/apps/desktop/src/main/services/modifier-state.ts b/apps/desktop/src/main/services/modifier-state.ts index 97eff1d..80634ad 100644 --- a/apps/desktop/src/main/services/modifier-state.ts +++ b/apps/desktop/src/main/services/modifier-state.ts @@ -28,6 +28,11 @@ function attach(): void { }) } +/** 떼는 이벤트를 놓쳤을 때(Win+L 의 Win 등) 눌림 상태를 잊는다. 안 그러면 다음 삽입이 매번 시간 초과까지 기다린다. */ +export function forgetHeldModifiers(): void { + held.clear() +} + /** 추적을 시작한다 — 단축키가 눌리기 전에 붙어 있어야 누른 상태를 안다. */ export function trackModifierKeys(): void { attach() diff --git a/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts b/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts index 6bb6625..5ca6272 100644 --- a/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts +++ b/apps/desktop/tests/main/services/keybinding-redteam-r2-16.test.ts @@ -5,7 +5,7 @@ // 3) 사용자가 비운 액션([])은 다른 액션 저장 · 재시작 뒤에도 비어 있다. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { globalShortcut, ipcMain } from 'electron' +import { globalShortcut, ipcMain, powerMonitor } from 'electron' import { uIOhook } from 'uiohook-napi' import type { UiohookMouseEvent } from 'uiohook-napi' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' @@ -220,6 +220,40 @@ describe('KeyBindingService — globalShortcut 예약 · 마우스 release', () expect(events).toEqual(['dictation:pressed', 'dictation:released']) }) + + it('화면이 잠기면 누르고 있던 hold 바인딩에 released 를 보내고, 잠금을 푼 뒤 첫 누름이 다시 동작한다', () => { + setPlatform('win32') + const map = createDefaultBindingMap() + map.dictation = [{ device: 'mouse', code: MouseButton.Back, ctrl: false, alt: false, shift: false, meta: false }] + configSet('keyBindings', map) + vi.mocked(powerMonitor.on).mockClear() + + const service = getKeyBindingService() + service.loadFromConfig() + service.start() + + const handlerOf = (event: string): ((e: UiohookMouseEvent) => void) => { + const call = vi.mocked(uIOhook.on).mock.calls.find((c) => c[0] === event) + if (!call) throw new Error(`no ${event} handler`) + return call[1] as (e: UiohookMouseEvent) => void + } + const lockCall = vi.mocked(powerMonitor.on).mock.calls.find((c) => c[0] === 'lock-screen') + if (!lockCall) throw new Error('no lock-screen handler') + const onLock = lockCall[1] as () => void + const events: string[] = [] + const listener = (p: KeyBindingTriggerPayload): void => { + events.push(`${p.actionId}:${p.type}`) + } + service.on('triggered', listener) + const back = { button: MouseButton.Back, altKey: false, ctrlKey: false, shiftKey: false, metaKey: false } as unknown as UiohookMouseEvent + + handlerOf('mousedown')(back) + onLock() // 떼는 이벤트는 잠금 데스크톱이 가져간다 + handlerOf('mousedown')(back) + service.off('triggered', listener) + + expect(events).toEqual(['dictation:pressed', 'dictation:released', 'dictation:pressed']) + }) }) // ============================================================ diff --git a/apps/desktop/tests/setup.ts b/apps/desktop/tests/setup.ts index bf197cc..00b1554 100644 --- a/apps/desktop/tests/setup.ts +++ b/apps/desktop/tests/setup.ts @@ -73,6 +73,10 @@ vi.mock('electron', () => ({ shell: { openExternal: vi.fn(async () => undefined), }, + powerMonitor: { + on: vi.fn(), + removeListener: vi.fn(), + }, safeStorage: { isEncryptionAvailable: vi.fn(() => false), encryptString: vi.fn((s: string) => Buffer.from(s, 'utf-8')), diff --git a/packages/core/__tests__/keybinding-runtime.test.ts b/packages/core/__tests__/keybinding-runtime.test.ts index 2fe0af5..3ea9c3e 100644 --- a/packages/core/__tests__/keybinding-runtime.test.ts +++ b/packages/core/__tests__/keybinding-runtime.test.ts @@ -195,6 +195,17 @@ describe('ChordStateMachine — press / release', () => { expect(events.map(label)).toEqual(['history-popup:pressed', 'history-popup:released']) }) + it('releaseAll sends released for held triggers and accepts the next press after a lost keyup', () => { + machine.setBindings([entry('history-popup', kb(0x56, { ctrl: true, shift: true }))]) + const key = keyOf(0x56, { ctrl: true, shift: true }) + + machine.keyDown(key) + machine.releaseAll() + machine.keyDown(key) + + expect(events.map(label)).toEqual(['history-popup:pressed', 'history-popup:released', 'history-popup:pressed']) + }) + it('ignores keys that match no binding and releases nothing that was not pressed', () => { machine.setBindings([entry('history-popup', kb(0x56, { ctrl: true, shift: true }))]) machine.keyDown(keyOf(0x41)) diff --git a/packages/core/src/keybinding-runtime.ts b/packages/core/src/keybinding-runtime.ts index 1921f4d..b3aeb99 100644 --- a/packages/core/src/keybinding-runtime.ts +++ b/packages/core/src/keybinding-runtime.ts @@ -276,6 +276,22 @@ export class ChordStateMachine { this._active.clear() } + /** + * 떼는 이벤트가 오지 않을 순간(화면 잠금·절전)에 부른다. 이미 보낸 pressed 에는 released 를 보내 + * hold 녹음이 끝나게 하고, 보류 중인 트리거는 버린다. 그 뒤 reset 처럼 모두 비운다. + * 안 비우면 잠금을 푼 뒤 첫 누름이 auto-repeat 로 버려진다. + */ + releaseAll(): void { + for (const trigger of this._pending) { + trigger.cancelTimer?.() + trigger.cancelTimer = null + trigger.status = 'cancelled' + } + this._pending.clear() + for (const key of [...this._isDown]) this._release(key) + this.reset() + } + // ── 입력 ─────────────────────────────────────────────── /**