diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 304a484..6fe602d 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 237 - versionName = "2.0.37" + versionCode = 238 + versionName = "2.0.38" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt index ebd0d39..066f18c 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt @@ -124,18 +124,29 @@ class NativeBridge(private val activity: Activity) { /** * AI 弹一个 HTML 界面(tools/show_ui.py)。 * - * **不阻塞**:弹出来就返回,用户看完自己关。理由见 [AiSurface.showScreen]。 + * [wait] 由工具参数决定: + * · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关 + * · true ——**等用户操作**:点了回传按钮或关掉界面才返回, + * 用户点的值原样带回给模型 + * + * ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话, + * 用户手快先点了(界面已经显示、按钮就在那儿), + * `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。 + * 这类"用户比代码快"的竞态在真机上很容易出现。 */ private fun uiScreen(req: JSONObject): JSONObject { val html = req.optString("html") if (html.isBlank()) return JSONObject().put("error", "html 是空的") - val s = AiSurface.showScreen( + val wait = req.optBoolean("wait", false) + if (wait) AiSurface.armScreenLatch() + return AiSurface.showScreen( html = html, title = req.optString("title"), fullHtml = req.optBoolean("full_html", false), conversationId = req.optString("conversationId"), + wait = wait, + timeoutMs = req.optLong("timeoutMs", 120_000L), ) - return JSONObject().put("ok", true).put("id", s.id) } /** diff --git a/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt b/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt index ce8aff2..cce9723 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt @@ -6,7 +6,6 @@ import org.json.JSONObject import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong - /** * ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。 * @@ -58,6 +57,8 @@ object AiSurface { val title: String, val fullHtml: Boolean, val conversationId: String, + /** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */ + val waiting: Boolean = false, ) data class Option(val label: String, val value: String, val description: String) @@ -90,25 +91,92 @@ object AiSurface { // ------------------------------------------------------------------ 界面 /** - * 弹一个 HTML 界面。**不阻塞** —— 弹出来就返回,用户看完自己关。 + * 弹一个 HTML 界面。 * - * ★ 为什么不做成阻塞:`show_ui` 是"展示"语义,用户可能盯着看很久, - * 把内核线程占住没有意义(而且模型这时也没别的事可做,但万一它想 - * 连续弹两个界面就会被卡死)。要阻塞的语义用 [ask]。 + * [wait] = false(默认):**不阻塞** —— 弹出来就返回。 + * [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。 + * + * ★ 为什么要两种: + * 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。 + * 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。 + * 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。 + * + * ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile` + * 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**, + * 不碰 UI 线程。 + * + * ★ 超时必须有:用户可能锁屏走了。不设的话内核工作线程永远挂着, + * 而 HTTP 是每请求一线程,挂一个少一个。 */ - fun showScreen(html: String, title: String, fullHtml: Boolean, conversationId: String): Screen { - val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId) + fun showScreen( + html: String, + title: String, + fullHtml: Boolean, + conversationId: String, + wait: Boolean = false, + timeoutMs: Long = 120_000L, + ): JSONObject { + val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId, waiting = wait) screen = s + screenClosed = false + screenAnswer = null notify("screen") - Log.i(TAG, "AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}") - return s + Log.i( + TAG, + "AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," + + if (wait) "等用户操作(最多 ${timeoutMs / 1000}s)" else "不等待", + ) + + if (!wait) { + return JSONObject().put("shown", true).put("bytes", html.length) + } + + // ---- 等待模式 ---- + val latch = screenLatch + val answered = latch?.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS) ?: false + val answer = screenAnswer + val closed = screenClosed + screenLatch = null + + // 等到答案(或超时)之后把界面收掉 —— 否则用户看到一个已经"用完了" + // 的界面还开着,会以为还能再点。 + if (answered) { + screen = null + notify("screen") + } + + return JSONObject() + .put("shown", true) + .put("bytes", html.length) + .put("waited", true) + .put("timeout", !answered) + .put("closed", closed) + // 用户点的值。超时/直接关掉时是空串。 + .put("value", answer ?: "") } - /** 用户在界面上点了带 `data-doubao-result` 的按钮(WebView 的 JS 桥转进来) */ + /** 等用户交互用的闩。非等待模式下是 null。 */ + @Volatile + private var screenLatch: CountDownLatch? = null + + @Volatile + private var screenAnswer: String? = null + + @Volatile + private var screenClosed: Boolean = false + + /** + * 用户在界面上点了回传按钮(`Doubao.sendToAi` / `data-doubao-result`)。 + * + * ★ 等待模式下这一下就是"用户答完了"的信号:记下值、放行。 + * 界面侧收到后会把自己收掉。 + */ fun screenResult(value: String) { Log.i(TAG, "界面里点了:$value") - // 界面上的点击不阻塞任何人,所以只通知一下、让界面记一笔 lastScreenResult = value + screenAnswer = value + screenClosed = false + screenLatch?.countDown() notify("screenResult") } @@ -119,9 +187,19 @@ object AiSurface { /** 用户把界面关掉了 */ fun closeScreen() { screen = null + // 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串 + screenClosed = true + screenLatch?.countDown() notify("screen") } + /** 进等待模式前由 NativeBridge 调一次,准备闩 */ + fun armScreenLatch() { + screenLatch = CountDownLatch(1) + screenAnswer = null + screenClosed = false + } + // ------------------------------------------------------------------ 弹窗 /** diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt index f91d131..d8746b4 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt @@ -83,7 +83,13 @@ import com.doubao.lynxclone.termux.AiSurface /* ==================================================================== */ @Composable -fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult: (String) -> Unit) { +fun AiHtmlScreenOverlay( + screen: AiSurface.Screen?, + onClose: () -> Unit, + onResult: (String) -> Unit, + /** 等待模式:用户点了回传按钮之后自动把界面收掉(这是"用户答完了"的信号) */ + autoCloseOnResult: Boolean = false, +) { // 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧", // 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。 var last by remember { mutableStateOf(null) } @@ -160,7 +166,17 @@ fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp)) } } - AiWebView(shown, onResult, onClose, onWebView = { web = it }) + AiWebView( + screen = shown, + onResult = { value -> + onResult(value) + // ★ 等待模式下这一下就是"用户答完了" —— 把界面收掉, + // 否则用户看到一个已经用完的界面还开着,会以为还能再点。 + if (autoCloseOnResult) onClose() + }, + onClose = onClose, + onWebView = { web = it }, + ) } } } @@ -502,10 +518,52 @@ private fun wrapSkeleton(fragment: String): String = """ } img, svg, canvas { max-width: 100%; height: auto; } hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; } - .db-btn { - display: inline-block; margin: 6px 8px 0 0; padding: 10px 16px; - background: #2a2d34; color: #e8eaed !important; text-decoration: none; - border-radius: 10px; font-size: 15px; + + /* ★★ 按钮 —— 这里刻意做得**非常显眼**。 + * + * 起因:有用户反馈"哪有按键,网页里的按键也点不了"。 + * 原因之一是模型把按钮写成了纯文字、或者用了暗底暗字, + * 在深色主题下跟普通段落长得一模一样,用户根本看不出那儿能点。 + * + * 所以这一版把回传按钮做成:大号、实心、亮底深字、整行宽、有按下的反馈。 + * 同时提示词里也明确要求模型"把按钮做得明显"。 + * (注意 !important:模型经常内联 style="background:..." 把它盖掉。) */ + .db-btn, [data-doubao-result] { + display: block !important; + width: 100% !important; + margin: 10px 0 !important; + padding: 15px 18px !important; + background: #2b7bff !important; + color: #ffffff !important; + text-decoration: none !important; + text-align: center !important; + border: 0 !important; + border-radius: 12px !important; + font-size: 16px !important; + font-weight: 500 !important; + line-height: 1.4 !important; + cursor: pointer !important; + -webkit-appearance: none; + appearance: none; + } + .db-btn:active, [data-doubao-result]:active { + background: #1e63d6 !important; + transform: scale(0.985); + } + /* 两个按钮并排时用这个包一层 */ + .db-row { display: flex; gap: 10px; } + .db-row > * { flex: 1; } + + /* 普通按钮(模型自己写的、没标 data-doubao-result 的)也给个像样的默认样式, + 但不像回传按钮那么抢眼 —— 免得满屏都是蓝块 */ + button:not([data-doubao-result]) { + padding: 12px 16px; + border: 1px solid #3d4450; + border-radius: 10px; + background: #232830; + color: #e8eaed; + font-size: 15px; + cursor: pointer; } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index 366d540..0d62cb7 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -128,7 +128,8 @@ fun AppRoot( AiHtmlScreenOverlay( screen = vm.aiScreen, onClose = { vm.closeAiScreen() }, - onResult = { vm.onAiScreenResult(it) }, + onResult = { vm.onAiScreenResult(it, vm.aiScreen?.waiting == true) }, + autoCloseOnResult = vm.aiScreen?.waiting == true, ) AiDialogOverlay( dialog = vm.aiDialog, diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index d1f61ec..1c9c974 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -148,20 +148,27 @@ class AppViewModel(val client: KernelClient) : ViewModel() { /** * ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。 * - * 过程: - * 页面上 `Doubao.sendToAi('值')`(或点了 `data-doubao-result` 按钮) - * → [AiSurface.screenResult] 记一笔 - * → 这里 POST 到内核 `/api/ui-result` 排队 - * → **下一轮对话**时 agent_loop 取走、作为上下文交给模型 + * 两条路,按界面是不是"等待模式"分流: * - * ★ 为什么用队列而不是"立刻起一轮对话": - * 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型又慢又费 token, - * 而且用户还没说完。排队 → 他下次说话时一起带上。 - * 所以提示语也要**如实**说"已记下、下次对话会带上", - * 不能写"已发送" —— 那会让用户以为模型马上会回话,然后干等。 + * · **等待模式**(`show_ui` 传了 `wait=true`): + * 这个值直接作为工具的返回值交给模型 —— 模型**在同一个回合里**就拿到了, + * 可以接着干活。所以这里不用再排队(排了反而会让模型看到重复信息)。 + * + * · **不等待模式**(默认): + * 模型这一轮已经答完了,所以值先排队(`/api/ui-result`), + * 等用户下次说话时和那句话一起交给模型。 + * + * ★ 提示语要**如实**区分这两种情况: + * 等待模式说"已提交"(模型确实马上会用); + * 不等待模式说"已记下,下次对话会告诉 AI" —— + * 写成"已发送"会让用户以为模型马上回话,然后干等。 */ - fun onAiScreenResult(value: String) { + fun onAiScreenResult(value: String, waiting: Boolean = false) { AiSurface.screenResult(value) + if (waiting) { + showHint("已提交:$value") + return + } val conv = activeConversationId if (conv.isBlank()) { showHint("已选择:$value") diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py index dfa34aa..a38ec2a 100644 --- a/android/kernel/agent_loop.py +++ b/android/kernel/agent_loop.py @@ -59,8 +59,14 @@ UI_TOOLS_HINT = '\n'.join([ ' ★★ 用户在界面上的选择**会回到你手里**:页面里调', ' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放', ' ` + + + +""" + + +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) diff --git a/scripts/probe-tools-writable.py b/scripts/probe-tools-writable.py new file mode 100644 index 0000000..42aaad2 --- /dev/null +++ b/scripts/probe-tools-writable.py @@ -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:]) diff --git a/scripts/verify-seed-tools.py b/scripts/verify-seed-tools.py new file mode 100644 index 0000000..1d8ceba --- /dev/null +++ b/scripts/verify-seed-tools.py @@ -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("✅ 全部通过") diff --git a/tools/.shipped-hashes.json b/tools/.shipped-hashes.json new file mode 100644 index 0000000..eedef76 --- /dev/null +++ b/tools/.shipped-hashes.json @@ -0,0 +1,47 @@ +{ + "_mcp_python_example.py": [ + "74a279c17b1af512" + ], + "_protocol.py": [ + "e289048324c38899" + ], + "_ui_bridge.py": [ + "048c7685991715fb" + ], + "ask_user.py": [ + "94a9734c8c934db2" + ], + "calc.py": [ + "4d9e5a51ad8f71eb" + ], + "end_conversation.py": [ + "b03b5b99dbd83587" + ], + "notes.py": [ + "f2255c693b2401b5" + ], + "now.py": [ + "eb0c37b5afc1dd8b" + ], + "python_run.py": [ + "ca82671140ada806" + ], + "shell.py": [ + "932c45a5881ba59c" + ], + "show_ui.py": [ + "1882a766fe0ee833", + "6f3ce8a4c924dfdd", + "ecea108ef1118386", + "f80e4da69db41722" + ], + "weather.py": [ + "bff69719c190d3d9" + ], + "web_fetch.py": [ + "7aaf278c29b1429a" + ], + "web_search.py": [ + "3f999cc4ccbc64a9" + ] +} diff --git a/tools/show_ui.py b/tools/show_ui.py index 27c307b..8ca91ed 100644 --- a/tools/show_ui.py +++ b/tools/show_ui.py @@ -38,16 +38,30 @@ TOOL = { "\n· html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);" "想完全控制就传 full_html=true。" "\n· **可以用