★ 修一个让所有工具更新都失效的 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:
@@ -30,8 +30,8 @@ android {
|
|||||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||||
* 改小了会装不上)。
|
* 改小了会装不上)。
|
||||||
*/
|
*/
|
||||||
versionCode = 237
|
versionCode = 238
|
||||||
versionName = "2.0.37"
|
versionName = "2.0.38"
|
||||||
|
|
||||||
ndk {
|
ndk {
|
||||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||||
|
|||||||
@@ -124,18 +124,29 @@ class NativeBridge(private val activity: Activity) {
|
|||||||
/**
|
/**
|
||||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||||
*
|
*
|
||||||
* **不阻塞**:弹出来就返回,用户看完自己关。理由见 [AiSurface.showScreen]。
|
* [wait] 由工具参数决定:
|
||||||
|
* · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关
|
||||||
|
* · true ——**等用户操作**:点了回传按钮或关掉界面才返回,
|
||||||
|
* 用户点的值原样带回给模型
|
||||||
|
*
|
||||||
|
* ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话,
|
||||||
|
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||||
|
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||||
|
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||||
*/
|
*/
|
||||||
private fun uiScreen(req: JSONObject): JSONObject {
|
private fun uiScreen(req: JSONObject): JSONObject {
|
||||||
val html = req.optString("html")
|
val html = req.optString("html")
|
||||||
if (html.isBlank()) return JSONObject().put("error", "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,
|
html = html,
|
||||||
title = req.optString("title"),
|
title = req.optString("title"),
|
||||||
fullHtml = req.optBoolean("full_html", false),
|
fullHtml = req.optBoolean("full_html", false),
|
||||||
conversationId = req.optString("conversationId"),
|
conversationId = req.optString("conversationId"),
|
||||||
|
wait = wait,
|
||||||
|
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||||
)
|
)
|
||||||
return JSONObject().put("ok", true).put("id", s.id)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import org.json.JSONObject
|
|||||||
import java.util.concurrent.CountDownLatch
|
import java.util.concurrent.CountDownLatch
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import java.util.concurrent.atomic.AtomicLong
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||||
*
|
*
|
||||||
@@ -58,6 +57,8 @@ object AiSurface {
|
|||||||
val title: String,
|
val title: String,
|
||||||
val fullHtml: Boolean,
|
val fullHtml: Boolean,
|
||||||
val conversationId: String,
|
val conversationId: String,
|
||||||
|
/** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */
|
||||||
|
val waiting: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class Option(val label: String, val value: String, val description: String)
|
data class Option(val label: String, val value: String, val description: String)
|
||||||
@@ -90,25 +91,92 @@ object AiSurface {
|
|||||||
// ------------------------------------------------------------------ 界面
|
// ------------------------------------------------------------------ 界面
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 弹一个 HTML 界面。**不阻塞** —— 弹出来就返回,用户看完自己关。
|
* 弹一个 HTML 界面。
|
||||||
*
|
*
|
||||||
* ★ 为什么不做成阻塞:`show_ui` 是"展示"语义,用户可能盯着看很久,
|
* [wait] = false(默认):**不阻塞** —— 弹出来就返回。
|
||||||
* 把内核线程占住没有意义(而且模型这时也没别的事可做,但万一它想
|
* [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。
|
||||||
* 连续弹两个界面就会被卡死)。要阻塞的语义用 [ask]。
|
*
|
||||||
|
* ★ 为什么要两种:
|
||||||
|
* 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。
|
||||||
|
* 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。
|
||||||
|
* 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。
|
||||||
|
*
|
||||||
|
* ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile`
|
||||||
|
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||||
|
* 不碰 UI 线程。
|
||||||
|
*
|
||||||
|
* ★ 超时必须有:用户可能锁屏走了。不设的话内核工作线程永远挂着,
|
||||||
|
* 而 HTTP 是每请求一线程,挂一个少一个。
|
||||||
*/
|
*/
|
||||||
fun showScreen(html: String, title: String, fullHtml: Boolean, conversationId: String): Screen {
|
fun showScreen(
|
||||||
val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId)
|
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
|
screen = s
|
||||||
|
screenClosed = false
|
||||||
|
screenAnswer = null
|
||||||
notify("screen")
|
notify("screen")
|
||||||
Log.i(TAG, "AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}")
|
Log.i(
|
||||||
return s
|
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) {
|
fun screenResult(value: String) {
|
||||||
Log.i(TAG, "界面里点了:$value")
|
Log.i(TAG, "界面里点了:$value")
|
||||||
// 界面上的点击不阻塞任何人,所以只通知一下、让界面记一笔
|
|
||||||
lastScreenResult = value
|
lastScreenResult = value
|
||||||
|
screenAnswer = value
|
||||||
|
screenClosed = false
|
||||||
|
screenLatch?.countDown()
|
||||||
notify("screenResult")
|
notify("screenResult")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,9 +187,19 @@ object AiSurface {
|
|||||||
/** 用户把界面关掉了 */
|
/** 用户把界面关掉了 */
|
||||||
fun closeScreen() {
|
fun closeScreen() {
|
||||||
screen = null
|
screen = null
|
||||||
|
// 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串
|
||||||
|
screenClosed = true
|
||||||
|
screenLatch?.countDown()
|
||||||
notify("screen")
|
notify("screen")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 进等待模式前由 NativeBridge 调一次,准备闩 */
|
||||||
|
fun armScreenLatch() {
|
||||||
|
screenLatch = CountDownLatch(1)
|
||||||
|
screenAnswer = null
|
||||||
|
screenClosed = false
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ 弹窗
|
// ------------------------------------------------------------------ 弹窗
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -83,7 +83,13 @@ import com.doubao.lynxclone.termux.AiSurface
|
|||||||
/* ==================================================================== */
|
/* ==================================================================== */
|
||||||
|
|
||||||
@Composable
|
@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,但退出动画需要内容 —— 所以留一份"最后一帧",
|
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||||
@@ -160,7 +166,17 @@ fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult
|
|||||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
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; }
|
img, svg, canvas { max-width: 100%; height: auto; }
|
||||||
hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; }
|
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;
|
||||||
}
|
}
|
||||||
</style></head>
|
</style></head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -128,7 +128,8 @@ fun AppRoot(
|
|||||||
AiHtmlScreenOverlay(
|
AiHtmlScreenOverlay(
|
||||||
screen = vm.aiScreen,
|
screen = vm.aiScreen,
|
||||||
onClose = { vm.closeAiScreen() },
|
onClose = { vm.closeAiScreen() },
|
||||||
onResult = { vm.onAiScreenResult(it) },
|
onResult = { vm.onAiScreenResult(it, vm.aiScreen?.waiting == true) },
|
||||||
|
autoCloseOnResult = vm.aiScreen?.waiting == true,
|
||||||
)
|
)
|
||||||
AiDialogOverlay(
|
AiDialogOverlay(
|
||||||
dialog = vm.aiDialog,
|
dialog = vm.aiDialog,
|
||||||
|
|||||||
@@ -148,20 +148,27 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
/**
|
/**
|
||||||
* ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。
|
* ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。
|
||||||
*
|
*
|
||||||
* 过程:
|
* 两条路,按界面是不是"等待模式"分流:
|
||||||
* 页面上 `Doubao.sendToAi('值')`(或点了 `data-doubao-result` 按钮)
|
|
||||||
* → [AiSurface.screenResult] 记一笔
|
|
||||||
* → 这里 POST 到内核 `/api/ui-result` 排队
|
|
||||||
* → **下一轮对话**时 agent_loop 取走、作为上下文交给模型
|
|
||||||
*
|
*
|
||||||
* ★ 为什么用队列而不是"立刻起一轮对话":
|
* · **等待模式**(`show_ui` 传了 `wait=true`):
|
||||||
* 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型又慢又费 token,
|
* 这个值直接作为工具的返回值交给模型 —— 模型**在同一个回合里**就拿到了,
|
||||||
* 而且用户还没说完。排队 → 他下次说话时一起带上。
|
* 可以接着干活。所以这里不用再排队(排了反而会让模型看到重复信息)。
|
||||||
* 所以提示语也要**如实**说"已记下、下次对话会带上",
|
*
|
||||||
* 不能写"已发送" —— 那会让用户以为模型马上会回话,然后干等。
|
* · **不等待模式**(默认):
|
||||||
|
* 模型这一轮已经答完了,所以值先排队(`/api/ui-result`),
|
||||||
|
* 等用户下次说话时和那句话一起交给模型。
|
||||||
|
*
|
||||||
|
* ★ 提示语要**如实**区分这两种情况:
|
||||||
|
* 等待模式说"已提交"(模型确实马上会用);
|
||||||
|
* 不等待模式说"已记下,下次对话会告诉 AI" ——
|
||||||
|
* 写成"已发送"会让用户以为模型马上回话,然后干等。
|
||||||
*/
|
*/
|
||||||
fun onAiScreenResult(value: String) {
|
fun onAiScreenResult(value: String, waiting: Boolean = false) {
|
||||||
AiSurface.screenResult(value)
|
AiSurface.screenResult(value)
|
||||||
|
if (waiting) {
|
||||||
|
showHint("已提交:$value")
|
||||||
|
return
|
||||||
|
}
|
||||||
val conv = activeConversationId
|
val conv = activeConversationId
|
||||||
if (conv.isBlank()) {
|
if (conv.isBlank()) {
|
||||||
showHint("已选择:$value")
|
showHint("已选择:$value")
|
||||||
|
|||||||
@@ -59,8 +59,14 @@ UI_TOOLS_HINT = '\n'.join([
|
|||||||
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
||||||
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
||||||
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
||||||
' 注意:送回的值**在你下一轮对话时才看到**(它们排队等用户那句话一起给你),',
|
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||||||
' 所以别在同一个回合里等 —— 想让用户选完立刻有回应,用 ask_user(阻塞式)。',
|
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||||||
|
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||||||
|
' · wait=true = **等用户点一个回传按钮或关掉界面**(最多 timeout 秒,默认 120)。',
|
||||||
|
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||||
|
' 适合"弹几个选项让用户挑,然后我继续"。',
|
||||||
|
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||||
|
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||||
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
import importlib.util
|
import importlib.util
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -263,37 +264,130 @@ def _module_source(name: str):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _src_hash(text: str) -> str:
|
||||||
|
"""源码指纹前 16 位(够用,还短)"""
|
||||||
|
return hashlib.sha256(text.encode('utf-8')).hexdigest()[:16]
|
||||||
|
|
||||||
|
|
||||||
def _seed_tools(tools_dir: str) -> int:
|
def _seed_tools(tools_dir: str) -> int:
|
||||||
"""
|
"""
|
||||||
首次运行把内置工具写到手机上的可写目录。
|
把内置工具写到手机上的可写目录。之后用户就能自己改、自己加
|
||||||
之后用户就能自己改、自己加(设置里的"工具目录"指向这里)。
|
(设置里的"工具目录"指向这里)。
|
||||||
|
|
||||||
源码来源优先级:
|
源码来源优先级:
|
||||||
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||||||
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||||||
2) 直接从模块读源码 —— 电脑上跑时用这条
|
2) 直接从模块读源码 —— 电脑上跑时用这条
|
||||||
|
|
||||||
|
## ★★★ 升级时会重新播种(这是修的一个真 bug)
|
||||||
|
|
||||||
|
以前这里是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
|
||||||
|
后果:**每一次发版更新的内置工具,在老设备上一律不生效**。
|
||||||
|
|
||||||
|
这个 bug 的表现极具误导性:代码明明改了、APK 明明是新编的、
|
||||||
|
`app.imy` 里也确实有新的 .pyc,但设备上跑的还是几个月前那份 ——
|
||||||
|
因为内核加载的是**落盘的那份旧源码**。
|
||||||
|
实测踩到:v2.0.37 加了 `show_ui` 的 `wait` 参数,设备上报的 spec 里
|
||||||
|
根本没有这个参数,我一度以为是构建没生效。
|
||||||
|
|
||||||
|
## 怎么判断该不该覆盖 —— 这是这一版真正修对的地方
|
||||||
|
|
||||||
|
先看第一版(错的):只看一个本地指纹文件 `.doubao-seed.json`。
|
||||||
|
|
||||||
|
· 指纹对得上 → 我们写的 → 可以覆盖
|
||||||
|
· 对不上 → 用户改过 → 不覆盖
|
||||||
|
|
||||||
|
**但老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
|
||||||
|
于是所有文件都被判成"用户改过",**升级永远不生效**。
|
||||||
|
实测 v2.0.37 给 show_ui 加了 `wait` 参数,真机上死活拿不到 ——
|
||||||
|
12 个没改过的文件"内容相同"跳过,唯一改过的 show_ui 被判成用户改的。
|
||||||
|
|
||||||
|
第二版(现在):加一份**构建时累积的"历史版本哈希登记表"**
|
||||||
|
(`tools/.shipped-hashes.json`,打包时嵌进 `bundled_tool_sources.shipped()`)。
|
||||||
|
判断顺序:
|
||||||
|
|
||||||
|
1. 内容和我们这一版一样 → 什么都不做
|
||||||
|
2. 内容**在历史登记表里** → 是我们以前发的某个版本 → **安全覆盖**
|
||||||
|
3. 内容等于我们本地指纹记的 → 是我们写的 → **安全覆盖**
|
||||||
|
4. 都不是 → 用户改过 → **绝不覆盖**
|
||||||
|
|
||||||
|
第 2 条是关键:它让"老设备上那份我们几个月前发的旧源码"能被认出来。
|
||||||
|
没有它就只能靠"指纹文件",而老设备上那个是空的。
|
||||||
"""
|
"""
|
||||||
os.makedirs(tools_dir, exist_ok=True)
|
os.makedirs(tools_dir, exist_ok=True)
|
||||||
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||||||
|
|
||||||
|
shipped: dict = {}
|
||||||
try:
|
try:
|
||||||
import bundled_tool_sources # type: ignore[import-not-found]
|
import bundled_tool_sources # type: ignore[import-not-found]
|
||||||
|
|
||||||
for name, source in bundled_tool_sources.sources().items():
|
for name, source in bundled_tool_sources.sources().items():
|
||||||
wanted[name] = source
|
wanted[name] = source
|
||||||
|
# ★ 历史版本哈希表:靠它认出"盘上这份是我们以前发的"
|
||||||
|
try:
|
||||||
|
shipped = bundled_tool_sources.shipped()
|
||||||
|
except Exception: # noqa: BLE001 - 老版本生成的文件里没有这个函数
|
||||||
|
shipped = {}
|
||||||
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# 读上次写下的指纹
|
||||||
|
stamp_path = os.path.join(tools_dir, '.doubao-seed.json')
|
||||||
|
seeded: dict = {}
|
||||||
|
try:
|
||||||
|
with open(stamp_path, encoding='utf-8') as fh:
|
||||||
|
loaded = json.load(fh)
|
||||||
|
if isinstance(loaded, dict):
|
||||||
|
seeded = loaded
|
||||||
|
except Exception: # noqa: BLE001 - 没有/坏了都当第一版处理
|
||||||
|
seeded = {}
|
||||||
|
|
||||||
copied = 0
|
copied = 0
|
||||||
|
skipped_user = 0
|
||||||
for filename, source in wanted.items():
|
for filename, source in wanted.items():
|
||||||
if not source:
|
if not source:
|
||||||
continue
|
continue
|
||||||
dest = os.path.join(tools_dir, filename)
|
dest = os.path.join(tools_dir, filename)
|
||||||
|
new_hash = _src_hash(source)
|
||||||
|
|
||||||
if os.path.exists(dest):
|
if os.path.exists(dest):
|
||||||
continue
|
try:
|
||||||
with open(dest, 'w', encoding='utf-8') as fh:
|
with open(dest, encoding='utf-8') as fh:
|
||||||
fh.write(source)
|
current = fh.read()
|
||||||
copied += 1
|
except Exception: # noqa: BLE001
|
||||||
|
continue
|
||||||
|
cur_hash = _src_hash(current)
|
||||||
|
if cur_hash == new_hash:
|
||||||
|
# 已经是这一版了。**顺手把指纹补上** ——
|
||||||
|
# 老设备上指纹是空的,不补的话下次还会走"用户改过"那条。
|
||||||
|
seeded[filename] = cur_hash
|
||||||
|
continue
|
||||||
|
# 是我们以前发的某个版本?→ 可以覆盖
|
||||||
|
ours_history = cur_hash in (shipped.get(filename) or [])
|
||||||
|
ours_stamp = seeded.get(filename) == cur_hash
|
||||||
|
if not ours_history and not ours_stamp:
|
||||||
|
# 用户自己改过 —— 不覆盖。留个日志方便排查
|
||||||
|
skipped_user += 1
|
||||||
|
print(f'[tools] {filename} 被用户改过,保留不覆盖', file=sys.stderr, flush=True)
|
||||||
|
continue
|
||||||
|
# 没改过,且我们的版本变了 → 覆盖
|
||||||
|
try:
|
||||||
|
with open(dest, 'w', encoding='utf-8') as fh:
|
||||||
|
fh.write(source)
|
||||||
|
seeded[filename] = new_hash
|
||||||
|
copied += 1
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
print(f'[tools] 写 {filename} 失败:{exc}', file=sys.stderr, flush=True)
|
||||||
|
|
||||||
|
if copied or skipped_user:
|
||||||
|
print(f'[tools] 播种:更新 {copied} 个,保留用户改过的 {skipped_user} 个',
|
||||||
|
file=sys.stderr, flush=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(stamp_path, 'w', encoding='utf-8') as fh:
|
||||||
|
json.dump(seeded, fh, ensure_ascii=False, indent=2)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
return copied
|
return copied
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
93
scripts/backfill-shipped-hashes.py
Normal file
93
scripts/backfill-shipped-hashes.py
Normal 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 才真写)")
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
* 用法: node scripts/build-apk.mjs [--skip-build] [--release]
|
* 用法: node scripts/build-apk.mjs [--skip-build] [--release]
|
||||||
*/
|
*/
|
||||||
import { spawnSync } from 'node:child_process';
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -109,12 +110,56 @@ for (const file of fs.readdirSync(path.join(repo, 'tools'))) {
|
|||||||
toolSources[file] = source.toString('base64');
|
toolSources[file] = source.toString('base64');
|
||||||
toolCount += 1;
|
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 = [
|
const bundledPy = [
|
||||||
'"""构建时自动生成,不要手改。',
|
'"""构建时自动生成,不要手改。',
|
||||||
'',
|
'',
|
||||||
'内置 Python 工具的源码(base64)。安卓端 Chaquopy 只有 .pyc,',
|
'内置 Python 工具的源码(base64)。安卓端 Chaquopy 只有 .pyc,',
|
||||||
'所以由 scripts/build-apk.mjs 在打包时把源码嵌进来,',
|
'所以由 scripts/build-apk.mjs 在打包时把源码嵌进来,',
|
||||||
'由 doubao_entry 首次启动时解码写到手机上的可写工具目录。',
|
'由 doubao_entry 启动时解码写到手机上的可写工具目录。',
|
||||||
|
'',
|
||||||
|
'`shipped()` 返回"历史上我们发过的所有源码哈希" —— 内核靠它区分',
|
||||||
|
'"盘上这份是我们旧版本写的(可以覆盖)" 和 "用户自己改过(不能覆盖)"。',
|
||||||
'"""',
|
'"""',
|
||||||
'',
|
'',
|
||||||
'import base64',
|
'import base64',
|
||||||
@@ -123,14 +168,23 @@ const bundledPy = [
|
|||||||
...Object.entries(toolSources).map(([name, b64]) => ` ${JSON.stringify(name)}: ${JSON.stringify(b64)},`),
|
...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():',
|
'def sources():',
|
||||||
' """返回 {文件名: 源码文本}"""',
|
' """返回 {文件名: 源码文本}"""',
|
||||||
' return {name: base64.b64decode(data).decode("utf-8") for name, data in _DATA.items()}',
|
' 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');
|
].join('\n');
|
||||||
fs.writeFileSync(path.join(pyRoot, 'bundled_tool_sources.py'), bundledPy, 'utf8');
|
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") 引入;
|
// 内核源码在 android/kernel,靠 chaquopy 的 srcDir("../kernel") 引入;
|
||||||
// 这里检查一下它确实在
|
// 这里检查一下它确实在
|
||||||
|
|||||||
49
scripts/probe-check-showui-spec.py
Normal file
49
scripts/probe-check-showui-spec.py
Normal 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 "(没报)"))
|
||||||
57
scripts/probe-device-pyc.py
Normal file
57
scripts/probe-device-pyc.py
Normal 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])
|
||||||
63
scripts/probe-device-tools-dir.py
Normal file
63
scripts/probe-device-tools-dir.py
Normal 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])
|
||||||
109
scripts/probe-kernel-write.py
Normal file
109
scripts/probe-kernel-write.py
Normal 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])
|
||||||
43
scripts/probe-list-and-run.py
Normal file
43
scripts/probe-list-and-run.py
Normal 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])
|
||||||
71
scripts/probe-loaded-entry.py
Normal file
71
scripts/probe-loaded-entry.py
Normal 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
111
scripts/probe-seed-trace.py
Normal 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
74
scripts/probe-seed-why.py
Normal 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:])
|
||||||
82
scripts/probe-show-ui-modes.py
Normal file
82
scripts/probe-show-ui-modes.py
Normal 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)
|
||||||
95
scripts/probe-tools-writable.py
Normal file
95
scripts/probe-tools-writable.py
Normal 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:])
|
||||||
227
scripts/verify-seed-tools.py
Normal file
227
scripts/verify-seed-tools.py
Normal 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("✅ 全部通过")
|
||||||
47
tools/.shipped-hashes.json
Normal file
47
tools/.shipped-hashes.json
Normal file
@@ -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"
|
||||||
|
]
|
||||||
|
}
|
||||||
108
tools/show_ui.py
108
tools/show_ui.py
@@ -38,16 +38,30 @@ TOOL = {
|
|||||||
"\n· html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
|
"\n· html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
|
||||||
"想完全控制就传 full_html=true。"
|
"想完全控制就传 full_html=true。"
|
||||||
"\n· **可以用 <script>**:canvas 画图、SVG 动画、算完再渲染都行。"
|
"\n· **可以用 <script>**:canvas 画图、SVG 动画、算完再渲染都行。"
|
||||||
"\n· ★★ **用户的选择会回到你手里** —— 在页面里调这三个接口:"
|
"\n· 用户的选择会回到你手里 —— 页面里调:"
|
||||||
"\n Doubao.sendToAi('值') 或 Doubao.pick('值') → 把值送回给你"
|
"\n Doubao.sendToAi('值') 或 Doubao.pick('值') → 回传值给你"
|
||||||
"\n Doubao.close() → 关掉这个界面"
|
"\n Doubao.close() → 关掉这个界面"
|
||||||
"\n 也可以不写 JS,直接放按钮:"
|
"\n 也可以不写 JS,直接放按钮:"
|
||||||
"\n <button data-doubao-result=\"值\">文字</button>"
|
"\n <button data-doubao-result=\"值\">文字</button>"
|
||||||
"\n"
|
|
||||||
"\n ★ 送回的值**在你下一轮对话时才会看到**(它们排着队,和用户那句话一起给你),"
|
|
||||||
"\n 所以别在同一个回合里等它。想让用户选完立刻有回应,用 ask_user(它是阻塞的)。"
|
|
||||||
"\n· 普通链接(http/https)**在界面里打开**,用户可以点进去看,顶部有返回键。"
|
"\n· 普通链接(http/https)**在界面里打开**,用户可以点进去看,顶部有返回键。"
|
||||||
"\n\n调用后界面立刻显示、本工具立刻返回,用户看完再继续对话。"
|
"\n"
|
||||||
|
"\n★★ **三种收尾方式,按需要选**(这是这个工具最重要的一个参数):"
|
||||||
|
"\n"
|
||||||
|
"\n wait=false(默认)—— 不等,弹出就继续。适合图表、报告这类"
|
||||||
|
"\n \"给用户看\"的东西。用户看完自己关,你这一轮已经答完了。"
|
||||||
|
"\n 用户后来说话时,你能看到他在界面上点过什么(会作为上下文附给你)。"
|
||||||
|
"\n"
|
||||||
|
"\n wait=true —— **等用户操作**(点回传按钮或关掉界面,最多 timeout 秒)。"
|
||||||
|
"\n 适合\"弹出几个选项让用户挑,然后我接着干\"。用户点了什么会**立刻**"
|
||||||
|
"\n 作为本工具的返回值给你,你能在**同一个回合里**继续处理。"
|
||||||
|
"\n 用户直接关掉界面(没点任何按钮)时返回 value=空串、closed=true。"
|
||||||
|
"\n 超时返回 timeout=true —— 那就当作用户没理你,正常收尾就行。"
|
||||||
|
"\n"
|
||||||
|
"\n 也可以**什么都不做**:不弹界面,直接文字回答。"
|
||||||
|
"\n"
|
||||||
|
"\n★ 要放让用户点的按钮时,把按钮做得**明显**:"
|
||||||
|
"\n 深色底 + 亮色字(或亮色底 + 深色字),padding 至少 14px、字号至少 16px。"
|
||||||
|
"\n 纯文字当按钮、或者暗底暗字,用户根本看不出那儿能点。"
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -64,6 +78,17 @@ TOOL = {
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "true 表示 html 是一份完整文档,不再套骨架。默认 false",
|
"description": "true 表示 html 是一份完整文档,不再套骨架。默认 false",
|
||||||
},
|
},
|
||||||
|
"wait": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": (
|
||||||
|
"false(默认)弹出就返回,不等用户;"
|
||||||
|
"true 等用户点回传按钮或关掉界面再返回(最多 timeout 秒)"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
"timeout": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "wait=true 时最多等多少秒,默认 120,最大 600",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
"required": ["html"],
|
"required": ["html"],
|
||||||
},
|
},
|
||||||
@@ -74,24 +99,67 @@ def run(args: dict) -> dict:
|
|||||||
html = str(args.get("html") or "").strip()
|
html = str(args.get("html") or "").strip()
|
||||||
if not html:
|
if not html:
|
||||||
raise ValueError("html 不能为空")
|
raise ValueError("html 不能为空")
|
||||||
res = call_device(
|
|
||||||
{
|
wait = bool(args.get("wait"))
|
||||||
"action": "ui_screen",
|
# 上限 600 秒:再长的话内核工作线程被占住太久(HTTP 是每请求一线程)。
|
||||||
"html": html,
|
# 下限 5 秒:低于这个值用户根本来不及看清界面就被判超时了。
|
||||||
"title": str(args.get("title") or ""),
|
try:
|
||||||
"full_html": bool(args.get("full_html")),
|
timeout = float(args.get("timeout") or 120)
|
||||||
"conversationId": conversation_id(),
|
except (TypeError, ValueError):
|
||||||
}
|
timeout = 120.0
|
||||||
)
|
timeout = max(5.0, min(600.0, timeout))
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"action": "ui_screen",
|
||||||
|
"html": html,
|
||||||
|
"title": str(args.get("title") or ""),
|
||||||
|
"full_html": bool(args.get("full_html")),
|
||||||
|
"conversationId": conversation_id(),
|
||||||
|
"wait": wait,
|
||||||
|
}
|
||||||
|
if wait:
|
||||||
|
payload["timeoutMs"] = int(timeout * 1000)
|
||||||
|
|
||||||
|
res = call_device(payload)
|
||||||
if res.get("unavailable"):
|
if res.get("unavailable"):
|
||||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||||
if res.get("error"):
|
if res.get("error"):
|
||||||
raise RuntimeError(str(res["error"]))
|
raise RuntimeError(str(res["error"]))
|
||||||
return {
|
|
||||||
"shown": True,
|
out = {"shown": True, "bytes": len(html)}
|
||||||
"bytes": len(html),
|
|
||||||
"note": "界面已弹出,用户看完会自己关掉。你不需要再重复内容。",
|
if not wait:
|
||||||
}
|
# 不等待:这一轮就到此为止。用户之后说话时,他在界面上点过什么
|
||||||
|
# 会作为上下文附给模型(内核的待交付队列),所以这里如实说明。
|
||||||
|
out["note"] = (
|
||||||
|
"界面已弹出,你没有等用户。用户看完会自己关掉;"
|
||||||
|
"他在界面上点过什么,等他下次说话时会作为上下文给你。"
|
||||||
|
"现在可以正常收尾这一轮了。"
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ---- 等待模式:用户点了什么 / 关掉了 / 超时 ----
|
||||||
|
out["waited"] = True
|
||||||
|
out["timeout"] = bool(res.get("timeout"))
|
||||||
|
out["closed"] = bool(res.get("closed"))
|
||||||
|
value = str(res.get("value") or "")
|
||||||
|
out["value"] = value
|
||||||
|
|
||||||
|
if out["timeout"]:
|
||||||
|
out["note"] = (
|
||||||
|
f"等了 {timeout:.0f} 秒用户也没操作,界面已收起。"
|
||||||
|
"当作用户暂时没空处理,别反复重弹 —— 正常收尾,等他自己来说。"
|
||||||
|
)
|
||||||
|
elif value:
|
||||||
|
out["note"] = (
|
||||||
|
"用户点了这个。**现在就按这个值继续处理**,不用再问一遍、也不用重复界面内容。"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
out["note"] = (
|
||||||
|
"用户没点任何按钮,直接把界面关掉了。"
|
||||||
|
"通常表示他不想选 / 想自己说 —— 别重弹同一个界面,用一句话收尾就行。"
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user