Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ddd8650b7 | ||
|
|
05626e95c7 | ||
|
|
a74fda07e2 |
@@ -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 |
|
||||
|
||||
## 开发 / 测试
|
||||
|
||||
@@ -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)" }
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -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 审查记录。
|
||||
|
||||
@@ -261,7 +261,7 @@ class AalcEngine(Engine):
|
||||
time.sleep(0.12)
|
||||
try:
|
||||
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
|
||||
time.sleep(0.12)
|
||||
time.sleep(0.5 if self.cfg.win_input_type == 'window_move' else 0.12)
|
||||
finally:
|
||||
self._background_mouse(win32con.WM_LBUTTONUP, x, y)
|
||||
# Let Unity consume the release before another target is selected.
|
||||
|
||||
@@ -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 任务和故障重启。"""
|
||||
|
||||
+3
-7
@@ -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,10 +75,7 @@ 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:
|
||||
|
||||
+27
-7
@@ -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,6 +163,7 @@ class DriverInput:
|
||||
# ---------------------------------------------------------------- 移动
|
||||
|
||||
def move_relative(self, dx, dy):
|
||||
with self._input_lock:
|
||||
if not self.ready:
|
||||
return False
|
||||
if dx == 0 and dy == 0:
|
||||
@@ -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:
|
||||
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:
|
||||
|
||||
+38
-7
@@ -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' -> '<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:
|
||||
log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始')
|
||||
if on_stop is not None:
|
||||
on_stop()
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
+3
-1
@@ -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)))}
|
||||
|
||||
@@ -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 '')
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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。
|
||||
|
||||
@@ -46,6 +46,12 @@ def text_items(state):
|
||||
|
||||
def scene_fingerprint(state):
|
||||
"""Ignore changing clocks and counters when checking failed confirmations."""
|
||||
texts = [item['text'].replace(' ', '') for item in text_items(state)]
|
||||
if any(label in texts for label in ('结果', '判定成功', '判定失败')):
|
||||
# The video changes OCR line breaks/spelling even on a static result.
|
||||
# Its result header and actual continuation controls define this scene.
|
||||
return tuple(text for text in texts
|
||||
if text in ('结果', '判定成功', '判定失败', '继续', '开始战斗', '确认'))
|
||||
return tuple(item['text'] for item in text_items(state)
|
||||
if item.get('score', 0) > .93
|
||||
and not re.fullmatch(r'[0-9:.]+', item['text'].replace(' ', '')))
|
||||
@@ -238,7 +244,7 @@ def candidates(state, previous_battle=False, refresh_used=0):
|
||||
}
|
||||
return options
|
||||
gift_headers = sum(t == '获得E.G.O饰品' for t in texts)
|
||||
if gift_headers == 1 and '拒绝饰品' in texts and '选择' in texts:
|
||||
if gift_headers == 1 and '拒绝饰品' in texts and '选择' in texts and '追加的苦难' not in combined:
|
||||
core = any(name in combined for name in ('成捆的符咒','标准负载电池','干巴柴涩鸡胸肉','干松紧致鸡胸肉','快感','雷枝'))
|
||||
if core and '雷枝' not in combined:
|
||||
return options
|
||||
@@ -369,6 +375,8 @@ def candidates(state, previous_battle=False, refresh_used=0):
|
||||
'action':{'tool':'advance_dialog','args':{'presses':3}},
|
||||
'fallback_action':{'tool':'click','args':{'x':item['x']+item['w']//2,'y':item['y']+item['h']//2}},
|
||||
}
|
||||
if 'hardship_confirm' in options:
|
||||
return {key: options[key] for key in ('requires_analysis', 'wait', 'hardship_confirm')}
|
||||
return options
|
||||
# Nested confirmation/detail windows override the reward/pack behind them.
|
||||
modal_question = ('确认' in texts and any('取消' in t for t in texts)
|
||||
@@ -511,6 +519,9 @@ def candidates(state, previous_battle=False, refresh_used=0):
|
||||
and 0 < item['y']-sold['y'] < height*.25 for sold in items)]
|
||||
if in_shop and state.get('floor', 1) >= 2 and not state.get('symbol_upgraded', False):
|
||||
return options
|
||||
if in_shop and state.get('thrill_fusion_due'):
|
||||
options['requires_analysis']['description'] = '本层商店需检查快感合成:保留核心饰品,按普通/特殊商店预览进行有界尝试;检查完成或材料不足后记录本层已处理,再继续技能替换。'
|
||||
return options
|
||||
if in_shop:
|
||||
pending = 'thrill' if state.get('thrill_pending') else 'thunderbranch' if state.get('thunderbranch_pending') else None
|
||||
if pending:
|
||||
@@ -797,6 +808,21 @@ def acquire_single_instance():
|
||||
return lambda: kernel.CloseHandle(lease)
|
||||
|
||||
|
||||
def apply_confirmation_retry(options, last_choice, consecutive_attempts):
|
||||
"""A changing skill description must not hide an unsuccessful Enter."""
|
||||
option = options.get(last_choice)
|
||||
if not option or consecutive_attempts < 1 or not option.get('fallback_action'):
|
||||
return
|
||||
action = option['action']
|
||||
if action != {'tool': 'keypress', 'args': {'key': 'enter'}} and action['tool'] != 'advance_dialog':
|
||||
return
|
||||
if consecutive_attempts >= 3:
|
||||
del options[last_choice]
|
||||
return
|
||||
option['action'] = option['fallback_action']
|
||||
option['description'] += ' 上次快捷确认未推进,点击本次已核对的按钮。'
|
||||
|
||||
|
||||
def main(executor_decider=None):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('config', nargs='?', help='Optional Jev JSON config; omit for execution-model handoff')
|
||||
@@ -820,6 +846,8 @@ def main(executor_decider=None):
|
||||
run = None
|
||||
recent = []
|
||||
repeats = {}
|
||||
last_choice = None
|
||||
consecutive_attempts = 0
|
||||
context_path = RUNTIME_HOME / 'jev_shop_context.json'
|
||||
stable_since = time.monotonic()
|
||||
last_fingerprint = None
|
||||
@@ -866,11 +894,15 @@ def main(executor_decider=None):
|
||||
state['battery_obtained'] = context.get('battery_obtained', False)
|
||||
state['thunderbranch_pending'] = context.get('thunderbranch_pending',False)
|
||||
state['thrill_pending'] = context.get('thrill_obtained',False) and not context.get('thrill_upgraded',False)
|
||||
state['thrill_fusion_due'] = (context.get('floor', 1) >= 3
|
||||
and not context.get('thrill_obtained', False)
|
||||
and context.get('thrill_fusion_checked_floor') != context.get('floor'))
|
||||
state['claim_requested'] = claim_is_current(run, context)
|
||||
options = candidates(state, previous_battle, context['refresh_used'])
|
||||
if fingerprint != last_fingerprint:
|
||||
stable_since = time.monotonic()
|
||||
last_fingerprint = fingerprint
|
||||
repeats.clear()
|
||||
stable_seconds = round(time.monotonic() - stable_since)
|
||||
if stable_seconds > 30:
|
||||
recent.append({'observation':'画面已%d秒没有有效改变,请你判断是否需要主助手排查。' % stable_seconds})
|
||||
@@ -890,6 +922,7 @@ def main(executor_decider=None):
|
||||
action_id = json.dumps(options[key]['action'], sort_keys=True)
|
||||
if key not in ('requires_analysis', 'wait', 'battle') and repeats.get((fingerprint, action_id), 0) >= 2:
|
||||
del options[key]
|
||||
apply_confirmation_retry(options, last_choice, consecutive_attempts)
|
||||
if len(options) == 2:
|
||||
unknown_since = unknown_since or time.monotonic()
|
||||
else:
|
||||
@@ -964,6 +997,8 @@ def main(executor_decider=None):
|
||||
repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1
|
||||
action_started = time.monotonic()
|
||||
result = execute(bridge, action, deadline=deadline)
|
||||
consecutive_attempts = consecutive_attempts + 1 if choice == last_choice else 1
|
||||
last_choice = choice
|
||||
record['action_ms'] = round((time.monotonic()-action_started)*1000)
|
||||
record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S')
|
||||
if result.get('stopped'):
|
||||
|
||||
@@ -24,6 +24,8 @@ LABELS = {
|
||||
'e.g.ogiftsearch':'额外观测', 'eg.dgiftsearch':'额外观测',
|
||||
'nextfloor':'下一层', 'gotonextfloor':'前往下一层', 'proceedtonextfloor':'前往下一层', 'claim':'领取',
|
||||
'additionalhardship':'追加的苦难', 'additionalhardships':'追加的苦难',
|
||||
'mountingtrials':'追加的苦难', 'acquiree.g.ogift':'获得E.G.O饰品',
|
||||
'acquiree.g.ogift!':'获得E.G.O饰品!', 'skilsowned':'当前持有技能',
|
||||
'obtaine.g.ogift':'获得E.G.O饰品', 'obtaine.g.ogifts':'获得E.G.O饰品',
|
||||
'claimrewards':'领取奖励', 'explorationcomplete':'探索完成',
|
||||
'explorationcompleted':'探索完成', 'dungeoncomplete':'探索完成',
|
||||
@@ -40,7 +42,17 @@ def normalize(state):
|
||||
raw = item['text']
|
||||
compact = re.sub(r'\s+', '', raw).lower().lstrip('×x')
|
||||
compact = compact.replace('e.g.0', 'e.g.o')
|
||||
compact = re.sub(r'fl[o0]{2}r', 'floor', compact)
|
||||
text = LABELS.get(compact, raw)
|
||||
screen = state.get('screen', {})
|
||||
if item.get('x', 0) > screen.get('w', 1920) * .65 and item.get('y', 0) > screen.get('h', 1080) * .5:
|
||||
if compact in ('winrate', 'damage'):
|
||||
text = '胜率' if compact == 'winrate' else '伤害'
|
||||
elif compact == 'win' and any(
|
||||
re.sub(r'\s+', '', other['text']).lower() in ('rate', 'bate')
|
||||
and abs(other['x'] - item['x']) < 40
|
||||
and 0 < other['y'] - item['y'] < 35 for other in source_items):
|
||||
text = '胜率'
|
||||
if compact == 'enhance' and any(re.sub(r'\s+', '', other['text']).lower() == 'gifts'
|
||||
and abs(other['x'] - item['x']) < 80 and 0 < other['y'] - item['y'] < 70
|
||||
for other in source_items):
|
||||
@@ -93,6 +105,13 @@ def normalize(state):
|
||||
('Heathcliff','希斯克利夫'), ('Outis','奥提斯'), ('Gregor','格里高尔'),
|
||||
('Ryoshu','良秀'), ('Faust','浮士德')]:
|
||||
text = text.replace(english, chinese)
|
||||
text = re.sub(r'Max\s*HP', '体力上限', text, flags=re.I)
|
||||
text = re.sub(r'Defense\s*Level', '防御等级', text, flags=re.I)
|
||||
if re.fullmatch(r'\d+/\d+', compact) and any(
|
||||
re.sub(r'\s+', '', other['text']).lower() in ('select', '选择')
|
||||
and 0 < item['x'] - other['x'] < 150
|
||||
and abs(item['y'] - other['y']) < 30 for other in source_items):
|
||||
text = '选择' + compact
|
||||
if text != raw:
|
||||
item['original_text'] = raw
|
||||
item['text'] = text
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Controller lifecycle and battle regressions using mocked MCP only."""
|
||||
import contextlib
|
||||
import copy
|
||||
import ctypes
|
||||
import io
|
||||
import json
|
||||
@@ -154,6 +155,21 @@ class AgentRuntimeTest(unittest.TestCase):
|
||||
self.assertTrue(result['stopped'])
|
||||
bridge.call.assert_not_called()
|
||||
|
||||
def test_changing_modal_ocr_still_falls_back_from_enter_and_bounds_retries(self):
|
||||
bridge = mock.Mock()
|
||||
frames = iter(['skill description A', 'skill description B', 'skill description C', 'skill description D'])
|
||||
bridge.call.side_effect = lambda tool, args=None: (
|
||||
{'ok': True, 'items': [{'text': next(frames), 'score': 1}]} if tool == 'get_state' else {'ok': True})
|
||||
options = {'wait': {'action': {'tool': 'wait', 'args': {}}, 'description': 'wait'},
|
||||
'requires_analysis': {'action': {'tool': 'requires_analysis', 'args': {}}, 'description': 'analysis'},
|
||||
'buy_swap': {'description': 'validated skill payment',
|
||||
'action': {'tool': 'keypress', 'args': {'key': 'enter'}},
|
||||
'fallback_action': {'tool': 'click', 'args': {'x': 790, 'y': 548}}}}
|
||||
with mock.patch.object(agent, 'candidates', side_effect=lambda *args: copy.deepcopy(options)):
|
||||
self.run_agent(bridge, extra_args=('--steps', '4'))
|
||||
inputs = [call.args[0] for call in bridge.call.call_args_list if call.args[0] != 'get_state']
|
||||
self.assertEqual(inputs, ['keypress', 'click', 'click'])
|
||||
|
||||
def test_close_error_still_releases_controller_mutex(self):
|
||||
bridge = mock.Mock()
|
||||
bridge.call.return_value = {'ok': True, 'items': []}
|
||||
|
||||
@@ -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)
|
||||
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()
|
||||
|
||||
@@ -77,6 +77,14 @@ class SceneRegressionTest(unittest.TestCase):
|
||||
options['event_2']={'description':'当前事件选项:按下按钮;结果:选择后获得破裂饰品'}
|
||||
self.assertEqual(agent.fixed_fallback(options),'event_2')
|
||||
|
||||
@mock.patch.object(agent,'button_enabled',return_value=True)
|
||||
def test_due_thrill_fusion_prevents_leaving_before_bounded_check(self,_enabled):
|
||||
state={'symbol_upgraded':True,'floor':3,'thrill_fusion_due':True,'items':[
|
||||
{'text':t,'x':100,'y':100,'w':100,'h':40} for t in ('商店','刷新','离开')]}
|
||||
self.assertEqual(set(agent.candidates(state,refresh_used=4)), {'wait','requires_analysis'})
|
||||
state['thrill_fusion_due']=False
|
||||
self.assertTrue(any(k.startswith('button_') for k in agent.candidates(state,refresh_used=4)))
|
||||
|
||||
def test_sinner_very_high_precedes_high_and_generic_gold(self):
|
||||
options={'sinner_1':{'description':'预计成功率高'},
|
||||
'sinner_2':{'description':'预计成功率极高'},
|
||||
|
||||
+90
-25
@@ -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(''), '<f12>')
|
||||
self.assertEqual(killswitch._key_spec(None), '<f12>')
|
||||
self.assertEqual(killswitch._key_spec(' '), '<f12>')
|
||||
|
||||
|
||||
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')
|
||||
|
||||
@@ -87,6 +87,41 @@ class EnglishMirrorBoundaryTest(unittest.TestCase):
|
||||
self.assertNotEqual(agent.scene_fingerprint(observation('00:00:43:02')),
|
||||
agent.scene_fingerprint(observation('00:00:43:02', 'Commence')))
|
||||
|
||||
def test_result_story_ocr_changes_do_not_reset_continue_fallback(self):
|
||||
def observation(story, clock, button='Continue'):
|
||||
return normalize({'items': [{'text': text, 'score': score} for text, score in
|
||||
[('Result', .99), (button, .99), (story, .95), (clock, .98)]]})
|
||||
first = observation('You lookaway and continue on your path.', '00:00:10:02')
|
||||
second = observation('You look away and continue on your path.', '00:00:10:16')
|
||||
self.assertEqual(agent.scene_fingerprint(first), agent.scene_fingerprint(second))
|
||||
self.assertNotEqual(agent.scene_fingerprint(first),
|
||||
agent.scene_fingerprint(observation('same', '00:00:10:16', 'Battle!')))
|
||||
|
||||
def test_english_layer_cards_are_not_single_gift_observation(self):
|
||||
state = {'screen': {'w': 1278, 'h': 731}, 'items': [
|
||||
{'text': text, 'x': x, 'y': y, 'w': 90, 'h': 25, 'score': .99}
|
||||
for text, x, y in [('Acquire E.G.O Gift', 250, 159), ('Mounting Trials', 250, 425),
|
||||
('DefenseLevel +1, MaxHP+7.5%', 250, 491),
|
||||
('Select', 1080, 572), ('0/2', 1160, 569), ('Refuse Gift', 900, 572)]]}
|
||||
normalize(state)
|
||||
self.assertIn('防御等级 +1, 体力上限+7.5%', [item['text'] for item in state['items']])
|
||||
with mock.patch.object(agent, 'button_enabled', return_value=True):
|
||||
options = agent.candidates(state)
|
||||
self.assertTrue(any(key.startswith('hardship_') for key in options))
|
||||
self.assertNotIn('decline_extra_observation', options)
|
||||
self.assertNotIn('hardship_confirm', options)
|
||||
state['items'][-2]['text'] = '选择2/2'
|
||||
with mock.patch.object(agent, 'button_enabled', return_value=True):
|
||||
options = agent.candidates(state)
|
||||
self.assertEqual(set(options), {'requires_analysis', 'wait', 'hardship_confirm'})
|
||||
|
||||
def test_split_win_rate_button_starts_battle_loop_without_wave_label(self):
|
||||
state = normalize({'screen': {'w': 1278, 'h': 731}, 'items': [
|
||||
{'text': text, 'x': 993, 'y': y, 'w': 30, 'h': 16, 'score': .97}
|
||||
for text, y in [('Win', 542), ('Bate', 554)]]})
|
||||
self.assertTrue(agent.battle_is_visible(state))
|
||||
self.assertIn('battle', agent.candidates(state))
|
||||
|
||||
def test_commence_and_split_sinner_header_reach_judgement_boundary(self):
|
||||
state = {'screen': {'w': 1920, 'h': 1080}, 'items': [
|
||||
{'text': text, 'x': 1200, 'y': y, 'w': 200, 'h': 40, 'score': 1}
|
||||
|
||||
Reference in New Issue
Block a user