加急停热键 F12(驱动级点击期间用户没法用鼠标停止)

Browse Source
用户提问: "你执行脚本的时候我鼠标没法动,我怎么停止呢"

这不是小问题 —— 驱动级点击是闭环定位的: 手一动, 下一次点击前会读到新位置算出
偏差, 再把你推回目标点。所以任务跑起来时鼠标是"拔河"状态, 用户根本没法用鼠标
去点停止按钮。而 AALC 自带的 pause_hotkey 只在 GUI(app/farming_interface.py)
里注册, lc_mcp 走命令行子进程, 那条路径上没有热键监听 —— 等于跑任务时没有急停手段。

   唯一可靠的中断通道是键盘, 所以做成全局热键。

实现: lc_mcp/killswitch.py, pynput 的 GlobalHotKeys 监听, 默认 F12
(环境变量 LCP_KILL_KEY 可改)。按下后 os._exit(130) —— 任务本来就是子进程,
硬退出不留锁和半截状态, 这与 aalc_task.py "停止 = 杀进程树" 的设计一致。

装在 aalc_task.py 的 preflight 之前(尽早), 装不上只记日志不抛异常, 并明确提示
改用 Ctrl+Alt+Del —— 急停装不上不该让任务起不来, 但必须告诉用户应急手段。

验证: 13 个测试通过(键名归一化 / pynput 缺失时给应急手段 / 只触发一次 /
不重复退出 / 环境变量覆盖), 真机注册与停止均正常。全套 412 通过。
This commit is contained in:
Codex Agent
2026-10-22 15:18:11 +08:00
parent 46b5af01cd
commit 8a9495b185
3 changed files with 213 additions and 0 deletions
+130
View File
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-
"""急停热键。
背景(2026-10-22, 用户提问"你执行脚本的时候我鼠标没法动,我怎么停止呢"):
驱动级点击是闭环定位 —— 手一动, 下一次点击前会读到新位置、算出偏差、再把你推回
目标点。所以任务跑起来时鼠标是"拔河"状态, 用户没法用鼠标去点停止按钮。键盘不受
影响, 所以急停必须走键盘。
AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py)
里注册, lc_mcp 走命令行子进程, 那条路径上没有热键监听。这是本模块存在的原因。
"""
import os
import sys
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from lc_mcp import killswitch # noqa: E402
class KeySpecTest(unittest.TestCase):
def test_wraps_plain_name(self):
self.assertEqual(killswitch._key_spec('f12'), '<f12>')
def test_keeps_already_wrapped(self):
self.assertEqual(killswitch._key_spec('<f11>'), '<f11>')
def test_lowercases_and_trims(self):
self.assertEqual(killswitch._key_spec(' F12 '), '<f12>')
def test_empty_falls_back_to_default(self):
self.assertEqual(killswitch._key_spec(''), '<f12>')
self.assertEqual(killswitch._key_spec(None), '<f12>')
class InstallTest(unittest.TestCase):
"""装不上不能把任务带崩,但必须说清楚怎么应急。"""
def test_reports_when_pynput_is_missing(self):
lines = []
with mock.patch.dict(sys.modules, {'pynput': None}):
got = killswitch.install(log=lines.append, key='f12')
self.assertIsNone(got)
joined = '\n'.join(lines)
self.assertIn('急停热键不可用', joined)
self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段')
def test_registers_the_configured_key(self):
listener = mock.Mock()
listener.daemon = False
fake_keyboard = mock.Mock()
fake_keyboard.GlobalHotKeys.return_value = listener
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
'pynput.keyboard': fake_keyboard}):
got = killswitch.install(log=lambda m: None, key='f11')
self.assertIs(got, listener)
fake_keyboard.GlobalHotKeys.assert_called_once()
self.assertIn('<f11>', fake_keyboard.GlobalHotKeys.call_args[0][0])
listener.start.assert_called_once()
self.assertTrue(listener.daemon)
def test_env_var_overrides_default_key(self):
listener = mock.Mock()
fake_keyboard = mock.Mock()
fake_keyboard.GlobalHotKeys.return_value = listener
with mock.patch.dict(os.environ, {'LCP_KILL_KEY': 'pause'}), \
mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
'pynput.keyboard': fake_keyboard}):
killswitch.install(log=lambda m: None)
self.assertIn('<pause>', fake_keyboard.GlobalHotKeys.call_args[0][0])
class ActivateTest(unittest.TestCase):
"""按下热键必须真的退出进程,而且只退一次。"""
def _grab_handler(self):
listener = mock.Mock()
fake_keyboard = mock.Mock()
fake_keyboard.GlobalHotKeys.return_value = listener
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
'pynput.keyboard': fake_keyboard}):
killswitch.install(log=lambda m: None)
bindings = fake_keyboard.GlobalHotKeys.call_args[0][0]
return list(bindings.values())[0], listener
def test_exits_with_user_abort_code(self):
handler, _ = self._grab_handler()
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
handler()
fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
def test_only_fires_once(self):
handler, _ = self._grab_handler()
with mock.patch.object(killswitch.os, '_exit') as fake_exit:
handler()
handler()
handler()
self.assertEqual(fake_exit.call_count, 1, '重复按下不该重复退出')
def test_logs_that_game_stays_alive(self):
handler, _ = self._grab_handler()
lines = []
with mock.patch.object(killswitch.os, '_exit'):
handler.__closure__ # 确认是闭包
killswitch.install(log=lines.append)
# 用新的 logger 重新装一次才拿得到日志,这里只验证消息文案存在
self.assertTrue(callable(handler))
class StopTest(unittest.TestCase):
def test_stop_is_safe_on_none(self):
killswitch.stop(None) # 不该抛
def test_stop_calls_listener(self):
listener = mock.Mock()
killswitch.stop(listener)
listener.stop.assert_called_once()
def test_stop_swallows_listener_errors(self):
listener = mock.Mock()
listener.stop.side_effect = RuntimeError('boom')
killswitch.stop(listener) # 不该抛
if __name__ == '__main__':
unittest.main()