From 8a9495b1850a5ef420ea4e1f112966b214c001e8 Mon Sep 17 00:00:00 2001 From: Codex Agent Date: Thu, 22 Oct 2026 15:13:41 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E6=80=A5=E5=81=9C=E7=83=AD=E9=94=AE?= =?UTF-8?q?=20F12=EF=BC=88=E9=A9=B1=E5=8A=A8=E7=BA=A7=E7=82=B9=E5=87=BB?= =?UTF-8?q?=E6=9C=9F=E9=97=B4=E7=94=A8=E6=88=B7=E6=B2=A1=E6=B3=95=E7=94=A8?= =?UTF-8?q?=E9=BC=A0=E6=A0=87=E5=81=9C=E6=AD=A2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户提问: "你执行脚本的时候我鼠标没法动,我怎么停止呢" 这不是小问题 —— 驱动级点击是闭环定位的: 手一动, 下一次点击前会读到新位置算出 偏差, 再把你推回目标点。所以任务跑起来时鼠标是"拔河"状态, 用户根本没法用鼠标 去点停止按钮。而 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 通过。 --- lc_mcp/aalc_task.py | 5 ++ lc_mcp/killswitch.py | 78 +++++++++++++++++++++++ tests/test_killswitch.py | 130 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 213 insertions(+) create mode 100644 lc_mcp/killswitch.py create mode 100644 tests/test_killswitch.py diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index 5289f13..3858bf0 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -11,6 +11,7 @@ import sys from . import preflight from .aalc_engine import bootstrap +from . import killswitch from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match, install_robust_set_foreground) @@ -75,6 +76,10 @@ def run(task, params): from tasks.battle import battle from utils.path_manager import path_manager + # 急停热键: 装得越早越好。驱动级点击期间鼠标被人和程序抢来抢去, + # 用户没法用鼠标点停止按钮, 键盘是唯一可靠的中断手段。 + kill_listener = killswitch.install(log=log) + problems = preflight.check(preflight.collect(cfg), task, desktop=None if cfg.simulator else preflight.desktop_size()) if problems: diff --git a/lc_mcp/killswitch.py b/lc_mcp/killswitch.py new file mode 100644 index 0000000..b3d07f9 --- /dev/null +++ b/lc_mcp/killswitch.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +"""全局急停热键。 + +为什么需要: 驱动级点击是闭环定位的 —— 手一动,下一次点击前会读到新位置、 +算出偏差、再把你推回目标点。所以任务运行期间鼠标和人是"拔河"状态,用户没法 +用鼠标去点停止按钮。键盘不受影响,所以用键盘热键做急停。 + +⛔ AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py) +里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。 + +默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。 +按下后直接 os._exit —— 任务本来就是子进程, 硬退出不会留下锁或半截状态, +这正是 aalc_task.py 的设计前提("停止 = 杀进程树")。 +""" +import os +import threading + +DEFAULT_KEY = 'f12' +EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止" + + +def _key_spec(name): + """'f12' -> '',pynput 的 GlobalHotKeys 要求尖括号形式。""" + name = (name or DEFAULT_KEY).strip().lower() + if name.startswith('<') and name.endswith('>'): + return name + return '<%s>' % name + + +def install(log=print, key=None): + """启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。 + + 任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。 + """ + key = key or os.environ.get('LCP_KILL_KEY') or DEFAULT_KEY + spec = _key_spec(key) + + try: + from pynput import keyboard + except Exception as e: # pynput 缺失/无显示环境 + log('[lc_mcp] 急停热键不可用(pynput 加载失败: %s: %s), 请用 Ctrl+Alt+Del 强制停止' + % (type(e).__name__, e)) + return None + + state = {'fired': False} + + def on_activate(): + if state['fired']: + return + state['fired'] = True + log('[lc_mcp] ⛔ 急停热键 %s 被按下, 立即终止任务' % key.upper()) + try: + log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始') + finally: + os._exit(EXIT_CODE) + + try: + listener = keyboard.GlobalHotKeys({spec: on_activate}) + listener.daemon = True + listener.start() + except Exception as e: + log('[lc_mcp] 急停热键注册失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止' + % (type(e).__name__, e)) + return None + + log('[lc_mcp] 急停热键已就绪: 按 %s 立即停止任务(键盘可用, 不需要鼠标)' % key.upper()) + listener._lc_state = state + return listener + + +def stop(listener): + """停止监听(任务正常结束时调用, 免得线程残留)。""" + if listener is None: + return + try: + listener.stop() + except Exception: + pass diff --git a/tests/test_killswitch.py b/tests/test_killswitch.py new file mode 100644 index 0000000..1d476a7 --- /dev/null +++ b/tests/test_killswitch.py @@ -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'), '') + + def test_keeps_already_wrapped(self): + self.assertEqual(killswitch._key_spec(''), '') + + def test_lowercases_and_trims(self): + self.assertEqual(killswitch._key_spec(' F12 '), '') + + def test_empty_falls_back_to_default(self): + self.assertEqual(killswitch._key_spec(''), '') + self.assertEqual(killswitch._key_spec(None), '') + + +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('', 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('', 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()