diff --git a/CLAUDE.md b/CLAUDE.md index 7603b99..a0b970c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,6 +89,27 @@ Loading is atomic: all pre-validation (file existence, JSON validity, conflict d Once loaded, pipeline nodes persist in the Resource until `clear_pipeline_resources()` is called or the process exits. +### JSONC Support (issue #38) + +MaaFramework's own pipeline parser (meojson `json::parsec`) accepts JSONC, so MaaMCP must too — otherwise the same file loads in MaaFramework but fails in MaaMCP. + +[jsonc.py](maa_mcp/jsonc.py) re-implements that semantics in Python (zero new dependencies): + +- Allowed: `//` line comments, `/* */` block comments, trailing commas in objects/arrays (a comma in an *empty* container — `{,}` / `[,]` — is still a syntax error, same as MaaFramework) +- Rejected (same as MaaFramework): unquoted keys, single-quoted strings, `NaN` / `Infinity`, duplicate keys, lone surrogates (e.g. `"\ud800"`) + +Where it applies: pipeline files read by `load_pipeline` / `run_pipeline` / `benchmark_node`, the `pipeline_json` string passed to `save_pipeline` (output is still normalized standard JSON — comments are dropped), and `interface.json` read by the agent supervisor. + +Implementation note: comments are replaced with equal-length whitespace (newlines preserved), then trailing commas are stripped, then the text goes to stdlib `json.loads`. Byte offsets are preserved, so stdlib's line/column error positions apply directly to the original file (a leading UTF-8 BOM shifts them by one character, since the BOM is stripped before parsing). + +Three deliberate deviations from meojson: + +1. Numbers that overflow to `inf` (`1e999`) are rejected — MaaMCP re-serializes the parsed result into strict JSON for `Resource.override_pipeline`, so meojson's literal round-trip would write back the invalid literal `Infinity`. +2. `loads` accepts any top-level value while meojson only accepts objects/arrays (callers still require a non-empty object). +3. Trailing residue __after__ the top-level value is reported as an error. meojson's `skip_whitespace` conflates "end of input" with "malformed comment start", so it silently accepts and discards a trailing `/x` or an unterminated block comment; MaaFramework inherits that. This direction is __stricter__ — MaaMCP never accepts a file MaaFramework rejects. An unterminated comment __inside__ the document is rejected by both. + +`interface.json` caveat: MaaMCP tolerates comments there, and so does MFAAvalonia (Newtonsoft.Json skips comments). But MAAGC's own `agent/main.py` reads that file with stdlib `json.load` to detect the version — a commented `interface.json` makes it log an exception and fall back to version `"unknown"` (it only decides dev-mode vs. venv setup). Keep `interface.json` comment-free if you rely on MAAGC's version detection. + ### Agent Subprocess Lifecycle (Custom Action Support) For pipelines containing `action: "Custom"` nodes (e.g. MAAGC's `TaskProcessor` / `YearlyTaskProcessor`), MaaMCP spawns a Python agent subprocess to host the custom callbacks, following the MFAAvalonia pattern. @@ -189,6 +210,12 @@ When a TemplateMatch / OCR / ColorMatch node isn't reliable, iterate this loop ( For MaaMCP-side pipeline infra testing, see `tests/test_dbg_pipeline.py` (gated by `@pytest.mark.integration`; skips if `MaaDbgControlUnit` DLL isn't shipped). +### Stress tests are opt-in — never auto-pick a window + +`tests/test_performance_stress.py` drives __real__ devices/windows (clicks, swipes, typed text, key presses). It is skipped unless `MAA_STRESS=1` is set, and the target must be named explicitly via `MAA_STRESS_DEVICE` / `MAA_STRESS_WINDOW`. + +Do not "fix" it by picking `find_window_list()[0]`: the first desktop window is usually the user's editor (VS Code), and the stress test's synthetic clicks/keystrokes land on it — this closed VS Code during a plain `pytest tests/` run. This mirrors the rule in [win32.py](maa_mcp/win32.py): never auto-select a window when several are available. + ## Localization - [CLAUDE_CN.md](CLAUDE_CN.md): Chinese version of this document diff --git a/CLAUDE_CN.md b/CLAUDE_CN.md index 4d4727a..8a3e1cf 100644 --- a/CLAUDE_CN.md +++ b/CLAUDE_CN.md @@ -89,6 +89,27 @@ pytest tests/test_basic.py -v # 运行特定文件 节点一旦加载会持续驻留到 Resource,直到调用 `clear_pipeline_resources()` 或进程结束。 +### JSONC 语法支持(issue #38) + +MaaFramework 自带的 pipeline 解析器(meojson 的 `json::parsec`)接受 JSONC,因此 MaaMCP 也必须接受——否则同一份文件在 MaaFramework 能加载、在 MaaMCP 却报解析失败。 + +[jsonc.py](maa_mcp/jsonc.py) 在 Python 侧复刻了这套语义(不引入任何新依赖): + +- 允许:`//` 行注释、`/* */` 块注释、对象/数组尾逗号(__空__容器里的逗号 `{,}` / `[,]` 仍是语法错误,与 MaaFramework 一致) +- 拒绝(与 MaaFramework 一致):无引号键、单引号字符串、`NaN` / `Infinity`、重复键、落单的代理字符(如 `"\ud800"`) + +生效范围:`load_pipeline` / `run_pipeline` / `benchmark_node` 读取的 pipeline 文件、`save_pipeline` 的 `pipeline_json` 输入字符串(落盘仍是格式化后的标准 JSON,注释丢弃)、以及 agent supervisor 读取的 `interface.json`。 + +实现要点:先把注释替换成等长空白(保留换行),再剥掉尾逗号,最后交给标准库 `json.loads`。字节偏移保持不变,因此标准库自带的行列号报错可直接对到原文件(文件带 UTF-8 BOM 时位置会偏移一个字符——BOM 在解析前被剥掉)。 + +三处有意偏离 meojson: + +1. 溢出成 `inf` 的数字(`1e999`)会被拒绝——MaaMCP 会把解析结果重新序列化成严格 JSON 再交给 `Resource.override_pipeline`,meojson 按字面量保存能原样往返,我们写回去会是非法的 `Infinity` 字面量。 +2. `loads` 接受任意顶层值,而 meojson 只接受对象/数组(调用方仍要求顶层为非空对象)。 +3. 顶层值__之后__的尾部残余按错误处理。meojson 的 `skip_whitespace` 把「已到输入末尾」与「注释起始符非法」混为一谈,会静默接受并丢弃尾部残余(如 `/x` 或未闭合的块注释),MaaFramework 继承了这一行为。这一处的方向是「更严」——MaaMCP 不会接受 MaaFramework 拒绝的文件;未闭合注释出现在文档__内部__时两边都拒绝。 + +`interface.json` 的注意事项:MaaMCP 这里容忍注释,MFAAvalonia 也容忍(Newtonsoft.Json 会跳过注释)。但 MAAGC 自己的 `agent/main.py` 用标准库 `json.load` 读同一个文件来检测版本——带注释的 `interface.json` 会让它记一条异常并回退到版本 `"unknown"`(该值只用来区分 dev 模式与 venv 准备)。依赖 MAAGC 版本检测时,`interface.json` 保持无注释。 + ### Agent 子进程生命周期(Custom Action 支持) 对于含 `action: "Custom"` 节点的 pipeline(如 MAAGC 的 `TaskProcessor` / `YearlyTaskProcessor`),MaaMCP 启动一个 Python agent 子进程来托管自定义回调,对齐 MFAAvalonia 模式。 @@ -188,6 +209,12 @@ TemplateMatch / OCR / ColorMatch 节点不稳定时,按这个循环迭代(is MaaMCP 侧 pipeline infra 集成测试见 `tests/test_dbg_pipeline.py`(标 `@pytest.mark.integration`;缺 `MaaDbgControlUnit` DLL 时自动 skip)。 +### 压力测试必须显式开启——绝不自动挑窗口 + +`tests/test_performance_stress.py` 会操作__真实__设备/窗口(点击、滑动、输入文本、按键)。默认整体跳过:需设置 `MAA_STRESS=1`,并用 `MAA_STRESS_DEVICE` / `MAA_STRESS_WINDOW` 显式指定目标。 + +不要用「取 `find_window_list()[0]`」来"修好"它:桌面窗口列表的第一项通常是用户正在用的编辑器(VS Code),压力测试合成的点击与按键会直接打上去——曾导致一次普通的 `pytest tests/` 把 VS Code 关掉。这与 [win32.py](maa_mcp/win32.py) 里的约定一致:多个窗口时绝不自动选择。 + ## 本地化 - [CLAUDE.md](CLAUDE.md):本文档的英文版 diff --git a/docs/superpowers/specs/2026-11-08-jsonc-support-design.md b/docs/superpowers/specs/2026-11-08-jsonc-support-design.md new file mode 100644 index 0000000..9f6ad38 --- /dev/null +++ b/docs/superpowers/specs/2026-11-08-jsonc-support-design.md @@ -0,0 +1,165 @@ +# JSONC 支持设计(issue #38) + +> 状态:已实现 +> 关联 issue:https://github.com/MAA-AI/MaaMCP/issues/38 +> 日期:2026-11-08 + +## 背景 + +MaaMCP 用标准库 `json` 读取 pipeline 文件与 `interface.json`。但 MaaFramework 自带的 +pipeline 解析器(内部使用 [meojson](https://github.com/MistEO/meojson) 的 `json::parsec`) +是 JSONC 语法——允许注释与尾逗号。于是同一份文件 MaaFramework 能读、MaaMCP 报 +`Expecting value`,`load_pipeline` / `run_pipeline` / `benchmark_node` / `save_pipeline` +全部受影响。 + +实测 MaaFramework 5.14.3(`Resource.post_pipeline`)的接受集合: + +| 语法 | MaaFramework | +|---|---| +| `//` 行注释 | ✅ | +| `/* */` 块注释 | ✅ | +| 尾逗号(对象/数组) | ✅ | +| 无引号键 | ❌ | +| 单引号字符串 | ❌ | + +MaaMCP 侧必须与之一致:比 MaaFramework 更宽松会让「MaaMCP 能跑、bundle 加载失败」, +更严格则会让 MaaFramework 能跑的文件在 MaaMCP 报错。 + +## 方案选型 + +### 为什么不是 meojson + +meojson 是 header-only C++17 库,无 PyPI 包、无 Python binding(GitHub 全库搜索仅 +C++ 仓库本身)。MaaMCP 是纯 Python pip 包,调用它需要: + +1. 把头文件 vendor 进仓库; +2. 写 CPython 扩展; +3. 构建系统从 hatchling 换成 scikit-build-core; +4. 要么要求用户本机有 C++17 工具链,要么 CI 为 win/mac/linux 交叉编译 wheel。 + +为一个 JSON 解析功能付出这个分发代价不划算。 + +被否决的两条「借道 MaaFramework」的路: + +- `Resource.post_pipeline()` 确实能原生解析 JSONC,但 `get_node_data()` 返回的是 + MaaFramework **归一化后**的节点结构(未知字段被丢弃、默认值被填充、`next` 被改写成 + 对象数组),有损,不能当解析器用。 +- `Resource.override_pipeline()` 走的是 meojson 的严格 `json::parse`(见 MaaFramework + 仓库 `.agents/skills/meojson/SKILL.md`),所以 MaaMCP 交给它的必须是严格 JSON。 + +### 选定方案 + +在 Python 侧复刻 meojson `json::parsec` 的语义,零新依赖。 + +## 解析层:`maa_mcp/jsonc.py` + +### 公开 API + +```python +def loads(text: str) -> Any +``` + +- 入参:JSONC 文本(可含 BOM)。 +- 返回:解析后的 Python 对象。 +- 失败:抛 `json.JSONDecodeError` 子类(兼容现有 `except json.JSONDecodeError`)。 + +### 语义 + +| 语法 | 支持 | +|---|---| +| `//` 行注释、`/* */` 块注释 | ✅ | +| 对象/数组尾逗号 | ✅(空容器里的逗号 `{,}` / `[,]` 仍是语法错误,与 meojson 一致) | +| 无引号键、单引号字符串 | ❌ | +| `NaN` / `Infinity` / `-Infinity` | ❌(stdlib `json` 默认接受,需显式拦截) | +| 重复键 | ❌(meojson 同样报错) | +| 落单的代理字符(`"\ud800"`) | ❌(meojson 同样报错;stdlib 接受但会让后续编码崩溃) | +| 溢出成 `inf` 的数字(`1e999`) | ❌(见下方「有意偏离」) | +| UTF-8 BOM | ✅(自动剥离) | + +### 实现 + +不写递归下降解析器,走「预处理 + 标准库」: + +1. **剥注释**:扫描文本,跟踪字符串字面量与转义状态;注释内容替换成**等长空白** + (块注释内的换行保留),因此字节偏移与行号完全不变。 +2. **拦非法字面量**:再扫一遍,识别 `NaN` / `Infinity` / `-Infinity` 并报错。 +3. **剥尾逗号**:再扫一遍,把「其后(跳过空白)是 `}` 或 `]`」且「前面已经有过至少 + 一个成员」的 `,` 替换成空格——meojson 的解析循环必须先完成一个键值对才会收尾, + 所以 `{,}`、`[,]` 是语法错误,必须同样拒绝。 +4. **交给标准库**:`json.loads(cleaned, object_pairs_hook=_make_pairs_hook(doc), + parse_float=_make_parse_float(doc))`——前者拒绝重复键,后者拒绝溢出数字。 +5. **修代理字符**:解析后递归处理字符串,把 `\uXXXX` 代理对还原成真实码点, + 落单的代理字符直接报错。 + +因为偏移量没变,stdlib `JSONDecodeError` 自带的行列号(`line X column Y`)可以直接 +用,不需要自己算位置(BOM 在解析前被剥掉,带 BOM 的文件位置会偏移一个字符)。 + +### 有意偏离 meojson 的三处 + +1. **溢出数字**:`1e999` 会被解析成 `inf`,序列化回去是非法的 `Infinity` 字面量。 + meojson 把数字当字面量保存能原样往返,MaaMCP 不能,因此直接拒绝。 +2. **顶层值类型**:meojson 只接受对象 / 数组,本模块 `loads` 接受任意顶层值 + (是否合法交给调用方判断——pipeline 文件另行要求顶层为非空对象)。 +3. **顶层值之后的尾部残余**:meojson 的 `skip_whitespace` 把「已到输入末尾」与 + 「注释起始符非法」混为一谈——顶层值之后出现 `/x` 或未闭合的块注释时,它会静默 + 接受并丢弃残余,MaaFramework 继承了这一行为。本模块按标准库语义报错。方向是 + 「更严」:MaaMCP 不会接受 MaaFramework 拒绝的文件,只会在这类病态的尾部残余上 + 报错。未闭合注释出现在文档**内部**时两边都拒绝,行为一致。 + +前两条源于 MaaMCP 与 MaaFramework 的调用方式不同——MaaMCP 要把解析结果重新序列化 +成严格 JSON 再交给 `Resource.override_pipeline`。 + +已确认与 meojson **一致**(无需偏离):注释、尾逗号(含 `{,}` / `[,]` 这类空容器 +逗号都拒绝)、重复键、NaN / Infinity、落单代理字符、顶层值之后非 `/` 开头的尾部 +垃圾(两者都报错)、顶层值之后的尾部注释(两者都接受)。 + +### 错误信息 + +| 情况 | 报错 | +|---|---| +| 块注释未闭合 | `Unterminated comment: line L column C (char N)` | +| 非法 JSON | 复用 stdlib 的 msg,位置用**原文**重新抛出 | +| `NaN` / `Infinity` | `NaN is not valid JSON: line L column C` | +| 溢出数字 | `1e999 is not a finite number`(无位置) | +| 落单代理字符 | `lone surrogate in string`(无位置) | +| 重复键 | `Duplicate key 'X'`(无位置,stdlib hook 无法定位) | + +## 接入点 + +| 位置 | 原实现 → 现实现 | 影响范围 | +|---|---|---| +| `pipeline_tools.py` `_read_and_validate_pipelines` | `json.load(fh)` → `jsonc_loads(fh.read())` | `load_pipeline` / `run_pipeline` / `benchmark_node`(三处共用该函数) | +| `pipeline_tools.py` `save_pipeline` | `json.loads(pipeline_json)` → `jsonc_loads(pipeline_json)` | 校验输入字符串;**写盘仍是 `json.dump(indent=2)` 的标准 JSON**,注释丢弃 | +| `agent_supervisor.py` `load_agent_config` | `json.loads(...)` → `jsonc_loads(...)` | `interface.json` 允许注释——与 MFAAvalonia(Newtonsoft.Json,容忍注释)对齐;MaaFramework 本身不读 `interface.json` | + +## 兼容性 + +- 纯 JSON 是合法 JSONC → 现有行为不变,现有测试全绿。 +- MaaMCP 交给 MaaFramework 的永远是**重新序列化出来的严格 JSON**(由 maafw 的 + `override_pipeline` 内部做 `json.dumps`)→ MaaFramework 侧零风险。 +- 新增的严格性:重复键报错、落单代理字符报错(这两条与 meojson 一致,能挡掉 + 「节点名写重了」「文件里有坏编码」这类真实问题),以及溢出数字报错 + (这一条是上文的有意偏离,防止落盘写出非法的 `Infinity`)。 + +## 测试 + +新增 `tests/test_jsonc.py`(按仓库既有惯例整体标 `@pytest.mark.unit`): + +- **解析器**:行/块注释、尾逗号、字符串内含 `//` 与 `/* */`、转义引号、未闭合块注释、 + 重复键、NaN/Infinity、溢出数字、代理对与落单代理、BOM、非 str 输入、错误行列号正确。 +- **工具层**:带注释的 pipeline 文件能被 `_read_and_validate_pipelines` / + `load_pipeline` 读出;重复键与非 UTF-8 文件给出明确错误;`save_pipeline` 接受带注释 + 的输入且落盘为标准 JSON;`interface.json` 带注释时 agent 配置仍能读到,坏文件返回 + None 而不抛异常。 + +## 文档 + +- `CLAUDE.md` / `CLAUDE_CN.md`:同步加一条「pipeline 文件与 interface.json 支持 JSONC」。 +- `load_pipeline` / `save_pipeline` / `run_pipeline` / `benchmark_node` 的工具描述里 + 点明——工具描述就是 AI 读到的说明书。 + +## 不做的事 + +- 不改 `save_pipeline` 的输出格式(统一输出标准 JSON)。 +- 不为 `.jsonc` 扩展名做特殊分流(MaaFramework 两种扩展名都收,MaaMCP 不按扩展名分流)。 +- 不引入任何新依赖。 diff --git a/maa_mcp/agent_supervisor.py b/maa_mcp/agent_supervisor.py index c036bda..0ae9ad4 100644 --- a/maa_mcp/agent_supervisor.py +++ b/maa_mcp/agent_supervisor.py @@ -36,6 +36,7 @@ from maa.tasker import Tasker from maa_mcp.core import object_registry +from maa_mcp.jsonc import loads as jsonc_loads # --------------------------------------------------------------------------- # 平台相关常量(Windows JobObject) @@ -125,8 +126,8 @@ def load_agent_config(resource_path: Optional[str]) -> Optional[AgentConfig]: if not cfg_path.is_file(): continue try: - data = json.loads(cfg_path.read_text(encoding="utf-8")) - except (json.JSONDecodeError, OSError) as e: + data = jsonc_loads(cfg_path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, UnicodeDecodeError, OSError, RecursionError) as e: logger.warning(f"解析 {cfg_path} 失败: {e}") return None if not isinstance(data, dict): diff --git a/maa_mcp/jsonc.py b/maa_mcp/jsonc.py new file mode 100644 index 0000000..8dc32cc --- /dev/null +++ b/maa_mcp/jsonc.py @@ -0,0 +1,342 @@ +"""JSONC(带注释的 JSON)解析。 + +MaaFramework 内置的 pipeline 解析器基于 +[meojson](https://github.com/MistEO/meojson) 的 `json::parsec`,接受带注释与 +尾逗号的 JSONC。本模块在 Python 侧复刻同一套语义,使 MaaMCP 能读的文件与 +MaaFramework 能读的文件保持一致——否则同一份 pipeline,MaaFramework 加载成功 +而 MaaMCP 报 `Expecting value`。 + +与 MaaFramework(= meojson `json::parsec`)一致的接受集合: + +- 允许 `//` 行注释、`/* */` 块注释 +- 允许对象 / 数组尾逗号(但 `{,}`、`[,]` 这类空容器里的逗号是语法错误, + MaaFramework 同样拒绝) +- 其余严格遵循 JSON 规范:键必须是双引号字符串,拒绝单引号、拒绝 + NaN / Infinity、拒绝重复键、拒绝落单的代理字符(`\\uD800` 之类) + +实现走「预处理 + 标准库」而不是自写递归下降解析器:先把注释替换成等长空白 +(保留换行),再剥掉尾逗号,最后交给标准库 `json.loads`。空白替换保留了字节 +偏移,因此标准库 `JSONDecodeError` 自带的行列号可以直接沿用,无需自己算位置。 + +已知的三处有意偏离: + +1. **顶层值类型**:meojson 只接受对象 / 数组,本模块的 `loads` 接受任意顶层值 + (是否合法由调用方判断——pipeline 文件另行要求顶层为非空对象)。 +2. **溢出数字**:meojson 把数字当字面量保存,`1e999` 能原样往返;但 MaaMCP 要 + 把解析结果重新序列化成严格 JSON 再交给 `Resource.override_pipeline`, + `1e999` 解析成 `inf` 后落盘会写出非法的 `Infinity` 字面量,因此这里显式拒绝。 +3. **顶层值之后的尾部残余**:meojson 的 `skip_whitespace` 把「已到输入末尾」与 + 「注释起始符非法」混为一谈——顶层值之后出现 `/x` 或未闭合的块注释时,它会 + 静默接受并丢弃残余,MaaFramework 继承了这一行为。本模块按标准库语义报错。 + 方向是「更严」:MaaMCP 不会接受 MaaFramework 拒绝的文件,只会在这类病态的 + 尾部残余上报错(`Extra data` / `Unterminated comment`)。 + 注:未闭合注释出现在文档**内部**时,两边都拒绝,行为一致。 +""" + +from __future__ import annotations + +import json +import math +from typing import Any, Callable + +__all__ = ["JsoncDecodeError", "loads"] + +_BOM = "" +_WHITESPACE = " \t\r\n" +# 标准库 json 默认接受、但 JSON 规范与 MaaFramework 都不接受的字面量 +_NON_JSON_CONSTANTS = frozenset({"NaN", "Infinity", "-Infinity"}) + + +class JsoncDecodeError(json.JSONDecodeError): + """JSONC 解析错误。 + + 继承 `json.JSONDecodeError`,既有的 `except json.JSONDecodeError` 分支 + 无需修改即可捕获。`pos` 为 `None` 表示该错误无法定位到具体位置(如重复 + 键),此时报错信息不带行列号,避免给出误导性的位置。 + """ + + def __init__(self, msg: str, doc: str, pos: int | None = None) -> None: + if pos is None: + ValueError.__init__(self, msg) + self.msg = msg + self.doc = doc + self.pos = None + self.lineno = None + self.colno = None + else: + super().__init__(msg, doc, pos) + + +def _strip_comments(text: str) -> str: + """把注释替换成等长空白。 + + 注释内容替换为空格(块注释内的换行保留),返回文本与入参等长, + 行列号完全一致,后续步骤的报错位置可以直接沿用。 + """ + out = list(text) + i = 0 + n = len(text) + in_string = False + + while i < n: + ch = text[i] + if in_string: + # 字符串内部:只有 \" 会转义下一个字符,其余按普通字符处理 + if ch == "\\": + i += 2 + continue + if ch == '"': + in_string = False + i += 1 + continue + + if ch == '"': + in_string = True + i += 1 + continue + + if ch == "/" and i + 1 < n: + marker = text[i + 1] + if marker == "/": + # 行注释:到行尾为止(换行符本身保留) + end = text.find("\n", i) + end = n if end == -1 else end + for k in range(i, end): + out[k] = " " + i = end + continue + if marker == "*": + # 块注释:到 */ 为止 + end = text.find("*/", i + 2) + if end == -1: + raise JsoncDecodeError("Unterminated comment", text, i) + for k in range(i, end + 2): + if text[k] != "\n": + out[k] = " " + i = end + 2 + continue + + i += 1 + + return "".join(out) + + +def _strip_trailing_commas(text: str) -> str: + """把对象 / 数组的尾逗号替换成空格。 + + 只有「前面已经有过至少一个成员」的逗号才算尾逗号——meojson 的解析循环在 + 取到 `}` / `]` 之前必须先完成一个键值对,所以 `{,}`、`[,]` 这类空容器里 + 的逗号是语法错误,MaaFramework 会拒绝。这里必须同样拒绝,否则 MaaMCP + 会接受 MaaFramework 拒绝的文件。 + """ + out = list(text) + i = 0 + n = len(text) + in_string = False + # 上一个非空白字符;字符串按整体的结束引号计 + prev = "" + + while i < n: + ch = text[i] + if in_string: + if ch == "\\": + i += 2 + continue + if ch == '"': + in_string = False + prev = '"' + i += 1 + continue + + if ch == '"': + in_string = True + i += 1 + continue + + if ch in _WHITESPACE: + i += 1 + continue + + if ch == ",": + # 逗号后(跳过空白)紧跟 } 或 ],且前面已有成员 → 尾逗号 + j = i + 1 + while j < n and text[j] in _WHITESPACE: + j += 1 + if j < n and text[j] in "}]" and prev not in "{[,": + out[i] = " " + prev = "," + i += 1 + continue + + prev = ch + i += 1 + + return "".join(out) + + +def _reject_non_json_constants(text: str) -> None: + """拒绝 NaN / Infinity / -Infinity 字面量。 + + 标准库 `json` 默认接受这三个字面量,但 JSON 规范与 MaaFramework 都不接受; + 更关键的是它们序列化回 JSON 后仍是 `NaN` 字面量,会让 MaaFramework 的严格 + 解析失败,错误信息也难以追溯。 + """ + i = 0 + n = len(text) + in_string = False + + while i < n: + ch = text[i] + if in_string: + if ch == "\\": + i += 2 + continue + if ch == '"': + in_string = False + i += 1 + continue + + if ch == '"': + in_string = True + i += 1 + continue + + # 裸标识符只可能是非法的 JSON 关键字(true / false / null 由标准库处理) + if ch.isalpha() or (ch == "-" and i + 1 < n and text[i + 1].isalpha()): + start = i + j = i + 1 + while j < n and (text[j].isalnum() or text[j] in "_+"): + j += 1 + token = text[start:j] + if token in _NON_JSON_CONSTANTS: + raise JsoncDecodeError(f"{token} is not valid JSON", text, start) + i = j + continue + + i += 1 + + +def _make_pairs_hook(doc: str) -> Callable[[list[tuple[str, Any]]], dict[str, Any]]: + """构造 `object_pairs_hook`:拒绝重复键。 + + meojson 遇到重复键会解析失败,标准库则静默取最后一个。这里选择与 + MaaFramework 一致地报错,顺带挡掉「pipeline 文件里节点名写重了」这类 + 真实错误。 + """ + + def hook(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise JsoncDecodeError(f"Duplicate key {key!r}", doc) + result[key] = value + return result + + return hook + + +def _make_parse_float(doc: str) -> Callable[[str], float]: + """构造 `parse_float` 钩子:拒绝溢出成非有限值的数字。 + + `1e999` 是合法 JSON 语法,但会被解析成 `inf`,序列化回去就成了非法的 + `Infinity` 字面量——写出来的文件既不是合法 JSON,MaaFramework 的严格 + 解析也会失败。标准库默认接受这种写法,这里显式拦掉。 + """ + + def parse_float(literal: str) -> float: + value = float(literal) + if not math.isfinite(value): + raise JsoncDecodeError(f"{literal} is not a finite number", doc) + return value + + return parse_float + + +def _decode_surrogates(text: str, doc: str) -> str: + """把 `\\uXXXX` 代理对还原成真实码点,拒绝落单的代理字符。 + + 标准库 `json` 会把 `"\\ud83d\\ude00"` 解析成两个代理码元(而不是 emoji), + 落单的代理码元(如 `"\\ud800"`)则会让后续 `json.dumps(...).encode()` 抛 + UnicodeEncodeError——MaaFramework 侧的 `override_pipeline` 正是这么调度的, + 异常会直接冲出工具调用。MaaFramework 的 meojson 则把代理对合成真实码点、 + 对落单代理直接解析失败,这里与它对齐。 + + Raises: + JsoncDecodeError: 字符串里存在落单的代理字符。 + """ + if not any(0xD800 <= ord(ch) <= 0xDFFF for ch in text): + return text + + out: list[str] = [] + i = 0 + n = len(text) + while i < n: + code = ord(text[i]) + if 0xD800 <= code <= 0xDBFF: + # 高位代理:后面必须紧跟低位代理 + if i + 1 < n and 0xDC00 <= ord(text[i + 1]) <= 0xDFFF: + low = ord(text[i + 1]) + out.append(chr(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00))) + i += 2 + continue + raise JsoncDecodeError("lone surrogate in string", doc) + if 0xDC00 <= code <= 0xDFFF: + # 低位代理:前面没有配对的高位代理 + raise JsoncDecodeError("lone surrogate in string", doc) + out.append(text[i]) + i += 1 + return "".join(out) + + +def _sanitize_surrogates(value: Any, doc: str) -> Any: + """递归处理解析结果里的字符串(键与值),还原代理对、拒绝落单代理。""" + if isinstance(value, str): + return _decode_surrogates(value, doc) + if isinstance(value, list): + return [_sanitize_surrogates(item, doc) for item in value] + if isinstance(value, dict): + return { + _decode_surrogates(key, doc): _sanitize_surrogates(item, doc) + for key, item in value.items() + } + return value + + +def loads(text: str) -> Any: + """解析 JSONC 文本。 + + Args: + text: JSONC 文本。允许 `//` 与 `/* */` 注释、对象 / 数组尾逗号; + 其余遵循 JSON 规范。 + + Returns: + 解析后的 Python 对象。 + + Raises: + TypeError: `text` 不是 str。 + json.JSONDecodeError: 语法错误、重复键、NaN / Infinity 等非法内容。 + 错误信息带行列号(重复键与溢出数字除外)。 + """ + if not isinstance(text, str): + raise TypeError(f"text 必须是 str,实际: {type(text).__name__}") + + # 去掉 UTF-8 BOM,其余偏移量保持不变 + doc = text.removeprefix(_BOM) + + cleaned = _strip_comments(doc) + _reject_non_json_constants(cleaned) + cleaned = _strip_trailing_commas(cleaned) + + try: + parsed = json.loads( + cleaned, + object_pairs_hook=_make_pairs_hook(doc), + parse_float=_make_parse_float(doc), + ) + except json.JSONDecodeError as e: + if isinstance(e, JsoncDecodeError): + raise + # 用原文重新抛出:偏移量一致,位置信息对用户仍然准确 + raise JsoncDecodeError(e.msg, doc, e.pos) from e + + return _sanitize_surrogates(parsed, doc) diff --git a/maa_mcp/pipeline_tools.py b/maa_mcp/pipeline_tools.py index 7f5ccf2..21fa6bf 100644 --- a/maa_mcp/pipeline_tools.py +++ b/maa_mcp/pipeline_tools.py @@ -19,6 +19,7 @@ from loguru import logger from maa_mcp.core import mcp, object_registry +from maa_mcp.jsonc import loads as jsonc_loads from maa_mcp.paths import ensure_within_pipelines_dir, get_data_dir from maa_mcp.resource import ( add_resource_path, @@ -512,8 +513,9 @@ def _read_and_validate_pipelines( 校验项: 1. 文件存在 2. 路径是文件(不是目录) - 3. JSON 解析成功 - 4. 顶层是非空 dict + 3. 文件是合法的 UTF-8 文本 + 4. JSONC 解析成功(允许注释与尾逗号,与 MaaFramework 一致) + 5. 顶层是非空 dict Args: files: 文件路径列表(绝对或相对路径均可) @@ -533,9 +535,13 @@ def _read_and_validate_pipelines( raise ValueError(f"Pipeline 路径不是文件: {f}") try: with open(path, "r", encoding="utf-8") as fh: - data = json.load(fh) + data = jsonc_loads(fh.read()) except json.JSONDecodeError as e: raise ValueError(f"Pipeline JSON 解析失败: {f}: {e}") from e + except UnicodeDecodeError as e: + raise ValueError(f"Pipeline 文件不是合法的 UTF-8 文本: {f}: {e}") from e + except RecursionError as e: + raise ValueError(f"Pipeline JSON 嵌套层级过深: {f}: {e}") from e if not isinstance(data, dict) or not data: raise ValueError(f"Pipeline 文件格式错误(顶层必须是非空对象): {f}") result.append((str(path.absolute()), data)) @@ -810,6 +816,8 @@ def _build_run_result( 说明: - 用于读取已保存的 Pipeline 进行查看或修改,修改后可调用 save_pipeline() 保存。 - 本工具只做文件 I/O,不触碰 Resource。合并/写入是 run_pipeline 的职责。 + - 支持 JSONC 语法:文件里的 `//` 与 `/* */` 注释、对象/数组尾逗号都能正常解析 + (与 MaaFramework 的解析器行为一致);返回值是解析后的 dict,注释不保留。 - 安全约束:所有路径必须位于用户数据目录下的 pipelines/ 子目录内, 越界路径会被拒绝。读取项目资源目录下的 pipeline 请使用 run_pipeline。 """, @@ -861,6 +869,8 @@ def load_pipeline(pipeline_path: Union[str, List[str]]) -> dict | str: 说明: 可用于新建 Pipeline 或更新已有 Pipeline(指定 output_path 为已有文件路径即可覆盖更新)。 + - pipeline_json 支持 JSONC 语法(`//` 与 `/* */` 注释、尾逗号),与 MaaFramework 一致; + 但写盘时统一输出格式化后的标准 JSON,注释不会保留。 - 安全约束:output_path 必须位于用户数据目录下的 pipelines/ 子目录内, 越界路径会被拒绝。 """, @@ -871,11 +881,13 @@ def save_pipeline( name: Optional[str] = None, overwrite: bool = True, ) -> str: - # 验证 JSON 格式 + # 验证 JSON 格式(允许注释与尾逗号,与 MaaFramework 一致) try: - pipeline = json.loads(pipeline_json) + pipeline = jsonc_loads(pipeline_json) except json.JSONDecodeError as e: return f"Pipeline JSON 格式错误: {e}" + except RecursionError as e: + return f"Pipeline JSON 嵌套层级过深: {e}" # 验证 Pipeline 结构:必须是以节点名为键的非空对象 if not isinstance(pipeline, dict): @@ -943,6 +955,8 @@ def save_pipeline( - pipeline_path: Pipeline JSON 文件路径(str),或多个路径组成的列表。 多文件场景下,按列表顺序合并节点到同一全局节点表; 一个文件的节点可以引用另一文件中的节点。 + 文件支持 JSONC 语法(`//` 与 `/* */` 注释、对象/数组尾逗号), + 与 MaaFramework 的解析器行为一致。 - entry: 入口节点名称(可选)。不指定时使用 pipeline_path 第一个文件的第一个节点。 - resource_path: 资源目录路径(可选),用于指定 Pipeline 所需的资源文件路径。 如果不指定,则使用 MaaMCP 默认的资源目录。 @@ -1521,7 +1535,8 @@ def _benchmark_node_impl( 参数: - controller_id: 控制器 ID,由 connect_adb_device() / connect_window() 返回 - - pipeline_path: Pipeline JSON 路径(str 或 list[str]) + - pipeline_path: Pipeline JSON 路径(str 或 list[str]),支持 JSONC 语法 + (`//` 与 `/* */` 注释、对象/数组尾逗号) - node: 被测节点名(必须在 pipeline 中) - entry: 入口节点名(可选;默认用首个文件第一个 key) - iterations: 跑几次(1..1000,默认 10) diff --git a/tests/test_jsonc.py b/tests/test_jsonc.py new file mode 100644 index 0000000..1cccb50 --- /dev/null +++ b/tests/test_jsonc.py @@ -0,0 +1,423 @@ +"""JSONC(带注释的 JSON)支持测试 (issue #38)。 + +覆盖: +- `maa_mcp.jsonc.loads` 单元行为:注释、尾逗号、严格性边界、错误定位 +- pipeline 文件读取:`load_pipeline` / `_read_and_validate_pipelines` +- `save_pipeline`:接受带注释的输入,落盘仍是标准 JSON +- `agent_supervisor`:读取带注释的 interface.json +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from maa_mcp.agent_supervisor import load_agent_config +from maa_mcp.jsonc import loads +from maa_mcp.pipeline_tools import ( + _read_and_validate_pipelines, + load_pipeline, + save_pipeline, +) + +# fastmcp 2.x wraps @mcp.tool functions in FunctionTool; 3.x does not. +load_pipeline = getattr(load_pipeline, "fn", load_pipeline) +save_pipeline = getattr(save_pipeline, "fn", save_pipeline) + + +# ============================================================================= +# jsonc.loads 单元测试 +# ============================================================================= + + +@pytest.mark.unit +class TestJsoncLoads: + """`jsonc.loads` 单元测试。""" + + def test_plain_json_unchanged(self) -> None: + """纯 JSON 应原样解析(JSON 是 JSONC 的子集)。""" + assert loads('{"a": 1, "b": [1, 2]}') == {"a": 1, "b": [1, 2]} + + def test_line_comment_ignored(self) -> None: + """`//` 行注释应被忽略。""" + text = """ + { + // 这是节点 A + "A": {"recognition": "DirectHit"} + } + """ + assert loads(text) == {"A": {"recognition": "DirectHit"}} + + def test_block_comment_ignored(self) -> None: + """`/* */` 块注释应被忽略。""" + text = '{ /* 头部说明 */ "A": 1 }' + assert loads(text) == {"A": 1} + + def test_multiline_block_comment_ignored(self) -> None: + """跨行块注释应被忽略。""" + text = '{\n/* 第一行\n 第二行 */\n"A": 1\n}' + assert loads(text) == {"A": 1} + + def test_trailing_comma_in_object(self) -> None: + """对象尾逗号应被接受(MaaFramework 同样接受)。""" + assert loads('{"A": 1, "B": 2,}') == {"A": 1, "B": 2} + + def test_trailing_comma_in_array(self) -> None: + """数组尾逗号应被接受。""" + assert loads('{"a": [1, 2, 3,]}') == {"a": [1, 2, 3]} + + def test_comment_markers_inside_string_preserved(self) -> None: + """字符串里的 `//` 与 `/* */` 是普通字符,不能被当注释剥掉。""" + text = json.dumps( + {"url": "https://example.com/a//b", "glob": "/* not a comment */"} + ) + assert loads(text) == { + "url": "https://example.com/a//b", + "glob": "/* not a comment */", + } + + def test_escaped_quote_does_not_break_comment_detection(self) -> None: + """字符串里的转义引号不应让后续内容被误判为字符串。""" + text = '{"a": "he said \\"hi\\" // still in string", "b": 2}' + assert loads(text) == {"a": 'he said "hi" // still in string', "b": 2} + + def test_comment_between_tokens(self) -> None: + """注释可以出现在任意 token 之间。""" + text = '{/*a*/"A"/*b*/:/*c*/1/*d*/,/*e*/"B"/*f*/:/*g*/2/*h*/}' + assert loads(text) == {"A": 1, "B": 2} + + def test_unterminated_block_comment_raises(self) -> None: + """未闭合的块注释应报错并给出位置。""" + with pytest.raises(json.JSONDecodeError, match="Unterminated comment"): + loads('{"A": 1} /* 没闭合') + + def test_duplicate_key_rejected(self) -> None: + """重复键应报错(meojson 同样拒绝)。""" + with pytest.raises(json.JSONDecodeError, match="Duplicate key"): + loads('{"A": 1, "A": 2}') + + def test_nan_rejected(self) -> None: + """NaN 不是合法 JSON,必须拒绝(stdlib json 默认接受)。""" + with pytest.raises(json.JSONDecodeError, match="not valid JSON"): + loads('{"A": NaN}') + + def test_infinity_rejected(self) -> None: + """Infinity 不是合法 JSON,必须拒绝。""" + with pytest.raises(json.JSONDecodeError, match="not valid JSON"): + loads('{"A": Infinity}') + + def test_negative_infinity_rejected(self) -> None: + """-Infinity 同样必须拒绝。""" + with pytest.raises(json.JSONDecodeError, match="not valid JSON"): + loads('{"A": -Infinity}') + + def test_bom_stripped(self) -> None: + """UTF-8 BOM 应被剥离而不是报错。""" + assert loads('{"A": 1}') == {"A": 1} + + def test_overflowing_float_rejected(self) -> None: + """溢出成 inf 的数字必须拒绝。 + + `1e999` 语法合法,但解析结果是 inf,序列化回去会变成非法的 + `Infinity` 字面量——写出来的文件既不是合法 JSON,MaaFramework 的 + 严格解析也会失败。 + """ + with pytest.raises(json.JSONDecodeError, match="not a finite number"): + loads('{"A": {"threshold": 1e999}}') + + def test_surrogate_pair_decoded(self) -> None: + """`\\uXXXX` 代理对应还原成真实码点(与 meojson 一致)。""" + assert loads('{"A": "\\ud83d\\ude00"}') == {"A": "\U0001f600"} + + def test_lone_surrogate_rejected(self) -> None: + """落单的代理字符必须拒绝。 + + 标准库会接受它,但后续 `json.dumps(...).encode()` 会抛 + UnicodeEncodeError,异常会直接冲出工具调用。 + """ + with pytest.raises(json.JSONDecodeError, match="lone surrogate"): + loads('{"A": "\\ud800"}') + + def test_non_str_input_raises_type_error(self) -> None: + """非 str 输入应抛 TypeError。""" + with pytest.raises(TypeError): + loads(b'{"A": 1}') # type: ignore[arg-type] + + def test_unquoted_key_rejected(self) -> None: + """无引号键必须拒绝(与 MaaFramework 行为一致)。""" + with pytest.raises(json.JSONDecodeError): + loads("{A: 1}") + + def test_single_quote_rejected(self) -> None: + """单引号字符串必须拒绝(与 MaaFramework 行为一致)。""" + with pytest.raises(json.JSONDecodeError): + loads("{'A': 1}") + + def test_error_reports_line_and_column(self) -> None: + """语法错误应报出正确的行列号。""" + text = '{\n "A": 1,\n "B": @\n}' + with pytest.raises(json.JSONDecodeError) as excinfo: + loads(text) + message = str(excinfo.value) + assert "line 3" in message + assert "column" in message + + def test_error_is_json_decode_error_subclass(self) -> None: + """抛出的错误必须是 json.JSONDecodeError 子类,兼容既有 except 分支。""" + with pytest.raises(json.JSONDecodeError): + loads("{not json") + + def test_duplicate_key_error_has_no_position(self) -> None: + """重复键无法定位,报错信息不应带误导性的行列号。""" + with pytest.raises(json.JSONDecodeError) as excinfo: + loads('{"A": 1, "A": 2}') + assert "line" not in str(excinfo.value) + + def test_trailing_garbage_rejected(self) -> None: + """顶层值之后的尾部垃圾应报错(meojson 同样报错)。""" + with pytest.raises(json.JSONDecodeError): + loads('{"A": 1} garbage') + + def test_trailing_comment_accepted(self) -> None: + """顶层值之后的注释应被忽略(meojson 同样接受)。""" + assert loads('{"A": 1} // done') == {"A": 1} + + def test_empty_container_comma_rejected(self) -> None: + """空容器里的逗号是语法错误(MaaFramework 同样拒绝)。 + + meojson 的解析循环必须先完成一个键值对才会收尾,所以 `{,}`、`[,]` + 都是错误;这里若放行,MaaMCP 就会接受 MaaFramework 拒绝的文件。 + """ + with pytest.raises(json.JSONDecodeError): + loads('{"a": {,}}') + with pytest.raises(json.JSONDecodeError): + loads('{"a": [,]}') + + def test_leading_comma_rejected(self) -> None: + """容器开头的逗号是语法错误(MaaFramework 同样拒绝)。""" + with pytest.raises(json.JSONDecodeError): + loads('{, "a": 1}') + + def test_trailing_slash_residue_rejected(self) -> None: + """顶层值之后的 `/x` 残余应报错。 + + 这是与 meojson 的一处有意偏离:meojson 的 `skip_whitespace` 把「已到输入 + 末尾」与「注释起始符非法」混为一谈,会静默丢弃残余;本模块按标准库语义 + 报错(方向是更严,不会接受 MaaFramework 拒绝的文件)。 + """ + with pytest.raises(json.JSONDecodeError): + loads('{"A": 1}/x') + + @pytest.mark.parametrize( + "payload", + [ + "{}", + "[]", + '{"a": 1}', + '{"a": [1, 2, {"b": null}]}', + '{"s": "he said \\"hi\\" // x"}', + '{"u": "\\u4f60\\u597d"}', + '{"esc": "a\\\\b"}', + '{"n": [0, -0, 1e5, 1E5, -1.5e-3, 0.0]}', + '{"t": true, "f": false, "z": null}', + '{"nested": {"a": {"b": {"c": [[[1]]]}}}}', + '{"slash": "a/b"}', + '{"emoji": "😀 中文"}', + ], + ) + def test_matches_stdlib_for_plain_json(self, payload: str) -> None: + """纯 JSON 的解析结果必须与标准库完全一致(JSON 是 JSONC 的子集)。""" + assert loads(payload) == json.loads(payload) + + +# ============================================================================= +# pipeline 文件读取 +# ============================================================================= + + +@pytest.mark.unit +class TestPipelineFileJsonc: + """pipeline 文件的 JSONC 读取。""" + + JSONC_TEXT = """ + { + // 入口节点 + "Start": { + "recognition": "DirectHit", + /* 直接命中后点击 */ + "action": "Click", + "next": ["Next"] + }, + "Next": { + "recognition": "DirectHit", + }, + } + """ + + def test_read_and_validate_pipelines_parses_jsonc(self, tmp_path: Path) -> None: + """_read_and_validate_pipelines 应能读带注释的 pipeline 文件。""" + p = tmp_path / "pipeline.json" + p.write_text(self.JSONC_TEXT, encoding="utf-8") + + out = _read_and_validate_pipelines([str(p)]) + + assert len(out) == 1 + data = out[0][1] + assert set(data) == {"Start", "Next"} + assert data["Start"]["next"] == ["Next"] + + def test_invalid_jsonc_reports_parse_error(self, tmp_path: Path) -> None: + """未闭合的块注释应抛出带文件名与 JSONC 具体原因的 ValueError。""" + p = tmp_path / "broken.json" + p.write_text('{"A": 1 /* 未闭合', encoding="utf-8") + + with pytest.raises(ValueError, match="JSON 解析失败") as excinfo: + _read_and_validate_pipelines([str(p)]) + + # 断言 JSONC 层的具体原因,避免这条用例在缺少 JSONC 支持时也能通过 + assert "Unterminated comment" in str(excinfo.value) + + def test_duplicate_key_rejected(self, tmp_path: Path) -> None: + """重复的节点名应报错(meojson 同样拒绝)。""" + p = tmp_path / "dup.json" + p.write_text('{"A": {"x": 1}, "A": {"x": 2}}', encoding="utf-8") + + with pytest.raises(ValueError, match="Duplicate key"): + _read_and_validate_pipelines([str(p)]) + + def test_non_utf8_file_reports_clear_error(self, tmp_path: Path) -> None: + """非 UTF-8 编码的文件应给出明确错误,而不是抛出裸异常。""" + p = tmp_path / "gbk.json" + p.write_bytes('{"A": "中文"}'.encode("gbk")) + + with pytest.raises(ValueError, match="UTF-8"): + _read_and_validate_pipelines([str(p)]) + + def test_deeply_nested_reports_clear_error(self, tmp_path: Path) -> None: + """嵌套层级过深应给出明确错误,而不是抛出未捕获的 RecursionError。""" + p = tmp_path / "deep.json" + p.write_text("[" * 2000 + "]" * 2000, encoding="utf-8") + + with pytest.raises(ValueError, match="嵌套层级过深"): + _read_and_validate_pipelines([str(p)]) + + def test_load_pipeline_returns_dict_for_jsonc(self, tmp_path: Path) -> None: + """load_pipeline 应返回解析后的 dict(注释被剥离)。""" + fake = tmp_path / "data" + (fake / "pipelines").mkdir(parents=True) + p = fake / "pipelines" / "ok.json" + p.write_text(self.JSONC_TEXT, encoding="utf-8") + + import maa_mcp.paths as paths_module + + original = paths_module.get_data_dir + paths_module.get_data_dir = lambda: fake + try: + out = load_pipeline(str(p)) + finally: + paths_module.get_data_dir = original + + assert isinstance(out, dict) + assert set(out) == {"Start", "Next"} + + +# ============================================================================= +# save_pipeline +# ============================================================================= + + +@pytest.mark.unit +class TestSavePipelineJsonc: + """save_pipeline 的 JSONC 输入。""" + + @pytest.fixture + def fake_data_dir(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + fake = tmp_path / "data" + (fake / "pipelines").mkdir(parents=True) + monkeypatch.setattr("maa_mcp.paths.get_data_dir", lambda: fake) + monkeypatch.setattr("maa_mcp.pipeline_tools.get_data_dir", lambda: fake) + return fake + + def test_accepts_jsonc_input(self, fake_data_dir: Path) -> None: + """带注释的输入字符串应被接受并成功落盘。""" + text = """ + { + // 注释 + "A": {"recognition": "DirectHit"}, + } + """ + out = save_pipeline(text, output_path="a.json") + assert Path(out).exists() + + def test_writes_standard_json(self, fake_data_dir: Path) -> None: + """落盘内容应是标准 JSON(注释丢弃),可被标准库 json 读取。""" + text = '{\n // 注释\n "A": {"recognition": "DirectHit"},\n}' + out = save_pipeline(text, output_path="b.json") + + content = Path(out).read_text(encoding="utf-8") + assert "//" not in content + assert json.loads(content) == {"A": {"recognition": "DirectHit"}} + + def test_invalid_jsonc_reports_error(self, fake_data_dir: Path) -> None: + """语法错误应返回错误信息而不是抛异常。""" + out = save_pipeline('{"A": 1 /* 未闭合', output_path="c.json") + assert isinstance(out, str) + assert "格式错误" in out + # 断言 JSONC 层的具体原因,避免这条用例在缺少 JSONC 支持时也能通过 + assert "Unterminated comment" in out + + def test_overflowing_number_rejected(self, fake_data_dir: Path) -> None: + """溢出成 inf 的数字应被拒绝——否则落盘会写出非法的 `Infinity`。""" + out = save_pipeline('{"A": {"threshold": 1e999}}', output_path="d.json") + assert isinstance(out, str) + assert "格式错误" in out + + def test_deeply_nested_reports_error(self, fake_data_dir: Path) -> None: + """嵌套层级过深应返回错误信息,而不是抛出未捕获的 RecursionError。""" + out = save_pipeline("[" * 2000 + "]" * 2000, output_path="e.json") + assert isinstance(out, str) + assert "嵌套层级过深" in out + + +# ============================================================================= +# interface.json +# ============================================================================= + + +@pytest.mark.unit +class TestInterfaceJsonJsonc: + """agent_supervisor 读取带注释的 interface.json。""" + + def test_reads_commented_interface(self, tmp_path: Path) -> None: + """带注释的 interface.json 应能读到 agent 配置。""" + (tmp_path / "interface.json").write_text( + """ + { + // agent 子进程配置 + "agent": { + /* 用 python 起 */ + "child_exec": "python", + "child_args": ["-u", "agent/main.py"], + "timeout": 30, + }, + } + """, + encoding="utf-8", + ) + + config = load_agent_config(str(tmp_path)) + + assert config is not None + assert config.child_exec == "python" + assert config.child_args == ["-u", "agent/main.py"] + + def test_broken_interface_returns_none(self, tmp_path: Path) -> None: + """interface.json 解析失败时应返回 None,而不是把异常抛出去。""" + (tmp_path / "interface.json").write_text( + '{"agent": {"child_exec": "python"} /* 未闭合', + encoding="utf-8", + ) + + assert load_agent_config(str(tmp_path)) is None diff --git a/tests/test_performance_stress.py b/tests/test_performance_stress.py index 0679074..3025af4 100644 --- a/tests/test_performance_stress.py +++ b/tests/test_performance_stress.py @@ -1,5 +1,22 @@ -"""压力测试 - 测量关键函数在高负载下的性能表现""" +"""压力测试 - 测量关键函数在高负载下的性能表现 +⚠️ 本文件会向**真实**设备 / 窗口发送点击、滑动、输入文本与按键,因此默认 +整体跳过,必须显式开启: + +```bash +# 只压测指定设备(ADB) +MAA_STRESS=1 MAA_STRESS_DEVICE="127.0.0.1:7555" pytest tests/test_performance_stress.py -v + +# 只压测指定窗口(Windows) +MAA_STRESS=1 MAA_STRESS_WINDOW="MuMu模拟器" pytest tests/test_performance_stress.py -v +``` + +目标必须通过环境变量显式指定,**绝不自动挑选第一个窗口 / 第一台设备**—— +`find_window_list()` 的第一项往往就是用户正在使用的 IDE 窗口,压力测试的 +点击与按键会直接打到它身上(曾导致 pytest 跑完把 VSCode 关掉)。 +""" + +import os import time import pytest from typing import Callable, Any, Optional, List, Dict @@ -10,6 +27,15 @@ from maa_mcp.adb import find_adb_device_list, connect_adb_device from maa_mcp.win32 import find_window_list, connect_window +# 压力测试会操作真实设备 / 窗口,属于集成级且默认关闭 +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif( + os.environ.get("MAA_STRESS", "").strip().lower() not in {"1", "true", "yes"}, + reason="压力测试会向真实设备/窗口发送点击与按键,需设置 MAA_STRESS=1 显式开启", + ), +] + def _call_tool(func, *args, **kwargs): """兼容模式:调用工具函数,自动处理 FunctionTool 和普通函数""" @@ -206,30 +232,50 @@ def setup_class(self): self.device_name = None self.window_name = None - # 尝试获取ADB设备 - try: - device_list = _call_tool(find_adb_device_list) - if device_list: - self.device_name = device_list[0] # 使用第一个设备 + # 目标必须显式指定:绝不自动挑第一个设备 / 窗口—— + # 第一个窗口往往就是用户正在用的 IDE 窗口,压力测试的点击与按键 + # 会直接打上去(曾把 VSCode 关掉)。 + device_name = os.environ.get("MAA_STRESS_DEVICE", "").strip() + window_name = os.environ.get("MAA_STRESS_WINDOW", "").strip() + + if not device_name and not window_name: + pytest.skip( + "未指定压力测试目标:设置 MAA_STRESS_DEVICE 或 MAA_STRESS_WINDOW " + "(绝不自动选择第一个窗口 / 设备,以免干扰用户正在使用的程序)" + ) + + # 指定的 ADB 设备 + if device_name: + try: + device_list = _call_tool(find_adb_device_list) + if device_name not in device_list: + pytest.skip( + f"指定的 ADB 设备 {device_name!r} 不存在," + f"可用设备: {device_list}" + ) + self.device_name = device_name self.controller_id = _call_tool(connect_adb_device, self.device_name) print( f" 使用ADB设备: {self.device_name}, 控制器ID: {self.controller_id}" ) - except Exception as e: - print(f" 获取ADB设备失败: {e}") + except Exception as e: + print(f" 连接ADB设备失败: {e}") - # 如果没有ADB设备,尝试获取Windows窗口 - if not self.controller_id: + # 指定的 Windows 窗口 + if not self.controller_id and window_name: try: window_list = _call_tool(find_window_list) - if window_list: - self.window_name = window_list[0] # 使用第一个窗口 - self.controller_id = _call_tool(connect_window, self.window_name) - print( - f" 使用Windows窗口: {self.window_name}, 控制器ID: {self.controller_id}" + if window_name not in window_list: + pytest.skip( + f"指定的窗口 {window_name!r} 不存在,可用窗口: {window_list}" ) + self.window_name = window_name + self.controller_id = _call_tool(connect_window, self.window_name) + print( + f" 使用Windows窗口: {self.window_name}, 控制器ID: {self.controller_id}" + ) except Exception as e: - print(f" 获取Windows窗口失败: {e}") + print(f" 连接Windows窗口失败: {e}") # 如果仍然没有控制器,跳过测试类 if not self.controller_id: @@ -636,6 +682,15 @@ def compare_function_performances( if __name__ == "__main__": """压力测试示例 - 展示如何使用压力测试模块""" + if os.environ.get("MAA_STRESS", "").strip().lower() not in {"1", "true", "yes"}: + print( + "压力测试会向真实设备/窗口发送点击与按键,已跳过。\n" + "请先设置 MAA_STRESS=1,并指定 MAA_STRESS_DEVICE 或 MAA_STRESS_WINDOW。\n" + '示例: MAA_STRESS=1 MAA_STRESS_WINDOW="MuMu模拟器" ' + "python tests/test_performance_stress.py" + ) + raise SystemExit(1) + print("MaaMCP 压力测试示例") print("=" * 60)