From 6b129ddba3df2cc868f6a368c95129489ae57d53 Mon Sep 17 00:00:00 2001 From: ywsabc2 Date: Tue, 13 Oct 2026 03:03:49 +0000 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A4=8D=E6=A0=B8=E5=8F=91?= =?UTF-8?q?=E7=8E=B0=E7=9A=84=E9=97=AE=E9=A2=98:=20=E5=9D=90=E6=A0=87?= =?UTF-8?q?=E7=BC=A9=E6=94=BE=E3=80=81=E5=8D=87=E7=BA=A7/=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E5=88=A4=E5=AE=9A=E3=80=81=E7=9C=8B=E9=97=A8=E7=8B=97?= =?UTF-8?q?=E8=AF=8A=E6=96=AD=E3=80=81=E5=8D=A1=E6=AD=BB=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts/lc_ui.py: 脚本坐标按 1600x900 书写, OCR 结果与点击/拖动按实际客户区换算; 去掉写死的 D:\lc-mcp 路径 - levelup.py: 升级以详情页等级/经验条变化判定成功; 同步先判断弹窗是否仍在, 无过场时不再多按 ESC、不再盲点取消 - auto_cycle.py: task_status 连续报 stall 即停任务; exit 0 但有 errors 判失败 - tasks.py: 运行中日志尾部"配队人数OCR得到"刷屏时返回 stall 字段 - keep_display.ps1: tscon 改用 -EncodedCommand 并记录退出码; 会话号自动取游戏所在会话 - 更正 10-05 README 选队结论、summary 卡死①统计、PITFALLS 坑 13 根因 Co-Authored-By: Claude Opus 5.5 --- docs/feedback/2026-10-05/PITFALLS.md | 5 + docs/feedback/2026-10-05/README.md | 5 + docs/feedback/2026-10-05/logs/summary.md | 10 +- lc_mcp/protocol.py | 3 +- lc_mcp/tasks.py | 20 +++- scripts/auto_cycle.py | 81 +++++-------- scripts/keep_display.ps1 | 37 ++++-- scripts/lc_ui.py | 96 ++++++++++++++++ scripts/levelup.py | 119 ++++++++----------- tests/test_lc_mcp.py | 36 ++++++ tests/test_levelup.py | 138 +++++++++++++++++++++++ 11 files changed, 412 insertions(+), 138 deletions(-) create mode 100644 scripts/lc_ui.py create mode 100644 tests/test_levelup.py diff --git a/docs/feedback/2026-10-05/PITFALLS.md b/docs/feedback/2026-10-05/PITFALLS.md index 31b7118..5c1d981 100644 --- a/docs/feedback/2026-10-05/PITFALLS.md +++ b/docs/feedback/2026-10-05/PITFALLS.md @@ -305,6 +305,11 @@ Currency Req. [Season8] Heathcliff's Egoshard (Owned:2) **AALC 内置"检测不到窗口就重启游戏"的逻辑**,而且它是用 Steam 命令 启动的。如果用户手动关了游戏,会被它重新拉起来——**看起来像"关不掉"**。 +> **2026-10-13 复核**:`task_20261005_201312_daily` 这一次并不是用户关了游戏。 +> 20:23–20:24 日志里 `点击(1,1)空白位置` 刷了 27 次(防卡死兜底),随后 +> `back_init_menu.py:27: 无法返回主界面,尝试重启游戏`——是 AALC 卡在未知界面后 +> **自己杀掉并重启了游戏**,窗口丢失是结果而不是原因。 + --- ## 坑 14:会话模型——RDP 与自动化**互斥** ★★★★★ diff --git a/docs/feedback/2026-10-05/README.md b/docs/feedback/2026-10-05/README.md index bf18d1d..9611d79 100644 --- a/docs/feedback/2026-10-05/README.md +++ b/docs/feedback/2026-10-05/README.md @@ -55,6 +55,11 @@ probe('drag', {'from_x': x, 'from_y': y, 'to_x': x, 'to_y': y}) ## 二、`select_team_by_order: true` 会静默选错队伍 ★ +> **2026-10-13 更正**:本节"改回按名字查找即修复"的结论**已被推翻**。 +> 同日 16:59 那轮按名字查找时,`TEAMS #1` 子串误匹配到 `TEAMS #10`(空预设), +> 空转 27 分钟。两种选队方式各有失效条件,最终解法是用 Team Code 把 +> TEAMS #1 复制到 #2,让落点无所谓。以 `PITFALLS.md` 坑 2–4 为准。 + **这个坑比看上去严重:它不报错,只是"刷了半天什么也没发生"。** `tasks/teams/team_formation.py` 有两条选队路径: diff --git a/docs/feedback/2026-10-05/logs/summary.md b/docs/feedback/2026-10-05/logs/summary.md index dcf5b85..f823681 100644 --- a/docs/feedback/2026-10-05/logs/summary.md +++ b/docs/feedback/2026-10-05/logs/summary.md @@ -9,11 +9,11 @@ |---|---|---|---|---|---|---| | 150033_daily | ✅ | 0 | 0 | 6 | 12 | 正常 | | 152011_daily | ✅ | 0 | 0 | 6 | 12 | 正常 | -| 154351_daily | — | 0 | 0 | 1 | 2 | **卡死①**:预设列表停在底部,`找不到队伍 # 1` | +| 154351_daily | — | 0 | 242¹ | 1 | 2 | **卡死①**:预设列表停在底部,`找不到队伍 # 1` | | 161735_daily | ✅ | 0 | 0 | 6 | 12 | 加入 `ensure_team1()` 起飞前检查后正常 | | 163949_daily | ✅ | 0 | 0 | 6 | 12 | 正常 | | 165908_daily | — | 0 | **306** | 1 | 0 | **卡死②**:子串 bug 选中空预设 `TEAMS #10`,空转 27 分钟 | -| 173104_daily | — | 0 | 0 | 2 | 2 | 切位置法后手动停止 | +| 173104_daily | — | 0 | 22¹ | 2 | 2 | 切位置法后手动停止 | | 174057_daily | — | 0 | 24 | 1 | 0 | **卡死③**:位置法 off-by-one,落到 `TEAMS #2` | | 174614_daily | — | 0 | 29 | 1 | 0 | 同上(补丁无效,已还原) | | 175842_daily | ✅ | 0 | 0 | 6 | 12 | **Team Code 复制到 #2 之后,卡死彻底消失** | @@ -25,6 +25,10 @@ | 201312_daily | — | **10** | 0 | 3 | 4 | **游戏窗口丢失**,AALC 自行重启了游戏 | | 173724 / 174344 / 174942 / 190424_reward | ✅ | 0 | 0 | 0 | 0 | 恢复用(`reward` 任务内含"返回主界面") | +¹ 2026-10-13 复核补记:这两轮 OCR 把人数读成了 `-4-0/5`,按 `配队人数OCR得到:0/5` +精确匹配会漏掉,原表记为 0。健康轮次里"配队人数OCR得到"这一行一次都不出现, +所以直接数这一行(不看后面的数字)才是可靠的卡死指标;`task_status` 的 `stall` 字段就按此实现。 + **判读要点**:`选队成功=6 且 完成阶段=12` 才是一轮真正跑完 (3 次经验本 + 3 次纽本,每次各含选队与战斗)。 `选队成功` 这一列**会骗人**——卡死②那一轮它也报了 1 次"成功"。 @@ -53,7 +57,7 @@ ```powershell # 单份日志的卡死次数(0/5 出现次数是最灵敏的故障指标) $log = 'task_20261005_165908_daily.log' -(Get-Content $log | Where-Object { $_ -match '配队人数OCR得到:0/5' }).Count +(Get-Content $log | Where-Object { $_ -match '配队人数OCR得到' }).Count # 是否完整跑完(12 = 3经验本 + 3纽本,各含一次编队与战斗) (Get-Content $log | Where-Object { $_ -match '结束执行 一次(经验|纽)本' }).Count diff --git a/lc_mcp/protocol.py b/lc_mcp/protocol.py index eb57984..b3e65ec 100644 --- a/lc_mcp/protocol.py +++ b/lc_mcp/protocol.py @@ -60,7 +60,8 @@ TOOLS = [ 'enkephalin=狂气换体力(times); mirror=镜牢(count 次数)。任务运行期间禁止手动点击类工具'), 'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)}, 'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['task'])}, - {'name': 'task_status', 'description': '查看任务状态(idle/running/succeeded/failed/stopped)和日志尾部', + {'name': 'task_status', 'description': '查看任务状态(idle/running/succeeded/failed/stopped)和日志尾部。' + 'succeeded 也要看 errors; running 时出现 stall 说明 AALC 在空转(如选中空队伍), 应 stop_task', 'inputSchema': _obj({'lines': {'type': 'number', 'default': 30}})}, {'name': 'stop_task', 'description': '强制停止当前任务(杀掉任务进程)', 'inputSchema': _obj()}, ] diff --git a/lc_mcp/tasks.py b/lc_mcp/tasks.py index 5c7fa56..0c56550 100644 --- a/lc_mcp/tasks.py +++ b/lc_mcp/tasks.py @@ -51,6 +51,20 @@ def log_errors(path, limit=3): return hits[-limit:] +# AALC 卡死时不报错、进程健在, 只是反复输出同一类日志。 +# "配队人数OCR得到" 只在编队人数检查失败的重试里打印, 健康运行中一次都不会出现; +# 2026-10-05 的三次空队伍卡死里它分别刷了 242/306/24 次。 +STALL_MARKERS = {'empty_team': '配队人数OCR得到'} +STALL_THRESHOLD = 10 + + +def log_stalls(path): + """统计日志尾部的卡死信号, 达到阈值的返回 {名称: 次数}。""" + lines = tail(path, ERROR_SCAN_LINES) + counts = {name: sum(marker in line for line in lines) for name, marker in STALL_MARKERS.items()} + return {name: n for name, n in counts.items() if n >= STALL_THRESHOLD} + + class TaskRunner: def __init__(self, run_dir, argv_factory=default_argv, keep_logs=20, restore_argv=default_restore_argv): @@ -126,7 +140,11 @@ class TaskRunner: r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'], 'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']), 'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))} - if code is not None: + if code is None: + stalls = log_stalls(self.info['log']) + if stalls: + r['stall'] = stalls + else: r['exit_code'] = code errors = log_errors(self.info['log']) if errors: diff --git a/scripts/auto_cycle.py b/scripts/auto_cycle.py index cafc882..fc2f6ec 100644 --- a/scripts/auto_cycle.py +++ b/scripts/auto_cycle.py @@ -7,17 +7,14 @@ 设计: 只做"一轮",不做无限循环——由外层(goal 轮次)负责重复与判断, 避免无人监督地长时间空转。每轮输出结构化报告供上层核对。 """ -import json import os -import subprocess -import sys import time -PY = r'D:\lc-mcp\vendor\aalc\.venv\Scripts\python.exe' -HERE = r'D:\lc-mcp\scripts' -PROBE = HERE + r'\mcp_probe.py' -LEVELUP = HERE + r'\levelup.py' -LUNACY_BASELINE = os.path.expanduser(r'~\lc_mcp\lunacy_baseline.txt') +from lc_ui import HERE, PY, click, drag, items, keypress, probe, run + +LEVELUP = os.path.join(HERE, 'levelup.py') +# 手动抽卡花掉狂气后, 删掉这个文件重新记基线, 否则每轮都会中止 +LUNACY_BASELINE = os.path.expanduser(os.path.join('~', 'lc_mcp', 'lunacy_baseline.txt')) # 导航 BACK = (85, 75) # 只在 Sinners 内部退层用, 主界面上按它会进剧情 @@ -26,31 +23,8 @@ TAB_ALL_IDENTITIES = (1472, 245) # TEAMS 页 -> All Identities # daily 轮询上限 DAILY_TIMEOUT_S = 45 * 60 - - -def run(cmd): - r = subprocess.run(cmd, capture_output=True, text=True, - encoding='utf-8', errors='replace') - return (r.stdout or '') + (r.stderr or '') - - -def probe(tool, args=None): - cmd = [PY, '-X', 'utf8', PROBE, tool] - if args is not None: - cmd.append(json.dumps(args, ensure_ascii=False)) - out = run(cmd) - for line in reversed(out.strip().splitlines()): - line = line.strip() - if line.startswith('{'): - try: - return json.loads(line) - except json.JSONDecodeError: - continue - return {} - - -def click(x, y): - return probe('click', {'x': int(x), 'y': int(y), 'times': 1}) +# task_status 连续几次报 stall 就判定卡死并停任务(每次轮询间隔 60 秒) +STALL_POLLS = 2 def log(msg): @@ -64,8 +38,8 @@ def goto_identities(): 实测会掉进过场动画, 需要额外恢复。 """ for attempt in range(5): - items = probe('get_state').get('items', []) - txt = ' | '.join(i.get('text', '') for i in items) + its = items() + txt = ' | '.join(i.get('text', '') for i in its) if 'IDENTITIES' in txt and 'Facades' in txt: return True if 'TEAMS #1' in txt or 'SIN COST' in txt or 'All Idensities' in txt: @@ -74,13 +48,13 @@ def goto_identities(): continue if 'LUXCAVATION' in txt.upper() or 'MIRROR' in txt.upper(): # 在副本/关卡菜单里, 先回主界面 - probe('keypress', {'key': 'esc'}) + keypress('esc') time.sleep(2) continue click(*BTN_SINNERS) time.sleep(3.5) - items = probe('get_state').get('items', []) - txt = ' | '.join(i.get('text', '') for i in items) + its = items() + txt = ' | '.join(i.get('text', '') for i in its) return 'IDENTITIES' in txt and 'Facades' in txt @@ -100,8 +74,8 @@ def ensure_team1(): "找不到队伍 # 1" 然后整轮空转。所以每轮开跑前先把列表拉回顶部。 """ for _ in range(5): - items = probe('get_state').get('items', []) - txt = ' | '.join(i.get('text', '') for i in items) + its = items() + txt = ' | '.join(i.get('text', '') for i in its) if on_teams_screen(txt): break if on_grid(txt): @@ -112,8 +86,8 @@ def ensure_team1(): time.sleep(3.5) for _ in range(10): - items = probe('get_state').get('items', []) - cand = [i for i in items + its = items() + cand = [i for i in its if i.get('text', '').strip().replace(' ', '') in ('TEAMS#1', 'TFAMS#1') and i.get('x', 999) < 320] if cand: @@ -122,8 +96,7 @@ def ensure_team1(): time.sleep(2.5) return True # 向下拖拽 = 列表内容下移 = 露出更靠前的预设 - probe('drag', {'from_x': 190, 'from_y': 400, - 'to_x': 190, 'to_y': 700}) + drag(190, 400, 190, 700) time.sleep(2) return False @@ -135,17 +108,25 @@ def run_daily(): return False, 'run_task 失败: %s' % r log('daily 已启动, 开始轮询') t0 = time.time() + stalled = 0 while time.time() - t0 < DAILY_TIMEOUT_S: time.sleep(60) st = probe('task_status', {'lines': 1}) s = st.get('state') + el = int(time.time() - t0) if s != 'running': - el = int(time.time() - t0) log('daily 结束: state=%s elapsed=%ds exit=%s' % (s, el, st.get('exit_code'))) + # AALC 单次战斗失败后仍会 exit 0, succeeded 还要看 errors + if s == 'succeeded' and st.get('errors'): + return False, 'exit 0 但日志有报错: %s' % st['errors'][-1] return s == 'succeeded', 'state=%s elapsed=%ds' % (s, el) - if int(time.time() - t0) % 600 < 60: - log(' ...running %ds' % int(time.time() - t0)) + stalled = stalled + 1 if st.get('stall') else 0 + if stalled >= STALL_POLLS: + probe('stop_task') + return False, '卡死(%s), 已停止任务 elapsed=%ds' % (st['stall'], el) + if el % 600 < 60: + log(' ...running %ds' % el) probe('stop_task') return False, '超时 %ds' % DAILY_TIMEOUT_S @@ -157,16 +138,16 @@ def report_grid(): def read_lunacy(): """从主界面读狂气余额(LUNACY 标签右下方的数字)。读不到返回 None。""" - items = probe('get_state').get('items', []) + its = items() lab = None - for it in items: + for it in its: if 'LUNACY' in it.get('text', '').upper(): lab = it break if not lab: return None best = None - for it in items: + for it in its: t = it.get('text', '').strip() if t.isdigit() and len(t) >= 3: dy = it.get('y', 0) - lab.get('y', 0) diff --git a/scripts/keep_display.ps1 b/scripts/keep_display.ps1 index f8f1cf3..0ae4ba7 100644 --- a/scripts/keep_display.ps1 +++ b/scripts/keep_display.ps1 @@ -9,9 +9,13 @@ # # tscon 需要 SeTcbPrivilege, 普通令牌拿不到, 所以用 -Verb RunAs 提权。 # 本机 ConsentPromptBehaviorAdmin=0(从不通知), 提权静默通过, 不会弹框。 +# +# 会话号默认取游戏进程所在会话, 找不到游戏时取本脚本所在会话(计划任务以 +# 登录用户身份运行, 与桌面同一会话)。重启或重新登录后会话号会变, 不要写死。 param( - [int]$SessionId = 2, + [int]$SessionId = -1, + [string]$Python = "", [string]$LogPath = "$env:USERPROFILE\lc_mcp\keep_display.log", [switch]$Verbose, [switch]$ForceDisc @@ -26,7 +30,11 @@ function Write-Log([string]$msg) { } # 会话状态: 用 WTS API (qwinsta 在计划任务上下文里拿不到输出) -$py = 'D:\lc-mcp\vendor\aalc\.venv\Scripts\python.exe' +$py = if ($Python) { $Python } else { Join-Path $PSScriptRoot '..\vendor\aalc\.venv\Scripts\python.exe' } +if ($SessionId -lt 0) { + $game = Get-Process -Name LimbusCompany -ErrorAction SilentlyContinue | Select-Object -First 1 + $SessionId = if ($game) { $game.SessionId } else { (Get-Process -Id $PID).SessionId } +} $statePy = Join-Path $PSScriptRoot 'session_state.py' if (-not (Test-Path $py) -or -not (Test-Path $statePy)) { Write-Log "missing python ($py) or session_state.py ($statePy); abort" @@ -39,30 +47,37 @@ if ($state -notin @('Active', 'Connected', 'Disc', 'Idle')) { } if ($ForceDisc) { - $state = 'Disc' Write-Log "ForceDisc: skipping state check (real state was '$state')" + $state = 'Disc' } elseif ($state -ne 'Disc') { if ($Verbose) { Write-Log "session $SessionId is $state; nothing to do" } exit 0 } Write-Log "session $SessionId is Disc -> re-attaching to console via elevated tscon" -$out = Join-Path $env:TEMP 'lc_keep_display_tscon.txt' +$out = Join-Path (Split-Path -Parent $LogPath) 'tscon_last.txt' Remove-Item $out -ErrorAction SilentlyContinue -# 显式记录退出码: 只看有没有输出文件分不清"成功但无输出"和"根本没跑" -$inner = "tscon $SessionId /dest:console > `"$out`" 2>&1; Add-Content `"$out`" ('EXIT=' + `$LASTEXITCODE)" +# 之前的版本把命令拼成 -Command 字符串交给 Start-Process, 10-05 的 41 次失败 +# 全部只留下 "(no output file)", 连 tscon 有没有跑都看不出(多半是引号在 +# 命令行拼接时被吃掉, 重定向没生效)。改用 -EncodedCommand 原样传递, +# 并用 -PassThru 拿提权进程的退出码(= tscon 的退出码)。 +# 32 位宿主里 System32 会被重定向到 SysWOW64, 那里没有 tscon.exe, 用 Sysnative 绕过。 +$sysDir = if (Test-Path "$env:SystemRoot\Sysnative") { "$env:SystemRoot\Sysnative" } else { "$env:SystemRoot\System32" } +$inner = "& '$sysDir\tscon.exe' $SessionId /dest:console *> '$out'; exit `$LASTEXITCODE" +$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner)) try { - Start-Process -FilePath "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" ` - -ArgumentList @('-NoProfile', '-WindowStyle', 'Hidden', '-Command', $inner) ` - -Verb RunAs -WindowStyle Hidden -Wait -ErrorAction Stop + $proc = Start-Process -FilePath "$sysDir\WindowsPowerShell\v1.0\powershell.exe" ` + -ArgumentList @('-NoProfile', '-NonInteractive', '-EncodedCommand', $encoded) ` + -Verb RunAs -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop } catch { Write-Log "elevated tscon launch FAILED: $($_.Exception.Message)" exit 1 } Start-Sleep -Seconds 2 -$tsconOut = if (Test-Path $out) { ((Get-Content $out -Raw) -replace '\s+', ' ').Trim() } else { '(no output file)' } +$tsconOut = if (Test-Path $out) { ((Get-Content $out -Raw) -replace '\s+', ' ').Trim() } else { '' } +if (-not $tsconOut) { $tsconOut = '(no output)' } $after = (& $py -X utf8 $statePy $SessionId 2>&1 | Out-String).Trim() -Write-Log "tscon said: $tsconOut | session $SessionId now: $after" +Write-Log "tscon exit=$($proc.ExitCode) said: $tsconOut | session $SessionId now: $after" # 渲染自检: BitBlt 屏幕 DC 成功 = 桌面在出图 $renderPy = Join-Path $PSScriptRoot 'render_check.py' diff --git a/scripts/lc_ui.py b/scripts/lc_ui.py new file mode 100644 index 0000000..6ec922f --- /dev/null +++ b/scripts/lc_ui.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +"""levelup.py / auto_cycle.py 共用的 MCP 调用与坐标换算。 + +脚本里的坐标都是在 1600x900 客户区上实测的。实际客户区随 set_win_size +和桌面分辨率变化(720/900/1080 都出现过), 所以: + - get_state 返回的 OCR 坐标先换算到 1600x900 再交给脚本逻辑; + - click/drag 的坐标从 1600x900 换算回当前客户区再发出。 +脚本内部因此只需要面对一套坐标。 +""" +import json +import os +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +# 默认用运行本脚本的解释器(AALC 的 venv); 需要时用 LC_PY 指定 +PY = os.environ.get('LC_PY') or sys.executable +PROBE = os.path.join(HERE, 'mcp_probe.py') + +BASE_W, BASE_H = 1600, 900 +_scale = None + + +def run(cmd): + r = subprocess.run(cmd, capture_output=True, text=True, + encoding='utf-8', errors='replace') + return (r.stdout or '') + (r.stderr or '') + + +def probe(tool, args=None, quiet=True): + cmd = [PY, '-X', 'utf8', PROBE, tool] + if args is not None: + cmd.append(json.dumps(args, ensure_ascii=False)) + out = run(cmd).strip() + for line in reversed(out.splitlines()): + line = line.strip() + if line.startswith('{'): + try: + return json.loads(line) + except json.JSONDecodeError: + continue + if not quiet: + print('[warn] probe %s 无 JSON 输出: %r' % (tool, out[:200])) + return {} + + +def state(): + """get_state, 并把 OCR 坐标换算到 1600x900。""" + global _scale + r = probe('get_state', quiet=False) + screen = r.get('screen') or {} + if screen.get('w') and screen.get('h'): + if abs(screen['w'] / screen['h'] - BASE_W / BASE_H) > 0.02: + print('[warn] 客户区 %sx%s 不是 16:9, 坐标会偏' % (screen['w'], screen['h'])) + _scale = screen['w'] / BASE_W + s = _scale or 1.0 + for it in r.get('items', []): + for k in ('x', 'y', 'w', 'h'): + if k in it: + it[k] = round(it[k] / s) + return r + + +def items(): + return state().get('items', []) + + +def screen_text(its): + return ' | '.join(i.get('text', '') for i in its) + + +def _to_client(x, y): + if _scale is None: + state() + s = _scale or 1.0 + return int(round(x * s)), int(round(y * s)) + + +def click(x, y, times=1): + cx, cy = _to_client(x, y) + return probe('click', {'x': cx, 'y': cy, 'times': times}) + + +def drag(from_x, from_y, to_x, to_y): + fx, fy = _to_client(from_x, from_y) + tx, ty = _to_client(to_x, to_y) + return probe('drag', {'from_x': fx, 'from_y': fy, 'to_x': tx, 'to_y': ty}) + + +def long_press(x, y): + """drag 起点==终点 即长按(实测可打开人格详情)。""" + return drag(x, y, x, y) + + +def keypress(key): + return probe('keypress', {'key': key}) diff --git a/scripts/levelup.py b/scripts/levelup.py index 393bcab..3b97688 100644 --- a/scripts/levelup.py +++ b/scripts/levelup.py @@ -19,17 +19,15 @@ 退出码: 0 成功 / 1 失败 """ -import json -import subprocess import sys import time -PY = r'D:\lc-mcp\vendor\aalc\.venv\Scripts\python.exe' -PROBE = r'D:\lc-mcp\scripts\mcp_probe.py' +from lc_ui import click, keypress, long_press, screen_text, state -# 网格布局 +# 网格布局(1600x900 坐标, 由 lc_ui 换算到实际客户区)。 +# 第 4 行在 y=942, 超出客户区, 需要滚动才能看到, 这里不处理。 COLS = [335, 508, 681, 853, 1026, 1198] -ROWS = [260, 487, 715, 942] +ROWS = [260, 487, 715] # 固定控件坐标 BACK = (85, 75) @@ -44,43 +42,6 @@ UPTIE_DONE_CONFIRM = (772, 661) UPTIE_CANCEL = (526, 660) -def probe(tool, args=None, quiet=False): - cmd = [PY, '-X', 'utf8', PROBE, tool] - if args is not None: - cmd.append(json.dumps(args, ensure_ascii=False)) - r = subprocess.run(cmd, capture_output=True, text=True, - encoding='utf-8', errors='replace') - out = (r.stdout or '').strip() - for line in reversed(out.splitlines()): - line = line.strip() - if line.startswith('{'): - try: - return json.loads(line) - except json.JSONDecodeError: - continue - if not quiet: - print('[warn] probe %s 无 JSON 输出: %r' % (tool, out[:200])) - return {} - - -def state(): - return probe('get_state') - - -def click(x, y, times=1): - return probe('click', {'x': int(x), 'y': int(y), 'times': times}) - - -def long_press(x, y): - """drag 起点==终点 即长按(实测可打开人格详情)。""" - return probe('drag', {'from_x': int(x), 'from_y': int(y), - 'to_x': int(x), 'to_y': int(y)}) - - -def screen_text(items): - return ' | '.join(i.get('text', '') for i in items) - - def near(items, cx, cy, dx=100, dy=115): return [i for i in items if abs(i.get('x', 0) - cx) < dx and abs(i.get('y', 0) - cy) < dy] @@ -151,9 +112,13 @@ def ticket_balance(): return bal -def do_level_up(): - """在已打开的人格详情页执行升级。返回 (ok, 描述)""" - before = None +def do_level_up(hint=None): + """在已打开的人格详情页执行升级。返回 (ok, 描述), ok 为 None 表示没有券可用。 + + 成败看详情页的等级/经验条在升级前后是否变化。不能看 'Level Up'/'Uptie' + 字样: 详情页上它们一直都在, 升级失败也会被判成成功。 + """ + lvl0, _, bar0 = read_detail(hint) click(*BTN_LEVEL_UP) time.sleep(3.5) items = state().get('items', []) @@ -189,21 +154,30 @@ def do_level_up(): target = nums[-1] click(*POWERUP_CONFIRM) time.sleep(4.5) - items = state().get('items', []) - txt = screen_text(items) - ok = 'Uptie' in txt or 'Level Up' in txt - return ok, '升级前券=%s 目标等级=%s' % (before, target) + txt = screen_text(state().get('items', [])) + if 'Owned' in txt and 'Cancel' in txt: + click(*POWERUP_CANCEL) + time.sleep(2) + return False, 'Confirm 后 Power-up 窗口仍在, 已取消(券=%s)' % before + lvl1, _, bar1 = read_detail(hint=target or lvl0 or hint) + desc = '券=%s 目标=%s 等级 %s->%s 经验 %s->%s' % (before, target, lvl0, lvl1, bar0, bar1) + if lvl0 is not None and lvl1 is not None and lvl1 > lvl0: + return True, desc + if bar0 is not None and bar1 is not None and bar1 != bar0: + return True, desc + return False, '升级未确认: ' + desc -def skip_cutscene(): +def skip_cutscene(press_esc=True): """同步到三阶会解锁人格剧情并自动播放。ESC 会弹"是否跳过", 点 Confirm。 - 返回 True 表示确实跳过一个过场。 + press_esc=False 时只处理已经弹出的跳过框, 不主动按 ESC——没有过场时按 ESC + 会关掉当前弹窗或退出详情页。返回 True 表示确实跳过一个过场。 """ items = state().get('items', []) txt = screen_text(items) - if 'skip' not in txt.lower(): - probe('keypress', {'key': 'esc'}) + if 'skip' not in txt.lower() and press_esc: + keypress('esc') time.sleep(2) items = state().get('items', []) txt = screen_text(items) @@ -238,22 +212,25 @@ def do_uptie(): click(*UPTIE_CONFIRM) time.sleep(4.5) - if skip_cutscene(): + txt = screen_text(state().get('items', [])) + # 弹窗还在(仍显示材料需求)说明没同步成。必须先判断这个: 弹窗里本身就有 + # 'Skills Gained', 放在成功判定后面会把失败认成成功。 + if 'Currency Req' in txt or 'Egoshard' in txt: + click(*UPTIE_CANCEL) + time.sleep(2) + return False, '同步未生效(通常缺自我碎片): ' + txt[:160] + if skip_cutscene(press_esc=False): time.sleep(3) return True, '同步成功(并跳过了解锁的人格剧情)' - - items = state().get('items', []) - txt = screen_text(items) if 'Uptied' in txt or 'Enhanced' in txt or 'Gained' in txt: click(*UPTIE_DONE_CONFIRM) time.sleep(2.5) return True, '同步成功' - if 'Owned' in txt or 'Egoshard' in txt: - click(*UPTIE_CANCEL) - time.sleep(2) - return False, '同步未生效(通常缺自我碎片): ' + txt[:160] - click(*UPTIE_CANCEL) - time.sleep(2) + # 什么都没认出: 可能是剧情已经在播但还没出跳过提示, 这时才按 ESC + if skip_cutscene(press_esc=True): + time.sleep(3) + return True, '同步成功(并跳过了解锁的人格剧情)' + # 画面未知时不盲点坐标, 交给调用方按网格判断退回 return False, '同步结果未知: ' + txt[:160] @@ -327,7 +304,7 @@ def level_from_bar(cur, need, hint=None): def read_detail(hint=None): - """从已打开的人格详情页读 (真实等级, 名字)。 + """从已打开的人格详情页读 (真实等级, 名字, 经验条 (cur, need))。 网格里的小号艺术字 OCR 极不可靠(实测 LV14->'Lv.1', LV24->'LV2H'); 详情页的大号等级也常被漏认(实测 LCB 罪人页只认出 '547/885')。 @@ -361,12 +338,10 @@ def read_detail(hint=None): if abs(from_bar - direct) > 2: print(' [warn] 进度条推算 Lv.%d 与直读 Lv.%d 不符, 取进度条' % (from_bar, direct)) - return from_bar, name + return from_bar, name, bar if from_bar is not None: - return from_bar, name - if direct is not None: - return direct, name - return None, name + return from_bar, name, bar + return direct, name, bar def cmd_progress(target=34, uptie=True, max_try=6): @@ -389,7 +364,7 @@ def cmd_progress(target=34, uptie=True, max_try=6): if 'Level Up' not in txt: print(' 长按未打开详情, 跳过') 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)) if true_lvl is None: # 详情页读不到时退回网格值——网格会误读, 但总比跳过整张卡好 @@ -400,7 +375,7 @@ def cmd_progress(target=34, uptie=True, max_try=6): click(*BACK) time.sleep(2.5) continue - ok, desc = do_level_up() + ok, desc = do_level_up(hint=true_lvl) print(' 升级: %s (%s)' % ('OK' if ok else ('SKIP' if ok is None else 'FAIL'), desc)) if uptie: ok2, desc2 = do_uptie() diff --git a/tests/test_lc_mcp.py b/tests/test_lc_mcp.py index e840a2d..3429677 100644 --- a/tests/test_lc_mcp.py +++ b/tests/test_lc_mcp.py @@ -675,5 +675,41 @@ class TaskErrorSurfaceTest(unittest.TestCase): self.assertNotIn('errors', status) +class TaskStallSurfaceTest(unittest.TestCase): + """空队伍卡死时进程健在、日志无报错, 只有编队人数检查在刷屏。""" + + @staticmethod + def child(repeats): + return ('import sys, time\n' + 'for _ in range(%d):\n' + ' sys.stdout.write("[DEBUG] tasks\\\\teams\\\\team_formation.py:225: ' + '对于配队人数OCR得到:0/5\\n")\n' + 'sys.stdout.flush()\n' + 'time.sleep(30)\n' % repeats) + + def status_while_running(self, repeats): + with tempfile.TemporaryDirectory() as d: + runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', self.child(repeats)]) + self.assertTrue(runner.start('daily', {})['ok']) + try: + deadline = time.time() + 15 + while time.time() < deadline and repeats and not os.path.getsize(runner.info['log']): + time.sleep(0.05) + time.sleep(0.2) + return runner.status() + finally: + runner.stop() + + def test_repeated_empty_team_check_is_reported(self): + status = self.status_while_running(12) + self.assertEqual(status['state'], 'running') + self.assertEqual(status['stall'], {'empty_team': 12}) + + def test_occasional_check_is_not_a_stall(self): + status = self.status_while_running(3) + self.assertEqual(status['state'], 'running') + self.assertNotIn('stall', status) + + if __name__ == '__main__': unittest.main() diff --git a/tests/test_levelup.py b/tests/test_levelup.py new file mode 100644 index 0000000..f172aba --- /dev/null +++ b/tests/test_levelup.py @@ -0,0 +1,138 @@ +from pathlib import Path +import sys +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +import lc_ui # noqa: E402 +import levelup # noqa: E402 + + +def shot(w, h, items=()): + return {'ok': True, 'screen': {'path': 'x.png', 'w': w, 'h': h}, + 'items': [dict(i) for i in items]} + + +class ScaleTest(unittest.TestCase): + """脚本坐标按 1600x900 写, 实际客户区可能是 1280x720 或 1920x1080。""" + + def setUp(self): + lc_ui._scale = None + + def test_720p_items_and_clicks_use_base_coordinates(self): + calls = [] + + def probe(tool, args=None, quiet=True): + calls.append((tool, args)) + return shot(1280, 720, [{'text': 'Level Up', 'x': 800, 'y': 400, 'w': 80, 'h': 20}]) + + with mock.patch.object(lc_ui, 'probe', probe): + item = lc_ui.items()[0] + lc_ui.click(1600, 900) + lc_ui.long_press(800, 450) + self.assertEqual((item['x'], item['y'], item['w']), (1000, 500, 100)) + self.assertEqual(calls[1], ('click', {'x': 1280, 'y': 720, 'times': 1})) + self.assertEqual(calls[2], ('drag', {'from_x': 640, 'from_y': 360, 'to_x': 640, 'to_y': 360})) + + def test_click_before_any_state_reads_client_size_first(self): + calls = [] + + def probe(tool, args=None, quiet=True): + calls.append((tool, args)) + return shot(1920, 1080) + + with mock.patch.object(lc_ui, 'probe', probe): + lc_ui.click(100, 100) + self.assertEqual(calls, [('get_state', None), ('click', {'x': 120, 'y': 120, 'times': 1})]) + + +class Screens: + """按顺序返回预设画面的假 state(), 记录点击。""" + + def __init__(self, *screens): + self.screens = list(screens) + self.clicks = [] + self.keys = [] + + def state(self): + texts = self.screens.pop(0) if len(self.screens) > 1 else self.screens[0] + return {'items': [{'text': t, 'x': x, 'y': y} for t, x, y in texts]} + + def patch(self): + return mock.patch.multiple(levelup, state=self.state, time=mock.Mock(), + click=lambda *a, **k: self.clicks.append(a), + keypress=lambda k: self.keys.append(k)) + + +DETAIL = [('Level Up', 1164, 235), ('Uptie', 1367, 235), ('547/885', 400, 250)] +POWERUP = [('Owned:3', 900, 380), ('Owned:0', 900, 485), ('Owned:7', 900, 595), ('Cancel', 603, 670)] + + +class LevelUpVerdictTest(unittest.TestCase): + + def test_detail_page_without_exp_change_is_not_success(self): + # 旧逻辑只要回到详情页(有 Level Up / Uptie)就算成功 + screens = Screens(DETAIL, POWERUP, POWERUP, DETAIL, DETAIL) + with screens.patch(): + ok, desc = levelup.do_level_up(hint=17) + self.assertFalse(ok, desc) + + def test_level_increase_is_success(self): + after = [('Level Up', 1164, 235), ('Uptie', 1367, 235), ('100/1261', 400, 250)] + screens = Screens(DETAIL, POWERUP, POWERUP, after, after) + with screens.patch(): + ok, desc = levelup.do_level_up(hint=17) + self.assertTrue(ok, desc) + self.assertIn('17->19', desc) + + def test_popup_still_open_after_confirm_is_cancelled(self): + screens = Screens(DETAIL, POWERUP, POWERUP, POWERUP) + with screens.patch(): + ok, desc = levelup.do_level_up(hint=17) + self.assertFalse(ok) + self.assertEqual(screens.clicks[-1], levelup.POWERUP_CANCEL) + + +UPTIE_POPUP = [('Currency Req.', 700, 300), ('Skills Gained', 700, 400), + ('Owned:2', 900, 450), ('Uptie', 1085, 580)] + + +class UptieVerdictTest(unittest.TestCase): + + def test_popup_still_open_is_failure_even_with_skills_gained(self): + screens = Screens(UPTIE_POPUP, UPTIE_POPUP) + with screens.patch(): + ok, desc = levelup.do_uptie() + self.assertFalse(ok, desc) + self.assertEqual(screens.keys, []) + + def test_success_dialog_is_confirmed_without_esc(self): + done = [('Uptied!', 700, 300), ('Confirm', 772, 661)] + screens = Screens(UPTIE_POPUP, done, done) + with screens.patch(): + ok, desc = levelup.do_uptie() + self.assertTrue(ok, desc) + self.assertEqual(screens.keys, []) + self.assertEqual(screens.clicks[-1], levelup.UPTIE_DONE_CONFIRM) + + def test_unknown_screen_presses_esc_once_and_never_clicks_blind(self): + story = [("I swear to you! I will return this favor", 500, 700)] + screens = Screens(UPTIE_POPUP, story, story, story) + with screens.patch(): + ok, desc = levelup.do_uptie() + self.assertFalse(ok) + self.assertEqual(screens.keys, ['esc']) + self.assertNotIn(levelup.UPTIE_CANCEL, screens.clicks) + + def test_cutscene_skip_prompt_counts_as_success(self): + story = [("I swear to you!", 500, 700)] + skip = [('Skip this story?', 700, 400), ('Confirm', 900, 600)] + screens = Screens(UPTIE_POPUP, story, story, skip, skip) + with screens.patch(): + ok, desc = levelup.do_uptie() + self.assertTrue(ok, desc) + self.assertEqual(screens.clicks[-1], (900, 600)) + + +if __name__ == '__main__': + unittest.main()