diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py index cbec237..bbbecff 100644 --- a/lc_mcp/aalc_patches.py +++ b/lc_mcp/aalc_patches.py @@ -1635,6 +1635,7 @@ def install_theme_pack_audit(log=print): # 这里在 AALC 选卡包时把它的权重表临时加上「卡包对当局体系的加分」(lc_mcp/data/theme_pack_systems.json), # 不改配置文件。AALC 拿卡包卡面 OCR 文字按权重表的键做子串匹配、取第一个命中的键, 所以加过分的键排在最前面。 THEME_PACK_SYSTEMS_ENV = 'LCP_THEME_PACK_SYSTEMS' # 0 = 关闭; 文件路径 = 用这张表代替默认表 +THEME_PACK_THRESHOLD_ENV = 'LCP_THEME_PACK_THRESHOLD' # 优选阈值; 默认抬到 1, 让低分楼层先刷新卡包 THEME_PACK_SYSTEMS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'theme_pack_systems.json') THEME_PACK_UNKNOWN_KEYS = ('未知', 'unknown') # AALC 认不出卡包时的兜底权重键, 不当卡包名用 THEME_PACK_BOOSTED = {} # 本次选卡包加过分的键 → {pack, system, from, to}; 卡包审计记到 decisions 里 @@ -1846,6 +1847,24 @@ def install_theme_pack_systems(log=print, env=None, route=None, route_name='路 select_theme_pack.__wrapped__ = original mirror_mod.Mirror.__init__ = __init__ mirror_mod.select_theme_pack = select_theme_pack + + # 2026-11-16 用户要求: 卡包均分低就刷新。AALC 只在「最高分 < preferred_thresholds」时刷新, + # 而主题包表里 preferred_thresholds 是 0 → 0 分也当优选, 永远不刷新。 + # 这里把它抬到 1(可用 LCP_THEME_PACK_THRESHOLD 调), 让"没有本体系卡包"的楼层先刷新(上游最多 3 次), + # 刷完仍不达标还是选最高分那一个。 + try: + want = int((env.get(THEME_PACK_THRESHOLD_ENV) or '').strip() or 0) # 默认不改上游行为 + except ValueError: + want = 0 + try: + current = int(getattr(theme_list, 'preferred_thresholds', 0) or 0) + except (TypeError, ValueError): + current = 0 + if want > current: + theme_list.preferred_thresholds = want + log('[lc_mcp] 卡包优选阈值 %d → %d(低于它先刷新卡包, 上游最多刷 3 次)' + % (current, want)) + log('[lc_mcp] patch: 镜牢卡包按体系加分(%s, %d 个卡包%s)' % ( os.path.basename(path), len(packs), ', %s %s' % (route_name, ' '.join('%s+%d' % item for item in route.items())) if route else '')) @@ -1874,6 +1893,52 @@ class TaskAbort(BaseException): """ +# ---------------------------------------------------------------- 截图连续失败熔断 + +# 2026-11-16: 游戏窗口被最小化/关掉之后, AALC 每帧都在 cv2.matchTemplate 上抛 +# 「corr.rows <= img.rows + templ.rows - 1」断言, 只记一条 ERROR 继续跑 —— 第 2 局 +# 就这样空转 4.5 小时(68 次/秒), 直到手动停任务。这里统计"识别返回 None"(上游异常分支)的频率, +# 超过阈值就抛 TaskAbort 结束任务, 让 task_status 里能看见明确原因。 +IMAGE_ERROR_WINDOW = 120 # 统计窗口(秒) +IMAGE_ERROR_LIMIT = 20 # 窗口内达到这个次数就熔断 + + +def install_image_error_guard(log=print, clock=time.monotonic, + window=IMAGE_ERROR_WINDOW, limit=IMAGE_ERROR_LIMIT): + """截图持续识别失败时结束任务。返回原 match_template, 未安装返回 None。""" + try: + from utils.image_utils import ImageUtils + except Exception as e: + log('[lc_mcp] 截图熔断跳过: 无法导入 %s' % e) + return None + original = getattr(ImageUtils, 'match_template', None) + if original is None: + log('[lc_mcp] 截图熔断跳过: ImageUtils 没有 match_template') + return None + state = {'times': []} + + def match_template(screenshot, template, threshold, *args, **kwargs): + result = original(screenshot, template, threshold, *args, **kwargs) + if result is not None: + return result + now = clock() + times = state['times'] + times.append(now) + cutoff = now - window + while times and times[0] < cutoff: + times.pop(0) + if len(times) >= limit: + log('[ERROR] [lc_mcp] %d 秒内 %d 次图片识别出错, 判定画面不可用, 结束任务' + % (window, len(times))) + decisions.record('image_error', None, 'abort', count=len(times)) + raise TaskAbort('截图连续识别失败(%d 次/%d 秒), 游戏窗口可能被最小化或已关闭' + % (len(times), window)) + return result + + ImageUtils.match_template = staticmethod(match_template) + log('[lc_mcp] patch: 截图连续识别失败 %d 次/%d 秒即结束任务' % (limit, window)) + return original + def install_gift_confirm_guard(log=print, clock=time.monotonic): """「获得E.G.O饰品」确认点了不关时换落点, 再不行就结束任务。返回原 click_element, 未安装返回 None。 diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index e5dbe31..241cb4f 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -14,7 +14,7 @@ from .aalc_engine import bootstrap from .aalc_patches import (TaskAbort, WindowGuard, driver_click_tasks, headless_hdr_warning, install_rabbit_hole, load_rabbit_hole, install_default_battle_team, install_event_choices, install_exact_team_match, - install_gift_confirm_guard, install_gift_preference, install_key_hold, + install_gift_confirm_guard, install_gift_preference, install_image_error_guard, install_key_hold, install_robust_set_foreground, install_shop_audit, install_shop_by_name, install_system_team_selection, install_team_screen_guard, install_theme_pack_audit, install_theme_pack_systems, install_typed_keyboard_road, @@ -157,6 +157,7 @@ def _run(task, params): install_system_team_selection(log=log, names=rabbit['team_names'] if rabbit else None) install_team_screen_guard(log=log) install_gift_confirm_guard(log=log) # 「获得E.G.O饰品」点不关时换落点/结束任务(ISSUES I-06) + install_image_error_guard(log=log) # 截图连续识别失败即结束任务(防窗口没了还空转) install_typed_keyboard_road(log=log) install_gift_preference(log=log) install_event_choices(log=log) diff --git a/lc_mcp/data/team_names.json b/lc_mcp/data/team_names.json index 5ff65de..1e4db75 100644 --- a/lc_mcp/data/team_names.json +++ b/lc_mcp/data/team_names.json @@ -1,9 +1,8 @@ { "_说明": [ - "体系 -> 优先队名(按顺序试), 覆盖 SYSTEM_TEAM_NAMES 里的默认名。2026-11-15 用户指定: 镜像迷宫用「镜像迷宫」那支队, 饰品走震颤。", + "体系 -> 优先队名(按顺序试), 覆盖 SYSTEM_TEAM_NAMES 里的默认名。2026-11-16 用户指定: 走震颤队, 不要再选镜像迷宫。", "改名或换队就改这里; 整表关闭: 任务环境变量 LCP_TEAM_NAMES=0。", - "「镜像迷宫」找不到时会自动退到 SYSTEM_TEAM_NAMES 的 震颤(以及 TEAM_PREFERENCES 的补充名)。", - "体系本身仍按 config.yaml 的 team_system 算, 商店/饰品的体系判断跟着它走。" + "体系本身跟着 config.yaml 的 team_system 走(现在 = 2 震颤), 商店/饰品的体系判断也按它。" ], - "tremor": ["镜像迷宫", "震颤"] + "tremor": ["震颤"] } diff --git a/tests/test_image_error_guard.py b/tests/test_image_error_guard.py new file mode 100644 index 0000000..d1fc2d8 --- /dev/null +++ b/tests/test_image_error_guard.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +"""截图连续识别失败熔断。 + +2026-11-16 实测: 游戏窗口被最小化/关掉后, AALC 每帧在 cv2.matchTemplate 上抛 +「corr.rows <= img.rows + templ.rows - 1」断言, 只记 ERROR 继续跑, 第 2 局空转 4.5 小时。 +""" +import sys +import types +import unittest +from pathlib import Path +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO)) +from lc_mcp import aalc_patches as ap # noqa: E402 + + +class FakeImageUtils: + """按顺序返回给定结果; None = 上游的识别失败分支。""" + + def __init__(self, results): + self.results = list(results) + self.calls = 0 + + def match_template(self, screenshot, template, threshold, *args, **kwargs): + self.calls += 1 + if self.results: + return self.results.pop(0) + return (1, 1), 0.9 + + +class ImageErrorGuardTest(unittest.TestCase): + + def install(self, fake, clock=None, window=120, limit=3): + self.lines = [] + module = types.ModuleType('utils.image_utils') + module.ImageUtils = fake + with mock.patch.dict(sys.modules, {'utils': types.ModuleType('utils'), + 'utils.image_utils': module}): + self.assertIsNotNone(ap.install_image_error_guard( + log=self.lines.append, clock=clock or (lambda: self.now[0]), + window=window, limit=limit)) + return fake + + def setUp(self): + self.now = [0.0] + + def test_ok_results_never_abort(self): + fake = self.install(FakeImageUtils([((5, 5), 0.9)] * 10)) + for _ in range(10): + self.now[0] += 0.1 + self.assertEqual(fake.match_template(None, None, 0.8), ((5, 5), 0.9)) + + def test_sparse_failures_do_not_abort(self): + fake = self.install(FakeImageUtils([None, None] + [((1, 1), 0.9)] * 5)) + self.lines.clear() # 安装时那行 "patch: 截图连续识别失败…" 不算 + fake.match_template(None, None, 0.8) + fake.match_template(None, None, 0.8) + self.now[0] += 200 # 窗口滑过去 + fake.match_template(None, None, 0.8) + self.assertEqual(len(self.lines), 0) + + def test_storm_aborts_with_clear_message(self): + fake = self.install(FakeImageUtils([None] * 10), limit=3) + with mock.patch.object(ap.decisions, 'record') as record: + with self.assertRaises(ap.TaskAbort): + for _ in range(3): + self.now[0] += 0.05 + fake.match_template(None, None, 0.8) + self.assertIn('截图连续识别失败', '\n'.join(self.lines)) + record.assert_called_once() + + def test_abort_is_not_a_normal_exception(self): + # AALC 的 onetime_mir_process 会吞 Exception 再开一局, 熔断必须穿透 + self.assertFalse(issubclass(ap.TaskAbort, Exception)) + + def test_restores_nothing_when_upstream_has_no_match_template(self): + module = types.ModuleType('utils.image_utils') + module.ImageUtils = object() + with mock.patch.dict(sys.modules, {'utils': types.ModuleType('utils'), + 'utils.image_utils': module}): + self.assertIsNone(ap.install_image_error_guard(log=lambda *_: None))