"""守门:**所有超时都是可调的**(用户要求"全部超时做成可调")。 ## 为什么需要这个脚本 超时这件事以前散在 10 个文件里当模块级常量,谁也不知道一共有几个 —— 所以"哪些能调、哪些不能调"根本回答不了。收进 `timeouts.py` 之后, 这个脚本负责钉住两件事: A. **清单是完整的**:每一项都有默认值 + 边界 + 说明,界面拿得到 B. **没有漏网的硬编码**:内核里不该再出现写死的超时数字 (这是最容易回退的地方 —— 下次谁顺手写个 `timeout=30` 就又多一个调不了的) B 是重点。"查硬编码"必然会有误报(`join(timeout=2)` 这种内部清理、 `proc.wait(timeout=3)`),所以用一个**白名单**显式列出允许的例外, 并且要求每条例外都在代码里带注释说明为什么不用可调 —— 而不是靠正则蒙。 用法: python scripts/verify-timeouts.py """ import io import os import re import sys try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") except Exception: pass HERE = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.abspath(os.path.join(HERE, "..")) KERNEL = os.path.join(REPO, "android", "kernel") TOOLS = os.path.join(REPO, "tools") sys.path.insert(0, KERNEL) fails = [] warns = [] def fail(m): fails.append(m) print(f" ✗ {m}") def ok(m): print(f" ✓ {m}") def warn(m): warns.append(m) print(f" ! {m}") import timeouts as TO # noqa: E402 # --------------------------------------------------------------------------- # # A. 清单本身 # --------------------------------------------------------------------------- # print("=== A. 超时清单 ===") if set(TO.DEFAULT) == set(TO.BY_KEY): ok(f"{len(TO.DEFAULT)} 项:默认值和说明一一对应") else: only_default = sorted(set(TO.DEFAULT) - set(TO.BY_KEY)) only_spec = sorted(set(TO.BY_KEY) - set(TO.DEFAULT)) if only_default: fail(f"这些有默认值但没有说明(界面会少一行):{only_default}") if only_spec: fail(f"这些有说明但没有默认值:{only_spec}") for spec in TO.SPECS: for field in ("key", "label", "group", "desc", "default", "min", "max", "unit"): if field not in spec: fail(f"{spec.get('key')} 少了字段 {field}") if spec["min"] > spec["default"] or spec["default"] > spec["max"]: fail(f"{spec['key']} 的默认值 {spec['default']} 不在 [{spec['min']}, {spec['max']}] 里") groups = sorted({s["group"] for s in TO.SPECS}) ok(f"分组:{' / '.join(groups)}") # 边界的实际效果:填什么都不该炸 print("\n=== 边界(用户输入的容错)===") cases = [ ("tool", "abc", "文字"), ("tool", "", "空串"), ("tool", -5, "负数"), ("tool", 999999, "超大值"), ("tool", "60秒", "带单位"), ("tool", None, "None"), ("model", 0, "0"), ] for key, raw, label in cases: try: got = TO.coerce(key, raw) spec = TO.BY_KEY[key] if spec["min"] <= got <= spec["max"]: ok(f"{label:>8} → {got:g}(夹在 [{spec['min']}, {spec['max']}] 内)") else: fail(f"{label} 算出来 {got},越界了") except Exception as exc: # noqa: BLE001 fail(f"{label} 把 coerce 弄炸了:{exc}") # 「不限时」只给该给的项 zero_ok = sorted(k for k, s in TO.BY_KEY.items() if s["min"] == 0) if zero_ok == ["agentAnim.gap", "askUser", "tool", "waitUi"]: ok(f"允许「不限时」的只有:{zero_ok}") else: fail(f"允许 min=0 的项不对:{zero_ok}(应该只有等用户的两项 + 工具执行 + 动画的「中间留白」)") # --------------------------------------------------------------------------- # # B. 没有漏网的硬编码 # --------------------------------------------------------------------------- # print("\n=== B. 内核里的硬编码超时 ===") # 允许的例外:内部清理用的短超时 / 探测。 # 每一条都必须能在源码里找到一句说明"为什么它不用可调"。 ALLOWED = { "mcp_client.py": [ # 进程退出时等它自己收尾,跟用户可感知的"等多久"无关 (r"proc\.wait\(timeout=3\)", "关进程时的收尾等待"), (r"_thread\.join\(timeout=2\)", "收线程时的收尾等待"), (r"_thread\.join\(timeout=", "收线程时的收尾等待"), ], "providers.py": [ (r"return 180\.0", "读设置失败时的兜底值"), ], "speech.py": [ (r"return 60\.0", "读设置失败时的兜底值"), (r"return 120\.0", "读设置失败时的兜底值"), ], "timeouts.py": [ (r".*", "它就是定义超时的那个文件"), ], "doubao_entry.py": [ (r"_TERMUX_FIRST_PROBE_S", "第一次探测 Termux 可用性的短超时"), ], "main.py": [ # 主线程每秒醒一次看"要不要停机" —— 这是**轮询间隔**不是超时, # 调它没有任何用户可感知的意义 (r"stop\.wait\(1\)", "停机轮询间隔"), ], } # 形如 timeout=30 / timeout: float = 60 / join(10) / wait(15) 的写法 PAT = re.compile( r"(?:timeout\s*[:=]\s*|\.join\(\s*|\.wait\(\s*|\.wait\(timeout\s*=\s*)" r"(\d+(?:\.\d+)?)\b" ) # 本来就该带数字的地方(这些不是"超时") SKIP_LINE = re.compile(r"TIMEOUT_KEYS|'timeout'|\"timeout\"|#|timeouts\.get|budget|api/v1|version") checked = 0 for name in sorted(os.listdir(KERNEL)): if not name.endswith(".py"): continue if name in ("builtin_tools.py",): # 这里的 join(timeout_s) 是**实现超时机制本身**,不是某个超时值 continue path = os.path.join(KERNEL, name) with io.open(path, encoding="utf-8") as fh: for lineno, line in enumerate(fh, 1): if SKIP_LINE.search(line): continue for m in PAT.finditer(line): checked += 1 allowed = any(re.search(pat, line) for pat, _ in ALLOWED.get(name, [])) if allowed: continue fail(f"{name}:{lineno} 写死了超时 {m.group(0).strip()}:{line.strip()[:70]}") if checked and not fails: ok(f"扫了 {len(os.listdir(KERNEL))} 个内核文件,没有调不了的硬编码超时") elif not checked: warn("一条 timeout=数字 都没扫到 —— 正则可能失效了,检查一下") # tools/ 下的工具:它们的默认值必须是**兜底**,真值由内核注入 print("\n=== C. 工具侧的默认值只是兜底 ===") for tool, key in (("ask_user.py", "askUser"), ("show_ui.py", "waitUi")): with io.open(os.path.join(TOOLS, tool), encoding="utf-8") as fh: src = fh.read() if "TIMEOUT_KEYS" in src and key in src: ok(f"{tool} 声明了 TIMEOUT_KEYS(内核会把设置里的值注入进去)") else: fail(f"{tool} 没声明 TIMEOUT_KEYS —— 设置里那一项对它无效") import tools_runtime as TR # noqa: E402 if "TIMEOUT_KEYS" in __import__("inspect").getsource(TR._with_default_timeouts): ok("tools_runtime 会按 TIMEOUT_KEYS 注入默认值") else: fail("tools_runtime 的注入逻辑不见了") # --------------------------------------------------------------------------- # # D. Node 端那份必须和 Python 这份逐项一致 # --------------------------------------------------------------------------- # print("\n=== D. Node 端(server/src/timeouts.mjs)对拍 ===") import json # noqa: E402 import subprocess # noqa: E402 NODE_PROBE = ( "import('./server/src/timeouts.mjs').then(m => " "console.log(JSON.stringify({d: m.DEFAULT_TIMEOUTS, s: m.TIMEOUT_SPECS})))" ) proc = None try: # ★ encoding 必须显式给 utf-8:node 输出的是 UTF-8,而这台机器的 # locale 是 GBK —— 用 text=True 的默认编码去解会把中文解崩 # (表现是 stdout 读不出来,还看不出是编码问题)。 proc = subprocess.run( ["node", "--input-type=module", "-e", NODE_PROBE], cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60, ) raw = (proc.stdout or "").strip().splitlines() data = json.loads(raw[-1]) if raw else None except Exception as exc: # noqa: BLE001 data = None warn(f"跑不了 node 对拍({exc})—— 跳过这一节") if data is None: detail = "" if proc is not None: detail = (f"(退出码 {proc.returncode},stdout={(proc.stdout or '')[:120]!r}," f"stderr={(proc.stderr or '')[:200]!r})") warn(f"node 探测没拿到结果{detail} —— 跳过这一节") else: js_default = data["d"] js_specs = {s["key"]: s for s in data["s"]} if set(js_default) == set(TO.DEFAULT): ok(f"默认值的键两边一致(各 {len(js_default)} 项)") else: only_py = sorted(set(TO.DEFAULT) - set(js_default)) only_js = sorted(set(js_default) - set(TO.DEFAULT)) if only_py: fail(f"Python 有、Node 没有的项:{only_py}") if only_js: fail(f"Node 有、Python 没有的项:{only_js}") if set(js_specs) == set(TO.BY_KEY): ok("说明表的键两边一致") else: fail(f"说明表对不上:Node 独有 {sorted(set(js_specs) - set(TO.BY_KEY))}," f"Python 独有 {sorted(set(TO.BY_KEY) - set(js_specs))}") diff = 0 for key, spec in TO.BY_KEY.items(): js = js_specs.get(key) if not js: continue for field in ("label", "group", "default", "min", "max"): if spec.get(field) != js.get(field): diff += 1 fail(f"{key}.{field} 不一致:Python {spec.get(field)!r} vs Node {js.get(field)!r}") if not diff: ok("每一项的 名字 / 分组 / 默认值 / 上下界 都一致") # --------------------------------------------------------------------------- # print() if fails: print(f"❌ {len(fails)} 项不合格:") for m in fails: print(" -", m) sys.exit(1) print(f"✅ 全部通过(警告 {len(warns)} 条)")