Files
doubao-clone/scripts/probe-tools-writable.py
doubao ba429e67cd ★ 修一个让所有工具更新都失效的 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 拿到用户点的值 ✓
2026-10-15 11:31:00 +08:00

96 lines
3.1 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.

"""直接测:那个工具目录到底能不能写、_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:])