★ 修一个让所有工具更新都失效的 bug + show_ui 支持"等用户操作" (v2.0.38)

用户反馈两条:
  1. "不行哪有按键,网页里的按键也点不了"
  2. "ai 可以选择等待网页关闭并返回结果,也可以不等结果进下一轮对话,也可啥也不做"

第 2 条直接做成了 show_ui 的 wait 参数。第 1 条查下去,挖出一个**比按钮本身严重得多**的 bug。

## ★★★ 根因:内置工具更新在老设备上永远不生效

`_seed_tools` 是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
后果:**每一次发版更新的内置工具,在老设备上一律拿不到。**

这个 bug 的表现极具误导性,值得完整记下来:

  · 代码改了 ✓  APK 重编了 ✓  app.imy 里确实有新 .pyc ✓
  · 但设备上跑的还是旧那份 —— 因为内核加载的是**落盘的那份旧源码**
  · 实测:v2.0.37 给 show_ui 加了 wait 参数,设备上报的 spec 里根本没这个参数
  · 我一度以为是 Gradle 构建缓存没生效,查了好几轮

**用户报的"按键点不了",根因就是这个**:他手机上还是 v2.0.36 那份 show_ui,
而回传按钮(`Doubao.sendToAi`)是 v2.0.37 才接通的。

### 修的过程里又踩了两个坑(都记在代码注释里了)

**坑一**:第一版修法是只看一个本地指纹文件 `.doubao-seed.json`:
指纹对得上=我们写的(可覆盖),对不上=用户改过(不覆盖)。

结果**老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
于是所有文件都被判成"用户改过" —— **升级还是永远不生效**。
我把中间量全打出来才看清:`{"skip-same": 12, "skip-user-edited": 1}`,
12 个没改过的是"内容相同"跳过,唯一改过的 show_ui 被判成用户改的。

**坑二(先有鸡还是先有蛋)**:于是加了一份**构建时累积的历史哈希登记表**
(`tools/.shipped-hashes.json`),靠它认出"盘上这份是我们以前发的某个版本"。
但登记表是这次才开始记的 —— **设备上现存的旧哈希不在表里**,还是认不出来。
所以补了 `scripts/backfill-shipped-hashes.py`:翻 git 历史,把每个工具文件
**出现过的每一个版本**都算一遍哈希填进去。回填后确认设备上那份
(show_ui.py sha256 前 16 位 `1882a766fe0ee833`)在表里了。

最终的判断顺序(4 条):
  1. 内容和这一版一样          → 什么都不做(顺手补指纹)
  2. 内容在**历史登记表**里    → 我们以前发的 → **安全覆盖**
  3. 内容等于本地指纹记的      → 我们写的 → **安全覆盖**
  4. 都不是                    → 用户改过 → **绝不覆盖**

实测效果:设备上 `show_ui.py` 从 3883 字节 → **7439 字节**,
spec 里 wait/timeout 参数都出现了。

## show_ui 的三种收尾方式(用户要的)

| 用法 | 行为 | 适合 |
|---|---|---|
| `wait` 不传(默认) | 弹出就返回,不等 | 图表、报告这类"给用户看"的 |
| `wait=true` | **等用户点回传按钮或关掉界面**,最多 timeout 秒(默认 120,上限 600) | "弹几个选项让用户挑,然后我接着干" |
| 不调用 show_ui | 纯文字回答 | —— |

等待模式下用户点的值**立刻**作为工具返回值给模型,**同一个回合里**就能接着处理。
直接关掉界面返回 `value=""` + `closed=true`;超时返回 `timeout=true`,
并提示模型"别反复重弹,正常收尾"。

实测:`wait=true` 阻塞了 9.3 秒,用户点了「方案丙(JS)」,
返回 `{"waited":true,"timeout":false,"value":"方案丙(JS)"}`,界面自动收掉。

★ 实现上有个竞态要防:**先备好闩再弹界面**。顺序反了的话用户手快先点了
(界面已经显示、按钮就在那儿),countDown 打在空闩上,然后才开始等,
直接等满超时。这类"用户比代码快"的问题在真机上很容易出现。

## 按钮做得不可能看不见

原来 `.db-btn` 是 `#2a2d34` 暗底 + `#e8eaed` 字 —— 在深色主题下**和普通段落
长得一模一样**,用户根本看不出那儿能点。现在:
整行宽、亮蓝底 + 白字、15px padding、16px 字号、有按下反馈,
`!important` 压掉模型内联的样式(模型经常内联 `style="background:..."` 把它盖掉)。
普通 `<button>`(没标 data-doubao-result 的)也给可见边框,但没那么抢眼。

提示词里也加了要求:放按钮时要做明显,别用纯文字当按钮。

## 验证

新增 `scripts/verify-seed-tools.py`(8 节)钉住播种逻辑,**包括那两个坑**:
 · 老设备场景:指纹文件是空的,但盘上是我们以前发的旧版本 → 必须覆盖
 · 反过来:盘上内容不在历史表里 → 一定是用户改的 → 不许覆盖
 · 指纹文件坏了不能崩、也不能乱覆盖(保守处理)
 · 内容没变时不许动 mtime

真机实测(Android 14 x86_64):
 · 设备上 show_ui.py 7439 字节、含 9 处 wait、指纹表 14 条 ✓
 · spec 里 wait / timeout 都在 ✓
 · wait=false 立刻返回(0.0s)✓
 · wait=true 等 9.3s 拿到用户点的值 ✓
This commit is contained in:
doubao
2026-10-15 11:31:00 +08:00
parent 5f138be5fa
commit ba429e67cd
23 changed files with 1562 additions and 64 deletions

View File

@@ -0,0 +1,93 @@
"""把 tools/*.py 在**所有历史提交**里出现过的版本哈希,回填进 tools/.shipped-hashes.json。
## 为什么需要这个回填
`_seed_tools` 靠"这份哈希是不是我们发过的"来区分
「老设备上的旧版本(可以覆盖)」和「用户自己改的(绝不能覆盖)」。
但登记表是这一次才开始记的,所以**设备上现存的那些旧版本哈希不在表里**——
升级还是会被判成"用户改过"。典型的先有鸡还是先有蛋。
修法:翻 git 历史,把每个工具文件**出现过的每一个版本**都算一遍哈希填进去。
老设备上跑的一定是历史里的某一版,这样就都能认出来。
(只增不减:哈希多记几个没坏处,最多是"把某个用户恰好改成一模一样内容的文件"
也当成我们的 —— 那种情况实际不可能发生。)
用法:
python scripts/backfill-shipped-hashes.py # 只看,不写
python scripts/backfill-shipped-hashes.py --write # 真写
"""
import hashlib
import json
import os
import subprocess
import sys
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.join(WS, "tools")
REG = os.path.join(TOOLS, ".shipped-hashes.json")
WRITE = "--write" in sys.argv
def git(*args) -> str:
out = subprocess.run(
["git", "-C", WS, *args],
capture_output=True, text=True, encoding="utf-8", errors="replace",
)
if out.returncode != 0:
raise RuntimeError(f"git {' '.join(args)} 失败:{out.stderr[:300]}")
return out.stdout
def h(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
try:
registry = json.load(open(REG, encoding="utf-8"))
except Exception:
registry = {}
files = sorted(f for f in os.listdir(TOOLS) if f.endswith(".py"))
print(f"仓库里有 {len(files)} 个工具文件\n")
added_total = 0
for name in files:
rel = f"tools/{name}"
# 这个文件历史上被改过的所有提交
commits = git("log", "--all", "--format=%H", "--", rel).split()
versions = set()
for sha in commits:
try:
content = git("show", f"{sha}:{rel}")
except RuntimeError:
continue
versions.add(h(content))
# 当前工作区那份也要在(构建时会自己加,但这里保证一致)
versions.add(h(open(os.path.join(TOOLS, name), encoding="utf-8").read()))
have = set(registry.get(name) or [])
new = sorted(versions - have)
if new:
print(f" {name}: 历史 {len(versions)} 版,新增 {len(new)} 条")
added_total += len(new)
registry[name] = sorted(have | versions)
print(f"\n共新增 {added_total} 条")
for name in files:
print(f" {name}: {len(registry[name])} 条")
if WRITE:
with open(REG, "w", encoding="utf-8") as fh:
json.dump(registry, fh, ensure_ascii=False, indent=2, sort_keys=True)
fh.write("\n")
print(f"\n已写入 {REG}")
else:
print("\n(只看不写。加 --write 才真写)")

View File

@@ -11,6 +11,7 @@
* 用法: node scripts/build-apk.mjs [--skip-build] [--release]
*/
import { spawnSync } from 'node:child_process';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -109,12 +110,56 @@ for (const file of fs.readdirSync(path.join(repo, 'tools'))) {
toolSources[file] = source.toString('base64');
toolCount += 1;
}
// ★★★ 内置工具的"历史版本哈希登记表"
//
// 为什么需要它 —— 这里踩过一个非常隐蔽的坑:
//
// 内核启动时把内置工具播种到手机可写目录(用户能自己改)。
// 为了**不许覆盖用户改过的文件**,播种时要判断"盘上这份是不是我们写的"。
// 第一版只看一个本地指纹文件(.doubao-seed.json):
// 指纹对得上 = 我们写的;对不上 = 用户改过 → 不覆盖。
//
// 问题是**老设备上那个指纹文件是空的**(第一版播种逻辑没写过它)。
// 于是所有文件都被判成"用户改过",**升级永远不生效** ——
// 实测 v2.0.37 给 show_ui 加了 wait 参数,真机上死活拿不到。
//
// 所以必须有一份"我们**以前**发过哪些内容"的记录,才能区分:
// · 盘上这份是我们旧版本发的 → 安全覆盖
// · 盘上这份不是任何一版我们发的 → 用户改过 → 绝不覆盖
//
// 这份登记表在构建时累积:每发一版就把当前哈希加进去(去重、只增不减)。
// 存成仓库里的一个 JSON 文件,跟着代码走。
const regPath = path.join(repo, 'tools', '.shipped-hashes.json');
let registry = {};
try {
registry = JSON.parse(fs.readFileSync(regPath, 'utf8'));
} catch {
registry = {};
}
const hashOf = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 16);
let newHashes = 0;
for (const [name, source] of Object.entries(toolSources)) {
const text = Buffer.from(source, 'base64').toString('utf8');
const h = hashOf(text);
const list = Array.isArray(registry[name]) ? registry[name] : [];
if (!list.includes(h)) {
list.push(h);
newHashes += 1;
}
registry[name] = list;
}
fs.writeFileSync(regPath, JSON.stringify(registry, null, 2) + '\n', 'utf8');
if (newHashes) log(`工具哈希登记表:新增 ${newHashes} 条`);
const bundledPy = [
'"""构建时自动生成,不要手改。',
'',
'内置 Python 工具的源码(base64)。安卓端 Chaquopy 只有 .pyc,',
'所以由 scripts/build-apk.mjs 在打包时把源码嵌进来,',
'由 doubao_entry 首次启动时解码写到手机上的可写工具目录。',
'由 doubao_entry 启动时解码写到手机上的可写工具目录。',
'',
'`shipped()` 返回"历史上我们发过的所有源码哈希" —— 内核靠它区分',
'"盘上这份是我们旧版本写的(可以覆盖)" 和 "用户自己改过(不能覆盖)"。',
'"""',
'',
'import base64',
@@ -123,14 +168,23 @@ const bundledPy = [
...Object.entries(toolSources).map(([name, b64]) => ` ${JSON.stringify(name)}: ${JSON.stringify(b64)},`),
'}',
'',
'_SHIPPED = {',
...Object.entries(registry).map(([name, list]) => ` ${JSON.stringify(name)}: ${JSON.stringify(list)},`),
'}',
'',
'',
'def sources():',
' """返回 {文件名: 源码文本}"""',
' return {name: base64.b64decode(data).decode("utf-8") for name, data in _DATA.items()}',
'',
'',
'def shipped():',
' """返回 {文件名: [历史哈希, ...]}"""',
' return {name: list(v) for name, v in _SHIPPED.items()}',
'',
].join('\n');
fs.writeFileSync(path.join(pyRoot, 'bundled_tool_sources.py'), bundledPy, 'utf8');
log(`已内置 ${toolCount} 个 Python 工具(含源码与 _protocol.py)`);
log(`已内置 ${toolCount} 个 Python 工具(含源码、_protocol.py、历史哈希表)`);
// 内核源码在 android/kernel,靠 chaquopy 的 srcDir("../kernel") 引入;
// 这里检查一下它确实在

View File

@@ -0,0 +1,49 @@
"""查设备上跑的 show_ui.py 是不是新的(有没有 wait 参数)。"""
import json
import sys
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
def call(path, payload=None, method="POST", timeout=60):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
tools = call("/api/tools", None, "GET")
py = (tools.get("python") or tools.get("tools") or [])
if isinstance(py, dict):
py = py.get("python") or []
found = None
for t in py:
if t.get("name") == "show_ui":
found = t
break
if not found:
print("!! /api/tools 里没有 show_ui;原始返回:")
print(json.dumps(tools, ensure_ascii=False)[:1500])
sys.exit(1)
print("show_ui 的 spec:")
print(" 有 wait 参数:", "wait" in json.dumps(found.get("parameters") or {}, ensure_ascii=False))
print(" 有 timeout 参数:", "timeout" in json.dumps(found.get("parameters") or {}, ensure_ascii=False))
desc = found.get("description") or ""
print(" description 里提到 wait:", "wait" in desc)
print(" description 里提到'三种收尾':", "三种收尾" in desc)
print()
print("description 前 400 字:")
print(desc[:400])
print()
print("工具目录:", (tools.get("dir") or tools.get("toolsDir") or "(没报)"))

View File

@@ -0,0 +1,57 @@
"""把设备上 show_ui.pyc 的修改时间、以及内核报的 spec 一起打出来。
用于回答:"我明明重建安装了,为什么设备上跑的还是旧的?"
"""
import json
import sys
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
def call(path, payload=None, method="POST", timeout=60):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
# python_run 能在**内核进程里**跑(虽然是子进程,但能看文件系统)
probe = r'''
import os, sys, json, glob
out = {}
# Chaquopy 的 Python 根目录
for p in sys.path:
if p and os.path.isdir(p):
for name in ("show_ui.py", "show_ui.pyc", "bundled_tool_sources.pyc"):
f = os.path.join(p, name)
if os.path.exists(f):
st = os.stat(f)
out.setdefault("found", []).append({
"path": f, "size": st.st_size, "mtime": st.st_mtime,
})
out["sys_path_head"] = sys.path[:6]
out["has_wait_in_source"] = None
# 试着从 bundled_tool_sources 里解出 show_ui 的源码,看看有没有 wait
try:
import base64, bundled_tool_sources
src = bundled_tool_sources.sources().get("show_ui.py", "")
out["has_wait_in_source"] = ("wait" in src)
out["source_len"] = len(src)
out["source_head"] = src[:200]
except Exception as e:
out["bundled_error"] = f"{type(e).__name__}: {e}"
print(json.dumps(out, ensure_ascii=False))
'''
res = call("/api/tools/run", {
"name": "python_run", "args": {"code": probe, "timeout": 30},
}, timeout=90)
print(json.dumps(res, ensure_ascii=False, indent=2)[:2500])

View File

@@ -0,0 +1,63 @@
"""看设备上 show_ui.py 的实际大小 / 指纹,以及播种日志。"""
import json
import sys
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
TOOLS = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
def call(path, payload=None, method="POST", timeout=90):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
probe = r'''
import os, sys, json, hashlib
D = %r
out = {"dir": D, "exists": os.path.isdir(D)}
if os.path.isdir(D):
files = []
for name in sorted(os.listdir(D)):
p = os.path.join(D, name)
if os.path.isfile(p):
st = os.stat(p)
item = {"name": name, "size": st.st_size, "mtime": st.st_mtime}
if name.endswith(".py"):
txt = open(p, encoding="utf-8", errors="replace").read()
item["has_wait"] = "wait" in txt
item["sha16"] = hashlib.sha256(txt.encode()).hexdigest()[:16]
files.append(item)
out["files"] = files
sp = os.path.join(D, ".doubao-seed.json")
if os.path.isfile(sp):
out["stamp_exists"] = True
out["stamp_show_ui"] = json.load(open(sp, encoding="utf-8")).get("show_ui.py")
else:
out["stamp_exists"] = False
# 内嵌源码里的那份
try:
import hashlib as _h
import bundled_tool_sources
src = bundled_tool_sources.sources().get("show_ui.py", "")
out["bundled_len"] = len(src)
out["bundled_sha16"] = _h.sha256(src.encode()).hexdigest()[:16]
out["bundled_has_wait"] = "wait" in src
except Exception as e:
out["bundled_error"] = f"{type(e).__name__}: {e}"
print(json.dumps(out, ensure_ascii=False, indent=1))
''' % TOOLS
res = call("/api/tools/run", {"name": "python_run", "args": {"code": probe, "timeout": 30}}, timeout=120)
out = (res or {}).get("result") or {}
print(out.get("stdout") or json.dumps(out, ensure_ascii=False)[:1500])

View File

@@ -0,0 +1,109 @@
"""让内核进程直接往工具目录写一个文件,再从宿主机看它到底有没有真的落地。
★ 目的:排除"FUSE / 作用域存储导致宿主机看到的是另一份视图"这种可能。
"""
import base64
import json
import sys
import time
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
MARK = "内核进程写的标记 abc123"
code = (
"import os, json\n"
"D = %r\n"
"out = {}\n"
"p = os.path.join(D, '_kernelwrite.txt')\n"
"try:\n"
" with open(p, 'w', encoding='utf-8') as fh:\n"
" fh.write(%r)\n"
" out['wrote'] = True\n"
" out['size'] = os.path.getsize(p)\n"
" out['readback'] = open(p, encoding='utf-8').read()\n"
"except Exception as e:\n"
" out['err'] = f'{type(e).__name__}: {e}'\n"
"try:\n"
" import paths\n"
" out['paths_tools_dir'] = paths.get().tools_dir\n"
"except Exception as e:\n"
" out['paths_err'] = f'{type(e).__name__}: {e}'\n"
"try:\n"
" import doubao_entry as de\n"
" out['bundled_files_count'] = len(de.BUNDLED_TOOL_FILES)\n"
" out['bundled_files'] = list(de.BUNDLED_TOOL_FILES)\n"
" out['seed_wrote'] = de._seed_tools(getattr(paths.get(), 'tools_dir', D))\n"
"except Exception as e:\n"
" import traceback\n"
" out['seed_err'] = f'{type(e).__name__}: {e}'\n"
" out['seed_tb'] = traceback.format_exc()[-900:]\n"
"print(json.dumps(out, ensure_ascii=False, indent=1))\n"
) % (D, MARK)
# ★ 关键:用 /api/tools/run 跑的是**内核进程**吗?
# python_run 会 fork 子进程。但 device / shell 这类是进程内的。
# 这里用 python_run 不够 —— 要进程内的。所以写个临时工具让内核自己 import 执行。
probe_src = (
"import os, sys, json\n"
"sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n"
"TOOL = {'name': 'probe_kw', 'description': 'x',\n"
" 'parameters': {'type': 'object', 'properties': {}}}\n"
"def run(args):\n"
" out = {}\n"
" D = %r\n"
" p = os.path.join(D, '_kernelwrite.txt')\n"
" try:\n"
" with open(p, 'w', encoding='utf-8') as fh:\n"
" fh.write(%r)\n"
" out['wrote'] = True\n"
" out['readback'] = open(p, encoding='utf-8').read()\n"
" except Exception as e:\n"
" out['write_err'] = f'{type(e).__name__}: {e}'\n"
" try:\n"
" import paths\n"
" out['paths_tools_dir'] = paths.get().tools_dir\n"
" except Exception as e:\n"
" out['paths_err'] = f'{type(e).__name__}: {e}'\n"
" try:\n"
" import doubao_entry as de\n"
" out['bundled_count'] = len(de.BUNDLED_TOOL_FILES)\n"
" out['has_src_hash'] = hasattr(de, '_src_hash')\n"
" out['seed_wrote'] = de._seed_tools(D)\n"
" except Exception as e:\n"
" import traceback\n"
" out['seed_err'] = f'{type(e).__name__}: {e}'\n"
" out['seed_tb'] = traceback.format_exc()[-900:]\n"
" return out\n"
) % (D, MARK)
b64 = base64.b64encode(probe_src.encode("utf-8")).decode()
w = (
"import base64,os;"
"open(os.path.join('%s','probe_kw.py'),'wb').write(base64.b64decode('%s'));"
"print('ok')" % (D, b64)
)
def call(path, payload=None, method="POST", timeout=120):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
time.sleep(1)
call("/api/tools", None, "GET")
r = call("/api/tools/run", {"name": "probe_kw", "args": {}}, timeout=120)
res = (r or {}).get("result") or {}
print(res.get("stdout") or json.dumps(r, ensure_ascii=False)[:2500])

View File

@@ -0,0 +1,43 @@
"""列出内核发现的工具 + 试跑 probe_perm 看真实异常。"""
import json
import sys
import urllib.request
import urllib.error
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
def call(path, payload=None, method="POST", timeout=120):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", "replace")
return {"__http_error": e.code, "__body": body[:2000]}
tools = call("/api/tools", None, "GET")
py = tools.get("python") or tools.get("tools") or []
if isinstance(py, dict):
py = py.get("python") or []
names = sorted(t.get("name") for t in py if isinstance(t, dict))
print("内核发现的工具(%d 个):" % len(names))
print(" ", names)
print()
for probe in ("probe_perm", "probe_seed", "probe_loaded"):
print(f"{probe} 在列表里:", probe in names)
print()
print("=== 试跑 probe_perm ===")
r = call("/api/tools/run", {"name": "probe_perm", "args": {}})
print(json.dumps(r, ensure_ascii=False)[:2500])

View File

@@ -0,0 +1,71 @@
"""让设备上的内核自己报:它加载的 doubao_entry 是哪个文件、有没有新符号。"""
import json
import sys
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
def call(path, payload=None, method="POST", timeout=90):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
# ★ 用 python_run 跑不了(那是子进程,看不到内核进程里已加载的模块)。
# 所以用一个**临时工具**:内核会 import 它,它就能看到内核进程的 sys.modules。
probe_src = '''
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
TOOL = {"name": "probe_loaded", "description": "探内核加载了什么",
"parameters": {"type": "object", "properties": {}}}
def run(args):
out = {}
mod = sys.modules.get("doubao_entry")
out["doubao_entry_file"] = getattr(mod, "__file__", None) if mod else None
out["has_src_hash"] = hasattr(mod, "_src_hash") if mod else None
out["has_new_seed"] = None
if mod:
import inspect
try:
src = inspect.getsource(mod._seed_tools)
out["seed_src_len"] = len(src)
out["seed_has_fingerprint"] = "doubao-seed.json" in src
except Exception as e:
out["seed_src_error"] = f"{type(e).__name__}: {e}"
# 内嵌源码里 show_ui 有没有 wait
try:
import bundled_tool_sources
s = bundled_tool_sources.sources().get("show_ui.py", "")
out["bundled_show_ui_len"] = len(s)
out["bundled_show_ui_has_wait"] = "wait" in s
except Exception as e:
out["bundled_error"] = f"{type(e).__name__}: {e}"
return out
'''
# 写到可写工具目录里
import base64
b64 = base64.b64encode(probe_src.encode("utf-8")).decode()
write_js = (
"import base64,os;"
"d='/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools';"
"open(os.path.join(d,'probe_loaded.py'),'wb').write(base64.b64decode('%s'));"
"print('written')" % b64
)
r = call("/api/tools/run", {"name": "python_run", "args": {"code": write_js, "timeout": 30}}, timeout=90)
print("写探针:", (r.get("result") or {}).get("stdout", "").strip())
# 让内核重新发现工具再执行
r = call("/api/tools/run", {"name": "probe_loaded", "args": {}}, timeout=90)
print(json.dumps((r or {}).get("result"), ensure_ascii=False, indent=1))

111
scripts/probe-seed-trace.py Normal file
View File

@@ -0,0 +1,111 @@
"""在内核进程里逐行走一遍 _seed_tools 的逻辑,打印每个文件走哪个分支。
不猜了 —— 把中间量全打出来。
"""
import base64
import json
import sys
import time
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
probe_src = '''
import os, sys, json, traceback
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
TOOL = {"name": "probe_trace", "description": "x",
"parameters": {"type": "object", "properties": {}}}
def run(args):
D = %r
out = {}
try:
import doubao_entry as de
import bundled_tool_sources as bts
except Exception as e:
return {"import_err": f"{type(e).__name__}: {e}"}
out["has_src_hash"] = hasattr(de, "_src_hash")
if not out["has_src_hash"]:
return {"verdict": "内核里加载的是**旧** doubao_entry(没有 _src_hash)"}
srcs = bts.sources()
stamp_path = os.path.join(D, ".doubao-seed.json")
try:
seeded = json.load(open(stamp_path, encoding="utf-8"))
except Exception:
seeded = {}
out["seeded_keys"] = list(seeded.keys())[:5]
out["seeded_count"] = len(seeded)
rows = []
for filename in de.BUNDLED_TOOL_FILES:
source = srcs.get(filename)
dest = os.path.join(D, filename)
row = {"name": filename}
row["src_present"] = bool(source)
if not source:
row["branch"] = "no-source"
rows.append(row); continue
new_hash = de._src_hash(source)
row["new_hash"] = new_hash
if os.path.exists(dest):
current = open(dest, encoding="utf-8").read()
cur_hash = de._src_hash(current)
row["cur_hash"] = cur_hash
row["same"] = (cur_hash == new_hash)
row["seeded_for_it"] = seeded.get(filename)
row["seeded_matches"] = (seeded.get(filename) == cur_hash)
if cur_hash == new_hash:
row["branch"] = "skip-same"
elif seeded.get(filename) != cur_hash:
row["branch"] = "skip-user-edited"
else:
row["branch"] = "OVERWRITE"
else:
row["branch"] = "CREATE"
rows.append(row)
out["rows"] = rows
out["summary"] = {}
for r in rows:
out["summary"][r["branch"]] = out["summary"].get(r["branch"], 0) + 1
return out
''' % D
b64 = base64.b64encode(probe_src.encode("utf-8")).decode()
def call(path, payload=None, method="POST", timeout=120):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
w = (
"import base64,os;"
"open(os.path.join('%s','probe_trace.py'),'wb').write(base64.b64decode('%s'));"
"print('ok')" % (D, b64)
)
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
time.sleep(1)
call("/api/tools", None, "GET")
r = call("/api/tools/run", {"name": "probe_trace", "args": {}}, timeout=120)
res = (r or {}).get("result") or {}
data = res if isinstance(res, dict) and "rows" in res else json.loads(res.get("stdout") or "{}")
print("summary:", json.dumps(data.get("summary"), ensure_ascii=False))
print("has_src_hash:", data.get("has_src_hash"))
print("seeded_count:", data.get("seeded_count"), "keys:", data.get("seeded_keys"))
print()
for row in (data.get("rows") or []):
print(" ", row.get("name"), "->", row.get("branch"),
"| same=", row.get("same"), "| seeded_matches=", row.get("seeded_matches"))

74
scripts/probe-seed-why.py Normal file
View File

@@ -0,0 +1,74 @@
"""把内嵌源码列表 + BUNDLED_TOOL_FILES + 播种日志一起打出来。"""
import base64
import json
import sys
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
def call(path, payload=None, method="POST", timeout=90):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
probe = '''
import os, sys, json, traceback, inspect
D = %r
out = {}
# 1) 内核进程里 doubao_entry 的 BUNDLED_TOOL_FILES
mod = sys.modules.get("doubao_entry")
if mod:
out["BUNDLED_TOOL_FILES"] = list(getattr(mod, "BUNDLED_TOOL_FILES", []))
out["_module_source_show_ui"] = None
try:
s = mod._module_source("show_ui")
out["_module_source_show_ui"] = (len(s) if s else None)
except Exception as e:
out["_module_source_err"] = f"{type(e).__name__}: {e}"
# 2) 内嵌源码的键
try:
import bundled_tool_sources
srcs = bundled_tool_sources.sources()
out["bundled_keys"] = sorted(srcs.keys())
out["bundled_count"] = len(srcs)
except Exception as e:
out["bundled_err"] = f"{type(e).__name__}: {e}"
# 3) 手动调一次 _seed_tools 看它报什么
if mod:
try:
n = mod._seed_tools(D)
out["manual_seed_wrote"] = n
except Exception as e:
out["manual_seed_err"] = f"{type(e).__name__}: {e}"
out["manual_seed_tb"] = traceback.format_exc()[-800:]
print(json.dumps(out, ensure_ascii=False, indent=1))
'''
b64 = base64.b64encode(probe.encode("utf-8")).decode()
w = (
"import base64,os;"
"open(os.path.join('%s','probe_seed.py'),'wb').write(base64.b64decode('%s'));"
"print('ok')" % (D, b64)
)
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
# 让内核发现它(force 一下)
call("/api/tools", None, "GET")
r = call("/api/tools/run", {"name": "probe_seed", "args": {}}, timeout=120)
res = (r or {}).get("result") or {}
print(res.get("stdout") or json.dumps(r, ensure_ascii=False)[:1500])
if res.get("stderr"):
print("--- stderr ---")
print(res["stderr"][-1200:])

View File

@@ -0,0 +1,82 @@
"""测 show_ui 的三种收尾方式:不等 / 等 / 不弹。
★ 等待模式是**阻塞**的:脚本会挂在那儿等用户在手机上点。
所以它单独一个命令跑(另一个窗口截图 + 点按钮)。
"""
import json
import sys
import threading
import time
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
CONV = "c_main"
# 按钮故意写得很朴素(只靠骨架的 .db-btn 样式)——
# 就是要验证"模型不写样式时,按钮是不是也明显、也能点"。
HTML_PLAIN = """
<h1>挑一个</h1>
<p>下面这些是回传按钮,点了值会回到 AI 手里。</p>
<button data-doubao-result="方案甲">方案甲</button>
<button data-doubao-result="方案乙">方案乙</button>
<button onclick="Doubao.sendToAi('方案丙(JS)')">方案丙(JS)</button>
<button onclick="Doubao.close()">什么都不选,关掉</button>
"""
def call(path, payload=None, method="POST", timeout=300):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
def run_show(args, label, timeout=300):
print(f"\n--- {label} ---", flush=True)
print(" 参数:", json.dumps(args, ensure_ascii=False)[:120], flush=True)
t0 = time.time()
res = call("/api/tools/run", {
"name": "show_ui", "args": args, "conversationId": CONV,
}, timeout=timeout)
dt = time.time() - t0
print(f" 耗时 {dt:.1f}s -> {json.dumps(res, ensure_ascii=False)[:500]}", flush=True)
return res
which = sys.argv[1] if len(sys.argv) > 1 else "nowait"
call("/api/settings", {"uiTools": {"enabled": True}}, "PUT")
if which == "nowait":
# 不等:应该**立刻**返回(耗时接近 0)
res = run_show({"title": "不等待", "html": HTML_PLAIN}, "wait=false(默认)")
r = (res or {}).get("result") or {}
if r.get("shown") and not r.get("waited"):
print(" ✓ 立刻返回了(没等待)")
else:
print(" ✗ 行为不对:", r)
elif which == "wait":
# 等:会挂在这儿直到用户在手机上点,或 60 秒超时
res = run_show(
{"title": "等待中", "html": HTML_PLAIN, "wait": True, "timeout": 60},
"wait=true(等用户点,最多 60s)",
)
r = (res or {}).get("result") or {}
print()
if r.get("timeout"):
print(" → 超时了(用户没点)")
elif r.get("value"):
print(f" ✓ 用户点了:{r['value']!r}")
elif r.get("closed"):
print(" ✓ 用户直接关掉了(value 是空串)")
else:
print(" ✗ 结果不对:", r)

View File

@@ -0,0 +1,95 @@
"""直接测:那个工具目录到底能不能写、_seed_tools 报什么错。"""
import base64
import json
import sys
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
def call(path, payload=None, method="POST", timeout=90):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
probe = r'''
import os, sys, json, traceback
D = %r
out = {"dir": D}
out["isdir"] = os.path.isdir(D)
out["writable"] = os.access(D, os.W_OK)
# ① 直接写一个测试文件
try:
p = os.path.join(D, "_writetest.txt")
with open(p, "w", encoding="utf-8") as fh:
fh.write("hi")
out["direct_write"] = "ok"
os.remove(p)
except Exception as e:
out["direct_write"] = f"{type(e).__name__}: {e}"
# ② 内核认为的工具目录是哪个(paths)
try:
import paths
out["paths_tools_dir"] = paths.get().tools_dir
out["paths_work_dir"] = getattr(paths.get(), "work_dir", None)
out["paths_data_dir"] = paths.get().data_dir
except Exception as e:
out["paths_err"] = f"{type(e).__name__}: {e}"
# ③ 手动调 _seed_tools,把异常抓全
mod = sys.modules.get("doubao_entry")
if mod:
out["has_src_hash"] = hasattr(mod, "_src_hash")
try:
n = mod._seed_tools(D)
out["seed_wrote"] = n
except Exception as e:
out["seed_err"] = f"{type(e).__name__}: {e}"
out["seed_tb"] = traceback.format_exc()[-1200:]
# ④ 看看 wanted 里到底有几个
try:
import bundled_tool_sources
srcs = bundled_tool_sources.sources()
out["bundled_count"] = len(srcs)
out["bundled_names"] = sorted(srcs.keys())[:20]
wanted = {}
for name in mod.BUNDLED_TOOL_FILES:
wanted[name] = mod._module_source(name[:-3])
for k, v in srcs.items():
wanted[k] = v
out["wanted_nonempty"] = sum(1 for v in wanted.values() if v)
out["wanted_total"] = len(wanted)
except Exception as e:
out["wanted_err"] = f"{type(e).__name__}: {e}"
print(json.dumps(out, ensure_ascii=False, indent=1))
''' % D
b64 = base64.b64encode(probe.encode("utf-8")).decode()
w = (
"import base64,os;"
"open(os.path.join('%s','probe_perm.py'),'wb').write(base64.b64decode('%s'));"
"print('ok')" % (D, b64)
)
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
try:
r = call("/api/tools/run", {"name": "probe_perm", "args": {}}, timeout=120)
except Exception as exc: # noqa: BLE001
print("调用 probe_perm 失败:", exc)
sys.exit(1)
res = (r or {}).get("result") or {}
print(res.get("stdout") or json.dumps(r, ensure_ascii=False)[:2000])
if res.get("stderr"):
print("--- stderr ---")
print(res["stderr"][-1500:])

View File

@@ -0,0 +1,227 @@
"""守"内置工具升级时会重新播种"这条性质。
## 为什么值得单独守
这里踩过一个**表现极具误导性**的真 bug:
`_seed_tools` 以前是 `if os.path.exists(dest): continue` —— 只写不存在的文件。
后果:**每一次发版更新的内置工具,在老设备上一律不生效。**
误导在哪:代码改了、APK 重新编了、`app.imy` 里确实有新 .pyc,
但设备上跑的还是旧那份 —— 因为内核加载的是**落盘的那份旧源码**。
(v2.0.37 给 show_ui 加了 `wait` 参数,设备上报的 spec 里根本没这个参数,
我一度以为是构建缓存没生效,查了一圈才发现是这个。)
所以这条性质必须钉住:**改了内容要覆盖,用户改过的不许覆盖。**
## 测试手法
`_seed_tools` 的源码来源是 `bundled_tool_sources`(构建时生成的)。
电脑上没有那个文件,所以这里**塞一个假模块**进 `sys.modules` ——
比给源码打补丁干净,而且测的就是真实那条路径。
用法:
python scripts/verify-seed-tools.py
"""
import base64
import importlib.util
import json
import os
import shutil
import sys
import tempfile
import types
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
KERNEL = os.path.join(WS, "android", "kernel")
fails = []
def fail(m):
fails.append(m)
print(f" ✗ {m}")
def ok(m):
print(f" ✓ {m}")
def install_fake_bundled(files: dict, shipped: dict = None) -> None:
"""
往 sys.modules 里塞一个假的 bundled_tool_sources。
★ 必须走模块这一层:`_seed_tools` 第二个来源是 `_module_source()`(读模块源码),
在电脑上对 android/kernel 里的模块有效、对我们造的假工具无效。
塞模块能同时喂到**两个来源**,测的就是设备上真实走的那条。
[shipped] 模拟"我们历史上发过的所有哈希"(tools/.shipped-hashes.json
在构建时嵌进来的那份)。**这一条是修老设备升级问题的关键**,所以
下面专门有一节测它。
"""
mod = types.ModuleType("bundled_tool_sources")
def sources():
return {
name: base64.b64decode(data).decode("utf-8")
for name, data in files.items()
}
def shipped_fn():
return {k: list(v) for k, v in (shipped or {}).items()}
mod.sources = sources
mod.shipped = shipped_fn
sys.modules["bundled_tool_sources"] = mod
def load_entry():
sys.path.insert(0, KERNEL)
spec = importlib.util.spec_from_file_location("dbe", os.path.join(KERNEL, "doubao_entry.py"))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
V1 = "TOOL = {'name': 'demo'}\n# 第一版\n"
V2 = "TOOL = {'name': 'demo'}\n# 第二版(修了 bug)\n"
V3 = "TOOL = {'name': 'demo'}\n# 第三版\n"
def b64(s):
return base64.b64encode(s.encode("utf-8")).decode()
print("=== 内置工具播种的硬性质 ===")
install_fake_bundled({"demo.py": b64(V1)})
dbe = load_entry()
tmp = tempfile.mkdtemp(prefix="seedtest-")
stamp = os.path.join(tmp, ".doubao-seed.json")
path = os.path.join(tmp, "demo.py")
try:
# ---------------------------------------------------------------- 1
print("\n[1] 首次运行:写出来 + 留指纹")
n = seed_n = dbe._seed_tools(tmp)
exists = os.path.isfile(path)
has_stamp = os.path.isfile(stamp)
if n == 1 and exists and has_stamp:
ok("写了 demo.py,也留了 .doubao-seed.json")
else:
fail(f"首次运行不对:n={n} 文件={exists} 指纹={has_stamp}")
if open(path, encoding="utf-8").read() == V1:
ok("内容是内置的那份")
else:
fail("内容不对")
# ---------------------------------------------------------------- 2
print("\n[2] 再跑一次:内容没变就什么都不做(别每次动 mtime)")
mt = os.stat(path).st_mtime_ns
n = dbe._seed_tools(tmp)
if n == 0 and os.stat(path).st_mtime_ns == mt:
ok("空操作,mtime 没动")
else:
fail(f"第二次动了东西:n={n} mtime变了={os.stat(path).st_mtime_ns != mt}")
# ---------------------------------------------------------------- 3
print("\n[3] ★ 我们发了新版本 → 必须覆盖(就是这么坏的)")
install_fake_bundled({"demo.py": b64(V2)})
dbe = load_entry() # 重新加载,让它拿到新的 bundled 源码
n = dbe._seed_tools(tmp)
content = open(path, encoding="utf-8").read()
if n == 1 and content == V2:
ok("旧版被覆盖成新版了(老设备现在能拿到更新)")
else:
fail(f"没覆盖:n={n},内容正确={content == V2}")
# ---------------------------------------------------------------- 4
print("\n[4] ★ 用户自己改过 → 绝对不许覆盖")
user_edit = V2 + "# 这是用户自己加的\n"
open(path, "w", encoding="utf-8").write(user_edit)
# 关键:**不动指纹文件** —— 于是"盘上内容 ≠ 我们上次写的" = 用户改过
install_fake_bundled({"demo.py": b64(V3)})
dbe = load_entry()
n = dbe._seed_tools(tmp)
content = open(path, encoding="utf-8").read()
if n == 0 and content == user_edit:
ok("用户改过的被保留了(用户的改动比'用上新版'重要)")
else:
fail(f"把用户改过的覆盖了:n={n},内容还在={'这是用户自己加的' in content}")
# ---------------------------------------------------------------- 5
print("\n[5] 指纹文件坏了也不能崩、也不能乱覆盖")
open(stamp, "w", encoding="utf-8").write("{ 这不是 json")
n = dbe._seed_tools(tmp)
content = open(path, encoding="utf-8").read()
if content == user_edit:
ok("坏指纹当成'用户改过'处理 —— 保守,不覆盖(没崩)")
else:
fail("坏指纹时把用户的文件覆盖了")
# ---------------------------------------------------------------- 6
print("\n[6] 用户删掉文件 → 补回来")
os.remove(path)
install_fake_bundled({"demo.py": b64(V3)})
dbe = load_entry()
n = dbe._seed_tools(tmp)
if n == 1 and os.path.isfile(path) and open(path, encoding="utf-8").read() == V3:
ok("删掉的内置工具被补回来了")
else:
fail(f"没补回来:n={n}")
# ---------------------------------------------------------------- 7
print("\n[7] ★★★ 老设备:指纹文件是空的,但盘上是我们以前发的旧版本")
#
# 这是**真机上真实出现的场景**,也是第一版修复没修好的地方:
# · 设备上装的是几个月前那版工具(旧源码)
# · .doubao-seed.json 是空的(第一版播种逻辑从没写过它)
# 只靠指纹判断的话,这份旧源码会被当成"用户改过" → **升级永远不生效**。
# (实测 v2.0.37 给 show_ui 加了 wait 参数,真机上报的 spec 里就是没有。)
#
# 修法:构建时累积"我们历史上发过哪些哈希",靠它认出旧版本。
fresh = tempfile.mkdtemp(prefix="seedtest2-")
try:
fresh_path = os.path.join(fresh, "demo.py")
# 盘上是 V1(我们以前发的),指纹文件**不存在**
open(fresh_path, "w", encoding="utf-8").write(V1)
h1 = dbe._src_hash(V1)
install_fake_bundled({"demo.py": b64(V3)}, shipped={"demo.py": [h1]})
dbe = load_entry()
n = dbe._seed_tools(fresh)
content = open(fresh_path, encoding="utf-8").read()
if n == 1 and content == V3:
ok("靠历史哈希表认出了旧版本并覆盖(老设备能拿到更新了)")
else:
fail(f"旧版本没被覆盖:n={n} 内容正确={content == V3}")
# 8. 反过来:盘上的内容**不在**历史表里 → 一定是用户改的 → 不覆盖
print("\n[8] ★ 盘上内容不在历史表里 → 判为用户改过 → 不覆盖")
open(fresh_path, "w", encoding="utf-8").write(V1 + "# 用户手改的\n")
n = dbe._seed_tools(fresh)
content = open(fresh_path, encoding="utf-8").read()
if n == 0 and "用户手改的" in content:
ok("不在历史表里的改动被保留了")
else:
fail(f"把用户改的覆盖了:n={n}")
finally:
shutil.rmtree(fresh, ignore_errors=True)
finally:
shutil.rmtree(tmp, ignore_errors=True)
sys.modules.pop("bundled_tool_sources", None)
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for m in fails:
print(" -", m)
sys.exit(1)
print("✅ 全部通过")