diff --git a/README.md b/README.md index f54fbd0..e322616 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,21 @@ vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts 运行数据默认写到 `~/lc_mcp/jev`,可用 `LC_JEV_HOME` 指定其他目录。创建该目录下的 `JEV_STOP` 文件即可停止;续跑前移除它。不要与 AALC 完整任务或另一个游戏执行器同时操作。 +每局运行现在有独立标识。默认续跑尚未结束且上下文一致的当前局;已完成或没有运行记录时建立新局。重新开一局时使用 `--new-run`,明确要求续跑时使用 `--resume`。旧版本未完成记录会保留楼层和强化进度,但旧的领取及战斗标记不会作为本局完成证据;只有上下文而没有运行记录时会重置它。领取截图和返回大厅截图必须属于当前局,才能记录完成。 + +```powershell +# 新开一局:清除上一局的楼层、饰品与领取状态 +vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts\jev_config.example.json --new-run --seconds 1800 +# 续跑已保存的未完成局,保持原计时起点 +vendor\aalc\.venv\Scripts\python.exe -X utf8 scripts\jev_mirror_agent.py scripts\jev_config.example.json --resume --seconds 1800 +``` + +MCP 客户端默认每次请求等待 30 秒,文字等待工具按自身时长延长响应期限。等待回复期间也检查停止标记和本次运行的时间预算。超时或中断时关闭客户端连接,并记录结果可能未知;不会自动重发点击或按键。常驻服务已经接收的操作可能仍会完成,需核对当前画面后再续跑。`battle_batch.py` 与主执行器共用判定、奖励、死亡和地图等战斗退出条件,并在每个按键前检查停止标记。 + +设置 `LC_FIXED_FALLBACK=1` 可只使用固定候选,无需 Jev API 密钥;仍需运行 MCP 服务。完整 AALC 任务启动时,如有 MCP 工具正在执行,会立即返回忙碌错误,避免与当前输入交错;查询与停止任务不受影响。 + +本轮修复、验证范围与已知限制见 [2026-10-03 运行可靠性改进](docs/mcp_runtime_improvements_20261003.md)。 + 本次修复、实际失败反馈、操作日志、截图清单、修改源码快照和速通 skill 见 [2026-10-02 实测记录](docs/feedback/2026-10-02/README.md);安装与测试说明见 [INSTALL_TEST_REPORT.md](INSTALL_TEST_REPORT.md)。这些是开发中的真实记录,包含失败和仍未验证的步骤。 ## 许可证 diff --git a/docs/mcp_runtime_improvements_20261003.md b/docs/mcp_runtime_improvements_20261003.md new file mode 100644 index 0000000..5d05541 --- /dev/null +++ b/docs/mcp_runtime_improvements_20261003.md @@ -0,0 +1,23 @@ +# MCP 运行可靠性改进(2026-10-03) + +基于 `97eca204` 的代码与另一台电脑提交的 2026-10-02 实测资料,修复离线复现确认的问题。改动未修改 AALC 子模块、输入后端或系统驱动;未启动游戏或重启常驻服务。 + +原先运行结束后,`claim_requested` 等上下文会遗留在磁盘。下一次执行器若读到这个标记与大厅文字,会把一个新的运行记录直接写成完成。现在运行记录与上下文共享 `run_id`;已完成局的状态不会被新局复用。领取和返回截图绑定当前局,缺少证据时不能设置完成字段。默认续跑有效的未完成记录;`--new-run` 建立全新状态,`--resume` 要求已有未完成记录。 + +旧版本未完成记录允许迁移:保留楼层、强化等进度,删除未绑定当前局的领取及战斗标记。没有运行记录的孤立上下文会重置。两份记录的标识不一致时停止并报告原因。JSON 快照改为临时文件写完后原子替换,中断不再留下半份 JSON。战斗上下文随当前局保存,也不再为推断它而读取全部历史动作日志。 + +原先客户端会无限阻塞在回复读取上;标准错误管道无人读取时也可能堵住子进程。现在标准输入、输出和错误流由独立线程处理,请求有期限,并在等待期间检查停止标记与运行预算。默认期限 30 秒,文字等待工具按其轮询时长增加 5 秒余量,仍受控制器总预算约束。初始化失败、超时、停止或无效回复均清理客户端子进程和管道。错误日志仅保留有限尾部供本地诊断。 + +超时不代表远端动作没有执行。客户端关闭连接后不会重放请求;状态日志记录 `outcome_unknown` 和相关工具名。停止或总预算耗尽时标记 stopped;超时和其他异常标记 requires_analysis。领取、完成、要求分析和异常终止会留下日志;步骤上限到达时也有明确停止状态。固定候选模式不再强制要求无用的 API 密钥。连接清理即使出错,也会释放执行器互斥句柄。 + +独立 `battle_batch.py` 原先漏掉判定、奖励卡与全员死亡界面。现在两个战斗入口共享场景识别,并在每个按键前检查停止标记和预算;空 OCR 的特写仍允许继续当前战斗,明确的退出界面则返回。新客户端在等待 MCP 回复期间也能响应停止。普通睡眠与已接收的服务端操作不保证立即取消。 + +MCP 请求现在先验证 JSON-RPC 外层、参数对象与工具名称/参数类型。坏请求返回协议错误,后续合法请求继续处理;通知不返回响应,也不能作为无 ID 的输入调用执行。`null` 请求不再被当作空行忽略。另修复完整任务启动与已经开始的手动输入之间的竞态:忙碌时立即拒绝启动完整任务,查询与停止任务仍不等待游戏工具锁。 + +验证使用 Python 3.12 的临时环境。全套 unittest:**105 项通过,无跳过**,其中原有 73 项,新增 32 项。新增测试包含真实子进程管道的无响应、阻塞写入、密集 stderr、中文响应、初始化失败与取消;还通过实际 bridge 连入隔离的 FakeEngine TCP 服务,验证新客户端与原有桥接的兼容性。其他测试核对旧状态迁移、领取证据、原子写入失败、任务并发、按键中途停止和终止界面。所有游戏输入均为 mock 或 FakeEngine,没有操作真实游戏。 + +测试通过证明这些离线边界已修复,不能证明自动通关或提速。另一台电脑的第一局最后确认由用户完成,第二局以人工接管结束;后续完整流程、截图识别和速度效果仍需要新的一局实测。商店合成/强化、未明确识别的事件等仍可能要求主助手核对。约 70 MB 历史截图压缩包未下载,已分析保存的独立证据截图与日志。 + +下一轮实测应从开局到领取后返回大厅使用同一 run_id,保留人工干预记录;出现 outcome_unknown 时先核对游戏画面,避免重复确认已经执行的操作。新开局使用 --new-run,重启游戏后继续同一存档使用 --resume。停止文件需要在准备继续时移除。 + +本轮提交只包含程序、测试和说明文件,没有包含个人运行记录、凭据、虚拟环境或历史物理驱动资料。 diff --git a/lc_mcp/protocol.py b/lc_mcp/protocol.py index 5ba0aff..bf97e7e 100644 --- a/lc_mcp/protocol.py +++ b/lc_mcp/protocol.py @@ -78,6 +78,18 @@ class Server: if not isinstance(msg, dict): return _error(None, -32600, 'request must be a JSON object') method, mid = msg.get('method'), msg.get('id') + valid_id = (mid is None or isinstance(mid, str) or + isinstance(mid, (int, float)) and not isinstance(mid, bool) and + (not isinstance(mid, float) or math.isfinite(mid))) + if msg.get('jsonrpc') != '2.0' or not isinstance(method, str) or not method or not valid_id: + return _error(mid if valid_id else None, -32600, 'invalid JSON-RPC request') + notification = 'id' not in msg + params = msg.get('params', {}) + if not isinstance(params, dict): + return None if notification else _error(mid, -32602, 'params must be an object') + # Notifications never produce responses or trigger request-only tools. + if notification: + return None if method == 'initialize': return _ok(mid, {'protocolVersion': '2024-11-05', 'capabilities': {'tools': {'listChanged': False}}, @@ -87,17 +99,17 @@ class Server: if method == 'tools/list': return _ok(mid, {'tools': TOOLS}) if method == 'tools/call': - params = msg.get('params') or {} - result = self.call_tool(params.get('name'), params.get('arguments') or {}) + name, arguments = params.get('name'), params.get('arguments', {}) + if not isinstance(name, str) or not name.strip() or not isinstance(arguments, dict): + return _error(mid, -32602, 'tools/call requires a name and object arguments') + result = self.call_tool(name, arguments) return _ok(mid, {'content': [{'type': 'text', 'text': json.dumps(result, ensure_ascii=False)}], 'isError': not result.get('ok', False)}) - if mid is None: - return None # 通知 (notifications/*) 不回 return _error(mid, -32601, 'method not found: %s' % method) def call_tool(self, name, args): try: - if name in TASK_TOOLS: # 不抢游戏锁: wait_for_text 期间也能查任务/停任务 + if name in TASK_TOOLS: # 查任务/停任务不等待正在执行的游戏工具 return self._task_tool(name, args) with self.lock: return self._call(name, args) @@ -113,7 +125,14 @@ class Server: if task not in TASKS: raise ValueError('unknown task %r' % task) params = {k: int(a[k]) for k in TASKS[task] if a.get(k) is not None} - return self.tasks.start(task, params) + # Starting must not race a click that has already checked running(). + # Reject promptly when busy instead of waiting behind a long OCR poll. + if not self.lock.acquire(blocking=False): + return {'ok': False, 'error': 'MCP 工具正在执行,完成后再启动 AALC 任务'} + try: + return self.tasks.start(task, params) + finally: + self.lock.release() if name == 'task_status': return self.tasks.status(a.get('lines', 30)) return self.tasks.stop() @@ -216,6 +235,9 @@ def parse_line(line): if not line: return None, None try: - return json.loads(line), None + msg = json.loads(line) + if msg is None: + return None, _error(None, -32600, 'request must be a JSON object') + return msg, None except ValueError as e: return None, _error(None, -32700, 'parse error: %s' % e) diff --git a/scripts/battle_batch.py b/scripts/battle_batch.py index 5420e5c..620a29b 100644 --- a/scripts/battle_batch.py +++ b/scripts/battle_batch.py @@ -1,16 +1,18 @@ """Bounded P/Enter batches through MCP; stop when the battle UI disappears.""" import argparse import json +import math +import os import time -from mcp_session import Session +from pathlib import Path +from mcp_session import Session, SessionCancelled, SessionTimeout +from game_scenes import battle_is_terminal, battle_is_visible + +STOP_FILE = Path(os.environ.get('LC_JEV_HOME', str(Path.home() / 'lc_mcp' / 'jev'))) / 'JEV_STOP' def is_terminal(state): - texts = [item['text'].replace(' ', '') for item in state.get('items', [])] - return any(text.upper() in ('VICTORY', 'DEFEAT') or - any(marker in text for marker in ('正在探索', '获得E.G.O饰品', '选择主题卡包', - '开始战斗', '选择一位罪人', '选项事件')) - for text in texts) + return battle_is_terminal(state) def main(): @@ -18,24 +20,38 @@ def main(): parser.add_argument('--seconds', type=float, default=40) parser.add_argument('--battle-confirmed', action='store_true') args = parser.parse_args() + if not math.isfinite(args.seconds) or args.seconds <= 0: + parser.error('--seconds must be finite and positive') deadline = time.monotonic() + min(50, max(1, args.seconds)) pairs = 0 - with Session() as client: - state = client.call('get_state') - texts = ' '.join(item['text'] for item in state.get('items', [])) - active = args.battle_confirmed or any(marker in texts.upper() for marker in ('WAVE', 'TURN', 'DURANTE', '胜率', '伤害')) - while time.monotonic() < deadline: - # 战斗特写会隐藏 HUD;只有明确的结算/地图/选项信号才退出。 - if not active or is_terminal(state): - break - # 短批次,批次末只检查界面是否仍为战斗,不分析拼点。 - for _ in range(2): - client.call('keypress', {'key': 'p'}) - client.call('keypress', {'key': 'enter'}) - pairs += 1 - time.sleep(1.5) + state = {} + def cancelled(): + return STOP_FILE.exists() or time.monotonic() >= deadline + try: + if cancelled(): + raise SessionCancelled('Battle batch stopped before connecting') + with Session(cancelled=cancelled) as client: state = client.call('get_state') - print(json.dumps({'pairs': pairs, 'state': state}, ensure_ascii=False)) + active = args.battle_confirmed or battle_is_visible(state) + while not cancelled(): + # Cinematics hide the HUD; explicit scene boundaries end combat. + if not state.get('ok') or not active or is_terminal(state): + break + for _ in range(2): + for key in ('p', 'enter'): + if cancelled(): + raise SessionCancelled('Battle batch stopped between keys') + client.call('keypress', {'key': key}) + pairs += 1 + time.sleep(min(1.5, max(0, deadline - time.monotonic()))) + if cancelled(): + break + state = client.call('get_state') + result = {'pairs': pairs, 'state': state, 'stopped': cancelled()} + except (SessionCancelled, SessionTimeout) as error: + result = {'pairs': pairs, 'state': state, 'stopped': True, + 'error': str(error), 'outcome_unknown': error.outcome_unknown} + print(json.dumps(result, ensure_ascii=False)) if __name__ == '__main__': diff --git a/scripts/game_scenes.py b/scripts/game_scenes.py new file mode 100644 index 0000000..52823ea --- /dev/null +++ b/scripts/game_scenes.py @@ -0,0 +1,28 @@ +"""Shared battle boundaries for all MCP controllers.""" + + +def normalized_texts(state): + return [item['text'].replace(' ', '') for item in state.get('items', [])] + + +def death_retry_screen(texts): + combined = '\n'.join(texts) + return ('全体罪人' in combined and '死亡' in combined + or '当前剩余人员' in combined and '重试关卡' in combined) + + +def battle_is_terminal(state): + texts = normalized_texts(state) + markers = ('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', + '开始战斗', '主题卡包', '应该让谁', '选择一位罪人', '进行判定', + '选择遭遇战奖励卡', '选项事件', '选择苦难', '选项', '结果', + '探索完成', '探索结束', '驾驶席', '服务器发生错误', '重试关卡') + return death_retry_screen(texts) or any( + text.upper() in ('VICTORY', 'DEFEAT') or any(marker in text for marker in markers) + for text in texts) + + +def battle_is_visible(state): + texts = normalized_texts(state) + return (any(marker in '\n'.join(texts).upper() for marker in ('WAVE', 'TURN', 'DURANTE')) + or any(text in ('胜率', '伤害') for text in texts)) diff --git a/scripts/jev_mirror_agent.py b/scripts/jev_mirror_agent.py index 890ce34..5521912 100644 --- a/scripts/jev_mirror_agent.py +++ b/scripts/jev_mirror_agent.py @@ -11,7 +11,9 @@ import urllib.error import urllib.request from pathlib import Path -from mcp_session import Session as Bridge +from mcp_session import Session as Bridge, SessionCancelled, SessionTimeout +from game_scenes import battle_is_terminal, battle_is_visible, death_retry_screen +from run_state import prepare_run, save_json, record_claim, claim_is_current, complete_run REPO_ROOT = Path(__file__).resolve().parents[1] RUNTIME_HOME = Path(os.environ.get('LC_JEV_HOME', str(Path.home() / 'lc_mcp' / 'jev'))) @@ -40,12 +42,6 @@ def text_items(state): return state.get('items') or [] -def death_retry_screen(texts): - combined = '\n'.join(texts) - return ('全体罪人' in combined and '死亡' in combined - or '当前剩余人员' in combined and '重试关卡' in combined) - - def button_enabled(state, item): try: from PIL import Image @@ -478,9 +474,8 @@ def candidates(state, previous_battle=False, refresh_used=0): 'action': {'tool': 'click', 'args': {'x': item['x'] + item['w'] // 2, 'y': item['y'] + item['h'] // 2}}, } - end_screen = any(t.upper() in ('VICTORY', 'DEFEAT') or any(m in t for m in - ('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', '开始战斗', '主题卡包', '应该让谁', '选择一位罪人', '进行判定', '选择遭遇战奖励卡')) for t in texts) - battle = any(m in combined.upper() for m in ('WAVE', 'TURN', 'DURANTE')) or any(t in ('胜率', '伤害') for t in texts) + end_screen = battle_is_terminal(state) + battle = battle_is_visible(state) if not end_screen and (battle or previous_battle): options['battle'] = {'description': '仍处于战斗或特写:执行短批次 P→回车,两次后检查结算,不分析拼点。', 'action': {'tool': 'battle', 'args': {'rounds': 2}}} @@ -629,9 +624,9 @@ def fixed_fallback(options): return 'requires_analysis' -def execute(bridge, action): +def execute(bridge, action, deadline=None): def call(tool, args=None): - if STOP_FILE.exists(): + if STOP_FILE.exists() or deadline is not None and time.monotonic() >= deadline: return {'ok':False,'stopped':True} return bridge.call(tool, args) if action['tool'] == 'claim_final': @@ -661,9 +656,9 @@ def execute(bridge, action): time.sleep(0.7) return {'ok': True, 'waited': 0.7} if action['tool'] == 'battle': - deadline = time.monotonic() + 45 + battle_deadline = min(deadline if deadline is not None else float('inf'), time.monotonic() + 45) pairs = 0 - while time.monotonic() < deadline and not STOP_FILE.exists(): + while time.monotonic() < battle_deadline and not STOP_FILE.exists(): for _ in range(2): for key in ('p', 'enter'): result = call('keypress', {'key': key}) @@ -675,13 +670,10 @@ def execute(bridge, action): state = call('get_state') if not state.get('ok'): return state - texts = [i['text'].replace(' ', '') for i in text_items(state)] - terminal = death_retry_screen(texts) or any(t.upper() in ('VICTORY', 'DEFEAT') or any(m in t for m in - ('正在探', '获得E.G.O饰品', '选择E.G.O饰品', '饰品观测', '开始战斗', '主题卡包', - '应该让谁', '选择一位罪人', '进行判定', '选择遭遇战奖励卡', '选项事件', '选择苦难', '选项', '结果')) for t in texts) - if terminal: + if battle_is_terminal(state): return {'ok': True, 'pairs': pairs, 'terminal': True, 'screen': state.get('screen')} - return {'ok': not STOP_FILE.exists(), 'stopped':STOP_FILE.exists(), 'pairs': pairs, 'terminal': False} + stopped = STOP_FILE.exists() or deadline is not None and time.monotonic() >= deadline + return {'ok': not stopped, 'stopped': stopped, 'pairs': pairs, 'terminal': False} return call(action['tool'], action.get('args')) @@ -690,7 +682,12 @@ def main(): parser.add_argument('config') parser.add_argument('--steps', type=int, default=250) parser.add_argument('--seconds', type=int, default=1200) + mode = parser.add_mutually_exclusive_group() + mode.add_argument('--new-run', action='store_true', help='Start fresh state for a new dungeon') + mode.add_argument('--resume', action='store_true', help='Require an unfinished run with matching state') args = parser.parse_args() + if args.steps <= 0 or args.seconds <= 0: + parser.error('--steps and --seconds must be positive') # 防止另一个终端重复启动同一个游戏的执行器。 import ctypes kernel = ctypes.windll.kernel32 @@ -702,34 +699,35 @@ def main(): if lease: kernel.CloseHandle(ctypes.c_void_p(lease)) return - cfg = json.loads(Path(args.config).read_text(encoding='utf-8')) - cfg['apiKey'] = os.environ.get('OPENCODE_API_KEY') or cfg.get('apiKey') - if not cfg['apiKey']: - kernel.CloseHandle(ctypes.c_void_p(lease)) - raise RuntimeError('Set OPENCODE_API_KEY or use an untracked local config with apiKey') - RUNTIME_HOME.mkdir(parents=True, exist_ok=True) log = RUNTIME_HOME / 'jev_mirror_log.jsonl' status = RUNTIME_HOME / 'jev_mirror_status.json' - bridge = Bridge() deadline = time.monotonic() + args.seconds + bridge = None + run = None recent = [] repeats = {} - previous_battle = False - if log.exists(): - last_lines = log.read_text(encoding='utf-8').splitlines() - if last_lines: - last_record = json.loads(last_lines[-1]) - previous_battle = last_record.get('battle_context', last_record.get('action', {}).get('tool') == 'battle') context_path = RUNTIME_HOME / 'jev_shop_context.json' - context = json.loads(context_path.read_text(encoding='utf-8')) if context_path.exists() else {'refresh_used': 0} stable_since = time.monotonic() last_fingerprint = None unknown_since = None decision_fallback_reason = None try: + RUNTIME_HOME.mkdir(parents=True, exist_ok=True) + cfg = json.loads(Path(args.config).read_text(encoding='utf-8-sig')) + cfg['apiKey'] = os.environ.get('OPENCODE_API_KEY') or cfg.get('apiKey') + if not cfg['apiKey'] and os.environ.get('LC_FIXED_FALLBACK') != '1': + raise RuntimeError('Set OPENCODE_API_KEY or enable LC_FIXED_FALLBACK=1') + if STOP_FILE.exists(): + save_json(status, {'state': 'stopped', 'reason': 'stop_requested'}) + return + run, context = prepare_run(RUNTIME_HOME, args.new_run, args.resume) + previous_battle = context.get('battle_context', False) + bridge = Bridge(cancelled=lambda: STOP_FILE.exists() or time.monotonic() >= deadline) for step in range(args.steps): if STOP_FILE.exists() or time.monotonic() > deadline: - status.write_text(json.dumps({'state': 'stopped', 'step': step}), encoding='utf-8') + run['status'] = 'stopped' + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, {'state': 'stopped', 'step': step, 'run_id': run['run_id']}) return observation_started = time.monotonic() state = bridge.call('get_state') @@ -745,13 +743,13 @@ def main(): match = re.search(r'(?:第|选择)([1-5])层', item['text'].replace(' ', '')) if match: context['floor'] = int(match[1]) - context_path.write_text(json.dumps(context), encoding='utf-8') - state['floor'] = context.get('floor', 3) + save_json(context_path, context) + state['floor'] = context.get('floor', 1) state['symbol_upgraded'] = context.get('symbol_upgraded', False) state['battery_obtained'] = context.get('battery_obtained', False) state['thunderbranch_pending'] = context.get('thunderbranch_pending',False) state['thrill_pending'] = context.get('thrill_obtained',False) and not context.get('thrill_upgraded',False) - state['claim_requested'] = context.get('claim_requested', False) + state['claim_requested'] = claim_is_current(run, context) options = candidates(state, previous_battle, context['refresh_used']) if fingerprint != last_fingerprint: stable_since = time.monotonic() @@ -805,71 +803,88 @@ def main(): decision_fallback_reason='Jev HTTP %d; deterministic fallback for this session' % error.code choice, latency=fixed_fallback(options),0 action = options[choice]['action'] - record = {'step': step, 'choice': choice, 'action': action, 'jev_ms': latency, + record = {'step': step, 'run_id': run['run_id'], 'choice': choice, 'action': action, 'jev_ms': latency, 'ocr_ms':observation_ms,'screen': state.get('screen'), 'at': time.strftime('%Y-%m-%dT%H:%M:%S')} if decision_fallback_reason: record['decision_fallback_reason']=decision_fallback_reason if choice == 'run_complete': + complete_run(RUNTIME_HOME, run, context, state.get('screen')) record['state'] = 'completed' - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') - run_path = RUNTIME_HOME / 'mirror_current_run.json' - if run_path.exists(): - from datetime import datetime, timezone - run = json.loads(run_path.read_text(encoding='utf-8')) - now = datetime.now(timezone.utc) - run.update(status='completed', dungeon_completed=True, final_reward_claimed=True, - end_utc=now.isoformat(), elapsed_seconds=(now-datetime.fromisoformat(run['start_utc'])).total_seconds(), - completion_evidence=state.get('screen')) - run_path.write_text(json.dumps(run, ensure_ascii=False, indent=2), encoding='utf-8') + save_json(status, record) + with log.open('a', encoding='utf-8') as output: + output.write(json.dumps(record, ensure_ascii=False) + '\n') print(json.dumps(record, ensure_ascii=False), flush=True) return if choice == 'requires_analysis': record.update(state='requires_analysis', items=text_items(state)) - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') + run['status'] = 'requires_analysis' + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, record) + with log.open('a', encoding='utf-8') as output: + output.write(json.dumps(record, ensure_ascii=False) + '\n') print(json.dumps(record, ensure_ascii=False), flush=True) return action_id = json.dumps(action, sort_keys=True) repeats[(fingerprint, action_id)] = repeats.get((fingerprint, action_id), 0) + 1 action_started = time.monotonic() - result = execute(bridge, action) + result = execute(bridge, action, deadline=deadline) record['action_ms'] = round((time.monotonic()-action_started)*1000) record['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%S') if result.get('stopped'): record.update(result=result,state='stopped',battle_context=previous_battle) with log.open('a',encoding='utf-8') as output: output.write(json.dumps(record,ensure_ascii=False)+'\n') - status.write_text(json.dumps(record,ensure_ascii=False),encoding='utf-8') + run['status'] = 'stopped' + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, record) return if choice == 'claim_final' and result.get('ok'): - context['claim_requested'] = True - context_path.write_text(json.dumps(context), encoding='utf-8') + record_claim(RUNTIME_HOME, run, context, state.get('screen')) if choice in ('confirm_startup_battery','confirm_thunderbranch') and result.get('ok'): context['battery_obtained' if choice == 'confirm_startup_battery' else 'thunderbranch_pending'] = True - context_path.write_text(json.dumps(context),encoding='utf-8') + save_json(context_path, context) if choice=='modal_confirm' and result.get('ok') and any(i['text'].replace(' ','')=='快感' for i in text_items(state)) and any('获得E.G.O' in i['text'].replace(' ','') for i in text_items(state)): context['thrill_obtained']=True - context_path.write_text(json.dumps(context),encoding='utf-8') + save_json(context_path, context) if choice == 'shop_refresh': context['refresh_used'] += 1 - context_path.write_text(json.dumps(context), encoding='utf-8') + save_json(context_path, context) started_battle = choice.startswith('button_') and any( i['text'].replace(' ', '') == '开始战斗' for i in text_items(state)) previous_battle = ((action['tool'] == 'battle' and not result.get('terminal')) or started_battle or (previous_battle and action['tool'] == 'wait')) + context['battle_context'] = previous_battle + save_json(context_path, context) record.update(result=result, state='running', battle_context=previous_battle) with log.open('a', encoding='utf-8') as output: output.write(json.dumps(record, ensure_ascii=False) + '\n') - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') + save_json(status, record) recent.append({'action': action, 'ok': result.get('ok'), 'unchanged_attempt': repeats[(fingerprint, action_id)]}) print(json.dumps({k:v for k,v in record.items() if k != 'items'}, ensure_ascii=False), flush=True) time.sleep(0.35) + run['status'] = 'stopped' + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, {'state': 'stopped', 'reason': 'step_limit', 'run_id': run['run_id']}) except Exception as error: - record = {'state': 'requires_analysis', 'error': '%s: %s' % (type(error).__name__, str(error))} - status.write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8') + state = 'stopped' if isinstance(error, SessionCancelled) else 'requires_analysis' + record = {'state': state, 'error': '%s: %s' % (type(error).__name__, str(error))} + if isinstance(error, (SessionCancelled, SessionTimeout)): + record['outcome_unknown'] = error.outcome_unknown + record['pending_tool'] = getattr(error, 'tool', None) + if run is not None: + run['status'] = state + record['run_id'] = run['run_id'] + save_json(RUNTIME_HOME / 'mirror_current_run.json', run) + save_json(status, record) + with log.open('a', encoding='utf-8') as output: + output.write(json.dumps(record, ensure_ascii=False) + '\n') print(json.dumps(record, ensure_ascii=False), flush=True) finally: - bridge.close() - kernel.CloseHandle(ctypes.c_void_p(lease)) + try: + if bridge is not None: + bridge.close() + finally: + kernel.CloseHandle(ctypes.c_void_p(lease)) if __name__ == '__main__': diff --git a/scripts/mcp_session.py b/scripts/mcp_session.py index dada977..d783129 100644 --- a/scripts/mcp_session.py +++ b/scripts/mcp_session.py @@ -1,13 +1,39 @@ """Reusable client for the installed stdio MCP bridge; no direct game input.""" import json +import math import os +import queue import subprocess import sys +import threading +import time +from collections import deque from pathlib import Path +class SessionCancelled(InterruptedError): + """The caller stopped waiting; a sent remote action may have completed.""" + + def __init__(self, message, outcome_unknown=False): + super().__init__(message) + self.outcome_unknown = outcome_unknown + + +class SessionTimeout(TimeoutError): + outcome_unknown = True + + class Session: - def __init__(self): + def __init__(self, timeout=30, cancelled=None): + self.timeout = float(timeout) + if not math.isfinite(self.timeout) or self.timeout <= 0: + raise ValueError('MCP timeout must be finite and positive') + self.cancelled = cancelled or (lambda: False) + self._closed = False + self._lock = threading.Lock() + self._responses = queue.Queue() + self._outgoing = queue.Queue() + self.stderr_tail = deque(maxlen=20) root = Path(__file__).resolve().parents[1] self.process = subprocess.Popen( [sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')], @@ -16,45 +42,137 @@ class Session: text=True, encoding='utf-8', bufsize=1, ) self.sequence = 0 - self.request('initialize', { - 'protocolVersion': '2024-11-05', 'capabilities': {}, - 'clientInfo': {'name': 'lc-mcp-session', 'version': '1'}, - }) - self.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n') - self.process.stdin.flush() + # Windows pipes cannot be polled with select(). Dedicated readers and + # a writer let the caller cancel even if a pipe read/write is blocked. + self._threads = [threading.Thread(target=target, daemon=True) for target in + (self._read_responses, self._write_requests, self._drain_stderr)] + for thread in self._threads: + thread.start() + try: + self.request('initialize', { + 'protocolVersion': '2024-11-05', 'capabilities': {}, + 'clientInfo': {'name': 'lc-mcp-session', 'version': '1'}, + }) + self._send({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + except BaseException: + self._abort() + raise - def request(self, method, params): - self.sequence += 1 - mid = self.sequence - request = {'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params} - self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n') - self.process.stdin.flush() - while True: - line = self.process.stdout.readline() - if not line: - raise ConnectionError('MCP bridge closed') - result = json.loads(line) - if result.get('id') == mid: - if 'error' in result: - raise RuntimeError(result['error']['message']) - return result['result'] + def _read_responses(self): + try: + for line in self.process.stdout: + self._responses.put(line) + except (OSError, ValueError, UnicodeError) as error: + self._responses.put(error) + finally: + self._responses.put(None) + + def _write_requests(self): + try: + while True: + line = self._outgoing.get() + if line is None: + break + self.process.stdin.write(line) + self.process.stdin.flush() + except (OSError, ValueError) as error: + self._responses.put(error) + finally: + try: + self.process.stdin.close() + except (OSError, ValueError): + pass + + def _drain_stderr(self): + try: + for line in self.process.stderr: + self.stderr_tail.append(line.rstrip()[-2000:]) + except (OSError, ValueError, UnicodeError): + return + + def _send(self, message): + if self._closed: + raise ConnectionError('MCP session is closed') + self._outgoing.put(json.dumps(message, ensure_ascii=False) + '\n') + + def request(self, method, params, timeout=None): + limit = self.timeout if timeout is None else float(timeout) + if not math.isfinite(limit) or limit <= 0: + raise ValueError('MCP timeout must be finite and positive') + with self._lock: + if self.cancelled(): + self._abort() + raise SessionCancelled('MCP request cancelled before sending') + self.sequence += 1 + mid = self.sequence + self._send({'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params}) + deadline = time.monotonic() + limit + while True: + if self.cancelled(): + self._abort() + error = SessionCancelled('MCP request cancelled; remote outcome unknown', True) + error.tool = params.get('name') if isinstance(params, dict) else None + raise error + remaining = deadline - time.monotonic() + if remaining <= 0: + self._abort() + error = SessionTimeout('MCP %s timed out; remote outcome unknown; request was not retried' % method) + error.tool = params.get('name') if isinstance(params, dict) else None + raise error + try: + line = self._responses.get(timeout=min(.1, remaining)) + except queue.Empty: + continue + if line is None or isinstance(line, Exception): + self._abort() + raise ConnectionError('MCP bridge closed') from (line if isinstance(line, Exception) else None) + try: + result = json.loads(line) + if not isinstance(result, dict): + raise ValueError('response must be an object') + except ValueError as error: + self._abort() + raise ConnectionError('MCP bridge returned invalid JSON-RPC') from error + if result.get('id') == mid: + if 'error' in result: + raise RuntimeError(result['error']['message']) + return result['result'] def call(self, name, arguments=None): - result = self.request('tools/call', {'name': name, 'arguments': arguments or {}}) + arguments = {} if arguments is None else arguments + timeout = self.timeout + if name in ('wait_for_text', 'wait_for_text_gone') and isinstance(arguments, dict): + try: + wait = float(arguments.get('timeout', 30)) + if math.isfinite(wait): + timeout = max(timeout, min(300, max(0, wait)) + 5) + except (TypeError, ValueError): + pass # The server reports invalid tool arguments. + result = self.request('tools/call', {'name': name, 'arguments': arguments}, timeout) data = json.loads(result['content'][0]['text']) if result.get('isError'): raise RuntimeError(data) return data + def _abort(self): + if self.process.poll() is None: + self.process.kill() + self.close() + def close(self): - self.process.stdin.close() + if self._closed: + return + self._closed = True + self._outgoing.put(None) try: - self.process.wait(5) + self.process.wait(1) except subprocess.TimeoutExpired: self.process.kill() self.process.wait() - self.process.stdout.close() - self.process.stderr.close() + for thread in self._threads: + thread.join(1) + for stream in (self.process.stdin, self.process.stdout, self.process.stderr): + stream.close() def __enter__(self): return self diff --git a/scripts/run_state.py b/scripts/run_state.py new file mode 100644 index 0000000..23b1f4f --- /dev/null +++ b/scripts/run_state.py @@ -0,0 +1,99 @@ +"""Persist one mirror run without carrying completed-run state into a new run.""" +import json +import os +import tempfile +import uuid +from datetime import datetime, timezone +from pathlib import Path + +RESUMABLE = {'running', 'requires_analysis', 'stopped', 'user_takeover'} + + +def save_json(path, value): + """Replace complete snapshots atomically so interruption cannot truncate them.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = None + try: + with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, + prefix=path.name + '.', suffix='.tmp', delete=False) as output: + temporary = Path(output.name) + json.dump(value, output, ensure_ascii=False, indent=2) + output.write('\n') + os.replace(temporary, path) + finally: + if temporary is not None and temporary.exists(): + temporary.unlink() + + +def load_json(path): + if not path.exists(): + return None + value = json.loads(path.read_text(encoding='utf-8-sig')) + if not isinstance(value, dict): + raise ValueError('%s must contain an object' % path.name) + return value + + +def prepare_run(home, new_run=False, resume=False): + home = Path(home) + run_path = home / 'mirror_current_run.json' + context_path = home / 'jev_shop_context.json' + # Explicit new-run also recovers from corrupt or legacy state files. + run = None if new_run else load_json(run_path) + resumable = run is not None and run.get('status') in RESUMABLE + if resume and not resumable: + raise ValueError('No unfinished run to resume; use --new-run for a new dungeon') + if resumable: + started = datetime.fromisoformat(run['start_utc']) + if started.tzinfo is None: + raise ValueError('Run start_utc must include a timezone') + context = load_json(context_path) or {} + run_id = run.get('run_id') or uuid.uuid4().hex + if context.get('run_id') not in (None, run_id): + raise ValueError('Run/context IDs differ; inspect the state or use --new-run') + if context.get('run_id') is None: + # Keep legacy floor/upgrades for an unfinished run, but an unbound + # claim or battle flag cannot establish current-run completion. + for key in ('claim_requested', 'claim_run_id', 'claim_screen', 'claim_at_utc', 'battle_context'): + context.pop(key, None) + run['legacy_context_migrated'] = True + context.setdefault('refresh_used', 0) + context.setdefault('floor', 1) + context['run_id'] = run_id + run['run_id'] = run_id + run['status'] = 'running' + else: + run_id = uuid.uuid4().hex + run = {'run_id': run_id, 'start_utc': datetime.now(timezone.utc).isoformat(), + 'status': 'running', 'dungeon_completed': False, 'final_reward_claimed': False} + context = {'run_id': run_id, 'refresh_used': 0, 'floor': 1} + save_json(run_path, run) + save_json(context_path, context) + return run, context + + +def claim_is_current(run, context): + screen = context.get('claim_screen') + return bool(context.get('claim_requested') and context.get('run_id') == run['run_id'] + and context.get('claim_run_id') == run['run_id'] + and isinstance(screen, dict) and screen.get('path')) + + +def record_claim(home, run, context, screen): + if not screen or not screen.get('path'): + raise ValueError('Final claim requires an observed completion screenshot') + context.update(claim_requested=True, claim_run_id=run['run_id'], claim_screen=screen, + claim_at_utc=datetime.now(timezone.utc).isoformat()) + save_json(Path(home) / 'jev_shop_context.json', context) + + +def complete_run(home, run, context, screen): + if not claim_is_current(run, context) or not screen or not screen.get('path'): + raise ValueError('Completion requires current-run claim and return-screen evidence') + now = datetime.now(timezone.utc) + run.update(status='completed', dungeon_completed=True, final_reward_claimed=True, + end_utc=now.isoformat(), + elapsed_seconds=(now-datetime.fromisoformat(run['start_utc'])).total_seconds(), + claim_evidence=context['claim_screen'], completion_evidence=screen) + save_json(Path(home) / 'mirror_current_run.json', run) diff --git a/tests/test_controller_runtime.py b/tests/test_controller_runtime.py new file mode 100644 index 0000000..ffb943e --- /dev/null +++ b/tests/test_controller_runtime.py @@ -0,0 +1,156 @@ +"""Controller lifecycle and battle regressions using mocked MCP only.""" +import contextlib +import ctypes +import io +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +import battle_batch +import jev_mirror_agent as agent +from mcp_session import SessionCancelled, SessionTimeout +from run_state import save_json + + +class BattleBatchTest(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.stop = Path(self.folder.name) / 'JEV_STOP' + + def run_helper(self, client): + session = mock.MagicMock() + session.__enter__.return_value = client + output = io.StringIO() + with mock.patch.object(battle_batch, 'Session', return_value=session), \ + mock.patch.object(battle_batch, 'STOP_FILE', self.stop), \ + mock.patch.object(sys, 'argv', ['battle_batch.py', '--seconds', '1', '--battle-confirmed']), \ + mock.patch.object(battle_batch.time, 'sleep'), contextlib.redirect_stdout(output): + battle_batch.main() + return json.loads(output.getvalue()) + + def test_terminal_screens_never_receive_more_keys(self): + for text in ('进行判定', '选择遭遇战奖励卡', '参加战斗的全体罪人已经死亡。'): + with self.subTest(text=text): + client = mock.Mock() + client.call.return_value = {'ok': True, 'items': [{'text': text}]} + result = self.run_helper(client) + self.assertEqual(result['pairs'], 0) + self.assertEqual(client.call.call_args_list, [mock.call('get_state')]) + + def test_stop_after_p_prevents_enter(self): + client = mock.Mock() + def call(tool, args=None): + if tool == 'get_state': + return {'ok': True, 'items': [{'text': 'WAVE 1'}]} + self.stop.touch() + return {'ok': True} + client.call.side_effect = call + result = self.run_helper(client) + self.assertTrue(result['stopped']) + self.assertFalse(result['outcome_unknown']) + self.assertEqual(client.call.call_args_list, [mock.call('get_state'), mock.call('keypress', {'key': 'p'})]) + + def test_judgement_after_one_batch_ends_without_a_second_batch(self): + client = mock.Mock() + frames = iter(['WAVE 1', '选择一位罪人来进行判定']) + client.call.side_effect = lambda tool, args=None: ( + {'ok': True, 'items': [{'text': next(frames)}]} if tool == 'get_state' else {'ok': True}) + result = self.run_helper(client) + self.assertEqual(result['pairs'], 2) + self.assertEqual(sum(call.args[0] == 'keypress' for call in client.call.call_args_list), 4) + + +class AgentRuntimeTest(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.home = Path(self.folder.name) + self.config = self.home / 'config.json' + self.config.write_text('{}') + self.kernel = mock.Mock() + self.kernel.CreateMutexW.return_value = 12345 + self.kernel.GetLastError.return_value = 0 + + def run_agent(self, bridge, extra_args=(), constructor_error=None): + output = io.StringIO() + environment = dict(os.environ, LC_FIXED_FALLBACK='1') + environment.pop('OPENCODE_API_KEY', None) + with mock.patch.object(agent, 'RUNTIME_HOME', self.home), \ + mock.patch.object(agent, 'STOP_FILE', self.home / 'JEV_STOP'), \ + mock.patch.object(agent, 'Bridge', return_value=bridge, side_effect=constructor_error) as factory, \ + mock.patch.object(ctypes, 'windll', mock.Mock(kernel32=self.kernel), create=True), \ + mock.patch.object(sys, 'argv', ['jev_mirror_agent.py', str(self.config), '--steps', '1', *extra_args]), \ + mock.patch.dict(os.environ, environment, clear=True), \ + mock.patch.object(agent.time, 'sleep'), \ + mock.patch.object(agent, 'button_enabled', return_value=False), \ + contextlib.redirect_stdout(output): + agent.main() + status = json.loads((self.home / 'jev_mirror_status.json').read_text()) + return status, factory + + def test_old_claim_context_does_not_complete_new_run_at_lobby(self): + save_json(self.home / 'jev_shop_context.json', {'floor': 5, 'claim_requested': True}) + save_json(self.home / 'mirror_current_run.json', { + 'start_utc': '2026-10-02T00:00:00+00:00', 'status': 'running', + 'dungeon_completed': False, 'final_reward_claimed': False}) + bridge = mock.Mock() + bridge.call.return_value = {'ok': True, 'items': [ + {'text': text, 'score': 1} for text in ('探索状态', '进入', '名与蛛之镜')]} + status, _ = self.run_agent(bridge) + run = json.loads((self.home / 'mirror_current_run.json').read_text()) + self.assertEqual(status['state'], 'stopped') + self.assertFalse(run['dungeon_completed']) + self.assertFalse(run['final_reward_claimed']) + bridge.close.assert_called_once() + self.assertEqual(self.kernel.CloseHandle.call_count, 1) + + def test_bridge_initialization_failure_records_error_and_releases_mutex(self): + status, _ = self.run_agent(mock.Mock(), constructor_error=SessionTimeout('initialization hung')) + self.assertEqual(status['state'], 'requires_analysis') + self.assertTrue(status['outcome_unknown']) + self.assertEqual(self.kernel.CloseHandle.call_count, 1) + + def test_stop_file_prevents_bridge_startup(self): + (self.home / 'JEV_STOP').touch() + status, factory = self.run_agent(mock.Mock()) + self.assertEqual(status['state'], 'stopped') + factory.assert_not_called() + self.assertEqual(self.kernel.CloseHandle.call_count, 1) + + def test_pending_request_cancellation_marks_run_stopped_and_logs_uncertainty(self): + bridge = mock.Mock() + bridge.call.side_effect = SessionCancelled('cancelled pending get_state', True) + status, _ = self.run_agent(bridge) + self.assertEqual(status['state'], 'stopped') + self.assertTrue(status['outcome_unknown']) + run = json.loads((self.home / 'mirror_current_run.json').read_text()) + self.assertEqual(run['status'], 'stopped') + rows = (self.home / 'jev_mirror_log.jsonl').read_text().splitlines() + self.assertEqual(json.loads(rows[-1])['state'], 'stopped') + bridge.close.assert_called_once() + + def test_expired_budget_prevents_execute_from_sending_any_key(self): + bridge = mock.Mock() + with mock.patch.object(agent, 'STOP_FILE') as stop: + stop.exists.return_value = False + result = agent.execute(bridge, {'tool': 'keypress', 'args': {'key': 'enter'}}, deadline=0) + self.assertTrue(result['stopped']) + bridge.call.assert_not_called() + + def test_close_error_still_releases_controller_mutex(self): + bridge = mock.Mock() + bridge.call.return_value = {'ok': True, 'items': []} + bridge.close.side_effect = RuntimeError('close failed') + with self.assertRaisesRegex(RuntimeError, 'close failed'): + self.run_agent(bridge) + self.assertEqual(self.kernel.CloseHandle.call_count, 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_lc_mcp.py b/tests/test_lc_mcp.py index 83de729..c231522 100644 --- a/tests/test_lc_mcp.py +++ b/tests/test_lc_mcp.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- """不需要 Windows/AALC 的测试: python -m unittest discover -s tests""" import json +import io import os import socket import subprocess @@ -84,6 +85,55 @@ class ProtocolTest(unittest.TestCase): self.assertIn('bad arguments', r['error']) self.assertFalse(call(self.s, 'click')['ok']) + def test_invalid_request_shapes_do_not_escape_or_send_input(self): + for params in (['invalid'], 'invalid', 1, True, None): + response = self.s.handle({'jsonrpc': '2.0', 'id': 7, 'method': 'tools/call', 'params': params}) + self.assertEqual(response['error']['code'], -32602) + for arguments in ([], 'invalid', 1, True, None): + response = self.s.handle({'jsonrpc': '2.0', 'id': 8, 'method': 'tools/call', + 'params': {'name': 'click', 'arguments': arguments}}) + self.assertEqual(response['error']['code'], -32602) + self.assertEqual(self.engine.actions, []) + + def test_notifications_never_reply_or_perform_request_only_actions(self): + message = {'jsonrpc': '2.0', 'method': 'tools/call', + 'params': {'name': 'click', 'arguments': {'x': 1, 'y': 2}}} + self.assertIsNone(self.s.handle(message)) + self.assertEqual(self.engine.actions, []) + self.assertIsNotNone(self.s.handle(dict(message, id=None))) + + def test_malformed_messages_allow_following_valid_request(self): + messages = ['null', '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":[1]}', + '{"jsonrpc":"2.0","id":2,"method":"ping"}'] + stdin, stdout = io.StringIO('\n'.join(messages) + '\n'), io.StringIO() + srv_mod.serve_lines(self.s, stdin.readline, stdout.write) + responses = [json.loads(line) for line in stdout.getvalue().splitlines()] + self.assertEqual([r.get('error', {}).get('code') for r in responses[:2]], [-32600, -32602]) + self.assertEqual(responses[2], {'jsonrpc': '2.0', 'id': 2, 'result': {}}) + + def test_invalid_envelope_returns_request_error(self): + for updates in ({'jsonrpc': '1.0'}, {'method': []}, {'id': True}, {'id': []}): + message = dict({'jsonrpc': '2.0', 'id': 9, 'method': 'ping'}, **updates) + self.assertEqual(self.s.handle(message)['error']['code'], -32600) + + def test_task_start_cannot_race_an_input_already_in_progress(self): + entered, release = threading.Event(), threading.Event() + self.engine.click = lambda *args: (entered.set(), release.wait(3)) + worker = threading.Thread(target=lambda: call(self.s, 'click', x=1, y=2)) + worker.start() + try: + self.assertTrue(entered.wait(2)) + started = time.monotonic() + response = call(self.s, 'run_task', task='mirror') + self.assertFalse(response['ok']) + self.assertIsNone(self.tasks.proc) + self.assertLess(time.monotonic() - started, 1) + self.assertEqual(call(self.s, 'task_status')['state'], 'idle') + self.assertTrue(call(self.s, 'stop_task')['ok']) + finally: + release.set() + worker.join(3) + def test_drag_duration_and_rejected_arguments(self): r = call(self.s, 'drag', from_x=200, from_y=300, to_x=200, to_y=600, duration=1.5) self.assertTrue(r['ok']) diff --git a/tests/test_mcp_session.py b/tests/test_mcp_session.py new file mode 100644 index 0000000..1ad7d7f --- /dev/null +++ b/tests/test_mcp_session.py @@ -0,0 +1,156 @@ +"""Real pipe regressions with a dummy worker; never connects to a game service.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +from mcp_session import Session, SessionCancelled, SessionTimeout + +WORKER = '''import json,os,sys,time +mode=os.environ['WORKER_MODE'] +for line in sys.stdin: + message=json.loads(line) + with open(os.environ['WORKER_LOG'],'a',encoding='utf-8') as log: + log.write(json.dumps(message)+'\\n') + mid=message.get('id') + if mode=='initialize-failure': + sys.exit(1) + if mid is None: + continue + if message['method']=='initialize': + if mode=='stderr-burst': + sys.stderr.write('diagnostic\\n'*50000) + sys.stderr.flush() + result={} + elif mode=='silent': + continue + elif mode=='malformed': + print('invalid json',flush=True) + continue + else: + result={'content':[{'type':'text','text':json.dumps({'ok':True,'text':'中文'})}]} + print(json.dumps({'jsonrpc':'2.0','id':mid,'result':result}),flush=True) + if mode=='no-read': + time.sleep(60) +''' + + +class SessionTest(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.log = Path(self.folder.name) / 'requests.jsonl' + self.children = [] + + def worker(self, mode, **options): + real_popen = subprocess.Popen + def launch(*args, **kwargs): + kwargs['env'] = dict(kwargs['env'], WORKER_MODE=mode, WORKER_LOG=str(self.log)) + child = real_popen([sys.executable, '-u', '-c', WORKER], **kwargs) + self.children.append(child) + return child + with mock.patch('mcp_session.subprocess.Popen', side_effect=launch): + return Session(**options) + + def test_silent_response_times_out_without_retry_and_closes_child(self): + client = self.worker('silent', timeout=.5) + self.addCleanup(client.close) + started = time.monotonic() + with self.assertRaises(SessionTimeout) as caught: + client.call('click', {'x': 1, 'y': 2}) + self.assertTrue(caught.exception.outcome_unknown) + self.assertEqual(caught.exception.tool, 'click') + self.assertLess(time.monotonic() - started, 3) + self.assertIsNotNone(client.process.poll()) + rows = [json.loads(line) for line in self.log.read_text().splitlines()] + self.assertEqual(sum(row['method'] == 'tools/call' for row in rows), 1) + with self.assertRaises(ConnectionError): + client.call('get_state') + + def test_stop_interrupts_pending_response(self): + cancelled = threading.Event() + client = self.worker('silent', timeout=5, cancelled=cancelled.is_set) + self.addCleanup(client.close) + timer = threading.Timer(.2, cancelled.set) + timer.start() + self.addCleanup(timer.cancel) + started = time.monotonic() + with self.assertRaises(SessionCancelled) as caught: + client.call('keypress', {'key': 'enter'}) + self.assertTrue(caught.exception.outcome_unknown) + self.assertLess(time.monotonic() - started, 3) + self.assertIsNotNone(client.process.poll()) + + def test_stderr_burst_does_not_block_handshake_and_chinese_response(self): + with self.worker('stderr-burst', timeout=5) as client: + self.assertEqual(client.call('get_state')['text'], '中文') + self.assertLessEqual(len(client.stderr_tail), 20) + + def test_initialization_failure_closes_every_pipe(self): + with self.assertRaises(ConnectionError): + self.worker('initialize-failure', timeout=2) + child = self.children[0] + self.assertIsNotNone(child.poll()) + self.assertTrue(all(stream.closed for stream in (child.stdin, child.stdout, child.stderr))) + + def test_invalid_response_closes_session(self): + client = self.worker('malformed', timeout=2) + self.addCleanup(client.close) + with self.assertRaises(ConnectionError): + client.call('get_state') + self.assertIsNotNone(client.process.poll()) + + def test_blocked_stdin_write_is_also_bounded(self): + client = self.worker('no-read', timeout=.5) + self.addCleanup(client.close) + started = time.monotonic() + with self.assertRaises(SessionTimeout): + client.call('type_text', {'text': 'x' * 500000}) + self.assertLess(time.monotonic() - started, 3) + self.assertIsNotNone(client.process.poll()) + self.assertFalse(any(thread.is_alive() for thread in client._threads)) + + def test_long_wait_tool_has_a_response_budget_beyond_its_polling_timeout(self): + client = Session.__new__(Session) + client.timeout = 30 + client.request = mock.Mock(return_value={'content': [{'text': '{"ok":true}'}]}) + client.call('wait_for_text', {'text': '开始', 'timeout': 300}) + self.assertEqual(client.request.call_args.args[2], 305) + + def test_session_uses_real_bridge_against_isolated_fake_server(self): + from lc_mcp.fake_engine import FakeEngine + from lc_mcp.protocol import Server + from lc_mcp.server import make_tcp + from lc_mcp.tasks import TaskRunner + home = Path(self.folder.name) + runtime = home / 'lc_mcp' + runtime.mkdir() + (runtime / 'token').write_text('test-only-token') + engine = FakeEngine() + tcp = make_tcp(Server(engine, TaskRunner(str(home / 'runs'))), '127.0.0.1', 0, 'test-only-token') + serving = threading.Thread(target=tcp.serve_forever, daemon=True) + serving.start() + try: + with mock.patch.dict(os.environ, {'LCP_PORT': str(tcp.server_address[1]), + 'HOME': str(home), 'USERPROFILE': str(home)}): + with Session(timeout=5) as client: + self.assertTrue(client.call('get_state')['ok']) + self.assertTrue(client.call('drag', {'from_x': 1, 'from_y': 2, + 'to_x': 3, 'to_y': 4})['ok']) + self.assertTrue(client.call('type_text', {'text': '中文'})['ok']) + self.assertEqual(engine.actions[-1], ('type', '中文')) + finally: + tcp.shutdown() + tcp.server_close() + serving.join(2) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_run_state.py b/tests/test_run_state.py new file mode 100644 index 0000000..81491b4 --- /dev/null +++ b/tests/test_run_state.py @@ -0,0 +1,111 @@ +import json +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +from run_state import prepare_run, save_json, record_claim, claim_is_current, complete_run + + +class RunStateTest(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.home = Path(self.folder.name) + self.run_path = self.home / 'mirror_current_run.json' + self.context_path = self.home / 'jev_shop_context.json' + + def test_completed_run_starts_with_fresh_floor_and_no_claim_or_upgrades(self): + old_run, old_context = prepare_run(self.home) + old_run['status'] = 'completed' + old_context.update(floor=5, claim_requested=True, symbol_upgraded=True, battle_context=True) + save_json(self.run_path, old_run) + save_json(self.context_path, old_context) + run, context = prepare_run(self.home) + self.assertNotEqual(run['run_id'], old_run['run_id']) + self.assertEqual(context, {'run_id': run['run_id'], 'floor': 1, 'refresh_used': 0}) + self.assertFalse(claim_is_current(run, context)) + + def test_resume_keeps_matching_run_and_verified_claim(self): + old_run, context = prepare_run(self.home) + context.update(floor=4, symbol_upgraded=True) + record_claim(self.home, old_run, context, {'path': 'completion.png'}) + run, resumed = prepare_run(self.home, resume=True) + self.assertEqual(run['run_id'], old_run['run_id']) + self.assertEqual(run['start_utc'], old_run['start_utc']) + self.assertEqual(resumed['floor'], 4) + self.assertTrue(resumed['symbol_upgraded']) + self.assertTrue(claim_is_current(run, resumed)) + + def test_explicit_new_run_discards_even_unfinished_state(self): + old_run, _ = prepare_run(self.home) + run, _ = prepare_run(self.home, new_run=True) + self.assertNotEqual(run['run_id'], old_run['run_id']) + + def test_resume_requires_an_unfinished_record(self): + with self.assertRaises(ValueError): + prepare_run(self.home, resume=True) + run, _ = prepare_run(self.home) + run['status'] = 'completed' + save_json(self.run_path, run) + with self.assertRaises(ValueError): + prepare_run(self.home, resume=True) + + def test_orphan_context_does_not_supply_completion_to_new_run(self): + save_json(self.context_path, {'floor': 5, 'claim_requested': True}) + run, context = prepare_run(self.home) + self.assertEqual(context['floor'], 1) + self.assertFalse(claim_is_current(run, context)) + + def test_legacy_unfinished_run_preserves_upgrades_but_discards_unbound_claim(self): + save_json(self.run_path, {'start_utc': '2026-10-02T18:13:22+08:00', 'status': 'user_takeover'}) + save_json(self.context_path, {'floor': 5, 'symbol_upgraded': True, + 'claim_requested': True, 'battle_context': True}) + run, context = prepare_run(self.home, resume=True) + self.assertEqual(context['floor'], 5) + self.assertTrue(context['symbol_upgraded']) + self.assertNotIn('battle_context', context) + self.assertFalse(claim_is_current(run, context)) + self.assertTrue(run['legacy_context_migrated']) + + def test_mismatched_ids_fail_before_overwriting_the_context(self): + prepare_run(self.home) + save_json(self.context_path, {'run_id': 'another-run', 'floor': 5}) + before = self.context_path.read_bytes() + with self.assertRaises(ValueError): + prepare_run(self.home) + self.assertEqual(self.context_path.read_bytes(), before) + + def test_completion_requires_matching_claim_and_keeps_both_screens(self): + run, context = prepare_run(self.home) + with self.assertRaises(ValueError): + complete_run(self.home, run, context, {'path': 'home.png'}) + record_claim(self.home, run, context, {'path': 'completion.png'}) + context['claim_run_id'] = 'another-run' + with self.assertRaises(ValueError): + complete_run(self.home, run, context, {'path': 'home.png'}) + context['claim_run_id'] = run['run_id'] + complete_run(self.home, run, context, {'path': 'home.png'}) + saved = json.loads(self.run_path.read_text()) + self.assertTrue(saved['dungeon_completed']) + self.assertEqual(saved['claim_evidence']['path'], 'completion.png') + self.assertEqual(saved['completion_evidence']['path'], 'home.png') + + def test_atomic_snapshot_retains_old_data_if_serialization_fails(self): + save_json(self.context_path, {'floor': 2}) + with self.assertRaises(TypeError): + save_json(self.context_path, {'bad': {1, 2}}) + self.assertEqual(json.loads(self.context_path.read_text()), {'floor': 2}) + self.assertFalse(list(self.home.glob('*.tmp'))) + + def test_new_run_can_recover_from_corrupt_old_files(self): + self.run_path.write_text('truncated') + self.context_path.write_text('truncated') + run, context = prepare_run(self.home, new_run=True) + self.assertEqual(run['status'], 'running') + self.assertEqual(context['floor'], 1) + + +if __name__ == '__main__': + unittest.main()