合并前复核:补齐急停释放、整轮中止和计划任务时限

Browse Source
This commit is contained in:
yws
2026-10-22 07:32:58 +00:00
parent 8a9495b185
commit a74fda07e2
14 changed files with 324 additions and 111 deletions
+9
View File
@@ -98,6 +98,14 @@ $env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。 模拟器不接管;拖拽、滚动、键盘以及 MCP 的独立 `click` 工具仍使用原后端。
当前回归验证覆盖软件接线和异常处理,DLL、实际驱动及游戏响应需在 Windows 实机核验。 当前回归验证覆盖软件接线和异常处理,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_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` | `f12` | 任务子进程的急停键,如 `f11` / `pause` |
| `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 审查记录。
+7 -2
View File
@@ -179,8 +179,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:
@@ -226,6 +225,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 任务和故障重启。"""
+3 -7
View File
@@ -9,11 +9,10 @@ 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_exact_team_match, from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match,
install_robust_set_foreground) install_robust_set_foreground, stop_driver_click)
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = { TASKS = {
@@ -76,10 +75,7 @@ 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)):
# 用户没法用鼠标点停止按钮, 键盘是唯一可靠的中断手段。
kill_listener = killswitch.install(log=log)
problems = preflight.check(preflight.collect(cfg), task, problems = preflight.check(preflight.collect(cfg), task,
desktop=None if cfg.simulator else preflight.desktop_size()) desktop=None if cfg.simulator else preflight.desktop_size())
if problems: if problems:
+27 -7
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
@@ -106,6 +107,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()
# ---------------------------------------------------------------- 生命周期 # ---------------------------------------------------------------- 生命周期
@@ -131,7 +135,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):
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。""" """返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
@@ -152,6 +163,7 @@ class DriverInput:
# ---------------------------------------------------------------- 移动 # ---------------------------------------------------------------- 移动
def move_relative(self, dx, dy): def move_relative(self, dx, dy):
with self._input_lock:
if not self.ready: if not self.ready:
return False return False
if dx == 0 and dy == 0: if dx == 0 and dy == 0:
@@ -177,12 +189,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:
if self._open and self._dll is not None:
self._dll.mouse_up(int(button)) self._dll.mouse_up(int(button))
self._pressed.discard(int(button))
def click(self, sx, sy, times=1, tol=1): def click(self, sx, sy, times=1, tol=1):
"""先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。""" """先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。"""
@@ -195,11 +214,12 @@ class DriverInput:
return False return False
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(0.03) time.sleep(0.03)
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:
+38 -7
View File
@@ -9,25 +9,28 @@
里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。 里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。
默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。 默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。
按下后直接 os._exit —— 任务本来就是子进程, 硬退出不会留下锁或半截状态, 按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally;
这正是 aalc_task.py 的设计前提("停止 = 杀进程树")。 临时配置由 TaskRunner 的恢复文件机制处理。退出前给驱动释放鼠标的短暂机会,
清理卡住时仍强制退出。
""" """
import os import os
import threading import threading
from contextlib import contextmanager
DEFAULT_KEY = 'f12' DEFAULT_KEY = 'f12'
EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止" EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止"
STOP_TIMEOUT = 0.25
def _key_spec(name): def _key_spec(name):
"""'f12' -> '<f12>',pynput 的 GlobalHotKeys 要求尖括号形式。""" """'f12' -> '<f12>',pynput 的 GlobalHotKeys 要求尖括号形式。"""
name = (name or DEFAULT_KEY).strip().lower() name = (name or '').strip().lower() or DEFAULT_KEY
if name.startswith('<') and name.endswith('>'): if name.startswith('<') and name.endswith('>'):
return name return name
return '<%s>' % name return '<%s>' % name
def install(log=print, key=None): def install(log=print, key=None, on_stop=None):
"""启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。 """启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。
任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。 任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。
@@ -48,10 +51,28 @@ def install(log=print, key=None):
if state['fired']: if state['fired']:
return return
state['fired'] = True 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: try:
log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始') if on_stop is not None:
on_stop()
finally: finally:
try:
os._exit(EXIT_CODE)
finally:
timer.cancel() # 仅供 _exit 被测试替换的情况
try:
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) os._exit(EXIT_CODE)
try: try:
@@ -63,7 +84,8 @@ def install(log=print, key=None):
% (type(e).__name__, e)) % (type(e).__name__, e))
return None return None
log('[lc_mcp] 急停热键已就绪: 按 %s 立即停止任务(键盘可用, 不需要鼠标)' % key.upper()) log('[lc_mcp] 急停监听已启动: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
% key.upper())
listener._lc_state = state listener._lc_state = state
return listener return listener
@@ -76,3 +98,12 @@ def stop(listener):
listener.stop() listener.stop()
except Exception: except Exception:
pass pass
@contextmanager
def listening(log=print, on_stop=None):
listener = install(log=log, on_stop=on_stop)
try:
yield listener
finally:
stop(listener)
+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)
+26 -4
View File
@@ -300,8 +300,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)
@@ -328,14 +328,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)
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) 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)]:
@@ -349,6 +356,21 @@ 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.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): 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()
+90 -25
View File
@@ -12,6 +12,9 @@ AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_
""" """
import os import os
import sys import sys
import threading
import tempfile
import time
import unittest import unittest
from pathlib import Path from pathlib import Path
from unittest import mock from unittest import mock
@@ -34,6 +37,7 @@ class KeySpecTest(unittest.TestCase):
def test_empty_falls_back_to_default(self): def test_empty_falls_back_to_default(self):
self.assertEqual(killswitch._key_spec(''), '<f12>') self.assertEqual(killswitch._key_spec(''), '<f12>')
self.assertEqual(killswitch._key_spec(None), '<f12>') self.assertEqual(killswitch._key_spec(None), '<f12>')
self.assertEqual(killswitch._key_spec(' '), '<f12>')
class InstallTest(unittest.TestCase): class InstallTest(unittest.TestCase):
@@ -74,40 +78,88 @@ class InstallTest(unittest.TestCase):
class ActivateTest(unittest.TestCase): class ActivateTest(unittest.TestCase):
"""按下热键必须真的退出进程,而且只退一次。""" def _grab_handler(self, log=lambda _: None, on_stop=None):
def _grab_handler(self):
listener = mock.Mock() listener = mock.Mock()
fake_keyboard = mock.Mock() keyboard = mock.Mock()
fake_keyboard.GlobalHotKeys.return_value = listener keyboard.GlobalHotKeys.return_value = listener
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard), with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=keyboard)}):
'pynput.keyboard': fake_keyboard}): killswitch.install(log=log, on_stop=on_stop)
killswitch.install(log=lambda m: None) return next(iter(keyboard.GlobalHotKeys.call_args.args[0].values())), listener
bindings = fake_keyboard.GlobalHotKeys.call_args[0][0]
return list(bindings.values())[0], listener
def test_exits_with_user_abort_code(self): def fire(self, handler, listener):
handler, _ = self._grab_handler() 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: with mock.patch.object(killswitch.os, '_exit') as fake_exit:
self.fire(handler, listener)
handler() handler()
fake_exit.assert_called_once_with(killswitch.EXIT_CODE) fake_exit.assert_called_once_with(killswitch.EXIT_CODE)
def test_only_fires_once(self): def test_broken_log_cannot_disable_the_hotkey(self):
handler, _ = self._grab_handler() 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: with mock.patch.object(killswitch.os, '_exit') as fake_exit:
handler() self.fire(handler, listener)
handler() fake_exit.assert_called_once_with(130)
handler() log.assert_not_called()
self.assertEqual(fake_exit.call_count, 1, '重复按下不该重复退出')
def test_logs_that_game_stays_alive(self): def test_releases_input_before_exiting_even_when_cleanup_raises(self):
handler, _ = self._grab_handler() 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 = [] lines = []
with mock.patch.object(killswitch.os, '_exit'): self._grab_handler(log=lines.append)
handler.__closure__ # 确认是闭包 self.assertIn('游戏窗口保留', '\n'.join(lines))
killswitch.install(log=lines.append)
# 用新的 logger 重新装一次才拿得到日志,这里只验证消息文案存在 def test_real_emergency_exit_is_reported_as_stopped(self):
self.assertTrue(callable(handler)) 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): class StopTest(unittest.TestCase):
@@ -120,6 +172,19 @@ class StopTest(unittest.TestCase):
killswitch.stop(listener) killswitch.stop(listener)
listener.stop.assert_called_once() 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): def test_stop_swallows_listener_errors(self):
listener = mock.Mock() listener = mock.Mock()
listener.stop.side_effect = RuntimeError('boom') listener.stop.side_effect = RuntimeError('boom')