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
yws e1ebb09648 复核 DSH 合入代码并修复早期任务错误漏报 2026-10-22 01:17:52 +00:00
yws 625fdcd250 修复运行日志复核发现的任务控制与结果误判 2026-10-22 00:55:35 +00:00
yws 4e5d63ac6c 更新 AALC 上游至 e1d1749 2026-10-22 00:47:53 +00:00
29 changed files with 2305 additions and 204 deletions
+38 -2
View File
@@ -72,6 +72,40 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p
部分 Unity 界面仍读取系统指针位置,实测标题页按钮需使用 `window_move`。 部分 Unity 界面仍读取系统指针位置,实测标题页按钮需使用 `window_move`。
战斗按键有按下/释放间隔;隐藏启动后可用 `show_game_background` 恢复渲染。 战斗按键有按下/释放间隔;隐藏启动后可用 `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` 子进程,不覆盖独立运行的合成、升级脚本。
## 工具 ## 工具
| 工具 | 说明 | | 工具 | 说明 |
@@ -95,7 +129,8 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p
`state` 只反映任务子进程的退出码。AALC 在单次战斗失败(例如日志里的 `state` 只反映任务子进程的退出码。AALC 在单次战斗失败(例如日志里的
`超出最大尝试次数,未能进入战斗`)后仍会继续跑完并正常退出,所以 `task_status` `超出最大尝试次数,未能进入战斗`)后仍会继续跑完并正常退出,所以 `task_status`
会把日志尾部的 `[ERROR]`/异常行放进 `errors` 字段:**看到 `succeeded` 也要先看 `errors`。** 会扫描整份任务日志,把最后 3 条 `[ERROR]`/异常行放进 `errors` 字段:
**看到 `succeeded` 也要先看 `errors`。** 任务退出后的首次查询会缓存扫描结果,后续查询不再扫描日志。
任务运行中如果 `task_status` 带 `stall` 字段,说明 AALC 在原地空转(例如选中了空队伍, 任务运行中如果 `task_status` 带 `stall` 字段,说明 AALC 在原地空转(例如选中了空队伍,
编队人数检查一直刷屏)。它不会自己报错退出,应当 `stop_task` 后重跑。 编队人数检查一直刷屏)。它不会自己报错退出,应当 `stop_task` 后重跑。
@@ -153,6 +188,7 @@ powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Every
| `LCP_PORT` | 8765 | 服务/bridge 端口 | | `LCP_PORT` | 8765 | 服务/bridge 端口 |
| `LCP_KEEP_SHOTS` | 30 | 截图保留张数 | | `LCP_KEEP_SHOTS` | 30 | 截图保留张数 |
| `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 | | `LCP_ALLOW_LUNACY` | 未设置 | 设为 `1` 时允许预检放行 `set_lunacy_to_enkephalin` 不为 0 的配置 |
| `LCP_KILL_KEY` | `f12` | 任务子进程的急停键,如 `f11` / `pause` |
| `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python | | `LC_PY` | 当前解释器 | `levelup.py`/`auto_cycle.py` 调用 MCP 用的 Python |
## 开发 / 测试 ## 开发 / 测试
@@ -180,7 +216,7 @@ vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_client.py <private-conf
镜牢执行器的场景规则只适用于镜牢,推进主线时应提供主线观察和规则。 镜牢执行器的场景规则只适用于镜牢,推进主线时应提供主线观察和规则。
```bash ```bash
python -m unittest discover -s tests # 不需要 Windows/AALC (FakeEngine) python -m unittest discover -s tests -t tests # 不需要 Windows/AALC (FakeEngine)
python -m lc_mcp.server --stdio --fake # 假引擎手动调试协议 python -m lc_mcp.server --stdio --fake # 假引擎手动调试协议
``` ```
+9 -8
View File
@@ -77,15 +77,15 @@ python scripts/audit_runs.py # 体检: 日志与报告交叉核对, 揪出
确认 Confirm (943,671) 取消 Cancel (656,670) 确认 Confirm (943,671) 取消 Cancel (656,670)
``` ```
判定是否停在免费合成页签的依据:**兑换区显示体力条 `x/126`**(Use Lunacy 那边显示的是狂气)。 判定是否停在免费合成页签:优先识别问句 **`Would you like to assemble Enkephalin Modules?`**,
判不出来就不合成。 兑换区的体力条 `x/126` 作为备用信号。判不出来就不合成。
## 四、狂气的三道防线 ## 四、狂气的三道防线
1. **只点 `Modules` 页签**。`USE_LUNACY_TAB` 常量只用于"确认没点到它"。 1. **只点 `Modules` 页签**。`USE_LUNACY_TAB` 常量只用于"确认没点到它"。
2. **AST 测试盯着**:任何 `click()` 传入该坐标都会让测试失败(`test_convert_modules.py`)。 2. **AST 测试盯着**:任何 `click()` 传入该坐标都会让测试失败(`test_convert_modules.py`)。
3. **前后相对比对**:这个数字是像素艺术字,OCR 会误读(实测真实 6636 读成 9699、 3. **配置禁止购买**:`set_lunacy_to_enkephalin: 0`。前后 OCR 读数只作为核查线索,
真实 6388 读成 8859),所以不信任绝对值,只看前后是否一致。 数字是像素艺术字,可能有多种稳定误读,读数相同或落在已知集合里都不能证明没消费。
> ⛔ **第 3 道防线曾经整条哑掉**(2026-10-16 发现)。OCR 把标签 `LUNACY` 读成 > ⛔ **第 3 道防线曾经整条哑掉**(2026-10-16 发现)。OCR 把标签 `LUNACY` 读成
> `UNACY`(首字母被吃掉),而代码写的是 `'LUNACY' in text` —— `UNACY` 不包含 > `UNACY`(首字母被吃掉),而代码写的是 `'LUNACY' in text` —— `UNACY` 不包含
@@ -178,8 +178,11 @@ Interval : PT4H # 10:03 / 14:03 / 18:03 / 22:03 / 02:03 / 06:03
| 情况 | 结论 | | 情况 | 结论 |
|---|---| |---|---|
| 前后一致 | 没变 | | 前后一致 | 没变 |
| 后读数在已知读法集合里 | 判为 OCR 抖动,不算消费 | | 前后读数都在已知读法集合里 | 按已知 OCR 抖动处理,不单凭此告警 |
| 后读数不在集合里 | 出现没见过的值,值得人工看一眼 | | 变化涉及已知集合以外的读数 | 需人工核查,包括新余额变回集合内读数的情况 |
取数时标签和余额来自同一帧;读完 5 帧后取唯一众数,至少出现 2 次,平票则返回未知。
这能减少偶发误读,不能消除系统性误读。
**守不住的部分就承认守不住,别拿一个会误报的判据充数** —— 误报会让人去查一笔 **守不住的部分就承认守不住,别拿一个会误报的判据充数** —— 误报会让人去查一笔
根本没发生的消费,比"没检测到"更糟。 根本没发生的消费,比"没检测到"更糟。
@@ -225,5 +228,3 @@ Get-ChildItem "$dir\convert_*.json" | ForEach-Object {
if ($m -and $m.secs -eq $r.elapsed_s) { "OK $($r.started)" } else { "MISMATCH $($_.Name)" } if ($m -and $m.secs -eq $r.elapsed_s) { "OK $($r.started)" } else { "MISMATCH $($_.Name)" }
} }
``` ```
+130
View File
@@ -0,0 +1,130 @@
# 2026-10-22 自动运行代码复核
上游更新已单独提交为 `4e5d63a`:AALC 子模块从 `b0f4393` 更新到 `e1d1749`。
本次围绕自动运行、模块合成、人格升级和任务状态进行复核。
## 依据与范围
- 最近的完整实机归档是 `docs/feedback/2026-10-13/results/`,含 10 份任务日志和 3 份轮次报告。
- `docs/WATCH.md` 补充了 10 月 16~17 日的 OCR、显示会话和模块轨迹记录。
- 当前 Linux 环境没有 `~/lc_mcp` 实机运行目录。本次使用仓库归档和离线复现,没有连接或操作 Windows 游戏。
- 10 月 17 日跨轮模块减少已由用户确认为人工升阶消费,不能据此推断合成丢档。
## 已确认与修复
| 优先级 | 触发条件与原行为 | 修复与验证 |
|---|---|---|
| P1 | 缺模块弹窗出现时,`auto_cycle.py` 在 AALC 仍运行时点 Cancel;协议拒绝输入,但调用方不检查返回值,仍记为已处理 | 轮询只读识别,连续 3 次出现才停止任务,停止成功后重新识别并发送 Cancel。停止或点击失败不记成功,也不重跑。用真实 `Server` 和假引擎验证互斥顺序 |
| P1 | 升级子脚本返回非零或抛出异常,但 `lc_ui.run()` 丢弃退出码;输出没有 `FAIL` 时会报告“无需升级” | 升级和网格子脚本启用退出码检查;异常写入轮次失败报告,保留 stdout/stderr。测试实际启动一个崩溃子进程 |
| P1 | `levelup.cmd_progress()` 所有详情均打不开、或详情等级读不到时,仍可能退出 0;升级成功但同步失败也退出 0 | 未核实的等级不退回网格猜测;未核实候选和同步失败返回非零,确认全部候选达标才正常跳过 |
| P2 | 狂气读取遇到前两次同值就提前返回;合成脚本还用不同帧的标签和数字配对 | 采完所有帧后取唯一众数,平票返回未知;每次只读取一帧并在其中找标签和数字。刷取脚本同时支持 `UNACY` 和 0~99 的余额 |
| P2 | 合成前是新余额、合成后落入旧 OCR 值集合时,仅凭后值就跳过告警 | 前后都属于已知读法才按已知抖动处理;集合之外的变化提示核查,不直接宣称发生消费 |
| P2 | 合成后模组数小于合成前,末尾分支仍返回成功,合成数量为负 | 下降明确返回失败,数量为 0;报告不再把负数当已合成。重复调用主流程时清除上一轮字段 |
| P2 | 任务完全停止写日志时,文件 mtime 不再增长,“无进展秒数”也被冻结 | 在线判定使用当前时间;离线回放可传入观察时刻。回放真实卡死 daily、健康 daily 和镜牢日志,确认区分正确 |
| P3 | 实机报告指出 Windows Python 3.13 的测试发现命令存在导入问题;值守说明仍混用旧的 OCR 判据 | README 改用 `unittest discover -s tests -t tests`,值守手册同步当前免费页签和 OCR 判据 |
10 月 13 日领奖日志的 `ModuleNotFoundError: No module named 'config'` 已由此次 AALC
更新中的 `218c6f7` 修复:`tasks/daily/get_prize.py` 使用 `from module.config import cfg`。
无需在本仓库再加运行时补丁。
## 验证与限制
测试使用 Python 3.12 / Linux,374 项全部通过(16.813 秒),比更新前增加 22 项。
覆盖真实协议输入互斥、失败子进程、OCR 帧序列、负合成数量、重复轮次状态,以及归档日志回放。
`git diff --check` 通过。全套验证命令:
```sh
python3 -m unittest discover -s tests -t tests
git diff --check
```
仍需在 Windows 实机核验新版 AALC 的领奖、镜牢和实际截图行为。多帧投票无法消除稳定的
OCR 误读;已知读法集合只来自该账号历史观测,不是通用余额验证。狂气消费限制仍依赖
免费合成页签和 `set_lunacy_to_enkephalin: 0`。720 客户区模板匹配退化的历史证据也仍成立,
没有自动修改游戏配置或分辨率。
## 补充:DSH 提交的合入范围与审查
用户提到 DeepSeek 的提交后,进一步查到作者 `DSH <dsh@local.invalid>` 的
`66418dc`(2026-10-03)。Git 元数据没有模型标记,以下按该提交的可核实来源追踪。
- `95ae060` 的提交说明明确记录:从 `66418dc` 引入 `tasks.py` 的报错展示及两项测试。
该提交已在 `main` 和当前分支历史中。
- `66418dc` 的编队滑动补丁未合入。合入说明记录了分段移动过短导致后台不发移动事件、
前台停顿和行程不一致等问题。重写版本 `dd4259d` 留在 `origin/fix/team-scroll-patch`,
当前分支没有 `aalc_input_patch.py`,没有启用这套补丁。
- `e490a29` 是同一作者的实机记录提交,保存在 `archive/story-test-20261003` 标签中。
已合入的报错检测有一处 **P1 漏报**:只扫描最后 400 行,并受 `tail()` 的 64 KiB 上限限制。
因此一场战斗失败后继续输出调试日志,最终 exit 0 时会失去 `errors` 字段。用含早期
“未能进入战斗”及 5000 行后续输出的真实子进程可复现。
修复为任务退出后流式扫描整份日志,仅保留最后 3 条报错并缓存结果。任务仍以退出码给出
`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 os
import sys import sys
import time import time
from contextlib import contextmanager
from .engine import Engine from .engine import Engine
@@ -228,28 +229,41 @@ class AalcEngine(Engine):
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER | win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
win32con.SWP_NOACTIVATE) 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): def click(self, x, y, times=1):
self._prepare_input() self._prepare_input()
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'): if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con import win32con
handler = self.auto.input_handler
self.auto.wait_pause() self.auto.wait_pause()
for _ in range(int(times)): for _ in range(int(times)):
position = None with self._background_target(x, y):
if self.cfg.win_input_type == 'window_move': self._background_mouse(win32con.WM_MOUSEMOVE, x, y)
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:
time.sleep(0.12) time.sleep(0.12)
finally: try:
self._background_mouse(win32con.WM_LBUTTONUP, x, y) self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
if position is not None: time.sleep(0.5 if self.cfg.win_input_type == 'window_move' else 0.12)
time.sleep(0.12) finally:
self._restore_background_position(position) self._background_mouse(win32con.WM_LBUTTONUP, x, y)
# Let Unity consume the release before another target is selected. # Let Unity consume the release before another target is selected.
time.sleep(0.12) time.sleep(0.12)
elif not self.cfg.simulator and self.cfg.win_input_type == 'foreground': 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'): if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
import win32con import win32con
self.auto.wait_pause() self.auto.wait_pause()
position = None with self._background_target(from_x, from_y) as position:
if self.cfg.win_input_type == 'window_move': self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y)
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:
time.sleep(0.12) time.sleep(0.12)
steps = max(1, int(float(duration) / 0.02)) last_x, last_y = from_x, from_y
for step in range(1, steps + 1): try:
last_x = round(from_x + (to_x - from_x) * step / steps) self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
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:
time.sleep(0.12) 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 return
if not self.cfg.simulator and self.cfg.win_input_type == 'foreground': if not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
import pyautogui import pyautogui
+211
View File
@@ -12,9 +12,11 @@
一次, 之后全部模板匹配分数掉到阈值以下, 表现为原地空转、不报错。这里在后台定期 一次, 之后全部模板匹配分数掉到阈值以下, 表现为原地空转、不报错。这里在后台定期
检查客户区尺寸, 偏离 set_win_size 时调回去。 检查客户区尺寸, 偏离 set_win_size 时调回去。
""" """
import os
import re import re
import threading import threading
import time import time
from contextlib import contextmanager
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE) TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
@@ -94,3 +96,212 @@ class WindowGuard(threading.Thread):
def stop(self): def stop(self):
self.stopped.set() 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 os
import sys import sys
from . import preflight from . import killswitch, preflight
from .aalc_engine import bootstrap 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 配置项}; 参数只在本次运行内生效 # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = { TASKS = {
@@ -74,42 +75,45 @@ def run(task, params):
from tasks.battle import battle from tasks.battle import battle
from utils.path_manager import path_manager from utils.path_manager import path_manager
problems = preflight.check(preflight.collect(cfg), task, with killswitch.listening(log=log, on_stop=lambda: stop_driver_click(auto)):
desktop=None if cfg.simulator else preflight.desktop_size()) problems = preflight.check(preflight.collect(cfg), task,
if problems: desktop=None if cfg.simulator else preflight.desktop_size())
for p in problems: if problems:
log('[ERROR] [lc_mcp] preflight: %s' % p) for p in problems:
return PREFLIGHT_EXIT log('[ERROR] [lc_mcp] preflight: %s' % p)
return PREFLIGHT_EXIT
install_exact_team_match(auto, log) install_exact_team_match(auto, log)
guard = WindowGuard(screen, cfg, log=log) install_robust_set_foreground(screen, log=log)
guard.start() guard = WindowGuard(screen, cfg, log=log)
restore_path = os.environ.get(RESTORE_ENV) guard.start()
originals = apply_overrides(cfg, task, params, restore_path) restore_path = os.environ.get(RESTORE_ENV)
try: originals = apply_overrides(cfg, task, params, restore_path)
if task == 'all': with driver_click_tasks(scheme, auto, screen, cfg, log=log):
scheme.script_task() try:
return 0 if task == 'all':
# 与 script_task() 相同的前置步骤 scheme.script_task()
scheme.init_game() return 0
path_manager.initialize_paths() # 与 script_task() 相同的前置步骤
auto.clear_img_cache() scheme.init_game()
retry_monitor.start() path_manager.initialize_paths()
get_reward = None auto.clear_img_cache()
if auto.click_element('battle/turn_assets.png', take_screenshot=True): retry_monitor.start()
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True) get_reward = None
get_reward = battle.fight() if auto.click_element('battle/turn_assets.png', take_screenshot=True):
{ print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
'daily': scheme.Daily_task_wrapper(get_reward=get_reward), get_reward = battle.fight()
'reward': scheme.to_get_reward, {
'enkephalin': scheme.Buy_enkephalin, 'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'mirror': scheme.Mirror_task, 'reward': scheme.to_get_reward,
}[task]() 'enkephalin': scheme.Buy_enkephalin,
return 0 'mirror': scheme.Mirror_task,
finally: }[task]()
guard.stop() return 0
retry_monitor.stop() finally:
restore(cfg, originals, restore_path) guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
def main(argv): 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)
+22 -12
View File
@@ -9,8 +9,10 @@ import subprocess
import sys import sys
import threading import threading
import time import time
from collections import deque
from .aalc_task import RESTORE_ENV from .aalc_task import RESTORE_ENV
from .killswitch import EXIT_CODE as USER_ABORT_EXIT
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IS_WIN = sys.platform.startswith('win') IS_WIN = sys.platform.startswith('win')
@@ -41,15 +43,21 @@ ERROR_SCAN_LINES = 400
def log_errors(path, limit=3): def log_errors(path, limit=3):
"""挑出日志尾部的报错行。 """流式扫描整份任务日志, 只保留最后 limit 条报错。
AALC 的每日流程在单次战斗失败后会继续跑完并正常退出(exit 0), 只看退出码 AALC 的每日流程在单次战斗失败后会继续跑完并正常退出(exit 0), 只看退出码
会把"超出最大尝试次数,未能进入战斗"这类失败当成成功, 所以状态里额外附上 会把"超出最大尝试次数,未能进入战斗"这类失败当成成功, 所以状态里额外附上
日志里的报错行。 日志里的报错行。
""" """
hits = [line for line in tail(path, ERROR_SCAN_LINES) hits = deque(maxlen=limit)
if any(marker in line for marker in ERROR_MARKERS)] try:
return hits[-limit:] with open(path, encoding='utf-8', errors='replace') as f:
for line in f:
if any(marker in line for marker in ERROR_MARKERS):
hits.append(line.rstrip('\r\n'))
except OSError:
pass
return list(hits)
# AALC 卡死时不报错、进程健在, 只是反复输出同一类日志。 # AALC 卡死时不报错、进程健在, 只是反复输出同一类日志。
@@ -92,19 +100,17 @@ def last_progress_epoch(path):
return last return last
def log_stalls(path): def log_stalls(path, now=None):
"""统计日志尾部的卡死信号, 达到阈值的返回 {名称: 次数}。""" """统计日志尾部的卡死信号, 达到阈值的返回 {名称: 次数}。"""
lines = tail(path, ERROR_SCAN_LINES) lines = tail(path, ERROR_SCAN_LINES)
counts = {name: sum(marker in line for line in lines) for name, marker in STALL_MARKERS.items()} counts = {name: sum(marker in line for line in lines) for name, marker in STALL_MARKERS.items()}
stalls = {name: n for name, n in counts.items() if n >= STALL_THRESHOLD} stalls = {name: n for name, n in counts.items() if n >= STALL_THRESHOLD}
# 无进展判据: 用日志自身的最后写入时间当"现在", 避免与调用方时钟不一致 # 必须随真实时间推进: 进程卡住不再写日志时, mtime 也会冻结。
# 离线复核历史日志时可显式传入当时的 now。
progress = last_progress_epoch(path) progress = last_progress_epoch(path)
if progress is not None: if progress is not None:
try: idle = (time.time() if now is None else now) - progress
idle = os.path.getmtime(path) - progress
except OSError:
idle = 0
if idle >= STALL_NO_PROGRESS_S: if idle >= STALL_NO_PROGRESS_S:
stalls['no_progress'] = int(idle) stalls['no_progress'] = int(idle)
return stalls return stalls
@@ -181,7 +187,8 @@ class TaskRunner:
state = 'running' state = 'running'
else: else:
self.info.setdefault('ended', time.time()) self.info.setdefault('ended', time.time())
state = 'stopped' if self.info['stopped_by_user'] else 'succeeded' if code == 0 else 'failed' state = ('stopped' if self.info['stopped_by_user'] or code == USER_ABORT_EXIT
else 'succeeded' if code == 0 else 'failed')
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'], r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']), 'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))} 'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}
@@ -191,7 +198,10 @@ class TaskRunner:
r['stall'] = stalls r['stall'] = stalls
else: else:
r['exit_code'] = code r['exit_code'] = code
errors = log_errors(self.info['log']) # 子进程退出后日志已写完; 结果只计算一次, 避免轮询反复扫描大文件。
if 'errors' not in self.info:
self.info['errors'] = log_errors(self.info['log'])
errors = self.info['errors']
if errors: if errors:
r['errors'] = errors r['errors'] = errors
pending = self._pending_restores() pending = self._pending_restores()
+76 -39
View File
@@ -13,6 +13,7 @@
import argparse import argparse
import json import json
import os import os
import subprocess
import time import time
from lc_ui import HERE, PY, click, drag, items, keypress, probe, run from lc_ui import HERE, PY, click, drag, items, keypress, probe, run
@@ -41,6 +42,10 @@ DEFAULT_REPORT_DIR = os.path.expanduser(os.path.join('~', 'lc_mcp', 'cycles'))
_log_file = None _log_file = None
class UserAborted(RuntimeError):
"""用户主动停止, 结束整轮, 不执行后续导航、升级或重试。"""
def log(msg): def log(msg):
line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg) line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg)
print(line, flush=True) print(line, flush=True)
@@ -127,31 +132,37 @@ def ensure_team1():
return False return False
def clear_blocking_modal(): def blocking_module_modal():
"""清掉挡在 AALC 前面的模态框, 返回清掉的说明或 None。 """只读识别缺模组弹窗, 返回 Cancel 中心。AALC 运行期间不发送输入。"""
2026-10-13 实测: Enkephalin Modules 不足时游戏弹出
"You don't have enough Enkephalin Modules. / Would you like to go assemble some?"
而 AALC 的 Luxcavation 流程不认这个框 —— 它一直在后面点被挡住的 Enter 按钮,
每次都要等满 10 分钟被 no_progress 判据救回来。点 Cancel 拒绝去组装,
AALC 就会自己往下走(该关卡过不去, 它会降级试下一关)。
只在轮询里做这件事, 不碰 AALC 自己的识别; 模态框本来就挡住了一切输入,
点它的 Cancel 不会造成误操作。
"""
its = items() its = items()
txt = ' '.join(i.get('text', '') for i in its).replace(' ', '') txt = ''.join(''.join(i.get('text', '').split()) for i in its).lower()
if 'enoughEnkephalinModules' not in txt: if 'enoughenkephalinmodules' not in txt:
return None return None
for it in its: for it in its:
if 'cancel' in it.get('text', '').lower(): if 'cancel' in it.get('text', '').lower():
w = it.get('w') or 0 w = it.get('w') or 0
h = it.get('h') or 0 h = it.get('h') or 0
click(it['x'] + w / 2.0, it['y'] + h / 2.0) return it['x'] + w / 2.0, it['y'] + h / 2.0
return 'Enkephalin Modules 不足 -> 点 Cancel'
return None return None
def clear_blocking_modal():
"""任务停止后重新识别并取消缺模组弹窗; 点击被拒绝时不能报成功。"""
pos = blocking_module_modal()
if pos is None:
return None
result = click(*pos)
if not result.get('ok'):
raise RuntimeError('取消缺模组弹窗失败: %s' % result.get('error', result))
return 'Enkephalin Modules 不足 -> 已发送 Cancel'
def stop_running_task():
result = probe('stop_task')
if not result.get('ok'):
raise RuntimeError('停止 AALC 任务失败: %s' % result.get('error', result))
# 同一轮里连着这么多次看到"模组不足", 就不是偶发了, 是资源真的见底 # 同一轮里连着这么多次看到"模组不足", 就不是偶发了, 是资源真的见底
RESOURCE_OUT_LIMIT = 3 RESOURCE_OUT_LIMIT = 3
@@ -160,12 +171,17 @@ def poll_task(task, timeout_s, sleep=time.sleep):
"""轮询到任务结束。返回 (ok, 说明, 是否因卡死被停)。""" """轮询到任务结束。返回 (ok, 说明, 是否因卡死被停)。"""
t0 = time.time() t0 = time.time()
stalled = 0 stalled = 0
cleared = 0 resource_polls = 0
while time.time() - t0 < timeout_s: while time.time() - t0 < timeout_s:
sleep(POLL_S) sleep(POLL_S)
st = probe('task_status', {'lines': 1}) st = probe('task_status', {'lines': 1})
if st.get('ok') is False or not st.get('state'):
stop_running_task()
raise RuntimeError('无法读取任务状态: %s' % st.get('error', st))
s = st.get('state') s = st.get('state')
el = int(time.time() - t0) el = int(time.time() - t0)
if s == 'stopped' or st.get('exit_code') == 130:
raise UserAborted('%s 已被用户停止' % task)
if s != 'running': if s != 'running':
log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code'))) log('%s 结束: state=%s elapsed=%ds exit=%s' % (task, s, el, st.get('exit_code')))
# AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors # AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors
@@ -173,25 +189,28 @@ def poll_task(task, timeout_s, sleep=time.sleep):
return False, '%s: %s' % (s, st['errors'][-1]), False return False, '%s: %s' % (s, st['errors'][-1]), False
return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el), False return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el), False
try: try:
msg = clear_blocking_modal() modal = blocking_module_modal()
except Exception as e: # 清道夫不该拖垮轮询 except Exception as e: # 清道夫不该拖垮轮询
msg = None modal = None
log(' [warn] 清模态框时出错: %s' % e) log(' [warn] 读取缺模组弹窗时出错: %s' % e)
if msg: resource_polls = resource_polls + 1 if modal is not None else 0
cleared += 1 if resource_polls:
log(' [fix] %s (%d/%d)' % (msg, cleared, RESOURCE_OUT_LIMIT)) log(' 缺模组弹窗连续出现 (%d/%d)' % (resource_polls, RESOURCE_OUT_LIMIT))
if cleared >= RESOURCE_OUT_LIMIT: if resource_polls >= RESOURCE_OUT_LIMIT:
# 反复缺模组 = 体力/模组真的见底了。继续点下去只是空转到超时, # 反复缺模组 = 体力/模组真的见底了。继续点下去只是空转到超时,
# 浪费掉这一轮的时间(实测每次都烧满 10 分钟)。直接收工, 等下一轮。 # 浪费掉这一轮的时间(实测每次都烧满 10 分钟)。直接收工, 等下一轮。
probe('stop_task') stop_running_task()
msg = clear_blocking_modal()
if msg:
log(' [fix] %s' % msg)
return False, 'RESOURCE_OUT', False return False, 'RESOURCE_OUT', False
stalled = stalled + 1 if st.get('stall') else 0 stalled = stalled + 1 if st.get('stall') else 0
if stalled >= STALL_POLLS: if stalled >= STALL_POLLS:
probe('stop_task') stop_running_task()
return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el), True return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el), True
if el % 600 < POLL_S: if el % 600 < POLL_S:
log(' ...%s running %ds' % (task, el)) log(' ...%s running %ds' % (task, el))
probe('stop_task') stop_running_task()
return False, '超时 %ds' % timeout_s, False return False, '超时 %ds' % timeout_s, False
@@ -213,7 +232,7 @@ def run_aalc(task, params, timeout_s, retries=STALL_RETRIES, sleep=time.sleep):
def report_grid(): def report_grid():
out = run([PY, '-X', 'utf8', LEVELUP, 'list']) out = run([PY, '-X', 'utf8', LEVELUP, 'list'], check=True)
return out.strip() return out.strip()
@@ -228,35 +247,36 @@ def read_lunacy(reads=5, pause=1.0):
2. **同一个画面上数字本身就会抖**: 放大 6 倍肉眼确认余额是 6388, 而 OCR 在 2. **同一个画面上数字本身就会抖**: 放大 6 倍肉眼确认余额是 6388, 而 OCR 在
同一画面连读 5 次得到 6388 四次、8859 一次。8859 被当成基线后, 之后正确 同一画面连读 5 次得到 6388 四次、8859 一次。8859 被当成基线后, 之后正确
的 6388 反而被判成"已消耗"并中止整轮 —— 一次误读就能造成一次误报。 的 6388 反而被判成"已消耗"并中止整轮 —— 一次误读就能造成一次误报。
所以取众数(至少出现 2 次才采信), 而不是"最后读到什么就是什么"。 所以读完所有帧再取唯一众数(至少出现 2 次才采信), 平票返回 None。
曾经试过"只在主界面取数", 但那样几乎总是读不到(轮次开始/结束时常停在副本、 曾经试过"只在主界面取数", 但那样几乎总是读不到(轮次开始/结束时常停在副本、
网格、结算页), 守卫直接跳过 —— 防线等于没有。众数投票已经能压住误读, 网格、结算页), 守卫直接跳过。多帧投票只能减少偶发误读, 无法证明消费。
覆盖率更重要。
""" """
votes = {} votes = {}
for attempt in range(reads): for attempt in range(reads):
its = items() its = items()
lab = None lab = None
for it in its: for it in its:
if 'LUNACY' in it.get('text', '').upper(): if 'NACY' in it.get('text', '').upper():
lab = it lab = it
break break
if lab: if lab:
best = None best = None
for it in its: for it in its:
t = it.get('text', '').strip() t = it.get('text', '').strip()
if t.isdigit() and len(t) >= 3: if t.isdigit():
dy = it.get('y', 0) - lab.get('y', 0) dy = it.get('y', 0) - lab.get('y', 0)
dx = abs(it.get('x', 0) - lab.get('x', 0)) dx = abs(it.get('x', 0) - lab.get('x', 0))
if 0 < dy < 70 and dx < 130: if 0 < dy < 70 and dx < 130:
best = int(t) best = int(t)
if best is not None: if best is not None:
votes[best] = votes.get(best, 0) + 1 votes[best] = votes.get(best, 0) + 1
if votes[best] >= 2:
return best
if attempt < reads - 1: if attempt < reads - 1:
time.sleep(pause) time.sleep(pause)
ranked = sorted(votes, key=votes.get, reverse=True)
if ranked and votes[ranked[0]] >= 2:
if len(ranked) == 1 or votes[ranked[0]] > votes[ranked[1]]:
return ranked[0]
return None return None
@@ -279,7 +299,7 @@ def lunacy_guard():
f.write(str(cur)) f.write(str(cur))
return True, '记录狂气基线 %d' % cur return True, '记录狂气基线 %d' % cur
if cur < base: if cur < base:
return False, '狂气从 %d 降到 %d —— 已消耗, 立即停止' % (base, cur) return False, '狂气读数从 %d 降到 %d, 需人工核查(OCR 也可能误读), 本轮暂停' % (base, cur)
if cur > base: if cur > base:
with open(LUNACY_BASELINE, 'w', encoding='utf-8') as f: with open(LUNACY_BASELINE, 'w', encoding='utf-8') as f:
f.write(str(cur)) f.write(str(cur))
@@ -316,9 +336,26 @@ def main(argv=None):
json.dump(report, f, ensure_ascii=False, indent=2) json.dump(report, f, ensure_ascii=False, indent=2)
return code return code
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 '')
for line in output.splitlines():
log(' ' + line)
step('执行异常', False, '%s: %s' % (type(e).__name__, e))
return finish(1, '本轮失败: 执行异常')
finally:
_log_file = None
def run_cycle(args, step, finish):
log('=== 一轮开始 ===') log('=== 一轮开始 ===')
if not step('狂气校验', *lunacy_guard()): if not step('狂气校验', *lunacy_guard()):
return finish(1, '中止: 狂气被消耗, 按用户要求不得使用') return finish(1, '中止: 狂气读数下降, 需人工核查')
# 先把预设列表拉回顶部并选中 TEAMS #1——AALC 只朝列表下方找, 停在底部会找不到 # 先把预设列表拉回顶部并选中 TEAMS #1——AALC 只朝列表下方找, 停在底部会找不到
if not ensure_team1(): if not ensure_team1():
@@ -344,7 +381,7 @@ def main(argv=None):
# AALC 任务结束后在主界面, 这里才是能读到 LUNACY 的时机 # AALC 任务结束后在主界面, 这里才是能读到 LUNACY 的时机
time.sleep(8) time.sleep(8)
if not step('狂气校验(刷后)', *lunacy_guard()): if not step('狂气校验(刷后)', *lunacy_guard()):
return finish(1, '中止: 狂气被消耗, 按用户要求不得使用') return finish(1, '中止: 狂气读数下降, 需人工核查')
if not goto_identities(): if not goto_identities():
# 镜牢超时被强杀时游戏还停在副本里, 这时进不去网格是正常的, 不是缺陷。 # 镜牢超时被强杀时游戏还停在副本里, 这时进不去网格是正常的, 不是缺陷。
@@ -358,7 +395,7 @@ def main(argv=None):
log('对队内低于 Lv.%d 的人格升级 + 同步' % args.target) log('对队内低于 Lv.%d 的人格升级 + 同步' % args.target)
# 用 progress 而非 weakest: 网格 OCR 会把 LV14 读成 Lv.1, # 用 progress 而非 weakest: 网格 OCR 会把 LV14 读成 Lv.1,
# progress 会逐个打开详情页以真实等级判断目标。 # progress 会逐个打开详情页以真实等级判断目标。
out = run([PY, '-X', 'utf8', LEVELUP, 'progress', str(args.target), '--uptie']) out = run([PY, '-X', 'utf8', LEVELUP, 'progress', str(args.target), '--uptie'], check=True)
lines = out.strip().splitlines() lines = out.strip().splitlines()
for line in lines: for line in lines:
log(' ' + line) log(' ' + line)
+109 -30
View File
@@ -19,7 +19,7 @@
1. **绝不消费狂气**。Use Lunacy 页签的坐标 USE_LUNACY_TAB 在代码里只用于 1. **绝不消费狂气**。Use Lunacy 页签的坐标 USE_LUNACY_TAB 在代码里只用于
"确认自己没点到它", 任何点击路径都不会碰它。 "确认自己没点到它", 任何点击路径都不会碰它。
2. **不打任何关卡**。全程只碰底栏模组图标和合成面板。 2. **不打任何关卡**。全程只碰底栏模组图标和合成面板。
3. 合成前后各读一次狂气, 不一致就报错退出(宁可不合成, 也不冒险)。 3. 记录合成前后狂气读数; 已知 OCR 抖动以外的变化需要人工核查。
""" """
import argparse import argparse
import json import json
@@ -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(): def render_ok():
"""桌面是否在出图(BitBlt 能否成功)。""" """游戏画面是否可采集。
from ctypes import windll
u, g = windll.user32, windll.gdi32 ⛔ 原来只测屏幕 BitBlt(GetDC(0))。2026-10-22 实测它在 RDP 会话下会瞬时失败,
hdc = u.GetDC(0) 而 AALC 走的是 background_screenshot(窗口 DC + PrintWindow), 那条路照样能截到图
mem = g.CreateCompatibleDC(hdc) —— 结果是我的自检把本来能干活的轮次判成"截不到图"给跳过了(10-17 02:23 就这样
bmp = g.CreateCompatibleBitmap(hdc, 64, 64) 白丢过一轮)。
g.SelectObject(mem, bmp)
r = g.BitBlt(mem, 0, 0, 64, 64, hdc, 0, 0, 0x00CC0020) 现在优先按 AALC 的方式测**窗口**能否采集, 窗口不在或不可采时才回退到屏幕。
g.DeleteObject(bmp) """
g.DeleteDC(mem) hwnd = _find_hwnd()
u.ReleaseDC(0, hdc) if hwnd and window_blit_ok(hwnd):
return bool(r) return True
return screen_blit_ok()
def parse_session_table(text): def parse_session_table(text):
@@ -243,7 +318,7 @@ def panel_open(txt):
LABEL_KEY = 'NACY' # 见下: LUNACY 的首字母常被 OCR 吃掉, 只认后半段 LABEL_KEY = 'NACY' # 见下: LUNACY 的首字母常被 OCR 吃掉, 只认后半段
def find_lunacy_label(): def find_lunacy_label(its=None):
"""找狂气标签所在的那个 OCR 元素。 """找狂气标签所在的那个 OCR 元素。
⛔ 实测坑(2026-10-16 11:11): OCR 把 "LUNACY" 读成了 **"UNACY"** —— 首字母 L ⛔ 实测坑(2026-10-16 11:11): OCR 把 "LUNACY" 读成了 **"UNACY"** —— 首字母 L
@@ -254,7 +329,8 @@ def find_lunacy_label():
改成认后半段 "NACY": LUNACY / UNACY / 甚至 NACY 都能命中, 而这个词根 改成认后半段 "NACY": LUNACY / UNACY / 甚至 NACY 都能命中, 而这个词根
在游戏界面里不会出现在别处。 在游戏界面里不会出现在别处。
""" """
its = items() if its is None:
its = items()
for it in its: for it in its:
if LABEL_KEY in it.get('text', '').upper(): if LABEL_KEY in it.get('text', '').upper():
return it return it
@@ -272,30 +348,30 @@ def read_lunacy(reads=5, pause=1.0):
两个实测坑: 两个实测坑:
1. 标签首字母会被 OCR 吃掉(LUNACY -> UNACY), 所以不能整词匹配, 见 find_lunacy_label。 1. 标签首字母会被 OCR 吃掉(LUNACY -> UNACY), 所以不能整词匹配, 见 find_lunacy_label。
2. 数字是像素风艺术字, OCR 很容易把 6 认成 9、3 认成 8 —— 实测同一个画面上 2. 读完所有帧再取唯一众数(至少出现两次), 平票返回 None。标签和数字必须来自
真实 6636 会被读成 9699、真实 6388 被读成 8859。所以取众数, 并且合成前后 同一帧。OCR 的系统性误读仍可能存在, 前后不同不能直接证明消费。
各读一次做**相对**比对(同一画面同一字体, 误读方式一致), 这样即使绝对值
读错, 也能发现"数字变了"。
""" """
votes = {} votes = {}
for i in range(reads): for i in range(reads):
its = items() its = items()
lab = find_lunacy_label() lab = find_lunacy_label(its)
if lab: if lab:
best = None best = None
for it in its: for it in its:
t = it.get('text', '').strip() t = it.get('text', '').strip()
if t.isdigit() and len(t) >= 3: if t.isdigit():
dy = it.get('y', 0) - lab.get('y', 0) dy = it.get('y', 0) - lab.get('y', 0)
dx = abs(it.get('x', 0) - lab.get('x', 0)) dx = abs(it.get('x', 0) - lab.get('x', 0))
if 0 < dy < 70 and dx < 130: if 0 < dy < 70 and dx < 130:
best = int(t) best = int(t)
if best is not None: if best is not None:
votes[best] = votes.get(best, 0) + 1 votes[best] = votes.get(best, 0) + 1
if votes[best] >= 2:
return best
if i < reads - 1: if i < reads - 1:
time.sleep(pause) time.sleep(pause)
ranked = sorted(votes, key=votes.get, reverse=True)
if ranked and votes[ranked[0]] >= 2:
if len(ranked) == 1 or votes[ranked[0]] > votes[ranked[1]]:
return ranked[0]
return None return None
@@ -307,8 +383,8 @@ def read_lunacy(reads=5, pause=1.0):
# 只点了模组图标和面板内的 » / 确认, 根本没碰 Use Lunacy 页签, 没有任何消费)。 # 只点了模组图标和面板内的 » / 确认, 根本没碰 Use Lunacy 页签, 没有任何消费)。
# #
# 能站得住的判断只有两种: # 能站得住的判断只有两种:
# * 后读数落在"已知读法"集合里 -> 视为没变(可能只是换了个误读法) # * 前后读数都落在"已知读法"集合里 -> 可能只是换了个误读法
# * 后读数不在集合里 -> 出现了从没见过的值, 值得人工看一眼 # * 变化涉及集合以外的读数 -> 需要人工核查
# 真正的防线是结构性的(只点 Modules 页签, 且 Use Lunacy 坐标被测试盯着), # 真正的防线是结构性的(只点 Modules 页签, 且 Use Lunacy 坐标被测试盯着),
# 这里只是补一层"数字有没有变成陌生值"的旁证。 # 这里只是补一层"数字有没有变成陌生值"的旁证。
LUNACY_KNOWN_READINGS = (6636, 9699, 6388, 8859) LUNACY_KNOWN_READINGS = (6636, 9699, 6388, 8859)
@@ -320,11 +396,11 @@ def lunacy_verdict(before, after):
return False, '读数不完整(%s -> %s), 本次未做比对' % (before, after) return False, '读数不完整(%s -> %s), 本次未做比对' % (before, after)
if before == after: if before == after:
return False, '前后读数一致 %s' % after return False, '前后读数一致 %s' % after
if after in LUNACY_KNOWN_READINGS: if before in LUNACY_KNOWN_READINGS and after in LUNACY_KNOWN_READINGS:
return False, ('前后读法不同(%s -> %s), 但 %s 是已知读法之一, 判为 OCR 抖动, ' return False, ('前后均为已知读法(%s -> %s), 可能为 OCR 抖动, 不单凭此判定消费'
'不算消费' % (before, after, after)) % (before, after))
return True, ('读数 %s -> %s, 而 %s 不在已知读法 %s 里, 需人工核查' return True, ('读数 %s -> %s, 前后至少一项不在已知读法 %s 里, 需人工核查'
% (before, after, after, list(LUNACY_KNOWN_READINGS))) % (before, after, list(LUNACY_KNOWN_READINGS)))
def read_owned(retries=3, pause=2.0): def read_owned(retries=3, pause=2.0):
@@ -638,6 +714,8 @@ def _convert_attempt():
after = read_owned() after = read_owned()
if after is None: if after is None:
return False, '合成后读不到模组数, 无法确认结果(合成前为 %d)' % before, 0 return False, '合成后读不到模组数, 无法确认结果(合成前为 %d)' % before, 0
if after < before:
return False, '模组读数下降(%d -> %d), 无法确认合成结果' % (before, after), 0
if after == before: if after == before:
# 走到这里时调用方已经确认体力 >= 20, 所以"体力不足"不是可能的原因, # 走到这里时调用方已经确认体力 >= 20, 所以"体力不足"不是可能的原因,
# 写进去只会把排查方向带偏。真实原因只有这两种。 # 写进去只会把排查方向带偏。真实原因只有这两种。
@@ -665,6 +743,7 @@ def main(argv=None):
args = ap.parse_args(argv) args = ap.parse_args(argv)
t_start = time.time() t_start = time.time()
_result.clear()
_result.update({'started': time.strftime('%Y-%m-%d %H:%M:%S'), 'steps': []}) _result.update({'started': time.strftime('%Y-%m-%d %H:%M:%S'), 'steps': []})
def done(code, why): def done(code, why):
+3 -9
View File
@@ -5,14 +5,8 @@
# powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -EveryHours 6 # powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -EveryHours 6
# powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Uninstall # powershell -ExecutionPolicy Bypass -File scripts\install_convert_task.ps1 -Uninstall
# #
# 节奏怎么定(体力恢复速度): # 默认每 4 小时检查一次; 是否合成以本轮实际体力读数为准, 不按固定恢复速率推算。
# Limbus 的体力每 6 分钟回 1 点, 上限 126。 # 合成 1 个模块需要 20 点体力。
# 合成 1 个模块要 20 点体力, 所以:
# 每 2 小时 -> 约 20 点 -> 1 个模块
# 每 4 小时 -> 约 40 点 -> 2 个模块(默认)
# 每 6 小时 -> 约 60 点 -> 3 个模块
# 只要不顶到 126 上限就不浪费恢复量, 所以更勤快些也不会亏。
# 4 小时是"每次都能换到东西"和"别老折腾游戏启动"之间的折中。
# #
# 这个任务和 LcMCPDailyCycle 是分开的: 用户明确要求这次不打任何关卡, # 这个任务和 LcMCPDailyCycle 是分开的: 用户明确要求这次不打任何关卡,
# 只挂机攒模块, 所以不能把刷取任务一起打开。 # 只挂机攒模块, 所以不能把刷取任务一起打开。
@@ -42,7 +36,7 @@ if (-not (Test-Path $script)) {
throw "找不到脚本: $script" throw "找不到脚本: $script"
} }
# 以当前用户运行。无人值守要点: 不要勾"只在用户登录时运行", 否则注销后不跑。 # 以当前用户的交互会话运行, 必须保持登录; 注销后没有可供截图/点击的游戏桌面。
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" `
-LogonType Interactive -RunLevel Limited -LogonType Interactive -RunLevel Limited
+4 -3
View File
@@ -6,7 +6,7 @@
# powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1 # powershell -ExecutionPolicy Bypass -File scripts\install_unattended.ps1
# 可选: -At 05:30 每日运行时间。游戏每日重置为 06:00 (KST), 即北京时间 05:00 # 可选: -At 05:30 每日运行时间。游戏每日重置为 06:00 (KST), 即北京时间 05:00
# -EveryHours 2.5 改成"每 N 小时重复一轮"以持续刷取; 0 = 只按 -At 每天一次 # -EveryHours 2.5 改成"每 N 小时重复一轮"以持续刷取; 0 = 只按 -At 每天一次
# 单轮上限 = 60 + 75*Mirror 分钟, 间隔要大于它, 否则会被跳过 # 任务时限包含 daily 45 分钟、每局镜牢 100 分钟、各一次重试及 30 分钟收尾
# -Mirror 1 每轮镜牢局数, 0 = 不打镜牢 # -Mirror 1 每轮镜牢局数, 0 = 不打镜牢
# -Target 34 把队内人格升到的等级 # -Target 34 把队内人格升到的等级
# -Python <路径> 默认 vendor\aalc\.venv\Scripts\pythonw.exe (无窗口, 不抢游戏焦点) # -Python <路径> 默认 vendor\aalc\.venv\Scripts\pythonw.exe (无窗口, 不抢游戏焦点)
@@ -66,8 +66,9 @@ if (-not $NoWatchdog) {
$cycle = Join-Path $PSScriptRoot "auto_cycle.py" $cycle = Join-Path $PSScriptRoot "auto_cycle.py"
$action = New-ScheduledTaskAction -Execute $Python -WorkingDirectory $Repo ` $action = New-ScheduledTaskAction -Execute $Python -WorkingDirectory $Repo `
-Argument "-X utf8 `"$cycle`" --mirror $Mirror --target $Target" -Argument "-X utf8 `"$cycle`" --mirror $Mirror --target $Target"
# 一轮 daily 约 22 分钟, 每局镜牢实测 39~>70 分钟; 超过上限由计划任务强杀 # 与 auto_cycle.py 的 DAILY_TIMEOUT_S / MIRROR_TIMEOUT_S / STALL_RETRIES 对齐。
$limit = New-TimeSpan -Minutes (60 + 75 * [Math]::Max($Mirror, 0)) # 每个任务最多两次尝试, 另留 30 分钟给启动、轮询和升级; 避免外层先杀掉报告进程。
$limit = New-TimeSpan -Minutes (30 + 2 * (45 + 100 * [Math]::Max($Mirror, 0)))
if ($EveryHours -gt 0) { if ($EveryHours -gt 0) {
# 持续刷取: 每 N 小时重复一轮。开始时间取"现在", 装完即进入节奏。 # 持续刷取: 每 N 小时重复一轮。开始时间取"现在", 装完即进入节奏。
# 注意 New-TimeSpan -Hours 的参数是 [int], 传 2.5 会被截断成 2 小时, 所以用 -Minutes。 # 注意 New-TimeSpan -Hours 的参数是 [int], 传 2.5 会被截断成 2 小时, 所以用 -Minutes。
+36 -1
View File
@@ -46,6 +46,12 @@ def text_items(state):
def scene_fingerprint(state): def scene_fingerprint(state):
"""Ignore changing clocks and counters when checking failed confirmations.""" """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) return tuple(item['text'] for item in text_items(state)
if item.get('score', 0) > .93 if item.get('score', 0) > .93
and not re.fullmatch(r'[0-9:.]+', item['text'].replace(' ', ''))) 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 return options
gift_headers = sum(t == '获得E.G.O饰品' for t in texts) 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 ('成捆的符咒','标准负载电池','干巴柴涩鸡胸肉','干松紧致鸡胸肉','快感','雷枝')) core = any(name in combined for name in ('成捆的符咒','标准负载电池','干巴柴涩鸡胸肉','干松紧致鸡胸肉','快感','雷枝'))
if core and '雷枝' not in combined: if core and '雷枝' not in combined:
return options return options
@@ -369,6 +375,8 @@ def candidates(state, previous_battle=False, refresh_used=0):
'action':{'tool':'advance_dialog','args':{'presses':3}}, 'action':{'tool':'advance_dialog','args':{'presses':3}},
'fallback_action':{'tool':'click','args':{'x':item['x']+item['w']//2,'y':item['y']+item['h']//2}}, '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 return options
# Nested confirmation/detail windows override the reward/pack behind them. # Nested confirmation/detail windows override the reward/pack behind them.
modal_question = ('确认' in texts and any('取消' in t for t in texts) 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)] 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): if in_shop and state.get('floor', 1) >= 2 and not state.get('symbol_upgraded', False):
return options return options
if in_shop and state.get('thrill_fusion_due'):
options['requires_analysis']['description'] = '本层商店需检查快感合成:保留核心饰品,按普通/特殊商店预览进行有界尝试;检查完成或材料不足后记录本层已处理,再继续技能替换。'
return options
if in_shop: if in_shop:
pending = 'thrill' if state.get('thrill_pending') else 'thunderbranch' if state.get('thunderbranch_pending') else None pending = 'thrill' if state.get('thrill_pending') else 'thunderbranch' if state.get('thunderbranch_pending') else None
if pending: if pending:
@@ -797,6 +808,21 @@ def acquire_single_instance():
return lambda: kernel.CloseHandle(lease) 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): def main(executor_decider=None):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('config', nargs='?', help='Optional Jev JSON config; omit for execution-model handoff') 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 run = None
recent = [] recent = []
repeats = {} repeats = {}
last_choice = None
consecutive_attempts = 0
context_path = RUNTIME_HOME / 'jev_shop_context.json' context_path = RUNTIME_HOME / 'jev_shop_context.json'
stable_since = time.monotonic() stable_since = time.monotonic()
last_fingerprint = None last_fingerprint = None
@@ -866,11 +894,15 @@ def main(executor_decider=None):
state['battery_obtained'] = context.get('battery_obtained', False) state['battery_obtained'] = context.get('battery_obtained', False)
state['thunderbranch_pending'] = context.get('thunderbranch_pending',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_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) state['claim_requested'] = claim_is_current(run, context)
options = candidates(state, previous_battle, context['refresh_used']) options = candidates(state, previous_battle, context['refresh_used'])
if fingerprint != last_fingerprint: if fingerprint != last_fingerprint:
stable_since = time.monotonic() stable_since = time.monotonic()
last_fingerprint = fingerprint last_fingerprint = fingerprint
repeats.clear()
stable_seconds = round(time.monotonic() - stable_since) stable_seconds = round(time.monotonic() - stable_since)
if stable_seconds > 30: if stable_seconds > 30:
recent.append({'observation':'画面已%d秒没有有效改变,请你判断是否需要主助手排查。' % stable_seconds}) 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) 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: if key not in ('requires_analysis', 'wait', 'battle') and repeats.get((fingerprint, action_id), 0) >= 2:
del options[key] del options[key]
apply_confirmation_retry(options, last_choice, consecutive_attempts)
if len(options) == 2: if len(options) == 2:
unknown_since = unknown_since or time.monotonic() unknown_since = unknown_since or time.monotonic()
else: else:
@@ -964,6 +997,8 @@ def main(executor_decider=None):
repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1 repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1
action_started = time.monotonic() action_started = time.monotonic()
result = execute(bridge, action, deadline=deadline) 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['action_ms'] = round((time.monotonic()-action_started)*1000)
record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S') record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S')
if result.get('stopped'): if result.get('stopped'):
+19
View File
@@ -24,6 +24,8 @@ LABELS = {
'e.g.ogiftsearch':'额外观测', 'eg.dgiftsearch':'额外观测', 'e.g.ogiftsearch':'额外观测', 'eg.dgiftsearch':'额外观测',
'nextfloor':'下一层', 'gotonextfloor':'前往下一层', 'proceedtonextfloor':'前往下一层', 'claim':'领取', 'nextfloor':'下一层', 'gotonextfloor':'前往下一层', 'proceedtonextfloor':'前往下一层', 'claim':'领取',
'additionalhardship':'追加的苦难', 'additionalhardships':'追加的苦难', '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饰品', 'obtaine.g.ogift':'获得E.G.O饰品', 'obtaine.g.ogifts':'获得E.G.O饰品',
'claimrewards':'领取奖励', 'explorationcomplete':'探索完成', 'claimrewards':'领取奖励', 'explorationcomplete':'探索完成',
'explorationcompleted':'探索完成', 'dungeoncomplete':'探索完成', 'explorationcompleted':'探索完成', 'dungeoncomplete':'探索完成',
@@ -40,7 +42,17 @@ def normalize(state):
raw = item['text'] raw = item['text']
compact = re.sub(r'\s+', '', raw).lower().lstrip('×x') compact = re.sub(r'\s+', '', raw).lower().lstrip('×x')
compact = compact.replace('e.g.0', 'e.g.o') compact = compact.replace('e.g.0', 'e.g.o')
compact = re.sub(r'fl[o0]{2}r', 'floor', compact)
text = LABELS.get(compact, raw) 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' 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 and abs(other['x'] - item['x']) < 80 and 0 < other['y'] - item['y'] < 70
for other in source_items): for other in source_items):
@@ -93,6 +105,13 @@ def normalize(state):
('Heathcliff','希斯克利夫'), ('Outis','奥提斯'), ('Gregor','格里高尔'), ('Heathcliff','希斯克利夫'), ('Outis','奥提斯'), ('Gregor','格里高尔'),
('Ryoshu','良秀'), ('Faust','浮士德')]: ('Ryoshu','良秀'), ('Faust','浮士德')]:
text = text.replace(english, chinese) 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: if text != raw:
item['original_text'] = raw item['original_text'] = raw
item['text'] = text item['text'] = text
+2 -2
View File
@@ -33,9 +33,9 @@ BASE_W, BASE_H = 1600, 900
_scale = None _scale = None
def run(cmd): def run(cmd, *, check=False):
r = subprocess.run(cmd, capture_output=True, text=True, r = subprocess.run(cmd, capture_output=True, text=True,
encoding='utf-8', errors='replace', **NO_WINDOW) encoding='utf-8', errors='replace', check=check, **NO_WINDOW)
return (r.stdout or '') + (r.stderr or '') return (r.stdout or '') + (r.stderr or '')
+13 -5
View File
@@ -411,6 +411,7 @@ def cmd_progress(target=34, uptie=True, max_try=6):
if not team: if not team:
print('未找到队内(SELECTED)人格') print('未找到队内(SELECTED)人格')
return 1 return 1
unreadable = 0
for ci, ri, cx, ry, ocr_lvl, sel, nm in team[:max_try]: for ci, ri, cx, ry, ocr_lvl, sel, nm in team[:max_try]:
print('--- 候选 col=%d row=%d (网格读作 Lv.%s %s)' % (ci, ri, ocr_lvl, nm)) print('--- 候选 col=%d row=%d (网格读作 Lv.%s %s)' % (ci, ri, ocr_lvl, nm))
# 长按前先清残留弹窗: 一张卡没关干净, 后面每张都会被挡住 # 长按前先清残留弹窗: 一张卡没关干净, 后面每张都会被挡住
@@ -422,13 +423,16 @@ def cmd_progress(target=34, uptie=True, max_try=6):
txt = screen_text(items) txt = screen_text(items)
if not detail_page_open(txt): if not detail_page_open(txt):
print(' 长按未打开详情, 跳过') print(' 长按未打开详情, 跳过')
unreadable += 1
continue continue
true_lvl, true_name, _ = read_detail(hint=ocr_lvl) true_lvl, true_name, _ = read_detail(hint=ocr_lvl)
print(' 详情页: %s 真实等级=%s' % (true_name, true_lvl)) print(' 详情页: %s 真实等级=%s' % (true_name, true_lvl))
if true_lvl is None: if true_lvl is None:
# 详情页读不到时退回网格值——网格会误读, 但总比跳过整张卡好 print(' 详情页读不到等级, 无法确认是否需要升级, 跳过')
print(' 详情页读不到等级, 退回网格值 Lv.%s' % ocr_lvl) unreadable += 1
true_lvl = ocr_lvl click(*BACK)
time.sleep(2.5)
continue
if true_lvl >= target: if true_lvl >= target:
print(' 已达目标 Lv.%d, 跳过' % target) print(' 已达目标 Lv.%d, 跳过' % target)
click(*BACK) click(*BACK)
@@ -436,6 +440,7 @@ def cmd_progress(target=34, uptie=True, max_try=6):
continue continue
ok, desc = do_level_up(hint=true_lvl) ok, desc = do_level_up(hint=true_lvl)
print(' 升级: %s (%s)' % ('OK' if ok else ('SKIP' if ok is None else 'FAIL'), desc)) print(' 升级: %s (%s)' % ('OK' if ok else ('SKIP' if ok is None else 'FAIL'), desc))
ok2 = True
if uptie: if uptie:
ok2, desc2 = do_uptie() ok2, desc2 = do_uptie()
print(' 同步: %s (%s)' % ('OK' if ok2 else 'FAIL', desc2)) print(' 同步: %s (%s)' % ('OK' if ok2 else 'FAIL', desc2))
@@ -446,8 +451,11 @@ def cmd_progress(target=34, uptie=True, max_try=6):
if not ('IDENTITIES' in txt and 'Facades' in txt): if not ('IDENTITIES' in txt and 'Facades' in txt):
click(*BACK) click(*BACK)
time.sleep(2.5) time.sleep(2.5)
return 0 if ok else 1 return 0 if ok and ok2 else 1
print('前 %d 个候选都不需要升级或无法读取' % max_try) if unreadable:
print('FAIL: %d 个候选未能核实详情等级, 不能判定为无需升级' % unreadable)
return 1
print('已核实的 %d 个候选均达到目标等级, 无需升级' % len(team[:max_try]))
return 0 return 0
+155 -11
View File
@@ -1,5 +1,7 @@
from pathlib import Path from pathlib import Path
import json
import sys import sys
import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
@@ -54,6 +56,7 @@ class RunAalcTest(unittest.TestCase):
def run_aalc(self, mcp, **kw): def run_aalc(self, mcp, **kw):
with mock.patch.object(auto_cycle, 'probe', mcp.probe), \ with mock.patch.object(auto_cycle, 'probe', mcp.probe), \
mock.patch.object(auto_cycle, 'blocking_module_modal', return_value=None), \
mock.patch.object(auto_cycle, 'log', lambda m: None): mock.patch.object(auto_cycle, 'log', lambda m: None):
return auto_cycle.run_aalc('daily', {}, 3600, sleep=lambda s: None, **kw) return auto_cycle.run_aalc('daily', {}, 3600, sleep=lambda s: None, **kw)
@@ -62,9 +65,12 @@ class RunAalcTest(unittest.TestCase):
clock = FakeTime(step) clock = FakeTime(step)
patches = [mock.patch.object(auto_cycle, 'probe', mcp.probe), patches = [mock.patch.object(auto_cycle, 'probe', mcp.probe),
mock.patch.object(auto_cycle, 'log', lambda m: None), mock.patch.object(auto_cycle, 'log', lambda m: None),
mock.patch.object(auto_cycle.time, 'time', clock.time)] mock.patch.object(auto_cycle.time, 'time', clock.time),
mock.patch.object(auto_cycle, 'clear_blocking_modal', return_value='已发送 Cancel')]
if clear is not None: if clear is not None:
patches.append(mock.patch.object(auto_cycle, 'clear_blocking_modal', clear)) patches.append(mock.patch.object(auto_cycle, 'blocking_module_modal', clear))
else:
patches.append(mock.patch.object(auto_cycle, 'blocking_module_modal', return_value=None))
for p in patches: for p in patches:
p.start() p.start()
try: try:
@@ -108,11 +114,11 @@ class RunAalcTest(unittest.TestCase):
self.assertFalse(ok) self.assertFalse(ok)
self.assertEqual(info, 'RESOURCE_OUT') self.assertEqual(info, 'RESOURCE_OUT')
self.assertFalse(stalled) self.assertFalse(stalled)
# 只清了 RESOURCE_OUT_LIMIT 次就停, 而不是一路点到超时 # 连续观察到 RESOURCE_OUT_LIMIT 次就停, 不在任务运行时点击
self.assertIn('stop_task', self.tools(mcp)) self.assertIn('stop_task', self.tools(mcp))
def test_occasional_modal_does_not_end_the_task(self): def test_occasional_modal_does_not_end_the_task(self):
"""偶发一次模态框不该收工 —— 点掉继续跑才对。""" """偶发一次模态框不该收工, 继续观察任务。"""
seq = ['x'] seq = ['x']
mcp = FakeMcp() mcp = FakeMcp()
mcp.current = [RUNNING] mcp.current = [RUNNING]
@@ -122,6 +128,33 @@ class RunAalcTest(unittest.TestCase):
# 跑到超时收工, 而不是被当成资源耗尽 # 跑到超时收工, 而不是被当成资源耗尽
self.assertIn('超时', info) self.assertIn('超时', info)
def test_separate_shortage_sightings_are_not_consecutive(self):
seq = iter(['x', None, 'x', None, 'x', None])
mcp = FakeMcp()
mcp.current = [RUNNING] * 6 + [DONE]
ok, info, _ = self.poll(mcp, 3600, clear=lambda: next(seq))
self.assertTrue(ok, info)
self.assertNotIn('stop_task', self.tools(mcp))
def test_failed_stop_prevents_retry(self):
mcp = FakeMcp([STALL, STALL], [DONE])
original = mcp.probe
def probe(tool, args=None):
result = original(tool, args)
return {'ok': False, 'error': '进程未退出'} if tool == 'stop_task' else result
mcp.probe = probe
with self.assertRaisesRegex(RuntimeError, '停止 AALC 任务失败'):
self.run_aalc(mcp)
self.assertEqual(self.tools(mcp), ['run_task', 'stop_task'])
def test_status_error_stops_the_task_before_reporting_failure(self):
mcp = FakeMcp([{'ok': False, 'error': '连接中断'}])
with self.assertRaisesRegex(RuntimeError, '无法读取任务状态'):
self.run_aalc(mcp)
self.assertEqual(self.tools(mcp), ['run_task', 'stop_task'])
def test_preflight_failure_is_not_retried(self): def test_preflight_failure_is_not_retried(self):
failed = {'state': 'failed', 'exit_code': 3, failed = {'state': 'failed', 'exit_code': 3,
'errors': ['[ERROR] [lc_mcp] preflight: 队伍 1 的 sinner_order 没有罪人']} 'errors': ['[ERROR] [lc_mcp] preflight: 队伍 1 的 sinner_order 没有罪人']}
@@ -131,6 +164,35 @@ class RunAalcTest(unittest.TestCase):
self.assertIn('preflight', info) self.assertIn('preflight', info)
self.assertEqual(self.tools(mcp), ['run_task']) self.assertEqual(self.tools(mcp), ['run_task'])
def test_user_stop_never_retries(self):
for status in ({'state': 'stopped', 'exit_code': 130},
{'state': 'stopped'}, {'state': 'failed', 'exit_code': 130}):
mcp = FakeMcp([status], [DONE])
with self.subTest(status=status), self.assertRaises(auto_cycle.UserAborted):
self.run_aalc(mcp)
self.assertEqual(self.tools(mcp), ['run_task'])
def test_mirror_emergency_stop_ends_cycle_before_upgrade_or_navigation(self):
mcp = FakeMcp([DONE], [{'state': 'stopped', 'exit_code': 130}])
poll = auto_cycle.poll_task
with tempfile.TemporaryDirectory() as tmp:
with mock.patch.object(auto_cycle, 'probe', mcp.probe), \
mock.patch.object(auto_cycle, 'poll_task',
side_effect=lambda t, s, **kw: poll(t, s, sleep=lambda _: None)), \
mock.patch.object(auto_cycle, 'lunacy_guard', return_value=(True, 'ok')), \
mock.patch.object(auto_cycle, 'ensure_team1', return_value=True), \
mock.patch.object(auto_cycle, 'goto_identities') as navigate, \
mock.patch.object(auto_cycle, 'run') as upgrade, \
mock.patch('builtins.print'):
code = auto_cycle.main(['--mirror', '1', '--report-dir', tmp])
report = json.loads(next(Path(tmp).glob('cycle_*.json')).read_text(encoding='utf-8'))
self.assertEqual(code, 130)
self.assertFalse(report['ok'])
self.assertIn('用户停止', report['result'])
navigate.assert_not_called()
upgrade.assert_not_called()
self.assertEqual(self.tools(mcp), ['run_task', 'run_task'])
def test_exit_zero_with_errors_is_failure(self): def test_exit_zero_with_errors_is_failure(self):
mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])]) mcp = FakeMcp([dict(DONE, errors=['[ERROR] 超出最大尝试次数,未能进入战斗'])])
ok, info = self.run_aalc(mcp) ok, info = self.run_aalc(mcp)
@@ -177,9 +239,8 @@ class BlockingModalTest(unittest.TestCase):
2026-10-13 实测: 模组不足时游戏弹 2026-10-13 实测: 模组不足时游戏弹
"You don't have enough Enkephalin Modules. / Would you like to go assemble some?" "You don't have enough Enkephalin Modules. / Would you like to go assemble some?"
AALC 的 Luxcavation 流程不认它, 一直在后面点被挡住的 Enter 按钮, 每次卡满 AALC 的 Luxcavation 流程不认它, 一直在后面点被挡住的 Enter 按钮。
10 分钟才被 no_progress 判据救回来。清道夫点 Cancel 之后 AALC 就能继续降级 连续观察到缺资源后先停止任务, 再重新识别并点 Cancel。
试下一关。
""" """
MODAL = [{'text': "You don't have enough Enkephalin Modules.", 'x': 554, 'y': 404, 'w': 460, 'h': 24}, MODAL = [{'text': "You don't have enough Enkephalin Modules.", 'x': 554, 'y': 404, 'w': 460, 'h': 24},
@@ -190,7 +251,8 @@ class BlockingModalTest(unittest.TestCase):
def test_clicks_cancel_centre(self): def test_clicks_cancel_centre(self):
clicked = [] clicked = []
with mock.patch.object(auto_cycle, 'items', lambda: list(self.MODAL)), \ with mock.patch.object(auto_cycle, 'items', lambda: list(self.MODAL)), \
mock.patch.object(auto_cycle, 'click', lambda x, y: clicked.append((x, y))): mock.patch.object(auto_cycle, 'click',
lambda x, y: (clicked.append((x, y)) or {'ok': True})):
msg = auto_cycle.clear_blocking_modal() msg = auto_cycle.clear_blocking_modal()
self.assertIn('Cancel', msg) self.assertIn('Cancel', msg)
# 点的是识别框中心, 不是左上角 —— 实测点左上角常常落空 # 点的是识别框中心, 不是左上角 —— 实测点左上角常常落空
@@ -201,7 +263,8 @@ class BlockingModalTest(unittest.TestCase):
grid = [{'text': 'TEAMS#1', 'x': 100, 'y': 300}, grid = [{'text': 'TEAMS#1', 'x': 100, 'y': 300},
{'text': 'IDENTITIES', 'x': 200, 'y': 300}] {'text': 'IDENTITIES', 'x': 200, 'y': 300}]
with mock.patch.object(auto_cycle, 'items', lambda: grid), \ with mock.patch.object(auto_cycle, 'items', lambda: grid), \
mock.patch.object(auto_cycle, 'click', lambda x, y: clicked.append((x, y))): mock.patch.object(auto_cycle, 'click',
lambda x, y: (clicked.append((x, y)) or {'ok': True})):
self.assertIsNone(auto_cycle.clear_blocking_modal()) self.assertIsNone(auto_cycle.clear_blocking_modal())
self.assertEqual(clicked, []) self.assertEqual(clicked, [])
@@ -211,13 +274,77 @@ class BlockingModalTest(unittest.TestCase):
{'text': 'Cancel', 'x': 30, 'y': 40, 'w': 10, 'h': 10}] {'text': 'Cancel', 'x': 30, 'y': 40, 'w': 10, 'h': 10}]
clicked = [] clicked = []
with mock.patch.object(auto_cycle, 'items', lambda: modal), \ with mock.patch.object(auto_cycle, 'items', lambda: modal), \
mock.patch.object(auto_cycle, 'click', lambda x, y: clicked.append((x, y))): mock.patch.object(auto_cycle, 'click',
lambda x, y: (clicked.append((x, y)) or {'ok': True})):
self.assertIsNotNone(auto_cycle.clear_blocking_modal()) self.assertIsNotNone(auto_cycle.clear_blocking_modal())
self.assertEqual(clicked, [(35, 45)]) self.assertEqual(clicked, [(35, 45)])
def test_rejected_click_is_not_reported_as_cleared(self):
with mock.patch.object(auto_cycle, 'items', return_value=self.MODAL), \
mock.patch.object(auto_cycle, 'click', return_value={'ok': False, 'error': '先 stop_task'}):
with self.assertRaisesRegex(RuntimeError, '先 stop_task'):
auto_cycle.clear_blocking_modal()
def test_real_protocol_receives_cancel_only_after_task_stops(self):
# 使用真实 Server 的输入互斥逻辑, 避免假 click 掩盖“运行中点击被拒绝”。
from lc_mcp.fake_engine import FakeEngine
from lc_mcp.protocol import Server
runner = mock.Mock()
runner.info = {'task': 'daily'}
runner.running.return_value = True
runner.status.return_value = {'ok': True, 'state': 'running'}
def stop():
runner.running.return_value = False
return {'ok': True, 'state': 'stopped'}
runner.stop.side_effect = stop
engine = FakeEngine(frames=[self.MODAL])
server = Server(engine, runner)
click_states = []
def click(x, y):
click_states.append(runner.running())
return server.call_tool('click', {'x': x, 'y': y})
with mock.patch.object(auto_cycle, 'probe', lambda tool, args=None: server.call_tool(tool, args or {})), \
mock.patch.object(auto_cycle, 'items', lambda: server.call_tool('get_state', {})['items']), \
mock.patch.object(auto_cycle, 'click', click), \
mock.patch.object(auto_cycle, 'log'), \
mock.patch.object(auto_cycle.time, 'time', FakeTime().time):
ok, info, stalled = auto_cycle.poll_task('daily', 3600, sleep=lambda s: None)
self.assertEqual((ok, info, stalled), (False, 'RESOURCE_OUT', False))
self.assertEqual(click_states, [False])
self.assertEqual(engine.actions, [('click', 637, 612, 1)])
runner.stop.assert_called_once()
class CycleReportTest(unittest.TestCase):
def test_crashed_levelup_is_a_failed_report_with_diagnostics(self):
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp, 'broken_levelup.py')
script.write_text('raise RuntimeError("levelup crashed")\n', encoding='utf-8')
with mock.patch.multiple(auto_cycle, PY=sys.executable, LEVELUP=str(script)), \
mock.patch.object(auto_cycle, 'lunacy_guard', return_value=(True, '读数一致')), \
mock.patch.object(auto_cycle, 'ensure_team1', return_value=True), \
mock.patch.object(auto_cycle, 'run_aalc', return_value=(True, '已完成')), \
mock.patch.object(auto_cycle, 'goto_identities', return_value=True), \
mock.patch.object(auto_cycle, 'report_grid', return_value='grid'), \
mock.patch.object(auto_cycle.time, 'sleep'), \
mock.patch('builtins.print'):
code = auto_cycle.main(['--report-dir', tmp])
report = json.loads(next(Path(tmp).glob('cycle_*.json')).read_text(encoding='utf-8'))
output = next(Path(tmp).glob('cycle_*.log')).read_text(encoding='utf-8')
self.assertEqual(code, 1)
self.assertFalse(report['ok'])
self.assertIn('levelup crashed', output)
self.assertNotIn('无需升级', output)
self.assertIsNone(auto_cycle._log_file)
class LunacyReadTest(unittest.TestCase): class LunacyReadTest(unittest.TestCase):
"""狂气校验是"不许消费"的唯一防线, 读不到就是没校验, 所以要重试。 """狂气 OCR 是辅助核查, 读不到就是没校验, 所以要重试。
2026-10-13 实测更麻烦的一种情况: 同一个画面上 OCR 会给出**两个不同的值** 2026-10-13 实测更麻烦的一种情况: 同一个画面上 OCR 会给出**两个不同的值**
(放大 6 倍肉眼确认余额是 6388, 而连读 5 次得到 6388 四次、8859 一次)。 (放大 6 倍肉眼确认余额是 6388, 而连读 5 次得到 6388 四次、8859 一次)。
@@ -250,6 +377,23 @@ class LunacyReadTest(unittest.TestCase):
mock.patch.object(auto_cycle.time, 'sleep', lambda s: None): mock.patch.object(auto_cycle.time, 'sleep', lambda s: None):
self.assertEqual(auto_cycle.read_lunacy(), 6388) self.assertEqual(auto_cycle.read_lunacy(), 6388)
def test_first_pair_does_not_override_later_majority(self):
with mock.patch.object(auto_cycle, 'items', self._frames([8859, 8859, 6388, 6388, 6388])), \
mock.patch.object(auto_cycle.time, 'sleep'):
self.assertEqual(auto_cycle.read_lunacy(), 6388)
def test_tied_readings_are_unknown(self):
with mock.patch.object(auto_cycle, 'items', self._frames([8859, 8859, 6388, 6388, None])), \
mock.patch.object(auto_cycle.time, 'sleep'):
self.assertIsNone(auto_cycle.read_lunacy())
def test_truncated_label_and_low_balance_are_read(self):
frame = [{'text': 'UNACY', 'x': 671, 'y': 795},
{'text': '0', 'x': 664, 'y': 823}]
with mock.patch.object(auto_cycle, 'items', return_value=frame), \
mock.patch.object(auto_cycle.time, 'sleep'):
self.assertEqual(auto_cycle.read_lunacy(), 0)
def test_retries_until_the_label_shows_up(self): def test_retries_until_the_label_shows_up(self):
with mock.patch.object(auto_cycle, 'items', self._frames([None, None, 5864, 5864, 5864])), \ with mock.patch.object(auto_cycle, 'items', self._frames([None, None, 5864, 5864, 5864])), \
mock.patch.object(auto_cycle.time, 'sleep', lambda s: None): mock.patch.object(auto_cycle.time, 'sleep', lambda s: None):
+103 -1
View File
@@ -48,7 +48,109 @@ class BackgroundRestoreTest(unittest.TestCase):
engine.click(100, 200) engine.click(100, 200)
engine._restore_background_position.assert_called_once_with((20, 30)) engine._restore_background_position.assert_called_once_with((20, 30))
engine.auto.input_handler.set_mouse_pos.assert_not_called() 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): def test_restore_uses_noactivate_and_preserves_foreground(self):
gui = mock.Mock() gui = mock.Mock()
+16
View File
@@ -1,5 +1,6 @@
"""Controller lifecycle and battle regressions using mocked MCP only.""" """Controller lifecycle and battle regressions using mocked MCP only."""
import contextlib import contextlib
import copy
import ctypes import ctypes
import io import io
import json import json
@@ -154,6 +155,21 @@ class AgentRuntimeTest(unittest.TestCase):
self.assertTrue(result['stopped']) self.assertTrue(result['stopped'])
bridge.call.assert_not_called() 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): def test_close_error_still_releases_controller_mutex(self):
bridge = mock.Mock() bridge = mock.Mock()
bridge.call.return_value = {'ok': True, 'items': []} bridge.call.return_value = {'ok': True, 'items': []}
+120 -5
View File
@@ -131,11 +131,7 @@ class ReadEnkephalinTest(QuietLogMixin, unittest.TestCase):
class LunacyReadTest(QuietLogMixin, unittest.TestCase): class LunacyReadTest(QuietLogMixin, unittest.TestCase):
"""狂气数字是像素艺术字, OCR 会误读(实测 6636 读成 9699)。 """狂气数字会有多种 OCR 误读; 同帧取数、多帧投票仍只提供核查线索。"""
所以脚本不对绝对值下结论, 只做**前后相对比对**: 同一个画面同一套字体,
误读方式一致, 两次读数不同就说明数字真的变了。
"""
def _frames(self, values): def _frames(self, values):
seq = list(values) seq = list(values)
@@ -156,6 +152,25 @@ class LunacyReadTest(QuietLogMixin, unittest.TestCase):
mock.patch.object(cm.time, 'sleep', lambda s: None): mock.patch.object(cm.time, 'sleep', lambda s: None):
self.assertIsNone(cm.read_lunacy()) self.assertIsNone(cm.read_lunacy())
def test_first_pair_does_not_override_later_majority(self):
with mock.patch.object(cm, 'items', self._frames([8859, 8859, 6388, 6388, 6388])), \
mock.patch.object(cm.time, 'sleep'):
self.assertEqual(cm.read_lunacy(), 6388)
def test_label_and_balance_must_come_from_the_same_frame(self):
# 数字和标签从未同时出现, 跨帧拼接会伪造一个有效读数。
frames = [[{'text': '9999', 'x': 664, 'y': 823}],
[{'text': 'LUNACY', 'x': 670, 'y': 795}]] * 5
with mock.patch.object(cm, 'items', side_effect=frames) as sample, \
mock.patch.object(cm.time, 'sleep'):
self.assertIsNone(cm.read_lunacy())
self.assertEqual(sample.call_count, 5)
def test_tied_readings_are_unknown(self):
with mock.patch.object(cm, 'items', self._frames([8859, 8859, 6388, 6388, 1000])), \
mock.patch.object(cm.time, 'sleep'):
self.assertIsNone(cm.read_lunacy())
class EnkephalinGateTest(QuietLogMixin, unittest.TestCase): class EnkephalinGateTest(QuietLogMixin, unittest.TestCase):
"""体力读数是"要不要合成"的闸门, 读不到时不能贸然去点合成。 """体力读数是"要不要合成"的闸门, 读不到时不能贸然去点合成。
@@ -305,6 +320,10 @@ class LunacyVerdictTest(unittest.TestCase):
suspicious2, _ = cm.lunacy_verdict(4000, 3000) suspicious2, _ = cm.lunacy_verdict(4000, 3000)
self.assertTrue(suspicious2) self.assertTrue(suspicious2)
def test_new_balance_must_not_be_silently_folded_into_old_readings(self):
suspicious, _ = cm.lunacy_verdict(10000, 6636)
self.assertTrue(suspicious)
class LunacyFalseAlarmTest(QuietLogMixin, unittest.TestCase): class LunacyFalseAlarmTest(QuietLogMixin, unittest.TestCase):
"""整轮跑下来: 已知读法抖动不该让这一轮 FAIL。""" """整轮跑下来: 已知读法抖动不该让这一轮 FAIL。"""
@@ -388,6 +407,13 @@ class ConvertAttemptVerifiedTest(QuietLogMixin, unittest.TestCase):
self.assertFalse(ok) self.assertFalse(ok)
self.assertIn('没变', info) self.assertIn('没变', info)
def test_decrease_is_not_a_successful_negative_conversion(self):
seq = [35]
ok, info, got = self._attempt(lambda: seq.pop(0) if seq else 33)
self.assertFalse(ok)
self.assertEqual(got, 0)
self.assertIn('读数下降', info)
def test_unchanged_message_does_not_blame_enkephalin(self): def test_unchanged_message_does_not_blame_enkephalin(self):
"""走到这一步时体力 >= 20 已经确认过, 所以"体力不足"不可能是原因。 """走到这一步时体力 >= 20 已经确认过, 所以"体力不足"不可能是原因。
@@ -601,6 +627,14 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
self.assertEqual(code, 0) self.assertEqual(code, 0)
self.assertEqual(closed, [], '--keep-game 时不该关游戏') self.assertEqual(closed, [], '--keep-game 时不该关游戏')
def test_a_skipped_run_does_not_reuse_previous_lunacy_result(self):
cm._result.update(lunacy_after=9699, lunacy_checked=True, converted=True)
code, _, _ = self._main([]) # 体力不足, 不合成也不做后读。
self.assertEqual(code, 0)
self.assertNotIn('lunacy_after', cm._result)
self.assertNotIn('lunacy_checked', cm._result)
self.assertFalse(cm._result['converted'])
def test_report_is_written_with_the_expected_fields(self): def test_report_is_written_with_the_expected_fields(self):
"""报告字段要齐全 —— 值守就靠 lunacy_* 和 converted 那几项下结论。""" """报告字段要齐全 —— 值守就靠 lunacy_* 和 converted 那几项下结论。"""
import json import json
@@ -635,6 +669,87 @@ class CliRoutingTest(QuietLogMixin, unittest.TestCase):
self.assertEqual(code, 0) 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): class SessionTableTest(QuietLogMixin, unittest.TestCase):
"""解析 `query session` —— 用来区分"截不到图"到底是哪种情况。 """解析 `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':'当前事件选项:按下按钮;结果:选择后获得破裂饰品'} options['event_2']={'description':'当前事件选项:按下按钮;结果:选择后获得破裂饰品'}
self.assertEqual(agent.fixed_fallback(options),'event_2') 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): def test_sinner_very_high_precedes_high_and_generic_gold(self):
options={'sinner_1':{'description':'预计成功率高'}, options={'sinner_1':{'description':'预计成功率高'},
'sinner_2':{'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()
+43
View File
@@ -674,6 +674,49 @@ class TaskErrorSurfaceTest(unittest.TestCase):
self.assertEqual(status['state'], 'succeeded') self.assertEqual(status['state'], 'succeeded')
self.assertNotIn('errors', status) self.assertNotIn('errors', status)
def test_early_battle_error_survives_later_debug_output(self):
# AALC 会在一场战斗失败后继续执行, 报错可能已不在最后 400 行/64 KiB。
child = ('print("[ERROR] 超出最大尝试次数,未能进入战斗")\n'
'for _ in range(5000): print("[DEBUG] 后续正常输出")\n'
'print("[lc_mcp] task daily done")\n')
with tempfile.TemporaryDirectory() as d:
runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', child])
self.addCleanup(runner.stop)
self.assertTrue(runner.start('daily', {})['ok'])
runner.proc.wait(timeout=15)
status = runner.status(lines=1)
self.assertGreater(os.path.getsize(status['log']), 64 * 1024)
self.assertEqual((status['state'], status['exit_code']), ('succeeded', 0))
self.assertEqual(status['log_tail'], ['[lc_mcp] task daily done'])
self.assertIn('未能进入战斗', status.get('errors', [''])[-1])
def test_full_scan_keeps_only_last_three_errors(self):
from lc_mcp.tasks import log_errors
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, 'task.log')
with open(path, 'w', encoding='utf-8') as f:
for n in range(5):
f.write('[ERROR] problem %d\n' % n)
f.write('[DEBUG] running\n' * 500)
f.write('Traceback (most recent call last):\n')
f.write('[DEBUG] cleanup\n' * 500)
self.assertEqual(log_errors(path), ['[ERROR] problem 3', '[ERROR] problem 4',
'Traceback (most recent call last):'])
def test_finished_result_survives_log_removal_and_resets_for_next_run(self):
with tempfile.TemporaryDirectory() as d:
runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', self.CHILD])
self.addCleanup(runner.stop)
runner.start('daily', {})
runner.proc.wait(timeout=15)
first = runner.status()
os.remove(first['log'])
self.assertEqual(runner.status()['errors'], first['errors'])
runner.argv_factory = lambda t, p: [sys.executable, '-c', 'print("clean run")']
runner.start('reward', {})
runner.proc.wait(timeout=15)
self.assertNotIn('errors', runner.status())
class TaskStallSurfaceTest(unittest.TestCase): class TaskStallSurfaceTest(unittest.TestCase):
"""空队伍卡死时进程健在、日志无报错, 只有编队人数检查在刷屏。""" """空队伍卡死时进程健在、日志无报错, 只有编队人数检查在刷屏。"""
+35
View File
@@ -87,6 +87,41 @@ class EnglishMirrorBoundaryTest(unittest.TestCase):
self.assertNotEqual(agent.scene_fingerprint(observation('00:00:43:02')), self.assertNotEqual(agent.scene_fingerprint(observation('00:00:43:02')),
agent.scene_fingerprint(observation('00:00:43:02', 'Commence'))) 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): def test_commence_and_split_sinner_header_reach_judgement_boundary(self):
state = {'screen': {'w': 1920, 'h': 1080}, 'items': [ state = {'screen': {'w': 1920, 'h': 1080}, 'items': [
{'text': text, 'x': 1200, 'y': y, 'w': 200, 'h': 40, 'score': 1} {'text': text, 'x': 1200, 'y': y, 'w': 200, 'h': 40, 'score': 1}
+34
View File
@@ -46,6 +46,40 @@ class ScaleTest(unittest.TestCase):
self.assertEqual(calls, [('get_state', None), ('click', {'x': 120, 'y': 120, 'times': 1})]) self.assertEqual(calls, [('get_state', None), ('click', {'x': 120, 'y': 120, 'times': 1})])
class ProgressResultTest(unittest.TestCase):
def run_progress(self, detail=True, level=40, uptie=True):
card = (0, 0, 300, 400, 40, True, 'identity')
with mock.patch.object(levelup, 'state', return_value={'items': []}), \
mock.patch.object(levelup, 'scan_grid', return_value=[card]), \
mock.patch.object(levelup, 'dismiss_modal', return_value=True), \
mock.patch.object(levelup, 'long_press'), \
mock.patch.object(levelup, 'click'), \
mock.patch.object(levelup, 'detail_page_open', return_value=detail), \
mock.patch.object(levelup, 'read_detail', return_value=(level, 'identity', None)), \
mock.patch.object(levelup, 'do_level_up', return_value=(True, '等级增加')) as upgrade, \
mock.patch.object(levelup, 'do_uptie', return_value=(uptie, '同步结果')), \
mock.patch.object(levelup.time, 'sleep'), \
mock.patch('builtins.print'):
code = levelup.cmd_progress(target=34)
return code, upgrade.call_count
def test_unopened_details_are_not_a_successful_noop(self):
self.assertEqual(self.run_progress(detail=False), (1, 0))
def test_unreadable_details_do_not_trust_grid_level(self):
self.assertEqual(self.run_progress(level=None), (1, 0))
def test_verified_max_level_is_a_successful_noop(self):
self.assertEqual(self.run_progress(level=40), (0, 0))
def test_failed_uptie_is_a_failed_command(self):
self.assertEqual(self.run_progress(level=30, uptie=False), (1, 1))
def test_successful_upgrade_and_uptie(self):
self.assertEqual(self.run_progress(level=30), (0, 1))
class Screens: class Screens:
"""按顺序返回预设画面的假 state(), 记录点击。""" """按顺序返回预设画面的假 state(), 记录点击。"""
+23
View File
@@ -9,9 +9,11 @@ AALC 把镜牢入口误认成经验本界面, 把 home/luxcavation_assets.png
修法是加一条与日志内容无关的判据: 里程碑(开始执行/结束执行)多久没前进。 修法是加一条与日志内容无关的判据: 里程碑(开始执行/结束执行)多久没前进。
""" """
import os import os
import gzip
import tempfile import tempfile
import time import time
import unittest import unittest
from pathlib import Path
from lc_mcp import tasks from lc_mcp import tasks
@@ -61,6 +63,13 @@ class NoProgressStall(unittest.TestCase):
]) ])
self.assertNotIn('no_progress', tasks.log_stalls(p)) self.assertNotIn('no_progress', tasks.log_stalls(p))
def test_frozen_log_does_not_freeze_stall_clock(self):
old = tasks.STALL_NO_PROGRESS_S + 120
p = self._make(['[INFO] %s [AALC] 开始执行 一次纽本' % _stamp(old)])
frozen = time.time() - old
os.utime(p, (frozen, frozen))
self.assertIn('no_progress', tasks.log_stalls(p))
def test_no_milestone_at_all_is_not_reported(self): def test_no_milestone_at_all_is_not_reported(self):
"""一条里程碑都没有时不下结论(可能只是还没走到), 避免误杀启动阶段。""" """一条里程碑都没有时不下结论(可能只是还没走到), 避免误杀启动阶段。"""
p = self._make([ p = self._make([
@@ -86,6 +95,20 @@ class NoProgressStall(unittest.TestCase):
self.assertGreater(os.path.getsize(p), 64 * 1024) # 确定超出了 tail() 的 64KB 窗口 self.assertGreater(os.path.getsize(p), 64 * 1024) # 确定超出了 tail() 的 64KB 窗口
self.assertIn('no_progress', tasks.log_stalls(p)) self.assertIn('no_progress', tasks.log_stalls(p))
def test_archived_windows_runs_distinguish_stalled_and_healthy_tasks(self):
root = Path(__file__).resolve().parents[1] / 'docs/feedback/2026-10-13/results/runs'
for name, stalled in [('task_20261013_124337_daily.log.gz', True),
('task_20261013_132845_daily.log.gz', False),
('task_20261013_135050_mirror.log.gz', False)]:
with self.subTest(log=name):
with gzip.open(root / name, 'rt', encoding='utf-8') as f:
lines = f.read().splitlines()
stamp = next(tasks.TIMESTAMP_RE.search(line).group(1)
for line in reversed(lines) if tasks.TIMESTAMP_RE.search(line))
observed_at = time.mktime(time.strptime(stamp, '%Y-%m-%d %H:%M:%S'))
path = self._make(lines)
self.assertEqual('no_progress' in tasks.log_stalls(path, now=observed_at), stalled)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
Vendored
+1 -1