合并 main 的合并前复核修复到镜牢选队分支

Browse Source
分支从 8a9495b 分出,缺 main 上 a74fda0 的急停与驱动复核修复。
两边都保留,不取单边:

- 急停:沿用分支的 GetAsyncKeyState 轮询与 End 键(pynput 钩子在该
  机器收不到键,F12 是 Steam 截图键);移植 main 的 on_stop 释放驱动
  按住的鼠标键、250 毫秒强退兜底、listening() 管理监听生命周期。
  按键状态改为独立绑定(SHORT 返回值),接口不可用时启动即报告。
- 驱动输入:同时保留句柄级前台校验、press_ms/settle 与 main 的
  停止标志、输入锁和按键记录;点击经 down()/up() 以便急停释放。
  前台校验改用本模块的类型化 _api 绑定。
- 代理每次点击按当前句柄重新 bind_window:代理复用时不再拿安装时
  的旧句柄拒绝游戏重启后的全部点击。
- aalc_task:listening() 包住整个任务,内部安装两个选队补丁。
- 分支新增测试改为替换模块接口,不再直接 patch ctypes.windll
  (Linux 上 9 项报错);README 急停键改为 End。

验证:Linux / Python 3.12 全套 474 项通过;git diff --check 通过。
Windows 热键、驱动和选队仍需实机回归。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-11-14 03:19:53 +00:00
co-authored by Claude Opus 5.5
14 changed files with 490 additions and 182 deletions
+145 -32
View File
@@ -9,9 +9,12 @@
实现上踩过一个坑: 先用了 pynput 的 GlobalHotKeys, 静态注册成功、线程也活着, 但 实现上踩过一个坑: 先用了 pynput 的 GlobalHotKeys, 静态注册成功、线程也活着, 但
keybd_event 和 SendInput 两种注入都触发不了它 —— 钩子在当前会话下收不到键。 keybd_event 和 SendInput 两种注入都触发不了它 —— 钩子在当前会话下收不到键。
改成 GetAsyncKeyState 轮询后实测可用。这里的测试守住轮询方案的几个关键性质。 改成 GetAsyncKeyState 轮询后实测可用。这里的测试守住轮询方案的几个关键性质,
以及急停时"先放开鼠标、卡住也按时退出"的保证。
""" """
import sys import sys
import tempfile
import threading
import unittest import unittest
from pathlib import Path from pathlib import Path
from unittest import mock from unittest import mock
@@ -19,10 +22,16 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from lc_mcp import killswitch # noqa: E402 from lc_mcp import killswitch # noqa: E402
PRESSED = -32768 # SHORT 0x8000: GetAsyncKeyState 的"当前按下"位
def key_state(value):
return mock.patch.object(killswitch, '_key_state_api', return_value=lambda vk: value)
class ResolveVkTest(unittest.TestCase): class ResolveVkTest(unittest.TestCase):
"""键名解析必须严格: 认不出来要返回 None, 不能悄悄用默认值 —— """键名解析必须严格: 认不出来要返回 None, 不能悄悄用默认值 ——
否则用户以为设成了 F11, 实际还在监听 F12。""" 否则用户以为设成了 F11, 实际还在监听别的键。"""
def test_common_keys(self): def test_common_keys(self):
self.assertEqual(killswitch.resolve_vk('f12'), 0x7B) self.assertEqual(killswitch.resolve_vk('f12'), 0x7B)
@@ -30,6 +39,10 @@ class ResolveVkTest(unittest.TestCase):
self.assertEqual(killswitch.resolve_vk('esc'), 0x1B) self.assertEqual(killswitch.resolve_vk('esc'), 0x1B)
self.assertEqual(killswitch.resolve_vk('pause'), 0x13) self.assertEqual(killswitch.resolve_vk('pause'), 0x13)
def test_default_is_end_not_steam_screenshot_key(self):
self.assertEqual(killswitch.DEFAULT_KEY, 'end')
self.assertEqual(killswitch.resolve_vk(None), 0x23)
def test_accepts_angle_brackets(self): def test_accepts_angle_brackets(self):
self.assertEqual(killswitch.resolve_vk('<f12>'), 0x7B) self.assertEqual(killswitch.resolve_vk('<f12>'), 0x7B)
@@ -37,14 +50,15 @@ class ResolveVkTest(unittest.TestCase):
self.assertEqual(killswitch.resolve_vk(' F12 '), 0x7B) self.assertEqual(killswitch.resolve_vk(' F12 '), 0x7B)
def test_empty_uses_default(self): def test_empty_uses_default(self):
self.assertEqual(killswitch.resolve_vk(''), killswitch.VK[killswitch.DEFAULT_KEY]) for key in ('', None, ' '):
self.assertEqual(killswitch.resolve_vk(None), killswitch.VK[killswitch.DEFAULT_KEY]) self.assertEqual(killswitch.resolve_vk(key), killswitch.VK[killswitch.DEFAULT_KEY])
def test_unknown_returns_none(self): def test_unknown_returns_none(self):
self.assertIsNone(killswitch.resolve_vk('nosuchkey')) self.assertIsNone(killswitch.resolve_vk('nosuchkey'))
class InstallTest(unittest.TestCase): class InstallTest(unittest.TestCase):
"""装不上不能把任务带崩,但必须说清楚怎么应急。"""
def test_reports_unknown_key_and_suggests_fallback(self): def test_reports_unknown_key_and_suggests_fallback(self):
lines = [] lines = []
@@ -54,24 +68,35 @@ class InstallTest(unittest.TestCase):
self.assertIn('认不出键名', joined) self.assertIn('认不出键名', joined)
self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段') self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段')
def test_reports_when_keyboard_api_is_unavailable(self):
lines = []
with mock.patch.object(killswitch, '_key_state_api', side_effect=AttributeError('no user32')):
got = killswitch.install(log=lines.append)
self.assertIsNone(got)
joined = '\n'.join(lines)
self.assertIn('急停热键不可用', joined)
self.assertIn('Ctrl+Alt+Del', joined)
def test_installs_and_logs_the_key(self): def test_installs_and_logs_the_key(self):
lines = [] lines = []
with mock.patch.object(killswitch.KillSwitch, 'start', lambda self: self): with key_state(0), mock.patch.object(killswitch.KillSwitch, 'start', lambda self: self):
switch = killswitch.install(log=lines.append, key='f11') switch = killswitch.install(log=lines.append, key='f11')
self.assertIsInstance(switch, killswitch.KillSwitch) self.assertIsInstance(switch, killswitch.KillSwitch)
self.assertEqual(switch.vk, 0x7A) self.assertEqual(switch.vk, 0x7A)
self.assertIn('F11', '\n'.join(lines)) joined = '\n'.join(lines)
self.assertIn('F11', joined)
self.assertIn('游戏窗口保留', joined)
def test_env_var_overrides_default(self): def test_env_var_overrides_default(self):
with mock.patch.dict(killswitch.os.environ, {'LCP_KILL_KEY': 'esc'}), \ with mock.patch.dict(killswitch.os.environ, {'LCP_KILL_KEY': 'esc'}), key_state(0), \
mock.patch.object(killswitch.KillSwitch, 'start', lambda self: self): mock.patch.object(killswitch.KillSwitch, 'start', lambda self: self):
switch = killswitch.install(log=lambda m: None) switch = killswitch.install(log=lambda m: None)
self.assertEqual(switch.vk, 0x1B) self.assertEqual(switch.vk, 0x1B)
def test_start_failure_is_reported_not_raised(self): def test_start_failure_is_reported_not_raised(self):
lines = [] lines = []
with mock.patch.object(killswitch.KillSwitch, 'start', with key_state(0), mock.patch.object(killswitch.KillSwitch, 'start',
side_effect=RuntimeError('boom')): side_effect=RuntimeError('boom')):
got = killswitch.install(log=lines.append) got = killswitch.install(log=lines.append)
self.assertIsNone(got) self.assertIsNone(got)
self.assertIn('启动失败', '\n'.join(lines)) self.assertIn('启动失败', '\n'.join(lines))
@@ -81,60 +106,148 @@ class PollingTest(unittest.TestCase):
"""轮询判断的核心:0x8000 位。测错位会导致"一直触发"或"永不触发"。""" """轮询判断的核心:0x8000 位。测错位会导致"一直触发"或"永不触发"。"""
def test_high_bit_means_pressed(self): def test_high_bit_means_pressed(self):
with mock.patch.object(killswitch.ctypes.windll.user32, 'GetAsyncKeyState', for value in (PRESSED, PRESSED | 1):
return_value=0x8000): with self.subTest(value=value), key_state(value):
self.assertTrue(killswitch._pressed(0x7B)) self.assertTrue(killswitch._pressed(0x7B))
def test_low_bits_are_not_pressed(self): def test_low_bits_are_not_pressed(self):
# 0x0001 表示"上次调用后被按过", 不代表当前按住 —— 不能当成按下 # 0x0001 表示"上次调用后被按过", 不代表当前按住 —— 不能当成按下
with mock.patch.object(killswitch.ctypes.windll.user32, 'GetAsyncKeyState', with key_state(0x0001):
return_value=0x0001):
self.assertFalse(killswitch._pressed(0x7B)) self.assertFalse(killswitch._pressed(0x7B))
def test_zero_is_not_pressed(self): def test_zero_is_not_pressed(self):
with mock.patch.object(killswitch.ctypes.windll.user32, 'GetAsyncKeyState', with key_state(0):
return_value=0):
self.assertFalse(killswitch._pressed(0x7B)) self.assertFalse(killswitch._pressed(0x7B))
def test_poll_thread_fires_on_press(self):
sw = killswitch.KillSwitch(0x23, log=lambda m: None)
exited = threading.Event()
with key_state(PRESSED), mock.patch.object(killswitch, 'START_DELAY', 0), \
mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: exited.set()):
sw.start()
self.assertTrue(exited.wait(2))
sw._thread.join(2)
self.assertTrue(sw.fired)
def test_broken_api_stops_polling_with_a_message(self):
lines = []
sw = killswitch.KillSwitch(0x23, log=lines.append)
with mock.patch.object(killswitch, '_key_state_api', side_effect=OSError('gone')), \
mock.patch.object(killswitch, 'START_DELAY', 0), \
mock.patch.object(killswitch.os, '_exit') as fake_exit:
sw.start()
sw._thread.join(2)
self.assertFalse(sw.is_alive())
fake_exit.assert_not_called()
self.assertIn('急停热键失效', '\n'.join(lines))
class FireTest(unittest.TestCase): class FireTest(unittest.TestCase):
def _switch(self): def _switch(self, log=lambda m: None, on_stop=None):
return killswitch.KillSwitch(0x7B, log=lambda m: None, key_name='f12') return killswitch.KillSwitch(0x23, log=log, key_name='end', on_stop=on_stop)
def test_exits_with_user_abort_code(self): def test_exits_with_user_abort_code_and_only_fires_once(self):
sw = self._switch() sw = self._switch()
with mock.patch.object(killswitch.os, '_exit') as fake_exit: with mock.patch.object(killswitch.os, '_exit') as fake_exit:
sw._fire() sw._fire()
sw._fire()
sw._fire()
fake_exit.assert_called_once_with(killswitch.EXIT_CODE) fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
def test_only_fires_once(self):
sw = self._switch()
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
sw._fire()
sw._fire()
sw._fire()
self.assertEqual(fake_exit.call_count, 1, '重复触发不该重复退出')
def test_logs_that_game_is_kept(self): def test_logs_that_game_is_kept(self):
lines = [] lines = []
sw = killswitch.KillSwitch(0x7B, log=lines.append, key_name='f12')
with mock.patch.object(killswitch.os, '_exit'): with mock.patch.object(killswitch.os, '_exit'):
sw._fire() self._switch(log=lines.append)._fire()
joined = '\n'.join(lines) joined = '\n'.join(lines)
self.assertIn('F12', joined) self.assertIn('END', joined)
self.assertIn('重新开始', joined) self.assertIn('重新开始', joined)
def test_releases_input_before_logging_and_exiting(self):
calls = []
sw = self._switch(log=lambda m: calls.append('log'), on_stop=lambda: calls.append('release'))
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: calls.append(code)):
sw._fire()
self.assertEqual(calls, ['release', 'log', 130])
def test_broken_cleanup_or_log_cannot_disable_the_hotkey(self):
def cleanup():
raise OSError('driver disconnected')
log = mock.Mock(side_effect=OSError('closed log'))
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
self._switch(log=log, on_stop=cleanup)._fire()
fake_exit.assert_called_once_with(130)
def test_hung_cleanup_cannot_block_exit_deadline(self):
release, exited = threading.Event(), threading.Event()
sw = self._switch(on_stop=release.wait)
with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: exited.set()):
worker = threading.Thread(target=sw._fire, daemon=True)
worker.start()
try:
self.assertTrue(exited.wait(2), '清理卡住也必须触发强退')
finally:
release.set()
worker.join(2)
def test_real_emergency_exit_is_reported_as_stopped(self):
from lc_mcp.tasks import TaskRunner
child = """
import json, os, time
from lc_mcp import killswitch
from lc_mcp.aalc_task import RESTORE_ENV
with open(os.environ[RESTORE_ENV], 'w') as f: json.dump({'set_mirror_count': 1}, f)
killswitch._key_state_api = lambda: (lambda vk: -32768)
killswitch.install(log=lambda msg: None)
time.sleep(10)
"""
with tempfile.TemporaryDirectory() as tmp:
runner = TaskRunner(tmp, argv_factory=lambda t, p: [sys.executable, '-c', child])
self.assertTrue(runner.start('mirror', {'count': 2})['ok'])
self.addCleanup(runner.proc.kill)
runner.proc.wait(timeout=5)
status = runner.status()
self.assertEqual((status['state'], status['exit_code']), ('stopped', 130))
self.assertTrue(status['pending_restore'], '强退保留配置恢复文件, 下次启动前由服务处理')
class StopTest(unittest.TestCase): class StopTest(unittest.TestCase):
def test_stop_is_safe_on_none(self): def test_stop_is_safe_on_none(self):
killswitch.stop(None) killswitch.stop(None) # 不该抛
def test_stop_calls_switch(self):
sw = mock.Mock()
killswitch.stop(sw)
sw.stop.assert_called_once()
def test_stop_swallows_errors(self): def test_stop_swallows_errors(self):
sw = mock.Mock() sw = mock.Mock()
sw.stop.side_effect = RuntimeError('boom') sw.stop.side_effect = RuntimeError('boom')
killswitch.stop(sw) killswitch.stop(sw) # 不该抛
def test_stopped_switch_does_not_poll(self):
sw = killswitch.KillSwitch(0x23, log=lambda m: None)
with key_state(PRESSED), mock.patch.object(killswitch.os, '_exit') as fake_exit:
sw.stop()
sw.start()
sw._thread.join(2)
fake_exit.assert_not_called()
def test_listening_passes_cleanup_and_stops_on_return_and_exception(self):
cleanup = object()
for failure in (False, True):
switch = mock.Mock()
with self.subTest(failure=failure), \
mock.patch.object(killswitch, 'install', return_value=switch) as install:
try:
with killswitch.listening(on_stop=cleanup):
if failure:
raise RuntimeError('task failed')
except RuntimeError:
pass
self.assertIs(install.call_args.kwargs['on_stop'], cleanup)
switch.stop.assert_called_once()
if __name__ == '__main__': if __name__ == '__main__':