Files
doubao-clone/scripts/verify-timeouts.py
l c7fed95650 feat: 所有超时收成一份、全部可调(设置 → 超时,18 项)
用户要求"全部超时做成可调"。改造前 15 个超时散在 10 个文件里当模块级常量,
说不清一共有几个,也答不了"哪些能调"。

内核
- 新增 android/kernel/timeouts.py:**超时的唯一一份定义**(DEFAULT + SPECS),
  带每项的 名字/分组/说明/默认值/上下界;get() 一律夹取,用户填什么都不炸
- 新增 GET/POST /api/timeouts(清单 + 当前值 + 保存 + 恢复默认)
- 各处改现读:tools_runtime(tool)、builtin_tools(shell/pythonRun)、
  doubao_entry(termux)、providers(model)、speech(tts/stt)、
  mcp_client(请求/连接/调用)、meeting(meetingNode)、custom_nodes(customNode)、
  app.py 的 SSE 心跳
- ask_user / show_ui 用 TIMEOUT_KEYS 声明"哪个参数该用设置里的值",
  内核调用前注入(工具的默认值退化成单独跑时的兜底)
- store.py:timeouts 走**整体替换**而不是深合并 —— 深合并会让"改回默认"删不掉

安卓
- data/AppTimeouts.kt:客户端缓存(OkHttp 的 readTimeout、文件选择没法现问内核)
- KernelClient:readTimeout 跟着 sseRead 走,改完重建连接池;新增 timeouts 接口
- ui/TimeoutsScreen.kt:全屏界面,按分组列出、-/+ 与输入框、恢复默认
- 设置页加「超时」卡片入口;NativeBridge 的本地接口请求 / 选文件等待接上
- Settings 模型加 TimeoutItem / TimeoutsState(字段全部来自内核)

Node 端(Web/exe)
- 新增 server/src/timeouts.mjs(和 Python 那份逐字对应)
- config.mjs 加 timeouts(同样整体替换);speech / python-tools / mcp / providers
  各处改读;index.mjs 加 /api/timeouts

验证
- 新增 scripts/verify-timeouts.py:清单完整性、边界容错(文字/空串/负数/超大值/
  带单位/None)、**扫内核有没有漏网的硬编码超时**(带白名单)、
  工具侧声明、以及和 Node 端逐项对拍
- 实测真机:界面显示 18 项来自内核 → 点 + 保存 → 内核 heartbeat 15→25 →
  恢复默认 → 回 15;askUser 显示"不限时"

文档:README §3.13;docs/AI界面能力.md 的"不限时要三处一起改"补上可调入口。
版本 2.0.46。
2026-10-16 10:29:46 +08:00

267 lines
9.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""守门:**所有超时都是可调的**(用户要求"全部超时做成可调")。
## 为什么需要这个脚本
超时这件事以前散在 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 == ["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)} 条)")