From a74fda07e292012a0de0de12a1443897dab197b0 Mon Sep 17 00:00:00 2001 From: ywsabc2 Date: Thu, 22 Oct 2026 07:32:58 +0000 Subject: [PATCH] =?UTF-8?q?=E5=90=88=E5=B9=B6=E5=89=8D=E5=A4=8D=E6=A0=B8?= =?UTF-8?q?=EF=BC=9A=E8=A1=A5=E9=BD=90=E6=80=A5=E5=81=9C=E9=87=8A=E6=94=BE?= =?UTF-8?q?=E3=80=81=E6=95=B4=E8=BD=AE=E4=B8=AD=E6=AD=A2=E5=92=8C=E8=AE=A1?= =?UTF-8?q?=E5=88=92=E4=BB=BB=E5=8A=A1=E6=97=B6=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 +++ docs/WATCH.md | 2 - docs/review_20261022.md | 32 +++++++++ lc_mcp/aalc_patches.py | 9 ++- lc_mcp/aalc_task.py | 82 +++++++++++----------- lc_mcp/driver_input.py | 46 +++++++++---- lc_mcp/killswitch.py | 47 ++++++++++--- lc_mcp/tasks.py | 4 +- scripts/auto_cycle.py | 9 +++ scripts/install_convert_task.ps1 | 12 +--- scripts/install_unattended.ps1 | 7 +- tests/test_auto_cycle.py | 29 ++++++++ tests/test_driver_input.py | 32 +++++++-- tests/test_killswitch.py | 115 ++++++++++++++++++++++++------- 14 files changed, 324 insertions(+), 111 deletions(-) diff --git a/README.md b/README.md index 99a23fb..2e0614e 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,14 @@ $env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log" 模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。 当前回归验证覆盖软件接线和异常处理,DLL、实际驱动及游戏响应需在 Windows 实机核验。 +任务运行期间按 **F12** 急停,可用 `LCP_KILL_KEY` 改成 `f11`、`pause` 等键名。 +急停会终止任务子进程,保留游戏窗口;`task_status` 返回 `stopped`、退出码 `130`。 +刷取循环检测到用户停止后结束本轮,不再导航、升级或重试。急停前会尝试释放驱动 +按住的鼠标按钮,清理超过 250 毫秒仍强制退出;硬退出留下的临时配置恢复文件由 +`stop_task` 或下一次 `run_task` 处理。热键监听依赖 AALC 的 `pynput`,安装失败会写日志; +也可从 MCP 调用 `stop_task`,或按 Ctrl+Alt+Del 打开任务管理器终止任务进程。 +此热键只覆盖 `run_task` 子进程,不覆盖独立运行的合成、升级脚本。 + ## 工具 | 工具 | 说明 | @@ -180,6 +188,7 @@ powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Every | `LCP_PORT` | 8765 | 服务/bridge 端口 | | `LCP_KEEP_SHOTS` | 30 | 截图保留张数 | | `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 | +| `LCP_KILL_KEY` | `f12` | 任务子进程的急停键,如 `f11` / `pause` | | `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python | ## 开发 / 测试 diff --git a/docs/WATCH.md b/docs/WATCH.md index a149419..2f86cf5 100644 --- a/docs/WATCH.md +++ b/docs/WATCH.md @@ -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)" } } ``` - - diff --git a/docs/review_20261022.md b/docs/review_20261022.md index 1802944..2122b9e 100644 --- a/docs/review_20261022.md +++ b/docs/review_20261022.md @@ -96,3 +96,35 @@ OCR 误读;已知读法集合只来自该账号历史观测,不是通用余 测试从 vendor AST 提取并执行真实的 `init_input`、交互门与监控点击方法, 不复制其接线逻辑; 实际 `aalc_task.run` 的 `all` / `daily` 入口也有覆盖。Windows DLL 和游戏未在本次环境执行。 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 审查记录。 diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py index 681bff3..81d1de1 100644 --- a/lc_mcp/aalc_patches.py +++ b/lc_mcp/aalc_patches.py @@ -179,8 +179,7 @@ class DriverClickProxy: sx, sy = self._screen_pos(x, y) if not self._driver.move_to(sx, sy): return False - self._driver.down(1) - return True + return self._driver.down(1) is not False def mouse_up(self, x, y): try: @@ -226,6 +225,12 @@ def install_driver_click(auto, screen, driver=None, log=print): return drv +def stop_driver_click(auto): + handler = auto.input_handler + if isinstance(handler, DriverClickProxy): + handler._driver.emergency_stop() + + @contextmanager def driver_click_tasks(scheme, auto, screen, cfg, log=print): """每次游戏初始化完成后接管, 包括 all 任务和故障重启。""" diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index 3858bf0..f1bb1cf 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -9,11 +9,10 @@ import json import os import sys -from . import preflight +from . import killswitch, 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) + install_robust_set_foreground, stop_driver_click) # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 TASKS = { @@ -76,48 +75,45 @@ def run(task, params): from tasks.battle import battle from utils.path_manager import path_manager - # 急停热键: 装得越早越好。驱动级点击期间鼠标被人和程序抢来抢去, - # 用户没法用鼠标点停止按钮, 键盘是唯一可靠的中断手段。 - kill_listener = killswitch.install(log=log) + with killswitch.listening(log=log, on_stop=lambda: stop_driver_click(auto)): + problems = preflight.check(preflight.collect(cfg), task, + 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, - 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 - - install_exact_team_match(auto, log) - install_robust_set_foreground(screen, log=log) - guard = WindowGuard(screen, cfg, log=log) - guard.start() - restore_path = os.environ.get(RESTORE_ENV) - originals = apply_overrides(cfg, task, params, restore_path) - with driver_click_tasks(scheme, auto, screen, cfg, log=log): - try: - if task == 'all': - scheme.script_task() + install_exact_team_match(auto, log) + install_robust_set_foreground(screen, log=log) + guard = WindowGuard(screen, cfg, log=log) + guard.start() + restore_path = os.environ.get(RESTORE_ENV) + originals = apply_overrides(cfg, task, params, restore_path) + with driver_click_tasks(scheme, auto, screen, cfg, log=log): + try: + if task == 'all': + scheme.script_task() + return 0 + # 与 script_task() 相同的前置步骤 + scheme.init_game() + path_manager.initialize_paths() + auto.clear_img_cache() + 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 - # 与 script_task() 相同的前置步骤 - scheme.init_game() - path_manager.initialize_paths() - auto.clear_img_cache() - 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) + finally: + guard.stop() + retry_monitor.stop() + restore(cfg, originals, restore_path) def main(argv): diff --git a/lc_mcp/driver_input.py b/lc_mcp/driver_input.py index d59bb40..580edd5 100644 --- a/lc_mcp/driver_input.py +++ b/lc_mcp/driver_input.py @@ -22,6 +22,7 @@ import ctypes import os import time +import threading from ctypes import wintypes from functools import lru_cache @@ -106,6 +107,9 @@ class DriverInput: self.log = log self._dll = None self._open = False + self._stopped = False + self._input_lock = threading.RLock() + self._pressed = set() # ---------------------------------------------------------------- 生命周期 @@ -131,7 +135,14 @@ class DriverInput: @property 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): """返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。""" @@ -152,12 +163,13 @@ class DriverInput: # ---------------------------------------------------------------- 移动 def move_relative(self, dx, dy): - if not self.ready: - return False - if dx == 0 and dy == 0: + with self._input_lock: + if not self.ready: + return False + if dx == 0 and dy == 0: + return True + self._dll.moveR(int(dx), int(dy), 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): """把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。""" @@ -177,12 +189,19 @@ class DriverInput: # ---------------------------------------------------------------- 按键 def down(self, button=1): - if self.ready: - self._dll.mouse_down(int(button)) + with self._input_lock: + 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): - if self.ready: - self._dll.mouse_up(int(button)) + with self._input_lock: + 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): """先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。""" @@ -195,11 +214,12 @@ class DriverInput: return False for _ in range(int(times)): try: - self._dll.mouse_down(1) + if not self.down(1): + return False time.sleep(0.03) finally: - self._dll.mouse_up(1) - return True + self.up(1) + return not self._stopped def key_down(self, key): if self.ready: diff --git a/lc_mcp/killswitch.py b/lc_mcp/killswitch.py index b3d07f9..5282b63 100644 --- a/lc_mcp/killswitch.py +++ b/lc_mcp/killswitch.py @@ -9,25 +9,28 @@ 里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。 默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。 -按下后直接 os._exit —— 任务本来就是子进程, 硬退出不会留下锁或半截状态, -这正是 aalc_task.py 的设计前提("停止 = 杀进程树")。 +按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally; +临时配置由 TaskRunner 的恢复文件机制处理。退出前给驱动释放鼠标的短暂机会, +清理卡住时仍强制退出。 """ import os import threading +from contextlib import contextmanager DEFAULT_KEY = 'f12' EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止" +STOP_TIMEOUT = 0.25 def _key_spec(name): """'f12' -> '',pynput 的 GlobalHotKeys 要求尖括号形式。""" - name = (name or DEFAULT_KEY).strip().lower() + name = (name or '').strip().lower() or DEFAULT_KEY if name.startswith('<') and name.endswith('>'): return name return '<%s>' % name -def install(log=print, key=None): +def install(log=print, key=None, on_stop=None): """启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。 任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。 @@ -48,10 +51,28 @@ def install(log=print, key=None): if state['fired']: return state['fired'] = True - log('[lc_mcp] ⛔ 急停热键 %s 被按下, 立即终止任务' % key.upper()) + # Windows 在系统输入线程上调用此函数, 不在这里写日志或等待清理。 + # 即使日志锁/驱动清理卡住, 也必须按时退出。 + timer = threading.Timer(STOP_TIMEOUT, os._exit, args=(EXIT_CODE,)) + timer.daemon = True + + def shutdown(): + try: + if on_stop is not None: + on_stop() + finally: + try: + os._exit(EXIT_CODE) + finally: + timer.cancel() # 仅供 _exit 被测试替换的情况 + try: - log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始') - finally: + timer.start() + worker = threading.Thread(target=shutdown, name='lc-mcp-emergency-stop', daemon=True) + state['worker'] = worker + worker.start() + except Exception: + timer.cancel() os._exit(EXIT_CODE) try: @@ -63,7 +84,8 @@ def install(log=print, key=None): % (type(e).__name__, e)) return None - log('[lc_mcp] 急停热键已就绪: 按 %s 立即停止任务(键盘可用, 不需要鼠标)' % key.upper()) + log('[lc_mcp] 急停监听已启动: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始' + % key.upper()) listener._lc_state = state return listener @@ -76,3 +98,12 @@ def stop(listener): listener.stop() except Exception: pass + + +@contextmanager +def listening(log=print, on_stop=None): + listener = install(log=log, on_stop=on_stop) + try: + yield listener + finally: + stop(listener) diff --git a/lc_mcp/tasks.py b/lc_mcp/tasks.py index 9931637..640639b 100644 --- a/lc_mcp/tasks.py +++ b/lc_mcp/tasks.py @@ -12,6 +12,7 @@ import time from collections import deque 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__))) IS_WIN = sys.platform.startswith('win') @@ -186,7 +187,8 @@ class TaskRunner: state = 'running' else: 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'], '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)))} diff --git a/scripts/auto_cycle.py b/scripts/auto_cycle.py index 2f86c10..11e5636 100644 --- a/scripts/auto_cycle.py +++ b/scripts/auto_cycle.py @@ -42,6 +42,10 @@ DEFAULT_REPORT_DIR = os.path.expanduser(os.path.join('~', 'lc_mcp', 'cycles')) _log_file = None +class UserAborted(RuntimeError): + """用户主动停止, 结束整轮, 不执行后续导航、升级或重试。""" + + def log(msg): line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg) print(line, flush=True) @@ -176,6 +180,8 @@ def poll_task(task, timeout_s, sleep=time.sleep): raise RuntimeError('无法读取任务状态: %s' % st.get('error', st)) s = st.get('state') el = int(time.time() - t0) + if s == 'stopped' or st.get('exit_code') == 130: + raise UserAborted('%s 已被用户停止' % task) if s != 'running': log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code'))) # AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors @@ -332,6 +338,9 @@ def main(argv=None): try: return run_cycle(args, step, finish) + except UserAborted as e: + step('用户停止', False, str(e)) + return finish(130, '本轮已由用户停止') except (OSError, RuntimeError, subprocess.SubprocessError) as e: if isinstance(e, subprocess.CalledProcessError): output = (e.stdout or '') + (e.stderr or '') diff --git a/scripts/install_convert_task.ps1 b/scripts/install_convert_task.ps1 index 1b00c99..b2e4a73 100644 --- a/scripts/install_convert_task.ps1 +++ b/scripts/install_convert_task.ps1 @@ -5,14 +5,8 @@ # powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -EveryHours 6 # powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Uninstall # -# 节奏怎么定(体力恢复速度): -# Limbus 的体力每 6 分钟回 1 点, 上限 126。 -# 合成 1 个模块要 20 点体力, 所以: -# 每 2 小时 -> 约 20 点 -> 1 个模块 -# 每 4 小时 -> 约 40 点 -> 2 个模块(默认) -# 每 6 小时 -> 约 60 点 -> 3 个模块 -# 只要不顶到 126 上限就不浪费恢复量, 所以更勤快些也不会亏。 -# 4 小时是"每次都能换到东西"和"别老折腾游戏启动"之间的折中。 +# 默认每 4 小时检查一次; 是否合成以本轮实际体力读数为准, 不按固定恢复速率推算。 +# 合成 1 个模块需要 20 点体力。 # # 这个任务和 LcMCPDailyCycle 是分开的: 用户明确要求这次不打任何关卡, # 只挂机攒模块, 所以不能把刷取任务一起打开。 @@ -42,7 +36,7 @@ if (-not (Test-Path $script)) { throw "找不到脚本: $script" } -# 以当前用户运行。无人值守要点: 不要勾"只在用户登录时运行", 否则注销后不跑。 +# 以当前用户的交互会话运行, 必须保持登录; 注销后没有可供截图/点击的游戏桌面。 $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` -LogonType Interactive -RunLevel Limited diff --git a/scripts/install_unattended.ps1 b/scripts/install_unattended.ps1 index d99090c..9076d5e 100644 --- a/scripts/install_unattended.ps1 +++ b/scripts/install_unattended.ps1 @@ -6,7 +6,7 @@ # powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1 # 可选: -At 05:30 每日运行时间。游戏每日重置为 06:00 (KST), 即北京时间 05:00 # -EveryHours 2.5 改成"每 N 小时重复一轮"以持续刷取; 0 = 只按 -At 每天一次 -# 单轮上限 = 60 + 75*Mirror 分钟, 间隔要大于它, 否则会被跳过 +# 任务时限包含 daily 45 分钟、每局镜牢 100 分钟、各一次重试及 30 分钟收尾 # -Mirror 1 每轮镜牢局数, 0 = 不打镜牢 # -Target 34 把队内人格升到的等级 # -Python <路径> 默认 vendor\aalc\.venv\Scripts\pythonw.exe (无窗口, 不抢游戏焦点) @@ -66,8 +66,9 @@ if (-not $NoWatchdog) { $cycle = Join-Path $PSScriptRoot "auto_cycle.py" $action = New-ScheduledTaskAction -Execute $Python -WorkingDirectory $Repo ` -Argument "-X utf8 `"$cycle`" --mirror $Mirror --target $Target" -# 一轮 daily 约 22 分钟, 每局镜牢实测 39~>70 分钟; 超过上限由计划任务强杀 -$limit = New-TimeSpan -Minutes (60 + 75 * [Math]::Max($Mirror, 0)) +# 与 auto_cycle.py 的 DAILY_TIMEOUT_S / MIRROR_TIMEOUT_S / STALL_RETRIES 对齐。 +# 每个任务最多两次尝试, 另留 30 分钟给启动、轮询和升级; 避免外层先杀掉报告进程。 +$limit = New-TimeSpan -Minutes (30 + 2 * (45 + 100 * [Math]::Max($Mirror, 0))) if ($EveryHours -gt 0) { # 持续刷取: 每 N 小时重复一轮。开始时间取"现在", 装完即进入节奏。 # 注意 New-TimeSpan -Hours 的参数是 [int], 传 2.5 会被截断成 2 小时, 所以用 -Minutes。 diff --git a/tests/test_auto_cycle.py b/tests/test_auto_cycle.py index c993e20..08c2e3a 100644 --- a/tests/test_auto_cycle.py +++ b/tests/test_auto_cycle.py @@ -164,6 +164,35 @@ class RunAalcTest(unittest.TestCase): self.assertIn('preflight', info) 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): mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])]) ok, info = self.run_aalc(mcp) diff --git a/tests/test_driver_input.py b/tests/test_driver_input.py index 2da9f10..c79afe1 100644 --- a/tests/test_driver_input.py +++ b/tests/test_driver_input.py @@ -300,8 +300,8 @@ class DriverWiringTest(unittest.TestCase): def test_actual_task_entry_enables_driver_for_all_and_daily(self): from lc_mcp import aalc_task - for task in ('all', 'daily'): - with self.subTest(task=task): + for task, problems in [('all', []), ('daily', []), ('all', ['invalid config'])]: + with self.subTest(task=task, problems=problems): auto, handler_type = vendor_auto() auto.clear_img_cache = mock.Mock() auto.click_element = mock.Mock(return_value=False) @@ -328,14 +328,21 @@ class DriverWiringTest(unittest.TestCase): mock.patch.object(aalc_task, 'install_exact_team_match'), \ mock.patch.object(aalc_task, 'install_robust_set_foreground'), \ 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.preflight, 'collect', return_value={}), \ 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(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)): - self.assertEqual(aalc_task.run(task, {}), 0) - drv.click.assert_called_once_with(10, 20, times=1) + self.assertEqual(aalc_task.run(task, {}), 3 if problems else 0) + 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): for enabled, simulator in [('0', False), ('1', True)]: @@ -349,6 +356,21 @@ class DriverWiringTest(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.time, 'sleep', side_effect=lambda _: drv.emergency_stop()): + self.assertFalse(drv.click(10, 20, times=3)) + 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): drv = di.DriverInput() drv._open, drv._dll = True, mock.Mock() diff --git a/tests/test_killswitch.py b/tests/test_killswitch.py index 1d476a7..d7a0bb1 100644 --- a/tests/test_killswitch.py +++ b/tests/test_killswitch.py @@ -12,6 +12,9 @@ AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_ """ import os import sys +import threading +import tempfile +import time import unittest from pathlib import Path from unittest import mock @@ -34,6 +37,7 @@ class KeySpecTest(unittest.TestCase): def test_empty_falls_back_to_default(self): self.assertEqual(killswitch._key_spec(''), '') self.assertEqual(killswitch._key_spec(None), '') + self.assertEqual(killswitch._key_spec(' '), '') class InstallTest(unittest.TestCase): @@ -74,40 +78,88 @@ class InstallTest(unittest.TestCase): class ActivateTest(unittest.TestCase): - """按下热键必须真的退出进程,而且只退一次。""" - - def _grab_handler(self): + def _grab_handler(self, log=lambda _: None, on_stop=None): 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 + keyboard = mock.Mock() + keyboard.GlobalHotKeys.return_value = listener + with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=keyboard)}): + killswitch.install(log=log, on_stop=on_stop) + return next(iter(keyboard.GlobalHotKeys.call_args.args[0].values())), listener - def test_exits_with_user_abort_code(self): - handler, _ = self._grab_handler() + def fire(self, handler, listener): + handler() + listener._lc_state['worker'].join(2) + self.assertFalse(listener._lc_state['worker'].is_alive()) + + def test_exits_with_user_abort_code_and_only_fires_once(self): + handler, listener = self._grab_handler() with mock.patch.object(killswitch.os, '_exit') as fake_exit: + self.fire(handler, listener) handler() fake_exit.assert_called_once_with(killswitch.EXIT_CODE) - def test_only_fires_once(self): - handler, _ = self._grab_handler() + def test_broken_log_cannot_disable_the_hotkey(self): + log = mock.Mock() + handler, listener = self._grab_handler(log=log) + log.reset_mock() + log.side_effect = OSError('closed log') with mock.patch.object(killswitch.os, '_exit') as fake_exit: - handler() - handler() - handler() - self.assertEqual(fake_exit.call_count, 1, '重复按下不该重复退出') + self.fire(handler, listener) + fake_exit.assert_called_once_with(130) + log.assert_not_called() - def test_logs_that_game_stays_alive(self): - handler, _ = self._grab_handler() + def test_releases_input_before_exiting_even_when_cleanup_raises(self): + calls = [] + def cleanup(): + calls.append('release') + raise OSError('driver disconnected') + handler, listener = self._grab_handler(on_stop=cleanup) + # 不让测试线程输出预期的异常 traceback。 + with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: calls.append(code)), \ + mock.patch.object(threading, 'excepthook'): + self.fire(handler, listener) + self.assertEqual(calls, ['release', 130]) + + def test_hung_cleanup_cannot_block_exit_deadline(self): + release, exited = threading.Event(), threading.Event() + handler, listener = self._grab_handler(on_stop=release.wait) + with mock.patch.object(killswitch.os, '_exit', side_effect=lambda code: exited.set()): + handler() + try: + self.assertTrue(exited.wait(2), '清理卡住也必须触发强退') + finally: + release.set() + listener._lc_state['worker'].join(2) + + def test_startup_message_explains_game_is_kept(self): lines = [] - with mock.patch.object(killswitch.os, '_exit'): - handler.__closure__ # 确认是闭包 - killswitch.install(log=lines.append) - # 用新的 logger 重新装一次才拿得到日志,这里只验证消息文案存在 - self.assertTrue(callable(handler)) + self._grab_handler(log=lines.append) + self.assertIn('游戏窗口保留', '\n'.join(lines)) + + def test_real_emergency_exit_is_reported_as_stopped(self): + from lc_mcp.tasks import TaskRunner + child = """ +import json, os, sys, time +from types import SimpleNamespace +from lc_mcp import killswitch +from lc_mcp.aalc_task import RESTORE_ENV +class Listener: + def __init__(self, bindings): self.activate = next(iter(bindings.values())) + def start(self): pass +sys.modules['pynput'] = SimpleNamespace(keyboard=SimpleNamespace(GlobalHotKeys=Listener)) +listener = killswitch.install(log=lambda msg: None) +with open(os.environ[RESTORE_ENV], 'w') as f: json.dump({'set_mirror_count': 1}, f) +listener.activate() +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): @@ -120,6 +172,19 @@ class StopTest(unittest.TestCase): killswitch.stop(listener) listener.stop.assert_called_once() + def test_listening_stops_on_return_and_exception(self): + for failure in (False, True): + listener = mock.Mock() + with self.subTest(failure=failure), \ + mock.patch.object(killswitch, 'install', return_value=listener): + try: + with killswitch.listening(): + if failure: + raise RuntimeError('task failed') + except RuntimeError: + pass + listener.stop.assert_called_once() + def test_stop_swallows_listener_errors(self): listener = mock.Mock() listener.stop.side_effect = RuntimeError('boom')