Author SHA1 Message Date
Codex Agent 0ddd8650b7 镜牢决策补强: 确认重试回退、快感合成闸门与英文 OCR 别名
- aalc_engine: window_move 下按压保持 0.5s, 避免 Unity 漏点
- jev_mirror_agent: 技能描述抖动时 Enter 未推进改点已核对按钮并限制连续重试;
  结果页指纹忽略剧情与时钟变化; 追加的苦难不再误判为单个饰品场景;
  第 3 层起离开商店前强制做一次有界快感合成检查
- lc_scene_aliases: 补 Mounting Trials / Acquire E.G.O Gift 等标签,
  识别拆分的 Win/Bate 胜率按钮与 Max HP / Defense Level 文本
- tests: 覆盖上述回归点
2026-10-22 15:44:02 +08:00
yws 05626e95c7 合并自动化与驱动输入修复分支,完成审查和急停回归 2026-10-22 07:33:05 +00:00
yws a74fda07e2 合并前复核:补齐急停释放、整轮中止和计划任务时限 2026-10-22 07:32:58 +00:00
Codex Agent 8a9495b185 加急停热键 F12(驱动级点击期间用户没法用鼠标停止)
用户提问: "你执行脚本的时候我鼠标没法动,我怎么停止呢"

这不是小问题 —— 驱动级点击是闭环定位的: 手一动, 下一次点击前会读到新位置算出
偏差, 再把你推回目标点。所以任务跑起来时鼠标是"拔河"状态, 用户根本没法用鼠标
去点停止按钮。而 AALC 自带的 pause_hotkey 只在 GUI(app/farming_interface.py)
里注册, lc_mcp 走命令行子进程, 那条路径上没有热键监听 —— 等于跑任务时没有急停手段。

   唯一可靠的中断通道是键盘, 所以做成全局热键。

实现: lc_mcp/killswitch.py, pynput 的 GlobalHotKeys 监听, 默认 F12
(环境变量 LCP_KILL_KEY 可改)。按下后 os._exit(130) —— 任务本来就是子进程,
硬退出不留锁和半截状态, 这与 aalc_task.py "停止 = 杀进程树" 的设计一致。

装在 aalc_task.py 的 preflight 之前(尽早), 装不上只记日志不抛异常, 并明确提示
改用 Ctrl+Alt+Del —— 急停装不上不该让任务起不来, 但必须告诉用户应急手段。

验证: 13 个测试通过(键名归一化 / pynput 缺失时给应急手段 / 只触发一次 /
不重复退出 / 环境变量覆盖), 真机注册与停止均正常。全套 412 通过。
2026-10-22 15:18:11 +08:00
yws 46b5af01cd 复核驱动输入与窗口补丁,修复接管互斥和异常清理 2026-10-22 06:52:39 +00:00
Codex Agent e2de126687 修复 background_click=false 时 setForeground 崩溃
现象: 改 set_win_size 后任务在 init_game() 里直接崩, exit code 3, traceback:
  screen.py:343 _set_win -> handle.setForeground()
  -> win32gui.SetForegroundWindow(hwnd)
  -> pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available')

原因: screen.py:342 在 cfg.background_click=False 时才调 setForeground, 而原生
实现(screen.py:167-171)只有一句裸调用, 没有任何兜底。Windows 不允许非前台进程
抢占前台, 失败就抛异常, 这个异常在 set_win() 里没被捕获, 整个任务崩掉。

  也就是说: 我为了修抓图黑屏把 background_click 改成 false, 反而踩出了这条
  一直存在但从没被走到的崩溃路径。

修复: install_robust_set_foreground —— 先试原生调用, 失败则用 MSDN 认可的标准
手法兜底: 把自己的线程输入队列 AttachThreadInput 到当前前台窗口线程上, 借它的
前台权限 BringWindowToTop + SetForegroundWindow, 完成后解挂。兜底也失败只记日志
不抛异常 —— 抢不到前台不该让整个任务死掉。

验证: 同样的 set_win_size=720 配置, 修复前 exit 3 崩溃, 修复后正常走到"一次镜牢"。

附带发现: 驱动级输入这次被 preflight 正确拒绝了(GetForegroundWindow=0)。
用户改用 ToDesk 连接后桌面变成独立会话(主屏是 Todesk Virtual Display Adapter),
驱动级注入在这种会话里本来就不生效 —— 拒绝并回退普通注入是正确行为。
2026-10-22 13:27:12 +08:00
Codex Agent 7eafbdd651 修复驱动点击接管被 init_game() 覆盖(补追踪)
问题: 日志里能看到 "鼠标点击已切到罗技驱动级输入", 但驱动点击一次都没发生
(追踪文件只有 2 行 install 记录, [driver] 日志 0 条, 而 automation.py:152 的
点击日志有 58 次)。

原因: 安装在 scheme.init_game() **之前**。init_game() 会重建 auto.input_handler
(automation.py:46/65/72/77/84/89/94/98 多处赋值), 把装好的代理覆盖掉。所以
patch 日志打了, 但真正点击时 getattr(self.input_handler, 'mouse_click') 取到的
是原来的 handler。

修复: 把安装挪到 init_game() 之后。

另外加了 LCP_DRIVER_TRACE 文件追踪(install 时记录原 handler 与 auto.mouse_click
的原绑定, mouse_click 每次调用都记一行) —— 普通日志会被 AALC 的 logger 吞掉,
文件追踪是这次能定位到根因的关键。

这个问题说明测试覆盖不足: 单元测试用 Mock 造 auto, 没有复现 automation.py 真实的
别名/gate 接线, 所以没能发现"装完被覆盖"。后续要补一个贴近真实接线的测试。
2026-10-22 11:55:58 +08:00
Codex Agent 2902cf5dbf 驱动级输入接管 AALC 任务流的鼠标点击(LCP_DRIVER_INPUT=1 开关)
按"应该在输入层接管"的思路做的: 不是只改 lc_mcp 自己的 click, 而是把 AALC 任务流里
所有鼠标点击都转到罗技驱动上 —— 这样镜牢/日常的点击也走物理输入。

一、lc_mcp/driver_input.py(新)
   DriverInput 封装 logitech.driver.dll(device_open/moveR/mouse_down/mouse_up)。
   定位用**闭环**: 发相对位移 -> 读回实际坐标 -> 不够再发, 收敛到 <=1px 才认。
   不依赖任何标定常数, 也不怕偶发坐标跳变。

   preflight() 有三条硬性拒绝, 每条都对应一个实测过的失败条件:
     * device_open() != 1            -> 罗技驱动没就绪
     * GetForegroundWindow() == 0    -> 当前不是物理交互会话(RDP 独立会话里驱动级无效;
                                        实测那时 22 次采样光标纹丝不动, 切到 console 立刻正常)
     * 指针加速开着                  -> counts 与像素不成比例(实测 +100/+200/+400 对应
                                        -45/-3/-3 像素), 关掉后严格 1:1

二、aalc_patches.py: DriverClickProxy + install_driver_click
   只接管 mouse_click / mouse_down / mouse_up, 其余(拖拽/滑动/滚轮/等待)一律透传。
   拖拽类不接管: 那些行为差异大, 用相对位移复现更容易出错。

   ⛔ 关键细节: automation.py 初始化时把方法绑成了别名
   (self.mouse_click = self.input_handler.mouse_click), 所以**换 handler 不够**,
   必须把别名一起重绑, 否则任务流里调的还是老方法。测试里专门守这一条。

   条件不满足时**一个都不改** —— 宁可继续用原来的注入方式, 也不要半吊子接管。

三、aalc_task.py: 环境变量 LCP_DRIVER_INPUT=1 时才安装; 默认关闭。

验证(真机, 物理 console 会话):
  preflight: True | ok        前台窗口存在 True   指针加速 False
  move_to (400,300) / (1200,700) / (800,500) -> 误差全部 (0,0)
  click(600,400) -> True

测试 15 个, 重点在"各种条件不满足时必须拒绝"。全套 399/399 通过。
2026-10-22 11:09:42 +08:00
Codex Agent a6e987e796 修复点击时画面抽搐, 并把截屏自检改成走 AALC 实际用的采集路径
一、为什么"我用脚本点击时画面一直抽搐, AALC 点击不抽搐"

链条查清了:
  * lc_mcp/aalc_engine.py 的 click 每次先 set_window_transparent(True)
  * 而这个方法的实现是 SetLayeredWindowAttributes(hwnd, 0, 0, LWA_ALPHA)
    —— alpha=0, 整个游戏窗口**完全透明(看不见)**
  * 它原来**只有 background_screenshot 会恢复成 False**(screenshot.py:194)
  * 我的脚本是"点击 -> 截图 -> 点击 -> 截图"高频交替
    => 窗口在不可见/可见之间反复切换 => 肉眼看就是一直抽搐

AALC 自己的 WindowMoveInput.mouse_click 只搬窗口、**根本不碰透明度**, 所以它最多
"跳一下", 不会闪 —— 这就是两边观感不同的原因。

改法: 透明度在**本次点击/拖动结束时立刻还原**, 并且放在嵌套 try/finally 里 ——
还原位置那步也可能抛错(任务被停), 不能让它把透明度还原跳过去, 否则窗口会一直隐形。
(第一版就是把还原排在 finally 里的 sleep 之后, 测试里"异常路径"那条立刻抓到了。)

二、render_ok() 改成测 AALC 真正走的那条路

原来只测屏幕 BitBlt(GetDC(0))。2026-10-22 实测它在 RDP 会话下会瞬时失败, 而 AALC
走的是 background_screenshot(窗口 DC + PrintWindow), 那条路照样能截到图 —— 我的自检
把本来能干活的轮次判成"截不到图"跳过了(10-17 02:23 就白丢过一轮)。
现在优先测窗口能否采集, 窗口不在或不可采才回退到屏幕。

测试: 新增 3 个(点击内还原/异常也还原/前台模式不碰透明度) + 4 个 render_ok 分支。
全套 384/384 通过。
2026-10-22 09:34:29 +08:00
23 changed files with 1839 additions and 104 deletions
+35
View File
@@ -72,6 +72,40 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p
部分 Unity 界面仍读取系统指针位置,实测标题页按钮需使用 `window_move`。
战斗按键有按下/释放间隔;隐藏启动后可用 `show_game_background` 恢复渲染。
## 可选:任务流使用罗技驱动鼠标输入
驱动接入代码已随仓库提交:`lc_mcp/driver_input.py`、`lc_mcp/aalc_patches.py`、
`lc_mcp/aalc_task.py`,回归测试在 `tests/test_driver_input.py`。
**仓库不包含 `logitech.driver.dll`、罗技驱动安装包或 `logitech.test.py`。**
需要在 Windows 目标机安装配套驱动并提供 DLL;仅拉取本仓库不能启用这套输入。
在启动 MCP 服务的进程环境中设置(路径替换为本机实际位置):
```powershell
$env:LCP_DRIVER_INPUT = '1'
$env:LCP_LOGITECH_DLL = 'E:\罗技键鼠驱动\logitech.driver.dll'
# 可选,目录需已存在:
$env:LCP_DRIVER_TRACE = "$env:USERPROFILE\lc_mcp\driver-input.log"
```
`LCP_DRIVER_INPUT` 默认关闭,DLL 路径未设置时默认使用上面的 E 盘路径。
服务已经运行时,需要让服务以这些环境变量重新启动;只给 SSH bridge 设置无效。
任务子进程必须在物理 console 会话内,且关闭“提高指针精确度”。预检失败会记录原因,
继续使用原输入后端,不修改系统设置。驱动模式会移动真实系统光标并尝试激活游戏;
激活或坐标转换失败时拒绝本次点击。
接管范围是 `run_task` 的鼠标点击(含空白点击、`all` 和游戏重启后的点击)。
模拟器不接管;拖拽、滚动、键盘以及 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` 子进程,不覆盖独立运行的合成、升级脚本。
## 工具
| 工具 | 说明 |
@@ -154,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 |
## 开发 / 测试
-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)" }
}
```
+65
View File
@@ -63,3 +63,68 @@ OCR 误读;已知读法集合只来自该账号历史观测,不是通用余
`state`;`errors` 表示本次日志出现过错误,不代表所有步骤都失败。新任务重新计算自己的结果。
回归覆盖早期错误被大量日志挤出、错误条数上限、日志删除后的结果保留和下一轮状态清理。
补充修复后的全套测试:377 项通过(18.235 秒);`git diff --check` 通过。
## 补充:远程驱动输入与窗口补丁复核
本次审查范围是远程新增的 `a6e987e`、`2902cf5`、`7eafbdd`、`e2de126`。
从 `e2de126` 开始修复;未修改 AALC 子模块或目标机配置。
| 优先级 | 已确认问题 | 修复 |
|---|---|---|
| P1 | 直接把 `auto.mouse_click` 绑到代理, 覆盖了真实 `Automation.init_input()` 后续安装的交互门和输入锁, 业务线程可能与监控线程同时点击 | 通过 `_run_business_interaction` 重建入口, 继续使用相同的门与锁 |
| P1 | `task=all` 提前进入 `script_task()` 跳过安装; 游戏异常重启后 `init_game()` 再次重建后端也会丢失代理 | 在任务作用域包装 `scheme.init_game`, 每次初始化结束后安装, 退出恢复原入口; 模拟器和未启用时保持原流程 |
| P1 | `mouse_click_blank` 仍绑定原后端; 物理点击未确认游戏焦点, 失败的坐标转换也被当作有效坐标 | 接管空白点击; 校验 console 会话、游戏焦点、Win32 查询结果; 失败拒绝点击, 保留暂停和 `move_back` 参数 |
| P1 | 驱动按下后异常没有保证抬起; 代理抬起时坐标查询失败也会跳过释放 | 将释放置于 `finally`; 任务中断继续向上抛出 |
| P1 | 前台补丁把 pywin32 `AttachThreadInput` 成功返回的 `None` 转为 `False`, 导致未解除线程绑定 | 无异常即记录已绑定, 前台设置成功或失败都解除绑定 |
| P2 | `GetForegroundWindow()!=0` 被误当作 console 会话依据, RDP 内也可能存在前台窗口; 查询失败被当作加速关闭或坐标 `(0,0)` | 比较进程会话 ID 与活动 console ID; 显式检查查询返回值, 设置指针宽度正确的 API 类型; 使用独立 DLL 绑定避免影响其他库 |
| P2 | 点击/拖动的窗口设置、激活、按下前等待位于清理范围之外; 鼠标释放失败也能跳过位置恢复 | 共用覆盖完整操作的窗口作用域, 透明度和已取得的原位置分别保证恢复 |
| P2 | 截图自检只对窗口 DC 执行 BitBlt, 与提交说明声称的 PrintWindow 路径不符; 位图仍选在 DC 内时尝试删除 | 窗口自检调用 PrintWindow(flags=3), 按客户区大小创建位图, 恢复旧对象后释放 GDI 资源; 屏幕 BitBlt 作为后备 |
| P3 | 新增测试直接导入 pyautogui 和 ctypes.windll, 在 Linux 上 399 项中有 2 项报错 | 隔离平台接口, 补充真实 AALC 接线、任务入口、故障清理和采集 API 的回归测试 |
会话判断依据 Microsoft 的 [GetForegroundWindow 文档](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getforegroundwindow)
和 [WTSGetActiveConsoleSessionId 文档](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-wtsgetactiveconsolesessionid)。
线程绑定接口核对了 [pywin32 源码](https://github.com/mhammond/pywin32/blob/main/win32/src/win32process.i)
及 [接口文档](https://mhammond.github.io/pywin32/win32process__AttachThreadInput_meth.html)。
文件核查:`lc_mcp/driver_input.py`、`lc_mcp/aalc_patches.py`、`lc_mcp/aalc_task.py`
和 `tests/test_driver_input.py` 已存在于远程 `e2de126`。仓库没有 `logitech.driver.dll`、
罗技驱动安装包或注释提到的 `logitech.test.py`。README 已补充外部依赖、环境变量和接管范围。
驱动只接管任务流点击, 不将拖拽、滚动、键盘或独立 MCP `click` 工具改为驱动输入。
验证:Linux / Python 3.12 全套 **417 项通过**(16.832 秒);随后将 Win32 类型声明改为
独立 DLL 绑定, 驱动相关 **29 项回归通过**。`git diff --check` 通过。
测试从 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 审查记录。
+45 -38
View File
@@ -8,6 +8,7 @@ import glob
import os
import sys
import time
from contextlib import contextmanager
from .engine import Engine
@@ -228,28 +229,41 @@ class AalcEngine(Engine):
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
win32con.SWP_NOACTIVATE)
@contextmanager
def _background_target(self, x, y):
position = None
transparent = self.cfg.win_input_type == 'window_move'
try:
if transparent:
self.screen.handle.set_window_transparent(True)
position = self.auto.input_handler._set_window_pos(int(x), int(y))
self.auto.input_handler.set_active()
yield position
finally:
try:
if position is not None:
try:
time.sleep(0.12)
finally:
self._restore_background_position(position)
finally:
if transparent:
self.screen.handle.set_window_transparent(False)
def click(self, x, y, times=1):
self._prepare_input()
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con
handler = self.auto.input_handler
self.auto.wait_pause()
for _ in range(int(times)):
position = None
if self.cfg.win_input_type == 'window_move':
self.screen.handle.set_window_transparent(True)
position = handler._set_window_pos(int(x), int(y))
handler.set_active()
self._background_mouse(win32con.WM_MOUSEMOVE, x, y)
time.sleep(0.12)
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
try:
with self._background_target(x, y):
self._background_mouse(win32con.WM_MOUSEMOVE, x, y)
time.sleep(0.12)
finally:
self._background_mouse(win32con.WM_LBUTTONUP, x, y)
if position is not None:
time.sleep(0.12)
self._restore_background_position(position)
try:
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
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.
time.sleep(0.12)
elif not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
@@ -304,31 +318,24 @@ class AalcEngine(Engine):
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con
self.auto.wait_pause()
position = None
if self.cfg.win_input_type == 'window_move':
self.screen.handle.set_window_transparent(True)
position = self.auto.input_handler._set_window_pos(int(from_x), int(from_y))
self.auto.input_handler.set_active()
self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y)
time.sleep(0.12)
self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
last_x, last_y = from_x, from_y
try:
with self._background_target(from_x, from_y) as position:
self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y)
time.sleep(0.12)
steps = max(1, int(float(duration) / 0.02))
for step in range(1, steps + 1):
last_x = round(from_x + (to_x - from_x) * step / steps)
last_y = round(from_y + (to_y - from_y) * step / steps)
if position is not None:
self.auto.input_handler._set_window_pos(last_x, last_y)
self._background_mouse(win32con.WM_MOUSEMOVE, last_x, last_y, held=True)
time.sleep(float(duration) / steps)
time.sleep(0.12)
finally:
self._background_mouse(win32con.WM_LBUTTONUP, last_x, last_y)
if position is not None:
last_x, last_y = from_x, from_y
try:
self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
time.sleep(0.12)
self._restore_background_position(position)
steps = max(1, int(float(duration) / 0.02))
for step in range(1, steps + 1):
last_x = round(from_x + (to_x - from_x) * step / steps)
last_y = round(from_y + (to_y - from_y) * step / steps)
if position is not None:
self.auto.input_handler._set_window_pos(last_x, last_y)
self._background_mouse(win32con.WM_MOUSEMOVE, last_x, last_y, held=True)
time.sleep(float(duration) / steps)
time.sleep(0.12)
finally:
self._background_mouse(win32con.WM_LBUTTONUP, last_x, last_y)
return
if not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
import pyautogui
+211
View File
@@ -12,9 +12,11 @@
一次, 之后全部模板匹配分数掉到阈值以下, 表现为原地空转、不报错。这里在后台定期
检查客户区尺寸, 偏离 set_win_size 时调回去。
"""
import os
import re
import threading
import time
from contextlib import contextmanager
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
@@ -94,3 +96,212 @@ class WindowGuard(threading.Thread):
def stop(self):
self.stopped.set()
# ---------------------------------------------------------------- 驱动级点击接管
# 新版 AALC 的输入入口带交互门和锁, 重绑时必须保留这些包装。
REBIND_NAMES = ('mouse_click', 'mouse_click_blank', 'mouse_down', 'mouse_up')
class DriverClickProxy:
"""把鼠标点击转发到罗技驱动, 其余一律透传给原 handler。
⛔ 只接管**点击类**操作。拖拽/滑动/滚轮仍走 AALC 原逻辑 —— 那些在镜牢和日常
里用得少, 而各自的行为差异(惯性、多点)不好用相对位移复现, 接了反而更容易出错。
"""
def __init__(self, handler, driver, screen, log=print):
self._handler = handler
self._driver = driver
self._screen = screen
self.log = log
self.clicks = 0
self.refused = 0
# --- 透传 -------------------------------------------------------------
def __getattr__(self, name):
return getattr(self._handler, name)
# --- 接管 -------------------------------------------------------------
def _screen_pos(self, x, y):
from .driver_input import client_to_screen, foreground_window, is_console_session
handle = self._screen.handle
hwnd = handle.hwnd
if not hwnd or handle.isMinimized or not is_console_session():
raise OSError('驱动点击需要 console 会话中可见的游戏窗口')
if foreground_window() != hwnd:
handle.setForeground()
if foreground_window() != hwnd:
raise OSError('无法激活游戏窗口, 未发送驱动输入')
return client_to_screen(hwnd, x, y)
def _trace(self, msg):
"""排障用的文件追踪: 日志被 AALC 的 logger 吞掉时靠它看真实调用。"""
path = os.environ.get('LCP_DRIVER_TRACE')
if not path:
return
try:
with open(path, 'a', encoding='utf-8') as fh:
fh.write('%s %s\n' % (time.strftime('%H:%M:%S'), msg))
except OSError:
pass
def mouse_click(self, x, y, times=1, move_back=False):
from .driver_input import get_cursor
self._handler.wait_pause()
self._trace('mouse_click(%s,%s,times=%s)' % (x, y, times))
original_pos = None
try:
sx, sy = self._screen_pos(x, y)
if move_back:
original_pos = get_cursor()
if self._driver.click(sx, sy, times=times):
self.clicks += 1
self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy))
return True
except InterruptedError:
raise
except OSError as e:
self._trace('点击失败: %s' % e)
self.log('[driver] 点击失败: %s' % e)
finally:
if original_pos is not None:
self._driver.move_to(*original_pos)
self.refused += 1
self.log('[driver] 放弃点击客户区(%d,%d): 无法激活或精确定位' % (x, y))
return False
def mouse_click_blank(self, coordinate=(1, 1), times=1, move_back=False):
return self.mouse_click(*coordinate, times=times, move_back=move_back)
def mouse_down(self, x, y):
self._handler.wait_pause()
sx, sy = self._screen_pos(x, y)
if not self._driver.move_to(sx, sy):
return False
return self._driver.down(1) is not False
def mouse_up(self, x, y):
try:
sx, sy = self._screen_pos(x, y)
self._driver.move_to(sx, sy)
finally:
self._driver.up(1)
return True
def install_driver_click(auto, screen, driver=None, log=print):
"""如果环境满足, 把 AALC 的鼠标点击切到罗技驱动级输入。
返回驱动实例(成功) 或 None(条件不满足, AALC 保持原样)。
条件不满足时**不改任何东西** —— 宁可继续用原来的注入方式, 也不要半吊子接管。
"""
from .driver_input import DriverInput
if isinstance(auto.input_handler, DriverClickProxy):
return auto.input_handler._driver
drv = driver if driver is not None else DriverInput(log=log)
ok, why = drv.preflight()
if not ok:
log('[lc_mcp] 驱动级输入未启用: %s' % why)
return None
proxy = DriverClickProxy(auto.input_handler, drv, screen, log=log)
trace = os.environ.get('LCP_DRIVER_TRACE')
if trace:
try:
with open(trace, 'a', encoding='utf-8') as fh:
fh.write('%s install: 原 handler=%s -> proxy\n'
% (time.strftime('%H:%M:%S'), type(auto.input_handler).__name__))
fh.write('%s install: auto.mouse_click 原绑定=%r\n'
% (time.strftime('%H:%M:%S'), getattr(auto, 'mouse_click', None)))
except OSError:
pass
auto.input_handler = proxy
for name in REBIND_NAMES:
gate = getattr(auto, '_run_business_interaction', None)
setattr(auto, name, gate(name) if callable(gate) else getattr(proxy, name))
log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入')
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 任务和故障重启。"""
if cfg.simulator or os.environ.get('LCP_DRIVER_INPUT', '').strip() != '1':
yield
return
original = scheme.init_game
def init_game(*args, **kwargs):
result = original(*args, **kwargs)
install_driver_click(auto, screen, log=log)
return result
scheme.init_game = init_game
try:
yield
finally:
scheme.init_game = original
# ---------------------------------------------------------------- 前台窗口健壮化
def install_robust_set_foreground(screen, log=print):
"""把 SetForegroundWindow 换成带 AttachThreadInput 兜底的版本。
背景(2026-10-22): cfg.background_click=False 时 screen.py:342 会调
self.handle.setForeground(), 而原生实现只有一句裸调用
win32gui.SetForegroundWindow(hwnd)。Windows 不允许非前台进程抢占前台,
失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在
set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。
兜底尝试关联当前线程和前台线程的输入队列, 完成后解挂。
Windows 仍可能拒绝激活; 驱动输入在发送前另行检查游戏是否在前台。
"""
handle = getattr(screen, 'handle', None)
if handle is None or not hasattr(handle, 'setForeground'):
log('[lc_mcp] 前台窗口补丁跳过: screen.handle 没有 setForeground')
return None
original = handle.setForeground
def setForeground():
hwnd = getattr(handle, 'hwnd', 0)
if not hwnd:
return
try:
original()
return
except Exception:
pass # 落到下面的 AttachThreadInput 兜底
try:
import win32api
import win32gui
import win32process
foreground = win32gui.GetForegroundWindow()
thread_fg = win32process.GetWindowThreadProcessId(foreground)[0] if foreground else 0
thread_me = win32api.GetCurrentThreadId()
attached = False
if thread_fg and thread_fg != thread_me:
# pywin32 成功时返回 None, 失败抛异常, 不能按真假判断。
win32process.AttachThreadInput(thread_me, thread_fg, True)
attached = True
try:
win32gui.BringWindowToTop(hwnd)
win32gui.SetForegroundWindow(hwnd)
finally:
if attached:
win32process.AttachThreadInput(thread_me, thread_fg, False)
except Exception as e:
log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e))
handle.setForeground = setForeground
log('[lc_mcp] patch: SetForegroundWindow 加 AttachThreadInput 兜底')
return handle
+41 -37
View File
@@ -9,9 +9,10 @@ import json
import os
import sys
from . import preflight
from . import killswitch, preflight
from .aalc_engine import bootstrap
from .aalc_patches import WindowGuard, install_exact_team_match
from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match,
install_robust_set_foreground, stop_driver_click)
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = {
@@ -74,42 +75,45 @@ def run(task, params):
from tasks.battle import battle
from utils.path_manager import path_manager
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
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
install_exact_team_match(auto, log)
guard = WindowGuard(screen, cfg, log=log)
guard.start()
restore_path = os.environ.get(RESTORE_ENV)
originals = apply_overrides(cfg, task, params, restore_path)
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
finally:
guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
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
finally:
guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
def main(argv):
+246
View File
@@ -0,0 +1,246 @@
# -*- coding: utf-8 -*-
"""罗技驱动级输入(logitech.driver.dll)。
为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。
这个 DLL 通过罗技驱动的虚拟 HID 设备发事件。
⛔ 两个必须知道的前提(2026-10-22 实测):
1. **会话必须是物理 console**
RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动
(实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。
比较当前进程会话与 WTSGetActiveConsoleSessionId; 前台窗口句柄不能判定会话类型。
2. **必须关掉指针加速**
加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素),
当时的速度设置下关闭后比值为 1.0000。没关的话本模块会报警并拒绝定位,
而不是给出一个不准的位置。
接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`,
这是 logitech.test.py 里验证过的那几个。
"""
import ctypes
import os
import time
import threading
from ctypes import wintypes
from functools import lru_cache
# win32 SPI 常量
SPI_GETMOUSE = 0x0003
SPI_GETMOUSESPEED = 0x0070
DEFAULT_DLL = r'E:\罗技键鼠驱动\logitech.driver.dll'
class Cursor(ctypes.Structure):
_fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)]
@lru_cache(maxsize=None)
def _win_library(name):
# 使用独立绑定, 避免 argtypes 污染 AALC/pyautogui 共用的 ctypes.windll。
return ctypes.WinDLL(name, use_last_error=True)
def _api(library, name, result, args):
fn = getattr(_win_library(library), name)
fn.restype, fn.argtypes = result, args
return fn
def get_cursor():
c = Cursor()
fn = _api('user32', 'GetCursorPos', wintypes.BOOL, [ctypes.POINTER(Cursor)])
if not fn(ctypes.byref(c)):
raise OSError('GetCursorPos 失败')
return (c.x, c.y)
def foreground_window():
return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])()
def is_console_session():
current = wintypes.DWORD()
query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL,
[wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
if not query(os.getpid(), ctypes.byref(current)):
raise OSError('ProcessIdToSessionId 失败')
console = _api('kernel32', 'WTSGetActiveConsoleSessionId', wintypes.DWORD, [])()
return console != 0xFFFFFFFF and current.value == console
def has_foreground():
"""当前是否存在前台窗口; 激活切换时也可能短暂为 0。"""
return bool(foreground_window())
def acceleration_on():
"""指针加速是否开着。开着就别指望 counts 和像素成线性。"""
a = (ctypes.c_int * 3)()
fn = _api('user32', 'SystemParametersInfoA', wintypes.BOOL,
[wintypes.UINT, wintypes.UINT, ctypes.c_void_p, wintypes.UINT])
if not fn(SPI_GETMOUSE, 0, ctypes.byref(a), 0):
raise OSError('读取指针加速设置失败')
return bool(a[2])
def mouse_speed():
s = ctypes.c_int()
fn = _api('user32', 'SystemParametersInfoA', wintypes.BOOL,
[wintypes.UINT, wintypes.UINT, ctypes.c_void_p, wintypes.UINT])
if not fn(SPI_GETMOUSESPEED, 0, ctypes.byref(s), 0):
raise OSError('读取指针速度失败')
return s.value
class DriverInput:
"""罗技驱动级鼠标/键盘。
定位采用**闭环**: 发相对位移 -> 读回实际位置 -> 不够就再发, 直到误差 <= tol。
这样不依赖任何标定常数, 也能对抗偶发的坐标跳变。
"""
def __init__(self, dll_path=None, log=print):
self.dll_path = dll_path or os.environ.get('LCP_LOGITECH_DLL') or DEFAULT_DLL
self.log = log
self._dll = None
self._open = False
self._stopped = False
self._input_lock = threading.RLock()
self._pressed = set()
# ---------------------------------------------------------------- 生命周期
def open(self):
if self._open:
return True
if not os.path.exists(self.dll_path):
self.log('[driver] 找不到 %s' % self.dll_path)
return False
try:
self._dll = ctypes.CDLL(self.dll_path)
for name in ('device_open', 'moveR', 'mouse_down', 'mouse_up'):
getattr(self._dll, name)
ok = self._dll.device_open() == 1
except (OSError, AttributeError) as e:
self.log('[driver] 加载 DLL 失败: %s' % e)
self._dll = None
return False
self._open = bool(ok)
if not ok:
self.log('[driver] device_open() != 1, 罗技驱动未就绪')
return self._open
@property
def ready(self):
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):
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
if not self.open():
return False, '罗技驱动不可用(device_open 失败)'
try:
if not is_console_session():
return False, '当前进程不在物理 console 会话, 不启用驱动输入'
if not has_foreground():
return False, '当前会话没有前台窗口(GetForegroundWindow=0), 暂不启用驱动输入'
if acceleration_on():
return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— '
'关掉"提高指针精确度"后重试')
except (OSError, AttributeError) as e:
return False, '无法确认输入环境: %s' % e
return True, 'ok'
# ---------------------------------------------------------------- 移动
def move_relative(self, dx, dy):
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
def move_to(self, sx, sy, tol=1, iters=10, settle=0.03):
"""把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。"""
if not self.ready:
return False
for _ in range(iters):
cx, cy = get_cursor()
dx, dy = int(sx) - cx, int(sy) - cy
if abs(dx) <= tol and abs(dy) <= tol:
return True
if self.move_relative(dx, dy) is False:
return False
time.sleep(settle)
cx, cy = get_cursor()
return abs(int(sx) - cx) <= tol and abs(int(sy) - cy) <= tol
# ---------------------------------------------------------------- 按键
def down(self, button=1):
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):
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):
"""先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。"""
if not self.ready:
return False
if not self.move_to(sx, sy, tol=tol):
cx, cy = get_cursor()
self.log('[driver] 定位失败: 目标(%d,%d) 实际(%d,%d), 不点击'
% (sx, sy, cx, cy))
return False
for _ in range(int(times)):
try:
if not self.down(1):
return False
time.sleep(0.03)
finally:
self.up(1)
return not self._stopped
def key_down(self, key):
if self.ready:
self._dll.key_down(key)
def key_up(self, key):
if self.ready:
self._dll.key_up(key)
def scroll(self, amount):
if self.ready:
self._dll.scroll(int(amount))
def client_to_screen(hwnd, x, y):
"""游戏客户区坐标 -> 屏幕坐标。"""
if not hwnd:
raise OSError('没有游戏窗口句柄')
pt = wintypes.POINT(int(x), int(y))
fn = _api('user32', 'ClientToScreen', wintypes.BOOL,
[wintypes.HWND, ctypes.POINTER(wintypes.POINT)])
if not fn(hwnd, ctypes.byref(pt)):
raise OSError('ClientToScreen 失败, 未发送输入')
return (pt.x, pt.y)
+109
View File
@@ -0,0 +1,109 @@
# -*- coding: utf-8 -*-
"""全局急停热键。
为什么需要: 驱动级点击是闭环定位的 —— 手一动,下一次点击前会读到新位置、
算出偏差、再把你推回目标点。所以任务运行期间鼠标和人是"拔河"状态,用户没法
用鼠标去点停止按钮。键盘不受影响,所以用键盘热键做急停。
⛔ AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py)
里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。
默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。
按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 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 '').strip().lower() or DEFAULT_KEY
if name.startswith('<') and name.endswith('>'):
return name
return '<%s>' % name
def install(log=print, key=None, on_stop=None):
"""启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。
任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。
"""
key = key or os.environ.get('LCP_KILL_KEY') or DEFAULT_KEY
spec = _key_spec(key)
try:
from pynput import keyboard
except Exception as e: # pynput 缺失/无显示环境
log('[lc_mcp] 急停热键不可用(pynput 加载失败: %s: %s), 请用 Ctrl+Alt+Del 强制停止'
% (type(e).__name__, e))
return None
state = {'fired': False}
def on_activate():
if state['fired']:
return
state['fired'] = True
# 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:
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:
listener = keyboard.GlobalHotKeys({spec: on_activate})
listener.daemon = True
listener.start()
except Exception as e:
log('[lc_mcp] 急停热键注册失败(%s: %s), 请用 Ctrl+Alt+Del 强制停止'
% (type(e).__name__, e))
return None
log('[lc_mcp] 急停监听已启动: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
% key.upper())
listener._lc_state = state
return listener
def stop(listener):
"""停止监听(任务正常结束时调用, 免得线程残留)。"""
if listener is None:
return
try:
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
View File
@@ -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)))}
+9
View File
@@ -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 '')
+87 -12
View File
@@ -110,19 +110,94 @@ def ensure_server(timeout_s=90):
# ---------------------------------------------------------------- 桌面渲染
def _blit_ok(hdc, hwnd=None):
"""探测采集 API, 窗口走 AALC 的 PrintWindow(flags=3)。不验证画面内容。"""
if not hdc:
return False
import ctypes
from ctypes import wintypes
import win32gui
import win32ui
source = target = bitmap = old = bitmap_handle = None
try:
width, height = 64, 64
if hwnd:
left, top, right, bottom = win32gui.GetClientRect(hwnd)
width, height = right - left, bottom - top
if width <= 0 or height <= 0:
return False
source = win32ui.CreateDCFromHandle(hdc)
target = source.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(source, width, height)
bitmap_handle = bitmap.GetHandle()
old = target.SelectObject(bitmap)
if hwnd:
capture = ctypes.windll.user32.PrintWindow
capture.argtypes = [wintypes.HWND, wintypes.HDC, wintypes.UINT]
capture.restype = wintypes.BOOL
return bool(capture(hwnd, target.GetSafeHdc(), 3))
target.BitBlt((0, 0), (width, height), source, (0, 0), 0x00CC0020)
return True
except Exception:
return False
finally:
try:
if old is not None:
target.SelectObject(old)
finally:
try:
if target is not None:
target.DeleteDC()
finally:
if bitmap_handle is not None:
win32gui.DeleteObject(bitmap_handle)
# source 只包装调用者的 DC, 由调用者 ReleaseDC, 不能 DeleteDC。
def screen_blit_ok():
import win32gui
hdc = None
try:
hdc = win32gui.GetDC(0)
return _blit_ok(hdc)
except Exception:
return False
finally:
if hdc:
win32gui.ReleaseDC(0, hdc)
def window_blit_ok(hwnd):
import win32gui
hdc = None
try:
if win32gui.IsIconic(hwnd):
return False
hdc = win32gui.GetWindowDC(hwnd)
return _blit_ok(hdc, hwnd=hwnd)
except Exception:
return False
finally:
if hdc:
win32gui.ReleaseDC(hwnd, hdc)
def render_ok():
"""桌面是否在出图(BitBlt 能否成功)。"""
from ctypes import windll
u, g = windll.user32, windll.gdi32
hdc = u.GetDC(0)
mem = g.CreateCompatibleDC(hdc)
bmp = g.CreateCompatibleBitmap(hdc, 64, 64)
g.SelectObject(mem, bmp)
r = g.BitBlt(mem, 0, 0, 64, 64, hdc, 0, 0, 0x00CC0020)
g.DeleteObject(bmp)
g.DeleteDC(mem)
u.ReleaseDC(0, hdc)
return bool(r)
"""游戏画面是否可采集。
⛔ 原来只测屏幕 BitBlt(GetDC(0))。2026-10-22 实测它在 RDP 会话下会瞬时失败,
而 AALC 走的是 background_screenshot(窗口 DC + PrintWindow), 那条路照样能截到图
—— 结果是我的自检把本来能干活的轮次判成"截不到图"给跳过了(10-17 02:23 就这样
白丢过一轮)。
现在优先按 AALC 的方式测**窗口**能否采集, 窗口不在或不可采时才回退到屏幕。
"""
hwnd = _find_hwnd()
if hwnd and window_blit_ok(hwnd):
return True
return screen_blit_ok()
def parse_session_table(text):
+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 -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
+4 -3
View File
@@ -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。
+36 -1
View File
@@ -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'):
+19
View File
@@ -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
+29
View File
@@ -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)
+103 -1
View File
@@ -48,7 +48,109 @@ class BackgroundRestoreTest(unittest.TestCase):
engine.click(100, 200)
engine._restore_background_position.assert_called_once_with((20, 30))
engine.auto.input_handler.set_mouse_pos.assert_not_called()
engine.screen.handle.set_window_transparent.assert_called_once_with(True)
def test_click_restores_transparency_within_the_same_click(self):
"""⛔ 透明度必须在本次点击内还原, 不能留给下一次截图。
以前只在 background_screenshot 里恢复, 于是"点击 -> 截图 -> 点击 -> 截图"
的高频交替会让游戏窗口在不可见/可见之间反复切换 —— 肉眼看就是画面一直抽搐。
AALC 自己的 WindowMoveInput.mouse_click 根本不碰透明度, 所以它只"跳一下"。
"""
engine = AalcEngine.__new__(AalcEngine)
engine.cfg = SimpleNamespace(simulator=False, win_input_type='window_move')
engine.auto = mock.Mock()
engine.screen = mock.Mock()
engine.auto.input_handler._set_window_pos.return_value = (20, 30)
engine._background_mouse = mock.Mock()
engine._restore_background_position = mock.Mock()
engine._prepare_input = mock.Mock()
constants = SimpleNamespace(WM_MOUSEMOVE=512, WM_LBUTTONDOWN=513, WM_LBUTTONUP=514)
with mock.patch.dict(sys.modules, win32con=constants), \
mock.patch('lc_mcp.aalc_engine.time.sleep'):
engine.click(100, 200)
calls = [c.args[0] for c in engine.screen.handle.set_window_transparent.call_args_list]
self.assertEqual(calls, [True, False], '应当先设透明再立刻还原, 实际: %s' % calls)
def test_click_leaves_no_transparency_when_it_raises(self):
"""中途抛异常也必须把透明度还原, 否则窗口会一直隐形。"""
engine = AalcEngine.__new__(AalcEngine)
engine.cfg = SimpleNamespace(simulator=False, win_input_type='window_move')
engine.auto = mock.Mock()
engine.screen = mock.Mock()
engine.auto.input_handler._set_window_pos.return_value = (20, 30)
engine._background_mouse = mock.Mock()
engine._restore_background_position = mock.Mock()
engine._prepare_input = mock.Mock()
constants = SimpleNamespace(WM_MOUSEMOVE=512, WM_LBUTTONDOWN=513, WM_LBUTTONUP=514)
# 第二次 sleep 时抛错 —— 那一步在按下之后的 try 里, finally 必须照常还原
calls = {'n': 0}
def sleep_then_fail(_):
calls['n'] += 1
if calls['n'] >= 2:
raise RuntimeError('stopped')
with mock.patch.dict(sys.modules, win32con=constants), \
mock.patch('lc_mcp.aalc_engine.time.sleep', sleep_then_fail):
with self.assertRaises(RuntimeError):
engine.click(100, 200)
seen = [c.args[0] for c in engine.screen.handle.set_window_transparent.call_args_list]
self.assertIn(True, seen, '点击前应当设过透明')
self.assertEqual(seen[-1], False, '异常路径也要还原透明度, 实际: %s' % seen)
def test_foreground_mode_never_touches_transparency(self):
"""前台模式不需要搬窗口, 也就不该动透明度。"""
engine = AalcEngine.__new__(AalcEngine)
engine.cfg = SimpleNamespace(simulator=False, win_input_type='foreground')
engine.auto = mock.Mock()
engine.screen = mock.Mock()
engine.auto.input_handler.pos_offset.return_value = (100, 200)
engine._prepare_input = mock.Mock()
with mock.patch.dict(sys.modules, pyautogui=mock.Mock()), \
mock.patch('lc_mcp.aalc_engine.time.sleep'):
engine.click(100, 200)
engine.screen.handle.set_window_transparent.assert_not_called()
def test_window_cleanup_covers_setup_release_and_restore_failures(self):
constants = SimpleNamespace(WM_MOUSEMOVE=512, WM_LBUTTONDOWN=513, WM_LBUTTONUP=514)
for action in ('click', 'drag'):
for stage in ('move_window', 'activate', 'move_message', 'pre_press_sleep',
'release', 'restore'):
with self.subTest(action=action, stage=stage):
engine = AalcEngine.__new__(AalcEngine)
engine.cfg = SimpleNamespace(simulator=False, win_input_type='window_move')
engine.auto, engine.screen = mock.Mock(), mock.Mock()
engine.auto.input_handler._set_window_pos.return_value = (20, 30)
engine._grab = mock.Mock(return_value=SimpleNamespace(width=800, height=600))
engine._background_mouse = mock.Mock()
engine._restore_background_position = mock.Mock()
failure = RuntimeError(stage)
if stage == 'move_window':
engine.auto.input_handler._set_window_pos.side_effect = failure
elif stage == 'activate':
engine.auto.input_handler.set_active.side_effect = failure
elif stage == 'restore':
engine._restore_background_position.side_effect = failure
elif stage in ('move_message', 'release'):
message = 512 if stage == 'move_message' else 514
def send(kind, *args, **kwargs):
if kind == message:
raise failure
engine._background_mouse.side_effect = send
with mock.patch.dict(sys.modules, win32con=constants), \
mock.patch('lc_mcp.aalc_engine.time.sleep') as sleep:
if stage == 'pre_press_sleep':
sleep.side_effect = failure
with self.assertRaises(RuntimeError):
if action == 'click':
engine.click(100, 200)
else:
engine.drag(100, 100, 100, 300)
self.assertEqual(engine.screen.handle.set_window_transparent.call_args_list,
[mock.call(True), mock.call(False)])
if stage != 'move_window':
engine._restore_background_position.assert_called_once_with((20, 30))
def test_restore_uses_noactivate_and_preserves_foreground(self):
gui = mock.Mock()
+16
View File
@@ -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': []}
+81
View File
@@ -669,6 +669,87 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
self.assertEqual(code, 0)
class RenderCheckTest(QuietLogMixin, unittest.TestCase):
"""⛔ render_ok() 必须测 AALC 真正走的那条采集路径。
原来只测屏幕 BitBlt(GetDC(0))。2026-10-22 实测它在 RDP 会话下会瞬时失败, 而
AALC 走的是 background_screenshot(窗口 DC + PrintWindow), 那条路照样能截到图 ——
结果是我的自检把本来能干活的轮次判成"截不到图"跳过了。
"""
def test_window_capture_alone_is_enough(self):
"""窗口能采到就算能干活 —— 不该再去看屏幕那一路。"""
with mock.patch.object(cm, '_find_hwnd', lambda: 123), \
mock.patch.object(cm, 'window_blit_ok', lambda hwnd: True), \
mock.patch.object(cm, 'screen_blit_ok',
lambda: self.fail('窗口能采就不该再测屏幕')):
self.assertTrue(cm.render_ok())
def test_falls_back_to_screen_when_window_is_missing(self):
with mock.patch.object(cm, '_find_hwnd', lambda: 0), \
mock.patch.object(cm, 'screen_blit_ok', lambda: True):
self.assertTrue(cm.render_ok())
def test_falls_back_to_screen_when_window_blit_fails(self):
with mock.patch.object(cm, '_find_hwnd', lambda: 123), \
mock.patch.object(cm, 'window_blit_ok', lambda hwnd: False), \
mock.patch.object(cm, 'screen_blit_ok', lambda: True):
self.assertTrue(cm.render_ok())
def test_reports_false_only_when_both_paths_fail(self):
with mock.patch.object(cm, '_find_hwnd', lambda: 123), \
mock.patch.object(cm, 'window_blit_ok', lambda hwnd: False), \
mock.patch.object(cm, 'screen_blit_ok', lambda: False):
self.assertFalse(cm.render_ok())
class CaptureApiTest(QuietLogMixin, unittest.TestCase):
def test_window_capture_uses_printwindow_and_releases_gdi_objects(self):
import ctypes
for outcome in (1, 0, OSError('capture failed')):
with self.subTest(outcome=outcome):
api, gui, ui = mock.Mock(), mock.Mock(), mock.Mock()
gui.GetClientRect.return_value = (0, 0, 1280, 720)
gui.IsIconic.return_value = False
source = ui.CreateDCFromHandle.return_value
target = source.CreateCompatibleDC.return_value
bitmap = ui.CreateBitmap.return_value
previous = target.SelectObject.return_value
if isinstance(outcome, Exception):
api.user32.PrintWindow.side_effect = outcome
else:
api.user32.PrintWindow.return_value = outcome
with mock.patch.dict(sys.modules, win32gui=gui, win32ui=ui), \
mock.patch.object(ctypes, 'windll', api, create=True):
self.assertEqual(cm.window_blit_ok(123), outcome == 1)
api.user32.PrintWindow.assert_called_once_with(123, target.GetSafeHdc(), 3)
target.BitBlt.assert_not_called()
bitmap.CreateCompatibleBitmap.assert_called_once_with(source, 1280, 720)
self.assertEqual(target.SelectObject.call_args_list,
[mock.call(bitmap), mock.call(previous)])
target.DeleteDC.assert_called_once()
gui.DeleteObject.assert_called_once_with(bitmap.GetHandle())
source.DeleteDC.assert_not_called()
gui.ReleaseDC.assert_called_once_with(123, gui.GetWindowDC())
def test_missing_dc_and_minimized_window_cannot_pass_capture(self):
gui = mock.Mock()
gui.IsIconic.return_value = True
with mock.patch.dict(sys.modules, win32gui=gui):
self.assertFalse(cm.window_blit_ok(123))
gui.GetWindowDC.assert_not_called()
self.assertFalse(cm._blit_ok(0))
def test_screen_fallback_uses_bitblt(self):
gui, ui = mock.Mock(), mock.Mock()
source = ui.CreateDCFromHandle.return_value
target = source.CreateCompatibleDC.return_value
with mock.patch.dict(sys.modules, win32gui=gui, win32ui=ui):
self.assertTrue(cm.screen_blit_ok())
target.BitBlt.assert_called_once_with((0, 0), (64, 64), source, (0, 0), 0x00CC0020)
gui.ReleaseDC.assert_called_once_with(0, gui.GetDC())
class SessionTableTest(QuietLogMixin, unittest.TestCase):
"""解析 `query session` —— 用来区分"截不到图"到底是哪种情况。
+459
View File
@@ -0,0 +1,459 @@
# -*- coding: utf-8 -*-
"""驱动级输入接管。
⛔ 这个模块的每一条"拒绝"都比"接管"更重要: 接管错了会让任务点错地方,
而拒绝只是继续用原来的注入方式。所以测试重点放在 preflight 的各种拒绝条件上。
背景(2026-10-22 实测):
* RDP 独立会话不能靠前台窗口判定, 必须核对进程与 console 会话 ID。
* 指针加速开着时 counts 和像素不成比例(+100/+200/+400 -> -45/-3/-3 像素),
关掉后严格 1:1。所以加速没关时不该给出"差不多"的位置。
"""
import sys
import os
import ast
import inspect
import threading
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from lc_mcp import driver_input as di # noqa: E402
from lc_mcp import aalc_patches as ap # noqa: E402
class PreflightTest(unittest.TestCase):
"""能不能用, 必须说得清楚; 不能用时一条都不能含糊。"""
def _drv(self, dll_ok=True, fg=True, accel=False, console=True):
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = dll_ok
with mock.patch.object(di, 'has_foreground', lambda: fg), \
mock.patch.object(di, 'is_console_session', lambda: console), \
mock.patch.object(di, 'acceleration_on', lambda: accel):
return d.preflight()
def test_ok_when_everything_is_right(self):
ok, why = self._drv()
self.assertTrue(ok)
self.assertEqual(why, 'ok')
def test_refuses_without_driver(self):
ok, why = self._drv(dll_ok=False)
self.assertFalse(ok)
self.assertIn('device_open', why)
def test_refuses_in_a_session_without_foreground(self):
"""RDP 独立会话的典型特征 —— 这种会话里驱动级输入无效。"""
ok, why = self._drv(fg=False)
self.assertFalse(ok)
self.assertIn('前台窗口', why)
def test_remote_session_is_rejected_even_with_foreground(self):
ok, why = self._drv(console=False, fg=True)
self.assertFalse(ok)
self.assertIn('console', why)
def test_refuses_when_acceleration_is_on(self):
ok, why = self._drv(accel=True)
self.assertFalse(ok)
self.assertIn('加速', why)
def test_refuses_missing_dll_file(self):
d = di.DriverInput(dll_path=r'Z:\nope\nope.dll', log=lambda m: None)
self.assertFalse(d.open())
self.assertFalse(d.ready)
class MoveToTest(unittest.TestCase):
"""定位必须是闭环: 发位移 -> 读回 -> 不够再发。不依赖标定常数。"""
def test_converges_when_moves_are_exact(self):
pos = {'v': (0, 0)}
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
def moveR(dx, dy, _):
pos['v'] = (pos['v'][0] + dx, pos['v'][1] + dy)
d._dll.moveR.side_effect = moveR
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertTrue(d.move_to(300, 200))
self.assertEqual(pos['v'], (300, 200))
def test_gives_up_when_moves_do_nothing(self):
"""驱动不理人时不能假称到位 —— 那样会点错地方。"""
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.move_to(300, 200, iters=4))
def test_tolerance_is_respected(self):
"""已经在容差内就不该再发位移 —— 白折腾还容易引入抖动。"""
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
with mock.patch.object(di, 'get_cursor', lambda: (100, 100)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertTrue(d.move_to(101, 101, tol=1))
self.assertEqual(d._dll.moveR.call_count, 0, '容差内不该发位移')
def test_out_of_tolerance_does_move(self):
"""超出容差就必须尝试移动, 只是驱动不动时要如实返回失败。"""
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
with mock.patch.object(di, 'get_cursor', lambda: (100, 100)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.move_to(105, 105, tol=1, iters=3))
self.assertGreater(d._dll.moveR.call_count, 0)
class ClickTest(unittest.TestCase):
"""没到位置就绝不点。"""
def _drv(self, reachable):
d = di.DriverInput(dll_path='X.dll', log=lambda m: None)
d._dll = mock.Mock()
d._open = True
return d
def test_clicks_only_after_positioning(self):
pos = {'v': (0, 0)}
d = self._drv(True)
d._dll.moveR.side_effect = lambda dx, dy, _: pos.update(
{'v': (pos['v'][0] + dx, pos['v'][1] + dy)})
with mock.patch.object(di, 'get_cursor', lambda: pos['v']), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertTrue(d.click(500, 400))
self.assertEqual(pos['v'], (500, 400))
d._dll.mouse_down.assert_called_once_with(1)
d._dll.mouse_up.assert_called_once_with(1)
def test_never_clicks_when_positioning_fails(self):
d = self._drv(False)
with mock.patch.object(di, 'get_cursor', lambda: (0, 0)), \
mock.patch.object(di.time, 'sleep', lambda s: None):
self.assertFalse(d.click(500, 400))
d._dll.mouse_down.assert_not_called()
d._dll.mouse_up.assert_not_called()
class InstallTest(unittest.TestCase):
"""接管 AALC 的点击: 条件不满足时**一个都不许改**。"""
def _auto(self):
auto = SimpleNamespace()
auto.input_handler = mock.Mock()
auto.mouse_click = auto.input_handler.mouse_click
return auto
def test_refuses_quietly_when_preflight_fails(self):
auto = self._auto()
before = auto.input_handler
drv = mock.Mock()
drv.preflight.return_value = (False, '不是物理会话')
got = ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda m: None)
self.assertIsNone(got)
self.assertIs(auto.input_handler, before, '条件不满足就不该换 handler')
def test_rebinds_the_aliases_captured_at_init(self):
"""automation.py 初始化时把方法绑成了别名, 光换 handler 影响不到那些别名。"""
auto = self._auto()
old_click = auto.mouse_click
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
got = ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda m: None)
self.assertIs(got, drv)
self.assertIsNot(auto.mouse_click, old_click, '别名必须重绑')
def test_proxy_other_methods_fall_through(self):
"""拖拽/滑动/滚轮等仍走 AALC 原逻辑, 不能被吞掉。"""
handler = mock.Mock()
proxy = ap.DriverClickProxy(handler, mock.Mock(), mock.Mock(), log=lambda m: None)
proxy.mouse_drag(10, 20, 0.5, 0, 100, True)
handler.mouse_drag.assert_called_once()
proxy.wait_pause()
handler.wait_pause.assert_called_once()
class ClientToScreenTest(unittest.TestCase):
def test_uses_client_to_screen(self):
def fake(hwnd, byref_pt):
ptr = byref_pt._obj
ptr.x, ptr.y = ptr.x + 100, ptr.y + 50
return 1
api = mock.Mock()
api.user32.ClientToScreen.side_effect = fake
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
self.assertEqual(di.client_to_screen(123, 7, 9), (107, 59))
def vendor_auto():
"""执行 vendor 的真实接线与交互门方法, 只隔离 Windows 输入后端。"""
root = Path(__file__).resolve().parents[1] / 'vendor/aalc/module/automation'
abstract = ast.parse((root / 'input_handlers/__init__.py').read_text())
abstract.body = [n for n in abstract.body if isinstance(n, ast.ClassDef)]
namespace = {'log': mock.Mock(), 'sleep': lambda _: None, 'time': lambda: 0}
exec(compile(abstract, str(root / 'input_handlers/__init__.py'), 'exec'), namespace)
base = namespace['AbstractInput']
class Handler(base):
def mouse_click(self, *args, **kwargs):
raise AssertionError('旧点击后端不应被调用')
def mouse_click_blank(self, *args, **kwargs):
raise AssertionError('空白点击不应回落到旧后端')
source = ast.parse((root / 'automation.py').read_text())
cls = next(n for n in source.body if isinstance(n, ast.ClassDef) and n.name == 'Automation')
keep = {'init_input', '_run_business_interaction', 'monitor_mouse_click',
'suspend_interactions', 'resume_interactions'}
cls.body = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in keep]
cls.keywords = []
namespace = {'__name__': 'module.automation.automation', '__package__': 'module.automation',
'inspect': inspect, 'AbstractInput': base, 'log': mock.Mock(),
'cfg': SimpleNamespace(simulator=False, win_input_type='foreground',
memory_protection=False), 'GATE_WAIT_TIMEOUT': 30}
exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'automation.py'), 'exec'), namespace)
auto = namespace['Automation']()
auto.input_handler = None
auto._input_lock = threading.RLock()
auto._interaction_gate = threading.Event()
auto._interaction_gate.set()
with mock.patch.dict(sys.modules, {'module.automation.input_handlers.input':
SimpleNamespace(Input=Handler)}):
auto.init_input()
return auto, Handler
class DriverWiringTest(unittest.TestCase):
def test_real_business_gate_and_monitor_share_the_input_lock(self):
auto, _ = vendor_auto()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
locked = []
drv.click.side_effect = lambda *a, **k: locked.append(auto._input_lock._is_owned()) or True
ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda _: None)
auto.suspend_interactions()
entered = threading.Event()
wait = auto._interaction_gate.wait
def waiting(*args, **kwargs):
entered.set()
return wait(*args, **kwargs)
with mock.patch.object(auto.input_handler, '_screen_pos', return_value=(10, 20)), \
mock.patch.object(auto._interaction_gate, 'wait', side_effect=waiting):
worker = threading.Thread(target=auto.mouse_click, args=(10, 20), daemon=True)
worker.start()
try:
self.assertTrue(entered.wait(1), '业务点击必须等待交互门')
drv.click.assert_not_called()
# 监控点击允许绕过门, 但仍必须持有同一把锁。
auto.monitor_mouse_click(10, 20)
finally:
auto.resume_interactions()
worker.join(2)
self.assertFalse(worker.is_alive())
self.assertEqual(locked, [True, True])
def test_blank_click_uses_driver_and_move_back_is_honored(self):
auto, _ = vendor_auto()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
ap.install_driver_click(auto, mock.Mock(), driver=drv, log=lambda _: None)
with mock.patch.object(auto.input_handler, '_screen_pos', return_value=(10, 20)), \
mock.patch.object(di, 'get_cursor', return_value=(90, 80)):
self.assertTrue(auto.mouse_click_blank((1, 2), times=2, move_back=True))
drv.click.assert_called_once_with(10, 20, times=2)
drv.move_to.assert_called_once_with(90, 80)
def test_all_task_and_reinitialization_reinstall_after_init(self):
auto, handler_type = vendor_auto()
scheme = SimpleNamespace(init_game=auto.init_input)
scheme.script_task = lambda: (scheme.init_game(), auto.mouse_click_blank())
original = scheme.init_game
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
with mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1'), \
mock.patch.dict(sys.modules, {'module.automation.input_handlers.input':
SimpleNamespace(Input=handler_type)}), \
mock.patch.object(di, 'DriverInput', return_value=drv), \
mock.patch.object(ap.DriverClickProxy, '_screen_pos', return_value=(10, 20)):
with ap.driver_click_tasks(scheme, auto, mock.Mock(),
SimpleNamespace(simulator=False), log=lambda _: None):
scheme.script_task()
first = auto.input_handler
scheme.script_task()
self.assertIsNot(auto.input_handler, first)
self.assertIsInstance(auto.input_handler, ap.DriverClickProxy)
self.assertEqual(drv.click.call_count, 2)
self.assertIs(scheme.init_game, original)
def test_actual_task_entry_enables_driver_for_all_and_daily(self):
from lc_mcp import aalc_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)
cfg = SimpleNamespace(simulator=False)
scheme = SimpleNamespace(init_game=auto.init_input)
scheme.script_task = lambda: (scheme.init_game(), auto.mouse_click(10, 20))
scheme.Daily_task_wrapper = lambda **kw: lambda: auto.mouse_click(10, 20)
scheme.to_get_reward = scheme.Buy_enkephalin = scheme.Mirror_task = mock.Mock()
drv = mock.Mock()
drv.preflight.return_value = (True, 'ok')
modules = {
'module.automation': SimpleNamespace(auto=auto),
'module.automation.input_handlers.input': SimpleNamespace(Input=handler_type),
'module.config': SimpleNamespace(cfg=cfg),
'module.game_and_screen': SimpleNamespace(screen=mock.Mock()),
'tasks.base': SimpleNamespace(script_task_scheme=scheme),
'tasks.base.retry_monitor': SimpleNamespace(retry_monitor=mock.Mock()),
'tasks.battle': SimpleNamespace(battle=mock.Mock()),
'utils.path_manager': SimpleNamespace(path_manager=mock.Mock()),
}
with mock.patch.dict(sys.modules, modules), \
mock.patch.dict(os.environ, LCP_DRIVER_INPUT='1', LCP_RESTORE_FILE=''), \
mock.patch.object(aalc_task, 'bootstrap'), \
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=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, {}), 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)]:
with self.subTest(enabled=enabled, simulator=simulator):
scheme = SimpleNamespace(init_game=mock.Mock())
original = scheme.init_game
with mock.patch.dict(os.environ, LCP_DRIVER_INPUT=enabled):
with ap.driver_click_tasks(scheme, mock.Mock(), mock.Mock(),
SimpleNamespace(simulator=simulator)):
self.assertIs(scheme.init_game, original)
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()
with mock.patch.object(drv, 'move_to', return_value=True), \
mock.patch.object(di.time, 'sleep', side_effect=InterruptedError):
with self.assertRaises(InterruptedError):
drv.click(1, 2)
drv._dll.mouse_up.assert_called_once_with(1)
def test_release_even_if_coordinate_lookup_fails(self):
drv = mock.Mock()
proxy = ap.DriverClickProxy(mock.Mock(), drv, mock.Mock())
with mock.patch.object(proxy, '_screen_pos', side_effect=OSError('closed')):
with self.assertRaises(OSError):
proxy.mouse_up(1, 2)
drv.up.assert_called_once_with(1)
def test_no_physical_click_if_game_cannot_get_foreground(self):
drv = mock.Mock()
handle = SimpleNamespace(hwnd=123, isMinimized=False, setForeground=mock.Mock())
proxy = ap.DriverClickProxy(mock.Mock(), drv, SimpleNamespace(handle=handle), log=lambda _: None)
with mock.patch.object(di, 'is_console_session', return_value=True), \
mock.patch.object(di, 'foreground_window', return_value=999):
self.assertFalse(proxy.mouse_click(1, 2))
drv.click.assert_not_called()
handle.setForeground.assert_called_once()
def test_failed_windows_reads_do_not_become_zero_coordinates(self):
api = mock.Mock()
api.user32.ClientToScreen.return_value = 0
api.user32.GetCursorPos.return_value = 0
api.user32.SystemParametersInfoA.return_value = 0
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
for fn, args in [(di.client_to_screen, (123, 1, 2)), (di.get_cursor, ()),
(di.acceleration_on, ())]:
with self.subTest(function=fn.__name__), self.assertRaises(OSError):
fn(*args)
def test_failed_environment_query_refuses_installation(self):
drv = di.DriverInput()
drv._open, drv._dll = True, mock.Mock()
with mock.patch.object(di, 'is_console_session', side_effect=OSError('session query failed')):
ok, reason = drv.preflight()
self.assertFalse(ok)
self.assertIn('session query failed', reason)
def test_dll_without_mouse_exports_is_rejected(self):
drv = di.DriverInput()
with mock.patch.object(di.os.path, 'exists', return_value=True), \
mock.patch.object(di.ctypes, 'CDLL', return_value=SimpleNamespace(device_open=lambda: 1)):
self.assertFalse(drv.open())
self.assertFalse(drv.ready)
def test_console_session_ids_are_compared(self):
api = mock.Mock()
def query(pid, sid):
sid._obj.value = 2
return 1
api.kernel32.ProcessIdToSessionId.side_effect = query
with mock.patch.object(di, '_win_library', side_effect=lambda name: getattr(api, name)):
for console, expected in [(2, True), (3, False), (0xFFFFFFFF, False)]:
api.kernel32.WTSGetActiveConsoleSessionId.return_value = console
self.assertEqual(di.is_console_session(), expected)
class ForegroundFallbackTest(unittest.TestCase):
def test_none_on_success_still_detaches_after_success_or_failure(self):
for failed in (False, True):
with self.subTest(failed=failed):
handle = SimpleNamespace(hwnd=123, setForeground=mock.Mock(side_effect=OSError))
gui = mock.Mock()
gui.GetForegroundWindow.return_value = 456
gui.SetForegroundWindow.side_effect = OSError if failed else None
process = mock.Mock()
process.GetWindowThreadProcessId.return_value = (11, 22)
process.AttachThreadInput.return_value = None
api = SimpleNamespace(GetCurrentThreadId=lambda: 33)
with mock.patch.dict(sys.modules, win32api=api, win32gui=gui, win32process=process):
ap.install_robust_set_foreground(SimpleNamespace(handle=handle), log=lambda _: None)
handle.setForeground()
self.assertEqual(process.AttachThreadInput.call_args_list,
[mock.call(33, 11, True), mock.call(33, 11, False)])
if __name__ == '__main__':
unittest.main()
+8
View File
@@ -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':'预计成功率极高'},
+195
View File
@@ -0,0 +1,195 @@
# -*- coding: utf-8 -*-
"""急停热键。
背景(2026-10-22, 用户提问"你执行脚本的时候我鼠标没法动,我怎么停止呢"):
驱动级点击是闭环定位 —— 手一动, 下一次点击前会读到新位置、算出偏差、再把你推回
目标点。所以任务跑起来时鼠标是"拔河"状态, 用户没法用鼠标去点停止按钮。键盘不受
影响, 所以急停必须走键盘。
AALC 自带的 pause_hotkey 帮不上忙: 那个配置项只在 GUI(app/farming_interface.py)
里注册, lc_mcp 走命令行子进程, 那条路径上没有热键监听。这是本模块存在的原因。
"""
import os
import sys
import threading
import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from lc_mcp import killswitch # noqa: E402
class KeySpecTest(unittest.TestCase):
def test_wraps_plain_name(self):
self.assertEqual(killswitch._key_spec('f12'), '<f12>')
def test_keeps_already_wrapped(self):
self.assertEqual(killswitch._key_spec('<f11>'), '<f11>')
def test_lowercases_and_trims(self):
self.assertEqual(killswitch._key_spec(' F12 '), '<f12>')
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):
"""装不上不能把任务带崩,但必须说清楚怎么应急。"""
def test_reports_when_pynput_is_missing(self):
lines = []
with mock.patch.dict(sys.modules, {'pynput': None}):
got = killswitch.install(log=lines.append, key='f12')
self.assertIsNone(got)
joined = '\n'.join(lines)
self.assertIn('急停热键不可用', joined)
self.assertIn('Ctrl+Alt+Del', joined, '必须给出应急手段')
def test_registers_the_configured_key(self):
listener = mock.Mock()
listener.daemon = False
fake_keyboard = mock.Mock()
fake_keyboard.GlobalHotKeys.return_value = listener
with mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
'pynput.keyboard': fake_keyboard}):
got = killswitch.install(log=lambda m: None, key='f11')
self.assertIs(got, listener)
fake_keyboard.GlobalHotKeys.assert_called_once()
self.assertIn('<f11>', fake_keyboard.GlobalHotKeys.call_args[0][0])
listener.start.assert_called_once()
self.assertTrue(listener.daemon)
def test_env_var_overrides_default_key(self):
listener = mock.Mock()
fake_keyboard = mock.Mock()
fake_keyboard.GlobalHotKeys.return_value = listener
with mock.patch.dict(os.environ, {'LCP_KILL_KEY': 'pause'}), \
mock.patch.dict(sys.modules, {'pynput': mock.Mock(keyboard=fake_keyboard),
'pynput.keyboard': fake_keyboard}):
killswitch.install(log=lambda m: None)
self.assertIn('<pause>', fake_keyboard.GlobalHotKeys.call_args[0][0])
class ActivateTest(unittest.TestCase):
def _grab_handler(self, log=lambda _: None, on_stop=None):
listener = mock.Mock()
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 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_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:
self.fire(handler, listener)
fake_exit.assert_called_once_with(130)
log.assert_not_called()
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 = []
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):
def test_stop_is_safe_on_none(self):
killswitch.stop(None) # 不该抛
def test_stop_calls_listener(self):
listener = mock.Mock()
killswitch.stop(listener)
listener.stop.assert_called_once()
def test_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')
killswitch.stop(listener) # 不该抛
if __name__ == '__main__':
unittest.main()
+35
View File
@@ -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}