diff --git a/README.md b/README.md index 7bb1b1b..299b748 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,22 @@ codex mcp add limbus --env PYTHONUTF8=1 -- D:\lc-mcp\vendor\aalc\.venv\Scripts\p 所以任务启动时先把原值写到 `~/lc_mcp/runs/*.restore.json`;`stop_task` 强停或任务进程异常退出后, 服务会据此写回。写回失败时 `task_status` 显示 `pending_restore`,并在写回成功前拒绝启动新任务。 +`state` 只反映任务子进程的退出码。AALC 在单次战斗失败(例如日志里的 +`超出最大尝试次数,未能进入战斗`)后仍会继续跑完并正常退出,所以 `task_status` +会把日志尾部的 `[ERROR]`/异常行放进 `errors` 字段:**看到 `succeeded` 也要先看 `errors`。** + +### 与上游 AALC 的差异(不改其源码) + +`lc_mcp/aalc_input_patch.py` 在 `bootstrap()` 时给 Windows 输入适配器打补丁,只补上游缺的东西: + +- **编队列表滑动**:AALC 基类要求适配器覆盖 `mouse_swipe_for_team_scroll` 以"规避队伍拖拽判定", + 但上游只有 MuMu 模拟器适配器覆盖了它(见 `input_handlers/__init__.py` 注释)。Windows 前台/后台适配器 + 仍用普通列表手势 `build_windows_scroll_swipe_plan`(escape 30px/0.01s),在游戏的编队列表里不足以脱离 + "按住罪人卡"判定,滑动会被当成拖动卡片:队伍顺序被拖乱,缺人时后续还会"未能进入战斗"。 + 补丁按 MuMu 的参数(按 `set_win_size` 缩放 60px escape、保持 0.1s、分段走完、松手前停稳 0.5s) + 在 `Input`(前台)和 `BackgroundInput`(后台)上补上等价实现;`WindowMoveInput` 没有 + `set_mouse_pos`,保持原样。 + ## 环境变量 | 变量 | 默认 | 说明 | diff --git a/lc_mcp/aalc_engine.py b/lc_mcp/aalc_engine.py index fd2626f..cf1f979 100644 --- a/lc_mcp/aalc_engine.py +++ b/lc_mcp/aalc_engine.py @@ -43,6 +43,10 @@ def bootstrap(): from module.logger.my_log import Logger Logger() _booted = d + # 编队列表滑动: Windows 输入适配器缺队伍拖拽规避, 上游只有模拟器适配器有。 + # 在导入 AALC 之后立即打补丁, 服务的 MCP 输入与 run_task 子进程都会生效。 + from . import aalc_input_patch + aalc_input_patch.install() return d diff --git a/lc_mcp/aalc_input_patch.py b/lc_mcp/aalc_input_patch.py new file mode 100644 index 0000000..fa74331 --- /dev/null +++ b/lc_mcp/aalc_input_patch.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +"""编队列表滑动补丁: 给 Windows 输入适配器补上队伍拖拽规避。 + +AALC 基类注释说明 ``mouse_swipe_for_team_scroll`` 需要适配器覆盖以"规避队伍 +拖拽判定", 但上游只有 MuMu 模拟器适配器覆盖了它; Windows 的前台(Input)与后台 +(BackgroundInput)适配器仍在用普通列表滚动手势 ``build_windows_scroll_swipe_plan``: +按下后只 escape 30px / 0.01s。在游戏的编队列表里这不足以脱离"按住罪人卡"的 +判定, 滑动会被当成拖动卡片 —— 队伍顺序被拖乱, 编队人数不足时还会让后续的 +"进入战斗"失败(battle.py 报"未能进入战斗")。 + +这里按 MuMu 的参数(按 set_win_size 缩放的 60px escape、保持 0.1s、分段走完、 +松手前停稳 0.5s)在 Windows 适配器上补一份等价实现, 不改 AALC 源码。 +""" + +import time +from math import hypot + +# 与 MuMu 覆盖实现保持一致的量级 +ESCAPE_AT_1080P = 60 +ESCAPE_HOLD_SECONDS = 0.1 +SETTLE_SECONDS = 0.5 +POINT_SPACING_AT_1080P = 8 +MIN_SEGMENT_DURATION = 0.05 + + +def team_scroll_plan(x, y, dx, dy, duration, escape_distance): + """编队列表滑动的几何路径(纯函数, 便于单测)。 + + 返回 ``(start, escape, end, duration)``; ``distance == 0`` 时返回 None。 + 向下滑动(dy > 0)时把起点沿反向偏移 escape, 终点沿正向多走 escape, + 这样手指/指针能落在可见行内, 同时保持总位移不变。 + """ + distance = hypot(dx, dy) + if distance == 0: + return None + unit_x, unit_y = dx / distance, dy / distance + if dy > 0: + start = (x - unit_x * escape_distance, y - unit_y * escape_distance) + else: + start = (float(x), float(y)) + end = (start[0] + dx + unit_x * escape_distance, + start[1] + dy + unit_y * escape_distance) + escape = (start[0] + unit_x * escape_distance, + start[1] + unit_y * escape_distance) + return start, escape, end, max(0.0, float(duration)) + + +def _scaled_escape(): + from module.config import cfg + return ESCAPE_AT_1080P * cfg.set_win_size / 1080 + + +def _segment_steps(escape_point, end): + """把 escape 之后的剩余位移切成小段, 返回 (段数, 位移x, 位移y)。""" + from module.config import cfg + + move_x = end[0] - escape_point[0] + move_y = end[1] - escape_point[1] + distance = hypot(move_x, move_y) + if distance == 0: + return 0, 0.0, 0.0 + spacing = POINT_SPACING_AT_1080P * cfg.set_win_size / 1080 + steps = max(int(distance / max(spacing, 1.0)), 1) + return steps, move_x, move_y + + +def _foreground_team_scroll(self, x, y, duration=0.3, dx=0, dy=0, move_back=True): + """前台输入(pyautogui)下的编队列表滑动。""" + import pyautogui + + plan = team_scroll_plan(x, y, dx, dy, duration, _scaled_escape()) + if plan is None: + return + start, escape, end, total_duration = plan + restore = self.get_mouse_position() if move_back else None + + sx, sy = self.pos_offset(*start) + ex, ey = self.pos_offset(*escape) + fx, fy = self.pos_offset(*end) + + pyautogui.moveTo(sx, sy) + pyautogui.mouseDown(sx, sy) + try: + pyautogui.moveTo(ex, ey, duration=MIN_SEGMENT_DURATION) + # 让游戏渲染一帧, 确认这是滚动而不是按住卡片。 + time.sleep(ESCAPE_HOLD_SECONDS) + steps, move_x, move_y = _segment_steps(escape, end) + if steps: + step_duration = max(total_duration, MIN_SEGMENT_DURATION) / steps + for index in range(1, steps + 1): + ratio = index / steps + pyautogui.moveTo(ex + move_x * ratio, ey + move_y * ratio, + duration=step_duration) + time.sleep(SETTLE_SECONDS) + finally: + pyautogui.mouseUp(fx, fy) + + if restore: + self.mouse_move(restore) + + +def _adapter_team_scroll(self, x, y, duration=0.3, dx=0, dy=0, move_back=True): + """后台/其它 Windows 适配器下的编队列表滑动(走适配器自身的原语)。""" + plan = team_scroll_plan(x, y, dx, dy, duration, _scaled_escape()) + if plan is None: + return + start, escape, end, total_duration = plan + restore = self.get_mouse_position() if move_back else None + + self.set_active() + self.set_mouse_pos(*start) + self.mouse_down(*start) + try: + self.set_mouse_pos(*escape, duration=MIN_SEGMENT_DURATION) + time.sleep(ESCAPE_HOLD_SECONDS) + steps, move_x, move_y = _segment_steps(escape, end) + if steps: + step_duration = max(total_duration, MIN_SEGMENT_DURATION) / steps + for index in range(1, steps + 1): + ratio = index / steps + self.set_mouse_pos(escape[0] + move_x * ratio, + escape[1] + move_y * ratio, + duration=step_duration) + time.sleep(SETTLE_SECONDS) + finally: + self.mouse_up(*end) + + if restore: + self.mouse_move(restore) + + +def install(): + """给 AALC 的 Windows 输入适配器装上队伍安全滑动。幂等。""" + from module.automation.input_handlers import input as input_module + + patched = [] + cls = getattr(input_module, 'Input', None) + if cls is not None and getattr(cls, 'mouse_swipe_for_team_scroll', None) \ + is not _foreground_team_scroll: + cls.mouse_swipe_for_team_scroll = _foreground_team_scroll + patched.append('Input') + + for name in ('BackgroundInput', 'WindowMoveInput'): + cls = getattr(input_module, name, None) + if cls is None or not hasattr(cls, 'set_mouse_pos'): + continue + if getattr(cls, 'mouse_swipe_for_team_scroll', None) is _adapter_team_scroll: + continue + cls.mouse_swipe_for_team_scroll = _adapter_team_scroll + patched.append(name) + return patched diff --git a/lc_mcp/tasks.py b/lc_mcp/tasks.py index 61cb119..5c7fa56 100644 --- a/lc_mcp/tasks.py +++ b/lc_mcp/tasks.py @@ -35,6 +35,22 @@ def tail(path, n): return [] +ERROR_MARKERS = ('[ERROR]', 'Traceback (most recent call last)') +ERROR_SCAN_LINES = 400 + + +def log_errors(path, limit=3): + """挑出日志尾部的报错行。 + + AALC 的每日流程在单次战斗失败后会继续跑完并正常退出(exit 0), 只看退出码 + 会把"超出最大尝试次数,未能进入战斗"这类失败当成成功, 所以状态里额外附上 + 日志里的报错行。 + """ + hits = [line for line in tail(path, ERROR_SCAN_LINES) + if any(marker in line for marker in ERROR_MARKERS)] + return hits[-limit:] + + class TaskRunner: def __init__(self, run_dir, argv_factory=default_argv, keep_logs=20, restore_argv=default_restore_argv): @@ -112,6 +128,9 @@ class TaskRunner: 'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))} if code is not None: r['exit_code'] = code + errors = log_errors(self.info['log']) + if errors: + r['errors'] = errors pending = self._pending_restores() if pending: r['pending_restore'] = [os.path.basename(p) for p in pending] diff --git a/tests/test_lc_mcp.py b/tests/test_lc_mcp.py index 40e01f1..cfbfb4e 100644 --- a/tests/test_lc_mcp.py +++ b/tests/test_lc_mcp.py @@ -15,6 +15,7 @@ REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, REPO) from lc_mcp import server as srv_mod # noqa: E402 +from lc_mcp import aalc_input_patch # noqa: E402 from lc_mcp.engine import find_hits # noqa: E402 from lc_mcp.fake_engine import FakeEngine # noqa: E402 from lc_mcp.protocol import Server, TOOLS # noqa: E402 @@ -580,5 +581,110 @@ class TransportTest(unittest.TestCase): self.assertEqual((state['ok'], state['items']), (True, [])) +class TaskErrorSurfaceTest(unittest.TestCase): + """AALC 每日流程单次战斗失败后仍 exit 0; 状态里必须带出日志报错。""" + + CHILD = ('import sys; ' + 'sys.stdout.write("[ERROR] [AALC] tasks\\\\battle\\\\battle.py:83: ' + '超出最大尝试次数,未能进入战斗\\n"); ' + 'sys.stdout.write("[lc_mcp] task daily done\\n"); ' + 'sys.stdout.flush()') + + def test_exit_zero_with_battle_error_is_reported(self): + with tempfile.TemporaryDirectory() as d: + runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', self.CHILD]) + self.assertTrue(runner.start('daily', {'exp': 1})['ok']) + deadline = time.time() + 15 + while time.time() < deadline and runner.running(): + time.sleep(0.05) + status = runner.status() + self.assertEqual((status['state'], status['exit_code']), ('succeeded', 0), status) + self.assertIn('未能进入战斗', status['errors'][-1]) + + def test_clean_log_has_no_errors_field(self): + with tempfile.TemporaryDirectory() as d: + runner = TaskRunner(d, argv_factory=lambda t, p: [sys.executable, '-c', 'print("[lc_mcp] ok")']) + self.assertTrue(runner.start('daily', {})['ok']) + deadline = time.time() + 15 + while time.time() < deadline and runner.running(): + time.sleep(0.05) + status = runner.status() + self.assertEqual(status['state'], 'succeeded') + self.assertNotIn('errors', status) + + +class TeamScrollPatchTest(unittest.TestCase): + """编队列表滑动: Windows 适配器缺少队伍拖拽规避, 补丁的几何必须是 + "先 escape 脱离按住判定, 再按名义位移走完"。 + """ + + def test_zero_distance_is_noop(self): + self.assertIsNone(aalc_input_patch.team_scroll_plan(10, 20, 0, 0, 0.3, 60)) + + def test_upward_swipe_escapes_first_then_travels_nominal_delta(self): + start, escape, end, duration = aalc_input_patch.team_scroll_plan(100, 200, 0, -200, 0.4, 60) + self.assertEqual(start, (100.0, 200.0)) + self.assertEqual(escape, (100.0, 140.0)) + self.assertEqual(end, (100.0, -60.0)) + self.assertAlmostEqual(end[1] - escape[1], -200.0) + self.assertEqual(duration, 0.4) + + def test_downward_swipe_shifts_start_into_visible_rows(self): + start, escape, end, _ = aalc_input_patch.team_scroll_plan(100, 200, 0, 200, 0.4, 60) + self.assertEqual(start, (100.0, 140.0)) + self.assertEqual(escape, (100.0, 200.0)) + self.assertEqual(end, (100.0, 400.0)) + self.assertAlmostEqual(end[1] - escape[1], 200.0) + + def test_escape_leg_has_requested_length(self): + start, escape, end, _ = aalc_input_patch.team_scroll_plan(0, 0, 300, -400, 0.5, 50) + leg = (escape[0] - start[0], escape[1] - start[1]) + self.assertAlmostEqual((leg[0] ** 2 + leg[1] ** 2) ** 0.5, 50.0) + self.assertAlmostEqual(end[0] - escape[0], 300.0) + self.assertAlmostEqual(end[1] - escape[1], -400.0) + + def test_install_patches_team_scroll_on_windows_adapters(self): + import types + + class FakeInput: + def mouse_swipe_for_team_scroll(self, *args, **kwargs): + raise AssertionError('未打补丁') + + class FakeBackground: + def set_mouse_pos(self, *args, **kwargs): + pass + + def mouse_swipe_for_team_scroll(self, *args, **kwargs): + raise AssertionError('未打补丁') + + class FakeWindowMove: + """没有 set_mouse_pos 的适配器保持原样。""" + + def mouse_swipe_for_team_scroll(self, *args, **kwargs): + raise AssertionError('未打补丁') + + leaf = types.ModuleType('module.automation.input_handlers.input') + leaf.Input = FakeInput + leaf.BackgroundInput = FakeBackground + leaf.WindowMoveInput = FakeWindowMove + parents = {} + for name in ('module', 'module.automation', 'module.automation.input_handlers'): + parents[name] = types.ModuleType(name) + parents[name].__path__ = [] + parents['module.automation.input_handlers'].input = leaf + parents['module.automation'].input_handlers = parents['module.automation.input_handlers'] + parents['module'].automation = parents['module.automation'] + + with mock.patch.dict(sys.modules, parents): + patched = aalc_input_patch.install() + self.assertEqual(patched, ['Input', 'BackgroundInput']) + self.assertIs(FakeInput.mouse_swipe_for_team_scroll, + aalc_input_patch._foreground_team_scroll) + self.assertIs(FakeBackground.mouse_swipe_for_team_scroll, + aalc_input_patch._adapter_team_scroll) + # 幂等: 再装一次不再重复补 + self.assertEqual(aalc_input_patch.install(), []) + + if __name__ == '__main__': unittest.main()