合并 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
+10
View File
@@ -98,6 +98,15 @@ $env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。 模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。
当前回归验证覆盖软件接线和异常处理,DLL、实际驱动及游戏响应需在 Windows 实机核验。 当前回归验证覆盖软件接线和异常处理,DLL、实际驱动及游戏响应需在 Windows 实机核验。
任务运行期间按 **End** 急停,可用 `LCP_KILL_KEY` 改成 `pause`、`scrolllock` 等键名。
不要用 F12(Steam 截图键);监听用 `GetAsyncKeyState` 轮询,因为 pynput 钩子在该机器的会话里收不到按键。
急停会终止任务子进程,保留游戏窗口;`task_status` 返回 `stopped`、退出码 `130`。
刷取循环检测到用户停止后结束本轮,不再导航、升级或重试。急停前会尝试释放驱动
按住的鼠标按钮,清理超过 250 毫秒仍强制退出;硬退出留下的临时配置恢复文件由
`stop_task` 或下一次 `run_task` 处理。热键监听依赖 AALC 的 `pynput`,安装失败会写日志;
也可从 MCP 调用 `stop_task`,或按 Ctrl+Alt+Del 打开任务管理器终止任务进程。
此热键只覆盖 `run_task` 子进程,不覆盖独立运行的合成、升级脚本。
## 工具 ## 工具
| 工具 | 说明 | | 工具 | 说明 |
@@ -180,6 +189,7 @@ powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Every
| `LCP_PORT` | 8765 | 服务/bridge 端口 | | `LCP_PORT` | 8765 | 服务/bridge 端口 |
| `LCP_KEEP_SHOTS` | 30 | 截图保留张数 | | `LCP_KEEP_SHOTS` | 30 | 截图保留张数 |
| `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 | | `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 |
| `LCP_KILL_KEY` | `end` | 任务子进程的急停键,如 `pause` / `scrolllock`;认不出的键名会报错而不是换成默认键 |
| `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python | | `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python |
## 开发 / 测试 ## 开发 / 测试
-2
View File
@@ -228,5 +228,3 @@ Get-ChildItem "$dir\convert_*.json" | ForEach-Object {
if ($m -and $m.secs -eq $r.elapsed_s) { "OK $($r.started)" } else { "MISMATCH $($_.Name)" } if ($m -and $m.secs -eq $r.elapsed_s) { "OK $($r.started)" } else { "MISMATCH $($_.Name)" }
} }
``` ```
+32
View File
@@ -96,3 +96,35 @@ OCR 误读;已知读法集合只来自该账号历史观测,不是通用余
测试从 vendor AST 提取并执行真实的 `init_input`、交互门与监控点击方法, 不复制其接线逻辑; 测试从 vendor AST 提取并执行真实的 `init_input`、交互门与监控点击方法, 不复制其接线逻辑;
实际 `aalc_task.run` 的 `all` / `daily` 入口也有覆盖。Windows DLL 和游戏未在本次环境执行。 实际 `aalc_task.run` 的 `all` / `daily` 入口也有覆盖。Windows DLL 和游戏未在本次环境执行。
PrintWindow 探测仅表示 API 调用成功, 不保证像素内容有效; 真机仍需检查画面、焦点和点击响应。 PrintWindow 探测仅表示 API 调用成功, 不保证像素内容有效; 真机仍需检查画面、焦点和点击响应。
## 合入 main 前的复核与急停补齐
合并目标为 `main`(原 `073e407`),来源为
`codex/feedback-unattended-setup-20261004`。本轮拉取又发现 `8a9495b`:
它是一个新增 F12 急停的提交,涉及三个文件,也纳入本次合并。
复核覆盖分支相对 main 的运行时、脚本、安装配置和测试变更,结合上述两轮审查记录;
AALC 子模块保持已验证的 `e1d1749`,没有追入 develop 的图标提交。
合并前另修复以下问题:
- 急停回调先写日志,日志抛错会跳过退出,日志阻塞也会延迟急停。
回调改为分发退出工作,不写日志;清理另有 250 毫秒强退兜底。
这遵循 [pynput 对 Windows 键盘回调的说明](https://pynput.readthedocs.io/en/latest/keyboard.html#the-keyboard-listener-thread):避免在回调中阻塞。
- 硬退出跳过驱动点击的 finally,可能留下按住的鼠标按钮。
驱动增加停止标志及输入锁,急停先拒绝新鼠标输入,再释放本实例按住的按钮。
驱动本身卡住时仍按时退出;本次离线验证不证明硬件故障下必定释放成功。
- `killswitch.stop` 原先未接到任务退出路径;现在正常结束、异常和预检拒绝都会关闭监听器。
- 退出码 130 原先显示 failed,镜牢轮询后还会继续导航和升级。
现在状态为 stopped,刷取脚本终止整轮并写入用户停止报告,不重试、不继续升级。
- 计划任务时限仍按 75 分钟镜牢设置,短于脚本的 100 分钟上限,也未覆盖一次卡死重试。
安装脚本改为 daily 45 分钟、每局镜牢 100 分钟、各至多两次尝试,另加 30 分钟收尾预算。
此改动只影响后续安装任务,未操作现有 Windows 计划任务。
- 纠正合成安装脚本关于注销后运行和固定体力恢复速率的过时注释,清理文档尾部空行。
验证:Linux / Python 3.12 全套 **437 项通过**(17.112 秒);相对 main 的
`git diff --check` 通过。新增回归涵盖真正退出 130 的子进程、保留恢复文件、用户停止后
不继续操作、驱动按住时急停、清理卡住仍退出以及正常/预检拒绝后的监听器清理。
Windows 热键、驱动及 PowerShell 计划任务仍需实机验收。
分支清理仅针对完整合入 main 的来源分支。`fix/team-scroll-patch` 仍有独有的
`dd4259d` 实验提交,本次不合入也不删除;其历史取舍见上面的 DSH 审查记录。
+11 -2
View File
@@ -182,6 +182,10 @@ class DriverClickProxy:
handle.setForeground() handle.setForeground()
if foreground_window() != hwnd: if foreground_window() != hwnd:
raise OSError('无法激活游戏窗口, 未发送驱动输入') raise OSError('无法激活游戏窗口, 未发送驱动输入')
# 游戏重启后句柄会变; 每次按当前句柄重新绑定, 免得前台校验拿旧句柄拒绝所有点击。
bind = getattr(self._driver, 'bind_window', None)
if bind is not None:
bind(hwnd)
return client_to_screen(hwnd, x, y) return client_to_screen(hwnd, x, y)
def _trace(self, msg): def _trace(self, msg):
@@ -228,8 +232,7 @@ class DriverClickProxy:
sx, sy = self._screen_pos(x, y) sx, sy = self._screen_pos(x, y)
if not self._driver.move_to(sx, sy): if not self._driver.move_to(sx, sy):
return False return False
self._driver.down(1) return self._driver.down(1) is not False
return True
def mouse_up(self, x, y): def mouse_up(self, x, y):
try: try:
@@ -282,6 +285,12 @@ def install_driver_click(auto, screen, driver=None, log=print):
return drv return drv
def stop_driver_click(auto):
handler = auto.input_handler
if isinstance(handler, DriverClickProxy):
handler._driver.emergency_stop()
@contextmanager @contextmanager
def driver_click_tasks(scheme, auto, screen, cfg, log=print): def driver_click_tasks(scheme, auto, screen, cfg, log=print):
"""每次游戏初始化完成后接管, 包括 all 任务和故障重启。""" """每次游戏初始化完成后接管, 包括 all 任务和故障重启。"""
+46 -50
View File
@@ -9,12 +9,11 @@ import json
import os import os
import sys import sys
from . import preflight from . import killswitch, preflight
from .aalc_engine import bootstrap from .aalc_engine import bootstrap
from . import killswitch
from .aalc_patches import (WindowGuard, driver_click_tasks, install_default_battle_team, from .aalc_patches import (WindowGuard, driver_click_tasks, install_default_battle_team,
install_exact_team_match, install_robust_set_foreground, install_exact_team_match, install_robust_set_foreground,
install_system_team_selection) install_system_team_selection, stop_driver_click)
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = { TASKS = {
@@ -77,55 +76,52 @@ def run(task, params):
from tasks.battle import battle from tasks.battle import battle
from utils.path_manager import path_manager from utils.path_manager import path_manager
# 急停热键: 装得越早越好。驱动级点击期间鼠标被人和程序抢来抢去, with killswitch.listening(log=log, on_stop=lambda: stop_driver_click(auto)):
# 用户没法用鼠标点停止按钮, 键盘是唯一可靠的中断手段。 problems = preflight.check(preflight.collect(cfg), task,
kill_listener = killswitch.install(log=log) desktop=None if cfg.simulator else preflight.desktop_size())
if problems:
for p in problems:
log('[ERROR] [lc_mcp] preflight: %s' % p)
return PREFLIGHT_EXIT
problems = preflight.check(preflight.collect(cfg), task, install_exact_team_match(auto, log)
desktop=None if cfg.simulator else preflight.desktop_size()) install_robust_set_foreground(screen, log=log)
if problems: # 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败,
for p in problems: # 白等 60 秒还会把界面滚乱, 后面 to_battle 就找不到 "进入战斗" 了。
log('[ERROR] [lc_mcp] preflight: %s' % p) if task in ('daily', 'all'):
return PREFLIGHT_EXIT install_default_battle_team(scheme, log=log)
# 镜牢: 编队是自定义名字(体系名), AALC 只会找 "编队#N"; 改成按体系名点选。
install_exact_team_match(auto, log) if task in ('mirror', 'all'):
install_robust_set_foreground(screen, log=log) install_system_team_selection(log=log)
# 日常本(经验/纽本)不翻队伍列表: 队伍是自定义名字时按名字找必然失败, guard = WindowGuard(screen, cfg, log=log)
# 白等 60 秒还会把界面滚乱, 后面 to_battle 就找不到 "进入战斗" 了。 guard.start()
if task in ('daily', 'all'): restore_path = os.environ.get(RESTORE_ENV)
install_default_battle_team(scheme, log=log) originals = apply_overrides(cfg, task, params, restore_path)
# 镜牢: 编队是自定义名字(体系名), AALC 只会找 "编队#N"; 改成按体系名点选。 with driver_click_tasks(scheme, auto, screen, cfg, log=log):
if task in ('mirror', 'all'): try:
install_system_team_selection(log=log) if task == 'all':
guard = WindowGuard(screen, cfg, log=log) scheme.script_task()
guard.start() return 0
restore_path = os.environ.get(RESTORE_ENV) # 与 script_task() 相同的前置步骤
originals = apply_overrides(cfg, task, params, restore_path) scheme.init_game()
with driver_click_tasks(scheme, auto, screen, cfg, log=log): path_manager.initialize_paths()
try: auto.clear_img_cache()
if task == 'all': retry_monitor.start()
scheme.script_task() get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
return 0 return 0
# 与 script_task() 相同的前置步骤 finally:
scheme.init_game() guard.stop()
path_manager.initialize_paths() retry_monitor.stop()
auto.clear_img_cache() restore(cfg, originals, restore_path)
retry_monitor.start()
get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
return 0
finally:
guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
def main(argv): def main(argv):
+48 -22
View File
@@ -22,6 +22,7 @@
import ctypes import ctypes
import os import os
import time import time
import threading
from ctypes import wintypes from ctypes import wintypes
from functools import lru_cache from functools import lru_cache
@@ -60,6 +61,14 @@ def foreground_window():
return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])() return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])()
def window_title(hwnd, limit=64):
"""窗口标题, 只用于报错说明; 取不到返回空串。"""
buf = ctypes.create_unicode_buffer(limit)
_api('user32', 'GetWindowTextW', ctypes.c_int,
[wintypes.HWND, wintypes.LPWSTR, ctypes.c_int])(hwnd, buf, limit)
return buf.value
def is_console_session(): def is_console_session():
current = wintypes.DWORD() current = wintypes.DWORD()
query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL, query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL,
@@ -106,6 +115,9 @@ class DriverInput:
self.log = log self.log = log
self._dll = None self._dll = None
self._open = False self._open = False
self._stopped = False
self._input_lock = threading.RLock()
self._pressed = set()
# 目标窗口句柄。有它才能做句柄级前台校验 —— 几何校验在窗口重叠时没用: # 目标窗口句柄。有它才能做句柄级前台校验 —— 几何校验在窗口重叠时没用:
# 实测把浏览器切到前台, 点游戏里同一个坐标, 只比矩形的话校验照样通过。 # 实测把浏览器切到前台, 点游戏里同一个坐标, 只比矩形的话校验照样通过。
self.hwnd = 0 self.hwnd = 0
@@ -139,7 +151,14 @@ class DriverInput:
@property @property
def ready(self): def ready(self):
return self._open and self._dll is not None return self._open and self._dll is not None and not self._stopped
def emergency_stop(self):
"""拒绝后续鼠标输入并释放本实例按住的按钮。急停线程另有退出超时。"""
self._stopped = True
with self._input_lock:
for button in tuple(self._pressed):
self.up(button)
def preflight(self): def preflight(self):
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。""" """返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
@@ -160,12 +179,13 @@ class DriverInput:
# ---------------------------------------------------------------- 移动 # ---------------------------------------------------------------- 移动
def move_relative(self, dx, dy): def move_relative(self, dx, dy):
if not self.ready: with self._input_lock:
return False if not self.ready:
if dx == 0 and dy == 0: return False
if dx == 0 and dy == 0:
return True
self._dll.moveR(int(dx), int(dy), True)
return True return True
self._dll.moveR(int(dx), int(dy), True)
return True
def move_to(self, sx, sy, tol=1, iters=10, settle=0.03): def move_to(self, sx, sy, tol=1, iters=10, settle=0.03):
"""把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。""" """把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。"""
@@ -185,12 +205,19 @@ class DriverInput:
# ---------------------------------------------------------------- 按键 # ---------------------------------------------------------------- 按键
def down(self, button=1): def down(self, button=1):
if self.ready: with self._input_lock:
self._dll.mouse_down(int(button)) if not self.ready:
return False
button = int(button)
self._pressed.add(button)
self._dll.mouse_down(button)
return True
def up(self, button=1): def up(self, button=1):
if self.ready: with self._input_lock:
self._dll.mouse_up(int(button)) if self._open and self._dll is not None:
self._dll.mouse_up(int(button))
self._pressed.discard(int(button))
def click(self, sx, sy, times=1, tol=1, require_foreground=True, def click(self, sx, sy, times=1, tol=1, require_foreground=True,
press_ms=60, settle=0.05): press_ms=60, settle=0.05):
@@ -222,11 +249,12 @@ class DriverInput:
time.sleep(settle) time.sleep(settle)
for _ in range(int(times)): for _ in range(int(times)):
try: try:
self._dll.mouse_down(1) if not self.down(1):
return False
time.sleep(press_ms / 1000.0) time.sleep(press_ms / 1000.0)
finally: finally:
self._dll.mouse_up(1) self.up(1)
return True return not self._stopped
def key_down(self, key): def key_down(self, key):
if self.ready: if self.ready:
@@ -254,22 +282,20 @@ def click_point_is_on_foreground(sx, sy, hwnd=None):
所以: 给了 hwnd 就要求前台窗口**就是它**(或是它的子窗口); 没给 hwnd 时 所以: 给了 hwnd 就要求前台窗口**就是它**(或是它的子窗口); 没给 hwnd 时
退化成"有前台窗口且点在它矩形内", 可用性有限, 仅作兜底。 退化成"有前台窗口且点在它矩形内", 可用性有限, 仅作兜底。
""" """
user32 = ctypes.windll.user32 fg = foreground_window()
fg = user32.GetForegroundWindow()
if not fg: if not fg:
return False, '当前没有前台窗口(GetForegroundWindow=0)' return False, '当前没有前台窗口(GetForegroundWindow=0)'
if hwnd: if hwnd:
if fg == hwnd or user32.IsChild(hwnd, fg): if fg == hwnd or _api('user32', 'IsChild', wintypes.BOOL,
[wintypes.HWND, wintypes.HWND])(hwnd, fg):
return True, 'ok' return True, 'ok'
buf = ctypes.create_unicode_buffer(64)
user32.GetWindowTextW(fg, buf, 64)
other = ctypes.create_unicode_buffer(64)
user32.GetWindowTextW(hwnd, other, 64)
return False, ('前台不是目标窗口(前台=%r, 目标=%r) —— 这次点击会打到别的窗口' return False, ('前台不是目标窗口(前台=%r, 目标=%r) —— 这次点击会打到别的窗口'
% (buf.value, other.value)) % (window_title(fg), window_title(hwnd)))
pt = wintypes.POINT(int(sx), int(sy)) pt = wintypes.POINT(int(sx), int(sy))
rect = wintypes.RECT() rect = wintypes.RECT()
if not user32.GetWindowRect(fg, ctypes.byref(rect)): get_rect = _api('user32', 'GetWindowRect', wintypes.BOOL,
[wintypes.HWND, ctypes.POINTER(wintypes.RECT)])
if not get_rect(fg, ctypes.byref(rect)):
return False, '取不到前台窗口的区域' return False, '取不到前台窗口的区域'
if not (rect.left <= pt.x < rect.right and rect.top <= pt.y < rect.bottom): if not (rect.left <= pt.x < rect.right and rect.top <= pt.y < rect.bottom):
return False, ('点击点(%d,%d)不在前台窗口内(区域 %d,%d-%d,%d)' return False, ('点击点(%d,%d)不在前台窗口内(区域 %d,%d-%d,%d)'
+78 -21
View File
@@ -18,19 +18,25 @@
默认 End(小键盘区右下角, 好按且不冲突), 可用环境变量 LCP_KILL_KEY 改成 pause / scrolllock / f11 等。 默认 End(小键盘区右下角, 好按且不冲突), 可用环境变量 LCP_KILL_KEY 改成 pause / scrolllock / f11 等。
⛔ 不要用 F12: 那是 Steam 的截图键(用户 2026-10-22 指出), 按下去会弹 Steam 截图 ⛔ 不要用 F12: 那是 Steam 的截图键(用户 2026-10-22 指出), 按下去会弹 Steam 截图
覆盖层, 而且可能被 Steam 抢先消费。Esc / F11 也不合适 —— 游戏里分别是关菜单 覆盖层, 而且可能被 Steam 抢先消费。Esc / F11 也不合适 —— 游戏里分别是关菜单
和切全屏。Pause 没有任何软件抢, 是最稳的选择。 和切全屏。
按下后直接 os._exit —— 任务本来就是子进程, 硬退出不留锁或半截状态, 这与
aalc_task.py "停止 = 杀进程树" 的设计前提一致。监听器活在任务进程内, 按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally; 临时配置由
所以即使 MCP 服务出问题、用户联系不上调用方, 按热键仍然能停。 TaskRunner 的恢复文件机制处理。退出前先给驱动释放按住的鼠标键(on_stop),
清理或日志卡住时 STOP_TIMEOUT 后仍强制退出。监听器活在任务进程内, 所以即使
MCP 服务出问题、用户联系不上调用方, 按热键仍然能停。
""" """
import ctypes import ctypes
import os import os
import threading import threading
import time import time
from contextlib import contextmanager
from functools import lru_cache
DEFAULT_KEY = 'end' DEFAULT_KEY = 'end'
EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止" EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止"
POLL_INTERVAL = 0.05 # 50ms 轮询, 人手按一下不会漏 POLL_INTERVAL = 0.05 # 50ms 轮询, 人手按一下不会漏
STOP_TIMEOUT = 0.25 # 释放鼠标/写日志最多等这么久, 然后强退
START_DELAY = 0.3 # 先等一会儿, 避免把启动时按住的键当成急停
# 常用键 -> 虚拟键码。f12 保留是为了兼容旧配置, 但**不推荐** —— Steam 占用它。 # 常用键 -> 虚拟键码。f12 保留是为了兼容旧配置, 但**不推荐** —— Steam 占用它。
VK = { VK = {
@@ -51,18 +57,28 @@ def resolve_vk(key):
return VK.get(name) return VK.get(name)
@lru_cache(maxsize=None)
def _key_state_api():
"""独立绑定 GetAsyncKeyState, 不改共用的 ctypes.windll 的类型声明。"""
fn = ctypes.WinDLL('user32', use_last_error=True).GetAsyncKeyState
fn.argtypes = [ctypes.c_int]
fn.restype = ctypes.c_short
return fn
def _pressed(vk): def _pressed(vk):
"""GetAsyncKeyState 的最高位 = 当前是否按下。""" """GetAsyncKeyState 的最高位 = 当前是否按下(低位只表示"按过", 不算)。"""
return bool(ctypes.windll.user32.GetAsyncKeyState(vk) & 0x8000) return bool(_key_state_api()(vk) & 0x8000)
class KillSwitch: class KillSwitch:
"""轮询线程。按住热键会立刻退出, 不会重复触发。""" """轮询线程。按住热键会立刻退出, 不会重复触发。"""
def __init__(self, vk, log=print, key_name=DEFAULT_KEY): def __init__(self, vk, log=print, key_name=DEFAULT_KEY, on_stop=None):
self.vk = vk self.vk = vk
self.log = log self.log = log
self.key_name = key_name self.key_name = key_name
self.on_stop = on_stop
self.fired = False self.fired = False
self._stopped = threading.Event() self._stopped = threading.Event()
self._thread = threading.Thread(target=self._run, daemon=True, self._thread = threading.Thread(target=self._run, daemon=True,
@@ -79,28 +95,54 @@ class KillSwitch:
self._stopped.set() self._stopped.set()
def _run(self): def _run(self):
# 先等一会儿, 避免把启动时按住的键当成急停 if self._stopped.wait(START_DELAY):
time.sleep(0.3) return
while not self._stopped.is_set(): while not self._stopped.is_set():
if _pressed(self.vk): try:
pressed = _pressed(self.vk)
except Exception as e: # 接口失效: 说清楚后退出, 不刷满异常
try:
self.log('[lc_mcp] 急停热键失效(%s: %s), 请用 stop_task 或 Ctrl+Alt+Del 停止'
% (type(e).__name__, e))
except Exception:
pass
return
if pressed:
self._fire() self._fire()
return return
time.sleep(POLL_INTERVAL) self._stopped.wait(POLL_INTERVAL)
def _fire(self): def _fire(self):
if self.fired: if self.fired:
return return
self.fired = True self.fired = True
# 释放驱动按键或写日志卡住时, 由计时器按时强退。
timer = threading.Timer(STOP_TIMEOUT, os._exit, args=(EXIT_CODE,))
timer.daemon = True
try: try:
self.log('[lc_mcp] ⛔ 急停热键 %s 被按下, 立即终止任务' timer.start()
% self.key_name.upper()) try:
self.log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始') if self.on_stop is not None:
self.on_stop()
except Exception:
pass # 释放失败也必须退出
try:
self.log('[lc_mcp] ⛔ 急停热键 %s 被按下, 终止任务; 游戏窗口保留, 可用 run_task 重新开始'
% self.key_name.upper())
except Exception:
pass # 日志坏了不能拦住急停
finally: finally:
os._exit(EXIT_CODE) try:
os._exit(EXIT_CODE)
finally:
timer.cancel() # 仅在测试替换 _exit 时才会走到
def install(log=print, key=None): def install(log=print, key=None, on_stop=None):
"""启动急停轮询线程。返回 KillSwitch, 失败返回 None(不抛异常)。""" """启动急停轮询线程。返回 KillSwitch, 失败返回 None(不抛异常)。
急停装不上不该让任务起不来, 但必须把原因和应急手段说清楚。
"""
key = key or os.environ.get('LCP_KILL_KEY') or DEFAULT_KEY key = key or os.environ.get('LCP_KILL_KEY') or DEFAULT_KEY
vk = resolve_vk(key) vk = resolve_vk(key)
if vk is None: if vk is None:
@@ -108,21 +150,36 @@ def install(log=print, key=None):
% (key, ', '.join(sorted(VK)))) % (key, ', '.join(sorted(VK))))
return None return None
try: try:
switch = KillSwitch(vk, log=log, key_name=key).start() _key_state_api()
except Exception as e: # 非 Windows / user32 不可用
log('[lc_mcp] 急停热键不可用(读取键盘状态失败: %s: %s), 请用 Ctrl+Alt+Del 强制停止'
% (type(e).__name__, e))
return None
try:
switch = KillSwitch(vk, log=log, key_name=key, on_stop=on_stop).start()
except Exception as e: except Exception as e:
log('[lc_mcp] 急停热键启动失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止' log('[lc_mcp] 急停热键启动失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止'
% (type(e).__name__, e)) % (type(e).__name__, e))
return None return None
log('[lc_mcp] 急停热键已就绪: 按 %s 立即停止任务(键盘可用, 不需要鼠标, ' log('[lc_mcp] 急停热键已就绪: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
'也不依赖 MCP 服务)' % key.upper()) '(键盘可用, 不需要鼠标, 也不依赖 MCP 服务)' % key.upper())
return switch return switch
def stop(switch): def stop(switch):
"""停止轮询(任务正常结束时调用)。""" """停止轮询(任务结束时调用, 免得线程残留)。"""
if switch is None: if switch is None:
return return
try: try:
switch.stop() switch.stop()
except Exception: except Exception:
pass pass
@contextmanager
def listening(log=print, on_stop=None):
switch = install(log=log, on_stop=on_stop)
try:
yield switch
finally:
stop(switch)
+3 -1
View File
@@ -12,6 +12,7 @@ import time
from collections import deque from collections import deque
from .aalc_task import RESTORE_ENV from .aalc_task import RESTORE_ENV
from .killswitch import EXIT_CODE as USER_ABORT_EXIT
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IS_WIN = sys.platform.startswith('win') IS_WIN = sys.platform.startswith('win')
@@ -186,7 +187,8 @@ class TaskRunner:
state = 'running' state = 'running'
else: else:
self.info.setdefault('ended', time.time()) self.info.setdefault('ended', time.time())
state = 'stopped' if self.info['stopped_by_user'] else 'succeeded' if code == 0 else 'failed' state = ('stopped' if self.info['stopped_by_user'] or code == USER_ABORT_EXIT
else 'succeeded' if code == 0 else 'failed')
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'], r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']), 'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))} 'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}
+9
View File
@@ -42,6 +42,10 @@ DEFAULT_REPORT_DIR = os.path.expanduser(os.path.join('~', 'lc_mcp', 'cycles'))
_log_file = None _log_file = None
class UserAborted(RuntimeError):
"""用户主动停止, 结束整轮, 不执行后续导航、升级或重试。"""
def log(msg): def log(msg):
line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg) line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg)
print(line, flush=True) print(line, flush=True)
@@ -176,6 +180,8 @@ def poll_task(task, timeout_s, sleep=time.sleep):
raise RuntimeError('无法读取任务状态: %s' % st.get('error', st)) raise RuntimeError('无法读取任务状态: %s' % st.get('error', st))
s = st.get('state') s = st.get('state')
el = int(time.time() - t0) el = int(time.time() - t0)
if s == 'stopped' or st.get('exit_code') == 130:
raise UserAborted('%s 已被用户停止' % task)
if s != 'running': if s != 'running':
log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code'))) log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code')))
# AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors # AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors
@@ -332,6 +338,9 @@ def main(argv=None):
try: try:
return run_cycle(args, step, finish) return run_cycle(args, step, finish)
except UserAborted as e:
step('用户停止', False, str(e))
return finish(130, '本轮已由用户停止')
except (OSError, RuntimeError, subprocess.SubprocessError) as e: except (OSError, RuntimeError, subprocess.SubprocessError) as e:
if isinstance(e, subprocess.CalledProcessError): if isinstance(e, subprocess.CalledProcessError):
output = (e.stdout or '') + (e.stderr or '') output = (e.stdout or '') + (e.stderr or '')
+3 -9
View File
@@ -5,14 +5,8 @@
# powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -EveryHours 6 # powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -EveryHours 6
# powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Uninstall # powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Uninstall
# #
# 节奏怎么定(体力恢复速度): # 默认每 4 小时检查一次; 是否合成以本轮实际体力读数为准, 不按固定恢复速率推算。
# Limbus 的体力每 6 分钟回 1 点, 上限 126。 # 合成 1 个模块需要 20 点体力。
# 合成 1 个模块要 20 点体力, 所以:
# 每 2 小时 -> 约 20 点 -> 1 个模块
# 每 4 小时 -> 约 40 点 -> 2 个模块(默认)
# 每 6 小时 -> 约 60 点 -> 3 个模块
# 只要不顶到 126 上限就不浪费恢复量, 所以更勤快些也不会亏。
# 4 小时是"每次都能换到东西"和"别老折腾游戏启动"之间的折中。
# #
# 这个任务和 LcMCPDailyCycle 是分开的: 用户明确要求这次不打任何关卡, # 这个任务和 LcMCPDailyCycle 是分开的: 用户明确要求这次不打任何关卡,
# 只挂机攒模块, 所以不能把刷取任务一起打开。 # 只挂机攒模块, 所以不能把刷取任务一起打开。
@@ -42,7 +36,7 @@ if (-not (Test-Path $script)) {
throw "找不到脚本: $script" throw "找不到脚本: $script"
} }
# 以当前用户运行。无人值守要点: 不要勾"只在用户登录时运行", 否则注销后不跑。 # 以当前用户的交互会话运行, 必须保持登录; 注销后没有可供截图/点击的游戏桌面。
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" `
-LogonType Interactive -RunLevel Limited -LogonType Interactive -RunLevel Limited
+4 -3
View File
@@ -6,7 +6,7 @@
# powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1 # powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1
# 可选: -At 05:30 每日运行时间。游戏每日重置为 06:00 (KST), 即北京时间 05:00 # 可选: -At 05:30 每日运行时间。游戏每日重置为 06:00 (KST), 即北京时间 05:00
# -EveryHours 2.5 改成"每 N 小时重复一轮"以持续刷取; 0 = 只按 -At 每天一次 # -EveryHours 2.5 改成"每 N 小时重复一轮"以持续刷取; 0 = 只按 -At 每天一次
# 单轮上限 = 60 + 75*Mirror 分钟, 间隔要大于它, 否则会被跳过 # 任务时限包含 daily 45 分钟、每局镜牢 100 分钟、各一次重试及 30 分钟收尾
# -Mirror 1 每轮镜牢局数, 0 = 不打镜牢 # -Mirror 1 每轮镜牢局数, 0 = 不打镜牢
# -Target 34 把队内人格升到的等级 # -Target 34 把队内人格升到的等级
# -Python <路径> 默认 vendor\aalc\.venv\Scripts\pythonw.exe (无窗口, 不抢游戏焦点) # -Python <路径> 默认 vendor\aalc\.venv\Scripts\pythonw.exe (无窗口, 不抢游戏焦点)
@@ -66,8 +66,9 @@ if (-not $NoWatchdog) {
$cycle = Join-Path $PSScriptRoot "auto_cycle.py" $cycle = Join-Path $PSScriptRoot "auto_cycle.py"
$action = New-ScheduledTaskAction -Execute $Python -WorkingDirectory $Repo ` $action = New-ScheduledTaskAction -Execute $Python -WorkingDirectory $Repo `
-Argument "-X utf8 `"$cycle`" --mirror $Mirror --target $Target" -Argument "-X utf8 `"$cycle`" --mirror $Mirror --target $Target"
# 一轮 daily 约 22 分钟, 每局镜牢实测 39~>70 分钟; 超过上限由计划任务强杀 # 与 auto_cycle.py 的 DAILY_TIMEOUT_S / MIRROR_TIMEOUT_S / STALL_RETRIES 对齐。
$limit = New-TimeSpan -Minutes (60 + 75 * [Math]::Max($Mirror, 0)) # 每个任务最多两次尝试, 另留 30 分钟给启动、轮询和升级; 避免外层先杀掉报告进程。
$limit = New-TimeSpan -Minutes (30 + 2 * (45 + 100 * [Math]::Max($Mirror, 0)))
if ($EveryHours -gt 0) { if ($EveryHours -gt 0) {
# 持续刷取: 每 N 小时重复一轮。开始时间取"现在", 装完即进入节奏。 # 持续刷取: 每 N 小时重复一轮。开始时间取"现在", 装完即进入节奏。
# 注意 New-TimeSpan -Hours 的参数是 [int], 传 2.5 会被截断成 2 小时, 所以用 -Minutes。 # 注意 New-TimeSpan -Hours 的参数是 [int], 传 2.5 会被截断成 2 小时, 所以用 -Minutes。
+29
View File
@@ -164,6 +164,35 @@ class RunAalcTest(unittest.TestCase):
self.assertIn('preflight', info) self.assertIn('preflight', info)
self.assertEqual(self.tools(mcp), ['run_task']) self.assertEqual(self.tools(mcp), ['run_task'])
def test_user_stop_never_retries(self):
for status in ({'state': 'stopped', 'exit_code': 130},
{'state': 'stopped'}, {'state': 'failed', 'exit_code': 130}):
mcp = FakeMcp([status], [DONE])
with self.subTest(status=status), self.assertRaises(auto_cycle.UserAborted):
self.run_aalc(mcp)
self.assertEqual(self.tools(mcp), ['run_task'])
def test_mirror_emergency_stop_ends_cycle_before_upgrade_or_navigation(self):
mcp = FakeMcp([DONE], [{'state': 'stopped', 'exit_code': 130}])
poll = auto_cycle.poll_task
with tempfile.TemporaryDirectory() as tmp:
with mock.patch.object(auto_cycle, 'probe', mcp.probe), \
mock.patch.object(auto_cycle, 'poll_task',
side_effect=lambda t, s, **kw: poll(t, s, sleep=lambda _: None)), \
mock.patch.object(auto_cycle, 'lunacy_guard', return_value=(True, 'ok')), \
mock.patch.object(auto_cycle, 'ensure_team1', return_value=True), \
mock.patch.object(auto_cycle, 'goto_identities') as navigate, \
mock.patch.object(auto_cycle, 'run') as upgrade, \
mock.patch('builtins.print'):
code = auto_cycle.main(['--mirror', '1', '--report-dir', tmp])
report = json.loads(next(Path(tmp).glob('cycle_*.json')).read_text(encoding='utf-8'))
self.assertEqual(code, 130)
self.assertFalse(report['ok'])
self.assertIn('用户停止', report['result'])
navigate.assert_not_called()
upgrade.assert_not_called()
self.assertEqual(self.tools(mcp), ['run_task', 'run_task'])
def test_exit_zero_with_errors_is_failure(self): def test_exit_zero_with_errors_is_failure(self):
mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])]) mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])])
ok, info = self.run_aalc(mcp) ok, info = self.run_aalc(mcp)
+72 -40
View File
@@ -301,8 +301,8 @@ class DriverWiringTest(unittest.TestCase):
def test_actual_task_entry_enables_driver_for_all_and_daily(self): def test_actual_task_entry_enables_driver_for_all_and_daily(self):
from lc_mcp import aalc_task from lc_mcp import aalc_task
for task in ('all', 'daily'): for task, problems in [('all', []), ('daily', []), ('all', ['invalid config'])]:
with self.subTest(task=task): with self.subTest(task=task, problems=problems):
auto, handler_type = vendor_auto() auto, handler_type = vendor_auto()
auto.clear_img_cache = mock.Mock() auto.clear_img_cache = mock.Mock()
auto.click_element = mock.Mock(return_value=False) auto.click_element = mock.Mock(return_value=False)
@@ -329,14 +329,21 @@ class DriverWiringTest(unittest.TestCase):
mock.patch.object(aalc_task, 'install_exact_team_match'), \ mock.patch.object(aalc_task, 'install_exact_team_match'), \
mock.patch.object(aalc_task, 'install_robust_set_foreground'), \ mock.patch.object(aalc_task, 'install_robust_set_foreground'), \
mock.patch.object(aalc_task, 'WindowGuard'), \ mock.patch.object(aalc_task, 'WindowGuard'), \
mock.patch.object(aalc_task.killswitch, 'install') as install_hotkey, \
mock.patch.object(aalc_task, 'log'), \ mock.patch.object(aalc_task, 'log'), \
mock.patch.object(aalc_task.preflight, 'collect', return_value={}), \ mock.patch.object(aalc_task.preflight, 'collect', return_value={}), \
mock.patch.object(aalc_task.preflight, 'desktop_size', return_value=(1920, 1080)), \ mock.patch.object(aalc_task.preflight, 'desktop_size', return_value=(1920, 1080)), \
mock.patch.object(aalc_task.preflight, 'check', return_value=[]), \ mock.patch.object(aalc_task.preflight, 'check', return_value=problems), \
mock.patch.object(di, 'DriverInput', return_value=drv), \ mock.patch.object(di, 'DriverInput', return_value=drv), \
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)): mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
self.assertEqual(aalc_task.run(task, {}), 0) self.assertEqual(aalc_task.run(task, {}), 3 if problems else 0)
drv.click.assert_called_once_with(10, 20, times=1) install_hotkey.return_value.stop.assert_called_once()
if problems:
drv.click.assert_not_called()
else:
drv.click.assert_called_once_with(10, 20, times=1)
install_hotkey.call_args.kwargs['on_stop']()
drv.emergency_stop.assert_called_once()
def test_disabled_and_simulator_leave_initialization_unchanged(self): def test_disabled_and_simulator_leave_initialization_unchanged(self):
for enabled, simulator in [('0', False), ('1', True)]: for enabled, simulator in [('0', False), ('1', True)]:
@@ -350,6 +357,23 @@ class DriverWiringTest(unittest.TestCase):
class DriverFailureTest(unittest.TestCase): class DriverFailureTest(unittest.TestCase):
def test_emergency_stop_releases_press_and_blocks_subsequent_clicks(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(drv, 'move_to', return_value=True), \
mock.patch.object(di, 'click_point_is_on_foreground', lambda *a, **k: (True, 'ok')), \
mock.patch.object(di.time, 'sleep', side_effect=lambda _: drv.emergency_stop()):
# settle=0: 第一次 sleep 是按下后的按住时长, 急停发生在按住期间
self.assertFalse(drv.click(10, 20, times=3, settle=0))
drv._dll.mouse_down.assert_called_once_with(1)
drv._dll.mouse_up.assert_called_with(1)
self.assertFalse(drv.ready)
self.assertFalse(drv.click(30, 40))
self.assertFalse(drv.move_relative(20, 30))
self.assertFalse(drv.down())
drv._dll.moveR.assert_not_called()
self.assertEqual(drv._pressed, set())
def test_release_even_if_sleep_is_interrupted(self): def test_release_even_if_sleep_is_interrupted(self):
drv = di.DriverInput() drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock() drv._open, drv._dll = True, mock.Mock()
@@ -437,8 +461,18 @@ class ForegroundFallbackTest(unittest.TestCase):
[mock.call(33, 11, True), mock.call(33, 11, False)]) [mock.call(33, 11, True), mock.call(33, 11, False)])
if __name__ == '__main__':
unittest.main() def win_api(**functions):
"""按 API 名替换 driver_input._api 返回的函数。"""
return mock.patch.object(di, '_api', side_effect=lambda library, name, result, args: functions[name])
def window_rect(left, top, right, bottom):
def get_window_rect(hwnd, ptr):
r = ptr._obj
r.left, r.top, r.right, r.bottom = left, top, right, bottom
return 1
return get_window_rect
class ForegroundCheckTest(unittest.TestCase): class ForegroundCheckTest(unittest.TestCase):
@@ -455,37 +489,21 @@ class ForegroundCheckTest(unittest.TestCase):
return d return d
def test_rejects_when_no_foreground_window(self): def test_rejects_when_no_foreground_window(self):
with mock.patch.object(di.ctypes.windll.user32, 'GetForegroundWindow', with mock.patch.object(di, 'foreground_window', return_value=None):
return_value=0):
ok, why = di.click_point_is_on_foreground(100, 100) ok, why = di.click_point_is_on_foreground(100, 100)
self.assertFalse(ok) self.assertFalse(ok)
self.assertIn('前台窗口', why) self.assertIn('前台窗口', why)
def test_rejects_when_point_outside_foreground_window(self): def test_rejects_when_point_outside_foreground_window(self):
def fake_get_window_rect(hwnd, ptr): with mock.patch.object(di, 'foreground_window', return_value=12345), \
r = ptr._obj win_api(GetWindowRect=window_rect(0, 0, 50, 50)):
r.left, r.top, r.right, r.bottom = 0, 0, 50, 50
return 1
with mock.patch.object(di.ctypes.windll.user32, 'GetForegroundWindow',
return_value=12345), \
mock.patch.object(di.ctypes.windll.user32, 'GetWindowRect',
fake_get_window_rect), \
mock.patch.object(di.ctypes.windll.user32, 'GetWindowTextW'):
ok, why = di.click_point_is_on_foreground(999, 999) ok, why = di.click_point_is_on_foreground(999, 999)
self.assertFalse(ok) self.assertFalse(ok)
self.assertIn('不在前台窗口内', why) self.assertIn('不在前台窗口内', why)
def test_accepts_when_point_inside_foreground_window(self): def test_accepts_when_point_inside_foreground_window(self):
def fake_get_window_rect(hwnd, ptr): with mock.patch.object(di, 'foreground_window', return_value=12345), \
r = ptr._obj win_api(GetWindowRect=window_rect(0, 0, 1920, 1080)):
r.left, r.top, r.right, r.bottom = 0, 0, 1920, 1080
return 1
with mock.patch.object(di.ctypes.windll.user32, 'GetForegroundWindow',
return_value=12345), \
mock.patch.object(di.ctypes.windll.user32, 'GetWindowRect',
fake_get_window_rect):
ok, why = di.click_point_is_on_foreground(500, 500) ok, why = di.click_point_is_on_foreground(500, 500)
self.assertTrue(ok) self.assertTrue(ok)
self.assertEqual(why, 'ok') self.assertEqual(why, 'ok')
@@ -553,30 +571,29 @@ class HwndForegroundCheckTest(unittest.TestCase):
""" """
def test_accepts_when_foreground_is_the_target(self): def test_accepts_when_foreground_is_the_target(self):
with mock.patch.object(di.ctypes.windll.user32, 'GetForegroundWindow', with mock.patch.object(di, 'foreground_window', return_value=999):
return_value=999):
ok, why = di.click_point_is_on_foreground(100, 100, 999) ok, why = di.click_point_is_on_foreground(100, 100, 999)
self.assertTrue(ok) self.assertTrue(ok)
self.assertEqual(why, 'ok') self.assertEqual(why, 'ok')
def test_accepts_child_window_of_target(self): def test_accepts_child_window_of_target(self):
"""游戏可能有子窗口拿到焦点, 也算在目标窗口上。""" """游戏可能有子窗口拿到焦点, 也算在目标窗口上。"""
with mock.patch.object(di.ctypes.windll.user32, 'GetForegroundWindow', is_child = mock.Mock(return_value=True)
return_value=1000), \ with mock.patch.object(di, 'foreground_window', return_value=1000), \
mock.patch.object(di.ctypes.windll.user32, 'IsChild', win_api(IsChild=is_child):
return_value=True):
ok, _ = di.click_point_is_on_foreground(100, 100, 999) ok, _ = di.click_point_is_on_foreground(100, 100, 999)
is_child.assert_called_once_with(999, 1000)
self.assertTrue(ok) self.assertTrue(ok)
def test_rejects_when_foreground_is_another_window(self): def test_rejects_when_foreground_is_another_window(self):
with mock.patch.object(di.ctypes.windll.user32, 'GetForegroundWindow', titles = {1000: 'Browser', 999: 'LimbusCompany'}
return_value=1000), \ with mock.patch.object(di, 'foreground_window', return_value=1000), \
mock.patch.object(di.ctypes.windll.user32, 'IsChild', win_api(IsChild=mock.Mock(return_value=False)), \
return_value=False), \ mock.patch.object(di, 'window_title', side_effect=titles.get):
mock.patch.object(di.ctypes.windll.user32, 'GetWindowTextW'):
ok, why = di.click_point_is_on_foreground(100, 100, 999) ok, why = di.click_point_is_on_foreground(100, 100, 999)
self.assertFalse(ok) self.assertFalse(ok)
self.assertIn('前台不是目标窗口', why) self.assertIn('前台不是目标窗口', why)
self.assertIn('Browser', why)
def test_bind_window_is_used_by_click(self): def test_bind_window_is_used_by_click(self):
"""绑定窗口后, click() 必须走句柄级校验。""" """绑定窗口后, click() 必须走句柄级校验。"""
@@ -596,4 +613,19 @@ class HwndForegroundCheckTest(unittest.TestCase):
mock.patch.object(di.time, 'sleep', lambda s: None): mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.click(10, 10)) self.assertFalse(d.click(10, 10))
self.assertEqual(seen['hwnd'], 4242, 'click 没把绑定的句柄传下去') self.assertEqual(seen['hwnd'], 4242, 'click 没把绑定的句柄传下去')
d._dll.mouse_down.assert_not_called() d._dll.mouse_down.assert_not_called()
def test_proxy_rebinds_current_window_before_each_click(self):
"""游戏重启后句柄会变; 代理复用时若仍拿安装时的旧句柄, 前台校验会拒绝所有点击。"""
drv = di.DriverInput(dll_path='X.dll', log=lambda m: None).bind_window(111)
handle = SimpleNamespace(hwnd=222, isMinimized=False, setForeground=mock.Mock())
proxy = ap.DriverClickProxy(mock.Mock(), drv, SimpleNamespace(handle=handle), log=lambda _: None)
with mock.patch.object(di, 'is_console_session', return_value=True), \
mock.patch.object(di, 'foreground_window', return_value=222), \
mock.patch.object(di, 'client_to_screen', return_value=(5, 6)):
self.assertEqual(proxy._screen_pos(1, 2), (5, 6))
self.assertEqual(drv.hwnd, 222)
if __name__ == '__main__':
unittest.main()
+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__':