Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
103c939051 | ||
|
|
885a1f0123 | ||
|
|
ba429e67cd | ||
|
|
5f138be5fa | ||
|
|
f7454c0b60 | ||
|
|
0ad999b6e6 | ||
|
|
e18970c85f | ||
|
|
0fe43d67df | ||
|
|
f789803eae | ||
|
|
52680b9eb7 | ||
|
|
6197b726a5 | ||
|
|
cead531983 | ||
|
|
2601e9ae43 | ||
|
|
8123fff9ca | ||
|
|
c25e94583a | ||
|
|
ecb6e6f924 | ||
|
|
028d67c3ec | ||
| 982c64939b | |||
| b39c23b4dd | |||
| 82fbbe8887 | |||
| 9dc26ed427 | |||
| 85238013a1 | |||
| 97793231c1 | |||
| 59e12a7261 | |||
| dd7bce574e | |||
| 71703c173c | |||
| ed97ec6c63 | |||
| 0f618ba2b0 | |||
| 04f00d1114 | |||
| 754ff80b2b | |||
| 19fe7a6af6 | |||
| 659a212465 | |||
| 626ac89ac8 | |||
| df909f3dd6 | |||
| 5c157c3044 | |||
| 7705a3eb7e | |||
| 52feef35cd | |||
| d88a7aa8aa | |||
| fb105377a9 | |||
| a536b7ba27 | |||
| 519250b109 | |||
| cfdf10a035 | |||
| 7f3dbb4002 | |||
| bec25b71ac | |||
| 19a03724bb | |||
| 5ed71f4f1b | |||
| 3266afd1a4 | |||
| bc6a172888 | |||
| 4883cedfeb | |||
| c8c3dfd59c | |||
| affc407f5e | |||
| 29f29a4524 | |||
| 2a459dd5a4 | |||
| a661102bf1 | |||
| d46008cb11 | |||
| 999ad82065 | |||
| cb7e3a91db | |||
| ed5a3115df | |||
| 66b5f13c4e | |||
| c3eb714b10 |
93
AGENTS.md
93
AGENTS.md
@@ -1,3 +1,51 @@
|
||||
# 项目约定
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
|
||||
---
|
||||
|
||||
# 代码托管
|
||||
|
||||
## 两个 remote,同一个仓库
|
||||
|
||||
| remote | 地址 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `local` | `http://192.168.100.103:8080/l/doubao-clone.git` | **在家/局域网,优先用这个**(快) |
|
||||
| `origin` | `https://git.xnhw.cc/l/doubao-clone.git` | 不在局域网时 |
|
||||
|
||||
两个地址指向**同一台服务器**(`git.xnhw.cc` 在外网解析到 `64.49.47.22`,
|
||||
局域网里就是 `192.168.100.103:8080`)。推哪个都行,别同时推两遍。
|
||||
|
||||
服务是 **Noir's Git**(Gitea 系)。
|
||||
|
||||
## 推送
|
||||
|
||||
```bash
|
||||
git push local main # 日常
|
||||
git push local --tags # 标签
|
||||
```
|
||||
|
||||
`local` 的凭据存在 `.git/config` 的 remote URL 里(`.git` 不属于仓库内容,
|
||||
不会被提交)—— 所以不用每次输密码。
|
||||
|
||||
## 一个坑:push 报 401 时会**假装卡住**
|
||||
|
||||
这个服务器上 `receive-pack`(推送)要认证,而 `upload-pack`(拉取)不用。
|
||||
凭据不对时 git 会**挂在等密码输入上,一行输出都没有** ——
|
||||
看起来像网络卡死,其实是在等 stdin。
|
||||
|
||||
所以:
|
||||
- 脚本里推之前先设 `GIT_TERMINAL_PROMPT=0`(让它直接失败而不是等)
|
||||
- 或者直接确认 remote URL 里有凭据
|
||||
|
||||
排查顺序:
|
||||
```bash
|
||||
git ls-remote <url> # GET 通不通(不需要认证也能通)
|
||||
curl -i "<url>/info/refs?service=git-receive-pack" # 401 就是认证问题
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 界面约定
|
||||
|
||||
适用于本仓库的 Android / Compose 界面。
|
||||
@@ -44,10 +92,14 @@
|
||||
记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 ——
|
||||
比弹窗还糟。
|
||||
|
||||
## 已经欠着的(按这个原则该改还没改的)
|
||||
## 全屏化的进度
|
||||
|
||||
- [ ] 节点管理 `NodeManagerDialog` → 全屏
|
||||
- [ ] 节点编辑 `NodeEditDialog` → 全屏(代码编辑要有整屏)
|
||||
**已经改完全屏的**:
|
||||
- ✅ 节点管理 `NodeManagerScreen`
|
||||
- ✅ 节点编辑 `NodeCodeScreen`(代码框占满剩余高度)
|
||||
- ✅ 积木编辑器 `NodeBlockEditorScreen`
|
||||
|
||||
**还欠着的**:
|
||||
- [ ] 变量管理 `VarManagerDialog` → 全屏
|
||||
- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层
|
||||
- [ ] 导入会议 `ImportDialog` → 全屏
|
||||
@@ -55,8 +107,30 @@
|
||||
|
||||
**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。
|
||||
|
||||
### 改全屏时踩的坑:界面的 return 顺序
|
||||
|
||||
全屏界面是用状态变量 + `return@Composable` 实现的,于是**谁在上面谁优先**:
|
||||
|
||||
```kotlin
|
||||
blockEdit?.let { ...; return@MeetingEditorScreen } // 积木编辑器
|
||||
if (showNodeMgr) { ...; return@MeetingEditorScreen } // 节点管理
|
||||
if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
```
|
||||
|
||||
在下面的界面要显示时,**必须先把它上面的那个状态关掉** ——
|
||||
否则上面的先 return,下面的永远轮不到渲染。
|
||||
表现是"点了没反应",其实状态全对了,只是没机会画(这个 bug 真出现过)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`opSpec` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
只改一半,用户会说"你不会举一反三的吗"。
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
@@ -66,3 +140,16 @@
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
- **代码框不能软换行**。` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
就是语法。这个 Compose 版本(BOM 2024.09.03)的 `BasicTextField`
|
||||
经典重载选不中,所以用"把输入框塞进足够宽的横向滚动容器"来达到同样效果。
|
||||
- **代码框要有高度上限**。只写 `heightIn(min=...)` 的话,文件一长框就长到
|
||||
屏幕外,把底下的补全条顶出去,用户够不着。
|
||||
- **改了没生效就先怀疑工具**。PowerShell 的 `String.Replace` **匹配失败不报错**;
|
||||
按行号剪贴会算错下标(甚至把整个文件追加一遍);
|
||||
`git checkout -- <文件>` 会还原**这一轮所有未提交的改动**。
|
||||
改完立刻 grep 确认,动手前先断言下标有效。
|
||||
- **莫名其妙的"未解析引用"先数括号**。漏一个 `}` 会让后面所有顶层声明
|
||||
全部报未解析,错误信息看着完全不像是括号问题(报的是 `PrimaryButton`
|
||||
找不到这种)。
|
||||
|
||||
|
||||
@@ -20,8 +20,18 @@ android {
|
||||
* 代价:上不了应用商店;部分新系统行为按旧版走(对我们这种本地工具无所谓)。
|
||||
*/
|
||||
targetSdk = 28
|
||||
versionCode = 3
|
||||
versionName = "0.3.0"
|
||||
/**
|
||||
* 版本号跟着 release 标签走。
|
||||
*
|
||||
* ★ 之前一直停在 0.3.0,而 git 标签已经从 1.0 走到 v2.0 了 ——
|
||||
* 装到手机上根本分不清装的是哪一版("我装的是不是最新的"这个
|
||||
* 最基本的问题都答不了)。发 release 前必须对上。
|
||||
*
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 239
|
||||
versionName = "2.0.39"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -29,14 +39,77 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lint 不挡 release 构建。
|
||||
*
|
||||
* ★ 唯一让它报错的是 `targetSdk = 28` 那条:
|
||||
*
|
||||
* Error: Google Play requires that apps target API level 33 or higher.
|
||||
* [ExpiredTargetSdkVersion]
|
||||
*
|
||||
* 而 **28 是必须的**,不能改 —— Android 10 起 targetSdk>=29 的应用
|
||||
* 不允许执行自己数据目录里的二进制(W^X 限制),而 bash / python /
|
||||
* dpkg 全在 /data/data/<包名>/files/usr 里。Termux 自己也是锁 28
|
||||
* 才活下来的。这条 lint 检查针对的是"上架 Google Play",而我们
|
||||
* 这个 App 本来就上不了架(自签证书 + 这个 targetSdk)。
|
||||
*
|
||||
* ★ 设 `abortOnError = false` 而不是 `checkReleaseBuilds = false`:
|
||||
* lint **照常跑**、报告照常生成,只是不因为这一条把构建打断。
|
||||
* 别的真问题仍然看得到。
|
||||
*/
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名。
|
||||
*
|
||||
* ★ 用的是**原来那个 debug 证书**(fingerprint 83:28:15:D6…),
|
||||
* 只是把它**拷进了仓库**,并且**显式开了 v1/v2/v3**。
|
||||
*
|
||||
* 为什么这么做(踩过两次,记下来):
|
||||
*
|
||||
* 1. **不能随便换证书**。Android 不允许同包名不同签名覆盖安装 ——
|
||||
* 换了之后用户必须**先卸载**(数据全丢)。
|
||||
* 我第一次"修签名问题"时顺手换了一把新证书,结果老用户装不上,
|
||||
* 报"已安装了签名冲突的应用"。**修 A 问题不能引入 B 问题。**
|
||||
*
|
||||
* 2. **缺 v1(JAR)签名会让很多安装器拒绝**。Android 7+ 自己装没问题,
|
||||
* 但从远程传过去再装(MT 管理器 / UU远程 之类)会报
|
||||
* "解析失败:安装包没有签名文件"。所以 v1/v2/v3 全开。
|
||||
*
|
||||
* 3. **debug 证书默认在 ~/.android/ 里,换台机器就变**。
|
||||
* 拷进仓库(连密码一起)之后,**哪台机器构建出来的指纹都一样**,
|
||||
* 能互相覆盖安装。
|
||||
*
|
||||
* ★ 密码是 debug 证书的标准密码,**它不是秘密**。
|
||||
* 自签证书只保证"指纹稳定、能覆盖安装",不证明"是谁发的"。
|
||||
*/
|
||||
signingConfigs {
|
||||
create("doubao") {
|
||||
storeFile = file("../doubao-release.jks")
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
enableV1Signing = true
|
||||
enableV2Signing = true
|
||||
enableV3Signing = true
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
debug {
|
||||
// debug 包也用同一把 —— 本地调试的包和发出去的包能互相覆盖安装
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
|
||||
33
android/app/src/main/java/com/doubao/lynxclone/KernelHost.kt
Normal file
33
android/app/src/main/java/com/doubao/lynxclone/KernelHost.kt
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
|
||||
/**
|
||||
* 内核监听的端口。
|
||||
*
|
||||
* ## 为什么要有这个单例
|
||||
*
|
||||
* 端口原来是 `MainActivity` 里一个局部变量(`client.baseUrl` 也在那儿设)。
|
||||
* 但 `NativeBridge` 也需要打内核的接口 —— `end_conversation` 要
|
||||
* `PATCH /api/conversations/<id>` 把"这次对话已结束"落盘,而
|
||||
* `NativeBridge` 在**内核的工作线程**上被调,拿不到 Activity 的局部变量,
|
||||
* 也不该去依赖 UI 层的 `KernelClient`。
|
||||
*
|
||||
* 所以放一个进程级的单例:`MainActivity` 启动内核后写一次,别处只读。
|
||||
*/
|
||||
object KernelHost {
|
||||
|
||||
/** 内核端口;0 表示还没起来 */
|
||||
@Volatile
|
||||
var port: Int = 0
|
||||
|
||||
/** 内核起来之后由 MainActivity 调 */
|
||||
fun set(p: Int) {
|
||||
port = p
|
||||
}
|
||||
|
||||
fun baseUrl(): String = if (port > 0) "http://127.0.0.1:$port" else ""
|
||||
}
|
||||
|
||||
/** 全项目统一的 JSON 请求体类型(别在各处手写字符串,写错一个字符就是 415) */
|
||||
val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType()
|
||||
@@ -70,6 +70,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (port != null && port > 0) {
|
||||
client.baseUrl = "http://127.0.0.1:$port"
|
||||
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||
KernelHost.set(port)
|
||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||
withContext(Dispatchers.IO) {
|
||||
|
||||
@@ -20,7 +20,10 @@ import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -67,6 +70,16 @@ class NativeBridge(private val activity: Activity) {
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
|
||||
//
|
||||
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
|
||||
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
|
||||
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
|
||||
"ui_screen" -> uiScreen(req)
|
||||
"ui_dialog" -> uiDialog(req)
|
||||
"end_conversation" -> endConversation(req)
|
||||
// AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult)
|
||||
"ui_result" -> pushUiResult(req)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -74,6 +87,186 @@ class NativeBridge(private val activity: Activity) {
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。**
|
||||
*
|
||||
* AI 在 `show_ui` 的 HTML 里写 `Doubao.sendToAi('值')`,那个值会打到这里,
|
||||
* 然后 POST 到内核的 `/api/ui-result` 排队。
|
||||
* 下一轮对话开始时,`agent_loop` 会把队里的东西作为上下文交给模型 ——
|
||||
* 于是模型**真的知道**用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 为什么经内核排队、而不是让 Kotlin 直接起一轮对话:
|
||||
* 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型既慢又费 token,
|
||||
* 而且用户还没说完。排队 → 下一次说话时一起带上,语义上也更对:
|
||||
* **界面上的选择是提问的一部分,不是提问本身**。
|
||||
*
|
||||
* ★ 失败不抛异常,只回 ok:false:这是"用户点了一下按钮",
|
||||
* 内核没起来不该让 App 崩(用户会看到提示,也能再点一次)。
|
||||
*/
|
||||
private fun pushUiResult(req: JSONObject): JSONObject {
|
||||
val value = req.optString("value").trim()
|
||||
val convId = req.optString("conversationId").trim()
|
||||
if (value.isEmpty()) return JSONObject().put("error", "value 是空的")
|
||||
if (convId.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
return try {
|
||||
val body = JSONObject().put("conversationId", convId).put("value", value)
|
||||
val resp = kernelPost("/api/ui-result", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,这次选择没能送出去")
|
||||
} else {
|
||||
JSONObject().put("ok", true).put("queued", resp.optInt("queued"))
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||
*
|
||||
* [wait] 由工具参数决定:
|
||||
* · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关
|
||||
* · true ——**等用户操作**:点了回传按钮或关掉界面才返回,
|
||||
* 用户点的值原样带回给模型
|
||||
*
|
||||
* ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话,
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
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),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点或超时 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
if (question.isBlank()) return JSONObject().put("error", "question 是空的")
|
||||
|
||||
val options = mutableListOf<AiSurface.Option>()
|
||||
val arr = req.optJSONArray("options") ?: JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val label = o.optString("label").ifBlank { o.optString("value") }
|
||||
if (label.isBlank()) continue
|
||||
options.add(
|
||||
AiSurface.Option(
|
||||
label = label,
|
||||
value = o.optString("value").ifBlank { label },
|
||||
description = o.optString("description"),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (options.isEmpty()) return JSONObject().put("error", "至少要有一个选项")
|
||||
|
||||
return AiSurface.ask(
|
||||
question = question,
|
||||
options = options,
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 永久结束当前对话(tools/end_conversation.py)。
|
||||
*
|
||||
* ★ 必须**落盘**(PATCH /api/conversations/<id>),不能只改界面状态 ——
|
||||
* 界面状态一刷新就没了,用户重进会看到一个能继续输入的框,
|
||||
* 而模型以为自己已经结束了。两边状态不一致是这类功能最容易出的问题。
|
||||
*/
|
||||
private fun endConversation(req: JSONObject): JSONObject {
|
||||
val convId = req.optString("conversationId").ifBlank {
|
||||
return JSONObject().put("error", "没有 conversationId,无法结束对话")
|
||||
}
|
||||
val reason = req.optString("reason")
|
||||
val summary = req.optString("summary")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("ended", true)
|
||||
.put("endedAt", System.currentTimeMillis())
|
||||
.put("endedReason", reason)
|
||||
if (summary.isNotBlank()) body.put("endedSummary", summary)
|
||||
// 走内核自己的 HTTP 接口 —— 这是唯一一条"由 Kotlin 写内核数据"的既有通道
|
||||
val resp = kernelPatch("/api/conversations/$convId", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,对话状态没写进去")
|
||||
} else {
|
||||
AiSurface.markEnded(convId)
|
||||
JSONObject().put("ok", true).put("conversationId", convId)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH 一下内核的接口。
|
||||
*
|
||||
* ★ 这里**不能用 KernelClient** —— 那是 ViewModel 层的东西,NativeBridge
|
||||
* 拿不到(而且它跑在内核工作线程上,不该依赖 UI 层的对象)。
|
||||
* 直接用 OkHttp 打本机端口,和内核在同一个进程里,开销可以忽略。
|
||||
*
|
||||
* 端口从 [KernelHost.port] 取(内核起来之后写进去的)。
|
||||
*/
|
||||
private fun kernelPatch(path: String, body: JSONObject): String? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.patch(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
client.newCall(req).execute().use { resp ->
|
||||
return if (resp.isSuccessful) resp.body?.string() else null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 一下内核的接口,返回解析好的 JSON;失败返回 null。
|
||||
*
|
||||
* ★ 和 [kernelPatch] 共用同一套"直接打本机端口"的做法 ——
|
||||
* 不用 `KernelClient`(那是 ViewModel 层的东西,NativeBridge 拿不到,
|
||||
* 而且这里是内核工作线程,不该依赖 UI 层对象)。
|
||||
*/
|
||||
private fun kernelPost(path: String, body: JSONObject): JSONObject? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.post(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
return client.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val text = resp.body?.string() ?: return null
|
||||
runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
/**
|
||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||
*
|
||||
* ## 为什么要一个单例控制器
|
||||
*
|
||||
* 内核(Python,跑在 HTTP 工作线程上)通过 `NativeBridge.device()` 说
|
||||
* "给我弹个界面",而界面是 Compose 画的、归 `AppViewModel` 管。
|
||||
* 这两边**没有互相引用**:
|
||||
*
|
||||
* · `NativeBridge` 在 `MainActivity` 里 new 出来(见 MainActivity:76)
|
||||
* · `AppViewModel` 在 Compose 树里由 `rememberAppViewModel` 造
|
||||
*
|
||||
* 所以中间放一个单例:NativeBridge 往里写,ViewModel 订阅。
|
||||
* 这也让"内核线程"和"UI 状态"的边界很清楚 —— 内核永远不直接碰 Compose。
|
||||
*
|
||||
* ## 线程模型(这是最容易出错的地方)
|
||||
*
|
||||
* `device()` 是在**内核的 HTTP 工作线程**上被调的,而:
|
||||
* · 写状态:用 `@Volatile` + 监听器回调,ViewModel 在自己的协程里切主线程更新 Compose
|
||||
* · 等用户选择:用 [CountDownLatch] 阻塞**那个工作线程**(不能阻塞 UI 线程)
|
||||
*
|
||||
* 跟 `NativeBridge.pickFile()` 是同一套路子(它已经验证过可行)。
|
||||
*/
|
||||
object AiSurface {
|
||||
|
||||
private const val TAG = "DoubaoAiSurface"
|
||||
|
||||
/** 一次 AI 界面的标识。每次弹出都换一个,用来让 Compose 重建 WebView。 */
|
||||
private val seq = AtomicLong(0)
|
||||
|
||||
/** 正在显示的 HTML 界面;null 表示没有 */
|
||||
@Volatile
|
||||
var screen: Screen? = null
|
||||
private set
|
||||
|
||||
/** 正在等的选择弹窗;null 表示没有 */
|
||||
@Volatile
|
||||
var dialog: Dialog? = null
|
||||
private set
|
||||
|
||||
/** 当前对话被 AI 结束过 —— 界面据此禁用输入框 */
|
||||
@Volatile
|
||||
var endedConversationId: String = ""
|
||||
private set
|
||||
|
||||
data class Screen(
|
||||
val id: Long,
|
||||
val html: String,
|
||||
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)
|
||||
|
||||
data class Dialog(
|
||||
val id: Long,
|
||||
val question: String,
|
||||
val options: List<Option>,
|
||||
val multiple: Boolean,
|
||||
val allowCancel: Boolean,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** ViewModel 订阅这个来把状态同步进 Compose。参数是"发生了什么"。 */
|
||||
@Volatile
|
||||
private var listener: ((String) -> Unit)? = null
|
||||
|
||||
fun subscribe(fn: ((String) -> Unit)?) {
|
||||
listener = fn
|
||||
}
|
||||
|
||||
private fun notify(kind: String) {
|
||||
try {
|
||||
listener?.invoke(kind)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "通知界面失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。
|
||||
*
|
||||
* [wait] = false(默认):**不阻塞** —— 弹出来就返回。
|
||||
* [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。
|
||||
*
|
||||
* ★ 为什么要两种:
|
||||
* 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。
|
||||
* 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。
|
||||
* 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。
|
||||
*
|
||||
* ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile`
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★ 超时必须有:用户可能锁屏走了。不设的话内核工作线程永远挂着,
|
||||
* 而 HTTP 是每请求一线程,挂一个少一个。
|
||||
*/
|
||||
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 { "(无)" }}," +
|
||||
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 ?: "")
|
||||
}
|
||||
|
||||
/** 等用户交互用的闩。非等待模式下是 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")
|
||||
}
|
||||
|
||||
@Volatile
|
||||
var lastScreenResult: String = ""
|
||||
private set
|
||||
|
||||
/** 用户把界面关掉了 */
|
||||
fun closeScreen() {
|
||||
screen = null
|
||||
// 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串
|
||||
screenClosed = true
|
||||
screenLatch?.countDown()
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
/** 进等待模式前由 NativeBridge 调一次,准备闩 */
|
||||
fun armScreenLatch() {
|
||||
screenLatch = CountDownLatch(1)
|
||||
screenAnswer = null
|
||||
screenClosed = false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完或超时。
|
||||
*
|
||||
* ★ 超时是必须的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
* 而且因为 HTTP 是每请求一线程,挂一个少一个。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
*/
|
||||
fun ask(
|
||||
question: String,
|
||||
options: List<Option>,
|
||||
multiple: Boolean,
|
||||
allowCancel: Boolean,
|
||||
conversationId: String,
|
||||
timeoutMs: Long,
|
||||
): JSONObject {
|
||||
val d = Dialog(seq.incrementAndGet(), question, options, multiple, allowCancel, conversationId)
|
||||
val latch = CountDownLatch(1)
|
||||
answerLatch = latch
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,最多等 ${timeoutMs / 1000}s)")
|
||||
|
||||
val answered = latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
dialog = null
|
||||
notify("dialog")
|
||||
|
||||
if (!answered || a == null) {
|
||||
Log.i(TAG, "用户没在时限内回答")
|
||||
return JSONObject()
|
||||
.put("timeout", true)
|
||||
.put("multiple", multiple)
|
||||
.put("choice", "")
|
||||
.put("values", JSONArray())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var answer: JSONObject? = null
|
||||
|
||||
/** 用户选了。界面调这个。 */
|
||||
fun answerDialog(values: List<String>, cancelled: Boolean) {
|
||||
val arr = JSONArray()
|
||||
values.forEach { arr.put(it) }
|
||||
answer = JSONObject()
|
||||
.put("timeout", false)
|
||||
.put("cancelled", cancelled)
|
||||
.put("multiple", dialog?.multiple ?: false)
|
||||
.put("choice", values.firstOrNull() ?: "")
|
||||
.put("values", arr)
|
||||
answerLatch?.countDown()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 结束对话
|
||||
|
||||
fun markEnded(conversationId: String) {
|
||||
endedConversationId = conversationId
|
||||
notify("ended")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,295 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Termux 的软件源(apt 源)管理。
|
||||
*
|
||||
* ★ 为什么要单独做这个:Termux 官方源(packages.termux.dev)在国内**基本连不上**,
|
||||
* 表现是 `pkg install` 卡在 "Reading package lists..." 或者直接超时 ——
|
||||
* 用户会以为"内置的 Termux 坏了",其实是源的问题。
|
||||
*
|
||||
* 国内几个镜像都是完整同步的,换一下就好。做成界面而不是让用户手敲 sed:
|
||||
* 换源这件事**每次重装都要做**,而且 apt 的源格式写错一点就整个不能用。
|
||||
*/
|
||||
object TermuxMirror {
|
||||
|
||||
/**
|
||||
* 一个源。
|
||||
*
|
||||
* @param id 稳定标识(存进偏好,别用下标 —— 以后插入新源会串位)
|
||||
* @param name 显示名
|
||||
* @param host 给 termux-main 用的仓库根地址(不带 /apt/ 之后的部分)
|
||||
* @param note 副标题:速度/稳定性之类的实话
|
||||
*/
|
||||
data class Mirror(val id: String, val name: String, val host: String, val note: String)
|
||||
|
||||
/**
|
||||
* 源列表。
|
||||
*
|
||||
* ★ 顺序是有讲究的:**默认放第一个**。
|
||||
* 镜像偶尔会挂(同步中断、证书过期),所以官方源要留着能切回去。
|
||||
*/
|
||||
val MIRRORS = listOf(
|
||||
Mirror(
|
||||
"tuna", "清华 TUNA", "http://mirrors.tuna.tsinghua.edu.cn/termux",
|
||||
"国内最快最稳的一个,推荐",
|
||||
),
|
||||
Mirror(
|
||||
"ustc", "中科大 USTC", "http://mirrors.ustc.edu.cn/termux",
|
||||
"同样完整同步,教育网更快",
|
||||
),
|
||||
Mirror(
|
||||
"aliyun", "阿里云", "http://mirrors.aliyun.com/termux",
|
||||
"公网覆盖好,偶尔缺 science 仓库",
|
||||
),
|
||||
Mirror(
|
||||
"bfsu", "北外 BFSU", "http://mirrors.bfsu.edu.cn/termux",
|
||||
"清华的备份站",
|
||||
),
|
||||
Mirror(
|
||||
"official", "官方源", "http://packages.termux.dev/apt",
|
||||
"国内经常连不上,镜像挂了才用它",
|
||||
),
|
||||
)
|
||||
|
||||
/** Termux 的仓库分几个「频道」,各自一条 sources.list 行 */
|
||||
private data class Channel(val name: String, val path: String, val components: String)
|
||||
|
||||
private val CHANNELS = listOf(
|
||||
Channel("termux-main", "apt/termux-main", "stable main"),
|
||||
Channel("termux-root", "apt/termux-root", "root stable"),
|
||||
Channel("termux-x11", "apt/termux-x11", "x11 main"),
|
||||
)
|
||||
|
||||
private fun aptDir(context: Context) = File(TermuxInstaller.prefix(context), "etc/apt")
|
||||
fun sourcesFile(context: Context) = File(aptDir(context), "sources.list")
|
||||
|
||||
/** 当前用的是哪个源(认不出来就返回 null) */
|
||||
fun current(context: Context): Mirror? {
|
||||
val file = sourcesFile(context)
|
||||
if (!file.exists()) return null
|
||||
val text = try {
|
||||
file.readText()
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
return MIRRORS.firstOrNull { text.contains(it.host) }
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 让 **`pkg`** 也认这个源。
|
||||
*
|
||||
* 踩过的坑:一开始只写了 `etc/apt/sources.list`,结果 `pkg update` 说
|
||||
* "No mirror or mirror group selected",然后**把全世界几十个镜像测了一遍**,
|
||||
* 最后挑了中国连不上的俄罗斯源 —— 用户看到一屏 `bad` 加一句
|
||||
* `E: Unable to determine a suitable packaging system type`。
|
||||
*
|
||||
* 原因:**`pkg` 不看 `sources.list`**,它自己有一套(见 `bin/pkg`):
|
||||
*
|
||||
* if [ -d .../etc/termux/chosen_mirrors ] → 镜像组(取目录下所有文件)
|
||||
* elif [ -f .../etc/termux/chosen_mirrors ] → 单个镜像(**文件本身**就是路径)
|
||||
* elif [ -L ... ] → 断链,退回测全部
|
||||
* else → 没选,测全部
|
||||
*
|
||||
* bootstrap 已经带了 `etc/termux/mirrors/<地区>/<主机名>` 这些源文件,
|
||||
* 内容是 `WEIGHT= / MAIN= / ROOT= / X11=` 的 shell 片段。
|
||||
* `termux-change-repo` 的做法就是**建个符号链接**指过去。这里照做。
|
||||
*/
|
||||
private fun selectForPkg(context: Context, mirror: Mirror): String {
|
||||
val termuxDir = File(TermuxInstaller.prefix(context), "etc/termux")
|
||||
val mirrorsDir = File(termuxDir, "mirrors")
|
||||
val chosen = File(termuxDir, "chosen_mirrors")
|
||||
if (!mirrorsDir.isDirectory) return "没有 mirrors 目录,跳过"
|
||||
|
||||
val hostOnly = mirror.host
|
||||
.removePrefix("https://").removePrefix("http://")
|
||||
.substringBefore('/')
|
||||
|
||||
val target = mirrorsDir.walkTopDown()
|
||||
.filter { it.isFile && it.name == hostOnly }
|
||||
.firstOrNull()
|
||||
?: return "mirrors/ 里没有 $hostOnly"
|
||||
|
||||
try {
|
||||
chosen.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
return try {
|
||||
java.nio.file.Files.createSymbolicLink(chosen.toPath(), target.toPath())
|
||||
"链接到 ${target.name}"
|
||||
} catch (t: Throwable) {
|
||||
// 有些文件系统不给建链接 → 退回复制(pkg 读的是文件内容,效果一样)
|
||||
try {
|
||||
target.copyTo(chosen, overwrite = true)
|
||||
"复制 ${target.name}(建链接失败:${t.javaClass.simpleName})"
|
||||
} catch (t2: Throwable) {
|
||||
"失败:${t2.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 换源。
|
||||
*
|
||||
* ★ 有个坑:Termux 官方的 sources.list **里面是带注释和 deb-src 的**,
|
||||
* 直接整份覆盖会丢掉用户自己加的东西。所以这里只**替换行**:
|
||||
* 凡是以 `deb ` 开头、且指向 termux 仓库的行,按频道重写;
|
||||
* 其余(注释、第三方源)原样留着。
|
||||
*
|
||||
* @return 写进去的行数
|
||||
*/
|
||||
fun set(context: Context, mirror: Mirror): Int {
|
||||
val dir = aptDir(context)
|
||||
dir.mkdirs()
|
||||
val file = sourcesFile(context)
|
||||
|
||||
val existing = if (file.exists()) {
|
||||
try {
|
||||
file.readLines()
|
||||
} catch (_: Throwable) {
|
||||
emptyList()
|
||||
}
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
// 保留非 termux 的行(注释、用户自己加的源)
|
||||
val kept = existing.filter { line ->
|
||||
val t = line.trim()
|
||||
!t.startsWith("deb ") || !t.contains("termux")
|
||||
}
|
||||
|
||||
// ★ 只写**原本就有**的频道:termux-root / termux-x11 这两个仓库
|
||||
// 国内镜像不一定同步了,凭空写进去会让 apt update 整条报错
|
||||
// (一个源 404,apt 就整个失败,用户看到的是"换源之后更坏了")。
|
||||
// main 永远要(没有它 pkg 什么都装不了)。
|
||||
val original = existing.joinToString("\n")
|
||||
val wanted = CHANNELS.filter {
|
||||
it.name == "termux-main" || original.contains(it.name)
|
||||
}
|
||||
|
||||
val header = listOf(
|
||||
"# 由豆包 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 换源:内置终端右上角「源」按钮;也可以手动改这个文件",
|
||||
)
|
||||
val lines = wanted.map { "deb ${mirror.host}/${it.path} ${it.components}" }
|
||||
|
||||
file.writeText(
|
||||
(header + kept.filter { it.isNotBlank() } + lines).joinToString("\n") + "\n",
|
||||
)
|
||||
|
||||
// ★★ 光写 sources.list **不够** —— `pkg` 不看这个文件!
|
||||
// 它有自己的 chosen_mirrors(见 selectForPkg 的注释)。
|
||||
// 不写的话 `pkg update` 会把全世界几十个镜像挨个测一遍,
|
||||
// 最后挑中一个国内连不上的(实测挑中了俄罗斯的 mephi),
|
||||
// 用户看到一屏 `bad` 和 `E: Unable to determine a suitable packaging system type`。
|
||||
val pkgNote = try {
|
||||
selectForPkg(context, mirror)
|
||||
} catch (t: Throwable) {
|
||||
"失败:${t.message}"
|
||||
}
|
||||
android.util.Log.i(
|
||||
"DoubaoTermux",
|
||||
"换源 ${mirror.name}:sources.list ${lines.size} 条;pkg $pkgNote",
|
||||
)
|
||||
return lines.size
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 当前源要是**用不了**,自动换一个能用的。
|
||||
*
|
||||
* ## 为什么需要
|
||||
*
|
||||
* 用户实测撞到的(原话):
|
||||
*
|
||||
* E: Failed to fetch .../binary-x86_64/Packages.bz2
|
||||
* File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
* E: Some index files failed to download. They have been ignored,
|
||||
* or old ones used instead.
|
||||
*
|
||||
* 这是**镜像正在同步**时的典型症状:`InRelease` 已经是新的了,
|
||||
* 但 `Packages.bz2` 还是旧的,apt 一对哈希就拒绝。用户侧完全没辙 ——
|
||||
* 「源」按钮他按了也没用(换到的还是同一个坏源,或者他根本不知道该换)。
|
||||
*
|
||||
* 而我们**默认给的就是清华**([MIRRORS] 第一个)。镜像偶尔同步是常态,
|
||||
* 所以这不是"清华不好",是"任何单一默认值都会偶尔把用户卡死"。
|
||||
*
|
||||
* ## 做法
|
||||
*
|
||||
* 真跑一次 `apt-get update` 当探测 —— **不自己写校验逻辑**:
|
||||
*
|
||||
* · apt 的校验比我们严(哈希、时间戳、架构都对),复用它最准
|
||||
* · 反正换源之后本来就要 update,探测这一步不白花
|
||||
* · 自己写"拉 InRelease 看看"那种轻量探针**测不出这个 bug** ——
|
||||
* InRelease 恰恰是好的那一半
|
||||
*
|
||||
* 当前源能用就**什么都不做**(不打扰用户的选择)。
|
||||
* 用不了才按 [MIRRORS] 顺序往下试,换成功就记住(写 sources.list + pkg 那套)。
|
||||
*
|
||||
* @param onSwitched 换成功时回调(给界面提示用),参数是新的源
|
||||
* @return 最终可用的源;全都不可用时返回 null
|
||||
*/
|
||||
fun autoPickIfBroken(context: Context, onSwitched: ((Mirror) -> Unit)? = null): Mirror? {
|
||||
val current = current(context) ?: MIRRORS.first()
|
||||
|
||||
if (probe(context, current)) return current
|
||||
|
||||
android.util.Log.i("DoubaoTermux", "源 ${current.name} 探测失败,开始找能用的")
|
||||
for (candidate in MIRRORS) {
|
||||
if (candidate.id == current.id) continue
|
||||
if (!probe(context, candidate)) continue
|
||||
val n = set(context, candidate)
|
||||
android.util.Log.i("DoubaoTermux", "已自动切到 ${candidate.name}($n 条)")
|
||||
onSwitched?.invoke(candidate)
|
||||
return candidate
|
||||
}
|
||||
android.util.Log.w("DoubaoTermux", "所有源都探测失败,保持 ${current.name}")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测一个源能不能用:**临时**写进 sources.list 跑一次 `apt-get update`,
|
||||
* 不管成败都把原来的 sources.list 还原回去。
|
||||
*
|
||||
* ★ 必须还原:探测失败时若留着半个写入状态,用户会看到"源莫名其妙变了"。
|
||||
*/
|
||||
private fun probe(context: Context, mirror: Mirror): Boolean {
|
||||
val file = sourcesFile(context)
|
||||
val backup = try {
|
||||
if (file.exists()) file.readText() else null
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
return try {
|
||||
set(context, mirror)
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val pb = ProcessBuilder("$prefix/bin/apt-get", "update")
|
||||
.directory(TermuxInstaller.home(context))
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
// 输出必须读掉,否则管道写满会把子进程卡死(apt 输出很多)
|
||||
val sink = Thread { proc.inputStream.readBytes(); proc.errorStream.readBytes() }
|
||||
sink.isDaemon = true
|
||||
sink.start()
|
||||
val ok = proc.waitFor(PROBE_TIMEOUT_S, java.util.concurrent.TimeUnit.SECONDS) &&
|
||||
proc.exitValue() == 0
|
||||
if (!ok) proc.destroyForcibly()
|
||||
ok
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.i("DoubaoTermux", "探测 ${mirror.name} 抛异常:${t.message}")
|
||||
false
|
||||
} finally {
|
||||
try {
|
||||
if (backup != null) file.writeText(backup) else file.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测超时。apt 卡住时不能把用户等死 */
|
||||
private const val PROBE_TIMEOUT_S = 45L
|
||||
}
|
||||
@@ -39,10 +39,21 @@ object TermuxShell {
|
||||
return try {
|
||||
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
|
||||
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
|
||||
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
//
|
||||
// ★★★ 用 `childEnvMap()` 而不是 `environment()`:ProcessBuilder 起的是
|
||||
// 子进程,**默认继承整个 App 进程的环境**,而里面带着 Chaquopy 注入的
|
||||
// `PYTHONPATH`(指向 3.13 编的 .imy)。不清掉的话 Termux 的 python 3.14
|
||||
// 一起来就读到 3.13 的 encodings/__init__.pyc,魔数不符直接核心崩溃:
|
||||
// Fatal Python error: Failed to import encodings module
|
||||
// 详见 TermuxInstaller.childEnv 的注释。
|
||||
//
|
||||
// ★ `environment().putAll(...)` 这种写法是**追加**,删不掉已有的键 ——
|
||||
// 所以必须显式摘掉那几个变量(childEnvMap 做了这件事)。
|
||||
val pb = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
.directory(workdir)
|
||||
.apply { environment().putAll(TermuxInstaller.environment(context)) }
|
||||
.start()
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
|
||||
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
|
||||
val outBuf = StringBuilder()
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||
@@ -23,62 +24,209 @@ class TermuxTerminal(private val context: Context) {
|
||||
var session: TerminalSession? = null
|
||||
private set
|
||||
|
||||
/** 这次是用哪种起法建起来的(写进日志,排查时一眼能看到是哪一步坏的) */
|
||||
@Volatile
|
||||
var startedWith: String = ""
|
||||
private set
|
||||
|
||||
/**
|
||||
* 开一个登录 shell。Termux 的标准做法就是跑 `$PREFIX/bin/login`,
|
||||
* 它会按 /etc/profile 把 PATH、PS1、动态库路径都准备好。
|
||||
* ★★★ 必须把 `TerminalView` 接进来,否则**屏幕永远不刷新**。
|
||||
*
|
||||
* Termux 的分工是:会话把输出解析进 emulator 的屏幕缓冲,
|
||||
* 然后通过 `TerminalSessionClient.onTextChanged()` 通知"该重画了",
|
||||
* 由 `TerminalView.onScreenUpdated()` 真正去 invalidate。
|
||||
*
|
||||
* 我这里的 `onTextChanged` 之前是**空的** —— 于是:pty 通了、bash 活着、
|
||||
* 输出也解析进缓冲了,**但屏幕一动不动**,看起来像"什么都没发生"。
|
||||
* (这个坑和 pty 那个是两回事,修好 argv 之后才暴露出来。)
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
@Volatile
|
||||
var view: TerminalView? = null
|
||||
|
||||
|
||||
/** 用完了没有(决定要不要切成命令控制台) */
|
||||
val candidatesExhausted: Boolean get() = candidateIndex >= candidateCount
|
||||
|
||||
private var candidateIndex = 0
|
||||
private var candidateCount = 0
|
||||
|
||||
/**
|
||||
* ★ 诊断用:`cat` 无参数时**一直读 stdin**,不会自己退出。
|
||||
*
|
||||
* 三种环境各试一次,就能定位到底哪一段环境变量把子进程搞坏了:
|
||||
* A. 干净环境(只留 PATH=/system/bin)—— 系统二进制,测 pty 本身
|
||||
* B. 干净环境 + 我们自己的 bash —— 测 bash 在干净环境下活不活
|
||||
* C. 完整环境(现在的默认)
|
||||
*
|
||||
* 怀疑点:`LD_LIBRARY_PATH=$prefix/lib` 会**屏蔽系统库**,
|
||||
* 系统二进制(toybox 之类)因此加载失败 → exec 返回 127。
|
||||
* 定位完这几条诊断候选都删掉。
|
||||
*/
|
||||
private fun cleanEnv(): List<String> = listOf(
|
||||
"PATH=/system/bin:/system/xbin",
|
||||
"HOME=/data",
|
||||
"TERM=xterm-256color",
|
||||
"LANG=en_US.UTF-8",
|
||||
)
|
||||
|
||||
private fun candidateList(): List<Triple<String, Array<String>, Boolean>> {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val rc = TermuxInstaller.interactiveShellArgs(context)
|
||||
return listOf(
|
||||
// ⓪-A 干净环境跑 cat:能挂住 → pty 没问题
|
||||
// ⓪-B 干净环境跑我们的 bash
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ★★ 决定性实验(定位完删):让**子进程自己**把关键信息
|
||||
// **重定向到文件**(这样绕开 pty,不依赖输出通道通不通)。
|
||||
//
|
||||
// 要看的是 fd 0/1/2 到底指向什么:
|
||||
// · 指向 /dev/pts/N → 从端接上了,EIO 另有原因
|
||||
// · 指向别的东西/没有 → 从端根本没接上(那就是根因)
|
||||
// `tty` 和 `stty` 顺带验证"是不是一个真正的终端"。
|
||||
// ★ 用 **/system/bin/sh**(toybox 的 sh)而不是我们 prefix 里的:
|
||||
// 它不依赖 Termux 的库,变量最少,能干净地回答"子进程的 fd 是什么"。
|
||||
// 输出写**绝对路径**,别用 $PREFIX(那种环境里不一定会展开)。
|
||||
Triple(
|
||||
"/system/bin/sh",
|
||||
arrayOf(
|
||||
"-c",
|
||||
"{ echo '=== fds ==='; ls -l /proc/self/fd; " +
|
||||
"echo '=== tty ==='; tty; echo tty_exit=$?; " +
|
||||
"echo '=== stty ==='; stty -a 2>&1 | head -2; " +
|
||||
"echo '=== tty_nr ==='; awk '{print $7}' /proc/self/stat; " +
|
||||
"} > /data/user/0/com.doubao.lynxclone/files/childinfo.txt 2>&1; sleep 20",
|
||||
),
|
||||
true,
|
||||
),
|
||||
// ① 直接 bash + 我们自己的 rc(正常路径)
|
||||
Triple("$prefix/bin/bash", rc, true),
|
||||
// ② ★ **不带 LD_PRELOAD** 起。
|
||||
//
|
||||
// `libtermux-exec.so` 是拦 execve/open 的 .so,让二进制里写死的
|
||||
// `/data/data/com.termux/...` 在运行时被改写到我们的 prefix。
|
||||
// 但它**在 pty 里可能把 stdin 搞坏** —— 实测现象是:
|
||||
// bash 的 rc 正常跑完(那行 echo 打出来了),然后读 stdin 直接 EOF
|
||||
// 就退出(退出码 0),终端上只剩 [Process completed]。
|
||||
// 去掉它 bash 只认编译期路径(读不到 /etc/profile),
|
||||
// 但**至少能交互** —— 哪个能用用哪个。
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ③ Termux 的登录入口(有些机型上它才行;实测退出码 126)
|
||||
Triple("$prefix/bin/login", arrayOf("$prefix/bin/login", "-shell", "$prefix/bin/bash"), true),
|
||||
// ④ 最朴素的兜底:不带 preload。★ 第一个元素仍是程序名(见 interactiveShellArgs)
|
||||
Triple("$prefix/bin/bash", arrayOf("$prefix/bin/bash", "-i"), false),
|
||||
)
|
||||
}
|
||||
|
||||
private fun tryCreate(
|
||||
onTitle: (String) -> Unit,
|
||||
onExit: () -> Unit,
|
||||
): TerminalSession? {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val env = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
val baseEnv = TermuxInstaller.childEnv(context)
|
||||
|
||||
val client = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(context, "终端会话结束,退出码=${finishedSession.exitStatus}")
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
val list = candidateList()
|
||||
candidateCount = list.size
|
||||
if (candidateIndex >= list.size) {
|
||||
TermuxInstaller.trace(context, "所有起法都试过了")
|
||||
return null
|
||||
}
|
||||
val (shell, args, usePreload) = list[candidateIndex]
|
||||
if (!File(shell).exists()) {
|
||||
TermuxInstaller.trace(context, "$shell 不在,跳过")
|
||||
return tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
// 前两条候选(诊断用)走**干净环境**:只留 PATH/HOME/TERM/LANG。
|
||||
// 目的就是把"环境变量把子进程搞坏"这个可能性单独拎出来验。
|
||||
val env = when {
|
||||
candidateIndex < 0 -> cleanEnv()
|
||||
usePreload -> baseEnv
|
||||
else -> baseEnv.filterNot { s: String -> s.startsWith("LD_PRELOAD=") }
|
||||
}
|
||||
startedWith = "$shell ${args.joinToString(" ")}" + if (usePreload) "" else "(不带 preload)"
|
||||
return try {
|
||||
val created = TerminalSession(shell, home, args, env.toTypedArray(), 2000, client(onTitle, onExit))
|
||||
TermuxInstaller.trace(context, "终端会话已建:$startedWith")
|
||||
session = created
|
||||
created
|
||||
} catch (t: Throwable) {
|
||||
TermuxInstaller.trace(context, "起 $shell 抛异常:${t.javaClass.simpleName}: ${t.message}")
|
||||
tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
/**
|
||||
* ★ 秒退之后换下一种起法。
|
||||
*
|
||||
* 关键点:**"起法失败"不是靠异常发现的** ——
|
||||
* bash 起得来(构造函数不抛)、rc 也跑了,然后读 stdin 拿到 EOF 就退出。
|
||||
* 从代码角度看一切正常,只有"退出得太快"这个**事件**能说明它坏了。
|
||||
* 所以回退必须由秒退来驱动(TerminalScreen 在秒退回调里调这个)。
|
||||
*
|
||||
* @return 还有下一种就返回新会话;都用完了返回 null
|
||||
*/
|
||||
fun tryNextCandidate(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession? {
|
||||
candidateIndex += 1
|
||||
TermuxInstaller.trace(context, "换下一种起法(第 ${candidateIndex + 1} 种)")
|
||||
return tryCreate(onTitle, onExit)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线,用 Termux 的默认值 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
/**
|
||||
* 开一个登录 shell。
|
||||
*
|
||||
* ★ 会**依次试几种起法**,哪个活下来用哪个。
|
||||
* 为什么要试:pty 的从端没接上时 shell 的 stdin 立刻 EOF,
|
||||
* bash 读不到东西**直接退出(退出码 0)** —— 现象是"终端一闪就没了",
|
||||
* 而且**看不出是哪一步坏的**。分步试 + 每步落盘就能定位。
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
candidateIndex = 0
|
||||
return tryCreate(onTitle, onExit)
|
||||
?: throw IllegalStateException("$prefixPath 下没有能用的 shell")
|
||||
}
|
||||
|
||||
private val prefixPath: String get() = TermuxInstaller.prefix(context).absolutePath
|
||||
|
||||
private fun client(onTitle: (String) -> Unit, onExit: () -> Unit) = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
// ★ 这一行就是"屏幕刷新"的开关,别删(见 view 字段的注释)
|
||||
val v = view ?: return
|
||||
v.post { v.onScreenUpdated() }
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(
|
||||
context,
|
||||
"终端会话结束,退出码=${finishedSession.exitStatus} 用的=$startedWith",
|
||||
)
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
|
||||
val created = TerminalSession(
|
||||
"$prefix/bin/bash",
|
||||
home,
|
||||
// 用我们自己的 rc:Termux 的 bash 带的是编译期路径 /data/data/com.termux/...,
|
||||
// 直接当登录 shell 跑会去读别的包的 profile,报权限拒绝
|
||||
TermuxInstaller.interactiveShellArgs(context),
|
||||
env,
|
||||
2000,
|
||||
client,
|
||||
)
|
||||
session = created
|
||||
return created
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||
|
||||
785
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
785
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
@@ -0,0 +1,785 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.net.Uri
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
|
||||
/**
|
||||
* AI 主动弹出来的三个界面(都带进出动画)。
|
||||
*
|
||||
* 放在**导航之上**(见 AppRoot):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话在会议/设置页就看不到。
|
||||
*
|
||||
* 三个东西的动画各有讲究:
|
||||
* · HTML 界面 —— 从中心"长大"+ 淡入(像开一扇门),退出反向
|
||||
* · 选择弹窗 —— 从下方滑上来 + 淡入(手机上的惯例手势方向)
|
||||
* · 结束横幅 —— 从下方滑到**屏幕中间**停住,并且**留在那儿**(不自动消失)
|
||||
*/
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、AI 的 HTML 界面(show_ui) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiHtmlScreenOverlay(
|
||||
screen: AiSurface.Screen?,
|
||||
onClose: () -> Unit,
|
||||
onResult: (String) -> Unit,
|
||||
/** 等待模式:用户点了回传按钮之后自动把界面收掉(这是"用户答完了"的信号) */
|
||||
autoCloseOnResult: Boolean = false,
|
||||
) {
|
||||
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||
val shown = screen ?: last
|
||||
|
||||
// WebView 实例 + "能不能回退"。
|
||||
// ★ 拿到了 WebView 才能调 goBack();canGoBack 要轮询(WebView 没有变更回调)。
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var canGoBack by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(web, screen) {
|
||||
while (web != null && screen != null) {
|
||||
canGoBack = web?.canGoBack() == true
|
||||
kotlinx.coroutines.delay(400)
|
||||
}
|
||||
canGoBack = false
|
||||
}
|
||||
|
||||
// 系统返回键:能回退就先回退(用户点进去了一页,返回键该带他回来),
|
||||
// 不能回退才关掉整个界面 —— 比直接关掉符合直觉。
|
||||
BackHandler(enabled = screen != null) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = screen != null,
|
||||
enter = fadeIn(tween(180)) +
|
||||
scaleIn(tween(240, easing = androidx.compose.animation.core.FastOutSlowInEasing), initialScale = 0.86f),
|
||||
exit = fadeOut(tween(150)) + scaleOut(tween(180), targetScale = 0.92f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
shown.title.ifBlank { "AI 界面" },
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// 「返回上一页」只在真能回退时出现 —— 一直显示一个点了没反应的
|
||||
// 箭头比不显示更让人困惑
|
||||
AnimatedVisibility(
|
||||
visible = canGoBack,
|
||||
enter = fadeIn(tween(150)),
|
||||
exit = fadeOut(tween(120)),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { web?.goBack() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
"返回上一页",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
AiWebView(
|
||||
screen = shown,
|
||||
onResult = { value ->
|
||||
onResult(value)
|
||||
// ★ 等待模式下这一下就是"用户答完了" —— 把界面收掉,
|
||||
// 否则用户看到一个已经用完的界面还开着,会以为还能再点。
|
||||
if (autoCloseOnResult) onClose()
|
||||
},
|
||||
onClose = onClose,
|
||||
onWebView = { web = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 AI 写的 HTML。
|
||||
*
|
||||
* ## JS 开着,但 `@JavascriptInterface` 只在"我们自己那一页"暴露
|
||||
*
|
||||
* 用户要求"支持 js"。开了 JS 之后最大的风险不是 JS 本身,而是
|
||||
* **`addJavascriptInterface` 注入的那个桥**:它对**之后加载的每一个页面**
|
||||
* 都可见。AI 的页面里如果有个链接,用户点进去落到一个外部站点,
|
||||
* 那个站点的 JS 也能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
*
|
||||
* 所以这里**按 origin 收口**:
|
||||
*
|
||||
* · 初始文档用 `loadDataWithBaseURL(null, …)` 加载 —— 它的 document origin
|
||||
* 是**不透明(opaque)**的,WebView 会把它当作"没有来源"
|
||||
* · 导航到任何 **http/https** 之前,先把桥撤掉(`removeJavascriptInterface`)
|
||||
* · 外部页面在 WebView 里正常打开(用户要的"点进去"就是它),
|
||||
* 但它没有桥;而且 `onPageStarted` 里会再兜一次
|
||||
*
|
||||
* ## 依然保持关闭的那些
|
||||
*
|
||||
* · `allowFileAccess` / `allowContentAccess` —— 不让页面读本地文件
|
||||
* · `setAllowFileAccessFromFileURLs` / `setAllowUniversalAccessFromFileURLs`
|
||||
* · `mixedContentMode = NEVER` —— 不让 https 页面加载 http 资源
|
||||
*
|
||||
* ## 可点按钮的两条路都留着
|
||||
*
|
||||
* 1. `<button data-doubao-result="值">` —— App 侧字符串替换成
|
||||
* `doubao://pick?...`,由 `shouldOverrideUrlLoading` 拦。
|
||||
* **不依赖 JS**,所以页面即使 JS 出错也能用
|
||||
* 2. `Doubao.pick("值")` / `Doubao.close()` —— 给会写 JS 的模型用
|
||||
* (图表上点一个点回传、定时刷新之类)
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
private fun AiWebView(
|
||||
screen: AiSurface.Screen,
|
||||
onResult: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onWebView: (WebView) -> Unit = {},
|
||||
) {
|
||||
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||
// 记一下"桥还在不在",避免同一页里反复 remove/add
|
||||
val host = remember(screen.id) { AiWebHost() }
|
||||
host.onResult = onResult
|
||||
host.onClose = onClose
|
||||
|
||||
DisposableEffect(screen.id) {
|
||||
onDispose { host.detach() }
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
isVerticalScrollBarEnabled = true
|
||||
|
||||
/**
|
||||
* ★★ 桥的挂/摘时机 —— 这里改了两版才对,把结论记下来。
|
||||
*
|
||||
* **第一版**(错的):`loadDataWithBaseURL` 之前就 add,导航到
|
||||
* http(s) 时 remove。问题:外部页面在 `onPageStarted` 摘桥**之前**
|
||||
* 有个"已经开始加载、桥还在"的窗口期。
|
||||
*
|
||||
* **第二版**(也是错的):只在 `onPageFinished` 里判 url 是不是
|
||||
* `about:blank` 才 add。实测页面报
|
||||
* `Uncaught ReferenceError: Doubao is not defined`
|
||||
* —— `onPageFinished` 的**回调时机比页面内联 <script> 执行还晚**,
|
||||
* 脚本跑的时候桥还没挂上。
|
||||
*
|
||||
* **第三版**(现在这个):初始 load **之前就挂**(保证脚本能用到),
|
||||
* 然后靠 [AiWebHost.payloadLoaded] 这个标志挡住窗口期 ——
|
||||
* loadUrl 到别的地址时,`payloadLoaded` 已经是 true,
|
||||
* 所以立刻摘桥,外部页面**从头到尾**都碰不到它。
|
||||
*/
|
||||
addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
// 开始加载"非初始页"了 —— 说明初始页已经加载过(标志为 true),
|
||||
// 而这次是一个**导航**:立刻摘桥。
|
||||
//
|
||||
// ★ 纯锚点跳转(#xxx)不算导航,不能摘 —— 否则页面内
|
||||
// "跳到某一段"之后 JS 就废了。
|
||||
val anchorOnly = url != null && url.startsWith("about:blank#")
|
||||
if (host.payloadLoaded && !anchorOnly) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
if (!host.payloadLoaded) {
|
||||
// 初始那页加载完成。**马上补挂一次** —— 实测
|
||||
// loadDataWithBaseURL 的页面在脚本执行时桥可能还没生效,
|
||||
// 补挂之后重新 load 才稳。
|
||||
host.payloadLoaded = true
|
||||
view?.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS, null)
|
||||
return
|
||||
}
|
||||
// 之后每次加载完都探一次:**页面里有我们的标记**才重挂桥。
|
||||
//
|
||||
// ★ 为什么用"页面里有没有标记变量"而不是看 url:
|
||||
// 实测从外部页返回(goBack)时,onPageFinished 收到的 url
|
||||
// 并不是 `about:blank`,用 url 判会漏 —— 表现是
|
||||
// "点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
// 标记变量是**页面自己的属性**,页面被换掉它就没了,
|
||||
// 比 url 可靠。
|
||||
//
|
||||
// ★ 如果标记在**但桥不在**,说明这一页是我们的,
|
||||
// 而桥在上一次导航时被摘了 → 重挂。
|
||||
// 如果标记在**桥也在**,什么都不用做。
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS) { result ->
|
||||
// ★ evaluateJavascript 的回调参数是**字符串**,
|
||||
// 而且返回值经 JSON 编码("1" 带着引号)。
|
||||
// 我第一版按 Boolean 处理,条件永远不成立。
|
||||
val ok = (result ?: "").trim('"', ' ')
|
||||
if (ok == "1" && !host.bridgeAttached) {
|
||||
view.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
): Boolean {
|
||||
val u = url ?: return false
|
||||
|
||||
// ① 我们自己约定的回传协议
|
||||
if (u.startsWith("doubao://pick")) {
|
||||
val v = Uri.decode(Uri.parse(u).getQueryParameter("value") ?: "")
|
||||
if (v.isNotEmpty()) onResult(v)
|
||||
return true
|
||||
}
|
||||
if (u.startsWith("doubao://close")) {
|
||||
onClose()
|
||||
return true
|
||||
}
|
||||
|
||||
// ② http(s):**在 WebView 里打开**(用户要的"点进去")。
|
||||
// 桥会在 onPageStarted 里被摘掉(那时 payloadLoaded 已 true),
|
||||
// 所以外部站点碰不到 App。
|
||||
if (u.startsWith("http://") || u.startsWith("https://")) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
return false
|
||||
}
|
||||
|
||||
// ③ 页内锚点(#xxx)交给 WebView 自己处理
|
||||
if (u.startsWith("#")) return false
|
||||
|
||||
// ④ 别的协议(tel: / mailto: / intent: …)交给系统
|
||||
return try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(u))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||
onWebView(this)
|
||||
}
|
||||
},
|
||||
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 给 AI 页面用的 JS 桥。
|
||||
*
|
||||
* 暴露两个方法(页面上写 `Doubao.pick("值")` / `Doubao.close()`):
|
||||
*
|
||||
* · `pick(value)` —— 回传一个值,和点 `data-doubao-result` 按钮等价。
|
||||
* 适合"图表上点一个点"、"定时刷新后回传结果"这类需要脚本的场景。
|
||||
* · `close()` —— 关掉这个界面。
|
||||
*
|
||||
* ★ 方法名和 [NAME] 都刻意短且通用,因为模型要在 HTML 里手写它们;
|
||||
* 但**只暴露这两个** —— 桥能调到的越少,万一被滥用时的损失越小。
|
||||
*
|
||||
* ★ 注意:这个对象**只挂在初始那一页**上(见 [AiWebView] 的注释)。
|
||||
* 导航到外部站点时会被 `removeJavascriptInterface` 摘掉。
|
||||
*/
|
||||
class AiWebHost {
|
||||
@Volatile
|
||||
var onResult: ((String) -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onClose: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 初始那一页(AI 写的那份 HTML)加载完成了没有。
|
||||
*
|
||||
* 用来区分"初始加载"和"用户点链接导航" —— 两者都会走 `onPageStarted`,
|
||||
* 但只有后者该摘桥。见 [AiWebView] 里那段注释。
|
||||
*/
|
||||
@Volatile
|
||||
var payloadLoaded: Boolean = false
|
||||
|
||||
/** 桥现在挂着没有。重挂前要先看它,不然会重复 add。 */
|
||||
@Volatile
|
||||
var bridgeAttached: Boolean = false
|
||||
|
||||
@JavascriptInterface
|
||||
fun pick(value: String?) {
|
||||
val v = (value ?: "").trim()
|
||||
if (v.isEmpty()) return
|
||||
onResult?.invoke(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* `pick` 的别名 —— **这是"AI 自己能写进网页里的接口"**。
|
||||
*
|
||||
* AI 在它生成的 HTML 里写:
|
||||
* ```html
|
||||
* <button onclick="Doubao.sendToAi('用户选了方案 B')">方案 B</button>
|
||||
* ```
|
||||
* 那个值就会经安卓桥 POST 到内核排队,**下一轮对话时作为上下文交给模型**。
|
||||
* 也就是模型真的能知道用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 两个名字都留着(`pick` / `sendToAi`):模型有时写这个有时写那个,
|
||||
* 收两个比让它猜、猜错了整段交互失效要省事得多。
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun sendToAi(value: String?) = pick(value)
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
|
||||
/** 页面销毁时断开引用,别把 Compose 的东西一直攥着 */
|
||||
fun detach() {
|
||||
onResult = null
|
||||
onClose = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "Doubao"
|
||||
|
||||
/**
|
||||
* 往页面里写一个标记并回读 —— 用来判断"当前这一页是不是我们自己注入的"。
|
||||
*
|
||||
* ★ 走 `evaluateJavascript` 而不是看 url:实测从外部页返回时
|
||||
* `onPageFinished` 收到的 url 不是 `about:blank`,用 url 判会漏。
|
||||
* 标记是页面自己的属性,页面被换掉它就没了,可靠得多。
|
||||
*
|
||||
* 返回 "1" 表示是我们的页。
|
||||
*/
|
||||
const val PROBE_JS =
|
||||
"(function(){try{" +
|
||||
"if(!window.__doubaoAiPage){window.__doubaoAiPage=1;}" +
|
||||
"return '1';" +
|
||||
"}catch(e){return '0';}})()"
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 `data-doubao-result="x"` 变成可点的链接,再套一层骨架 */
|
||||
private fun buildAiHtml(screen: AiSurface.Screen): String {
|
||||
val body = if (screen.fullHtml) screen.html else wrapSkeleton(screen.html)
|
||||
return rewriteResultLinks(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `<button data-doubao-result="值">文字</button>` 重写成
|
||||
* `<a class="db-btn" href="doubao://pick?value=值">文字</a>`。
|
||||
*
|
||||
* ★ 用正则做单遍替换,**不引 HTML 解析器** —— 这点转换不值得多一个依赖,
|
||||
* 而且 AI 的输出是受控的(我们自己提示词里教的写法)。
|
||||
* `button` 和 `a` 两种都收,模型有时会写成链接。
|
||||
*/
|
||||
private fun rewriteResultLinks(html: String): String {
|
||||
val pattern = Regex(
|
||||
"""<(button|a)\b([^>]*?)data-doubao-result\s*=\s*["']([^"']*)["']([^>]*?)>(.*?)</\1>""",
|
||||
setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),
|
||||
)
|
||||
return pattern.replace(html) { m ->
|
||||
val value = android.net.Uri.encode(m.groupValues[3])
|
||||
val inner = m.groupValues[5]
|
||||
"""<a class="db-btn" href="doubao://pick?value=$value">$inner</a>"""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给"片段式" HTML 套一层骨架。
|
||||
*
|
||||
* 为什么要套:模型每次都要重复写 `<meta viewport>`、暗色主题背景、字体、
|
||||
* 边距 —— 既啰嗦又容易和 App 的主题打架。套一层之后它只管写内容。
|
||||
*/
|
||||
private fun wrapSkeleton(fragment: String): String = """
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 16px 16px 40px;
|
||||
background: #121317; color: #e8eaed;
|
||||
font: 15px/1.7 -apple-system, "PingFang SC", "Noto Sans CJK SC", sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
h1 { font-size: 21px; margin: 4px 0 12px; }
|
||||
h2 { font-size: 18px; margin: 20px 0 8px; }
|
||||
h3 { font-size: 16px; margin: 16px 0 6px; }
|
||||
p { margin: 8px 0; }
|
||||
a { color: #7cb0ff; }
|
||||
code, pre {
|
||||
background: #1d1f25; border-radius: 8px;
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px;
|
||||
}
|
||||
code { padding: 2px 5px; }
|
||||
pre { padding: 12px; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||
th, td { border: 1px solid #2c2f36; padding: 8px 10px; text-align: left; }
|
||||
th { background: #1b1d22; font-weight: 600; }
|
||||
blockquote {
|
||||
margin: 12px 0; padding: 8px 14px;
|
||||
border-left: 3px solid #3d4450; color: #b9bdc4;
|
||||
}
|
||||
img, svg, canvas { max-width: 100%; height: auto; }
|
||||
hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; }
|
||||
|
||||
/* ★★ 按钮 —— 这里刻意做得**非常显眼**。
|
||||
*
|
||||
* 起因:用户连着两次反馈"哪有按键,网页里的按键也点不了"、"没有一个按键能用"。
|
||||
* 实测下来**功能是好的**(点了值确实回到模型手里),问题出在**视觉**:
|
||||
*
|
||||
* · `data-doubao-result` 的按钮会被 App 改写成 `<a class="db-btn">`,
|
||||
* 拿到亮蓝整行的样式 → 看得出来能点
|
||||
* · 而 `onclick="Doubao.sendToAi(...)"` 的按钮**保持原样**,
|
||||
* 落进下面那条"普通按钮"规则 → 小灰块,在深色主题里跟正文几乎一样
|
||||
*
|
||||
* 同一屏里一半亮蓝一半灰暗,用户当然会以为"只有蓝的能点"甚至"都不能点"。
|
||||
*
|
||||
* 所以现在**所有 button / .db-btn 一律是同样显眼的实心蓝**,
|
||||
* 普通按钮那条规则删掉了。`!important` 是为了压掉模型内联的
|
||||
* `style="background:..."`(模型很爱写这个,一写就把我们的样式盖掉)。 */
|
||||
.db-btn, button, [data-doubao-result], [role=button] {
|
||||
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, button:active, [data-doubao-result]:active, [role=button]:active {
|
||||
background: #1e63d6 !important;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
/* 次要按钮(模型想要不那么抢眼的):加个 class 就能变灰 */
|
||||
.db-plain, button.db-plain {
|
||||
background: #262a31 !important;
|
||||
color: #e8eaed !important;
|
||||
border: 1px solid #3d4450 !important;
|
||||
}
|
||||
/* 两个按钮并排时用这个包一层 */
|
||||
.db-row { display: flex; gap: 10px; }
|
||||
.db-row > * { flex: 1; }
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、AI 的选择弹窗(ask_user) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiDialogOverlay(dialog: AiSurface.Dialog?, onAnswer: (List<String>, Boolean) -> Unit) {
|
||||
var last by remember { mutableStateOf<AiSurface.Dialog?>(null) }
|
||||
LaunchedEffect(dialog) { if (dialog != null) last = dialog }
|
||||
val shown = dialog ?: last
|
||||
|
||||
// 多选时先把已勾的攒起来,点「确定」才回传
|
||||
val picked = remember(dialog?.id) { mutableStateListOf<String>() }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
enter = fadeIn(tween(180)),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color(0xB3000000))
|
||||
.clickable(enabled = shown?.allowCancel == true) { onAnswer(emptyList(), true) },
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
enter = slideInVertically(tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) { it / 3 } +
|
||||
fadeIn(tween(200)) + scaleIn(tween(280), initialScale = 0.94f),
|
||||
exit = slideOutVertically(tween(200)) { it / 4 } + fadeOut(tween(150)) +
|
||||
scaleOut(tween(200), targetScale = 0.96f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 24.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(20.dp),
|
||||
) {
|
||||
Text("AI 想问你", fontSize = 12.sp, color = doubaoTextDim())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
shown.question,
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
lineHeight = 24.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("可多选", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
// 选项多时中间区域自己滚,按钮不跟着滚出去
|
||||
Column(
|
||||
Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
shown.options.forEach { opt ->
|
||||
val on = opt.value in picked
|
||||
OptionRow(
|
||||
label = opt.label,
|
||||
description = opt.description,
|
||||
selected = on,
|
||||
multiple = shown.multiple,
|
||||
onClick = {
|
||||
if (shown.multiple) {
|
||||
if (on) picked.remove(opt.value) else picked.add(opt.value)
|
||||
} else {
|
||||
onAnswer(listOf(opt.value), false)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (shown.allowCancel) {
|
||||
OutlinedButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
}
|
||||
Button(
|
||||
onClick = { onAnswer(picked.toList(), false) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("确定") }
|
||||
}
|
||||
} else if (shown.allowCancel) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
TextButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) { Text("取消") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OptionRow(
|
||||
label: String,
|
||||
description: String,
|
||||
selected: Boolean,
|
||||
multiple: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
// 选中时轻微放大 —— 比单纯变色更能让人感到"点到了"
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (selected) 1.02f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "optScale",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (selected) doubaoAccentSoft() else doubaoSurfaceAlt())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 15.sp,
|
||||
color = if (selected) doubaoAccent() else doubaoText(),
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
if (description.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(description, fontSize = 12.sp, color = doubaoTextDim(), lineHeight = 17.sp)
|
||||
}
|
||||
}
|
||||
if (multiple && selected) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("✓", fontSize = 16.sp, color = doubaoAccent())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、对话被 AI 结束 —— 屏幕中间的横幅 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* ★ 用户明确要求的样子:**屏幕中间一个横幅,写着 AI 关闭的原因**。
|
||||
*
|
||||
* 几个细节:
|
||||
* · **停在屏幕正中间**(不是顶部也不是底部)—— 这是"这次对话到此为止"
|
||||
* 这种终局状态,摆在视线中心最合适
|
||||
* · **不自动消失**。它不是提示条,是状态;消失了用户就不知道
|
||||
* 为什么发不出消息了
|
||||
* · 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
* · 只显示在与它相关的那次对话里(调用方按 conversationId 判断)
|
||||
*/
|
||||
@Composable
|
||||
fun EndedBanner(reason: String, onNewConversation: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
AnimatedVisibility(
|
||||
visible = true,
|
||||
enter = slideInVertically(
|
||||
tween(420, easing = androidx.compose.animation.core.FastOutSlowInEasing),
|
||||
) { it } + fadeIn(tween(280)) + scaleIn(tween(420), initialScale = 0.9f),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 28.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 20.dp, vertical = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.PowerSettingsNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("这次对话已结束", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
reason.ifBlank { "AI 结束了这次对话" },
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Button(
|
||||
onClick = onNewConversation,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = doubaoAccent()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("开始新对话", color = Color.White) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -112,6 +114,63 @@ fun AppRoot(
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- AI 主动弹出来的东西 ----------------
|
||||
*
|
||||
* ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 ——
|
||||
* 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。
|
||||
*
|
||||
* 顺序(后写的盖在上面):全屏网页 > 选择弹窗 > HTML 界面。
|
||||
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
AiHtmlScreenOverlay(
|
||||
screen = vm.aiScreen,
|
||||
onClose = { vm.closeAiScreen() },
|
||||
onResult = { vm.onAiScreenResult(it, vm.aiScreen?.waiting == true) },
|
||||
autoCloseOnResult = vm.aiScreen?.waiting == true,
|
||||
)
|
||||
AiDialogOverlay(
|
||||
dialog = vm.aiDialog,
|
||||
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||
)
|
||||
|
||||
// 「网页」界面(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页显示之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
AnimatedVisibility(
|
||||
visible = vm.pickUrlFrom.isNotEmpty() || vm.urlPickerOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
UrlListScreen(
|
||||
owner = "这条回复",
|
||||
urls = vm.pickUrlFrom,
|
||||
onPick = { vm.openTypedUrl(it) },
|
||||
onClose = { vm.dismissUrlPicker() },
|
||||
)
|
||||
}
|
||||
|
||||
// 全屏看网页(点消息下方「打开网页」按钮进来)
|
||||
AnimatedVisibility(
|
||||
visible = vm.webPage != null,
|
||||
enter = slideInVertically(tween(240)) { it / 5 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 6 } + fadeOut(tween(150)),
|
||||
) {
|
||||
vm.webPage?.let { url ->
|
||||
WebPageScreen(
|
||||
url = url,
|
||||
onClose = { vm.closeWebPage() },
|
||||
// 用户在网页上点选 → 发回给 AI。走的是**普通发消息**那条路
|
||||
// (所以会正常显示在对话里、正常存历史),而不是什么隐藏通道 ——
|
||||
// 用户能看见自己"发了什么",也能反悔(重新生成)。
|
||||
onSendToAi = { text ->
|
||||
vm.closeWebPage()
|
||||
vm.sendExternal(text)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.doubao.lynxclone.data.MeetingEvent
|
||||
import com.doubao.lynxclone.data.MeetingMeta
|
||||
import com.doubao.lynxclone.data.StreamEvent
|
||||
import com.doubao.lynxclone.data.ToolTrace
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -53,8 +54,194 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
/** 模型 / 思考强度面板(底部升起) */
|
||||
var modelPickerOpen by mutableStateOf(false)
|
||||
|
||||
/* -------------------- AI 主动弹出来的东西 -------------------- */
|
||||
|
||||
/**
|
||||
* AI 弹的全屏 HTML 界面(`show_ui` 工具);null 表示没有。
|
||||
*
|
||||
* 数据源是 [AiSurface](内核线程往里写),这里通过监听器同步过来 ——
|
||||
* 内核永远不直接碰 Compose。
|
||||
*/
|
||||
var aiScreen by mutableStateOf<AiSurface.Screen?>(null)
|
||||
private set
|
||||
|
||||
/** AI 弹的选择弹窗(`ask_user` 工具);null 表示没有 */
|
||||
var aiDialog by mutableStateOf<AiSurface.Dialog?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 当前对话被 AI 永久结束了 —— 界面据此把输入框换成结束横幅。
|
||||
*
|
||||
* ★ 这是从内核读回来的**落盘状态**(Conversation.ended),不是本地开关。
|
||||
*/
|
||||
var conversationEnded by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** AI 给出的结束原因(屏幕中间那个横幅上写的就是它) */
|
||||
var endedReason by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/**
|
||||
* 正在全屏看的网页(点消息下方的「打开网页」按钮进来的);null 表示没开。
|
||||
*
|
||||
* ★ 为什么要有这个独立界面,而不是让用户去点正文里那行小字:
|
||||
* 链接做成蓝色下划线**没有可发现性** —— 用户不知道能点、也不知道点了
|
||||
* 会发生什么。产品上正确的是给一个**明确的按钮**。
|
||||
*/
|
||||
var webPage by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 一条回复里提到、或用户自己输的网页;空表示不展示那个界面。
|
||||
*
|
||||
* ★ 按项目约定:**列表这种要滚动的东西不用弹窗**,用独立全屏界面。
|
||||
* 一条回复里挂五六个链接是常事,弹窗装不下、用户还得在里面滚动 ——
|
||||
* 那还不如直接开一屏。
|
||||
*/
|
||||
var pickUrlFrom by mutableStateOf<List<FoundUrl>>(emptyList())
|
||||
private set
|
||||
|
||||
/**
|
||||
* 「网页」界面开着没有。
|
||||
*
|
||||
* ★ 为什么它和 [pickUrlFrom] 要分开:**没找到链接时也要能打开这个界面**
|
||||
* (用户可能想自己输网址)。只看 `pickUrlFrom.isNotEmpty()` 的话,
|
||||
* 一条链接都没有的回复点按钮就毫无反应。
|
||||
*/
|
||||
var urlPickerOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 打开「网页」界面。
|
||||
*
|
||||
* ★★ v2.0.39 改:**只有一个链接时也走这个界面**,不再直接跳转。
|
||||
* 上一版是"1 个就直接开",于是用户没有任何确认的机会;
|
||||
* 而且他看不到自己到底要打开哪个地址。
|
||||
* 现在统一先看一眼再决定。(用户拍板:"你要单独开个按钮")
|
||||
*/
|
||||
fun openUrlPicker(urls: List<FoundUrl>) {
|
||||
pickUrlFrom = urls
|
||||
urlPickerOpen = true
|
||||
}
|
||||
|
||||
/** 用户自己输了一个网址(或从列表里挑了一个) */
|
||||
fun openTypedUrl(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty()) return
|
||||
// 没写协议就补 https —— 用户不会每次都打 https://
|
||||
val url = if (t.startsWith("http://") || t.startsWith("https://")) t else "https://$t"
|
||||
urlPickerOpen = false
|
||||
pickUrlFrom = emptyList()
|
||||
webPage = url
|
||||
}
|
||||
|
||||
fun dismissUrlPicker() {
|
||||
pickUrlFrom = emptyList()
|
||||
urlPickerOpen = false
|
||||
}
|
||||
|
||||
/** 打开一个网页(全屏界面) */
|
||||
fun openWebPage(url: String) {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return
|
||||
pickUrlFrom = emptyList() // 进网页界面时把"选哪个"收掉
|
||||
webPage = u
|
||||
}
|
||||
|
||||
fun closeWebPage() {
|
||||
webPage = null
|
||||
}
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
init {
|
||||
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
|
||||
AiSurface.subscribe { kind ->
|
||||
viewModelScope.launch {
|
||||
when (kind) {
|
||||
"screen" -> aiScreen = AiSurface.screen
|
||||
"dialog" -> aiDialog = AiSurface.dialog
|
||||
"ended" -> {
|
||||
conversationEnded = true
|
||||
refreshEndedReason()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户关掉 AI 的界面 */
|
||||
fun closeAiScreen() {
|
||||
AiSurface.closeScreen()
|
||||
aiScreen = null
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。
|
||||
*
|
||||
* 两条路,按界面是不是"等待模式"分流:
|
||||
*
|
||||
* · **等待模式**(`show_ui` 传了 `wait=true`):
|
||||
* 这个值直接作为工具的返回值交给模型 —— 模型**在同一个回合里**就拿到了,
|
||||
* 可以接着干活。所以这里不用再排队(排了反而会让模型看到重复信息)。
|
||||
*
|
||||
* · **不等待模式**(默认):
|
||||
* 模型这一轮已经答完了,所以值先排队(`/api/ui-result`),
|
||||
* 等用户下次说话时和那句话一起交给模型。
|
||||
*
|
||||
* ★ 提示语要**如实**区分这两种情况:
|
||||
* 等待模式说"已提交"(模型确实马上会用);
|
||||
* 不等待模式说"已记下,下次对话会告诉 AI" ——
|
||||
* 写成"已发送"会让用户以为模型马上回话,然后干等。
|
||||
*/
|
||||
fun onAiScreenResult(value: String, waiting: Boolean = false) {
|
||||
AiSurface.screenResult(value)
|
||||
if (waiting) {
|
||||
showHint("已提交:$value")
|
||||
return
|
||||
}
|
||||
val conv = activeConversationId
|
||||
if (conv.isBlank()) {
|
||||
showHint("已选择:$value")
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching { client.pushUiResult(conv, value) }.getOrDefault(false)
|
||||
}
|
||||
showHint(
|
||||
if (ok) {
|
||||
"已记下你的选择,下次对话会告诉 AI"
|
||||
} else {
|
||||
"选择没能送出去(内核没响应),再点一次试试"
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户在 AI 的选择弹窗里点了 */
|
||||
fun answerAiDialog(values: List<String>, cancelled: Boolean = false) {
|
||||
AiSurface.answerDialog(values, cancelled)
|
||||
aiDialog = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 把当前对话的"已结束"状态读回来。
|
||||
*
|
||||
* ★ 切换对话、刷新之后都要重新读一次 —— 上面那个监听器只在 AI **当场**
|
||||
* 结束对话时触发;用户重启 App 打开一个早就结束的对话,走的是这条路。
|
||||
*/
|
||||
private fun refreshEndedReason() {
|
||||
val id = activeConversationId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
val meta = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversationMeta(id) }
|
||||
}.getOrNull()
|
||||
conversationEnded = meta?.ended == true
|
||||
endedReason = meta?.endedReason.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
val settings get() = state.settings
|
||||
val agents: List<Agent> get() = state.agents
|
||||
val activeAgent: Agent? get() = state.activeAgent
|
||||
@@ -104,6 +291,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||
messages.clear()
|
||||
messages.addAll(list)
|
||||
// ★ 顺手读一下这次对话是不是被 AI 结束过 —— 只读 messages 是看不出来的
|
||||
// (ended 在会话对象上,不在消息里)。
|
||||
val meta = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversationMeta(id) }
|
||||
}.getOrNull()
|
||||
conversationEnded = meta?.ended == true
|
||||
endedReason = meta?.endedReason.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,9 +305,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
viewModelScope.launch {
|
||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||
refresh()
|
||||
if (conv != null) openConversation(conv.id) else {
|
||||
if (conv != null) {
|
||||
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
||||
conversationEnded = false
|
||||
endedReason = ""
|
||||
openConversation(conv.id)
|
||||
} else {
|
||||
messages.clear()
|
||||
activeConversationId = ""
|
||||
conversationEnded = false
|
||||
endedReason = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,6 +333,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
val text = draft.trim()
|
||||
if (text.isEmpty() && attachments.isEmpty()) return
|
||||
if (streaming) return
|
||||
// ★ 对话被 AI 结束后就挡住 —— 界面上的输入框已经换成了横幅,
|
||||
// 但发送按钮/回车/历史入口都可能绕过界面判断,所以在**这里**再拦一道。
|
||||
if (conversationEnded) {
|
||||
showHint("这次对话已结束,请开一个新对话")
|
||||
return
|
||||
}
|
||||
|
||||
val files = attachments.toList()
|
||||
draft = ""
|
||||
@@ -147,6 +354,25 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
runChat(lastUser.content, emptyList())
|
||||
}
|
||||
|
||||
/**
|
||||
* 从别处(现在只有"网页点选")发一条消息给 AI。
|
||||
*
|
||||
* ★ 走的是**和手打消息完全一样的那条路** —— 所以它会正常出现在对话里、
|
||||
* 正常存进历史、也能被"重新生成"。
|
||||
* 刻意不做成什么"隐藏上下文注入":用户得看得见自己发了什么,
|
||||
* 否则模型回一句"你选的这个……"而用户根本不知道自己选过什么。
|
||||
*/
|
||||
fun sendExternal(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty() || streaming) return
|
||||
if (conversationEnded) {
|
||||
showHint("这次对话已结束,请开一个新对话")
|
||||
return
|
||||
}
|
||||
screen = Screen.Chat
|
||||
runChat(t, emptyList())
|
||||
}
|
||||
|
||||
private fun runChat(text: String, files: List<Attachment>) {
|
||||
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||
@@ -464,6 +690,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
||||
saveSettings(mapOf("security" to json))
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 界面能力(show_ui / ask_user / end_conversation)开关。
|
||||
*
|
||||
* ★ 必须写成**嵌套对象** `{"enabled": true}`,不能写成布尔 ——
|
||||
* 内核 `ui_tools_enabled()` 认的就是 dict 里的 enabled。
|
||||
* 而 `patchToJson` 会把 Map 递归转成 JSONObject(见那个函数的注释:
|
||||
* 不转的话会变成字符串 `"{enabled=true}"`,内核每次读配置都抛 TypeError)。
|
||||
* 所以这里传 Map 进去,让它走那条已经修好的转换路径。
|
||||
*/
|
||||
fun saveUiTools(enabled: Boolean) {
|
||||
saveSettings(mapOf("uiTools" to mapOf("enabled" to enabled)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -309,7 +309,27 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
if (vm.conversationEnded) {
|
||||
/**
|
||||
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
* `Modifier.weight(1f)` 让它占掉原本给消息列表之外的全部剩余空间,
|
||||
* 横幅在**这块区域的中心**(也就是视觉上的屏幕中下部)。
|
||||
* 要的是"正中间",但顶部还有标题栏、下面还有输入法安全区,
|
||||
* 放在这块剩余区域的中心在观感上才是居中的。
|
||||
*
|
||||
* 输入框在此处**整个不渲染** —— 用户看到的就是"这儿没得输了",
|
||||
* 而不是一个点了没反应的框。
|
||||
*/
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
EndedBanner(
|
||||
reason = vm.endedReason,
|
||||
onNewConversation = { vm.newTopic() },
|
||||
)
|
||||
}
|
||||
} else {
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
|
||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||
@@ -593,6 +613,35 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
vm.showHint("已复制")
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
/**
|
||||
* ★★「打开网页」—— 用户明确要求"你要单独开个按钮"。
|
||||
*
|
||||
* 以前只有正文里那行蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会怎样。
|
||||
* 现在改成:回复里只要有 http(s) 链接,这里就出现一个按钮。
|
||||
*
|
||||
* · 只有 1 个链接 → 直接打开
|
||||
* · 多个链接 → 进「链接列表」全屏界面让用户挑
|
||||
* (按项目约定:列表这种要滚动的东西**不用弹窗**)
|
||||
*
|
||||
* ★ 链接是从 markdown 里现算的(`extractUrls`),不额外存状态 ——
|
||||
* 存了就要担心和 content 不同步(重新生成、编辑之后)。
|
||||
*
|
||||
* ★★ 按钮**无条件显示**(v2.0.39 改)。
|
||||
* 上一版是"这条回复里有链接才显示",于是:
|
||||
* · extractUrls 漏认写法时(裸 URL 就漏)按钮整个不见了
|
||||
* · 而且用户根本无从知道"这条能不能开网页"
|
||||
* 现在永远在,顺带还能自己在里面输网址 —— 它就是个浏览器入口。
|
||||
*/
|
||||
val urls = remember(msg.content) { extractUrls(msg.content) }
|
||||
RoundIconButton(
|
||||
Icons.Filled.Language,
|
||||
if (urls.isEmpty()) "打开网页" else "打开网页(${urls.size} 个链接)",
|
||||
tint = if (urls.isEmpty()) null else Doubao.Blue,
|
||||
) {
|
||||
vm.openUrlPicker(urls)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
if (speaking) {
|
||||
// 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停"
|
||||
RoundIconButton(
|
||||
|
||||
@@ -77,6 +77,71 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
|
||||
@Composable
|
||||
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
|
||||
|
||||
/** 主色(AI 界面/弹窗里强调"选中"用) */
|
||||
@Composable
|
||||
fun doubaoAccent() = if (isDark()) Color(0xFF6EA8FF) else Doubao.Blue
|
||||
|
||||
/** 主色的浅底(选中项的背景) */
|
||||
@Composable
|
||||
fun doubaoAccentSoft() = if (isDark()) Color(0xFF1B2A44) else Color(0xFFEAF1FF)
|
||||
|
||||
/** 比 surface 稍亮/稍暗一档的容器底色(弹窗里的选项行) */
|
||||
@Composable
|
||||
fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg
|
||||
|
||||
/** 三级文字色(比 secondary 更淡,用于说明小字) */
|
||||
@Composable
|
||||
fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary
|
||||
|
||||
/* ------------------------------ 打开链接 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 在系统浏览器里打开一个链接。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接**以前渲染成蓝色下划线但没有绑点击** ——
|
||||
* 看着像能点,点了完全没反应。用户会以为是"链接坏了"。
|
||||
* (这个坑是用户问"网页在哪点开"时才查出来的:我一直在讲 AI 弹的界面,
|
||||
* 而最容易想到的"点链接"其实一直是坏的。)
|
||||
*
|
||||
* ## 为什么用系统浏览器而不是应用内 WebView
|
||||
*
|
||||
* AI 弹出的那个界面里点链接是**应用内**打开的(用户明确要的"可再点进去")。
|
||||
* 但聊天正文里的链接不一样:那里没有"返回 AI 界面"这个上下文,
|
||||
* 在应用内开一个 WebView 会让用户迷失(返回键行为说不清)。
|
||||
* 交给系统浏览器,行为标准、有历史、有关闭 —— 对正文链接更合适。
|
||||
*
|
||||
* ★ 必须 try/catch:设备上可能没有浏览器(精简 ROM),
|
||||
* 或者链接协议没人能处理,那会抛 ActivityNotFoundException。
|
||||
* 不接的话点一下链接 App 就崩。
|
||||
*/
|
||||
fun openInBrowser(context: android.content.Context, url: String): Boolean {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return false
|
||||
val uri = try {
|
||||
android.net.Uri.parse(u)
|
||||
} catch (_: Throwable) {
|
||||
return false
|
||||
}
|
||||
// 只放行有 scheme 的绝对地址;相对地址点了没意义,还会让 Intent 解析失败
|
||||
if (uri.scheme.isNullOrBlank()) return false
|
||||
|
||||
return try {
|
||||
context.startActivity(
|
||||
android.content.Intent(android.content.Intent.ACTION_VIEW, uri)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.w("DoubaoLink", "打不开 $u:${t.javaClass.simpleName}: ${t.message}")
|
||||
android.widget.Toast
|
||||
.makeText(context, "打不开这个链接", android.widget.Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 动画 ------------------------------ */
|
||||
|
||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||
|
||||
@@ -13,14 +13,19 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.ExperimentalTextApi
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
@@ -99,17 +104,19 @@ fun MarkdownText(
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
is MdBlock.Heading -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
@@ -147,12 +154,14 @@ fun MarkdownText(
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
is MdBlock.Paragraph -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,6 +265,118 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** 一条回复里提到的一个网页 */
|
||||
data class FoundUrl(
|
||||
/** 完整地址 */
|
||||
val url: String,
|
||||
/** 模型给链接写的文字(`[文字](url)` 里的那个),没有就是空串 */
|
||||
val label: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 从 markdown 里抽出所有网页地址(去重、保序,带上链接文字)。
|
||||
*
|
||||
* ## ★★ 重写过一版:原来漏了 7/11 种写法
|
||||
*
|
||||
* 上一版是手写扫描器,**只认 `](` 紧挨着的 markdown 链接**。
|
||||
* 实测(`scripts/probe-extract-urls.py`)漏掉这些:
|
||||
*
|
||||
* · **裸 URL** —— `见 https://example.com`(**模型最常这么写**)
|
||||
* · `[文字] (地址)` —— 中英混排时中间常有空格
|
||||
* · `<https://example.com>` —— 尖括号包裹
|
||||
* · 中文标点紧跟着的 URL —— `见(https://…)。`
|
||||
* · 换行里的裸 URL
|
||||
* · `www.example.com`
|
||||
*
|
||||
* 后果不是"少显示一个链接",而是 **`extractUrls` 返回空 → 整个
|
||||
* 「打开网页」按钮都不显示**(用户报的"还是没有"就是这个)。
|
||||
*
|
||||
* 现在改成**正则扫全文**,两类都收:markdown 链接 + 裸 URL。
|
||||
*
|
||||
* ★ 只认 http/https。`[文档](docs/x.md)` 这种相对路径在手机上点了没意义,
|
||||
* 不算"网页"(剪掉尾巴上的中文标点和右括号,别把 `)。` 吞进地址里)。
|
||||
*/
|
||||
fun extractUrls(markdown: String): List<FoundUrl> {
|
||||
if (!markdown.contains("http://") && !markdown.contains("https://")) return emptyList()
|
||||
val out = LinkedHashSet<String>()
|
||||
val labels = HashMap<String, String>()
|
||||
|
||||
// ① markdown 链接:[文字](地址),允许中间有空格、文字里有方括号
|
||||
RE_MD_LINK.findAll(markdown).forEach { m ->
|
||||
val label = m.groupValues[1].trim().trim('[', ']')
|
||||
val url = cleanUrl(m.groupValues[2])
|
||||
if (url.isNotEmpty()) {
|
||||
if (label.isNotEmpty()) labels.putIfAbsent(url, label)
|
||||
out.add(url)
|
||||
}
|
||||
}
|
||||
|
||||
// ② 裸 URL / 尖括号包裹的 URL
|
||||
RE_BARE_URL.findAll(markdown).forEach { m ->
|
||||
val url = cleanUrl(m.value)
|
||||
if (url.isNotEmpty()) out.add(url)
|
||||
}
|
||||
|
||||
return out.map { FoundUrl(it, labels[it] ?: "") }
|
||||
}
|
||||
|
||||
/**
|
||||
* 剪掉 URL 尾巴上不属于地址的字符。
|
||||
*
|
||||
* ★ 必须做:中文回复里 URL 后面常紧跟 `)。`、`,`、`】`,
|
||||
* 不剪的话地址里会带上这些,打开必然 404。
|
||||
* 左右括号要配对判断(`.../a_(b)` 这种地址本身带括号,不能一刀切)。
|
||||
*/
|
||||
private fun cleanUrl(raw: String): String {
|
||||
var s = raw.trim().trim('<', '>', '"', '\'', '`')
|
||||
// 尾部的中文标点/空白一律剪掉
|
||||
s = s.trimEnd('。', ',', '、', ';', ':', '!', '?', ')', '】', '》', '」', '』', '…', '.', ',', ';', ':', '!', '?')
|
||||
// 去掉不配对的右括号
|
||||
while (s.endsWith(")") && s.count { it == ')' } > s.count { it == '(' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
while (s.endsWith("]") && s.count { it == ']' } > s.count { it == '[' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
if (!s.startsWith("http://") && !s.startsWith("https://")) return ""
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* markdown 链接 `[文字](地址)`。
|
||||
*
|
||||
* ★★ 地址部分用 **`(?:[^\s()]|\([^\s()]*\))+`** 而不是 `[^\s)]+`。
|
||||
*
|
||||
* 起因是一条维基百科地址:`https://en.wikipedia.org/wiki/A_(b)`
|
||||
*
|
||||
* · 用 `[^\s)]+` 的话,它在 `A_(b` 处被第一个 `)` 截断 ——
|
||||
* 然后外层那个 `\)` 匹配的是**地址里那个右括号**,
|
||||
* 于是算出来的地址是 `https://en.wikipedia.org/wiki/A_(b`(缺一个括号、点开 404)
|
||||
* · 而且裸 URL 规则会再匹配一次,得到另一个截断版本 →
|
||||
* **同一个链接在列表里出现两次,两个都不对**
|
||||
*
|
||||
* "平衡括号"这个写法让右括号只能以完整 `(…)` 的形式出现在地址里,
|
||||
* 所以维基那种地址能整个吃到,而 markdown 的收尾括号仍然能正确识别。
|
||||
*
|
||||
* ★ 文字部分用 `[^\]\n]*` 而不是 `.*?` —— 后者在长回复里可能跨行吞掉一大段。
|
||||
*/
|
||||
private val RE_MD_LINK =
|
||||
Regex("""\[([^\]\n]{1,200})]\s*\(\s*(https?://(?:[^\s()]|\([^\s()]*\))+)\s*\)""")
|
||||
|
||||
/**
|
||||
* 裸 URL(含尖括号包裹)。
|
||||
*
|
||||
* ★★ 同样用"平衡括号"写法。两种错法都踩过:
|
||||
*
|
||||
* · 允许右括号(`[^\s]+`)→ `[x](https://a.com)` 会被**再匹配一次**,
|
||||
* 同一条链接算出两个不同地址(一个还带多余的右括号)
|
||||
* · 完全禁止括号(`[^\s()]+`)→ `.../wiki/A_(b)` 被截断成 `.../wiki/A_`
|
||||
*
|
||||
* 到空白或中文标点为止(中文回复里 URL 后面常紧跟 `)。`、`,`)。
|
||||
*/
|
||||
private val RE_BARE_URL =
|
||||
Regex("""<?https?://(?:[^\s<>()\[\]{}()【】「」『』,。;:!?、]|\([^\s()]*\))+>?""")
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
@@ -264,8 +385,19 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*
|
||||
* ★ 这是个 `@Composable`:链接要用 `withLink(...)` 挂点击,
|
||||
* 而那个 API 是 composable 的(它内部要拿 `LocalTextLinkScope`)。
|
||||
*
|
||||
* ★ 还要 `@OptIn(ExperimentalTextApi::class)` —— `withLink` 标了实验 API。
|
||||
* 不 opt-in 的话报的是 `Unresolved reference 'withLink'`(不是"需要 opt-in"),
|
||||
* 很容易误判成"这个版本没有这个 API"。我是把 aar 拆开 javap 看了注解才确认的。
|
||||
*/
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString {
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
@Composable
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
val ctx = LocalContext.current
|
||||
return buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
when {
|
||||
@@ -325,8 +457,40 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
val url = text.substring(open + 1, end).trim()
|
||||
/**
|
||||
* ★★ 给链接**真正绑上点击**。
|
||||
*
|
||||
* 以前这里只有颜色和下划线,**没有 clickable** ——
|
||||
* 看着像能点、点了完全没反应。用户会以为"链接坏了"。
|
||||
* (这是用户问"网页在哪点开"时才查出来的:我一直在讲
|
||||
* AI 弹的那个界面,而最容易想到的"点链接"一直是坏的。)
|
||||
*
|
||||
* ★ 用 `withLink(LinkAnnotation.Url(...))`:这是 Compose 1.7
|
||||
* 起的方式,和 `Text()` 直接配合(不需要 ClickableText),
|
||||
* 而且**不需要在外部套 pointerInput 去算点击落在哪个字符上**。
|
||||
* 那个老办法要自己遍历 annotation 范围,容易算错。
|
||||
*/
|
||||
if (url.isNotEmpty()) {
|
||||
withLink(
|
||||
LinkAnnotation.Url(
|
||||
url = url,
|
||||
styles = TextLinkStyles(
|
||||
style = SpanStyle(
|
||||
color = linkColor,
|
||||
textDecoration = TextDecoration.Underline,
|
||||
),
|
||||
),
|
||||
linkInteractionListener = { link ->
|
||||
val target = (link as? LinkAnnotation.Url)?.url ?: url
|
||||
openInBrowser(ctx, target)
|
||||
},
|
||||
),
|
||||
) { append(label) }
|
||||
} else {
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
@@ -339,4 +503,7 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.termux.TermuxMirror
|
||||
|
||||
/**
|
||||
* 换源界面(全屏,不是弹窗)。
|
||||
*
|
||||
* ★ 为什么做成界面:源列表有五个,每个还要显示说明和当前选中状态 ——
|
||||
* 弹窗装不下(见 AGENTS.md 的界面约定)。
|
||||
*
|
||||
* ★ 为什么需要这个功能:Termux 官方源在国内基本连不上,
|
||||
* `pkg install` 会卡住或超时,用户会以为"内置的 Termux 坏了"。
|
||||
* 换源这件事**每次重装都要做**,手敲 sed 又容易把 apt 配置写坏。
|
||||
*/
|
||||
@Composable
|
||||
fun MirrorScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
// 每次进界面重读一次:用户可能手改过 sources.list
|
||||
var current by remember { mutableStateOf(TermuxMirror.current(context)) }
|
||||
var toast by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "软件源",
|
||||
subtitle = "换完记得跑一次 pkg update",
|
||||
onBack = onBack,
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"Termux 官方源(packages.termux.dev)在国内基本连不上,表现是 " +
|
||||
"pkg install 卡在 Reading package lists 或者直接超时。" +
|
||||
"换一个国内镜像就好。",
|
||||
color = doubaoTextSecondary(),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
|
||||
if (toast.isNotBlank()) {
|
||||
Surface(
|
||||
color = Color(0xFF16301F),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
) {
|
||||
Text(
|
||||
toast,
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("选一个源")
|
||||
|
||||
TermuxMirror.MIRRORS.forEach { m ->
|
||||
val selected = current?.id == m.id
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (selected) Doubao.Blue.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.clickable {
|
||||
val n = try {
|
||||
TermuxMirror.set(context, m)
|
||||
} catch (t: Throwable) {
|
||||
toast = "换源失败:${t.message}"
|
||||
return@clickable
|
||||
}
|
||||
current = m
|
||||
toast = "已切到 ${m.name}(写入 $n 条),去终端跑一次 pkg update"
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
m.name,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
|
||||
color = if (selected) Doubao.Blue else Color(0xFF1F2328),
|
||||
)
|
||||
Text(
|
||||
m.note,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Text(
|
||||
m.host,
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary().copy(alpha = 0.7f),
|
||||
)
|
||||
}
|
||||
if (selected) {
|
||||
Text("✓ 当前", fontSize = 11.sp, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("换完之后")
|
||||
Text(
|
||||
"去终端敲:\n" +
|
||||
" pkg update\n" +
|
||||
"\n" +
|
||||
"update 会重新拉索引,第一次可能要等十几秒。" +
|
||||
"如果报错,换另一个源再试 —— 镜像偶尔会同步中断。",
|
||||
color = doubaoTextSecondary(),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 19.sp,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -72,6 +73,12 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
|
||||
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
|
||||
|
||||
// AI 界面能力的开关。改一下立刻存 —— 这个开关不需要"应用"按钮,
|
||||
// 用户拨完就想生效(跟下面的权限白名单不一样,那个要挑一堆再一起提交)。
|
||||
var uiToolsOn by remember(vm.settings.uiToolsEnabled) {
|
||||
mutableStateOf(vm.settings.uiToolsEnabled)
|
||||
}
|
||||
|
||||
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
|
||||
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
@@ -105,6 +112,50 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
|
||||
/* ============ ⓪ AI 界面能力(show_ui / ask_user / end_conversation)============
|
||||
*
|
||||
* 为什么单独一个卡片、而且默认关:这三个工具会让 AI **主动往用户脸上
|
||||
* 弹东西**(HTML 界面、选择弹窗),甚至**把对话封掉** ——
|
||||
* 属于"打扰性"能力,不该装好就默认打开。
|
||||
*/
|
||||
SettingsCard("AI 界面能力") {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("允许 AI 弹出界面和弹窗", fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"打开后 AI 才能用这三个工具。关掉时它们对模型完全隐藏。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 17.sp,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = uiToolsOn,
|
||||
onCheckedChange = {
|
||||
uiToolsOn = it
|
||||
vm.saveUiTools(it)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormHint(
|
||||
"· show_ui —— AI 自己写 HTML 弹一个全屏界面(图表、卡片、对比表)\n" +
|
||||
"· ask_user —— 弹一个选择框,等用户选完再继续(最多 120 秒)\n" +
|
||||
"· end_conversation —— AI 永久结束这次对话。屏幕中间会出现一条" +
|
||||
"写着原因的横幅,之后要开新对话才能继续",
|
||||
)
|
||||
if (!uiToolsOn) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"当前:关闭(模型看不到这三个工具)",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== ① 工具权限 ==================== */
|
||||
SettingsCard("工具权限") {
|
||||
SegmentedOptions(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
@@ -19,9 +20,13 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.view.doOnLayout
|
||||
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||
import com.termux.view.TerminalView
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
@@ -43,19 +48,104 @@ fun TerminalScreen(
|
||||
val context = LocalContext.current
|
||||
val terminal = remember { TermuxTerminal(context) }
|
||||
var title by remember { mutableStateOf("termux") }
|
||||
/** pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台 */
|
||||
/**
|
||||
* pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台。
|
||||
*
|
||||
* ★ 这里**不再静默切换**:以前一旦判定失败就直接换成"命令框",
|
||||
* 用户只看到"怎么不是终端",完全不知道发生了什么(真踩过)。
|
||||
* 现在会**明说原因**并给"重试",终端仍然是主界面。
|
||||
*/
|
||||
var ptyFailed by remember { mutableStateOf(false) }
|
||||
var failReason by remember { mutableStateOf("") }
|
||||
var startedAt by remember { mutableStateOf(0L) }
|
||||
var showMirror by remember { mutableStateOf(false) }
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { terminal.destroy() }
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后 2 秒内就结束,说明 bash 拿不到 tty(stdin 直接 EOF)
|
||||
// 换源是独立全屏界面(源列表 + 说明装不进弹窗)
|
||||
if (showMirror) {
|
||||
MirrorScreen(onBack = { showMirror = false })
|
||||
return
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后很快就结束,说明 shell 拿不到 tty(stdin 直接 EOF)。
|
||||
//
|
||||
// ★ 要**连续两次**都秒退才认输。一次秒退可能是别的原因
|
||||
// (比如用户手滑按了 Ctrl+D 把 shell 退了),
|
||||
// 直接切到命令框会让"终端一闪就变成命令框",比不切还懵。
|
||||
var fastExits by remember { mutableStateOf(0) }
|
||||
/** 换起法之后要 +1,让 AndroidView 的 update 重新跑一遍去 attach 新会话 */
|
||||
var sessionTick by remember { mutableStateOf(0) }
|
||||
|
||||
// ★ 必须**在这里读一下** sessionTick。
|
||||
// Compose 只跟踪「组合期间读过」的状态:只在 update 那个 lambda 里读不算
|
||||
// (lambda 是布局阶段才跑的),于是 sessionTick 变了也不重组、update 不重跑、
|
||||
// 换了起法之后新会话**永远接不上** —— 表现是"屏幕停在旧会话的
|
||||
// [Process completed],打字没反应"。(真踩到了:修语法时把 key() 去掉,订阅也丢了。)
|
||||
val tickNow = sessionTick
|
||||
|
||||
/**
|
||||
* 重置 Termux 环境。
|
||||
*
|
||||
* ★ 为什么需要:装坏了自己救不回来。dpkg 的数据库和真实文件一旦不一致
|
||||
* (比如在修好 apt 路径之前试着装过包),后面 `pkg install` 会一直报
|
||||
* `E: Internal Error, No file name for ...` 或 `1 not fully installed or removed`,
|
||||
* **用户在界面上没有任何办法恢复**,只能清 App 数据 —— 那会把会议、设置、
|
||||
* 自定义节点全丢掉。有了这个,重置的代价只是"重下一次运行环境"。
|
||||
*
|
||||
* 删的是 `files/usr` + `files/home`;**不碰** kernel-data 和 nodes。
|
||||
*/
|
||||
var showResetConfirm by remember { mutableStateOf(false) }
|
||||
var resetting by remember { mutableStateOf(false) }
|
||||
var resetMsg by remember { mutableStateOf("") }
|
||||
|
||||
/**
|
||||
* 真 Termux 冲突(见下面横幅的注释)。
|
||||
*
|
||||
* ★ 为什么放在 `LaunchedEffect` 里而不是直接在组合里算:
|
||||
* 这个判断要**起一个进程跑 `dpkg --version`**,直接在组合里做会
|
||||
* 每帧跑一次。它是 IO,必须挪到副作用里,而且只查一次。
|
||||
*/
|
||||
var realTermuxConflict by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(termuxReady) {
|
||||
if (termuxReady) {
|
||||
realTermuxConflict = withContext(Dispatchers.IO) {
|
||||
runCatching { TermuxInstaller.hasRealTermuxConflict(context) }
|
||||
.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
val onSessionExit = {
|
||||
if (startedAt > 0 && System.currentTimeMillis() - startedAt < 2000) {
|
||||
ptyFailed = true
|
||||
TermuxInstaller.trace(context, "pty 不可用(会话秒退),切换到命令控制台")
|
||||
val quick = startedAt > 0 && System.currentTimeMillis() - startedAt < 900
|
||||
if (quick) {
|
||||
fastExits += 1
|
||||
TermuxInstaller.trace(context, "会话秒退(第 $fastExits 次)")
|
||||
// ★ 秒退 → **换下一种起法**。
|
||||
//
|
||||
// 关键:bash 起不来这件事**不会抛异常**(构造函数成功、rc 也跑了,
|
||||
// 然后 stdin EOF 就退出)。所以回退只能靠"退出得太快"这个事件驱动,
|
||||
// 不能靠 try/catch。试完所有起法才认输切命令控制台。
|
||||
val next = try {
|
||||
terminal.tryNextCandidate(onTitle = { title = it }, onExit = { })
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
if (next != null) {
|
||||
startedAt = System.currentTimeMillis()
|
||||
sessionTick += 1 // 触发 AndroidView update 去 attach 新会话
|
||||
TermuxInstaller.trace(context, "已切到:${terminal.startedWith}")
|
||||
// ★ 起法全试完 → **立刻**切命令控制台。之前要求"连续两次秒退",
|
||||
// 但候选有四种,全试完要好几秒,这期间屏幕是**全黑的**(上一种会话的画面
|
||||
// 刚被清掉、新的又没起来)—— 用户看到的就是"卡住了"。宁可切早点。
|
||||
} else {
|
||||
ptyFailed = true
|
||||
failReason = "几种起法都试过了,shell 一起来就退出(拿不到 tty)。"
|
||||
TermuxInstaller.trace(context, "pty 不可用,切成命令控制台:$failReason")
|
||||
}
|
||||
} else {
|
||||
fastExits = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +160,51 @@ fun TerminalScreen(
|
||||
}
|
||||
Text(title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 换源:国内用官方源基本装不了东西,这是最常用的一个入口
|
||||
TextButton(onClick = { showMirror = true }) {
|
||||
Text("源", color = Color(0xFF9BE7B4), fontSize = 13.sp)
|
||||
}
|
||||
// 重置环境:装坏了(dpkg 数据库和文件不一致)时的唯一自救入口。
|
||||
// 放在换源旁边 —— 出问题时这两个是最先要点的。
|
||||
TextButton(onClick = { showResetConfirm = true }) {
|
||||
Text("重置", color = Color(0xFFFFB4A9), fontSize = 13.sp)
|
||||
}
|
||||
|
||||
// ---------------- 重置确认 + 进度 ----------------
|
||||
if (showResetConfirm) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showResetConfirm = false },
|
||||
title = { Text("重置 Termux 环境?") },
|
||||
text = {
|
||||
Text(
|
||||
"会把内置运行环境(约 95MB)删掉重新解压。\n\n" +
|
||||
"什么时候需要:pkg install 报 Internal Error、\n" +
|
||||
"not fully installed,或者终端起不来又查不出原因。\n\n" +
|
||||
"**会议、设置、智能体、自定义节点都不会动**," +
|
||||
"只有装在 Termux 里的包(python 之类)会没。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showResetConfirm = false
|
||||
resetting = true
|
||||
resetMsg = "正在准备…"
|
||||
Thread {
|
||||
val ok = TermuxInstaller.reset(context) { msg ->
|
||||
resetMsg = msg
|
||||
}
|
||||
resetting = false
|
||||
resetMsg = if (ok) "重置完成,重新打开终端即可" else "重置失败,看看 termux-install.log"
|
||||
}.start()
|
||||
}) { Text("重置", color = Color(0xFFD93025)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showResetConfirm = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
IconButton(onClick = {
|
||||
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
|
||||
terminal.session?.write("\u0003".toByteArray(), 0, 1)
|
||||
@@ -99,7 +234,7 @@ fun TerminalScreen(
|
||||
Surface(color = Color(0xFF16301F), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Termux 已内置 · ${TermuxInstaller.prefix(context).absolutePath}\n" +
|
||||
"试试点上面的 + 装东西:pkg install python nodejs-lts",
|
||||
"装东西前先换源(右上角「源」),官方源国内连不上",
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
@@ -108,9 +243,68 @@ fun TerminalScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 真 Termux 的检测结果 —— v2.0.33 起**不再提示卸载**。
|
||||
*
|
||||
* 以前这里是一条红色横幅,让用户去卸载真 Termux,因为
|
||||
* Termux 仓库里的 dpkg 有个**编译死的配置目录**:
|
||||
*
|
||||
* dpkg: error: error opening configuration directory
|
||||
* "/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
|
||||
*
|
||||
* 那个目录"不存在"dpkg 会跳过、"存在但打不开"就直接死,
|
||||
* 而两个 App 同时装着就必然是后者 —— 从应用这侧无解。
|
||||
*
|
||||
* **现在从根上修掉了**:装的是我们自编的 dpkg,配置目录改成
|
||||
* 运行时从 `/proc/self/exe` 反推,指向自己所在的前缀。
|
||||
* 所以真 Termux 在不在场都无所谓,横幅也就没必要了。
|
||||
*
|
||||
* 配方见 `android/termux-dpkg/README.md`。
|
||||
* 安装逻辑在 `TermuxInstaller.installOwnDpkg`。
|
||||
*
|
||||
* ★ 这里不再渲染任何界面 —— 只在日志里记一笔,方便排查。
|
||||
* 保留这个变量和检测(`hasRealTermuxConflict`)是因为
|
||||
* 万一自编 dpkg 没装成功(比如 jniLibs 里那份坏了),
|
||||
* 日志里能看到"真 Termux 在场",好定位。
|
||||
*/
|
||||
LaunchedEffect(termuxReady, realTermuxConflict) {
|
||||
if (termuxReady && realTermuxConflict) {
|
||||
Log.i("DoubaoTerminal", "检测到真 Termux 在场 —— v2.0.33 起不影响使用(自编 dpkg)")
|
||||
}
|
||||
}
|
||||
|
||||
// ★ pty 失败要**明说**,别让用户以为"这软件就只有命令框"
|
||||
if (termuxReady && ptyFailed) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
"真终端起不来:$failReason\n" +
|
||||
"下面先用命令控制台顶着(同一条 Termux bash,只是没有 tty," +
|
||||
"所以 vim/top 这类全屏程序不能用)。",
|
||||
color = Color(0xFFFFD08A),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
TextButton(onClick = {
|
||||
ptyFailed = false
|
||||
failReason = ""
|
||||
startedAt = 0
|
||||
terminal.destroy()
|
||||
}) { Text("重试真终端") }
|
||||
TextButton(onClick = { showMirror = true }) { Text("换软件源") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 终端本体 ----------------
|
||||
if (termuxReady && ptyFailed) {
|
||||
// pty 用不了 → 命令控制台(跑的是同一条 Termux bash,只是没有 tty)
|
||||
//
|
||||
// ★ 上面那条橙色横幅会说明原因 + 给"重试真终端",
|
||||
// 不能让用户莫名其妙地从终端变成命令框。
|
||||
Box(Modifier.weight(1f).fillMaxWidth().background(Color(0xFF14161A))) {
|
||||
CommandConsole(
|
||||
onRun = { command, done ->
|
||||
@@ -130,17 +324,54 @@ fun TerminalScreen(
|
||||
setTextSize(28)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
// ★ 把 view 交给会话:`onTextChanged` 要靠它调 `onScreenUpdated()`
|
||||
// 去重画。不接的话屏幕永远不动 —— pty 通了、bash 活着、
|
||||
// 输出也解析了,**但一个像素都不刷新**(这个坑刚踩到)。
|
||||
terminal.view = this
|
||||
// ★ 点一下就弹软键盘。
|
||||
//
|
||||
// 之前 `onSingleTapUp` 里是一句空代码(`(e.source)`),
|
||||
// 点了什么都不会发生 —— 用户的原话是"输入不了"。
|
||||
// TerminalView 是普通 View,直接请求焦点 + 叫输入法就行。
|
||||
setOnClickListener {
|
||||
requestFocus()
|
||||
val imm = ctx.getSystemService(Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager
|
||||
imm?.showSoftInput(this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
// 读一下 tickNow:它变了说明换过起法,这次 update 要把新会话接上
|
||||
@Suppress("UNUSED_EXPRESSION") tickNow
|
||||
try {
|
||||
val session = terminal.session ?: run {
|
||||
startedAt = System.currentTimeMillis()
|
||||
terminal.createSession(onTitle = { title = it }, onExit = onSessionExit)
|
||||
}
|
||||
if (view.currentSession !== session) {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
// ★★ attach **必须等布局完成**。
|
||||
//
|
||||
// Termux 的 `TerminalSession` 构造函数**只存字段、不启动子进程**:
|
||||
// 子进程是在 `initializeEmulator(columns, rows, ...)` 里调
|
||||
// `JNI.createSubprocess(...)` 建的,而它由 `TerminalView.attachSession()`
|
||||
// 触发(内部拿 view 的宽高算行列数)。
|
||||
//
|
||||
// 在 `AndroidView.update` 里直接 attach 时 view 往往还没量过尺寸,
|
||||
// 于是 rows/columns = 0 → pty 建成 **0 列** →
|
||||
// shell 一起来就结束(退出码 0、几十毫秒),屏幕只剩 [Process completed]。
|
||||
// **这就是那个找了很久的"pty 拿不到 tty"。**
|
||||
//
|
||||
// doOnLayout 保证"量过了再 attach"。
|
||||
val doAttach = Runnable {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
}
|
||||
if (view.width > 0 && view.height > 0) {
|
||||
doAttach.run()
|
||||
} else {
|
||||
view.doOnLayout { doAttach.run() }
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
title = "会话启动失败:${t.message}"
|
||||
@@ -171,6 +402,18 @@ fun TerminalScreen(
|
||||
) {
|
||||
data class Key(val label: String, val bytes: String)
|
||||
val keys = listOf(
|
||||
// ★★ ENTER 放**第一个**,而且必须发 `\r`(CR)不是 `\n`(LF)。
|
||||
//
|
||||
// 终端里的"回车"是 **CR**:行规程(line discipline)靠 `\r`
|
||||
// 判定"这一行输入完了"。发 `\n` 的话光标会往下走一格,
|
||||
// 但**命令不会执行** —— 用户的原话就是"回车不了"。
|
||||
//
|
||||
// (Termux 自己的 TerminalView 也把输入法的回车转成 `\r`,
|
||||
// 见 TerminalView.java:401。)
|
||||
//
|
||||
// 另外它原来排在最后,被横向滚动**顶出屏幕**了,等于没有。
|
||||
// 回车是终端里按得最多的键,必须第一眼就能看到。
|
||||
Key("ENTER", "\r"),
|
||||
Key("ESC", "\u001b"),
|
||||
Key("TAB", "\t"),
|
||||
Key("CTRL+C", "\u0003"),
|
||||
@@ -184,7 +427,6 @@ fun TerminalScreen(
|
||||
Key("|", "|"),
|
||||
Key("/", "/"),
|
||||
Key("-", "-"),
|
||||
Key("ENTER", "\n"),
|
||||
)
|
||||
keys.forEach { key ->
|
||||
Surface(
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.TouchApp
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/**
|
||||
* ★★ 全屏看网页 —— 由一个**明确的按钮**打开,不靠去点正文里的小字。
|
||||
*
|
||||
* ## 为什么单独做这个界面
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接做成蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会发生什么(是开浏览器?还是在应用里开?)。
|
||||
* 用户的原话是"你要单独开个按钮" —— 对,产品上正确的就是给个按钮。
|
||||
*
|
||||
* 所以:消息操作栏里出现一个「打开网页」按钮(只有回复里真有链接才出现),
|
||||
* 点开就是这里 —— 一个像样的浏览器界面,而不是把用户丢给系统浏览器
|
||||
* (那样他就离开 App 了,回来还得重新找对话)。
|
||||
*
|
||||
* ## 和 AI 那个 `show_ui` 界面的区别
|
||||
*
|
||||
* `show_ui` 是 **AI 写的 HTML**,我们注入内容、页面里只有它写的东西
|
||||
* 这里 是**真的在浏览互联网**,用户能点链接、能返回、能前进
|
||||
*
|
||||
* 两者都需要 JS,但**桥只有 `show_ui` 那边有** —— 这里浏览的是外部网站,
|
||||
* 绝不能让它碰到 App 的接口(所以这个 WebView 里没有任何
|
||||
* `addJavascriptInterface`)。
|
||||
*
|
||||
* ## 安全
|
||||
*
|
||||
* 文件访问 / 跨域访问 / 混合内容全部关闭。没有注入任何 JS 桥。
|
||||
* 这是"浏览器",就该按浏览器的方式隔离。
|
||||
*
|
||||
* ## 点选模式(把网页上的东西回传给 AI)
|
||||
*
|
||||
* 顶部有个「点选」按钮。打开之后页面上的可点元素会被描上虚线边框,
|
||||
* 用户点哪个就把哪个的**文字/链接/位置**记下来,出现在底部确认条上,
|
||||
* 用户点「发给 AI」才真的发出去(点错了不至于白跑一轮模型)。
|
||||
*
|
||||
* ★ 实现上**没有挂 JS 桥** —— 用的是"注入脚本写进数组 + Kotlin 主动轮询取走",
|
||||
* 数据只从页面流向 App。理由见 [WebPick] 的注释:这里浏览的是外部网站,
|
||||
* 挂桥等于把 App 的内部接口交给互联网上任意一个站点。
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
fun WebPageScreen(
|
||||
url: String,
|
||||
onClose: () -> Unit,
|
||||
onSendToAi: (String) -> Unit = {},
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var title by remember(url) { mutableStateOf("") }
|
||||
var canBack by remember { mutableStateOf(false) }
|
||||
var canFwd by remember { mutableStateOf(false) }
|
||||
var progress by remember { mutableStateOf(0) }
|
||||
|
||||
/** 点选模式开着没有 */
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
|
||||
/**
|
||||
* 用户选中/填写的条目(**累积**)。
|
||||
*
|
||||
* ★ 累积而不是点一条发一条:用户可能在页面上选好几处、填几个框,
|
||||
* 然后一起问"这些对不对"。分开发会触发好几轮模型调用,又慢又费 token。
|
||||
*/
|
||||
val picked = remember { mutableStateListOf<PickedElement>() }
|
||||
|
||||
// WebView 没有"导航状态变了"的回调,只能轮询。
|
||||
// 400ms 在真机上完全够用(页面前进后退是用户动作,不是动画)。
|
||||
LaunchedEffect(web) {
|
||||
while (web != null) {
|
||||
canBack = web?.canGoBack() == true
|
||||
canFwd = web?.canGoForward() == true
|
||||
delay(400)
|
||||
}
|
||||
}
|
||||
|
||||
// 点选模式下:每次加载完注入一次;然后每 500ms 取一次队列。
|
||||
//
|
||||
// ★ 为什么要"每次加载完注入":用户点链接跳到新页面(或页面自己跳),
|
||||
// 新文档里没有我们注入的脚本,不重注就没法点了。
|
||||
LaunchedEffect(web, picking) {
|
||||
if (!picking || web == null) {
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
while (true) {
|
||||
delay(500)
|
||||
val w = web ?: break
|
||||
// evaluateJavascript 的返回值经 JSON 编码:脚本返回字符串 'xxx',
|
||||
// 这里拿到的是 "\"xxx\"" —— 所以要解两层
|
||||
w.evaluateJavascript(WebPick.DRAIN_JS) { raw ->
|
||||
val parsed = decodeJsonString(raw)
|
||||
if (parsed.isBlank() || parsed == "[]") return@evaluateJavascript
|
||||
runCatching {
|
||||
val arr = org.json.JSONArray(parsed)
|
||||
for (i in 0 until arr.length()) {
|
||||
val obj = arr.optJSONObject(i) ?: continue
|
||||
picked.add(
|
||||
PickedElement(
|
||||
summary = WebPick.describe(obj),
|
||||
kind = obj.optString("kind", "click"),
|
||||
url = obj.optString("url"),
|
||||
pageTitle = obj.optString("title").ifBlank { title },
|
||||
raw = obj.toString(),
|
||||
),
|
||||
)
|
||||
}
|
||||
// 只留最近 30 条,别让用户在页面上乱点把内存堆满
|
||||
while (picked.size > 30) picked.removeAt(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 系统返回键:先回退网页,退不了了才关界面
|
||||
BackHandler(enabled = true) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 6.dp, end = 6.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowBack, "后退", canBack) { web?.goBack() }
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowForward, "前进", canFwd) { web?.goForward() }
|
||||
NavIcon(Icons.Filled.Refresh, "刷新", true) { web?.reload() }
|
||||
|
||||
// 标题:能拿到网页 title 就用它,拿不到退回落 host ——
|
||||
// 只显示一长串 URL 在手机窄屏上没法看
|
||||
Column(Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||
Text(
|
||||
title.ifBlank { hostOf(url) },
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (title.isNotBlank()) {
|
||||
Text(
|
||||
hostOf(url),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NavIcon(Icons.Filled.OpenInNew, "用系统浏览器打开", true) {
|
||||
openInBrowser(ctx, web?.url ?: url)
|
||||
}
|
||||
NavIcon(Icons.Filled.Close, "关闭", true) { onClose() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 「点选」开关 —— 打开后能在网页上点东西回传给 AI。
|
||||
*
|
||||
* ★ 做成一条**常驻的横条**而不是顶部一个图标:
|
||||
* 这个能力不看说明根本发现不了(用户得先知道"能点选"才会去找按钮)。
|
||||
* 横条上写清楚现在是什么状态、点了会发生什么。
|
||||
*/
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(if (picking) doubaoAccentSoft() else doubaoCard())
|
||||
.clickable {
|
||||
if (picking) {
|
||||
web?.evaluateJavascript(WebPick.UNINSTALL_JS, null)
|
||||
picking = false
|
||||
picked.clear()
|
||||
} else {
|
||||
picking = true
|
||||
}
|
||||
}
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.TouchApp,
|
||||
null,
|
||||
tint = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
if (picking) "点选已开启 —— 点网页上任意元素,内容会带回给 AI" else "点选:把网页上的内容带回给 AI",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (picking) "关闭" else "开启",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
// 加载进度:细一条,不占地方但能让人知道"在动"
|
||||
AnimatedVisibility(
|
||||
visible = progress in 1..99,
|
||||
enter = fadeIn(tween(120)),
|
||||
exit = fadeOut(tween(300)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(progress / 100f)
|
||||
.height(2.dp)
|
||||
.background(doubaoAccent()),
|
||||
)
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { c ->
|
||||
WebView(c).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true // 正常浏览器行为
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = true
|
||||
settings.builtInZoomControls = true
|
||||
settings.displayZoomControls = false
|
||||
settings.userAgentString = settings.userAgentString + " DoubaoClone"
|
||||
|
||||
// ★ 这个 WebView 里**不挂任何 JS 桥** ——
|
||||
// 浏览的是外部网站,绝不能让它碰到 App 的接口。
|
||||
// (点选回传走的是"页面写队列 + 我们主动 evaluateJavascript 取",
|
||||
// 数据单向,页面没有办法主动调 App。见 WebPick 的注释。)
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, u: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, u, favicon)
|
||||
progress = 5
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, u: String?) {
|
||||
super.onPageFinished(view, u)
|
||||
progress = 100
|
||||
title = view?.title.orEmpty()
|
||||
// ★ 用户点链接跳到新页面(或页面自己跳)之后,
|
||||
// 新文档里没有我们注入的脚本 —— 点选模式就失效了。
|
||||
// 所以每次加载完补注一次(脚本自己防重)。
|
||||
if (picking) view?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
}
|
||||
}
|
||||
webChromeClient = object : android.webkit.WebChromeClient() {
|
||||
override fun onProgressChanged(view: WebView?, newProgress: Int) {
|
||||
progress = newProgress
|
||||
}
|
||||
|
||||
override fun onReceivedTitle(view: WebView?, t: String?) {
|
||||
if (!t.isNullOrBlank()) title = t
|
||||
}
|
||||
}
|
||||
loadUrl(url)
|
||||
web = this
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* 底部确认条:用户点中了什么,以及「发给 AI / 取消」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*/
|
||||
/**
|
||||
* 底部确认条:用户攒了哪些"选了/写了"的内容,以及
|
||||
* 「发给 AI」「清空」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持**累积多条**再一起发 —— 用户在页面上选几处、填几个框,
|
||||
* 最后一起问"这些对不对"。分开发会跑好几轮模型。
|
||||
*/
|
||||
AnimatedVisibility(
|
||||
visible = picked.isNotEmpty(),
|
||||
enter = slideInVertically(tween(220)) { it } + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(tween(180)) { it } + fadeOut(tween(120)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"已选 ${picked.size} 条,会一起发给 AI:",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"清空",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoAccent(),
|
||||
modifier = Modifier.clickable { picked.clear() },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// 条目多了要能滚 —— 但只占一段固定高度,别把网页挤没了
|
||||
Column(
|
||||
Modifier
|
||||
.heightIn(max = 120.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
picked.forEach { p ->
|
||||
Text(
|
||||
"· " + p.summary,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(11.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
androidx.compose.material3.OutlinedButton(
|
||||
onClick = { picked.clear() },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
androidx.compose.material3.Button(
|
||||
onClick = {
|
||||
onSendToAi(WebPick.buildReport(picked.toList()))
|
||||
picked.clear()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("发给 AI") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `evaluateJavascript` 的返回值是**经 JSON 编码的字符串**(脚本返回 `'abc'`
|
||||
* 时 Kotlin 拿到的是 `"\"abc\""`)。
|
||||
*
|
||||
* ★ 这个坑踩过两次([AiWebView] 的探针、这里),所以抽成一个函数,
|
||||
* 并在名字上把"要解两层"这件事写出来。
|
||||
*/
|
||||
private fun decodeJsonString(raw: String?): String {
|
||||
val s = (raw ?: "").trim()
|
||||
if (s.isEmpty() || s == "null") return ""
|
||||
return try {
|
||||
if (s.startsWith("\"")) org.json.JSONTokener(s).nextValue() as? String ?: "" else s
|
||||
} catch (_: Throwable) {
|
||||
s.trim('"')
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavIcon(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
desc: String,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
// 不能点的时候**也要占位**(否则顶部栏的图标会左右跳),
|
||||
// 但变淡 + 不响应点击
|
||||
.clickable(enabled = enabled) { onClick() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
icon,
|
||||
desc,
|
||||
tint = if (enabled) doubaoText() else doubaoTextDim().copy(alpha = 0.35f),
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 URL 里取主机名(显示用)。解析不了就原样返回。 */
|
||||
private fun hostOf(url: String): String = try {
|
||||
android.net.Uri.parse(url).host ?: url
|
||||
} catch (_: Throwable) {
|
||||
url
|
||||
}
|
||||
|
||||
/**
|
||||
* 「网页」—— **独立全屏界面**,不是弹窗。
|
||||
*
|
||||
* ## 为什么不用 AlertDialog
|
||||
*
|
||||
* 项目约定:**列表这种要滚动的东西不用弹窗**。一条回复里挂五六个链接是常事,
|
||||
* 弹窗一屏只装得下三四个,用户得在弹窗里滚动 —— 那还不如直接开一屏。
|
||||
* 而且弹窗盖住对话,用户没法一边看着回复一边挑链接。
|
||||
*
|
||||
* ## ★★ 自己输网址(v2.0.39 加)
|
||||
*
|
||||
* 用户的原话是"**你要单独开个按钮**"。既然它是个按钮,那它就不该只在
|
||||
* "这条回复恰好有链接"时才有用 —— 现在里面能直接输网址,
|
||||
* 它就是一个**浏览器入口**,任何时候按都有意义。
|
||||
* (另一个原因:`extractUrls` 曾经漏认写法,导致按钮整个不显示,
|
||||
* 用户根本不知道这功能存在。)
|
||||
*
|
||||
* 顶栏按项目约定:`← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun UrlListScreen(
|
||||
owner: String,
|
||||
urls: List<FoundUrl>,
|
||||
onPick: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
var typed by remember { mutableStateOf("") }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("网页", onBack = onClose) {
|
||||
if (urls.isNotEmpty()) {
|
||||
Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
/* ---------- 自己输网址(永远在最上面,入口要显眼)---------- */
|
||||
item {
|
||||
Column {
|
||||
Text("输入网址", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
singleLine = true,
|
||||
placeholder = { Text("example.com", fontSize = 14.sp) },
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 15.sp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
androidx.compose.material3.Button(
|
||||
onClick = { onPick(typed) },
|
||||
enabled = typed.isNotBlank(),
|
||||
) { Text("打开") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 这条回复里找到的链接 ---------- */
|
||||
if (urls.isNotEmpty()) {
|
||||
item {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// ★ 一定要写 ${owner} 而不是 $owner:紧跟中文时 Kotlin 会把
|
||||
// 后面那几个汉字当成变量名的一部分(`$owner里提到的网页` 会
|
||||
// 被解析成一个叫「owner里提到的网页」的标识符,报未解析引用)。
|
||||
Text("${owner}里提到的网页:", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
items(urls.size) { index ->
|
||||
val u = urls[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onPick(u.url) }
|
||||
.padding(horizontal = 14.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
/**
|
||||
* ★ 主标题优先用**模型给链接写的文字**。
|
||||
*
|
||||
* 以前只显示 host,于是同一域名的两条链接
|
||||
* (`https://example.com` 和
|
||||
* `https://example.com/index-zh`)
|
||||
* 看起来**一模一样**,用户根本分不出该点哪个。
|
||||
* 模型的链接文字就是为了区分它们而写的。
|
||||
*/
|
||||
Text(
|
||||
u.label.ifBlank { hostOf(u.url) },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
u.url,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
370
android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt
Normal file
370
android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt
Normal file
@@ -0,0 +1,370 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★★★ 在**真实网页**上点选,把点到的内容回传给 AI。
|
||||
*
|
||||
* ## 为什么不用 `@JavascriptInterface` 桥
|
||||
*
|
||||
* `show_ui` 那个界面里我们挂了 `Doubao` 桥,但那只挂在**我们自己注入的那一页**上,
|
||||
* 一导航到外部站点就摘掉了(见 [AiWebView] 的注释)。
|
||||
*
|
||||
* 这里不同:**用户就是在浏览外部网站**,全程都在别人的页面上。
|
||||
* 要是挂桥,等于把 App 的内部接口暴露给互联网上任意一个站点 —— 绝对不能这么干。
|
||||
*
|
||||
* ## 改用"单向队列 + 主动轮询"
|
||||
*
|
||||
* ```
|
||||
* 注入的脚本(页面里) Kotlin 侧
|
||||
* ──────────────────── ──────────────
|
||||
* 用户点了 → 写进 window.__doubaoPicks
|
||||
* setInterval 每 500ms
|
||||
* evaluateJavascript("取走队列")
|
||||
* ← 拿到 JSON
|
||||
* ```
|
||||
*
|
||||
* 数据**只从页面流向 App**,而且只有这一个取数入口(`evaluateJavascript`)。
|
||||
* 页面**没有任何办法**主动调用 App —— 它只能往一个数组里塞东西,
|
||||
* 而那个数组的内容是我们主动去读的、并且读之前会做类型和长度校验。
|
||||
*
|
||||
* ★ 注意 `evaluateJavascript` 的返回值经 JSON 编码,所以脚本里用
|
||||
* `JSON.stringify(...)` 返回**字符串**,Kotlin 这边再解一层。
|
||||
* (这个坑在 [AiWebView] 那边也踩过。)
|
||||
*/
|
||||
object WebPick {
|
||||
|
||||
/** 队列变量名。用不常见的名字,尽量不和页面自己的变量撞。 */
|
||||
private const val QUEUE = "__doubaoPicks"
|
||||
|
||||
/**
|
||||
* 注入的脚本。
|
||||
*
|
||||
* 做三件事:
|
||||
* 1. 给页面上**真正的链接/按钮**加虚线高亮(视觉提示)
|
||||
* 2. 捕获点击(**捕获阶段**,抢在页面自己的 handler 前面)
|
||||
* 3. 把点到的元素信息写进队列,并阻止这次跳转
|
||||
*
|
||||
* ★★ 改过一版:从"只能点可点元素"改成"**点哪儿抓哪儿**"。
|
||||
*
|
||||
* 第一版只给 `a,button,[role=button],...` 这些**看着能点**的元素加框,
|
||||
* 点击也只认这些。实测在 example.com 上**一个都标不出来** ——
|
||||
* 那页全是纯文本,没有任何按钮链接,于是"点选模式"看起来完全没生效。
|
||||
*
|
||||
* 我的假设错了:用户想点的不一定是"可点元素",他想点的就是
|
||||
* **页面上任意一段内容**("把这段告诉 AI")。
|
||||
* 所以现在点击用 `elementFromPoint` 抓,**点哪儿抓哪儿**;
|
||||
* 虚线框降级成纯视觉提示,不再限制能点什么。
|
||||
*
|
||||
* ★ 为什么用捕获阶段 + `preventDefault`:
|
||||
* 如果一个链接上挂着页面的点击统计脚本,冒泡阶段再加我们的监听就晚了。
|
||||
* 捕获阶段先拿到,`stopPropagation` 之后页面完全不知道被点过,
|
||||
* 也就不会跳走 —— 用户点一下是"选中",不是"跳转"。
|
||||
*
|
||||
* ★ 用 IIFE 包起来 + 可重复注入(先看有没有装过):
|
||||
* 每次页面加载完都会注入一遍,不防重会叠出好几层监听,
|
||||
* 一次点击写好几条重复记录。
|
||||
*/
|
||||
val INSTALL_JS: String = """
|
||||
(function () {
|
||||
if (window.__doubaoPickInstalled) { return '1'; }
|
||||
window.__doubaoPickInstalled = 1;
|
||||
window.$QUEUE = [];
|
||||
|
||||
// 只用来**画虚线框**(提示哪些是链接/按钮)。点击不受它限制。
|
||||
var HINT_SEL = 'a,button,[role=button],input,select,textarea,label,summary';
|
||||
|
||||
function visible(el) {
|
||||
if (!el || !el.getBoundingClientRect) { return false; }
|
||||
var r = el.getBoundingClientRect();
|
||||
if (r.width < 8 || r.height < 8) { return false; }
|
||||
var s = window.getComputedStyle(el);
|
||||
return s.display !== 'none' && s.visibility !== 'hidden' && s.opacity !== '0';
|
||||
}
|
||||
|
||||
function textOf(el) {
|
||||
var t = (el.innerText || el.textContent || el.value || el.getAttribute('aria-label')
|
||||
|| el.getAttribute('title') || el.getAttribute('placeholder') || '');
|
||||
t = t.replace(/\s+/g, ' ').trim();
|
||||
return t.slice(0, 300);
|
||||
}
|
||||
|
||||
function mark() {
|
||||
var list = document.querySelectorAll(HINT_SEL);
|
||||
for (var i = 0; i < list.length && i < 400; i++) {
|
||||
var el = list[i];
|
||||
if (el.__doubaoMarked || !visible(el)) { continue; }
|
||||
el.__doubaoMarked = 1;
|
||||
el.style.outline = '2px dashed rgba(76,141,255,.75)';
|
||||
el.style.outlineOffset = '1px';
|
||||
el.style.cursor = 'pointer';
|
||||
}
|
||||
return list.length;
|
||||
}
|
||||
|
||||
function onClick(e) {
|
||||
// ★★ 点哪儿抓哪儿:优先用坐标取元素,**不要求它"看起来能点"**。
|
||||
//
|
||||
// 第一版是"从 e.target 往上找最近的可点元素",找不到就退回 e.target ——
|
||||
// 在纯文本页面上用户点一段话,抓到的是最里层的 <b>/<span>,
|
||||
// 甚至可能是个没文字的容器。用坐标取到的是**用户真正看到的那个块**。
|
||||
var el = null;
|
||||
try {
|
||||
if (e.clientX || e.clientY) {
|
||||
el = document.elementFromPoint(e.clientX, e.clientY);
|
||||
}
|
||||
} catch (err) { el = null; }
|
||||
if (!el) { el = e.target; }
|
||||
|
||||
// 取到的可能是很里层的小元素(一个 <b>、一个 <span>)。
|
||||
// 往上走几层,让选中的是"一整段有意义的内容"而不是一个词。
|
||||
var hop = 0;
|
||||
while (el && el.parentElement && hop < 3) {
|
||||
var t = (el.innerText || el.textContent || '').trim();
|
||||
// 文字够多就停 —— 说明这一层已经是个完整段落了
|
||||
if (t.length >= 12) { break; }
|
||||
// 或者这一层本身就是链接/按钮,那也停(点链接当然要抓链接)
|
||||
if (el.matches && el.matches(HINT_SEL)) { break; }
|
||||
el = el.parentElement; hop++;
|
||||
}
|
||||
if (!el || el === document.documentElement) { el = e.target; }
|
||||
|
||||
var rec = {
|
||||
tag: (el.tagName || '').toLowerCase(),
|
||||
text: textOf(el),
|
||||
href: el.href || '',
|
||||
id: el.id || '',
|
||||
cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120),
|
||||
path: (function () {
|
||||
var p = [], n = el, d = 0;
|
||||
while (n && n.tagName && d < 4) {
|
||||
var s = n.tagName.toLowerCase();
|
||||
if (n.id) { s += '#' + n.id; }
|
||||
else if (typeof n.className === 'string' && n.className) {
|
||||
s += '.' + n.className.trim().split(/\s+/).slice(0, 2).join('.');
|
||||
}
|
||||
p.unshift(s); n = n.parentElement; d++;
|
||||
}
|
||||
return p.join(' > ');
|
||||
})(),
|
||||
title: document.title || '',
|
||||
url: location.href || '',
|
||||
kind: 'click'
|
||||
};
|
||||
window.$QUEUE.push(rec);
|
||||
|
||||
// 选中效果:给点到的那个元素一个实线高亮,然后褪成虚线
|
||||
try {
|
||||
el.style.outline = '3px solid #4c8dff';
|
||||
setTimeout(function () { el.style.outline = '2px dashed rgba(76,141,255,.75)'; }, 700);
|
||||
} catch (err) {}
|
||||
|
||||
// ★ 关键:拦掉这次点击 —— 用户是"选中"不是"跳转"。
|
||||
// 不拦的话点个链接页面就跳走了,用户根本来不及看"已选中"提示。
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户**写了什么** —— 表单输入 / 下拉选择 / 勾选框。
|
||||
*
|
||||
* ★ 用户明确要求"让 AI 知道用户选择了什么、**写了什么**"。
|
||||
* 光有"点了什么"不够:填表场景里真正重要的是填进去的内容。
|
||||
*
|
||||
* ★ 用 input/change 的**冒泡阶段**(不用捕获):这类事件页面自己也要处理
|
||||
* (自动补全、字数统计),拦掉会破坏页面功能。我们只是**旁听**,不干预。
|
||||
*
|
||||
* ★ 同一个输入框连续打字会触发很多次 input —— 每 600ms 合并一次,
|
||||
* 否则用户打十个字会往队列里塞十条,报告变得没法看。
|
||||
*/
|
||||
var pending = {};
|
||||
function labelOf(el) {
|
||||
var s = el.getAttribute('aria-label') || el.getAttribute('placeholder')
|
||||
|| el.getAttribute('name') || el.id || '';
|
||||
if (!s) {
|
||||
var lab = el.closest ? el.closest('label') : null;
|
||||
if (lab) { s = (lab.innerText || '').trim().slice(0, 60); }
|
||||
}
|
||||
if (!s && el.previousElementSibling) {
|
||||
s = (el.previousElementSibling.innerText || '').trim().slice(0, 60);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function flush(key) {
|
||||
var el = pending[key];
|
||||
if (!el) { return; }
|
||||
delete pending[key];
|
||||
var val = '';
|
||||
if (el.type === 'checkbox' || el.type === 'radio') { val = el.checked ? '已勾选' : '未勾选'; }
|
||||
else { val = (el.value || '').slice(0, 500); }
|
||||
if (!val) { return; }
|
||||
window.$QUEUE.push({
|
||||
kind: 'input',
|
||||
tag: (el.tagName || '').toLowerCase(),
|
||||
type: el.type || '',
|
||||
label: labelOf(el),
|
||||
text: val,
|
||||
href: '',
|
||||
id: el.id || '',
|
||||
cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120),
|
||||
path: '',
|
||||
title: document.title || '',
|
||||
url: location.href || ''
|
||||
});
|
||||
}
|
||||
|
||||
function onInput(e) {
|
||||
var el = e.target;
|
||||
if (!el || !el.tagName) { return; }
|
||||
var t = (el.tagName || '').toLowerCase();
|
||||
if (t !== 'input' && t !== 'textarea' && t !== 'select') { return; }
|
||||
var key = (el.id || '') + '|' + (el.name || '') + '|' +
|
||||
(el.getAttribute('placeholder') || '') + '|' + (el.type || '');
|
||||
pending[key] = el;
|
||||
if (el.__doubaoDebounce) { clearTimeout(el.__doubaoDebounce); }
|
||||
el.__doubaoDebounce = setTimeout(function () { flush(key); }, 600);
|
||||
}
|
||||
|
||||
document.addEventListener('input', onInput, false);
|
||||
document.addEventListener('change', onInput, false);
|
||||
// 失焦时立刻结算(用户填完就去点别的地方了,不等那 600ms)
|
||||
document.addEventListener('blur', function (e) {
|
||||
var el = e.target;
|
||||
if (!el || !el.tagName) { return; }
|
||||
var key = (el.id || '') + '|' + (el.name || '') + '|' +
|
||||
(el.getAttribute('placeholder') || '') + '|' + (el.type || '');
|
||||
flush(key);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('click', onClick, true);
|
||||
|
||||
// 动态加载的页面(下拉刷新、无限滚动)也要能点 —— 隔一会儿重新标一次
|
||||
var ticks = 0;
|
||||
var timer = setInterval(function () {
|
||||
mark(); ticks++;
|
||||
if (ticks > 40) { clearInterval(timer); }
|
||||
}, 1500);
|
||||
|
||||
mark();
|
||||
return '1';
|
||||
})()
|
||||
"""
|
||||
|
||||
/**
|
||||
* 取走队列(取完清空)。
|
||||
*
|
||||
* ★ 一定要"取走"而不是"读":读的话每次轮询都会把同一条记录
|
||||
* 重复报上来,用户点一下会触发十几次。
|
||||
*/
|
||||
val DRAIN_JS: String = """
|
||||
(function () {
|
||||
try {
|
||||
var q = window.$QUEUE || [];
|
||||
window.$QUEUE = [];
|
||||
return JSON.stringify(q.slice(0, 20));
|
||||
} catch (e) { return '[]'; }
|
||||
})()
|
||||
"""
|
||||
|
||||
/** 撤销高亮 + 拆掉监听(退出点选模式时调) */
|
||||
val UNINSTALL_JS: String = """
|
||||
(function () {
|
||||
try {
|
||||
window.__doubaoPickInstalled = 0;
|
||||
window.$QUEUE = [];
|
||||
var list = document.querySelectorAll('[style]');
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var el = list[i];
|
||||
if (el.__doubaoMarked) {
|
||||
el.style.outline = '';
|
||||
el.style.outlineOffset = '';
|
||||
el.style.cursor = '';
|
||||
el.__doubaoMarked = 0;
|
||||
}
|
||||
}
|
||||
return '1';
|
||||
} catch (e) { return '0'; }
|
||||
})()
|
||||
"""
|
||||
|
||||
/**
|
||||
* 把一条记录整理成给模型看的一行字。
|
||||
*
|
||||
* ★ 刻意做成**紧凑的一行**,而不是把整个 JSON 丢给模型:
|
||||
* 模型需要的是"用户干了什么",不是 DOM 的所有细节。
|
||||
* 附带页面标题和 URL,帮它知道用户在哪个页面操作的。
|
||||
*
|
||||
* ★ 分两种 `kind`:
|
||||
* · `click` —— 用户**点了/选了**一个元素(链接、按钮、一段文字)
|
||||
* · `input` —— 用户**写了**内容(输入框、下拉、勾选框)
|
||||
* 用户的原话是"让 AI 知道用户选择了什么、写了什么",就是这两类。
|
||||
*/
|
||||
fun describe(json: JSONObject): String {
|
||||
val parts = mutableListOf<String>()
|
||||
val kind = json.optString("kind", "click")
|
||||
val text = json.optString("text").trim()
|
||||
val tag = json.optString("tag")
|
||||
val type = json.optString("type")
|
||||
val label = json.optString("label").trim()
|
||||
val href = json.optString("href")
|
||||
val id = json.optString("id")
|
||||
val path = json.optString("path")
|
||||
|
||||
if (kind == "input") {
|
||||
val what = if (type == "checkbox" || type == "radio") "勾选" else "填写"
|
||||
parts.add("用户$what:${text.ifEmpty { "(空)" }}")
|
||||
if (label.isNotEmpty()) parts.add("字段:$label")
|
||||
parts.add("控件:<$tag" + (if (type.isNotEmpty()) " type=$type" else "") + ">")
|
||||
} else {
|
||||
if (text.isNotEmpty()) parts.add("内容:$text")
|
||||
parts.add("元素:<$tag>" + (if (id.isNotEmpty()) " #$id" else ""))
|
||||
if (href.isNotEmpty()) parts.add("链接:$href")
|
||||
if (path.isNotEmpty()) parts.add("位置:$path")
|
||||
}
|
||||
return parts.joinToString(";")
|
||||
}
|
||||
|
||||
/**
|
||||
* 把多条记录汇总成一段给模型的话。
|
||||
*
|
||||
* ★ 一次性发送多条(而不是点一条发一条):
|
||||
* 用户可能在页面上选了好几处、填了几个框,然后一起问"这些对不对"。
|
||||
* 分开发会触发好几轮模型调用,既慢又费 token。
|
||||
*/
|
||||
fun buildReport(items: List<PickedElement>): String = buildString {
|
||||
append("我在网页上")
|
||||
val clicks = items.count { it.kind != "input" }
|
||||
val inputs = items.count { it.kind == "input" }
|
||||
val bits = mutableListOf<String>()
|
||||
if (clicks > 0) bits.add("选了 $clicks 处")
|
||||
if (inputs > 0) bits.add("填了 $inputs 处")
|
||||
append(bits.joinToString("、").ifEmpty { "选了一些东西" })
|
||||
append(":\n")
|
||||
items.forEachIndexed { i, it ->
|
||||
append("${i + 1}. ${it.summary}\n")
|
||||
}
|
||||
val first = items.firstOrNull()
|
||||
if (first != null && first.url.isNotBlank()) append("\n页面:${first.url}")
|
||||
if (first != null && first.pageTitle.isNotBlank()) append("\n标题:${first.pageTitle}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 点选模式下用户选中/填写、但**还没决定要不要发给 AI** 的那一条。
|
||||
*
|
||||
* ★ 为什么要中间这一步(而不是点了就直接发):
|
||||
* 用户可能点错了元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而且模型会基于一个错误的前提回答。让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持累积多条:用户可以连着点好几处、填几个框,最后一起发。
|
||||
*/
|
||||
data class PickedElement(
|
||||
val summary: String,
|
||||
/** click / input —— 是"点了什么"还是"写了什么" */
|
||||
val kind: String,
|
||||
val url: String,
|
||||
val pageTitle: String,
|
||||
val raw: String,
|
||||
)
|
||||
@@ -101,6 +101,9 @@ public final class TerminalSession extends TerminalOutput {
|
||||
|
||||
/** Inform the attached pty of the new size and reflow or initialize the emulator. */
|
||||
public void updateSize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
|
||||
android.util.Log.i("DoubaoTermux", "updateSize cols=" + columns + " rows=" + rows
|
||||
+ " cell=" + cellWidthPixels + "x" + cellHeightPixels
|
||||
+ " emulator=" + (mEmulator != null));
|
||||
if (mEmulator == null) {
|
||||
initializeEmulator(columns, rows, cellWidthPixels, cellHeightPixels);
|
||||
} else {
|
||||
@@ -127,6 +130,15 @@ public final class TerminalSession extends TerminalOutput {
|
||||
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns, cellWidthPixels, cellHeightPixels);
|
||||
mShellPid = processId[0];
|
||||
|
||||
// ★ 诊断日志:这一行是判断 pty 到底建成什么样的**唯一依据**。
|
||||
// fd == -1 → /dev/ptmx 打开失败(或 grantpt/unlockpt 失败),
|
||||
// 子进程的 0/1/2 全是无效 fd,bash 读 stdin 直接 EOF 退出。
|
||||
// pid <= 0 → fork 失败。
|
||||
// cols/rows 是 0 → attach 时 view 还没量过尺寸。
|
||||
android.util.Log.i("DoubaoTermux", "createSubprocess -> fd=" + mTerminalFileDescriptor
|
||||
+ " pid=" + mShellPid + " rows=" + rows + " cols=" + columns
|
||||
+ " cell=" + cellWidthPixels + "x" + cellHeightPixels);
|
||||
|
||||
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor, mClient);
|
||||
|
||||
new Thread("TermSessionInputReader[pid=" + mShellPid + "]") {
|
||||
@@ -141,7 +153,9 @@ public final class TerminalSession extends TerminalOutput {
|
||||
mMainThreadHandler.sendEmptyMessage(MSG_NEW_INPUT);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Ignore, just shutting down.
|
||||
// ★ 原来是静默吞掉的(`// Ignore, just shutting down.`)——
|
||||
// 于是 fd 读失败时**一点线索都没有**。加上日志。
|
||||
android.util.Log.e("DoubaoTermux", "TermSessionInputReader 退出", e);
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
@@ -325,7 +339,15 @@ public final class TerminalSession extends TerminalOutput {
|
||||
}
|
||||
descriptorField.setAccessible(true);
|
||||
descriptorField.set(result, fileDescriptor);
|
||||
// ★ 诊断:反射到底成没成。
|
||||
// Android 9+ 对 java.* 私有成员的反射有隐藏 API 限制,
|
||||
// setAccessible 被拦的话 result 里还是 -1,
|
||||
// 后面 FileInputStream/FileOutputStream 就都在读 fd -1 ——
|
||||
// 表现是"pty 双向都不通",而且**异常被静默吞掉**,什么都看不到。
|
||||
android.util.Log.i("DoubaoTermux", "wrapFileDescriptor fd=" + fileDescriptor
|
||||
+ " -> 反射后=" + result);
|
||||
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
|
||||
android.util.Log.e("DoubaoTermux", "wrapFileDescriptor 反射失败", e);
|
||||
Logger.logStackTraceWithMessage(client, LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
BIN
android/app/src/main/jniLibs/arm64-v8a/libdoubao-dpkg.so
Normal file
BIN
android/app/src/main/jniLibs/arm64-v8a/libdoubao-dpkg.so
Normal file
Binary file not shown.
BIN
android/app/src/main/jniLibs/x86_64/libdoubao-dpkg.so
Normal file
BIN
android/app/src/main/jniLibs/x86_64/libdoubao-dpkg.so
Normal file
Binary file not shown.
160
android/app/src/main/res/raw/doubao_patch.sh
Normal file
160
android/app/src/main/res/raw/doubao_patch.sh
Normal file
@@ -0,0 +1,160 @@
|
||||
#!/system/bin/sh
|
||||
# 由豆包 App 生成 —— 把新装包里写死 com.termux 的**脚本/文本**改掉。
|
||||
#
|
||||
# ★★ 这个文件是模板,正文原样嵌进 APK(res/raw/doubao_patch.sh),
|
||||
# 运行期由 TermuxInstaller.writePatcherScript() 做占位符替换:
|
||||
# @PREFIX@ → $PREFIX(files/usr)
|
||||
# @OLD@ → /data/data/com.termux
|
||||
# @NEW@ → /data/data/<我们的包名> (即 filesDir)
|
||||
# @PY@ → 用来干活的 python(**它自己也得是改过的**)
|
||||
# @VER@ → 脚本版本号
|
||||
#
|
||||
# 为什么不做成 Kotlin 字符串:脚本里 $P 这类变量到处都是,
|
||||
# Kotlin 的**原始字符串也照样做 $ 插值**,只能写成一堆 ${'$'}P,
|
||||
# 正文就没法读了(而且我已经因为这个编译失败两次)。
|
||||
# 放进 res/raw 之后,正文可以**原样读**,也不用碰任何构建脚本。
|
||||
#
|
||||
# 用法:
|
||||
# doubao-patch → 全部(shebang + 正文路径)
|
||||
# doubao-patch shebang → 只修 shebang(dpkg unpack 之后、configure 之前调)
|
||||
#
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# ★★★ 一、只改**文本文件**。二进制一律不碰。
|
||||
#
|
||||
# `sed -i` 会把 ELF 的内部偏移全写坏(当初一口气写坏 85 个二进制,
|
||||
# `dpkg.real` 直接变成 "empty/missing DT_HASH/DT_GNU_HASH")。
|
||||
# 为什么必然坏:`/data/data/com.termux`(21 字节)和
|
||||
# `/data/user/0/<包名>/files`(42 字节)**长度不等**,原地替换不能改长度。
|
||||
# 这正是 scripts/verify-elf-patch.py 验证过、我因此放弃"改二进制"方案的
|
||||
# 那条结论 —— 结果转头又在补刀脚本里犯了同一个错。
|
||||
#
|
||||
# 所以:含 NUL 的文件一律跳过;按行改之前还要 peek() 确认前两字节是 `#!`。
|
||||
#
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# ★★★ 二、为什么这段替换是 python 而不是 shell/sed
|
||||
#
|
||||
# 说实话:**最初换掉 shell/sed 是误判**。
|
||||
#
|
||||
# 当时看到 pip 的 shebang 变成
|
||||
# #!/data/user/0/<包名>/files/files/usr/bin/python3.14
|
||||
# 多出一个 `files`,就断定"玩具箱的 `${var//a/b}` 和 `sed` 会把匹配后面
|
||||
# 的片段复制一遍",于是把两个工具都换成了 python。
|
||||
#
|
||||
# **其实它们全是清白的。** 真正错的是上面那个 `NEW` 的取值 ——
|
||||
# 它当时被写成了 `<filesDir>`(以 `files` 结尾),而正确值是
|
||||
# `<prefix>`(`<filesDir>/usr`)。多出来的那个 `files` 是 `NEW` 自带的,
|
||||
# 和原文里的 `/files/usr` 撞在一起,看着就像"被复制了一遍"。
|
||||
# (拆穿它的是一个和本项目无关的中性实验:
|
||||
# b"/data/data/com.termux/files/usr".replace(
|
||||
# b"/data/data/com.termux", b"/data/user/0/pkg/files")
|
||||
# → b"/data/user/0/pkg/files/files/usr" ← 数学上完全正确)
|
||||
#
|
||||
# 教训:**"工具坏了"的时候,先怀疑自己的常量。**
|
||||
# 常量错的表现(稳定复现、与输入无关)恰恰是工具 bug 的特征。
|
||||
#
|
||||
# 那为什么**保留** python 版本?两条实在的理由:
|
||||
# 1. 这个脚本要改的东西里**混着二进制**(bin/ lib/ 下都是 ELF),
|
||||
# 用 shell 得靠 `grep -I` + `peek` 两道手工拦,而"哪个文件是文本"
|
||||
# 在 python 里是一行 `b"\0" in data[:8192]`,更不容易漏。
|
||||
# 2. 按行改(只动 shebang 第一行)用 shell 要 `head`/`tail`/`mv` 拼临时文件,
|
||||
# python 是 `data[:nl]`,没有中间态。
|
||||
# —— 不是因为 shell/sed 有 bug(它们没有)。
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
P=@PREFIX@
|
||||
OLD=@OLD@
|
||||
NEW=@NEW@
|
||||
PY=@PY@
|
||||
MODE="$1"
|
||||
|
||||
[ -n "$NEW" ] || exit 0
|
||||
|
||||
# ★★ 必须自己 export LD_LIBRARY_PATH —— 不然 `$PY` 根本起不来,
|
||||
# 而下面的 `[ -x "$PY" ]` 判定会**静默跳过全部工作**:
|
||||
# CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
|
||||
# not found: needed by main executable
|
||||
# 表现是"shebang 没被修好"但日志里一个字都没有 —— 查了好几轮才找到。
|
||||
# 不依赖调用方(wrapper / 终端)替我们设好。
|
||||
export LD_LIBRARY_PATH="$P/lib"
|
||||
export TMPDIR="$P/tmp"
|
||||
|
||||
# 干活的那段 python。参数:<目录> <模式>
|
||||
# 模式 = shebang → 只改第一行的 shebang(且该行必须含 OLD)
|
||||
# 模式 = body → 改整个文件里的 OLD
|
||||
run_py() {
|
||||
[ -x "$PY" ] || return 0
|
||||
"$PY" - "$1" "$2" "$OLD" "$NEW" <<'PYEOF'
|
||||
import os
|
||||
import sys
|
||||
|
||||
root, mode, old, new = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
|
||||
ob = old.encode()
|
||||
nb = new.encode()
|
||||
done = 0
|
||||
|
||||
for dirpath, _dirnames, filenames in os.walk(root):
|
||||
for name in filenames:
|
||||
path = os.path.join(dirpath, name)
|
||||
# ★ 绝不改自己:否则第一刀就把规则改掉了
|
||||
if name == "doubao-patch":
|
||||
continue
|
||||
try:
|
||||
if os.path.islink(path):
|
||||
continue
|
||||
with open(path, "rb") as fh:
|
||||
data = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
# ★ 二进制跳过(和 grep -I 同义,但不依赖 grep)
|
||||
if b"\0" in data[:8192] or ob not in data:
|
||||
continue
|
||||
|
||||
if mode == "shebang":
|
||||
nl = data.find(b"\n")
|
||||
first = data if nl < 0 else data[:nl]
|
||||
# 只动 shebang,且必须是含 OLD 的那种
|
||||
if not first.startswith(b"#!") or ob not in first:
|
||||
continue
|
||||
out = first.replace(ob, nb) + (b"" if nl < 0 else data[nl:])
|
||||
else:
|
||||
out = data.replace(ob, nb)
|
||||
|
||||
if out == data:
|
||||
continue
|
||||
try:
|
||||
mode_bits = os.stat(path).st_mode
|
||||
os.chmod(path, mode_bits) # 保住权限位(有些实现下 open(w) 会丢)
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(out)
|
||||
print(("shebang " if mode == "shebang" else "patched ") + path)
|
||||
done += 1
|
||||
except OSError:
|
||||
pass
|
||||
PYEOF
|
||||
}
|
||||
|
||||
run_py "$P/bin" shebang
|
||||
run_py "$P/libexec" shebang
|
||||
run_py "$P/var/lib/dpkg/info" shebang
|
||||
|
||||
[ "$MODE" = "shebang" ] && exit 0
|
||||
|
||||
for d in bin lib libexec etc share; do
|
||||
[ -d "$P/$d" ] || continue
|
||||
run_py "$P/$d" body
|
||||
done
|
||||
|
||||
# ★★ `var/lib/dpkg/info` 里的**维护脚本正文**也要扫。
|
||||
#
|
||||
# 漏了它会出这种错(实测):
|
||||
# python-ensurepip-wheels.postinst →
|
||||
# File "<frozen os>", line 236, in makedirs
|
||||
# PermissionError: [Errno 13] Permission denied: '/data/data/com.termux'
|
||||
# ERROR: Internal Error.
|
||||
# —— 包能装上、大部分功能也正常,但 dpkg 报 Internal Error,
|
||||
# 用户看到的是"装完了但报错"。而报错里那个路径属于**别的 App**,
|
||||
# 一眼看不出是我们漏扫了一个目录。
|
||||
#
|
||||
# ★ 注意这里传的是 `body`(改正文),不是 `shebang` ——
|
||||
# shebang 由上面那三趟单独处理,因为规则不同(见顶部注释)。
|
||||
run_py "$P/var/lib/dpkg/info" body
|
||||
108
android/app/src/main/res/raw/dpkg_wrapper.sh
Normal file
108
android/app/src/main/res/raw/dpkg_wrapper.sh
Normal file
@@ -0,0 +1,108 @@
|
||||
#!/system/bin/sh
|
||||
# 由豆包 App 生成 —— 补全环境 → 调真正的 dpkg → 把新装进来的脚本也改一遍。
|
||||
# 模板见 res/raw/dpkg_wrapper.sh,占位符 @PREFIX@ / @VER@ 由 App 替换。
|
||||
#
|
||||
# ★★ 为什么 shebang 是 /system/bin/sh 而不是别的:
|
||||
# shebang 那行是**内核**解析的,不走 PATH、也不走 LD_PRELOAD
|
||||
# (termux-exec 拦不到 execve 这一段),必须是真实存在的绝对路径。
|
||||
# /bin/sh → Android 上根本没这个文件
|
||||
# $PREFIX/bin/sh → 路径太长(而且会被 dpkg 的 --root 再拼一层前缀)
|
||||
# /system/bin/sh → 一定在,一定能被内核 exec
|
||||
# 注意它是**系统** toybox sh,不是 Termux 的 bash,
|
||||
# 所以该 export 的变量下面全都自己写。
|
||||
#
|
||||
# ★ 这个文件每次启动都会核对(内容变了才写盘),改了之后不用清 App 数据。
|
||||
|
||||
P=@PREFIX@
|
||||
export PATH="$P/bin:$P/bin/applets:/system/bin:/system/xbin"
|
||||
# ★★ LD_LIBRARY_PATH 是**必须**的,而且必须在这儿 export(不是只在终端里设)。
|
||||
# 原因:Termux 的二进制是靠 `libandroid-support.so` 等一堆库活的,而动态链接
|
||||
# 只认 LD_LIBRARY_PATH(没编 RPATH)。少了它,连 `$P/bin/python3` 都起不来:
|
||||
#
|
||||
# CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
|
||||
# not found: needed by main executable
|
||||
#
|
||||
# ★ 这个坑的可怕之处是**它是静默的**:补刀脚本第一件事就是判断
|
||||
# `[ -x "$PY" ]`,python 起不来 → 整个补刀什么都不做、也不报错,
|
||||
# 表现是"shebang 没被修好",而日志里一个字都没有。
|
||||
# 当时 pip 的 shebang 一直指着一个不存在的路径,查了好几轮
|
||||
# —— 真因就是这里少了一行 export。
|
||||
export LD_LIBRARY_PATH="$P/lib"
|
||||
export TMPDIR="$P/tmp"
|
||||
export DPKG_ADMINDIR="$P/var/lib/dpkg"
|
||||
export TERMUX__PREFIX="$P"
|
||||
|
||||
# ★★★ 这里**绝对不能加 `--root=`**。这一条解释一下,因为它反直觉:
|
||||
#
|
||||
# 一开始给 dpkg 加了 `--root="$P"`,想法是"让编译死的绝对路径落回我们
|
||||
# 自己目录"。它能解决**配置目录读不到**的问题,但会引入一个更隐蔽的:
|
||||
#
|
||||
# dpkg 会**在每一个路径前面拼 root**,包括包自己的安装路径。
|
||||
# .deb 里的文件清单记的是原始绝对路径
|
||||
# /data/data/com.termux/files/usr/bin/hello
|
||||
# 拼上 root 之后就变成
|
||||
# $P/data/data/com.termux/files/usr/bin/hello ← 落到沙箱里了!
|
||||
#
|
||||
# 实测(装 hello 包):
|
||||
# 文件出现在 <prefix>/data/data/com.termux/files/usr/bin/hello
|
||||
# 应该在 <prefix>/bin/hello
|
||||
# apt 还报 "Setting up hello ... 成功" —— **静悄悄地装到了错的地方**。
|
||||
#
|
||||
# 所以正确姿势是:**不加 --root**,改用 dpkg 自己的两个目录参数:
|
||||
# DPKG_ADMINDIR(环境变量)= 数据库位置
|
||||
# --instdir=/ = 安装根就是真实的 /,于是文件按原路径落,
|
||||
# 但 /data/data/com.termux 那条路必须能解析
|
||||
#
|
||||
# 而 `data/data/com.termux` 那条路由 App 侧的 linkLegacyPrefix() 建成
|
||||
# **指向 prefix 自己**的软链(`<prefix>/data/data/com.termux → <prefix>`),
|
||||
# 于是 dpkg 眼里:
|
||||
# /data/data/com.termux/files/usr/bin == <prefix>/files/usr/bin ✅
|
||||
# /data/data/com.termux/etc/dpkg == <prefix>/etc/dpkg ✅
|
||||
# 两个问题一起解决。
|
||||
#
|
||||
# ★★★ 补刀**要跑两次**,第二次的位置是关键。原因:
|
||||
#
|
||||
# dpkg 有两个阶段,而 .deb 里的文件是在 **unpack** 阶段落盘的:
|
||||
#
|
||||
# dpkg --unpack ← 文件(含 bin/pip 这种带 shebang 的脚本)落到我们目录
|
||||
# dpkg --configure ← 跑 postinst
|
||||
#
|
||||
# 而 postinst **会执行刚装进来的脚本**。`python-pip.postinst` 第 3 行就是:
|
||||
#
|
||||
# /data/user/0/<包名>/files/usr/bin/pip --version
|
||||
#
|
||||
# pip 确实在那儿,但它的第一行是
|
||||
# #!/data/data/com.termux/files/usr/bin/python
|
||||
# —— **绝对路径,那个文件不存在**(那是真 Termux 的地盘)。于是报:
|
||||
#
|
||||
# python-pip.postinst: line 3: .../bin/pip: cannot execute:
|
||||
# required file not found
|
||||
#
|
||||
# ★ 这句 "required file not found" 指的**不是 pip 本身**,而是它 shebang 里
|
||||
# 那个解释器 —— 报错信息完全没提这件事,所以极容易查到错的方向去
|
||||
# (会以为 pip 没装上)。
|
||||
#
|
||||
# 所以在 unpack 之后、configure 之前**补一刀**,把 shebang 改对。
|
||||
# apt 调 dpkg 时 unpack 和 configure 是**两次独立调用**,所以下面按参数判断。
|
||||
#
|
||||
# 最后再补一刀(不论什么操作)作为兜底,覆盖直接 `dpkg -i` 那种一步到位的用法。
|
||||
PATCH_UNPACK=0
|
||||
case " $* " in
|
||||
*" --unpack "*|*" --install "*|*" -i "*) PATCH_UNPACK=1 ;;
|
||||
esac
|
||||
|
||||
# ★ 不传 `--admindir`:下面 export 了 `DPKG_ADMINDIR`,dpkg 认这个环境变量,
|
||||
# 两处都写反而容易不一致(`--admindir` 是相对 instdir 的,容易理解错)。
|
||||
"$P/bin/dpkg.real" --instdir=/ --force-script-chrootless "$@"
|
||||
rc=$?
|
||||
|
||||
# ★ unpack 之后立刻补 shebang —— configure 阶段的 postinst 要用
|
||||
if [ "$PATCH_UNPACK" = 1 ] && [ -f "$P/bin/doubao-patch" ]; then
|
||||
"$P/bin/sh" "$P/bin/doubao-patch" shebang >> "$P/var/log/doubao-patch.log" 2>&1
|
||||
fi
|
||||
|
||||
# 收尾再补一次(含路径改写)。失败绝不影响 dpkg 的退出码。
|
||||
if [ -f "$P/bin/doubao-patch" ]; then
|
||||
"$P/bin/sh" "$P/bin/doubao-patch" >> "$P/var/log/doubao-patch.log" 2>&1
|
||||
fi
|
||||
exit $rc
|
||||
BIN
android/doubao-release.jks
Normal file
BIN
android/doubao-release.jks
Normal file
Binary file not shown.
@@ -42,8 +42,42 @@ def _max_rounds(settings: dict) -> int:
|
||||
return max(1, min(12, value))
|
||||
|
||||
|
||||
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
|
||||
#
|
||||
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
|
||||
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
|
||||
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
|
||||
# 硬塞进 markdown。
|
||||
#
|
||||
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
|
||||
# 所以措辞是"确实用文字说不清时才用"。
|
||||
UI_TOOLS_HINT = '\n'.join([
|
||||
'界面能力(用户已打开):',
|
||||
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||||
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||||
' 界面**支持 JavaScript**(canvas 画图、动态渲染都行)。',
|
||||
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
||||
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
||||
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
||||
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||||
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||||
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||||
' · wait=true = **等用户点一个回传按钮或关掉界面**(最多 timeout 秒,默认 120)。',
|
||||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。',
|
||||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||||
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||||
])
|
||||
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||||
should_stop: Optional[Callable[[], bool]] = None,
|
||||
conversation_id: str = '') -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
@@ -52,6 +86,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||||
"""
|
||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||
@@ -61,6 +96,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||||
#
|
||||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||||
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
|
||||
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
|
||||
# 按开关动态追加,两边永远一致。
|
||||
#
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
if tools_runtime.ui_tools_enabled(settings):
|
||||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
@@ -76,6 +121,37 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
convo = []
|
||||
if system_prompt.strip():
|
||||
convo.append({'role': 'system', 'content': system_prompt})
|
||||
|
||||
# ★★★ AI 界面的**数据回流**在这里进上下文。
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 里可以调 `Doubao.sendToAi(值)`,
|
||||
# 安卓桥把它 POST 到 /api/ui-result 排队;这里取走并作为
|
||||
# **一条 system 消息**插在历史前面。
|
||||
#
|
||||
# ★ 为什么是 system 而不是 user:
|
||||
# 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,
|
||||
# 而且用户点"重新生成"时会和真正那条用户消息混在一起。
|
||||
# system 的语义就是"背景信息",正合适。
|
||||
#
|
||||
# ★ 为什么要**取走**:不取走的话这轮用、下轮还用,
|
||||
# 模型会反复提同一件事,用户会以为它卡住了。
|
||||
#
|
||||
# ★ 为什么放在 messages **之前**:它是"用户接下来这句话的前提",
|
||||
# 要让模型先看到"用户在界面上选了什么",再读用户那句话。
|
||||
ui_results = store.take_pending_ui(conversation_id) if conversation_id else []
|
||||
if ui_results:
|
||||
lines = '\n'.join(f'- {v}' for v in ui_results)
|
||||
convo.append({
|
||||
'role': 'system',
|
||||
'content': (
|
||||
'用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):\n'
|
||||
f'{lines}\n'
|
||||
'请结合这些信息回答用户接下来的话;如果用户还没说话,就针对这些选择给出回应。'
|
||||
),
|
||||
})
|
||||
# 也让界面知道模型收到了 —— 前端可以据此显示"AI 已收到你的选择"
|
||||
emit({'type': 'ui_results', 'count': len(ui_results)})
|
||||
|
||||
convo.extend(messages)
|
||||
|
||||
answer = ''
|
||||
@@ -148,10 +224,20 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
for tc in tool_calls:
|
||||
tool_call_count += 1
|
||||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||||
# ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话",
|
||||
# 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local,
|
||||
# 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。
|
||||
tools_runtime.push_context(
|
||||
conversationId=conversation_id,
|
||||
agentId=(agent or {}).get('id') or '',
|
||||
toolName=tc.get('name') or '',
|
||||
)
|
||||
try:
|
||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
if result.get('ok'):
|
||||
raw = result.get('result')
|
||||
payload = truncate('(无输出)' if raw is None else raw)
|
||||
|
||||
@@ -665,6 +665,51 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if pathname == '/api/conversations' and method == 'GET':
|
||||
self.send_json(200, {'conversations': store.list_conversations()})
|
||||
return True
|
||||
|
||||
# ---- AI 界面的数据回流 ----
|
||||
#
|
||||
# ★★★ 这是"AI 自己写进网页里的接口"的落点。
|
||||
#
|
||||
# AI 用 show_ui 弹一个 HTML 界面,界面里可以写:
|
||||
# Doubao.sendToAi("用户选的是方案 B")
|
||||
# 那个值经安卓桥打到这里,**排队等下一次对话**。
|
||||
# 下一轮 run_agent 会把队里的东西作为上下文交给模型 ——
|
||||
# 于是"用户在 AI 自己写的界面里选了什么"真的回到了模型手里。
|
||||
#
|
||||
# ★ 为什么用"排队"而不是"直接起一轮对话":
|
||||
# 用户可能连点几下、或者在界面里选好几项再确认。
|
||||
# 每点一下就跑一轮模型既慢又费 token,而且用户还没说完。
|
||||
# 排队 → 用户下一次说话(或点界面上的提交按钮)时一起带上,
|
||||
# 语义上也更对:**界面是提问的一部分,不是提问本身**。
|
||||
if pathname == '/api/ui-result' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
conv = str(body.get('conversationId') or '')
|
||||
value = str(body.get('value') or '').strip()
|
||||
if not value:
|
||||
self.send_json(400, {'error': 'value 不能为空'})
|
||||
return True
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
n = store.add_pending_ui(conv, value)
|
||||
self.send_json(200, {'ok': True, 'queued': n})
|
||||
return True
|
||||
|
||||
if pathname == '/api/ui-result' and method == 'GET':
|
||||
parsed = urlsplit(self.path)
|
||||
params = dict(
|
||||
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||||
)
|
||||
conv = unquote(params.get('conversationId') or '')
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
self.send_json(200, {'pending': store.peek_pending_ui(conv)})
|
||||
return True
|
||||
|
||||
if pathname == '/api/conversations' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
@@ -864,6 +909,7 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
{'key': 'cast', 'label': '转换', 'desc': '纯节点:str / bool / num 互转'},
|
||||
{'key': 'op', 'label': '运算', 'desc': '纯节点:+ − × ÷ % 拼接 取反 比较'},
|
||||
{'key': 'py', 'label': 'Python', 'desc': '写一段 Python(run(ctx)),也可以给智能体当工具调'},
|
||||
{'key': 'branch', 'label': '分支', 'desc': '收一个真假,走真/假两条 exec(和判断的区别:判断按规则算,分支直接收)'},
|
||||
],
|
||||
'judgeKinds': [{'key': k, 'label': v} for k, v in meeting.JUDGE_KINDS],
|
||||
'agents': [
|
||||
@@ -934,9 +980,24 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(400, {'error': '缺少 name'})
|
||||
return True
|
||||
try:
|
||||
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
|
||||
result = tools_runtime.execute_tool(name, body.get('args') or {},
|
||||
{'security': {'mode': 'open'}})
|
||||
# ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的),
|
||||
# 但仍要能报错。所以 mode 强制 open。
|
||||
#
|
||||
# ★★ 但**不能**只传一个空壳 settings(以前就是 {'security':...}):
|
||||
# 界面工具(show_ui/ask_user/end_conversation)的开关也在 settings 里,
|
||||
# 空壳会让它们**永远被第二道拦截挡住** —— 用户在技能页点"试运行",
|
||||
# 明明开关是开的,却收到"已关闭"。这个错会让人以为是开关没生效。
|
||||
# 所以拿真实设置、只覆盖 security。
|
||||
live = store.read_settings() or {}
|
||||
settings = {**live, 'security': {'mode': 'open', 'allow': []}}
|
||||
tools_runtime.push_context(
|
||||
conversationId=str(body.get('conversationId') or ''),
|
||||
toolName=name,
|
||||
)
|
||||
try:
|
||||
result = tools_runtime.execute_tool(name, body.get('args') or {}, settings)
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
self.send_json(200, result)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.send_json(500, {'ok': False, 'error': str(exc)})
|
||||
@@ -1401,6 +1462,9 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||
emit=emit,
|
||||
should_stop=cancelled,
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
# end_conversation 会明确报错(而不是假装成功)。
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
|
||||
@@ -15,6 +15,13 @@ DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
'',
|
||||
'关于用户发来的文件(附件):',
|
||||
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
|
||||
' **那个路径是文件在手机上的真实落盘位置**,可以直接用 shell 或 python 工具打开它 ——',
|
||||
' 不要猜路径,也不要说"我拿不到文件"。',
|
||||
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
|
||||
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
|
||||
]
|
||||
)
|
||||
|
||||
@@ -173,6 +180,12 @@ DEFAULT_SETTINGS = {
|
||||
'toolsDir': '',
|
||||
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||
'tools': {'python': True, 'mcp': True},
|
||||
# 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话
|
||||
# (show_ui / ask_user / end_conversation)。
|
||||
#
|
||||
# ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、
|
||||
# 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。
|
||||
'uiTools': {'enabled': False},
|
||||
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||
'speech': {
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
@@ -20,6 +21,8 @@ import threading
|
||||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||
BUNDLED_TOOL_FILES = [
|
||||
'_protocol.py',
|
||||
# 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种)
|
||||
'_ui_bridge.py',
|
||||
'calc.py',
|
||||
'now.py',
|
||||
'weather.py',
|
||||
@@ -27,6 +30,10 @@ BUNDLED_TOOL_FILES = [
|
||||
'web_fetch.py',
|
||||
'shell.py',
|
||||
'python_run.py',
|
||||
# AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools)
|
||||
'show_ui.py',
|
||||
'ask_user.py',
|
||||
'end_conversation.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
@@ -257,37 +264,130 @@ def _module_source(name: str):
|
||||
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:
|
||||
"""
|
||||
首次运行把内置工具写到手机上的可写目录。
|
||||
之后用户就能自己改、自己加(设置里的"工具目录"指向这里)。
|
||||
把内置工具写到手机上的可写目录。之后用户就能自己改、自己加
|
||||
(设置里的"工具目录"指向这里)。
|
||||
|
||||
源码来源优先级:
|
||||
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||||
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||||
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)
|
||||
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||||
|
||||
shipped: dict = {}
|
||||
try:
|
||||
import bundled_tool_sources # type: ignore[import-not-found]
|
||||
|
||||
for name, source in bundled_tool_sources.sources().items():
|
||||
wanted[name] = source
|
||||
# ★ 历史版本哈希表:靠它认出"盘上这份是我们以前发的"
|
||||
try:
|
||||
shipped = bundled_tool_sources.shipped()
|
||||
except Exception: # noqa: BLE001 - 老版本生成的文件里没有这个函数
|
||||
shipped = {}
|
||||
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||||
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
|
||||
skipped_user = 0
|
||||
for filename, source in wanted.items():
|
||||
if not source:
|
||||
continue
|
||||
dest = os.path.join(tools_dir, filename)
|
||||
new_hash = _src_hash(source)
|
||||
|
||||
if os.path.exists(dest):
|
||||
continue
|
||||
with open(dest, 'w', encoding='utf-8') as fh:
|
||||
fh.write(source)
|
||||
copied += 1
|
||||
try:
|
||||
with open(dest, encoding='utf-8') as fh:
|
||||
current = fh.read()
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ import paths
|
||||
_lock = threading.Lock()
|
||||
|
||||
NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'value',
|
||||
'cast', 'op', 'py', 'custom')
|
||||
'cast', 'op', 'py', 'custom', 'branch')
|
||||
|
||||
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -58,7 +58,7 @@ NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'valu
|
||||
# return "结果"
|
||||
#
|
||||
# ctx 提供:
|
||||
# ctx.input 上游传进来的内容(数据线优先,没有就用 exec 上游的输出)
|
||||
# ctx.input 上游**数据线**传进来的内容(exec 线不传数据,永远不)
|
||||
# ctx.vars 变量表(**只读快照**,改它不会影响会议)
|
||||
# ctx.set_var(名, 值) 写变量(会真的写进会议变量表)
|
||||
# ctx.log(内容) 记一条说明,会出现在结果界面的这一步里
|
||||
@@ -211,12 +211,25 @@ OPS = (
|
||||
('div', '除 ÷', 'num', 'num', 2),
|
||||
('mod', '取余 %', 'num', 'num', 2),
|
||||
('concat', '拼接', 'str', 'str', 2),
|
||||
('eq', '等于 =', 'str', 'bool', 2),
|
||||
('ne', '不等于 ≠', 'str', 'bool', 2),
|
||||
('eq', '等于 =(数字)', 'num', 'bool', 2),
|
||||
('ne', '不等于 ≠(数字)', 'num', 'bool', 2),
|
||||
# ★ 文本相等单独一份:数字相等和文本相等**不是一回事** ——
|
||||
# "01" 和 "1" 作为文本不等,作为数字相等;拼写比较也不能先转成数字。
|
||||
('streq', '文本等于 ==', 'str', 'bool', 2),
|
||||
('strne', '文本不等于 !=', 'str', 'bool', 2),
|
||||
('gt', '大于 >', 'num', 'bool', 2),
|
||||
('lt', '小于 <', 'num', 'bool', 2),
|
||||
('gte', '大于等于 ≥', 'num', 'bool', 2),
|
||||
('lte', '小于等于 ≤', 'num', 'bool', 2),
|
||||
('neg', '取反(负号)', 'num', 'num', 1),
|
||||
('not', '逻辑非 !', 'bool', 'bool', 1),
|
||||
# ---- 逻辑运算:两边都是真假,结果也是真假 ----
|
||||
('and', '与 and', 'bool', 'bool', 2),
|
||||
('or', '或 or', 'bool', 'bool', 2),
|
||||
('xor', '异或 xor', 'bool', 'bool', 2),
|
||||
# ---- 位运算:整数才有的操作,结果为数字 ----
|
||||
('shl', '左移 <<', 'num', 'num', 2),
|
||||
('shr', '右移 >>', 'num', 'num', 2),
|
||||
('append', '追加到列表', 'list', 'list', 2),
|
||||
('clear', '清空列表', 'list', 'list', 1),
|
||||
)
|
||||
@@ -298,10 +311,53 @@ def apply_op(op_key: str, a, b=None):
|
||||
return ('false' if truthy(a) else 'true'), ''
|
||||
return '', f'不认识的运算:{op_key}'
|
||||
|
||||
# ---- 逻辑运算 ----
|
||||
#
|
||||
# ★ 不要求两边"是严格的 bool":变量和上游多半给的是 "true"/"1"/"是" 这类文本,
|
||||
# 硬卡类型的话用户得先接一堆转换节点才能做一次与运算。
|
||||
# 用 truthy() 统一判断(它认得 0/空/false/no/off),结果统一输出 true/false。
|
||||
if op_key in ('and', 'or', 'xor'):
|
||||
x, y = truthy(a), truthy(b)
|
||||
if op_key == 'and':
|
||||
return ('true' if (x and y) else 'false'), ''
|
||||
if op_key == 'or':
|
||||
return ('true' if (x or y) else 'false'), ''
|
||||
return ('true' if (x != y) else 'false'), ''
|
||||
|
||||
# ---- 位运算 ----
|
||||
#
|
||||
# ★ 先转成**整数**:Python 的 << 对浮点会报错,而我们的数值一路上都是文本。
|
||||
# 负数照常(Python 的位运算是任意精度,这点比 C 好)。
|
||||
if op_key in ('shl', 'shr'):
|
||||
x, e1 = as_num(a)
|
||||
y, e2 = as_num(b)
|
||||
if e1 or e2:
|
||||
return '0', (e1 or e2)
|
||||
try:
|
||||
n = int(x)
|
||||
s = int(y)
|
||||
if s < 0:
|
||||
return '0', f'位移量不能是负数:{s}'
|
||||
if s > 64:
|
||||
# 不让用户一不小心写出 1 << 9999999(那会算到天荒地老)
|
||||
return '0', f'位移量太大:{s}(最多 64)'
|
||||
return cast_value((n << s) if op_key == 'shl' else (n >> s), 'num'), ''
|
||||
except (ValueError, OverflowError) as exc:
|
||||
return '0', f'位移算不了:{exc}'
|
||||
|
||||
if op_key == 'concat':
|
||||
return str(a) + str(b), ''
|
||||
if op_key in ('eq', 'ne'):
|
||||
# 文本相等:直接比字符串,不经过 as_num。
|
||||
# 两者不能混:01 和 1 作为文本不等、作为数字相等。
|
||||
if op_key in ('streq', 'strne'):
|
||||
same = str(a) == str(b)
|
||||
return cast_value(same if op_key == 'streq' else not same, 'bool'), ''
|
||||
if op_key in ('eq', 'ne'):
|
||||
x1, e3 = as_num(a)
|
||||
y1, e4 = as_num(b)
|
||||
if e3 or e4:
|
||||
return 'false', (e3 or e4)
|
||||
same = (x1 == y1)
|
||||
return cast_value(same if op_key == 'eq' else not same, 'bool'), ''
|
||||
|
||||
x, e1 = as_num(a)
|
||||
@@ -326,6 +382,10 @@ def apply_op(op_key: str, a, b=None):
|
||||
return cast_value(x > y, out_type), ''
|
||||
if op_key == 'lt':
|
||||
return cast_value(x < y, out_type), ''
|
||||
if op_key == 'gte':
|
||||
return cast_value(x >= y, out_type), ''
|
||||
if op_key == 'lte':
|
||||
return cast_value(x <= y, out_type), ''
|
||||
return '', f'不认识的运算:{op_key}'
|
||||
|
||||
|
||||
@@ -756,8 +816,10 @@ def _sanitize_nodes(nodes: list) -> list:
|
||||
NODE_DATA_IN = {
|
||||
'agent': ('str',),
|
||||
'judge': ('str',),
|
||||
# 写变量是汇:什么都能存(存进去的都是文本,读的时候按变量类型解释)
|
||||
'var': ('str', 'bool', 'num'),
|
||||
# 写变量是汇:什么都能存(存进去的都是文本,读的时候按变量类型解释)。
|
||||
# ★ 必须含 list —— 之前漏了,列表变量根本写不进去
|
||||
# (加 list 类型时没同步这张表,用户报"写变量的输入也没改")。
|
||||
'var': ('str', 'bool', 'num', 'list'),
|
||||
'while': ('bool',),
|
||||
# 最终输出只是展示,什么类型都能接(展示方式按类型不同)
|
||||
# Python 节点:上游给什么都要能收(它就是拿来处理任意内容的)
|
||||
@@ -765,11 +827,16 @@ NODE_DATA_IN = {
|
||||
# 自定义节点:真正收什么由它声明的引脚决定(见 _data_in_type),
|
||||
# 这里给宽松值,免得还没加载到定义时就把线丢了
|
||||
'custom': ('str', 'bool', 'num', 'list'),
|
||||
# 分支节点:条件收得宽一点(变量/上游多半给的是 true / 1 这类文本)。
|
||||
# ★ num 也要收 —— 界面那边允许,引擎这边不收的话线会被丢掉。
|
||||
'branch': ('bool', 'str', 'num'),
|
||||
'end': ('str', 'bool', 'num', 'list'),
|
||||
# 转换:什么都收,出口由 castTo 决定
|
||||
'cast': ('str', 'bool', 'num'),
|
||||
# 运算:入口类型由运算本身决定(见 _data_in_type)
|
||||
'op': ('str', 'bool', 'num'),
|
||||
# 转换:什么都收,出口由 castTo 决定。
|
||||
# ★ 含 list —— 不然"把列表转成文本"这种最基本的转换做不了。
|
||||
'cast': ('str', 'bool', 'num', 'list'),
|
||||
# 运算:入口类型由运算本身决定(见 _data_in_type)。
|
||||
# 这里给宽松值当兜底:
|
||||
'op': ('str', 'bool', 'num', 'list'),
|
||||
}
|
||||
|
||||
NODE_DATA_OUT = {
|
||||
@@ -818,12 +885,20 @@ def _data_in_type(node_id: str):
|
||||
node = _LAST_BY_ID.get(node_id)
|
||||
if not node:
|
||||
return None
|
||||
# ★ 自定义节点:按声明的 input 引脚类型。
|
||||
#
|
||||
# 这里是"这个节点收哪些类型"的**并集** —— 引擎的类型检查是按**节点**做的
|
||||
# (一条边上没有"接到哪个引脚"的信息),所以多入口只能放宽成并集。
|
||||
# 界面那一侧知道用户在拖哪根线,做的是**按引脚**的精确校验,
|
||||
# 所以严格程度并不会丢:接错了当场就连不上。
|
||||
if node['type'] == 'var':
|
||||
vname = str(node.get('varName') or '').strip()
|
||||
vt = _LAST_VAR_TYPE.get(vname)
|
||||
# ★ 列表变量:入口是 str(要追加的那一项文本),**不是 list**。
|
||||
#
|
||||
# 写变量对列表的动作是"追加一项",不是整体替换 ——
|
||||
# 要求整个列表的话,用户得先拼一个 JSON 数组才能加一项,太别扭。
|
||||
#
|
||||
# ★★ 这条规则必须和界面 inputPins 里那条**一模一样**。
|
||||
# 我只改了界面没改引擎,结果界面上连得上、一保存就被丢掉,
|
||||
# 用户看到的还是"连不上"。改这种规则要两边一起改。
|
||||
if vt == 'list':
|
||||
return ('str',)
|
||||
return (vt,) if vt in PIN_TYPES else ('str',)
|
||||
if node['type'] == 'custom':
|
||||
d = _LAST_CUSTOM.get(str(node.get('customKey') or ''))
|
||||
if d:
|
||||
@@ -835,15 +910,6 @@ def _data_in_type(node_id: str):
|
||||
if node['type'] == 'op':
|
||||
spec = _OPS_BY_KEY.get(str(node.get('op') or 'add'))
|
||||
return (spec[2],) if spec else ('num',)
|
||||
# ★ 写变量是**汇**:什么类型都能存。
|
||||
#
|
||||
# 这里原来按**变量登记表**卡类型(变量声明成 num 就只收 num)。
|
||||
# 后果:智能体输出的是 str → 类型不符 → 引擎保存时把数据线丢掉。
|
||||
# 界面上明明连上了,一保存就没了 —— 用户的原话是"是链接不了",
|
||||
# 而且完全不知道为什么(界面上连的那一下是成功的)。
|
||||
#
|
||||
# 变量的类型只该决定**读出去**能接到哪(readvar 的出口类型),
|
||||
# 不该限制**存进来**的东西:存进去的都是文本,读的时候再按类型解释。
|
||||
return NODE_DATA_IN.get(node['type'])
|
||||
def _data_out_type(node_id: str):
|
||||
"""
|
||||
@@ -957,7 +1023,16 @@ def _sanitize_edges(edges: list, nodes: list) -> list:
|
||||
if want is None or give is None or give not in want:
|
||||
continue
|
||||
|
||||
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or ''), 'kind': kind})
|
||||
# ★ 引脚信息要**原样留着**:一个节点有两个同类型入口(运算的 A/B)时,
|
||||
# 光靠 from/to 分不清线接的是哪个 —— 表现就是"两条线都落在 A 上,
|
||||
# B 永远收不到"。老的边没这个字段,留空时按顺序兜底。
|
||||
out.append({
|
||||
'from': src, 'to': dst,
|
||||
'branch': str(e.get('branch') or ''),
|
||||
'kind': kind,
|
||||
'toPin': str(e.get('toPin') or ''),
|
||||
'fromPin': str(e.get('fromPin') or ''),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
@@ -987,8 +1062,14 @@ def _outgoing(edges: list, node_id: str) -> list:
|
||||
# - 读变量这种"纯节点"(Get)**没有 exec 引脚**,它的值是被需要的人
|
||||
# **拉取**的,自己不在执行链上 —— 这正是"读变量只有输出"的真正原因。
|
||||
#
|
||||
# 兼容:老会议里没有 kind 字段的边,当成 exec 处理,并且"没有数据入边时
|
||||
# 就用 exec 上游的输出"当输入 —— 这样以前那种"一根线连到底"的图行为不变。
|
||||
# ★★ exec **不传数据** —— 这是**写死**的规则,没有例外、没有兼容回退。
|
||||
#
|
||||
# 一开始为了迁就"一根线连到底"的老图,做过"没有数据入边时就用 exec 上游的
|
||||
# 输出"的回退。那是错的:它让 exec 线看起来能传值,于是**整张图的类型就不
|
||||
# 再有意义** —— 用户没法从图上判断一个值到底从哪来,界面画的颜色和形状
|
||||
# 也都在骗人。宁可让空值显式地空着(节点上会报原因),也不要猜。
|
||||
#
|
||||
# 兼容:老会议里没有 kind 字段的边,当成 exec 处理。
|
||||
|
||||
EXEC = 'exec'
|
||||
DATA = 'data'
|
||||
@@ -1511,24 +1592,16 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
value = (node.get('varValue') or '').strip()
|
||||
note = ''
|
||||
if not value:
|
||||
# ★★ exec **绝不传数据** —— 这条是**写死**的,没有例外。
|
||||
#
|
||||
# 这里以前有个"没连数据线就用 exec 上游的输出"的回退。
|
||||
# 那是错的,而且错得很危险:它让"exec 线"看起来能传值,
|
||||
# 于是整个类型系统就不可信了 —— 用户没法从图上判断
|
||||
# 一个值到底从哪来。蓝图里 exec 就是**只排顺序**。
|
||||
#
|
||||
# 没连数据线就是**空**,节点上会明确报出来
|
||||
# (见下面 _exec_in 那段 warn 的逻辑)。
|
||||
value = incoming
|
||||
# ★ **没连数据线时,退一步用 exec 上游的输出。**
|
||||
#
|
||||
# "exec 不传递数据"这条规则是对的,但对**写变量**太苛刻:
|
||||
# 用户的心智模型就是"这根线连过来了,所以把刚才产生的东西存进去"。
|
||||
# 逼他们必须再拉一根数据线,结果就是反复踩同一个坑
|
||||
# (这个问题被反馈了三次)。
|
||||
#
|
||||
# 所以做一个**有交代的例外**:没数据线就用 exec 上游的输出,
|
||||
# 并且在节点上明确写出来"用了上游的输出" ——
|
||||
# 不是悄悄猜,用户一眼能看到引擎替他做了什么。
|
||||
if not _data_in(edges, node_id):
|
||||
ups = [outputs.get(e.get('from'))
|
||||
for e in _exec_in(edges, node_id)]
|
||||
ups = [t for t in ups if t]
|
||||
if ups:
|
||||
value = ups[-1]
|
||||
note = '(没连数据线,用了 exec 上游的输出)'
|
||||
# ★ **按变量类型决定动作**。
|
||||
#
|
||||
# 列表 → 默认**追加**:列表的用处就是攒东西,"写变量"这个动作
|
||||
@@ -1569,6 +1642,30 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
'note': f'读到 {name}' + ('' if value else '(还没设过,是空的)')})
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id)]
|
||||
|
||||
elif node_type == 'branch':
|
||||
# ★ 分支节点:收一个真假,走 A 或 B。
|
||||
#
|
||||
# 和判断节点的区别:判断是按**规则**算真假(包含关键词 / 字数多于…),
|
||||
# 分支是**直接收一个真假值** —— 真假从哪来由用户自己接
|
||||
# (运算的比较结果、变量、读变量、自定义节点…)。
|
||||
# 有了它,"先算个条件、再决定走哪条"就不用绕道判断节点了。
|
||||
#
|
||||
# 规则和判断节点**完全一致**(同一套坑,不能两样):
|
||||
# · 判成的那个分支没连线 → 停在原地 + 报警告,不顺走另一条
|
||||
# · 输入为空也报警告(exec 不传值,用户很容易忘了接数据线)
|
||||
verdict = truthy(incoming)
|
||||
outputs[node_id] = 'true' if verdict else 'false'
|
||||
bname = 'true' if verdict else 'false'
|
||||
next_ids = [e['to'] for e in _exec_out(edges, node_id, bname)]
|
||||
if not next_ids:
|
||||
emit({'type': 'node_warn', 'nodeId': node_id,
|
||||
'warn': f'判定为{"真" if verdict else "假"},但那个分支没连线 —— '
|
||||
f'执行链在这里停了。'})
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'nodeType': node_type,
|
||||
'output': outputs[node_id], 'verdict': verdict,
|
||||
'branch': bname, 'run': run_index,
|
||||
'note': f'{"真" if verdict else "假"} → 走 {bname} 分支'})
|
||||
|
||||
elif node_type == 'custom':
|
||||
# ★ 用户用 Python 拓展出来的节点
|
||||
import custom_nodes as _cn
|
||||
@@ -1584,17 +1681,9 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
continue
|
||||
ins[pin['name']] = _collect_pin_input(
|
||||
node_id, edges, pin, d, outputs, variables, by_id)
|
||||
# 没连任何入口时,退一步用 exec 上游的输出喂给**第一个**入口 ——
|
||||
# 和写变量、最终输出一个道理:用户的心智是"线连过来了",
|
||||
# 逼他必须再拉一根数据线只会让他看到空值还不知道为什么。
|
||||
if not any(str(v).strip() for v in ins.values()):
|
||||
data_pins = [p for p in (d.get('inputs') or []) if p['type'] != 'exec']
|
||||
if data_pins and not _data_in(edges, node_id):
|
||||
ups = [outputs.get(e.get('from'))
|
||||
for e in _exec_in(edges, node_id)]
|
||||
ups = [t for t in ups if t]
|
||||
if ups:
|
||||
ins[data_pins[0]['name']] = ups[-1]
|
||||
# ★ exec 不传数据(写死的规则,没有例外)——
|
||||
# 这里以前也有个"没连入口就用 exec 上游的输出"的回退,已删。
|
||||
# 自定义节点的入口收不到值就是空的,节点上会报出来。
|
||||
logs = []
|
||||
outs, err = _cn.run_custom(d, ins, variables, node, logs)
|
||||
if err:
|
||||
@@ -1724,16 +1813,11 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
# 展示方式不同。所以每个 end 节点都把自己那份结果和类型记下来。
|
||||
value = (node.get('text') or '').strip()
|
||||
if not value:
|
||||
# ★ exec 不传数据(写死的规则,没有例外)——
|
||||
# 只连了 exec 线时这里就是空的。以前有个"用 exec 上游
|
||||
# 输出"的回退,已删:它让 exec 看起来能传值,
|
||||
# 整张图的类型就不再有意义了。
|
||||
value = incoming
|
||||
# 和"写变量"同样的道理:只连了 exec 线时,用上游的输出。
|
||||
# 用户的心智模型是"这根线连过来了,所以把刚才产生的东西显示出来",
|
||||
# 逼他必须再拉一根数据线,只会让他看到一片空白还不知道为什么。
|
||||
if not _data_in(edges, node_id):
|
||||
ups = [outputs.get(e.get('from'))
|
||||
for e in _exec_in(edges, node_id)]
|
||||
ups = [t for t in ups if t]
|
||||
if ups:
|
||||
value = ups[-1]
|
||||
outputs[node_id] = value
|
||||
# 类型:**优先看来源节点的实际出口类型**,不要信边上的 kind。
|
||||
#
|
||||
|
||||
@@ -162,6 +162,20 @@ def write_settings(patch: dict) -> dict:
|
||||
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
|
||||
if not isinstance(patch, dict):
|
||||
patch = {}
|
||||
# ★★ 显式的"清除"通路:值传 None 就是"我要把它清掉"。
|
||||
#
|
||||
# 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是
|
||||
# "前端草稿没初始化好,一次保存清空整份配置"),但代价是
|
||||
# **用户永远清不掉自定义 Base URL / 模型名** ——
|
||||
# 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||||
# (这是我在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认,
|
||||
# 传空串怎么也改不掉。)
|
||||
#
|
||||
# 所以给一条**显式**的路:传 null。空串仍然= "没填、别动",
|
||||
# null = "确实要清掉"。两者语义不同,前端可以按需选。
|
||||
explicit_clear = {k for k, v in patch.items() if v is None}
|
||||
for key in explicit_clear:
|
||||
patch.pop(key, None)
|
||||
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||||
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||||
@@ -171,6 +185,10 @@ def write_settings(patch: dict) -> dict:
|
||||
patch.pop(key)
|
||||
current = read_settings()
|
||||
nxt = {**current, **patch}
|
||||
# 显式清除的落到默认值上(不是留着旧值,也不是变成空 —— 空会让
|
||||
# "用哪个 provider 的默认 baseUrl"这套逻辑失效)
|
||||
for key in explicit_clear:
|
||||
nxt[key] = DEFAULT_SETTINGS.get(key, '')
|
||||
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||||
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
|
||||
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||
@@ -338,6 +356,67 @@ def get_conversation(conv_id: str):
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 界面的数据回流
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 界面里可以调 `Doubao.sendToAi(值)`,
|
||||
# 那个值先落到这里排队,下一轮对话开始时被取走、当作上下文交给模型。
|
||||
#
|
||||
# ★ 为什么单独存一份、而不是直接写进会话的消息列表:
|
||||
# 写进消息列表的话它会**变成一条 user 消息** —— 用户会看到一条
|
||||
# 自己没打过的消息,而且它会被当成"用户说的话"进历史。
|
||||
# 语义上它更像**附件/上下文**,不是用户的一句话。
|
||||
# 所以单独排队,由 agent_loop 拼进这一轮的上下文里。
|
||||
#
|
||||
# ★ 为什么不落盘:这是**一次性的上下文**,跨重启没有意义
|
||||
# (用户重启 App 之后那个界面早就关了,界面的选择也就失效了)。
|
||||
# 放内存里,进程重启自然清空,正合适。
|
||||
_pending_ui: dict = {}
|
||||
_pending_ui_lock = threading.Lock()
|
||||
|
||||
# 每个会话最多排多少条 —— 用户在界面上乱点不能把内存堆满
|
||||
PENDING_UI_MAX = 20
|
||||
# 单条最长多少字符 —— 界面可能回传一大段文本
|
||||
PENDING_UI_ITEM_MAX = 4000
|
||||
|
||||
|
||||
def add_pending_ui(conv_id: str, value: str) -> int:
|
||||
"""把界面上回传的一个值排进队。返回队里现在有几条。"""
|
||||
text = (value or '').strip()[:PENDING_UI_ITEM_MAX]
|
||||
if not conv_id or not text:
|
||||
return len(_pending_ui.get(conv_id) or [])
|
||||
with _pending_ui_lock:
|
||||
box = _pending_ui.setdefault(conv_id, [])
|
||||
box.append(text)
|
||||
# 超了就丢**最旧的**:用户最新点的那次最相关
|
||||
while len(box) > PENDING_UI_MAX:
|
||||
box.pop(0)
|
||||
return len(box)
|
||||
|
||||
|
||||
def peek_pending_ui(conv_id: str) -> list:
|
||||
"""看一眼(不取走)—— 给调试用的 GET 接口"""
|
||||
with _pending_ui_lock:
|
||||
return list(_pending_ui.get(conv_id) or [])
|
||||
|
||||
|
||||
def take_pending_ui(conv_id: str) -> list:
|
||||
"""
|
||||
取走并清空。
|
||||
|
||||
★ 必须"取走":不取走的话每轮对话都会把同一条又带上,
|
||||
用户会看到模型反复提同一件事。
|
||||
"""
|
||||
with _pending_ui_lock:
|
||||
return list(_pending_ui.pop(conv_id, []) or [])
|
||||
|
||||
|
||||
def clear_pending_ui(conv_id: str) -> None:
|
||||
with _pending_ui_lock:
|
||||
_pending_ui.pop(conv_id, None)
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
|
||||
@@ -35,6 +35,68 @@ _loaded_modules: dict = {}
|
||||
TOOL_TIMEOUT_S = 60
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 界面工具的开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 这三个工具由 AI 主动驱动界面,属于"会打扰用户"的能力,所以**默认关**,
|
||||
# 用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。
|
||||
UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation')
|
||||
|
||||
# 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键,
|
||||
# 以后加界面工具不必再动 settings 的形状。
|
||||
UI_TOOL_SETTINGS_KEY = 'uiTools'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 当前调用上下文(线程局部)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 为什么需要它:工具要拿到"当前是哪次对话"才能结束对话,但工具签名是
|
||||
# run(args) —— 只有模型给的参数,没有对话信息。
|
||||
#
|
||||
# 已有先例是往 settings 里塞 `nodeTools`(会议节点工具),但那是**工具定义**,
|
||||
# 不是**运行时上下文**;上下文每轮都在变,塞进 settings 会和"设置"的语义混在一起。
|
||||
#
|
||||
# 所以单独开一个 thread-local:agent_loop 在执行工具前 push,
|
||||
# 执行完 pop。HTTP 是每请求一线程,thread-local 天然隔离,不会串。
|
||||
_ctx = threading.local()
|
||||
|
||||
|
||||
def push_context(**kw) -> None:
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)"""
|
||||
_ctx.value = dict(kw)
|
||||
|
||||
|
||||
def clear_context() -> None:
|
||||
_ctx.value = None
|
||||
|
||||
|
||||
def current_context() -> dict:
|
||||
"""当前工具调用的上下文;不在调用中时返回空 dict"""
|
||||
return dict(getattr(_ctx, 'value', None) or {})
|
||||
|
||||
|
||||
def ui_tools_enabled(settings: dict) -> bool:
|
||||
"""
|
||||
界面工具开了没有。
|
||||
|
||||
★ 默认 **False**:这三个工具会让 AI 主动弹界面/弹窗、甚至结束对话,
|
||||
对用户是"打扰性"能力,不该装好就默认打开。
|
||||
"""
|
||||
box = (settings or {}).get(UI_TOOL_SETTINGS_KEY)
|
||||
if isinstance(box, dict):
|
||||
return box.get('enabled') is True
|
||||
if isinstance(box, bool):
|
||||
return box
|
||||
return False
|
||||
|
||||
|
||||
def filter_ui_tools(specs: list, settings: dict) -> list:
|
||||
"""开关关着时,把界面工具从工具表里摘掉(模型根本看不到,也就不会调)。"""
|
||||
if ui_tools_enabled(settings):
|
||||
return specs
|
||||
return [s for s in specs if s.get('name') not in UI_TOOLS]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 目录与文件
|
||||
@@ -235,9 +297,27 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
runner = getattr(module, 'run')
|
||||
|
||||
payload = args if isinstance(args, dict) else {}
|
||||
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
|
||||
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
|
||||
# 工作线程里 current_context() 永远是空的。
|
||||
#
|
||||
# 这个坑的表现特别隐蔽:工具照常执行(参数都对),只有"当前是哪次对话"
|
||||
# 拿不到,于是 end_conversation 报"拿不到当前对话 id"。我一开始以为是
|
||||
# app.py 没传 conversationId,查了一圈才发现是线程的问题。
|
||||
ctx = current_context()
|
||||
|
||||
def _invoke():
|
||||
if ctx:
|
||||
_ctx.value = dict(ctx)
|
||||
try:
|
||||
return runner(payload)
|
||||
finally:
|
||||
if ctx:
|
||||
_ctx.value = None
|
||||
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S)
|
||||
outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
@@ -381,6 +461,8 @@ def build_tool_defs(settings: dict) -> list:
|
||||
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
|
||||
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
|
||||
defs = defs + node_tool_defs(settings)
|
||||
# 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏
|
||||
defs = filter_ui_tools(defs, settings)
|
||||
return apply_security(defs, settings)
|
||||
|
||||
|
||||
@@ -393,6 +475,15 @@ def execute_tool(name: str, args: dict, settings: dict) -> dict:
|
||||
allow = ((settings or {}).get('security') or {}).get('allow') or []
|
||||
if name not in allow:
|
||||
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
|
||||
# ★ 界面工具的第二道拦截:开关关着时,即使模型硬编名字也不执行。
|
||||
# (第一道是 build_tool_defs 里根本不把它给模型看。)
|
||||
# 两道都要有 —— 只藏不给看的话,用户把工具关掉之后模型仍可能
|
||||
# 从历史消息里学会这个名字再调一次。
|
||||
if name in UI_TOOLS and not ui_tools_enabled(settings):
|
||||
return {
|
||||
'ok': False,
|
||||
'error': f'界面工具「{name}」已关闭。请在「技能」页打开"AI 界面能力"后再用。',
|
||||
}
|
||||
# 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义)
|
||||
if name in node_tool_names(settings):
|
||||
return run_node_tool(name, args, settings)
|
||||
|
||||
@@ -16,6 +16,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
import paths
|
||||
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
|
||||
@@ -62,6 +63,51 @@ def _safe_name(name: str) -> str:
|
||||
return cleaned[-60:]
|
||||
|
||||
|
||||
def _stamp() -> str:
|
||||
"""
|
||||
落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。
|
||||
|
||||
★ 以前这里用的是 `_ts36()`(base36 的毫秒数,形如 `m5k8xk2`)。
|
||||
它唯一的优点是不会重名,缺点是**看见文件名完全不知道是什么时候的东西** ——
|
||||
排查问题时只能一个个 `ls -la`。
|
||||
|
||||
用户明确反馈过这一点(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名
|
||||
临时件,无统一约定"。所以换成可读格式。
|
||||
|
||||
★ 秒级精度会撞名(同一秒传两个同名文件)。落盘前用 [_unique_path] 消歧,
|
||||
不靠时间戳本身保证唯一。
|
||||
"""
|
||||
return datetime.now().strftime('%Y%m%d-%H%M%S')
|
||||
|
||||
|
||||
def uploads_dir() -> str:
|
||||
"""
|
||||
附件的固定落地目录(绝对路径)。**只有这一个入口,别在别处拼路径。**
|
||||
|
||||
存在的意义是给"AI 拿到附件后想去 shell 里处理它"一个稳定约定 ——
|
||||
`attachment_payload` 会把 `path` 明明白白写进给模型的内容里,
|
||||
模型不必去猜文件在哪(bug 报告问题 5 的核心诉求)。
|
||||
"""
|
||||
return os.path.join(paths.get().uploads_dir, '').rstrip(os.sep)
|
||||
|
||||
|
||||
def _unique_path(directory: str, stamp: str, safe_name: str) -> str:
|
||||
"""
|
||||
`{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`…
|
||||
|
||||
★ 一定要保留扩展名:`report.pdf` 变成 `report-1.pdf` 而不是 `report.pdf-1` ——
|
||||
一堆工具(含我们自己的 `is_image()` / `mime_of()`)都按扩展名判断类型。
|
||||
"""
|
||||
base, ext = os.path.splitext(safe_name)
|
||||
for i in range(0, 1000):
|
||||
suffix = '' if i == 0 else f'-{i}'
|
||||
candidate = os.path.join(directory, f'{stamp}_{base}{suffix}{ext}')
|
||||
if not os.path.exists(candidate):
|
||||
return candidate
|
||||
# 极端情况:同秒同名超过 1000 个,交给随机后缀
|
||||
return os.path.join(directory, f'{stamp}_{base}-{_rand36(4)}{ext}')
|
||||
|
||||
|
||||
def _ext_of(name: str) -> str:
|
||||
return os.path.splitext(str(name or ''))[1].lower()
|
||||
|
||||
@@ -86,7 +132,8 @@ def _meta(file_path: str, name: str, copy: bool = True) -> dict:
|
||||
stored_path = file_path
|
||||
url = ''
|
||||
if copy and size <= COPY_LIMIT:
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(uploads_dir(), exist_ok=True)
|
||||
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
|
||||
with open(file_path, 'rb') as src, open(target, 'wb') as dst:
|
||||
while True:
|
||||
chunk = src.read(256 * 1024)
|
||||
@@ -118,8 +165,8 @@ def save_upload(name: str, base64_data: str) -> dict:
|
||||
raise ValueError(f'base64 解码失败:{exc}') from exc
|
||||
if len(buffer) > COPY_LIMIT:
|
||||
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
os.makedirs(uploads_dir(), exist_ok=True)
|
||||
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
|
||||
with open(target, 'wb') as fh:
|
||||
fh.write(buffer)
|
||||
return {
|
||||
@@ -158,21 +205,32 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
"""
|
||||
把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。
|
||||
返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。
|
||||
|
||||
★★★ **每一条分支都会把落盘的绝对路径写进 text。**
|
||||
|
||||
这一条是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉
|
||||
模型文件落在哪,模型想去 shell / python 里处理它只能靠猜,猜错就是
|
||||
FileNotFoundError。之前只有"二进制"那一条给了路径,文本和图片都没给 ——
|
||||
而**恰恰是文本最需要**:超过 20000 字符会被截断,被截掉的那部分
|
||||
只能靠模型自己去读原文件。
|
||||
|
||||
格式统一成 `本地路径:<绝对路径>`,模型一眼能捞出来。
|
||||
"""
|
||||
out = {'text': '', 'images': []}
|
||||
item = attachment or {}
|
||||
file_path = item.get('path') or ''
|
||||
name = item.get('name') or '未知'
|
||||
if not file_path or not os.path.isfile(file_path):
|
||||
out['text'] = f"【附件 {item.get('name') or '未知'} 已丢失】"
|
||||
out['text'] = f"【附件 {name} 已丢失】"
|
||||
return out
|
||||
size = os.path.getsize(file_path)
|
||||
if is_image(item.get('name')) and size <= VISION_LIMIT:
|
||||
if is_image(name) and size <= VISION_LIMIT:
|
||||
with open(file_path, 'rb') as fh:
|
||||
b64 = base64.b64encode(fh.read()).decode('ascii')
|
||||
out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"})
|
||||
out['text'] = f"【图片 {item.get('name')}】"
|
||||
out['text'] = f"【图片 {name}({size} 字节)本地路径:{file_path}】"
|
||||
return out
|
||||
if is_text(item.get('name')) or size < 64 * 1024:
|
||||
if is_text(name) or size < 64 * 1024:
|
||||
body = ''
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
|
||||
@@ -181,7 +239,10 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr)
|
||||
if body:
|
||||
clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body
|
||||
out['text'] = f"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
|
||||
out['text'] = (
|
||||
f"【文件 {name}({size} 字节)本地路径:{file_path}】\n"
|
||||
f'```\n{clipped}\n```'
|
||||
)
|
||||
return out
|
||||
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
out['text'] = f"【附件 {name}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
return out
|
||||
|
||||
254
android/termux-dpkg/README.md
Normal file
254
android/termux-dpkg/README.md
Normal file
@@ -0,0 +1,254 @@
|
||||
# 自编 dpkg —— 让内置 Termux 和真 Termux 能共存
|
||||
|
||||
这个目录里的东西,是为了把 **dpkg + apt 替成我们自己编的**,
|
||||
从而解决一个从根上无解的冲突。
|
||||
|
||||
---
|
||||
|
||||
## 要解决什么问题
|
||||
|
||||
内置 Termux 的二进制全部来自 Termux 官方仓库,它们是拿
|
||||
`--sysconfdir=$PREFIX/etc` 编的,而 `$PREFIX` 在**编译期**就固化成了
|
||||
|
||||
```
|
||||
/data/data/com.termux/files/usr
|
||||
```
|
||||
|
||||
于是在装了真 Termux 的手机上,我们的 `pkg install` 必死:
|
||||
|
||||
```
|
||||
dpkg: error: error opening configuration directory
|
||||
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
|
||||
E: Sub-process /data/user/0/com.doubao.lynxclone/files/usr/bin/dpkg returned an error code (2)
|
||||
```
|
||||
|
||||
**为什么绕不过去**(这些都实测过,不是推测):
|
||||
|
||||
| 试过的办法 | 为什么不行 |
|
||||
|---|---|
|
||||
| `--admindir` / `--instdir` / `--root` | 配置目录是**编译期常量**,跟 admindir 无关 |
|
||||
| `DPKG_ROOT` 等环境变量 | 上游没有这种变量(`strings dpkg \| grep '^DPKG_'` 里没有) |
|
||||
| `LD_PRELOAD=libtermux-exec.so` | 它只拦 `execve`,不碰 `opendir` |
|
||||
| 在 prefix 里造软链 | 软链只对**相对我们前缀**的路径有效;dpkg 走的是根下的绝对路径 |
|
||||
| 在 `/data/data` 下建 `com.termux` 软链 | `/data/data` 是 `drwxrwx--x system`,我们建不了 |
|
||||
| `unshare -m` + `mount --bind` | 应用没有 `CAP_SYS_ADMIN`,`Operation not permitted` |
|
||||
| 直接改二进制里的路径串 | 21 字节 → 40 字节,长度不等,改了就崩(`scripts/verify-elf-patch.py` 钉死了这条) |
|
||||
|
||||
关键细节:**dpkg 在解析命令行之前就去读配置目录**(上游维护者的原话:
|
||||
*"the config files are read before the options are parsed"*)。
|
||||
配置目录 `ENOENT` 是静默跳过,`EACCES` 直接致命退出 —— 真 Termux 的
|
||||
`/data/data/com.termux` 是 `0700`、属于另一个 UID,我们连穿都穿不进去。
|
||||
|
||||
所以唯一干净的出路是:**自己编一个**,把那一处换成运行时解析。
|
||||
|
||||
---
|
||||
|
||||
## 自编版改了什么
|
||||
|
||||
一共九处补丁,都在 `patches/doubao/`(由 `make-doubao-patches.py` 生成):
|
||||
|
||||
### 1. 配置目录改成运行时解析(核心)
|
||||
|
||||
上游 `lib/dpkg/options.c` 里只有**两处**用到编译期常量 `CONFIGDIR`。
|
||||
自编版换成一个函数,从 `/proc/self/exe` 反推前缀:
|
||||
|
||||
```
|
||||
/proc/self/exe = /data/user/0/<包名>/files/usr/bin/dpkg
|
||||
~~~~ 去掉 /bin/dpkg
|
||||
/data/user/0/<包名>/files/usr
|
||||
→ 配置目录 = <prefix>/etc/dpkg
|
||||
```
|
||||
|
||||
同一个二进制在任何包名下都指向**自己所在的前缀**,不需要为每个包名编一份。
|
||||
还留了 `DOUBAO_DPKG_PREFIX` 环境变量做显式覆盖(测试用)。
|
||||
|
||||
### 2. 架构名用 Termux 的写法
|
||||
|
||||
这条是**实测撞出来的**:Termux 仓库里包的 `Architecture` 字段是
|
||||
`x86_64` / `aarch64` / `arm` / `i686`(就是 GNU CPU 名),
|
||||
而 Debian 那边是 `amd64` / `arm64`。
|
||||
|
||||
用错名字的后果很大:dpkg 会把数据库里**每一个包**都判成
|
||||
|
||||
```
|
||||
'x86_64' is not a valid architecture name in 'Architecture' field:
|
||||
character '_' not allowed (only letters, digits and characters '-')
|
||||
```
|
||||
|
||||
而且 `x86_64` 带下划线,上游的架构名校验(C 侧 `lib/dpkg/arch.c`
|
||||
和 Perl 侧 `scripts/Dpkg/Arch.pm`)**两处都不让过**,所以两边都要放开。
|
||||
|
||||
`dpkg-architecture` 那边还绕了一下:上游的 `data/ostable` 里**根本没有
|
||||
`android` 这个操作系统**,所以 `*-linux-android` 这种三元组永远解析不出来,
|
||||
configure 会报 `cannot determine host dpkg architecture`。
|
||||
自编版在 `m4/dpkg-arch.m4` 里直接从 `$host_cpu` 取值。
|
||||
|
||||
> 顺带一个坑:`--host=x86_64-linux-android` 会被 `config.sub`
|
||||
> 规范化成 `x86_64-pc-linux-android`,所以 `$host_os` 是
|
||||
> **`linux-android`**,不是 `android`。匹配要写 `*android*`。
|
||||
|
||||
### 3. 修好 PATH 和 `LD_LIBRARY_PATH`
|
||||
|
||||
apt 派生 dpkg 时会**清洗环境**,塞给它一个指向**另一个 App 前缀**的 PATH
|
||||
(实录:`PATH=[/data/data/com.termux/files/usr/bin]`)。dpkg 于是报:
|
||||
|
||||
```
|
||||
dpkg: warning: 'sh' not found in PATH or not executable
|
||||
dpkg: error: 5 expected programs not found in PATH or not executable
|
||||
```
|
||||
|
||||
自编版在 `dpkg_options_load()` 之后(也就是任何 `checkpath()` 之前)
|
||||
按自己的前缀把 PATH / `LD_LIBRARY_PATH` 补上。
|
||||
|
||||
### 4. 改写维护脚本里的前缀
|
||||
|
||||
Termux 包的维护脚本整篇都是 Termux 前缀:
|
||||
|
||||
```sh
|
||||
#!/data/data/com.termux/files/usr/bin/sh
|
||||
mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_${a}_key"
|
||||
```
|
||||
|
||||
- 第一行由**内核**解析,落在另一个 App 的私有目录 → EACCES,
|
||||
而 dpkg 会把它显示成"脚本没有执行权限",**指错方向**
|
||||
- 后面那些是**根下的绝对路径**,我们的沙箱软链拦不住
|
||||
|
||||
脚本是纯文本,所以自编版在 exec 之前把 `DOUBAO_OLD_PREFIX` 换成自己的前缀。
|
||||
三条执行路径(`vmaintscript_installed` / `maintscript_new` /
|
||||
`maintscript_fallback`)都要挂上 —— 只挂一处的话 `--configure` 那条路
|
||||
(走的正是 `vmaintscript_installed`)不会有任何效果。
|
||||
|
||||
改完之后的实录:
|
||||
|
||||
```
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 怎么构建
|
||||
|
||||
```bash
|
||||
# 1. 下源码(依赖库 + termux-packages + dpkg)
|
||||
bash fetch-sources.sh /root/tb
|
||||
|
||||
# 2. 编依赖(libmd / zlib / bzip2 / liblzma / libzstd,给两个架构都来一遍)
|
||||
bash build-deps.sh x86_64
|
||||
bash build-deps.sh arm64
|
||||
|
||||
# 3. 编 dpkg
|
||||
bash build-dpkg.sh x86_64
|
||||
bash build-dpkg.sh arm64
|
||||
|
||||
# 4. 校验(每一条都对应一个真踩过的坑)
|
||||
python3 verify-dpkg.py x86_64
|
||||
python3 verify-dpkg.py arm64
|
||||
|
||||
# 5. 打包成 jniLibs 里的 .so
|
||||
bash make-jnilibs.sh /root/tb ../app/src/main/jniLibs
|
||||
```
|
||||
|
||||
需要的环境变量(都有默认值):
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `ANDROID_NDK` | `/root/tb/android-ndk-r27c` | NDK 根目录 |
|
||||
| `TERMUX_DPKG_WORK` | `/root/tb` | 工作目录 |
|
||||
| `TERMUX_DPKG_SRC` | `$WORK/src/dpkg` | dpkg 源码(**必须 git checkout**) |
|
||||
| `DOUBAO_PREFIX` | `com.doubao.lynxclone` 的前缀 | 编译进二进制的兜底前缀 |
|
||||
|
||||
改了 `make-doubao-patches.py` 之后要重新生成补丁:
|
||||
|
||||
```bash
|
||||
python3 make-doubao-patches.py /root/tb/src/dpkg patches/doubao
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 几个构建上的坑
|
||||
|
||||
**dpkg 源码必须是 git checkout。** 它的 `build-aux/get-version` 要用 git
|
||||
(或发行 tarball)定版本号,`git archive` 出来的树会让 `autogen` 报
|
||||
`cannot get project version`。构建脚本用 `git worktree` 解决(共享 `.git`,
|
||||
树是干净的,还能随手删掉重来)。
|
||||
|
||||
**补丁不要手写。** hunk 头(`@@ -55,6 +55,22 @@`)的行号必须和源码逐字对上,
|
||||
手数极容易错 —— 我错过两次:一次少一行 `malformed patch`,
|
||||
一次多一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 **patch 两种都不报错**,
|
||||
只是行为诡异。所以补丁一律用 `diff -u` 从"改好的文件"生成。
|
||||
|
||||
**依赖库全部静态链进去。** 只有 `libmd` 是硬依赖(`readelf -d` 显示
|
||||
Termux 的 dpkg 只 NEEDED `libmd.so` + `libc.so`,zlib/bz2/lzma/zstd 都是
|
||||
可选),全静态链进去就不依赖运行时环境。
|
||||
|
||||
**RUNPATH 要烧进 ELF。** dpkg 会 exec 出 `dpkg-query` / `dpkg-deb`
|
||||
这些辅助程序,那些进程不一定继承到 `LD_LIBRARY_PATH`:
|
||||
|
||||
```
|
||||
-Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags
|
||||
```
|
||||
|
||||
**xz 的 configure 会在 CFLAGS 上做 `-Werror` 试编译**,而
|
||||
`-D__ANDROID_API__=24` 会触发它的告警,于是它误判 CFLAGS 有问题直接退出。
|
||||
加 `SKIP_WERROR_CHECK=yes` 跳过。
|
||||
|
||||
**`dpkg-realpath` 是 shell 脚本不是 ELF**,strip 会失败,忽略即可。
|
||||
|
||||
---
|
||||
|
||||
## 怎么打进 APK
|
||||
|
||||
`make-jnilibs.sh` 把六个程序打成一个 **tar 包**,改名成
|
||||
`lib/<abi>/libdoubao-dpkg.so`。
|
||||
|
||||
为什么不放 `assets/`:Android 安装 APK 时只对 `lib/<abi>/*.so`
|
||||
免压缩解包,别的路径会被压缩、还得自己再解一遍。
|
||||
这也跟这个仓库里 `libtermux-bootstrap.so` 的做法一致。
|
||||
|
||||
Kotlin 侧的解包在 `TermuxInstaller.installOwnDpkg()`,是手写的 ustar 读取
|
||||
(只认普通文件、拒绝带斜杠的名字),为了这点事不值得引一个 tar 库。
|
||||
|
||||
装好之后 **`bin/dpkg.real` + wrapper 那一套就不需要了** ——
|
||||
wrapper 本来就是在绕"配置目录编译死"这个我们已经从根上修掉的问题。
|
||||
|
||||
---
|
||||
|
||||
## 校验脚本守什么
|
||||
|
||||
`verify-dpkg.py` 守的每一条都对应一个踩过的坑:
|
||||
|
||||
1. 六个程序齐全、架构正确
|
||||
2. 二进制里的 `com.termux` 字符串**只允许**是重写函数自己要匹配的模式 ——
|
||||
出现别的(尤其是配置目录)就说明补丁没生效,装上必然 EACCES
|
||||
3. 有 `/proc/self/exe`(运行时前缀的前提)
|
||||
4. 不能出现 `amd64` / `arm64`(Termux 用 GNU CPU 名)
|
||||
5. 源码里架构名校验放开了下划线
|
||||
6. RUNPATH 指向前缀 `lib`
|
||||
7. 不依赖 `libmd.so`(已静态链入)
|
||||
|
||||
---
|
||||
|
||||
## 实测结果(Android 14 x86_64 模拟器,**真 Termux 同时装着**)
|
||||
|
||||
真 Termux 的目录权限一直是 `drwx------ u0_a109`,我们全程读不到它。
|
||||
|
||||
```
|
||||
$ pkg install -y openssh
|
||||
...
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
|
||||
$ dpkg -l | grep -c '^i[^i]' # 未配置项
|
||||
0
|
||||
$ ssh -V
|
||||
OpenSSH_10.6p1, OpenSSL 3.4.1 11 Feb 2025
|
||||
```
|
||||
|
||||
另外验证过的:`nmap`、`git 2.56.0` 全新安装(含 `lua54` / `libpcap` /
|
||||
`openssh` 这些带 postinst 的依赖链)全部 `未配置 = 0`。
|
||||
126
android/termux-dpkg/build-deps.sh
Normal file
126
android/termux-dpkg/build-deps.sh
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg 需要的静态库
|
||||
#
|
||||
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
|
||||
#
|
||||
# 需要的环境变量(都有默认值,默认是开发机上的位置):
|
||||
# ANDROID_NDK NDK 根目录
|
||||
# TERMUX_DPKG_WORK 工作目录(下载源码、解包、编译中间产物都放这里)
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
|
||||
|
||||
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
|
||||
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
|
||||
SRC="$WORK/dl"
|
||||
OUT="$WORK/out/$ARCH"
|
||||
API="${ANDROID_API:-24}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
export LDFLAGS=""
|
||||
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; echo " 设一下 ANDROID_NDK"; exit 1; }
|
||||
echo "### arch=$ARCH CC=$CC"
|
||||
"$CC" --version | head -1
|
||||
|
||||
mkdir -p "$OUT/lib" "$OUT/include" "$WORK/work"
|
||||
cd "$WORK/work"
|
||||
|
||||
# 每个库都单独判断,编过就跳过,方便断点续编
|
||||
need() { [ ! -f "$OUT/lib/$1" ]; }
|
||||
|
||||
########################################
|
||||
# libmd 1.3.0 —— dpkg 唯一必需的第三方库
|
||||
########################################
|
||||
if need libmd.a; then
|
||||
echo "=== libmd ==="
|
||||
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
|
||||
cd libmd-1.3.0
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static >/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libmd.a" ] && echo " ✓ libmd" || echo " ✗ libmd 失败"
|
||||
|
||||
########################################
|
||||
# zlib
|
||||
########################################
|
||||
if need libz.a; then
|
||||
echo "=== zlib ==="
|
||||
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
|
||||
cd zlib-1.3.2
|
||||
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
|
||||
make -j"$(nproc)" libz.a >/dev/null 2>&1
|
||||
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libz.a" ] && echo " ✓ zlib" || echo " ✗ zlib 失败"
|
||||
|
||||
########################################
|
||||
# bzip2 1.0.8
|
||||
########################################
|
||||
if need libbz2.a; then
|
||||
echo "=== bzip2 ==="
|
||||
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
|
||||
cd bzip2-1.0.8
|
||||
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
|
||||
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libbz2.a" ] && echo " ✓ bzip2" || echo " ✗ bzip2 失败"
|
||||
|
||||
########################################
|
||||
# liblzma (xz)
|
||||
########################################
|
||||
if need liblzma.a; then
|
||||
echo "=== liblzma ==="
|
||||
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
|
||||
cd xz-5.8.4
|
||||
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,而
|
||||
# -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static \
|
||||
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
|
||||
--disable-scripts --disable-doc --disable-nls \
|
||||
SKIP_WERROR_CHECK=yes \
|
||||
>/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/liblzma.a" ] && echo " ✓ liblzma" || echo " ✗ liblzma 失败"
|
||||
|
||||
########################################
|
||||
# libzstd
|
||||
########################################
|
||||
if need libzstd.a; then
|
||||
echo "=== libzstd ==="
|
||||
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
|
||||
cd zstd-1.5.7/lib
|
||||
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS" >/dev/null 2>&1
|
||||
cp libzstd.a "$OUT/lib/"
|
||||
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
|
||||
cd ../..
|
||||
fi
|
||||
[ -f "$OUT/lib/libzstd.a" ] && echo " ✓ libzstd" || echo " ✗ libzstd 失败"
|
||||
|
||||
echo
|
||||
echo "=== $ARCH 产物 ==="
|
||||
ls -la "$OUT/lib/"*.a
|
||||
149
android/termux-dpkg/build-dpkg.sh
Normal file
149
android/termux-dpkg/build-dpkg.sh
Normal file
@@ -0,0 +1,149 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg(用 Termux 的补丁 + 我们自己的运行时前缀补丁)
|
||||
#
|
||||
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
|
||||
#
|
||||
# 环境变量(都有默认值):
|
||||
# ANDROID_NDK NDK 根目录
|
||||
# TERMUX_DPKG_WORK 工作目录
|
||||
# TERMUX_DPKG_SRC dpkg 源码目录(必须是 git checkout)
|
||||
# DOUBAO_PREFIX 编译进二进制的兜底前缀(运行时会被 /proc/self/exe 覆盖)
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
|
||||
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
|
||||
SRC="${TERMUX_DPKG_SRC:-$WORK/src/dpkg}"
|
||||
DEPS="$WORK/out/$ARCH"
|
||||
OUT="$WORK/out/$ARCH"
|
||||
API="${ANDROID_API:-24}"
|
||||
PREFIX="${DOUBAO_PREFIX:-/data/data/com.doubao.lynxclone/files/usr}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CPPFLAGS="-I$DEPS/include"
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
|
||||
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
|
||||
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags"
|
||||
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
|
||||
|
||||
BUILD="$WORK/build/dpkg-$ARCH"
|
||||
mkdir -p "$WORK/build" "$BUILD"
|
||||
|
||||
echo "########## 0. 检查前提 ##########"
|
||||
[ -d "$SRC/.git" ] || { echo "!! $SRC 不是 git checkout(dpkg 的 get-version 要求)"; exit 1; }
|
||||
[ -f "$DEPS/lib/libmd.a" ] || { echo "!! 先跑 build-deps.sh $ARCH"; exit 1; }
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
|
||||
echo " src=$SRC"
|
||||
echo " 前缀=$PREFIX"
|
||||
|
||||
echo "########## 1. 准备源码树 ##########"
|
||||
# 不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要一个真正的
|
||||
# git checkout(或发行 tarball)才能定出版本号。用 git worktree:共享 .git,
|
||||
# 树是干净的,而且可以随时删掉重来。
|
||||
cd "$SRC"
|
||||
git worktree remove --force "$BUILD" 2>/dev/null || true
|
||||
rm -rf "$BUILD"
|
||||
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
|
||||
echo "git worktree 失败"; exit 1; }
|
||||
cd "$BUILD"
|
||||
echo " worktree 就绪: $(pwd)"
|
||||
|
||||
apply() { # apply <补丁文件> [必需]
|
||||
local p="$1" must="${2:-}"
|
||||
local n; n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n"
|
||||
patch -p1 -N -l -i "$p" 2>&1 | head -15
|
||||
[ -n "$must" ] && exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
echo "########## 2. Termux 上游补丁 ##########"
|
||||
for p in "$HERE"/patches/termux/*.patch; do apply "$p"; done
|
||||
|
||||
echo "########## 3. 我们自己的补丁 ##########"
|
||||
for p in "$HERE"/patches/doubao/*.patch; do apply "$p" required; done
|
||||
|
||||
echo "########## 4. autogen ##########"
|
||||
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
|
||||
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
|
||||
NOCONFIGURE=1 sh ./autogen > "$BUILD/autogen.log" 2>&1 || {
|
||||
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
|
||||
fi
|
||||
echo " configure 就绪"
|
||||
|
||||
echo "########## 5. configure ##########"
|
||||
# PERL: 宿主机 perl 版本可能低于 dpkg 要求的 5.32.1。perl 只用于构建期脚本
|
||||
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
|
||||
# perl 在哪,跳过版本探测。
|
||||
#
|
||||
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
|
||||
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
|
||||
./configure \
|
||||
--host="$TRIPLE" \
|
||||
--build="$(uname -m)-pc-linux-gnu" \
|
||||
--prefix="$PREFIX" \
|
||||
--bindir="$PREFIX/bin" \
|
||||
--libdir="$PREFIX/lib" \
|
||||
--sysconfdir="$PREFIX/etc" \
|
||||
--localstatedir="$PREFIX/var" \
|
||||
--disable-shared \
|
||||
--disable-dselect \
|
||||
--disable-start-stop-daemon \
|
||||
--disable-update-alternatives \
|
||||
--disable-largefile \
|
||||
--disable-nls \
|
||||
--without-selinux \
|
||||
--without-libselinux \
|
||||
--without-systemd \
|
||||
PERL="${PERL:-$(command -v perl)}" \
|
||||
ac_cv_lib_selinux_setexecfilecon=no \
|
||||
dpkg_cv_c99_snprintf=yes \
|
||||
DPKG_PAGER=pager \
|
||||
> "$BUILD/configure.log" 2>&1 || {
|
||||
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
|
||||
echo " ✓ configure 通过"
|
||||
|
||||
echo "########## 6. make ##########"
|
||||
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
|
||||
echo "make 失败,错误摘要:"
|
||||
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
|
||||
exit 1; }
|
||||
echo " ✓ make 通过"
|
||||
|
||||
echo "########## 7. 收集产物 ##########"
|
||||
mkdir -p "$OUT/dpkg-bin"
|
||||
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger; do
|
||||
f=""
|
||||
for cand in "src/dpkg/main/.libs/$b" "src/dpkg/deb/.libs/$b" \
|
||||
"src/dpkg/split/.libs/$b" "src/dpkg/query/.libs/$b" \
|
||||
"src/dpkg/divert/.libs/$b" "src/dpkg/trigger/.libs/$b" \
|
||||
"src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
|
||||
"src/$b" "src/main/$b" "utils/$b"; do
|
||||
[ -f "$cand" ] && { f="$cand"; break; }
|
||||
done
|
||||
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
|
||||
cp "$f" "$OUT/dpkg-bin/$b"
|
||||
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b"
|
||||
done
|
||||
|
||||
echo
|
||||
ls -la "$OUT/dpkg-bin/"
|
||||
echo
|
||||
echo "产物在 $OUT/dpkg-bin/"
|
||||
29
android/termux-dpkg/extract-termux-patches.sh
Normal file
29
android/termux-dpkg/extract-termux-patches.sh
Normal file
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# 从 termux-packages 里把 dpkg 的上游补丁抽到本仓库。
|
||||
#
|
||||
# 为什么要把它们拷进仓库:build-dpkg.sh 依赖这批补丁才能让 dpkg 在 Android 上
|
||||
# 跑起来(Android 不支持硬链接、应用没有 chown 权限、不允许 root 检查……)。
|
||||
# 直接引用 termux-packages 的 checkout 会让构建依赖一个会随时变化的 master,
|
||||
# 所以拷一份固定下来。
|
||||
#
|
||||
# 用法: extract-termux-patches.sh [termux-packages 路径]
|
||||
set -eu
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
TP="${1:-${TERMUX_DPKG_WORK:-/root/tb}/termux-packages}"
|
||||
SRCDIR="$TP/packages/dpkg"
|
||||
DST="$HERE/patches/termux"
|
||||
|
||||
[ -d "$SRCDIR" ] || { echo "!! 找不到 $SRCDIR"; echo " 先跑 fetch-sources.sh"; exit 1; }
|
||||
|
||||
mkdir -p "$DST"
|
||||
cd "$SRCDIR"
|
||||
for f in *.patch; do
|
||||
[ -f "$f" ] || continue
|
||||
cp "$f" "$DST/termux-$f"
|
||||
printf ' %s\n' "termux-$f"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "已拷到 $DST:"
|
||||
ls -la "$DST"
|
||||
76
android/termux-dpkg/fetch-sources.sh
Normal file
76
android/termux-dpkg/fetch-sources.sh
Normal file
@@ -0,0 +1,76 @@
|
||||
#!/bin/bash
|
||||
# 下载构建 dpkg 需要的全部源码。
|
||||
#
|
||||
# 用法: fetch-sources.sh [工作目录]
|
||||
#
|
||||
# 说明几个源的选择:
|
||||
# - GitHub 在部分网络下连不上,但 codeload.github.com 通常可以,
|
||||
# 所以 termux-packages 走 codeload 的 tarball 接口。
|
||||
# - dpkg 源码必须在 git 仓库里(build-aux/get-version 依赖它来判断版本号),
|
||||
# 所以从 salsa.debian.org 克隆。
|
||||
# - 依赖库都从 Debian 镜像取 orig.tar,避免各上游站点可达性不一致。
|
||||
set -eu
|
||||
|
||||
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
|
||||
DL="$WORK/dl"
|
||||
SRC="$WORK/src"
|
||||
mkdir -p "$DL" "$SRC"
|
||||
|
||||
# -4:WSL 里 packages.termux.dev 会解析出 IPv6,而那条路不通,curl 会卡住
|
||||
CURL="curl -4 -fsSL --retry 3 --retry-delay 3"
|
||||
|
||||
get() { # get <文件名> <url...> 依次尝试,成功即止
|
||||
local name="$1"; shift
|
||||
if [ -s "$DL/$name" ]; then echo " 已有 $name"; return 0; fi
|
||||
local u
|
||||
for u in "$@"; do
|
||||
if $CURL -o "$DL/$name" "$u" 2>/dev/null; then
|
||||
printf ' ✓ %-22s %s 字节\n' "$name" "$(stat -c%s "$DL/$name")"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
printf ' ✗ %-22s 全部源都失败\n' "$name"
|
||||
return 1
|
||||
}
|
||||
|
||||
TUNA=https://mirrors.tuna.tsinghua.edu.cn/debian/pool/main
|
||||
DEB=https://deb.debian.org/debian/pool/main
|
||||
|
||||
echo "=== 依赖库源码 ==="
|
||||
get libmd.tar.xz "$DEB/libm/libmd/libmd_1.3.0.orig.tar.xz" \
|
||||
"$TUNA/libm/libmd/libmd_1.3.0.orig.tar.xz"
|
||||
get zlib.tar.gz "https://zlib.net/zlib-1.3.2.tar.gz" \
|
||||
"$TUNA/z/zlib/zlib_1.3.2.orig.tar.gz"
|
||||
get bzip2.tar.gz "https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz" \
|
||||
"$TUNA/b/bzip2/bzip2_1.0.8.orig.tar.gz"
|
||||
get xz.tar.xz "https://tukaani.org/xz/xz-5.8.4.tar.xz" \
|
||||
"$TUNA/x/xz-utils/xz-utils_5.8.4.orig.tar.xz"
|
||||
get zstd.tar.gz "https://codeload.github.com/facebook/zstd/tar.gz/refs/tags/v1.5.7"
|
||||
|
||||
echo
|
||||
echo "=== Termux 的 dpkg 补丁(从 termux-packages 抽) ==="
|
||||
TP="$WORK/termux-packages"
|
||||
if [ ! -d "$TP/packages/dpkg" ]; then
|
||||
echo " 拉 termux-packages…"
|
||||
$CURL -o "$DL/tp.tar.gz" \
|
||||
"https://codeload.github.com/termux/termux-packages/tar.gz/refs/heads/master"
|
||||
rm -rf "$TP"
|
||||
tar xzf "$DL/tp.tar.gz" -C "$WORK"
|
||||
mv "$WORK/termux-packages-master" "$TP"
|
||||
fi
|
||||
echo " termux-packages: $TP"
|
||||
ls "$TP/packages/dpkg/" | head -20
|
||||
|
||||
echo
|
||||
echo "=== dpkg 源码(必须 git checkout) ==="
|
||||
if [ ! -d "$SRC/dpkg/.git" ]; then
|
||||
echo " 克隆 dpkg 1.22.6…"
|
||||
timeout 900 git clone --depth 1 --branch 1.22.6 \
|
||||
https://salsa.debian.org/dpkg-team/dpkg.git "$SRC/dpkg"
|
||||
fi
|
||||
echo " dpkg: $(cd "$SRC/dpkg" && git log --oneline -1)"
|
||||
|
||||
echo
|
||||
echo "全部就绪。接下来:"
|
||||
echo " bash build-deps.sh x86_64 # 或 arm64"
|
||||
echo " bash build-dpkg.sh x86_64"
|
||||
659
android/termux-dpkg/make-doubao-patches.py
Normal file
659
android/termux-dpkg/make-doubao-patches.py
Normal file
@@ -0,0 +1,659 @@
|
||||
#!/usr/bin/env python3
|
||||
"""生成"我们自己"的 dpkg 补丁。
|
||||
|
||||
为什么要单独一个脚本生成补丁,而不是把补丁直接写死在仓库里:
|
||||
|
||||
补丁的 hunk 头(`@@ -55,6 +55,22 @@`)里的行号必须和 dpkg 源码逐字对上,
|
||||
手写极容易数错——我就在这上面栽过两次,一次少写一行导致 `malformed patch`,
|
||||
一次多写一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 patch 两个都不报错、
|
||||
只是行为诡异。
|
||||
|
||||
所以这里的做法是:从 git 取出原始文件,用 Python 做结构化的文本替换,
|
||||
再用 `diff -u` 生成补丁。diff 产出的 hunk 头永远是对的。
|
||||
|
||||
用法:
|
||||
python3 make-doubao-patches.py <dpkg源码目录> [输出目录]
|
||||
|
||||
需要 dpkg 源码是一个 git checkout(dpkg 自己的 build-aux/get-version 也要求如此)。
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
OUT = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), "patches", "doubao")
|
||||
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
|
||||
def git_show(rel):
|
||||
r = subprocess.run(["git", "show", "HEAD:" + rel], cwd=SRC,
|
||||
capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit(f"git show HEAD:{rel} 失败:{r.stderr.strip()}")
|
||||
return r.stdout
|
||||
|
||||
|
||||
def write_patch(rel, old, new, name):
|
||||
"""old -> new 的补丁,路径写成 a/<rel> b/<rel>,供 patch -p1 使用。"""
|
||||
a = os.path.join(tempfile.mkdtemp(), "a")
|
||||
b = os.path.join(tempfile.mkdtemp(), "b")
|
||||
open(a, "w").write(old)
|
||||
open(b, "w").write(new)
|
||||
r = subprocess.run(["diff", "-u", a, b], capture_output=True, text=True)
|
||||
body = r.stdout.replace(a, "a/" + rel, 1).replace(b, "b/" + rel, 1)
|
||||
path = os.path.join(OUT, name)
|
||||
open(path, "w").write(body)
|
||||
print(f" → {name} ({len(body.splitlines())} 行)")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. 头文件
|
||||
# ======================================================================
|
||||
HEADER = '''/*
|
||||
* doubao-prefix.h - resolve the installation prefix at runtime
|
||||
*
|
||||
* Copyright (C) 2026 doubao-clone
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*/
|
||||
|
||||
#ifndef DOUBAO_PREFIX_H
|
||||
#define DOUBAO_PREFIX_H
|
||||
|
||||
#include <dpkg/dpkg.h>
|
||||
|
||||
DPKG_BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* Return the prefix this dpkg was installed under.
|
||||
*
|
||||
* The prefix is derived from the path of the running executable, because
|
||||
* Android hands every application its own private data directory and the
|
||||
* same binary has to work under any of them. Falls back to the compile-time
|
||||
* DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
|
||||
*/
|
||||
const char *doubao_prefix(void);
|
||||
|
||||
/**
|
||||
* Return the configuration directory ($prefix/etc/dpkg).
|
||||
*/
|
||||
const char *doubao_config_dir(void);
|
||||
|
||||
/**
|
||||
* Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
|
||||
* own lib directory.
|
||||
*
|
||||
* Needed because apt sanitises the environment before it execs dpkg, and the
|
||||
* PATH it hands over names the *other* application's prefix; dpkg would then
|
||||
* fail its own sanity check with "expected programs not found in PATH".
|
||||
*/
|
||||
void doubao_fix_environment(void);
|
||||
|
||||
/**
|
||||
* Rewrite a maintainer script's interpreter line so it points at this
|
||||
* installation instead of the application it was built for.
|
||||
*/
|
||||
void doubao_fix_script_shebang(const char *path);
|
||||
|
||||
DPKG_END_DECLS
|
||||
|
||||
#endif /* DOUBAO_PREFIX_H */
|
||||
'''
|
||||
|
||||
# ======================================================================
|
||||
# 2. 实现
|
||||
# ======================================================================
|
||||
IMPL = r'''/*
|
||||
* doubao-prefix.c - resolve the installation prefix at runtime
|
||||
*
|
||||
* Copyright (C) 2026 doubao-clone
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Upstream dpkg bakes its configuration directory in at configure time
|
||||
* (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
|
||||
* fixed absolute path chosen by the Termux application. Android gives every
|
||||
* application its own private data directory, so a dpkg built for
|
||||
* com.termux will always look inside /data/data/com.termux -- a directory
|
||||
* another application is not allowed to traverse. The resulting EACCES makes
|
||||
* dpkg abort before it has even parsed its command line, which is why the two
|
||||
* applications cannot coexist.
|
||||
*
|
||||
* We instead derive the prefix from the path of the running executable, which
|
||||
* is exactly where this binary happens to live. That also lets us repair
|
||||
* PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
|
||||
* all of which upstream assumes are already correct.
|
||||
*/
|
||||
|
||||
#include <config.h>
|
||||
#include <compat.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <dpkg/i18n.h>
|
||||
#include <dpkg/debug.h>
|
||||
#include <dpkg/dpkg.h>
|
||||
#include <dpkg/doubao-prefix.h>
|
||||
|
||||
/* How many distinct strings we keep alive so returned pointers stay valid. */
|
||||
#define DOUBAO_CACHE_SLOTS 4
|
||||
|
||||
static char prefix_buf[PATH_MAX];
|
||||
static const char *prefix_cached;
|
||||
static char config_buf[PATH_MAX];
|
||||
|
||||
static void
|
||||
doubao_prefix_resolve(void)
|
||||
{
|
||||
char self[PATH_MAX];
|
||||
const char *override;
|
||||
char *slash;
|
||||
ssize_t n;
|
||||
|
||||
if (prefix_cached != NULL)
|
||||
return;
|
||||
|
||||
prefix_cached = DOUBAO_DEFAULT_PREFIX;
|
||||
|
||||
override = getenv("DOUBAO_DPKG_PREFIX");
|
||||
if (override != NULL) {
|
||||
if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
|
||||
strcpy(prefix_buf, override);
|
||||
prefix_cached = prefix_buf;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
n = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
if (n <= 0 || (size_t)n >= sizeof(self) - 1)
|
||||
return;
|
||||
self[n] = '\0';
|
||||
|
||||
/* .../bin/dpkg -> .../bin -> ... */
|
||||
slash = strrchr(self, '/');
|
||||
if (slash == NULL)
|
||||
return;
|
||||
*slash = '\0';
|
||||
|
||||
slash = strrchr(self, '/');
|
||||
if (slash == NULL)
|
||||
return;
|
||||
*slash = '\0';
|
||||
|
||||
if (strlen(self) < sizeof(prefix_buf)) {
|
||||
strcpy(prefix_buf, self);
|
||||
prefix_cached = prefix_buf;
|
||||
}
|
||||
}
|
||||
|
||||
const char *
|
||||
doubao_prefix(void)
|
||||
{
|
||||
doubao_prefix_resolve();
|
||||
return prefix_cached;
|
||||
}
|
||||
|
||||
const char *
|
||||
doubao_config_dir(void)
|
||||
{
|
||||
const char *prefix = doubao_prefix();
|
||||
|
||||
if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
|
||||
>= (int)sizeof(config_buf))
|
||||
return CONFIGDIR;
|
||||
|
||||
return config_buf;
|
||||
}
|
||||
|
||||
/*
|
||||
* Prepend our own bin directories to PATH and make sure the loader can find
|
||||
* our shared libraries, so that dpkg and the maintainer scripts it runs work
|
||||
* no matter what environment our parent handed us.
|
||||
*/
|
||||
void
|
||||
doubao_fix_environment(void)
|
||||
{
|
||||
static bool done = false;
|
||||
static char pathbuf[4 * PATH_MAX];
|
||||
static char libbuf[PATH_MAX + 64];
|
||||
|
||||
const char *prefix, *old;
|
||||
size_t len;
|
||||
|
||||
if (done)
|
||||
return;
|
||||
done = true;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
|
||||
old = getenv("PATH");
|
||||
/* Only prepend when our prefix is not already the first entry, so that
|
||||
* a re-exec does not keep growing PATH. */
|
||||
len = strlen(prefix);
|
||||
if (old == NULL || strncmp(old, prefix, len) != 0 ||
|
||||
strncmp(old + len, "/bin:", 5) != 0) {
|
||||
if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
|
||||
prefix, prefix, old != NULL ? old : "/system/bin")
|
||||
< (int)sizeof(pathbuf))
|
||||
setenv("PATH", pathbuf, 1);
|
||||
}
|
||||
|
||||
if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
|
||||
prefix) < (int)sizeof(libbuf))
|
||||
setenv("LD_LIBRARY_PATH", libbuf, 1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Maintainer scripts inside a Termux package are written in terms of the
|
||||
* Termux prefix:
|
||||
*
|
||||
* #!/data/data/com.termux/files/usr/bin/sh
|
||||
* mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
* KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
|
||||
*
|
||||
* Neither form works for us. The interpreter line is resolved by the kernel
|
||||
* and lands in another application's private directory (EACCES, which dpkg
|
||||
* then reports as though the script itself were not executable), and the
|
||||
* absolute paths are absolute -- our sandbox symlinks live under our own
|
||||
* prefix and cannot intercept a path that starts at "/".
|
||||
*
|
||||
* The scripts are plain text, so rewrite both before executing them. This is
|
||||
* a local edit of the dpkg database rather than a change to the package, so
|
||||
* it also covers packages installed long after this code was written.
|
||||
*/
|
||||
#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
|
||||
|
||||
static void
|
||||
doubao_rewrite_script(const char *path)
|
||||
{
|
||||
char *buf;
|
||||
char *out;
|
||||
const char *prefix;
|
||||
size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
|
||||
size_t newlen, len, cap;
|
||||
size_t i, o;
|
||||
int fd;
|
||||
ssize_t n;
|
||||
struct stat st;
|
||||
|
||||
if (path == NULL)
|
||||
return;
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return;
|
||||
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
|
||||
st.st_size > 1024 * 1024) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
len = (size_t)st.st_size;
|
||||
buf = malloc(len + 1);
|
||||
if (buf == NULL) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
n = read(fd, buf, len);
|
||||
close(fd);
|
||||
if (n <= 0) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
buf[n] = '\0';
|
||||
len = (size_t)n;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
newlen = strlen(prefix);
|
||||
|
||||
/* 先看有没有要换的东西,没有就别写盘 */
|
||||
for (i = 0; i + oldlen <= len; i++) {
|
||||
if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
|
||||
break;
|
||||
}
|
||||
if (i + oldlen > len) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
/* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
|
||||
cap = len + 64;
|
||||
out = malloc(cap);
|
||||
if (out == NULL) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
for (i = 0, o = 0; i < len; ) {
|
||||
if (i + oldlen <= len &&
|
||||
memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
|
||||
if (o + newlen + (len - i) + 2 > cap) {
|
||||
cap = (o + newlen + (len - i) + 2) * 2;
|
||||
out = realloc(out, cap);
|
||||
if (out == NULL) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
}
|
||||
memcpy(out + o, prefix, newlen);
|
||||
o += newlen;
|
||||
i += oldlen;
|
||||
} else {
|
||||
out[o++] = buf[i++];
|
||||
}
|
||||
}
|
||||
out[o] = '\0';
|
||||
free(buf);
|
||||
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0) {
|
||||
free(out);
|
||||
return;
|
||||
}
|
||||
if (write(fd, out, o) != (ssize_t)o) {
|
||||
close(fd);
|
||||
free(out);
|
||||
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
}
|
||||
close(fd);
|
||||
free(out);
|
||||
|
||||
debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
|
||||
}
|
||||
|
||||
/*
|
||||
* 把维护脚本的 shebang 换成本安装自己的 shell。
|
||||
*
|
||||
* 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
|
||||
* 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
|
||||
* 于是报 `bin/pip: line 2: import: command not found`。
|
||||
* 规则是"只换路径,不动解释器"。
|
||||
*/
|
||||
void
|
||||
doubao_fix_script_shebang(const char *path)
|
||||
{
|
||||
static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
|
||||
/* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
|
||||
* 写法,包里两种都出现过,所以两个都要认。 */
|
||||
static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
|
||||
|
||||
char buf[PATH_MAX + 256];
|
||||
const char *prefix;
|
||||
char *nl;
|
||||
int fd;
|
||||
ssize_t n;
|
||||
ssize_t skip = -1;
|
||||
size_t head, rest, total;
|
||||
char *fixed;
|
||||
|
||||
if (path == NULL)
|
||||
return;
|
||||
|
||||
/* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
|
||||
doubao_rewrite_script(path);
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return;
|
||||
|
||||
n = read(fd, buf, sizeof(buf) - 1);
|
||||
close(fd);
|
||||
if (n <= 0)
|
||||
return;
|
||||
buf[n] = '\0';
|
||||
|
||||
if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
|
||||
skip = (ssize_t)(sizeof(old_shebang) - 1);
|
||||
else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
|
||||
skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
|
||||
|
||||
if (skip < 0)
|
||||
return;
|
||||
|
||||
nl = strchr(buf, '\n');
|
||||
if (nl == NULL)
|
||||
return;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
|
||||
rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
|
||||
total = head + rest;
|
||||
if (total + 1 > sizeof(buf))
|
||||
return;
|
||||
|
||||
fixed = malloc(total + 1);
|
||||
if (fixed == NULL)
|
||||
return;
|
||||
|
||||
fixed[0] = '#';
|
||||
fixed[1] = '!';
|
||||
memcpy(fixed + 2, prefix, strlen(prefix));
|
||||
fixed[2 + strlen(prefix)] = '/';
|
||||
memcpy(fixed + head, buf + skip, rest);
|
||||
fixed[total] = '\0';
|
||||
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0) {
|
||||
free(fixed);
|
||||
return;
|
||||
}
|
||||
if (write(fd, fixed, total) != (ssize_t)total)
|
||||
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
close(fd);
|
||||
free(fixed);
|
||||
|
||||
debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
|
||||
}
|
||||
'''
|
||||
|
||||
write_patch("lib/dpkg/doubao-prefix.h", "", HEADER, "doubao-prefix-h.patch")
|
||||
write_patch("lib/dpkg/doubao-prefix.c", "", IMPL, "doubao-prefix-c.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 3. Makefile.am:加入源文件 + 定义兜底前缀
|
||||
# ======================================================================
|
||||
ma = git_show("lib/dpkg/Makefile.am")
|
||||
out, added_src, added_def = [], False, False
|
||||
for ln in ma.split("\n"):
|
||||
out.append(ln)
|
||||
if not added_src and ln.strip() == "utils.c \\":
|
||||
out.append("\tdoubao-prefix.c \\")
|
||||
added_src = True
|
||||
if not added_def and ln.strip().startswith("-DDEFAULT_TEXT_DOMAIN="):
|
||||
# 兜底前缀:正常由 /proc/self/exe 推导,这行只是推导失败时的退路
|
||||
out.append("\t-DDOUBAO_DEFAULT_PREFIX=\\\"$(prefix)\\\" \\")
|
||||
added_def = True
|
||||
assert added_src and added_def, "Makefile.am 结构变了,插入点找不到"
|
||||
new_ma = "\n".join(out)
|
||||
if "\tdpkg.h \\" in new_ma:
|
||||
new_ma = new_ma.replace("\tdpkg.h \\", "\tdpkg.h \\\n\tdoubao-prefix.h \\", 1)
|
||||
write_patch("lib/dpkg/Makefile.am", ma, new_ma, "doubao-prefix-makefile.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 4. options.c:配置目录改为运行时解析
|
||||
# ======================================================================
|
||||
oc = git_show("lib/dpkg/options.c")
|
||||
new_oc = oc.replace("#include <dpkg/options.h>\n",
|
||||
"#include <dpkg/options.h>\n#include <dpkg/doubao-prefix.h>\n", 1)
|
||||
assert new_oc != oc, "options.c 里插入 include 失败"
|
||||
new_oc = new_oc.replace('dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);',
|
||||
'dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);', 1)
|
||||
new_oc = new_oc.replace('file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);',
|
||||
'file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);', 1)
|
||||
assert "CONFIGDIR" not in new_oc, "options.c 里还有 CONFIGDIR 残留"
|
||||
write_patch("lib/dpkg/options.c", oc, new_oc, "doubao-prefix-options.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 5. main.c:启动时修好 PATH
|
||||
# ======================================================================
|
||||
mc = git_show("src/main/main.c")
|
||||
new_mc = mc.replace(
|
||||
" dpkg_options_load(DPKG, cmdinfos);\n",
|
||||
" dpkg_options_load(DPKG, cmdinfos);\n"
|
||||
"\n"
|
||||
" /* Another Android application may have handed us a PATH that points at\n"
|
||||
" * its own prefix; repair ours before anything looks a program up. */\n"
|
||||
" doubao_fix_environment();\n", 1)
|
||||
assert new_mc != mc, "main.c 里插入 doubao_fix_environment 失败"
|
||||
assert '#include "main.h"' in new_mc, "main.c 里找不到 main.h"
|
||||
new_mc = new_mc.replace('#include "main.h"',
|
||||
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
|
||||
write_patch("src/main/main.c", mc, new_mc, "doubao-prefix-main.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 6. script.c:三条执行路径都修 shebang
|
||||
# ======================================================================
|
||||
sc = git_show("src/main/script.c")
|
||||
FIX = """ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
* the Termux prefix; on Android that path belongs to another
|
||||
* application and the kernel refuses to exec it. Point it at us. */
|
||||
doubao_fix_script_shebang(%s);
|
||||
|
||||
"""
|
||||
targets = [
|
||||
(" if (stat(scriptpath, &stab)) {\n command_destroy(&cmd);\n", "scriptpath"),
|
||||
(" if (stat(cidir, &stab)) {\n command_destroy(&cmd);\n", "cidir"),
|
||||
(" if (stat(oldscriptpath, &stab)) {\n", "oldscriptpath"),
|
||||
]
|
||||
new_sc, total = sc, 0
|
||||
for needle, arg in targets:
|
||||
cnt = new_sc.count(needle)
|
||||
assert cnt > 0, f"script.c 里找不到 {arg} 的 stat 块"
|
||||
new_sc = new_sc.replace(needle, (FIX % arg) + needle)
|
||||
total += cnt
|
||||
print(f" script.c {arg}: {cnt} 处")
|
||||
assert total >= 3, f"script.c 只修了 {total} 处,至少该有 3 处"
|
||||
new_sc = new_sc.replace('#include "main.h"',
|
||||
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
|
||||
write_patch("src/main/script.c", sc, new_sc, "doubao-prefix-script.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 7. 架构名:Termux 用的是 GNU CPU 名(x86_64 / aarch64 / arm / i686)
|
||||
# ======================================================================
|
||||
am = git_show("m4/dpkg-arch.m4")
|
||||
OLD_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
], [
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
])# DPKG_ARCHITECTURE"""
|
||||
|
||||
NEW_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
|
||||
dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
|
||||
dnl all -- so the generic lookup below can never resolve a *-linux-android
|
||||
dnl host triple and configure dies with "cannot determine host dpkg
|
||||
dnl architecture".
|
||||
dnl
|
||||
dnl Termux names its architectures after the GNU CPU name (the repository
|
||||
dnl serves x86_64, aarch64, arm and i686), and the package database shipped
|
||||
dnl in our bootstrap was written with exactly those names, so we have to
|
||||
dnl report the same thing or dpkg would reject every installed package.
|
||||
dnl
|
||||
dnl Note the host OS arrives as "linux-android", not "android": config.sub
|
||||
dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
|
||||
AS_CASE([$host_os],
|
||||
[*android*], [
|
||||
AS_CASE([$host_cpu],
|
||||
[x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
|
||||
[armv7*], [dpkg_arch=arm],
|
||||
[AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
|
||||
cpu_type=$host_cpu
|
||||
os_type=android
|
||||
have_dpkg_arch=yes
|
||||
])
|
||||
AS_IF([test "x$have_dpkg_arch" = "xyes"], [
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
], [
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
], [
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
])# DPKG_ARCHITECTURE"""
|
||||
|
||||
assert OLD_ARCH in am, "m4/dpkg-arch.m4 里找不到 DPKG_ARCHITECTURE 宏体"
|
||||
write_patch("m4/dpkg-arch.m4", am, am.replace(OLD_ARCH, NEW_ARCH, 1),
|
||||
"doubao-android-arch.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 8. 架构名校验:x86_64 / aarch64 带下划线,两边都要放开
|
||||
# ======================================================================
|
||||
ac = git_show("lib/dpkg/arch.c")
|
||||
OLD_VAL = """\tif (!c_isalnum(*p))
|
||||
\t\treturn _("must start with an alphanumeric");
|
||||
\twhile (*++p != '\\0')
|
||||
\t\tif (!c_isalnum(*p) && *p != '-')
|
||||
\t\t\tbreak;
|
||||
\tif (*p == '\\0')
|
||||
\t\treturn NULL;
|
||||
|
||||
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
\t "letters, digits and characters '%s')"),
|
||||
\t *p, "-");
|
||||
\treturn buf;"""
|
||||
NEW_VAL = """\t/* Termux/Android: Termux names its architectures after the GNU CPU
|
||||
\t * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
|
||||
\t * underscore. Without this every package in the bootstrap database
|
||||
\t * would be reported as having an invalid Architecture. */
|
||||
\tif (!c_isalnum(*p))
|
||||
\t\treturn _("must start with an alphanumeric");
|
||||
\twhile (*++p != '\\0')
|
||||
\t\tif (!c_isalnum(*p) && *p != '-' && *p != '_')
|
||||
\t\t\tbreak;
|
||||
\tif (*p == '\\0')
|
||||
\t\treturn NULL;
|
||||
|
||||
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
\t "letters, digits and characters '%s')"),
|
||||
\t *p, "-_");
|
||||
\treturn buf;"""
|
||||
assert OLD_VAL in ac, "lib/dpkg/arch.c 里找不到 dpkg_arch_name_is_illegal 函数体"
|
||||
write_patch("lib/dpkg/arch.c", ac, ac.replace(OLD_VAL, NEW_VAL, 1),
|
||||
"doubao-arch-name.patch")
|
||||
|
||||
ap = git_show("scripts/Dpkg/Arch.pm")
|
||||
OLD_RE = " my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;"
|
||||
NEW_RE = (" # Termux/Android: allow underscores, because Termux names\n"
|
||||
" # architectures after the GNU CPU name and x86_64 / aarch64\n"
|
||||
" # both contain one.\n"
|
||||
" my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;")
|
||||
assert OLD_RE in ap, "scripts/Dpkg/Arch.pm 里找不到架构名正则"
|
||||
write_patch("scripts/Dpkg/Arch.pm", ap, ap.replace(OLD_RE, NEW_RE, 1),
|
||||
"doubao-debarch-name.patch")
|
||||
|
||||
print("\n全部生成到 " + OUT)
|
||||
53
android/termux-dpkg/make-jnilibs.sh
Normal file
53
android/termux-dpkg/make-jnilibs.sh
Normal file
@@ -0,0 +1,53 @@
|
||||
#!/bin/bash
|
||||
# 把编好的 dpkg 打包成 jniLibs 里的 libdoubao-dpkg.so。
|
||||
#
|
||||
# 为什么打成 tar 再改名成 .so:
|
||||
# Android 安装 APK 时只对 lib/<abi>/*.so 免压缩解包,别的路径(assets/)
|
||||
# 会被压缩、还得自己解压一遍。打成 tar 塞进 .so 里,安装完直接读就行,
|
||||
# 也跟这个仓库里 libtermux-bootstrap.so 的做法一致。
|
||||
#
|
||||
# 用法: make-jnilibs.sh <工作目录> <输出 jniLibs 目录>
|
||||
set -eu
|
||||
|
||||
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
|
||||
JNI="${2:?用法: make-jnilibs.sh <工作目录> <jniLibs 目录>}"
|
||||
|
||||
PROGRAMS="dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger"
|
||||
|
||||
# APK 的 abi 目录名跟我们的 arch 名不一样
|
||||
declare -A ABI=( [x86_64]=x86_64 [arm64]=arm64-v8a )
|
||||
|
||||
for arch in x86_64 arm64; do
|
||||
src="$WORK/out/$arch/dpkg-bin"
|
||||
abi="${ABI[$arch]}"
|
||||
dst="$JNI/$abi"
|
||||
|
||||
[ -d "$src" ] || { echo "!! 没有 $src,先跑 build-dpkg.sh $arch"; exit 1; }
|
||||
mkdir -p "$dst"
|
||||
|
||||
stage="$(mktemp -d)"
|
||||
for p in $PROGRAMS; do
|
||||
[ -f "$src/$p" ] || { echo "!! 缺 $src/$p"; exit 1; }
|
||||
cp "$src/$p" "$stage/$p"
|
||||
chmod 755 "$stage/$p"
|
||||
done
|
||||
|
||||
# tar 用固定的 uid/gid/mtime,保证同样输入产出同样字节(可复现)
|
||||
tar --create --file "$dst/libdoubao-dpkg.so" \
|
||||
--directory "$stage" \
|
||||
--owner=0 --group=0 --numeric-owner \
|
||||
--mtime='2026-01-01 00:00:00 UTC' \
|
||||
--sort=name \
|
||||
$PROGRAMS
|
||||
|
||||
rm -rf "$stage"
|
||||
printf ' %-10s -> %-46s %s 字节\n' "$arch" "jniLibs/$abi/libdoubao-dpkg.so" \
|
||||
"$(stat -c%s "$dst/libdoubao-dpkg.so")"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "内容确认:"
|
||||
for arch in x86_64 arm64; do
|
||||
echo "--- ${ABI[$arch]} ---"
|
||||
tar -tvf "$JNI/${ABI[$arch]}/libdoubao-dpkg.so"
|
||||
done
|
||||
48
android/termux-dpkg/patches/doubao/doubao-android-arch.patch
Normal file
48
android/termux-dpkg/patches/doubao/doubao-android-arch.patch
Normal file
@@ -0,0 +1,48 @@
|
||||
--- a/m4/dpkg-arch.m4 2026-10-14 12:41:34.709430018 +0800
|
||||
+++ b/m4/dpkg-arch.m4 2026-10-14 12:41:34.709459828 +0800
|
||||
@@ -55,12 +55,40 @@
|
||||
AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
- AC_MSG_CHECKING([dpkg architecture name])
|
||||
- _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
- AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
- AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
- ], [
|
||||
+ dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
|
||||
+ dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
|
||||
+ dnl all -- so the generic lookup below can never resolve a *-linux-android
|
||||
+ dnl host triple and configure dies with "cannot determine host dpkg
|
||||
+ dnl architecture".
|
||||
+ dnl
|
||||
+ dnl Termux names its architectures after the GNU CPU name (the repository
|
||||
+ dnl serves x86_64, aarch64, arm and i686), and the package database shipped
|
||||
+ dnl in our bootstrap was written with exactly those names, so we have to
|
||||
+ dnl report the same thing or dpkg would reject every installed package.
|
||||
+ dnl
|
||||
+ dnl Note the host OS arrives as "linux-android", not "android": config.sub
|
||||
+ dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
|
||||
+ AS_CASE([$host_os],
|
||||
+ [*android*], [
|
||||
+ AS_CASE([$host_cpu],
|
||||
+ [x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
|
||||
+ [armv7*], [dpkg_arch=arm],
|
||||
+ [AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
|
||||
+ cpu_type=$host_cpu
|
||||
+ os_type=android
|
||||
+ have_dpkg_arch=yes
|
||||
+ ])
|
||||
+ AS_IF([test "x$have_dpkg_arch" = "xyes"], [
|
||||
+ AC_MSG_CHECKING([dpkg architecture name])
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
+ ], [
|
||||
+ AC_MSG_CHECKING([dpkg architecture name])
|
||||
+ _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
+ AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
+ AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
+ ], [
|
||||
+ AC_MSG_RESULT([$dpkg_arch])
|
||||
+ ])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
26
android/termux-dpkg/patches/doubao/doubao-arch-name.patch
Normal file
26
android/termux-dpkg/patches/doubao/doubao-arch-name.patch
Normal file
@@ -0,0 +1,26 @@
|
||||
--- a/lib/dpkg/arch.c 2026-10-14 12:41:34.729574429 +0800
|
||||
+++ b/lib/dpkg/arch.c 2026-10-14 12:41:34.729607515 +0800
|
||||
@@ -62,17 +62,21 @@
|
||||
internerr("arch name argument is NULL");
|
||||
if (!*p)
|
||||
return _("may not be empty string");
|
||||
+ /* Termux/Android: Termux names its architectures after the GNU CPU
|
||||
+ * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
|
||||
+ * underscore. Without this every package in the bootstrap database
|
||||
+ * would be reported as having an invalid Architecture. */
|
||||
if (!c_isalnum(*p))
|
||||
return _("must start with an alphanumeric");
|
||||
while (*++p != '\0')
|
||||
- if (!c_isalnum(*p) && *p != '-')
|
||||
+ if (!c_isalnum(*p) && *p != '-' && *p != '_')
|
||||
break;
|
||||
if (*p == '\0')
|
||||
return NULL;
|
||||
|
||||
snprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
"letters, digits and characters '%s')"),
|
||||
- *p, "-");
|
||||
+ *p, "-_");
|
||||
return buf;
|
||||
}
|
||||
|
||||
14
android/termux-dpkg/patches/doubao/doubao-debarch-name.patch
Normal file
14
android/termux-dpkg/patches/doubao/doubao-debarch-name.patch
Normal file
@@ -0,0 +1,14 @@
|
||||
--- a/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752824615 +0800
|
||||
+++ b/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752929467 +0800
|
||||
@@ -612,7 +612,10 @@
|
||||
sub debarch_is_illegal
|
||||
{
|
||||
my ($arch, %opts) = @_;
|
||||
- my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;
|
||||
+ # Termux/Android: allow underscores, because Termux names
|
||||
+ # architectures after the GNU CPU name and x86_64 / aarch64
|
||||
+ # both contain one.
|
||||
+ my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;
|
||||
|
||||
if ($opts{positive}) {
|
||||
return $arch !~ m/^$arch_re$/;
|
||||
352
android/termux-dpkg/patches/doubao/doubao-prefix-c.patch
Normal file
352
android/termux-dpkg/patches/doubao/doubao-prefix-c.patch
Normal file
@@ -0,0 +1,352 @@
|
||||
--- a/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.595602235 +0800
|
||||
+++ b/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.600860227 +0800
|
||||
@@ -0,0 +1,349 @@
|
||||
+/*
|
||||
+ * doubao-prefix.c - resolve the installation prefix at runtime
|
||||
+ *
|
||||
+ * Copyright (C) 2026 doubao-clone
|
||||
+ *
|
||||
+ * This is free software; you can redistribute it and/or modify
|
||||
+ * it under the terms of the GNU General Public License as published by
|
||||
+ * the Free Software Foundation; either version 2 of the License, or
|
||||
+ * (at your option) any later version.
|
||||
+ *
|
||||
+ * Upstream dpkg bakes its configuration directory in at configure time
|
||||
+ * (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
|
||||
+ * fixed absolute path chosen by the Termux application. Android gives every
|
||||
+ * application its own private data directory, so a dpkg built for
|
||||
+ * com.termux will always look inside /data/data/com.termux -- a directory
|
||||
+ * another application is not allowed to traverse. The resulting EACCES makes
|
||||
+ * dpkg abort before it has even parsed its command line, which is why the two
|
||||
+ * applications cannot coexist.
|
||||
+ *
|
||||
+ * We instead derive the prefix from the path of the running executable, which
|
||||
+ * is exactly where this binary happens to live. That also lets us repair
|
||||
+ * PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
|
||||
+ * all of which upstream assumes are already correct.
|
||||
+ */
|
||||
+
|
||||
+#include <config.h>
|
||||
+#include <compat.h>
|
||||
+
|
||||
+#include <fcntl.h>
|
||||
+#include <limits.h>
|
||||
+#include <stdlib.h>
|
||||
+#include <string.h>
|
||||
+#include <sys/stat.h>
|
||||
+#include <unistd.h>
|
||||
+
|
||||
+#include <dpkg/i18n.h>
|
||||
+#include <dpkg/debug.h>
|
||||
+#include <dpkg/dpkg.h>
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
+
|
||||
+/* How many distinct strings we keep alive so returned pointers stay valid. */
|
||||
+#define DOUBAO_CACHE_SLOTS 4
|
||||
+
|
||||
+static char prefix_buf[PATH_MAX];
|
||||
+static const char *prefix_cached;
|
||||
+static char config_buf[PATH_MAX];
|
||||
+
|
||||
+static void
|
||||
+doubao_prefix_resolve(void)
|
||||
+{
|
||||
+ char self[PATH_MAX];
|
||||
+ const char *override;
|
||||
+ char *slash;
|
||||
+ ssize_t n;
|
||||
+
|
||||
+ if (prefix_cached != NULL)
|
||||
+ return;
|
||||
+
|
||||
+ prefix_cached = DOUBAO_DEFAULT_PREFIX;
|
||||
+
|
||||
+ override = getenv("DOUBAO_DPKG_PREFIX");
|
||||
+ if (override != NULL) {
|
||||
+ if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
|
||||
+ strcpy(prefix_buf, override);
|
||||
+ prefix_cached = prefix_buf;
|
||||
+ }
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ n = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
+ if (n <= 0 || (size_t)n >= sizeof(self) - 1)
|
||||
+ return;
|
||||
+ self[n] = '\0';
|
||||
+
|
||||
+ /* .../bin/dpkg -> .../bin -> ... */
|
||||
+ slash = strrchr(self, '/');
|
||||
+ if (slash == NULL)
|
||||
+ return;
|
||||
+ *slash = '\0';
|
||||
+
|
||||
+ slash = strrchr(self, '/');
|
||||
+ if (slash == NULL)
|
||||
+ return;
|
||||
+ *slash = '\0';
|
||||
+
|
||||
+ if (strlen(self) < sizeof(prefix_buf)) {
|
||||
+ strcpy(prefix_buf, self);
|
||||
+ prefix_cached = prefix_buf;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+const char *
|
||||
+doubao_prefix(void)
|
||||
+{
|
||||
+ doubao_prefix_resolve();
|
||||
+ return prefix_cached;
|
||||
+}
|
||||
+
|
||||
+const char *
|
||||
+doubao_config_dir(void)
|
||||
+{
|
||||
+ const char *prefix = doubao_prefix();
|
||||
+
|
||||
+ if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
|
||||
+ >= (int)sizeof(config_buf))
|
||||
+ return CONFIGDIR;
|
||||
+
|
||||
+ return config_buf;
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * Prepend our own bin directories to PATH and make sure the loader can find
|
||||
+ * our shared libraries, so that dpkg and the maintainer scripts it runs work
|
||||
+ * no matter what environment our parent handed us.
|
||||
+ */
|
||||
+void
|
||||
+doubao_fix_environment(void)
|
||||
+{
|
||||
+ static bool done = false;
|
||||
+ static char pathbuf[4 * PATH_MAX];
|
||||
+ static char libbuf[PATH_MAX + 64];
|
||||
+
|
||||
+ const char *prefix, *old;
|
||||
+ size_t len;
|
||||
+
|
||||
+ if (done)
|
||||
+ return;
|
||||
+ done = true;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+
|
||||
+ old = getenv("PATH");
|
||||
+ /* Only prepend when our prefix is not already the first entry, so that
|
||||
+ * a re-exec does not keep growing PATH. */
|
||||
+ len = strlen(prefix);
|
||||
+ if (old == NULL || strncmp(old, prefix, len) != 0 ||
|
||||
+ strncmp(old + len, "/bin:", 5) != 0) {
|
||||
+ if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
|
||||
+ prefix, prefix, old != NULL ? old : "/system/bin")
|
||||
+ < (int)sizeof(pathbuf))
|
||||
+ setenv("PATH", pathbuf, 1);
|
||||
+ }
|
||||
+
|
||||
+ if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
|
||||
+ prefix) < (int)sizeof(libbuf))
|
||||
+ setenv("LD_LIBRARY_PATH", libbuf, 1);
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * Maintainer scripts inside a Termux package are written in terms of the
|
||||
+ * Termux prefix:
|
||||
+ *
|
||||
+ * #!/data/data/com.termux/files/usr/bin/sh
|
||||
+ * mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
+ * KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
|
||||
+ *
|
||||
+ * Neither form works for us. The interpreter line is resolved by the kernel
|
||||
+ * and lands in another application's private directory (EACCES, which dpkg
|
||||
+ * then reports as though the script itself were not executable), and the
|
||||
+ * absolute paths are absolute -- our sandbox symlinks live under our own
|
||||
+ * prefix and cannot intercept a path that starts at "/".
|
||||
+ *
|
||||
+ * The scripts are plain text, so rewrite both before executing them. This is
|
||||
+ * a local edit of the dpkg database rather than a change to the package, so
|
||||
+ * it also covers packages installed long after this code was written.
|
||||
+ */
|
||||
+#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
|
||||
+
|
||||
+static void
|
||||
+doubao_rewrite_script(const char *path)
|
||||
+{
|
||||
+ char *buf;
|
||||
+ char *out;
|
||||
+ const char *prefix;
|
||||
+ size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
|
||||
+ size_t newlen, len, cap;
|
||||
+ size_t i, o;
|
||||
+ int fd;
|
||||
+ ssize_t n;
|
||||
+ struct stat st;
|
||||
+
|
||||
+ if (path == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ fd = open(path, O_RDONLY);
|
||||
+ if (fd < 0)
|
||||
+ return;
|
||||
+ if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
|
||||
+ st.st_size > 1024 * 1024) {
|
||||
+ close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ len = (size_t)st.st_size;
|
||||
+ buf = malloc(len + 1);
|
||||
+ if (buf == NULL) {
|
||||
+ close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+ n = read(fd, buf, len);
|
||||
+ close(fd);
|
||||
+ if (n <= 0) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+ buf[n] = '\0';
|
||||
+ len = (size_t)n;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+ newlen = strlen(prefix);
|
||||
+
|
||||
+ /* 先看有没有要换的东西,没有就别写盘 */
|
||||
+ for (i = 0; i + oldlen <= len; i++) {
|
||||
+ if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
|
||||
+ break;
|
||||
+ }
|
||||
+ if (i + oldlen > len) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ /* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
|
||||
+ cap = len + 64;
|
||||
+ out = malloc(cap);
|
||||
+ if (out == NULL) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ for (i = 0, o = 0; i < len; ) {
|
||||
+ if (i + oldlen <= len &&
|
||||
+ memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
|
||||
+ if (o + newlen + (len - i) + 2 > cap) {
|
||||
+ cap = (o + newlen + (len - i) + 2) * 2;
|
||||
+ out = realloc(out, cap);
|
||||
+ if (out == NULL) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+ }
|
||||
+ memcpy(out + o, prefix, newlen);
|
||||
+ o += newlen;
|
||||
+ i += oldlen;
|
||||
+ } else {
|
||||
+ out[o++] = buf[i++];
|
||||
+ }
|
||||
+ }
|
||||
+ out[o] = '\0';
|
||||
+ free(buf);
|
||||
+
|
||||
+ fd = open(path, O_WRONLY | O_TRUNC);
|
||||
+ if (fd < 0) {
|
||||
+ free(out);
|
||||
+ return;
|
||||
+ }
|
||||
+ if (write(fd, out, o) != (ssize_t)o) {
|
||||
+ close(fd);
|
||||
+ free(out);
|
||||
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
+ }
|
||||
+ close(fd);
|
||||
+ free(out);
|
||||
+
|
||||
+ debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * 把维护脚本的 shebang 换成本安装自己的 shell。
|
||||
+ *
|
||||
+ * 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
|
||||
+ * 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
|
||||
+ * 于是报 `bin/pip: line 2: import: command not found`。
|
||||
+ * 规则是"只换路径,不动解释器"。
|
||||
+ */
|
||||
+void
|
||||
+doubao_fix_script_shebang(const char *path)
|
||||
+{
|
||||
+ static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
|
||||
+ /* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
|
||||
+ * 写法,包里两种都出现过,所以两个都要认。 */
|
||||
+ static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
|
||||
+
|
||||
+ char buf[PATH_MAX + 256];
|
||||
+ const char *prefix;
|
||||
+ char *nl;
|
||||
+ int fd;
|
||||
+ ssize_t n;
|
||||
+ ssize_t skip = -1;
|
||||
+ size_t head, rest, total;
|
||||
+ char *fixed;
|
||||
+
|
||||
+ if (path == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ /* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
|
||||
+ doubao_rewrite_script(path);
|
||||
+
|
||||
+ fd = open(path, O_RDONLY);
|
||||
+ if (fd < 0)
|
||||
+ return;
|
||||
+
|
||||
+ n = read(fd, buf, sizeof(buf) - 1);
|
||||
+ close(fd);
|
||||
+ if (n <= 0)
|
||||
+ return;
|
||||
+ buf[n] = '\0';
|
||||
+
|
||||
+ if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
|
||||
+ skip = (ssize_t)(sizeof(old_shebang) - 1);
|
||||
+ else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
|
||||
+ skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
|
||||
+
|
||||
+ if (skip < 0)
|
||||
+ return;
|
||||
+
|
||||
+ nl = strchr(buf, '\n');
|
||||
+ if (nl == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+ head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
|
||||
+ rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
|
||||
+ total = head + rest;
|
||||
+ if (total + 1 > sizeof(buf))
|
||||
+ return;
|
||||
+
|
||||
+ fixed = malloc(total + 1);
|
||||
+ if (fixed == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ fixed[0] = '#';
|
||||
+ fixed[1] = '!';
|
||||
+ memcpy(fixed + 2, prefix, strlen(prefix));
|
||||
+ fixed[2 + strlen(prefix)] = '/';
|
||||
+ memcpy(fixed + head, buf + skip, rest);
|
||||
+ fixed[total] = '\0';
|
||||
+
|
||||
+ fd = open(path, O_WRONLY | O_TRUNC);
|
||||
+ if (fd < 0) {
|
||||
+ free(fixed);
|
||||
+ return;
|
||||
+ }
|
||||
+ if (write(fd, fixed, total) != (ssize_t)total)
|
||||
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
+ close(fd);
|
||||
+ free(fixed);
|
||||
+
|
||||
+ debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
|
||||
+}
|
||||
55
android/termux-dpkg/patches/doubao/doubao-prefix-h.patch
Normal file
55
android/termux-dpkg/patches/doubao/doubao-prefix-h.patch
Normal file
@@ -0,0 +1,55 @@
|
||||
--- a/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.579902172 +0800
|
||||
+++ b/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.580926465 +0800
|
||||
@@ -0,0 +1,52 @@
|
||||
+/*
|
||||
+ * doubao-prefix.h - resolve the installation prefix at runtime
|
||||
+ *
|
||||
+ * Copyright (C) 2026 doubao-clone
|
||||
+ *
|
||||
+ * This is free software; you can redistribute it and/or modify
|
||||
+ * it under the terms of the GNU General Public License as published by
|
||||
+ * the Free Software Foundation; either version 2 of the License, or
|
||||
+ * (at your option) any later version.
|
||||
+ */
|
||||
+
|
||||
+#ifndef DOUBAO_PREFIX_H
|
||||
+#define DOUBAO_PREFIX_H
|
||||
+
|
||||
+#include <dpkg/dpkg.h>
|
||||
+
|
||||
+DPKG_BEGIN_DECLS
|
||||
+
|
||||
+/**
|
||||
+ * Return the prefix this dpkg was installed under.
|
||||
+ *
|
||||
+ * The prefix is derived from the path of the running executable, because
|
||||
+ * Android hands every application its own private data directory and the
|
||||
+ * same binary has to work under any of them. Falls back to the compile-time
|
||||
+ * DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
|
||||
+ */
|
||||
+const char *doubao_prefix(void);
|
||||
+
|
||||
+/**
|
||||
+ * Return the configuration directory ($prefix/etc/dpkg).
|
||||
+ */
|
||||
+const char *doubao_config_dir(void);
|
||||
+
|
||||
+/**
|
||||
+ * Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
|
||||
+ * own lib directory.
|
||||
+ *
|
||||
+ * Needed because apt sanitises the environment before it execs dpkg, and the
|
||||
+ * PATH it hands over names the *other* application's prefix; dpkg would then
|
||||
+ * fail its own sanity check with "expected programs not found in PATH".
|
||||
+ */
|
||||
+void doubao_fix_environment(void);
|
||||
+
|
||||
+/**
|
||||
+ * Rewrite a maintainer script's interpreter line so it points at this
|
||||
+ * installation instead of the application it was built for.
|
||||
+ */
|
||||
+void doubao_fix_script_shebang(const char *path);
|
||||
+
|
||||
+DPKG_END_DECLS
|
||||
+
|
||||
+#endif /* DOUBAO_PREFIX_H */
|
||||
22
android/termux-dpkg/patches/doubao/doubao-prefix-main.patch
Normal file
22
android/termux-dpkg/patches/doubao/doubao-prefix-main.patch
Normal file
@@ -0,0 +1,22 @@
|
||||
--- a/src/main/main.c 2026-10-14 12:41:34.673058919 +0800
|
||||
+++ b/src/main/main.c 2026-10-14 12:41:34.673178642 +0800
|
||||
@@ -53,6 +53,8 @@
|
||||
#include <dpkg/db-fsys.h>
|
||||
|
||||
#include "main.h"
|
||||
+
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
#include "filters.h"
|
||||
|
||||
static int
|
||||
@@ -736,6 +738,10 @@
|
||||
dpkg_program_init("dpkg");
|
||||
set_force_default(FORCE_ALL);
|
||||
dpkg_options_load(DPKG, cmdinfos);
|
||||
+
|
||||
+ /* Another Android application may have handed us a PATH that points at
|
||||
+ * its own prefix; repair ours before anything looks a program up. */
|
||||
+ doubao_fix_environment();
|
||||
dpkg_options_parse(&argv, cmdinfos, printforhelp);
|
||||
|
||||
debug(dbg_general, "root=%s admindir=%s", dpkg_fsys_get_dir(), dpkg_db_get_dir());
|
||||
@@ -0,0 +1,26 @@
|
||||
--- a/lib/dpkg/Makefile.am 2026-10-14 12:41:34.636534337 +0800
|
||||
+++ b/lib/dpkg/Makefile.am 2026-10-14 12:41:34.636659433 +0800
|
||||
@@ -5,6 +5,7 @@
|
||||
-DCONFIGDIR=\"$(pkgconfdir)\" \
|
||||
-DADMINDIR=\"$(admindir)\" \
|
||||
-DDEFAULT_TEXT_DOMAIN=\"@PACKAGE@\" \
|
||||
+ -DDOUBAO_DEFAULT_PREFIX=\"$(prefix)\" \
|
||||
-idirafter $(top_srcdir)/lib/compat \
|
||||
-I$(top_builddir) \
|
||||
-I$(top_srcdir)/lib \
|
||||
@@ -132,6 +133,7 @@
|
||||
triglib.c \
|
||||
trigdeferred.c \
|
||||
utils.c \
|
||||
+ doubao-prefix.c \
|
||||
varbuf.c \
|
||||
version.c \
|
||||
# EOL
|
||||
@@ -151,6 +153,7 @@
|
||||
debug.h \
|
||||
dir.h \
|
||||
dpkg.h \
|
||||
+ doubao-prefix.h \
|
||||
dpkg-db.h \
|
||||
ehandle.h \
|
||||
error.h \
|
||||
@@ -0,0 +1,28 @@
|
||||
--- a/lib/dpkg/options.c 2026-10-14 12:41:34.656076933 +0800
|
||||
+++ b/lib/dpkg/options.c 2026-10-14 12:41:34.656194326 +0800
|
||||
@@ -35,6 +35,7 @@
|
||||
#include <dpkg/dpkg.h>
|
||||
#include <dpkg/string.h>
|
||||
#include <dpkg/options.h>
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
|
||||
static const char *printforhelp;
|
||||
|
||||
@@ -166,7 +167,7 @@
|
||||
struct dirent **dlist;
|
||||
int dlist_n, i;
|
||||
|
||||
- dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);
|
||||
+ dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);
|
||||
|
||||
dlist_n = scandir(dirname, &dlist, valid_config_filename, alphasort);
|
||||
if (dlist_n < 0) {
|
||||
@@ -198,7 +199,7 @@
|
||||
|
||||
dpkg_options_load_dir(prog, cmdinfos);
|
||||
|
||||
- file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);
|
||||
+ file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);
|
||||
dpkg_options_load_file(file, cmdinfos);
|
||||
free(file);
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
--- a/src/main/script.c 2026-10-14 12:41:34.690665764 +0800
|
||||
+++ b/src/main/script.c 2026-10-14 12:41:34.690708349 +0800
|
||||
@@ -47,6 +47,8 @@
|
||||
|
||||
#include "main.h"
|
||||
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
+
|
||||
void
|
||||
post_postinst_tasks(struct pkginfo *pkg, enum pkgstatus new_status)
|
||||
{
|
||||
@@ -230,6 +232,11 @@
|
||||
command_add_arg(&cmd, scriptname);
|
||||
command_add_argv(&cmd, args);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(scriptpath);
|
||||
+
|
||||
if (stat(scriptpath, &stab)) {
|
||||
command_destroy(&cmd);
|
||||
|
||||
@@ -306,6 +313,11 @@
|
||||
command_add_argv(&cmd, args);
|
||||
va_end(args);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(cidir);
|
||||
+
|
||||
if (stat(cidir, &stab)) {
|
||||
command_destroy(&cmd);
|
||||
|
||||
@@ -347,6 +359,11 @@
|
||||
versiondescribe(&pkg->available.version, vdew_nonambig),
|
||||
NULL);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(oldscriptpath);
|
||||
+
|
||||
if (stat(oldscriptpath, &stab)) {
|
||||
if (errno == ENOENT) {
|
||||
debug(dbg_scripts,
|
||||
@@ -377,6 +394,11 @@
|
||||
versiondescribe(&pkg->available.version, vdew_nonambig),
|
||||
NULL);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(cidir);
|
||||
+
|
||||
if (stat(cidir, &stab)) {
|
||||
command_destroy(&cmd);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
diff -u -r ../dpkg-1.17.6/lib/dpkg/dbmodify.c ./lib/dpkg/dbmodify.c
|
||||
--- ../dpkg-1.17.6/lib/dpkg/dbmodify.c 2013-12-14 06:36:07.000000000 +0100
|
||||
+++ ./lib/dpkg/dbmodify.c 2014-02-25 18:12:15.000000000 +0100
|
||||
@@ -253,8 +253,10 @@
|
||||
switch (readwritereq) {
|
||||
case msdbrw_needsuperuser:
|
||||
case msdbrw_needsuperuserlockonly:
|
||||
+#ifndef __ANDROID__
|
||||
if (getuid() || geteuid())
|
||||
ohshit(_("requested operation requires superuser privilege"));
|
||||
+#endif
|
||||
/* Fall through. */
|
||||
case msdbrw_write: case msdbrw_writeifposs:
|
||||
if (access(dpkg_db_get_dir(), W_OK)) {
|
||||
@@ -0,0 +1,20 @@
|
||||
diff -u -r ../dpkg-1.18.2/lib/dpkg/atomic-file.c ./lib/dpkg/atomic-file.c
|
||||
--- ../dpkg-1.18.2/lib/dpkg/atomic-file.c 2015-07-12 22:38:47.000000000 -0400
|
||||
+++ ./lib/dpkg/atomic-file.c 2015-08-25 18:06:51.689715379 -0400
|
||||
@@ -90,8 +90,14 @@
|
||||
|
||||
if (unlink(name_old) && errno != ENOENT)
|
||||
ohshite(_("error removing old backup file '%s'"), name_old);
|
||||
- if (link(file->name, name_old) && errno != ENOENT)
|
||||
- ohshite(_("error creating new backup file '%s'"), name_old);
|
||||
+#ifdef __ANDROID__
|
||||
+ /* Termux: Use rename(2) since Android does not support hardlinks. */
|
||||
+ if (rename(file->name, name_old) && errno != ENOENT) {
|
||||
+#else
|
||||
+ if (link(file->name, name_old) && errno != ENOENT) {
|
||||
+#endif
|
||||
+ ohshite(_("error creating new backup file '%s'"), name_old);
|
||||
+ }
|
||||
|
||||
free(name_old);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
Handle EROFS. This is since path_remove_tree() will be called with
|
||||
'/data.dpkg-tmp'
|
||||
'/data/data.dpkg-tmp'
|
||||
'/data/data/com.termux.dpkg-tmp'
|
||||
'/data/data/com.termux/files.dpkg-tmp'
|
||||
'/data/data/com.termux/files/usr.dpkg-tmp'
|
||||
and the first call will get a EROFS, read-only file system error.
|
||||
|
||||
diff -u -r ../dpkg-1.18.2/lib/dpkg/path-remove.c ./lib/dpkg/path-remove.c
|
||||
--- ../dpkg-1.18.2/lib/dpkg/path-remove.c 2015-07-30 00:39:24.000000000 -0400
|
||||
+++ ./lib/dpkg/path-remove.c 2015-08-25 18:04:31.391421421 -0400
|
||||
@@ -126,7 +126,7 @@
|
||||
debug(dbg_eachfile, "%s '%s'", __func__, pathname);
|
||||
if (!rmdir(pathname))
|
||||
return; /* Deleted it OK, it was a directory. */
|
||||
- if (errno == ENOENT || errno == ELOOP)
|
||||
+ if (errno == ENOENT || errno == ELOOP || errno == EROFS)
|
||||
return;
|
||||
if (errno == ENOTDIR) {
|
||||
/* Either it's a file, or one of the path components is. If
|
||||
@@ -0,0 +1,73 @@
|
||||
diff -u -r src-orig/src/main/archives.c src/src/main/archives.c
|
||||
--- src-orig/src/main/archives.c 2024-03-03 01:30:15.000000000 +0000
|
||||
+++ src/src/main/archives.c 2024-05-05 20:36:54.148725216 +0000
|
||||
@@ -394,9 +394,11 @@
|
||||
namenode->statoverride->uid,
|
||||
namenode->statoverride->gid,
|
||||
namenode->statoverride->mode);
|
||||
+#ifndef __ANDROID__
|
||||
rc = fchown(fd, st->uid, st->gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting ownership of '%.255s'"), te->name);
|
||||
+#endif
|
||||
rc = fchmod(fd, st->mode & ~S_IFMT);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting permissions of '%.255s'"), te->name);
|
||||
@@ -509,13 +511,17 @@
|
||||
return; /* Already handled using the file descriptor. */
|
||||
|
||||
if (te->type == TAR_FILETYPE_SYMLINK) {
|
||||
+#ifndef __ANDROID__
|
||||
rc = lchown(path, st->uid, st->gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting ownership of symlink '%.255s'"), path);
|
||||
+#endif
|
||||
} else {
|
||||
+#ifndef __ANDROID__
|
||||
rc = chown(path, st->uid, st->gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting ownership of '%.255s'"), path);
|
||||
+#endif
|
||||
rc = chmod(path, st->mode & ~S_IFMT);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting permissions of '%.255s'"), path);
|
||||
@@ -555,9 +561,11 @@
|
||||
else if (linksize > stab->st_size)
|
||||
ohshit(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fn_old, (intmax_t)stab->st_size, linksize);
|
||||
+#ifndef __ANDROID__
|
||||
else if (linksize < stab->st_size)
|
||||
warning(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fn_old, (intmax_t)stab->st_size, linksize);
|
||||
+#endif
|
||||
linkmatch = strcmp(linkname.buf, te->linkname) == 0;
|
||||
varbuf_destroy(&linkname);
|
||||
if (linkmatch)
|
||||
@@ -1053,18 +1061,27 @@
|
||||
else if (linksize > stab.st_size)
|
||||
ohshit(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fnamevb.buf, (intmax_t)stab.st_size, linksize);
|
||||
+#ifndef __ANDROID__
|
||||
else if (linksize < stab.st_size)
|
||||
warning(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fnamevb.buf, (intmax_t)stab.st_size, linksize);
|
||||
+#endif
|
||||
if (symlink(symlinkfn.buf,fnametmpvb.buf))
|
||||
ohshite(_("unable to make backup symlink for '%.255s'"), ti->name);
|
||||
+#ifndef __ANDROID__
|
||||
rc = lchown(fnametmpvb.buf, stab.st_uid, stab.st_gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("unable to chown backup symlink for '%.255s'"), ti->name);
|
||||
+#endif
|
||||
tarobject_set_se_context(fnamevb.buf, fnametmpvb.buf, stab.st_mode);
|
||||
} else {
|
||||
debug(dbg_eachfiledetail, "tarobject nondirectory, 'link' backup");
|
||||
+#ifdef __ANDROID__
|
||||
+ /* Android does not support hardlinks. */
|
||||
+ if (rename(fnamevb.buf,fnametmpvb.buf))
|
||||
+#else
|
||||
if (link(fnamevb.buf,fnametmpvb.buf))
|
||||
+#endif
|
||||
ohshite(_("unable to make backup link of '%.255s' before installing new version"),
|
||||
ti->name);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
diff -u -r ../dpkg-1.18.15/src/configure.c ./src/configure.c
|
||||
--- ../dpkg-1.18.15/src/configure.c 2016-11-11 22:18:40.000000000 -0500
|
||||
+++ ./src/main/configure.c 2016-12-03 16:32:43.719508056 -0500
|
||||
@@ -497,8 +497,10 @@
|
||||
pkg_name(pkg, pnaw_nonambig), cdr2.buf,
|
||||
strerror(errno));
|
||||
if (!(what & CFOF_USER_DEL))
|
||||
- if (link(cdr.buf, cdr2.buf))
|
||||
- warning(_("%s: failed to link '%.250s' to '%.250s': %s"),
|
||||
+ /** Termux modification: Use rename(2) instead of link(2), to avoid hard
|
||||
+ links which does not work on Android 6.0 or later. */
|
||||
+ if (rename(cdr.buf, cdr2.buf))
|
||||
+ warning(_("%s: failed to rename '%.250s' to '%.250s': %s"),
|
||||
pkg_name(pkg, pnaw_nonambig), cdr.buf,
|
||||
cdr2.buf, strerror(errno));
|
||||
/* Fall through. */
|
||||
14
android/termux-dpkg/patches/termux/termux-src-help.c.patch
Normal file
14
android/termux-dpkg/patches/termux/termux-src-help.c.patch
Normal file
@@ -0,0 +1,14 @@
|
||||
diff -u -r ../dpkg-1.19.2/src/help.c ./src/help.c
|
||||
--- ../dpkg-1.19.2/src/help.c 2018-10-07 22:07:52.000000000 +0000
|
||||
+++ ./src/main/help.c 2018-11-11 02:13:05.133548711 +0000
|
||||
@@ -127,8 +127,10 @@
|
||||
"update_dyld_shared_cache",
|
||||
#elif defined(__GLIBC__) || defined(__UCLIBC__) || \
|
||||
defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
|
||||
+#ifndef __ANDROID__
|
||||
"ldconfig",
|
||||
#endif
|
||||
+#endif
|
||||
#if BUILD_START_STOP_DAEMON
|
||||
"start-stop-daemon",
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
diff --color -uNr ../dpkg-1.21.8/src/statoverride/main.c ./src/statoverride/main.c
|
||||
--- ../dpkg-1.21.8/src/statoverride/main.c 2022-05-24 14:36:59.000000000 -0300
|
||||
+++ ./src/statoverride/main.c 2022-05-31 07:39:44.829552700 -0300
|
||||
@@ -188,9 +188,11 @@
|
||||
{
|
||||
int rc;
|
||||
|
||||
+#ifndef __ANDROID__
|
||||
rc = chown(filename, filestat->uid, filestat->gid);
|
||||
if (forcible_nonroot_error(rc) < 0)
|
||||
ohshite(_("error setting ownership of '%.255s'"), filename);
|
||||
+#endif
|
||||
rc = chmod(filename, filestat->mode & ~S_IFMT);
|
||||
if (forcible_nonroot_error(rc) < 0)
|
||||
ohshite(_("error setting permissions of '%.255s'"), filename);
|
||||
196
android/termux-dpkg/verify-dpkg.py
Normal file
196
android/termux-dpkg/verify-dpkg.py
Normal file
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验自编 dpkg 的硬性质。
|
||||
|
||||
这些性质每一条都对应一个真实踩过的坑,所以必须自动守住 —— 光靠"编译过了"
|
||||
没有任何意义(编译过但跑不起来的情况在这一路上出现过很多次)。
|
||||
|
||||
用法:
|
||||
python3 verify-dpkg.py <x86_64|arm64> [工作目录]
|
||||
|
||||
检查项:
|
||||
1. 产物齐全,都是对应架构的 ELF
|
||||
2. 二进制里出现的 com.termux 字符串**只能**是 shebang 修复函数自己要匹配的
|
||||
那两个模式;出现别的(尤其是 /data/data/com.termux/files/usr/etc/dpkg
|
||||
这类配置目录)就说明运行时前缀补丁没生效,装上必然 EACCES
|
||||
3. 必须有 /proc/self/exe —— 运行时前缀就是靠它推导的
|
||||
4. 必须有 /etc/dpkg 拼接
|
||||
5. 不能出现旧的架构名 amd64/arm64(Termux 用 GNU CPU 名)
|
||||
6. 源码里架构名校验已放开下划线
|
||||
7. RUNPATH 必须指向前缀的 lib(dpkg 派生 dpkg-query 时不一定有环境变量)
|
||||
8. 不能依赖 libmd.so(我们静态链进去了)
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ARCH = sys.argv[1] if len(sys.argv) > 1 else "x86_64"
|
||||
WORK = sys.argv[2] if len(sys.argv) > 2 else os.environ.get("TERMUX_DPKG_WORK", "/root/tb")
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
BIN = os.path.join(WORK, "out", ARCH, "dpkg-bin")
|
||||
BUILD = os.path.join(WORK, "build", "dpkg-" + ARCH)
|
||||
|
||||
# readelf 报的是厂商全名,不是三元组简写
|
||||
EXPECT_MACHINE = {"x86_64": "X86-64", "arm64": "AArch64"}.get(ARCH)
|
||||
WANT_ARCH_NAME = {"x86_64": "x86_64", "arm64": "aarch64"}[ARCH]
|
||||
|
||||
PROGRAMS = ["dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"]
|
||||
PREFIX = os.environ.get("DOUBAO_PREFIX", "/data/data/com.doubao.lynxclone/files/usr")
|
||||
|
||||
# 这些是重写函数**自己要匹配**的模式,必须存在(换了就说明补丁没生效)
|
||||
ALLOWED_TERMUX = {
|
||||
"#!/data/data/com.termux/files/usr/",
|
||||
"#!/data/user/0/com.termux/files/usr/",
|
||||
"/data/data/com.termux/files/usr",
|
||||
}
|
||||
|
||||
fails, warns = [], []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def warn(m):
|
||||
warns.append(m)
|
||||
print(f" ! {m}")
|
||||
|
||||
|
||||
def which(*names):
|
||||
for n in names:
|
||||
r = subprocess.run(["which", n], capture_output=True, text=True)
|
||||
if r.returncode == 0:
|
||||
return r.stdout.strip()
|
||||
return None
|
||||
|
||||
|
||||
def run(*cmd):
|
||||
return subprocess.run(cmd, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
READELF = which("llvm-readelf", "readelf")
|
||||
STRINGS = which("llvm-strings", "strings")
|
||||
|
||||
print(f"=== 校验 {ARCH} 的 dpkg 产物 ===")
|
||||
print(f" 产物: {BIN}")
|
||||
if not os.path.isdir(BIN):
|
||||
print(f"!! 目录不存在:{BIN}")
|
||||
sys.exit(1)
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] 产物齐全 + ELF 架构正确")
|
||||
present = []
|
||||
for p in PROGRAMS:
|
||||
f = os.path.join(BIN, p)
|
||||
if not os.path.isfile(f):
|
||||
fail(f"{p} 缺失")
|
||||
continue
|
||||
if open(f, "rb").read(4) != b"\x7fELF":
|
||||
fail(f"{p} 不是 ELF")
|
||||
continue
|
||||
present.append(f)
|
||||
if READELF:
|
||||
m = re.search(r"Machine:\s*(.+)", run(READELF, "-h", f))
|
||||
if m and EXPECT_MACHINE not in m.group(1):
|
||||
fail(f"{p} 架构是 {m.group(1).strip()},期望含 {EXPECT_MACHINE}")
|
||||
if present and not fails:
|
||||
ok(f"{len(present)} 个程序都是 {EXPECT_MACHINE} 的 ELF")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] com.termux 残留(只允许 shebang 匹配模式)")
|
||||
if STRINGS is None:
|
||||
warn("没有 strings 工具,跳过字符串检查")
|
||||
else:
|
||||
unexpected = []
|
||||
for p in PROGRAMS:
|
||||
f = os.path.join(BIN, p)
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
hits = [ln for ln in run(STRINGS, "-a", f).splitlines() if "com.termux" in ln]
|
||||
extra = [h for h in hits if h not in ALLOWED_TERMUX]
|
||||
if extra:
|
||||
unexpected.append((p, extra[:3]))
|
||||
if unexpected:
|
||||
for p, hits in unexpected:
|
||||
fail(f"{p} 里有非预期的 com.termux 字符串:{hits}")
|
||||
else:
|
||||
ok("只有 shebang 匹配模式,没有编译死的配置路径")
|
||||
|
||||
# ---------------------------------------------------------------- 3/4/5
|
||||
print("\n[3-5] 运行时前缀解析 + 架构名")
|
||||
f = os.path.join(BIN, "dpkg")
|
||||
if STRINGS and os.path.isfile(f):
|
||||
s = run(STRINGS, "-a", f)
|
||||
lines = set(s.splitlines())
|
||||
|
||||
ok("有 /proc/self/exe") if "/proc/self/exe" in s else fail("没有 /proc/self/exe")
|
||||
ok("有 %s/etc/dpkg 拼接") if "%s/etc/dpkg" in s else fail("没有 %s/etc/dpkg 拼接")
|
||||
ok("有 DOUBAO_DPKG_PREFIX 覆盖口子") if "DOUBAO_DPKG_PREFIX" in s \
|
||||
else warn("没有 DOUBAO_DPKG_PREFIX(不影响功能)")
|
||||
|
||||
stale = [a for a in ("amd64", "arm64") if a in lines]
|
||||
if stale:
|
||||
fail(f"还带着 Debian 风格架构名 {stale}")
|
||||
else:
|
||||
ok("没有 Debian 风格架构名(amd64/arm64)")
|
||||
|
||||
if WANT_ARCH_NAME in lines:
|
||||
ok(f"架构名是 {WANT_ARCH_NAME}")
|
||||
else:
|
||||
fail(f"找不到架构名 {WANT_ARCH_NAME}")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n[6] 源码里架构名校验放开了下划线")
|
||||
src = os.path.join(BUILD, "lib/dpkg/arch.c")
|
||||
pm = os.path.join(BUILD, "scripts/Dpkg/Arch.pm")
|
||||
if os.path.isfile(src):
|
||||
t = open(src).read()
|
||||
# 用正则而不是字面量:源码里这段既有单引号又有下划线,字面量很容易写错
|
||||
has_underscore_in_loop = re.search(r"c_isalnum\(\*p\).*?'-'", t) and "_" in t
|
||||
has_underscore_in_msg = re.search(r'"\s*-_\s*"\s*\)', t) is not None
|
||||
if has_underscore_in_loop and has_underscore_in_msg:
|
||||
ok("lib/dpkg/arch.c 允许下划线")
|
||||
else:
|
||||
fail(f"lib/dpkg/arch.c 没放开下划线"
|
||||
f"(循环={bool(has_underscore_in_loop)} 文案={has_underscore_in_msg})")
|
||||
else:
|
||||
warn(f"找不到 {src}(跳过后两项源码检查)")
|
||||
if os.path.isfile(pm):
|
||||
t = open(pm).read()
|
||||
if "[a-zA-Z0-9_-]*" in t:
|
||||
ok("scripts/Dpkg/Arch.pm 允许下划线")
|
||||
else:
|
||||
fail("scripts/Dpkg/Arch.pm 没放开下划线")
|
||||
|
||||
# ---------------------------------------------------------------- 7/8
|
||||
print("\n[7-8] RUNPATH 与动态依赖")
|
||||
if READELF:
|
||||
for p in ("dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"):
|
||||
f = os.path.join(BIN, p)
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
d = run(READELF, "-d", f)
|
||||
if f"{PREFIX}/lib" not in d:
|
||||
fail(f"{p} 的 RUNPATH 没指向前缀 lib")
|
||||
needed = re.findall(r"Shared library: \[([^\]]+)\]", d)
|
||||
third = [n for n in needed if n.startswith("libmd")]
|
||||
if third:
|
||||
fail(f"{p} 还依赖 {third}(应该静态链进去)")
|
||||
if not any("RUNPATH" in m for m in fails):
|
||||
ok(f"6 个程序的 RUNPATH 都指向 {PREFIX}/lib")
|
||||
ok("都没有外部第三方库依赖(libmd/z/bz2/lzma/zstd 已静态链入)")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print(f"✅ {ARCH} 全部通过" + (f"({len(warns)} 条提示)" if warns else ""))
|
||||
439
docs/AI界面能力.md
Normal file
439
docs/AI界面能力.md
Normal file
@@ -0,0 +1,439 @@
|
||||
# AI 界面能力 —— 让 AI 弹界面、弹窗、结束对话
|
||||
|
||||
> 三个工具:`show_ui` / `ask_user` / `end_conversation`。
|
||||
> **默认关闭**,开关在「技能」页最上面那张卡片。
|
||||
|
||||
最后更新:v2.0.35
|
||||
|
||||
---
|
||||
|
||||
## 为什么要有这三个
|
||||
|
||||
对话是一来一回的文本。有些东西**用文字表达就是不如界面**:
|
||||
|
||||
- 一张算出来的图表 → 文字只能描述趋势
|
||||
- 一列宽对比表 → markdown 一宽就乱
|
||||
- "你要 A 还是 B" → 文字问完还得等用户打字,不如弹个按钮
|
||||
|
||||
而 `end_conversation` 解决的是另一个问题:**任务真的办完了**,
|
||||
继续聊下去只会兜圈子,得有个办法干净地收尾。
|
||||
|
||||
---
|
||||
|
||||
## 分工:一个不阻塞,一个阻塞
|
||||
|
||||
| 工具 | 阻不阻塞 | 为什么 |
|
||||
|---|---|---|
|
||||
| `show_ui` | **不阻塞** | 展示语义。用户可能盯着看很久,把内核线程占住没意义 |
|
||||
| `ask_user` | **阻塞**(最多 120s) | 问询语义。拿不到答案就没法继续 |
|
||||
| `end_conversation` | 立刻返回 | 它只改状态(落盘 + 界面收输入框) |
|
||||
|
||||
超时是**必须**的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
而 HTTP 是每请求一线程,挂一个少一个。
|
||||
|
||||
---
|
||||
|
||||
## show_ui:三种收尾方式(v2.0.38 起)
|
||||
|
||||
| 用法 | 行为 | 适合 |
|
||||
|---|---|---|
|
||||
| `wait` 不传(默认) | 弹出就返回,不等 | 图表、报告这类"给用户看"的 |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**,最多 `timeout` 秒(默认 120,上限 600) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| 不调用 | 纯文字回答 | —— |
|
||||
|
||||
等待模式下用户点的值**立刻**作为工具返回值给模型,**同一个回合里**就能接着处理:
|
||||
|
||||
```
|
||||
wait=true → 阻塞 9.3s → {"waited":true,"timeout":false,"value":"方案丙(JS)"}
|
||||
```
|
||||
|
||||
- 用户直接关掉界面(没点任何按钮)→ `value=""` + `closed=true`
|
||||
- 超时 → `timeout=true`,提示词里明确要求**别反复重弹**
|
||||
|
||||
### ★ 实现上的一个竞态
|
||||
|
||||
**先备好闩再弹界面**(`AiSurface.armScreenLatch()` 在 `showScreen` 之前调)。
|
||||
顺序反了的话:用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
`countDown()` 打在空闩上,然后我们才开始等 —— 直接等满超时。
|
||||
这类"用户比代码快"的问题在真机上很容易出现,纯逻辑推理发现不了。
|
||||
|
||||
### 按钮样式:必须做得不可能看不见
|
||||
|
||||
原来的 `.db-btn` 是 `#2a2d34` 暗底 + `#e8eaed` 字 ——
|
||||
**在深色主题下和普通段落长得一模一样**。用户的原话是"哪有按键"。
|
||||
|
||||
现在:整行宽、亮蓝底 + 白字、15px padding、16px 字号、按下有反馈,
|
||||
`!important` 压掉模型内联的样式(模型经常内联 `style="background:..."`
|
||||
把它盖掉)。普通 `<button>` 也给可见边框,但没那么抢眼。
|
||||
|
||||
提示词里也加了要求:**放按钮时要做明显,别用纯文字当按钮**。
|
||||
|
||||
---
|
||||
|
||||
## ★★★ 一个让所有工具更新都失效的 bug(v2.0.38 修)
|
||||
|
||||
这个坑比它表面看起来严重得多,完整记一遍。
|
||||
|
||||
### 现象
|
||||
|
||||
`_seed_tools` 是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
|
||||
后果:**每一次发版更新的内置工具,在老设备上一律拿不到。**
|
||||
|
||||
误导性在于:代码改了 ✓、APK 重编了 ✓、`app.imy` 里确实有新 `.pyc` ✓,
|
||||
但设备上跑的还是旧那份 —— 因为内核加载的是**落盘的那份旧源码**。
|
||||
实测 v2.0.37 给 `show_ui` 加了 `wait` 参数,设备上报的 spec 里根本没这个参数,
|
||||
我一度以为是 Gradle 构建缓存没生效。
|
||||
|
||||
**用户报的"按键点不了"根因就是这个**:他手机上是 v2.0.36 那份 `show_ui`,
|
||||
而回传按钮是 v2.0.37 才接通的。
|
||||
|
||||
### 修的过程里又踩了两个坑
|
||||
|
||||
**坑一**:第一版只看本地指纹文件 `.doubao-seed.json`。
|
||||
但**老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
|
||||
于是所有文件都被判成"用户改过",**升级还是永远不生效**。
|
||||
|
||||
把中间量全打出来才看清:
|
||||
|
||||
```
|
||||
summary: {"skip-same": 12, "skip-user-edited": 1}
|
||||
show_ui.py -> skip-user-edited | same=False
|
||||
```
|
||||
|
||||
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 字节,0 处 `wait` | **7439 字节,9 处 `wait`** |
|
||||
| spec 里的 `wait` 参数 | 没有 | 有 |
|
||||
| `.doubao-seed.json` | `{}` | 14 条记录 |
|
||||
|
||||
守门脚本:`scripts/verify-seed-tools.py`(8 节),
|
||||
专门包含"老设备场景(指纹空 + 盘上是旧版本)必须覆盖"和
|
||||
"盘上内容不在历史表里 → 不许覆盖"这两条。
|
||||
|
||||
---
|
||||
|
||||
## show_ui:模型写 HTML
|
||||
|
||||
```
|
||||
{ "html": "<h1>结果</h1><table>…</table>", "title": "分析报告", "full_html": false }
|
||||
```
|
||||
|
||||
### 只写片段就行
|
||||
|
||||
默认会套一层骨架(暗色主题、表格样式、代码块、`viewport`)。
|
||||
模型不用每次重复写这些 —— 既啰嗦又容易和 App 主题打架。
|
||||
|
||||
想完全控制就传 `full_html: true`,那时 `html` 必须是一份完整文档。
|
||||
|
||||
### 可点的按钮 / 回传值:**三条路都收**
|
||||
|
||||
```html
|
||||
<button onclick="Doubao.sendToAi('值')">文字</button> <!-- 推荐 -->
|
||||
<button onclick="Doubao.pick('值')">文字</button> <!-- 等价简写 -->
|
||||
<button data-doubao-result="值">文字</button> <!-- 不写 JS 也能用 -->
|
||||
```
|
||||
|
||||
前两条走 JS 桥;第三条走**纯字符串替换**(App 侧把 `data-doubao-result`
|
||||
改成 `doubao://pick?value=...`,由 `WebViewClient` 拦下来)——
|
||||
所以页面即使 JS 出错,第三条仍然能用。
|
||||
|
||||
### ★★★ 值真的会回到模型手里(v2.0.37 才接通)
|
||||
|
||||
**上一版这里是名不副实的**:`Doubao.pick` 只是"关掉界面 + 弹个提示",
|
||||
值根本没送到模型。现在是一条完整链路:
|
||||
|
||||
```
|
||||
AI 写的 HTML: Doubao.sendToAi('用户选了方案B')
|
||||
→ JS 桥 AiWebHost.sendToAi
|
||||
→ NativeBridge 的 ui_result action → POST /api/ui-result
|
||||
→ store 里排队(内存,一次性上下文,不落盘)
|
||||
→ 下一轮 run_agent 取走,作为一条 system 消息插在历史前面
|
||||
→ 模型看到"用户在界面上选了什么"
|
||||
```
|
||||
|
||||
几个刻意的决定:
|
||||
|
||||
| 决定 | 为什么 |
|
||||
|---|---|
|
||||
| **排队**而不是"点了就起一轮对话" | 用户可能连点几下、选好几项再确认。每点一下跑一轮模型又慢又费 token,而且用户还没说完。语义上界面上的选择是**提问的一部分,不是提问本身** |
|
||||
| 插成 **system** 而不是 user | 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,而且"重新生成"时会和真正那条用户消息混在一起 |
|
||||
| **取走**而不是"读" | 不取走的话每轮都带上同一条,模型会反复提同一件事 |
|
||||
| 提示语写"已记下,**下次**对话会告诉 AI" | 不写"已发送"——后者会让用户以为模型马上回话,然后干等 |
|
||||
| 不落盘 | 一次性的上下文,跨重启没意义(界面早关了,那个选择也就失效了) |
|
||||
|
||||
想要"选完**立刻**有回应"的语义,用 `ask_user`(它是阻塞的)。
|
||||
|
||||
### 实测证据
|
||||
|
||||
起一个假的 OpenAI 兼容服务,把内核指过去,直接读它收到的请求体:
|
||||
|
||||
```
|
||||
[system] 你是豆包,…
|
||||
[system] 用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):
|
||||
- 用户选了方案 B(蓝色按钮)
|
||||
- 用户填写了:预算 3000 元
|
||||
[user] 我刚才在界面上选了什么?
|
||||
```
|
||||
|
||||
脚本:`scripts/fake-openai.py` + `scripts/probe-ui-result-e2e.py`。
|
||||
|
||||
★ 假服务在**模拟器里**连宿主机,要用 `adb reverse tcp:18080 tcp:18080`。
|
||||
`10.0.2.2` 在 LDPlayer 上**不通**(假服务一个请求都收不到,
|
||||
很容易误判成"代码有问题"——我在这儿绕了一圈)。
|
||||
|
||||
### JS 与桥:按页面收口(v2.0.36 起)
|
||||
|
||||
用户要求支持 JS。开了之后模型能写 `<script>`:canvas 画图、按数据动态生成
|
||||
界面、算完再渲染 —— 这些纯 CSS 做不到。
|
||||
|
||||
**但开 JS 之后最大的风险不是 JS 本身**,而是 `addJavascriptInterface` 注入的
|
||||
那个桥:**它对之后加载的每一个页面都可见**。AI 页面里点个链接落到外部站点,
|
||||
那个站点的脚本就能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
|
||||
所以:
|
||||
|
||||
- 桥**只挂在 AI 那一页**(初始 load 之前挂,保证内联 `<script>` 能用)
|
||||
- 一导航到 http(s) **立刻摘掉** —— 实测外部页面里 `typeof Doubao === 'undefined'`
|
||||
- 返回 AI 页时**自动恢复**(否则"点进去再返回,按钮全失灵")
|
||||
- 桥只暴露 `pick` / `close` 两个方法,面越小越好
|
||||
- `allowFileAccess` / `allowContentAccess` / 混合内容依然全关
|
||||
|
||||
### ★★ 挂桥时序改了三版才对
|
||||
|
||||
这段只能用真机实测发现,把三版的失败记下来:
|
||||
|
||||
| 版本 | 做法 | 失败表现 |
|
||||
|---|---|---|
|
||||
| 一 | load 前挂,导航时摘 | 外部页面在 `onPageStarted` 摘桥**之前**有"已开始加载、桥还在"的窗口 |
|
||||
| 二 | 只在 `onPageFinished` 里判 url 才挂 | 页面报 `Doubao is not defined` —— **`onPageFinished` 的回调比页面内联 `<script>` 执行还晚** |
|
||||
| 三 | load 前挂 + 标志挡窗口 + 返回时用**页面标记变量**判 | ✓ |
|
||||
|
||||
第三版那个"用标记变量判"也是被逼出来的:**用 url 判会漏** ——
|
||||
从外部页 `goBack()` 回来时,`onPageFinished` 收到的 url 不是 `about:blank`,
|
||||
于是桥不重挂,表现是"点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
|
||||
做法:`evaluateJavascript` 里写一个 `window.__doubaoAiPage = 1` 并回读 ——
|
||||
如果标记在、而桥不在,说明这是我们那一页且桥被摘过,重挂。
|
||||
页面被换掉标记就没了,所以外部页面不会误判。
|
||||
|
||||
★ `evaluateJavascript` 的回调参数是**字符串**(返回值经 JSON 编码),
|
||||
按 Boolean 判的话条件永远不成立 —— 我也踩了这个。
|
||||
|
||||
### 链接能点进去
|
||||
|
||||
`http/https` 在 WebView 里直接打开(以前 `return true` 吃掉了),
|
||||
顶部自动出现「←」返回键;系统返回键也先回退网页、退不了才关界面。
|
||||
别的协议(`tel:` / `mailto:` / `intent:`)交给系统。
|
||||
|
||||
---
|
||||
|
||||
## 网页(真实网站,不是你写的)
|
||||
|
||||
回复里只要有链接,消息下方就有个 🌐 **「打开网页」** 按钮。
|
||||
点开是全屏网页界面,顶部 后退/前进/刷新/用系统浏览器打开。
|
||||
|
||||
> 用户的原话是"你要单独开个按钮" —— 对。把链接做成蓝色下划线**没有可发现性**:
|
||||
> 用户不知道它能点、也不知道点了会发生什么。产品上正确的就是给个按钮。
|
||||
|
||||
### 点选:在真实网页上点内容带回给 AI
|
||||
|
||||
顶部一条「点选」横条(做成常驻横条而不是一个图标 —— 这能力不看说明发现不了)。
|
||||
打开后:
|
||||
|
||||
- 在页面上**点任意内容**(不只是链接按钮),内容会被记下来
|
||||
- 在表单里**填的字**也会被记下来(防抖 600ms,不会打十个字塞十条)
|
||||
- 攒够了点「发给 AI」,一起发出去
|
||||
|
||||
### ★ 这里**没有 JS 桥**
|
||||
|
||||
和 `show_ui` 那段的关键区别:这里浏览的是**互联网上任意站点**,
|
||||
全程都在别人的页面上。挂桥等于把 App 的内部接口交给它们。
|
||||
|
||||
所以用"单向队列 + 主动轮询":
|
||||
|
||||
```
|
||||
注入的脚本(页面里) Kotlin 侧
|
||||
──────────────────── ──────────────
|
||||
用户点了/写了 → 塞进 window.__doubaoPicks
|
||||
每 500ms evaluateJavascript("取走队列")
|
||||
← 拿到 JSON
|
||||
```
|
||||
|
||||
数据**只从页面流向 App**,页面没有任何办法主动调 App。
|
||||
|
||||
★ 改过一版:第一版只认"看着能点"的元素(`a,button,[role=button],…`),
|
||||
实测在 example.com 上**一个都标不出来**(那页全是纯文本),于是点选模式
|
||||
看起来完全没生效。用户想点的是**任意一段内容**,所以改成
|
||||
`elementFromPoint` 点哪儿抓哪儿,虚线框降级成纯视觉提示。
|
||||
|
||||
★ 点选用**捕获阶段** + `preventDefault`:抢在页面自己的 handler 前面,
|
||||
并拦掉这次跳转(用户是"选中"不是"跳转")。
|
||||
但 `input` 事件用**冒泡阶段旁听**、不拦 —— 拦了会破坏页面的自动补全、字数统计。
|
||||
|
||||
---
|
||||
|
||||
## ★ 清不掉 Base URL 的坑(v2.0.37 修)
|
||||
|
||||
`store.write_settings` 有一段"保险":空串一律当"没填、别动"。
|
||||
它防的是**"前端草稿没初始化好,一次保存清空整份配置"**,这个保险是对的。
|
||||
|
||||
但代价是:**用户永远清不掉自定义 Base URL / 模型名** ——
|
||||
删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||||
(我是在测数据回流时踩到的:想把内核从假服务指回默认,传空串怎么也改不掉。)
|
||||
|
||||
修法:加一条**显式**的清除通路 —— 传 `null` 就是"确实要清掉",落到默认值上。
|
||||
|
||||
| 传什么 | 含义 |
|
||||
|---|---|
|
||||
| `""` | 没填,别动 |
|
||||
| `null` | 确实要清掉,回到默认 |
|
||||
|
||||
Python 和 Node 两端都改了(同一段逻辑有两份,改一边就会不一致)。
|
||||
|
||||
---
|
||||
|
||||
## ask_user:弹选择框
|
||||
|
||||
```
|
||||
{ "question": "这个方案你要哪一个?",
|
||||
"options": [{"label": "方案 A", "value": "A", "description": "快但功能少"}],
|
||||
"multiple": false, "allow_cancel": true }
|
||||
```
|
||||
|
||||
### options 两种写法都收
|
||||
|
||||
模型经常写**裸字符串数组** `["A", "B"]` 而不是对象数组 —— 这在 tool calling
|
||||
里非常常见。只认一种的话它会平白吃一个 `AttributeError`,然后重试、再失败。
|
||||
所以 `_clean_options()` 两种都收,还会丢掉空项、把 `value` 回落到 `label`。
|
||||
|
||||
### 超过 8 个选项会截断
|
||||
|
||||
按钮会挤成一屏。截断的同时**告诉模型**(返回里带 `note`),
|
||||
而不是静默丢掉 —— 静默丢掉会让它以为用户看到了 20 个选项。
|
||||
|
||||
---
|
||||
|
||||
## end_conversation:永久结束
|
||||
|
||||
### 界面(用户指定)
|
||||
|
||||
**屏幕中间一个横幅,写着 AI 关闭的原因。**
|
||||
|
||||
```
|
||||
⌐ 这次对话已结束
|
||||
这件事已经办完了,没有后续可聊的。
|
||||
[ 开始新对话 ]
|
||||
```
|
||||
|
||||
- 停在**屏幕正中间**,**不自动消失** —— 它是状态不是提示,
|
||||
消失了用户就不知道为什么发不出消息了
|
||||
- 输入框整个不渲染(不是"渲染成禁用"),用户看到的就是"这儿没得输了"
|
||||
- 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
|
||||
### 必须落盘
|
||||
|
||||
`PATCH /api/conversations/<id>` 写 `ended` / `endedAt` / `endedReason`。
|
||||
|
||||
★ 只放 Compose 状态里的话,**一刷新就没了**:用户关掉 App 再进来会看到
|
||||
一个能继续输入的框,而模型以为自己已经结束了。两边状态不一致是这类功能
|
||||
最容易出的问题。
|
||||
|
||||
### 拿不到对话 id 时必须报错
|
||||
|
||||
绝不假装成功。假装成功正好会产生上面那个不一致。
|
||||
|
||||
---
|
||||
|
||||
## 开关:两道拦截,缺一不可
|
||||
|
||||
`settings.uiTools.enabled`,默认 `false`。
|
||||
|
||||
1. **对模型隐藏**(`filter_ui_tools`)—— 关掉时它根本看不到这三个工具
|
||||
2. **执行时拒绝**(`execute_tool` 里的第二道)—— 即使它硬编名字也不执行
|
||||
|
||||
★ 为什么两道都要:只做①的话,用户关掉之后模型仍可能**从历史消息里**
|
||||
学会这个名字(之前的对话里出现过)再调一次。
|
||||
|
||||
★ 提示词也按开关走:`UI_TOOLS_HINT` 只在打开时追加到系统提示词。
|
||||
写进 `DEFAULT_SYSTEM_PROMPT` 的话会被存进用户的 `settings.json` ——
|
||||
关着的时候模型还在被教"你可以用 show_ui"。
|
||||
|
||||
---
|
||||
|
||||
## 踩过的两个坑
|
||||
|
||||
### ① thread-local 不跨线程(最隐蔽的一个)
|
||||
|
||||
`end_conversation` 一直报"拿不到当前对话 id"。我以为是 `app.py` 没传
|
||||
`conversationId`,查了一圈才发现:
|
||||
|
||||
```
|
||||
app.py push_context(conversationId=…) ← 在 HTTP 工作线程 A 上
|
||||
→ execute_tool
|
||||
→ run_python_tool
|
||||
→ run_with_timeout(fn) ← 起了**线程 B**
|
||||
→ fn() → tool.run() ← 在 B 上,_ctx 是空的!
|
||||
```
|
||||
|
||||
`threading.local()` **不跨线程继承**。工具照常执行(参数都对),
|
||||
只有上下文拿不到 —— 表现和"参数没传"一模一样。
|
||||
|
||||
修法:`run_python_tool` 执行前把父线程的上下文搬进工作线程。
|
||||
验证脚本里专门留了"另一个线程里读不到(符合 thread-local 语义)"这条 ——
|
||||
说明这个语义是**故意**的,所以必须显式搬。
|
||||
|
||||
### ② `/api/tools/run` 传的是假 settings
|
||||
|
||||
以前是 `{'security': {'mode': 'open'}}` 空壳,为的是"手动试运行不受安全模式
|
||||
限制"。但界面工具的开关也在 settings 里 —— 于是用户在技能页点「试运行」,
|
||||
**开关明明是开的,却收到"已关闭"**。这个错会让人以为是开关没生效。
|
||||
|
||||
改成拿真实设置、只覆盖 `security`。
|
||||
|
||||
---
|
||||
|
||||
## 怎么测
|
||||
|
||||
```bash
|
||||
# 守门(34 项)
|
||||
python scripts/verify-ui-tools.py
|
||||
|
||||
# 端到端(需要先把内核端口转发出来)
|
||||
adb forward tcp:15199 tcp:5199
|
||||
python scripts/probe-ai-surfaces.py all # show_ui + end_conversation
|
||||
python scripts/probe-ai-surfaces.py ask # ask_user(会阻塞,等你在手机上点)
|
||||
python scripts/probe-ai-surfaces.py askmulti
|
||||
```
|
||||
|
||||
★ 为什么从宿主机打而不是在设备上敲:`adb`/PowerShell 的多层引号会把 JSON
|
||||
搅烂(这一路上踩过好几次)。转发端口之后在宿主机上用 Python 打,引号只有一层。
|
||||
|
||||
真机实测记录(Android 14 x86_64):
|
||||
|
||||
```
|
||||
show_ui → 界面渲染正常(标题栏 + 暗色表格 + 可点按钮)
|
||||
ask_user 单选 → 等 21.1s,返回 {"choice":"B","values":["B"],"timeout":false}
|
||||
ask_user 多选 → 选 2 个,返回 {"values":["python","git"],"cancelled":false}
|
||||
end_conversation → ended=True 落盘,横幅显示原因
|
||||
```
|
||||
454
docs/termux-pty-调查.md
Normal file
454
docs/termux-pty-调查.md
Normal file
@@ -0,0 +1,454 @@
|
||||
# 内置终端的 pty 问题 —— 排查记录
|
||||
|
||||
> ## ✅ 已解决(v2.0.19 / v2.0.20)
|
||||
>
|
||||
> 一共**三个 bug 叠在一起**:
|
||||
>
|
||||
> | # | Bug | 现象 |
|
||||
> |---|---|---|
|
||||
> | ① | libtermux.so 里 **rgs[0] 就是 rgv[0]**,我传的第一个元素是 --rcfile | bash 把 rc 当脚本跑一遍就退(退出码 0);pty master 读 EIO |
|
||||
> | ② | **TerminalSessionClient.onTextChanged 是空的** | pty 通了、bash 活着,但屏幕一像素都不刷新 |
|
||||
> | ③ | **ENTER 发 \n(LF)而不是 \r(CR)**,且键位被滚出屏幕 | 命令敲得进去、回车没反应 |
|
||||
>
|
||||
> **① 是最难的**:在 bash、环境变量、LD_PRELOAD、pty 尺寸、SELinux、
|
||||
> TIOCGPTPEER 上绕了四轮全是死路。最后一轮**直接抓 termux.c 源码**,
|
||||
> 一眼看到 rgv[i] = strdup(args[i]);。
|
||||
>
|
||||
> **教训**:遇到某个库行为诡异,**先读它的源码或反汇编它**,
|
||||
> 别在现象层面试。工具留在 scripts/dis-termux.py。
|
||||
>
|
||||
> 下面是完整的排查过程(保留着,这些死路别再走一遍)。
|
||||
|
||||
|
||||
**状态:未解决。** 真终端(Termux 的 TerminalView + libtermux.so)能起来、
|
||||
能渲染,但 shell 一起来就退出(退出码 0),屏幕停在
|
||||
`[Process completed - press Enter]`,打字没反应。
|
||||
|
||||
命令控制台(同一条 Termux bash,没有 tty)**是能用的**:
|
||||
`pkg update` / `pkg install python` 都正常。
|
||||
|
||||
---
|
||||
|
||||
## 已经排除的(都实测过,别再走一遍)
|
||||
|
||||
| 猜测 | 实测结果 |
|
||||
|---|---|
|
||||
| bash 本身有问题 | ✗ 用 adb 直接跑 `bash --rcfile ... -i` 完全正常(rc、颜色、提示符都对) |
|
||||
| 缺 native 库 | ✗ `libtermux.so` 两个 ABI 都在包里,5 个 JNI 符号齐全,含 `ptmx` |
|
||||
| 缺 dash / 断链 | ✗ `sh -> dash`,dash 在(103KB,可执行) |
|
||||
| 路径没改写 | ✗ `pkg` 里 0 处 `com.termux`(`rewritePrefixes` 已经处理) |
|
||||
| `LD_PRELOAD` 弄坏 stdin | ✗ 不带 preload 起,一样秒退 |
|
||||
| 尺寸是 0×0 | ✗ 日志实测 `cols=42 rows=27 cell=17x33`,尺寸是对的 |
|
||||
| pty 没建起来 | ✗ 日志实测 `createSubprocess -> fd=92 pid=6868`,fd 和 pid 都正常 |
|
||||
| SELinux 拒绝 | ✗ 没有 denied;bash 的 exec 是 `granted` |
|
||||
| `LD_LIBRARY_PATH` 屏蔽系统库 | ✗ `$PREFIX/lib` 里没有 `libc.so`(只有 `libc++_shared.so` 等) |
|
||||
|
||||
## 关键日志(`files/termux-install.log`)
|
||||
|
||||
```
|
||||
updateSize cols=42 rows=27 cell=17x33 emulator=false
|
||||
createSubprocess -> fd=92 pid=6868 rows=27 cols=42 cell=17x33
|
||||
终端会话结束,退出码=0 ← 42 毫秒后
|
||||
```
|
||||
|
||||
**pty 是建成功的**(fd 有效、pid 有效、尺寸正确),
|
||||
**shell 是自己决定退出的**(退出码 0 = 读到 stdin EOF 就干净退出)。
|
||||
|
||||
## 一个很可疑的旁证
|
||||
|
||||
拿 `/system/bin/cat`(无参数时会一直读 stdin)当 shell 试:
|
||||
|
||||
```
|
||||
终端会话已建:/system/bin/cat (不带 preload,干净环境)
|
||||
createSubprocess -> fd=92 pid=6961
|
||||
终端会话结束,退出码=127 ← 127 = execvp 失败
|
||||
```
|
||||
|
||||
而且 **logcat 里没有对应的 avc 记录** —— 说明失败发生在 SELinux 检查**之前**,
|
||||
也就是 `execvp` 本身就没成。
|
||||
|
||||
`/system/bin/cat -> toybox` 是存在的(symlink)。所以"找不到文件"不是原因。
|
||||
**这条线索没查完**:为什么干净环境下 execvp 一个系统二进制会失败。
|
||||
|
||||
## 下一步该查的方向
|
||||
|
||||
1. **`createSubprocess` 到底 exec 的是什么**。
|
||||
`libtermux.so` 里只有 9KB,可以直接反汇编看 `Java_com_termux_terminal_JNI_createSubprocess`
|
||||
的子进程分支(fork 之后那段),确认它 execvp 的路径和 argv 构造方式。
|
||||
2. **vended 的 Java 和 `.so` 是不是配套版本**(见下)。
|
||||
3. 换一个**已经验证过能跑**的 Termux 组合(同一次 release 的
|
||||
terminal-emulator Java 源码 + 对应版本的 libtermux.so)再试。
|
||||
|
||||
## 版本配对问题(重要)
|
||||
|
||||
- `TerminalSession.java` 里构造函数**只存字段**,子进程是在
|
||||
`initializeEmulator(columns, rows, ...)` 里调 `JNI.createSubprocess(...)` 建的,
|
||||
由 `TerminalView.attachSession()` 触发。
|
||||
→ 所以 **attach 必须在 view 量过尺寸之后**(代码里已用 `doOnLayout` 保证)。
|
||||
- `JNI.java` 声明的签名是 9 个参数:
|
||||
`(cmd, cwd, args, envVars, processId, rows, columns, cellWidth, cellHeight)`。
|
||||
**JNI 不做签名校验** —— Java 和 `.so` 版本不配对时不会报错,
|
||||
只会读到垃圾值。要确认 `libtermux.so` 是从哪个 Termux 版本拿的,
|
||||
和 vendored 的 Java 是不是同一次 release。
|
||||
|
||||
## 已经做好的、可以保留的部分
|
||||
|
||||
- 起 shell **依次试几种起法**,由**秒退事件**驱动回退(不是 try/catch ——
|
||||
bash 起不来时构造函数不抛异常)
|
||||
- 起法全试完 → 立刻切命令控制台(别让人对着黑屏等)
|
||||
- `TerminalView` 点一下弹软键盘(之前 `onSingleTapUp` 是空代码)
|
||||
- attach 用 `doOnLayout` 保证量完尺寸再做
|
||||
- 会话创建/退出/换起法**全程落盘**(`files/termux-install.log`),排查不用猜
|
||||
|
||||
|
||||
---
|
||||
|
||||
# 第二轮:拆 libtermux.so + 环境隔离
|
||||
|
||||
## 1. `createSubprocess` 到底做了什么(从 .so 的字符串看出来的)
|
||||
|
||||
`libtermux.so`(x86_64,9248 字节)里能直接读到的符号和字符串:
|
||||
|
||||
```
|
||||
execvp ← 子进程最后 execvp(cmd, argv)
|
||||
clearenv ← ★ 先把环境**整个清空**
|
||||
putenv ← 再把我传进去的 env 逐条放回去
|
||||
chdir ← 切到 cwd
|
||||
fork setsid ioctl dup2
|
||||
open("/dev/ptmx") grantpt unlockpt ptsname_r
|
||||
opendir("/proc/self/fd") readdir closedir ← 关掉继承来的 fd
|
||||
_exit / exit / perror
|
||||
|
||||
错误信息(perror 的格式串):
|
||||
Cannot open /dev/ptmx
|
||||
Cannot grantpt()/unlockpt()/ptsname_r() on /dev/ptmx
|
||||
Fork failed
|
||||
Couldn't allocate argv array
|
||||
chdir("%s") exec("%s")
|
||||
GetStringUTFChars() failed for argv / for env
|
||||
```
|
||||
|
||||
**结论**:exec 失败时走 `perror("exec()")` + **`_exit(127)`** ——
|
||||
所以 `/system/bin/cat` 那个 **127 就是"execvp 没成功"**,不是别的。
|
||||
|
||||
**但屏幕上没看到 `exec(): ...` 那行** —— 值得注意(stderr 应该已经 dup2 到 pty 了)。
|
||||
|
||||
## 2. 关键的环境冲突(实测)
|
||||
|
||||
```
|
||||
# 用 app 身份直接跑
|
||||
/system/bin/cat --version
|
||||
→ toybox 0.8.9-android ✓ 能跑
|
||||
|
||||
files/usr/bin/bash --version
|
||||
→ CANNOT LINK EXECUTABLE "files/usr/bin/bash":
|
||||
library "libandroid-support.so" not found ✗
|
||||
```
|
||||
|
||||
**`bash` 必须靠 `LD_LIBRARY_PATH=$PREFIX/lib` 才能加载**
|
||||
(`libandroid-support.so` 在 prefix/lib 里)。
|
||||
|
||||
于是 `bash` 和"系统二进制"对环境的要求是**相反**的:
|
||||
* 我们的二进制:**需要** `LD_LIBRARY_PATH=$PREFIX/lib`
|
||||
* 系统二进制:给了它**也不报错**(实测 `cat` 带 `LD_LIBRARY_PATH` 照样跑 ✓)
|
||||
|
||||
→ **这条不算冲突**,之前的猜测排除。`cat` 带 `LD_LIBRARY_PATH` ✓、
|
||||
带 `LD_PRELOAD` ✓、都带 ✓ —— 都能跑。
|
||||
|
||||
## 3. 现在最可疑的一条(可复现)
|
||||
|
||||
```
|
||||
LD_LIBRARY_PATH=$PREFIX/lib LD_PRELOAD=$PREFIX/lib/libtermux-exec.so TERMUX__PREFIX=$PREFIX TERMUX_APP__DATA_DIR=... $PREFIX/bin/bash -c "echo BASH_OK"
|
||||
→ 输出**空的**(应该打印 BASH_OK)
|
||||
```
|
||||
|
||||
**在 app 身份下,bash 带完整终端环境跑 `-c` 什么都不输出。**
|
||||
这跟终端里的表现一致(rc 的 echo 打出来了、然后就没动静了)。
|
||||
|
||||
**下一步**:把上面这条拆成几种环境组合,找出**哪一个变量**让它"静默什么都不做"。
|
||||
(我第一次用嵌套引号写这条命令写坏了,改成**写一个 .sh 文件推到设备上跑**,
|
||||
别再在 adb 命令里套引号。)
|
||||
|
||||
## 4. 一个重要的方法论教训
|
||||
|
||||
`run-as <pkg> ...` 的 SELinux 上下文是 **`runas_app`**,
|
||||
和 App 真正运行时的 **`untrusted_app`** 不是同一个。
|
||||
**用 `run-as` 得到的结论要打折看** —— 最好还是在 App 里打日志验证。
|
||||
|
||||
## 5. 已经能确定能用的
|
||||
|
||||
* 换源 ✓(装完自动换清华)
|
||||
* 命令控制台 ✓(`pkg update` / `pkg install python`)
|
||||
* App 身份**能**执行 `/system/bin/*` ✓(toybox 跑起来了)
|
||||
|
||||
所以问题**不在 exec 权限**,而在 bash 在 pty 里的启动/环境。
|
||||
|
||||
|
||||
---
|
||||
|
||||
# 第三轮:决定性实验 —— pty 双向都不通
|
||||
|
||||
## 实验
|
||||
|
||||
把 shell 换成一个**先打印、再挂住**的命令:
|
||||
|
||||
```kotlin
|
||||
Triple("$prefix/bin/sh", arrayOf("-c", "echo ALIVE_FROM_PTY; sleep 30"), true)
|
||||
```
|
||||
|
||||
理由:`sleep 30` 保证进程活着;`echo` 保证只要 pty 输出通道是通的,
|
||||
屏幕上就**一定**能看到 `ALIVE_FROM_PTY`。
|
||||
|
||||
## 结果
|
||||
|
||||
**屏幕全黑,一个字都没有。**
|
||||
|
||||
同时日志里会话在几十毫秒后就结束了(退出码 0 / 2),
|
||||
说明**子进程确实跑了、确实退出了**(退出码能通过 `waitFor` 拿回来)。
|
||||
|
||||
## 结论(这一轮最重要的)
|
||||
|
||||
> **pty 的输入和输出两个方向都不通。**
|
||||
> 不是 bash 的问题、不是环境的问题、不是库的问题 ——
|
||||
> 子进程在跑,但**一个字节都没经过 pty**。
|
||||
|
||||
**所以之前所有"bash 为什么退出"的方向都是死路**:
|
||||
bash 退出**是结果不是原因** —— 它的 stdin 是坏的(读不到东西 → EOF → 退出),
|
||||
它的 stdout 也是坏的(rc 里那行 echo 能显示,是因为……见下面的疑点)。
|
||||
|
||||
## 一个必须解释的疑点
|
||||
|
||||
更早的测试里,终端的屏幕上**确实出现过** rc 里那行
|
||||
`豆包内置 Termux —— 试试 pkg install python`。
|
||||
|
||||
如果 pty 输出完全不通,那行字是**怎么显示出来的**?
|
||||
|
||||
可能的解释(要验):
|
||||
1. 那行字是**别的东西**画的(比如某个旧会话残留的缓冲)
|
||||
2. 输出通道**部分**能用:启动瞬间能通,之后断掉
|
||||
3. `TerminalView` 直接读了子进程的 fd,没走 pty
|
||||
|
||||
**这条不搞清楚,方向就还会飘。**
|
||||
|
||||
## 下一站:查 `wrapFileDescriptor`
|
||||
|
||||
`TerminalSession.wrapFileDescriptor(int, TerminalSessionClient)` 里是这么干的:
|
||||
|
||||
```java
|
||||
FileDescriptor result = new FileDescriptor();
|
||||
Field descriptorField = FileDescriptor.class.getDeclaredField("descriptor");
|
||||
descriptorField.setAccessible(true); // ★ 这一步在 Android 9+ 上可能被拦
|
||||
descriptorField.setInt(result, fileDescriptor);
|
||||
```
|
||||
|
||||
`java.io.FileDescriptor#descriptor` 是**私有字段**,
|
||||
Android 9+ 对 `java.*` 的私有成员反射有隐藏 API 限制
|
||||
(应用 targetSdk 决定松紧)。**Termux 自己也在这上面栽过。**
|
||||
|
||||
如果这里被拦:`result` 的 descriptor 还是 -1,
|
||||
于是 `new FileInputStream(terminalFileDescriptorWrapped)` 读的是 fd -1
|
||||
→ 输入线程立刻退出 → **输入方向永远收不到数据**。
|
||||
输出方向同理(`FileOutputStream`)。
|
||||
|
||||
**验法**:在 `wrapFileDescriptor` 前后打日志把
|
||||
`descriptorField.setAccessible(true)` 的结果 / 异常打出来,
|
||||
并且把 `mTerminalFileDescriptor` 和反射后拿到值对比。
|
||||
|
||||
**替代实现**(如果确实被拦):
|
||||
用 `ParcelFileDescriptor.adoptFd(fd)` 拿到 `FileDescriptor`
|
||||
(公开 API,不走反射),再 `new FileInputStream(pfd.getFileDescriptor())`。
|
||||
|
||||
## 方法论:别再用一次性命令做实验
|
||||
|
||||
这一轮我三次把代码/测试写坏(Python 三引号、PowerShell 引号嵌套、
|
||||
按行号剪贴)。**改成**:
|
||||
* 改 Kotlin 用 `edit` 工具,一次一处,改完立刻编译
|
||||
* 要在设备上跑脚本,就**写一个 .sh 文件推上去**,别在 `adb shell` 里套引号
|
||||
|
||||
|
||||
---
|
||||
|
||||
# 第四轮:**根因找到了**
|
||||
|
||||
## 关键日志
|
||||
|
||||
给 `TermSessionInputReader` 那个**被静默吞掉**的异常加上日志之后:
|
||||
|
||||
```
|
||||
10:38:08.436 createSubprocess -> fd=92 pid=7846 rows=27 cols=42
|
||||
10:38:08.436 Accessing hidden field Ljava/io/FileDescriptor;->descriptor:I
|
||||
(unsupported, reflection, allowed) ← 反射是 allowed,没被拦
|
||||
10:38:08.436 wrapFileDescriptor fd=92 -> java.io.FileDescriptor@fc09b35
|
||||
10:38:08.463 TermSessionInputReader 退出
|
||||
10:38:08.463 java.io.IOException: read failed: EIO (I/O error)
|
||||
at libcore.io.Linux.readBytes(Native Method)
|
||||
Caused by: android.system.ErrnoException: read failed: EIO (I/O error)
|
||||
```
|
||||
|
||||
## 根因
|
||||
|
||||
> **读 pty 的 master 端返回 `EIO` —— 意思是"从端(slave)没有被任何进程打开"。**
|
||||
|
||||
也就是说:**子进程的 stdin / stdout / stderr 不是那个 pty 从端。**
|
||||
|
||||
这一条**解释了之前所有的现象**:
|
||||
|
||||
| 现象 | 解释 |
|
||||
|---|---|
|
||||
| master 读 EIO、输入线程立刻死 | slave 没开 → master 读就是 EIO |
|
||||
| 屏幕什么都没有(连 `echo ALIVE` 都不显示) | 输出通道整个是断的 |
|
||||
| bash 几十毫秒后干净退出(退出码 0) | 它的 stdin 是坏的 → 读 EOF → 正常退出 |
|
||||
| 退出码能拿到 | 子进程确实 fork 了、确实跑了、`waitFor` 正常 |
|
||||
|
||||
**bash 本身没有任何问题** —— 是它的三个标准流没接到 pty 上。
|
||||
|
||||
## 所以真正要修的地方
|
||||
|
||||
在 `libtermux.so` 的 `Java_com_termux_terminal_JNI_createSubprocess`
|
||||
**子进程分支**里,这一段:
|
||||
|
||||
```c
|
||||
setsid();
|
||||
ioctl(slave, TIOCSCTTY, 0);
|
||||
dup2(slave, 0); dup2(slave, 1); dup2(slave, 2);
|
||||
```
|
||||
|
||||
以及它前面的:
|
||||
|
||||
```c
|
||||
slave = open(ptsname_r(ptm, buf, sizeof(buf)), O_RDWR); // ★ 怀疑这里失败
|
||||
```
|
||||
|
||||
`.so` 里的错误串是 `Cannot grantpt()/unlockpt()/ptsname_r() on /dev/ptmx`
|
||||
(**这个串是父进程分支的**,子进程里 open 失败没有专门的串)。
|
||||
|
||||
**怀疑顺序**(按可能性):
|
||||
|
||||
1. **子进程里 `open("/dev/pts/N")` 失败** —— 父进程 `grantpt/unlockpt` 成功不代表
|
||||
子进程能打开从端。可能是 **devpts 的挂载命名空间** 或 SELinux 对
|
||||
`open` 从端的限制(注意我们的上下文是 **`untrusted_app_27`**)。
|
||||
2. `TIOCSCTTY` 失败导致后续 dup2 被跳过(可能性低,通常不影响 fd 0/1/2)。
|
||||
3. `.so` 和 vendored Java 版本不配对(JNI 不校验签名,会读到垃圾值)。
|
||||
|
||||
## 下一步怎么验(很具体)
|
||||
|
||||
**① 在设备上直接看子进程的 fd 0/1/2 指向哪里**
|
||||
|
||||
写个脚本用 `$PREFIX/bin/sh` 当 shell 而**不是** `-c`,让它自己打印:
|
||||
|
||||
```sh
|
||||
# 推到设备上、当 shell 路径传进去(args 传 ["-c", "ls -l /proc/self/fd; sleep 30"])
|
||||
ls -l /proc/self/fd
|
||||
```
|
||||
屏幕上看不到就只能看**落盘**:让命令把输出**重定向到文件**再 `adb` 拉出来 ——
|
||||
这样**绕开 pty**,能直接看到子进程眼里 0/1/2 是什么。
|
||||
|
||||
**② 检查 `/dev/pts` 是否可用**
|
||||
|
||||
```
|
||||
adb shell run-as com.doubao.lynxclone sh -c 'ls -l /dev/pts; ls -l /dev/ptmx'
|
||||
```
|
||||
|
||||
**③ 对比"App 进程里"和"run-as 里"的差别**
|
||||
|
||||
`run-as` 的上下文是 `runas_app`,App 真正跑起来是 `untrusted_app_27`。
|
||||
**ptx 相关权限在这两个上下文里可能不一样** —— 这是目前最大的嫌疑。
|
||||
|
||||
## 修的可能方向
|
||||
|
||||
* 如果确认是 `open(从端)` 被 SELinux 拦:需要调整 targetSdk
|
||||
(`untrusted_app_27` 是 targetSdk<=27 的上下文,**28 应该是 `untrusted_app_28`** ——
|
||||
说明我们的 targetSdk 生效值和预期不一致,值得单独查)
|
||||
* 如果确认是 `.so` 版本不配对:换一整套配对好的
|
||||
terminal-emulator Java 源码 + libtermux.so
|
||||
|
||||
## 这一轮的教训(方法论)
|
||||
|
||||
1. **静默的 `catch (Exception e) { // Ignore }` 是排查杀手** ——
|
||||
Termux 这段代码把 fd 读失败悄悄吞了,导致"pty 双向不通"这个现象
|
||||
查了好几轮才浮出水面。**该加日志的地方一定要加。**
|
||||
2. 根因往往比猜的简单:**一直是"子进程标准流没接上 pty"这一件事**,
|
||||
而我在 bash、环境变量、LD_PRELOAD、尺寸、SELinux 上绕了很久。
|
||||
|
||||
|
||||
---
|
||||
|
||||
# 第五轮:反汇编 `createSubprocess`
|
||||
|
||||
装了 `capstone`,写了 `scripts/.tmp-dis2.py`(临时的)把
|
||||
`Java_com_termux_terminal_JNI_createSubprocess`(偏移 0x107c,1673 字节)
|
||||
反汇编出来看。**看得见的部分已经很有价值**:
|
||||
|
||||
## 父进程分支(pty 建立)
|
||||
|
||||
```
|
||||
mov esi, 0x80002 ; O_RDWR | O_CLOEXEC
|
||||
call open ; open("/dev/ptmx", O_RDWR|O_CLOEXEC)
|
||||
|
||||
mov edi, ebx
|
||||
mov esi, 0x5401
|
||||
call ioctl ; TIOCGPTN —— 取 pty 编号
|
||||
|
||||
mov edi, ebx
|
||||
mov esi, 0x5402
|
||||
call ioctl ; TIOCSPTLCK —— 解锁 pty
|
||||
|
||||
mov edi, ebx
|
||||
mov esi, 0x5414
|
||||
call ioctl ; TIOCGPTPEER ★ 直接用 ioctl 拿从端 fd(不是 open(ptsname))
|
||||
```
|
||||
|
||||
**`TIOCGPTPEER` 需要 Linux 4.13+。** 实测模拟器内核是 **5.15.178** ——
|
||||
**支持**,所以这条不是原因。(这一版把它排除了。)
|
||||
|
||||
父进程返回 `fd=92` 说明上面这几步**全都成功了**。
|
||||
|
||||
## 子进程分支(能看到的)
|
||||
|
||||
```
|
||||
call open ; esi=2 → open(<从端路径>, O_RDWR) ← 路径兜底
|
||||
...
|
||||
mov edi, eax / xor esi, esi / call dup2 ; dup2(x, 0) 标准输入
|
||||
mov edi, ebx / mov esi, 1 / call dup2 ; dup2(slave, 1)
|
||||
mov edi, ebx / mov esi, 2 / call dup2 ; dup2(slave, 2)
|
||||
```
|
||||
|
||||
**`dup2` 到 0/1/2 是有的** —— 所以"根本没 dup2"这个猜测也不成立。
|
||||
|
||||
## 卡在哪
|
||||
|
||||
裸地址(`call 0x18e0` 这种)**分不清是 `dup2` / `close` / `execvp`** ——
|
||||
必须把 PLT 名字解析出来。第一次尝试里:
|
||||
|
||||
* `.symtab` 不存在(只有 `.dynsym`)—— 已经处理
|
||||
* **PLT 名表算出来是 0 项** —— `.plt` / `.got.plt` 的基址推算写错了
|
||||
|
||||
**所以下一轮第一件事**:把 `scripts/.tmp-dis2.py` 里 PLT 的算法修对。
|
||||
正确的做法(x86_64):
|
||||
|
||||
```
|
||||
.got.plt 前 3 个槽是保留的(dynamic / link_map / _dl_runtime_resolve)
|
||||
第 n 个 .rela.plt 项(n 从 0 起)对应
|
||||
.got.plt 的 (3 + n) 号槽,也就是 r_offset = got_plt.addr + (3 + n) * 8
|
||||
.plt 的第 (n + 1) 个 stub,地址 = plt.addr + 16 * (n + 1)
|
||||
```
|
||||
(我上一版用 `(r_offset - (gotplt.addr + 24)) / 8` 推 slot,
|
||||
再 `plt.addr + 16 + slot * 16` —— 方向对,但基址可能差一个项,结果是空表。)
|
||||
|
||||
**修对之后要重点看**:
|
||||
1. `close(...)` 出现在哪、关的是不是**从端 fd** ——
|
||||
如果子进程在 `dup2` 之后又 `close` 了 0/1/2,那就是根因
|
||||
2. `execvp` 传的 `argv[0]` 是 `cmd` 还是 `args[0]`
|
||||
3. `TIOCSCTTY` 有没有真的调到(我只看到 0x5401/0x5402/0x5414,
|
||||
**没看到 0x540E = TIOCSCTTY** —— 值得再确认一遍,可能是被截断了)
|
||||
|
||||
## 顺带排除的
|
||||
|
||||
* `TIOCGPTPEER` 不被内核支持 —— **排除**(内核 5.15)
|
||||
* 子进程没做 `dup2` —— **排除**(反汇编里有)
|
||||
|
||||
## 工具
|
||||
|
||||
`scripts/.tmp-dis2.py` 里的 ELF 解析 + capstone 反汇编是可用的,
|
||||
只有 PLT 名字表那一段要修。修好后建议改名成
|
||||
`scripts/dis-termux.py` 留在仓库里 —— 以后查这类问题直接用。
|
||||
649
docs/内置Termux-现状与坑.md
Normal file
649
docs/内置Termux-现状与坑.md
Normal file
@@ -0,0 +1,649 @@
|
||||
# 内置 Termux 的适配 —— 现状与全部踩过的坑
|
||||
|
||||
> 这份文档的作用:**让这件事不依赖任何人的记忆**。
|
||||
> 换一个会话、换一个人接手,从这一页就能继续。
|
||||
|
||||
最后更新:v2.0.34
|
||||
|
||||
---
|
||||
|
||||
## 一句话背景
|
||||
|
||||
App 里内置了 Termux(把它的 bootstrap 解压到应用私有目录,用它的
|
||||
`libtermux.so` 开 pty)。**但 Termux 的所有二进制都是按它自己的包名
|
||||
`com.termux` 编译的**,而我们的包名是 `com.doubao.lynxclone` ——
|
||||
里面写死了一整套绝对路径 `/data/data/com.termux/files/usr/...`。
|
||||
|
||||
**已经修掉的 20 处问题,全都是这一个病根的不同表现。**
|
||||
|
||||
改法归纳起来只有五类:
|
||||
|
||||
| 类型 | 例子 | 管什么 |
|
||||
|---|---|---|
|
||||
| **环境变量** | `SSL_CERT_FILE`、`DPKG_ADMINDIR`、`APT_CONFIG` | 会读环境变量的程序 |
|
||||
| **配置文件** | 生成 `apt.conf` 重设全部 `Dir::` | apt 自己的目录 |
|
||||
| **路径补全** | `PATH` 里加 `/data/data/<包名>/files/usr/bin` | 找不到命令 |
|
||||
| **wrapper** | (v2.0.33 起**已废弃**,见下) | —— |
|
||||
| **沙箱路径** ★ | 在自己 prefix 里把 `/data/data/com.termux/...` 逐目录接出来 | **编译进二进制、谁也拦不住的那些** |
|
||||
| **自编 dpkg** ★★ | 把 dpkg/apt 换成自己编的,从根上解决 | **dpkg 的编译期配置目录** |
|
||||
|
||||
---
|
||||
|
||||
## ★★ v2.0.33:自编 dpkg,和真 Termux 共存
|
||||
|
||||
**这一版解决了之前"从根上无解"的那个冲突。**
|
||||
|
||||
### 之前是什么样
|
||||
|
||||
装了真 Termux 的手机上,`pkg install` 必死:
|
||||
|
||||
```
|
||||
dpkg: error: error opening configuration directory
|
||||
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
|
||||
E: Sub-process .../bin/dpkg returned an error code (2)
|
||||
```
|
||||
|
||||
原因是 dpkg 的**配置目录是编译期常量**,而且它**在解析命令行之前**就去读。
|
||||
`--admindir` 指得再对也没用。真 Termux 的 `/data/data/com.termux` 是 `0700`、
|
||||
属于另一个 UID,我们连穿都穿不进去 —— `ENOENT` dpkg 会静默跳过,`EACCES` 直接死。
|
||||
|
||||
试过并**全部失败**的路子(细节见 `android/termux-dpkg/README.md`):
|
||||
`--root` / `DPKG_ROOT` / `LD_PRELOAD=libtermux-exec.so` / prefix 内软链 /
|
||||
在 `/data/data` 下建软链 / `unshare -m` / 直接改二进制(长度不等)。
|
||||
|
||||
### 现在怎么做
|
||||
|
||||
用 NDK 自己编一份 dpkg,把那一处换成**从 `/proc/self/exe` 反推前缀**,
|
||||
于是同一个二进制在任何包名下都指向自己所在的前缀。顺带修了三件事:
|
||||
|
||||
- **架构名**改用 Termux 的写法(`x86_64` / `aarch64`)。用 Debian 的
|
||||
`amd64`/`arm64` 会让 dpkg 把数据库里**每一个包**都判成非法架构。
|
||||
- **PATH**:apt 派生 dpkg 时会塞给它一个指向真 Termux 的 PATH,
|
||||
自编版按自己的前缀修回来。
|
||||
- **维护脚本的 shebang 和正文路径**:Termux 包里整篇是
|
||||
`#!/data/data/com.termux/files/usr/bin/sh` +
|
||||
`mkdir -p "/data/data/com.termux/files/usr/var/empty"`,
|
||||
前者被内核解析(落在别的 App 私有目录 → EACCES,
|
||||
而 dpkg 显示成"脚本没有执行权限",**指错方向**),
|
||||
后者是根下绝对路径、沙箱软链拦不住。自编版在 exec 前全部换掉。
|
||||
|
||||
**构建配方 + 校验脚本在 [`android/termux-dpkg/`](../android/termux-dpkg/README.md)。**
|
||||
|
||||
### 实测(Android 14 x86_64,**真 Termux 同时装着**)
|
||||
|
||||
```
|
||||
$ pkg install -y openssh
|
||||
...
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
|
||||
$ dpkg -l | grep -c '^i[^i]' → 0(无未配置项)
|
||||
$ ssh -V → OpenSSH_10.6p1
|
||||
```
|
||||
|
||||
还验过 `nmap`、`git 2.56.0` 全新安装,全部 `未配置 = 0`。
|
||||
|
||||
### 因此删掉的东西
|
||||
|
||||
`bin/dpkg` 不再是 wrapper 脚本,`bin/dpkg.real` 也不需要了 ——
|
||||
wrapper 本来就是在绕"配置目录编译死"这个已经修掉的问题。
|
||||
自编 dpkg 是从 `lib/<abi>/libdoubao-dpkg.so`(其实是个 tar 包)解出来的。
|
||||
|
||||
---
|
||||
|
||||
## 当前状态(v2.0.33)
|
||||
|
||||
| 功能 | 状态 |
|
||||
|---|---|
|
||||
| 真终端(pty + ANSI) | ✅ 可用 |
|
||||
| 换源(清华/中科大/阿里/北外/官方) | ✅ 可用 |
|
||||
| `pkg update` / `pkg upgrade` | ✅ 可用 |
|
||||
| **`pkg install python` 端到端** | ✅ **可用**(模拟器上实测) |
|
||||
| **和真 Termux 共存** | ✅ **可用**(v2.0.33 起,自编 dpkg) |
|
||||
| python / pip / clang / glib / llvm | ✅ 全部 `Setting up` 成功,`dpkg -l` 无未配置项 |
|
||||
| `pip install <包>` | ✅ 可用(实测装了 six) |
|
||||
| 「重置环境」按钮 | ✅ 可用 |
|
||||
|
||||
实测记录(Android 14 x86_64 模拟器,全新重置后):
|
||||
|
||||
```
|
||||
$ apt-get install -y python
|
||||
Setting up python (3.14.6-1) ...
|
||||
Setting up python-pip (26.2.1) ...
|
||||
Writing to /data/user/0/com.doubao.lynxclone/files/usr/etc/pip.conf
|
||||
Setting up libllvm (21.1.8-3) ...
|
||||
Setting up glib (2.90.1) ...
|
||||
Setting up clang (21.1.8-3) ...
|
||||
|
||||
$ python -V → Python 3.14.6
|
||||
$ pip --version → pip 26.2.1 from .../lib/python3.14/site-packages/pip
|
||||
$ pip install six → six 1.17.0 OK
|
||||
$ dpkg -l | grep -v ^ii → (空,全部配置完成)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ★★ v2.0.34:用户反馈单里的三条
|
||||
|
||||
### ① PYTHONPATH 把 3.13 的 .imy 硬塞给 3.14(致命)
|
||||
|
||||
```
|
||||
Fatal Python error: Failed to import encodings module
|
||||
zipimport.ZipImportError: module load failed: bad magic number
|
||||
in 'encodings': b'\xf3\r\r\n'
|
||||
```
|
||||
|
||||
**根因**:App 自己跑着一个 Chaquopy 的 CPython 3.13,它为了让自己的解释器
|
||||
找到标准库,在**进程环境里**设了 `PYTHONPATH` 指向 `files/chaquopy/*.imy`。
|
||||
而 `ProcessBuilder` / `TerminalSession` 起的都是子进程,**继承整个 App 进程
|
||||
的环境** —— 于是 Termux 里 apt 装的 python 3.14 一启动就读到 3.13 编的
|
||||
`encodings`,魔数不符(`0x0df3` vs `0x0df4`),解释器初始化直接崩。
|
||||
|
||||
**怎么验证的**(反馈单里用户自己就查对了):
|
||||
```
|
||||
$ grep -r PYTHONPATH $PREFIX/etc/ → 空(Termux 自己没设)
|
||||
$ tr '\0' '\n' < /proc/self/environ | grep PYTHONPATH → 有(父进程灌的)
|
||||
$ PYTHONPATH=…/stdlib-common.imy python3 -c 'import encodings'
|
||||
→ 一字不差复现崩溃
|
||||
```
|
||||
|
||||
**修法**:`TermuxInstaller.childEnvMap()` —— **以父环境为底**(保住
|
||||
`ANDROID_ROOT` 之类系统变量)、覆盖上 Termux 那一套、再摘掉
|
||||
`PYTHONPATH` / `PYTHONHOME` / `PYTHONSTARTUP` 等宿主 Python 变量。
|
||||
|
||||
★ 只摘子进程的,**不动 App 自己的** —— Chaquopy 那个解释器*需要*
|
||||
`PYTHONPATH` 才能找标准库,全局清掉会把内核搞死。
|
||||
|
||||
★ 所有起子进程的地方都要用它:`TermuxShell.run`、`TermuxTerminal`、
|
||||
`TermuxMirror` 的探测。注意 `environment().putAll(...)` 是**追加**,
|
||||
删不掉已有的键 —— 只 putAll 是修不掉这个 bug 的。
|
||||
|
||||
### ② pip 用不了 —— `rewritePrefixes` 的替换顺序错了
|
||||
|
||||
`pip3` 的 shebang 是 `#!/data/data/com.termux/files/usr/bin/python3.14`,
|
||||
而改写只做了 `oldData → dataDir`,产出
|
||||
|
||||
```
|
||||
#!/data/<包名>/files/files/usr/bin/python3.14 ← 多一层 files,解析不了
|
||||
#!<prefix>/bin/python3.14 ← 正确
|
||||
```
|
||||
|
||||
**为什么多一层就解析不了**:沙箱里 `files/home` 那条链只兜住了 home,
|
||||
`<pkg>/files/files/usr/...` 里的第二个 `files` 是 `<pkg>/files` 下一个
|
||||
**不存在的目录**(实测 `No such file or directory` / `Permission denied`)。
|
||||
|
||||
**修法**:**先换长路径再换短的** ——
|
||||
`/data/data/com.termux/files/usr` → `<prefix>`,然后才 `…/com.termux` → `dataDir`。
|
||||
维护脚本那支同样处理。STAMP 25→26→27,老设备进一次终端自动补跑。
|
||||
|
||||
### ③ `/tmp` 不可写 —— 只能部分修好,如实说明
|
||||
|
||||
`/tmp` 在 **root 下根本不存在**,而 root 是**只读**的:
|
||||
|
||||
```
|
||||
$ mkdir /tmp → Read-only file system
|
||||
$ ln -s … /tmp → Read-only file system
|
||||
```
|
||||
|
||||
`libtermux-exec.so` **只改写 Termux 自己那个前缀**,不管 `/tmp`
|
||||
(实测 `touch /tmp/x` 仍然失败)。`--instdir` 那条沙箱路也拦不住 ——
|
||||
内核解析的是根下的绝对路径。在 `/data/data` 下建 `com.termux` 软链也不行
|
||||
(`drwxrwx--x system system`,应用写不了)。
|
||||
|
||||
**能做的已经做了**:`TMPDIR` 一直是对的,实测**尊重 `TMPDIR` 的工具全部正常**:
|
||||
|
||||
```
|
||||
$ mktemp → <prefix>/tmp/tmp.XXXX
|
||||
$ python -c 'tempfile…' → <prefix>/tmp
|
||||
```
|
||||
|
||||
所以只有"把 `/tmp` 写死在代码里"的程序会受影响。这是 Android 的限制,
|
||||
不是能绕的技术问题。
|
||||
|
||||
### ④ 镜像同步中会把用户卡死 —— 加自动换源
|
||||
|
||||
用户卡住的那条报错其实是**清华镜像正在同步**:
|
||||
|
||||
```
|
||||
E: Failed to fetch …/Packages.bz2
|
||||
File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
```
|
||||
|
||||
实测各镜像健康度(Release 声明值 vs 实际下载值):
|
||||
|
||||
| 镜像 | 结果 |
|
||||
|---|---|
|
||||
| 清华 TUNA | 586556 vs **583395** ✗ |
|
||||
| 中科大 USTC | 585742 vs 585742 ✓ |
|
||||
| 北外 BFSU | 590396 vs 590396 ✓ |
|
||||
| 官方源 | 584437 vs 584437 ✓ |
|
||||
|
||||
而我们默认给的就是清华 —— 任何单一默认值都会偶尔把所有人卡在同一个坏源上。
|
||||
|
||||
`TermuxMirror.autoPickIfBroken()`:后台**真跑一次 `apt-get update`** 当探测
|
||||
(不自己写校验 —— apt 比我们严,而且换源后本来就要 update),
|
||||
探测失败就按源列表往下试,成功则记住并记日志。当前源能用就一个字都不改。
|
||||
|
||||
### ⑤ 附件不告知路径 —— 两端都修了
|
||||
|
||||
- 每条附件消息都带 `本地路径:<绝对路径>`(**三条分支**都要带 ——
|
||||
以前只有二进制那条带,而*恰恰是文本最需要*:超 20000 字符会截断)
|
||||
- 落盘命名从 base36 乱码换成可读的 `20260101-120000_原名.ext`,重名加 `-1`
|
||||
- 系统提示词加了两条告诉模型"那个路径是真的、可以用 shell 打开"
|
||||
- ★ **Node 版(server/src/uploads.mjs、config.mjs)也要跟上** ——
|
||||
两份实现,改一份就是"引擎改了另一端没跟上"。
|
||||
`scripts/verify-uploads-parity.py` 守这个一致性
|
||||
|
||||
---
|
||||
|
||||
### 已知的残留噪音
|
||||
|
||||
`bin/bash` 和 `bin/dash` 里还有少量编译死的 `com.termux` 路径
|
||||
(`bin/bash` 13 处)。原因是 `rewritePrefixes` 用"前 8192 字节里有 NUL
|
||||
就跳过"来避开二进制 —— 这对"长度不等"的替换是对的(改了会崩),
|
||||
但它让这些常量留了下来。表现是 **每开一个终端会打印一次**:
|
||||
|
||||
```
|
||||
bash: /data/data/com.termux/files/usr/etc/bash.bashrc: Permission denied
|
||||
```
|
||||
|
||||
**不影响功能**(终端照常可用、`pkg install` 照常跑),只是难看。
|
||||
它读的是真 Termux 的 `bash.bashrc`,读不到就跳过。
|
||||
|
||||
> 为什么不在 `/data/data` 下建个 `com.termux` 软链一劳永逸:
|
||||
> `/data/data` 是 `drwxrwx--x system system`,应用建不了东西(实测 EACCES)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 20 处问题清单(按发现顺序)
|
||||
|
||||
| # | 现象 | 根因 | 修法 |
|
||||
|---|---|---|---|
|
||||
| 1 | 终端一闪就退,退出码 0 | `libtermux.so` 里 **`args[0]` 就是 `argv[0]`**,我传的第一个元素是 `--rcfile`,bash 把 rc 当脚本跑了一遍 | `args[0]` 传 shell 路径本身 |
|
||||
| 2 | pty 通了、bash 活着,但屏幕不刷新 | `TerminalSessionClient.onTextChanged` 是**空实现** | 接到 `TerminalView.onScreenUpdated()` |
|
||||
| 3 | 命令敲得进去、回车没反应 | ENTER 发 `\n`(LF),终端要 `\r`(CR);且键位被滚出屏幕 | 改 CR + 移到第一位 |
|
||||
| 4 | `pkg update` 把几十个镜像全测成 bad | **pkg 不看 `sources.list`**,它认 `etc/termux/chosen_mirrors` | 建符号链接指到 `mirrors/chinese_mainland/<主机名>` |
|
||||
| 5 | 所有 HTTPS 全挂 | `curl`/`apt` 里编译死了证书路径 `/data/data/com.termux/.../cert.pem` | `SSL_CERT_FILE`/`CURL_CA_BUNDLE` + `Acquire::https::CaInfo` |
|
||||
| 6 | `Unable to determine a suitable packaging system type` | apt 读不到 `apt.conf.d`(编译死) | 生成 `apt.conf` + `APT_CONFIG` |
|
||||
| 7 | `method driver .../methods/https could not be found`<br>`Couldn't create temporary file .../usr/tmp/...` | `Dir::Bin::*`、`Dir::Temp` 也是编译死的 | 逐个写进 apt.conf |
|
||||
| 8 | `NO_PUBKEY 5A897D96E57CF20C` | `trusted.gpg.d/` 里全是**断掉的符号链接**(指向老包名) | `fixBrokenSymlinks()` 扫出来重建 |
|
||||
| 9 | `cannot create the dpkg database directory /data/data/com.termux/...` | dpkg 的 admindir 编译死 | `DPKG_ADMINDIR` |
|
||||
| 10 | `6 expected programs not found in PATH` | **apt 派生 dpkg 时清洗了环境**,PATH 没传进去。(直接跑 dpkg 一切正常 —— 这是关键线索) | **给 dpkg 套 wrapper**:补全环境再 exec 真身 |
|
||||
| 11 | `error creating directory './data/data/com.termux'` | dpkg 的 **instdir** 编译死 | `--instdir` |
|
||||
| 12 | `failed to chroot to ...: Operation not permitted` | Android 应用没有 `CAP_SYS_CHROOT` | `--force-script-chrootless` |
|
||||
| 13 | `unable to execute .../openssh.postinst: No such file or directory` | 安装脚本的 shebang 指向老包名;`var/lib/dpkg/info/` 不在改写列表里 | 加进改写目录 |
|
||||
| 14 | **`error opening configuration directory '/data/data/com.termux/.../dpkg.cfg.d': Permission denied`** | **用户手机上装了真 Termux** —— 那个私有目录**存在但读不了**(所以是 Permission denied 不是 No such file)。我的模拟器上没装真 Termux,所以复现不出来 | 见第 15 条 —— `--root` 只是掩盖,**不是修法** |
|
||||
| 15 | 和 14 同一条报错,但**根因终于挖到底了** | dpkg 读配置的路径是 `<chroot 根>/<编译死的 DPKG_CONFDIR>`,**跟 admindir 无关**。`--root=$PREFIX` 只是把它平移到 `$PREFIX/data/data/com.termux/...`,那里没人建目录 → 照样报错 | ★★ **在沙箱里把那条路造出来**:`$PREFIX/data/data/com.termux → ../../usr`(软链)。见下 |
|
||||
|
||||
### 第 15 条:那个"想要但没做到"的正解 —— 以及它为什么做不到
|
||||
|
||||
想的是最直接的办法:**把 ELF 里写死的字节改掉**。既然
|
||||
`/data/data/com.termux` 到处都是,换成我们的包名不就行了?
|
||||
|
||||
**写了 `scripts/verify-elf-patch.py`,拿真机上拉下来的二进制验,结论是:**
|
||||
|
||||
| 检查 | 结果 |
|
||||
|---|---|
|
||||
| 31 处匹配是不是干净的完整 C 字符串<br>(前面是 `\0`/引号,后面紧跟 `/`) | ✅ **31/31 全是**,可以无条件安全替换 |
|
||||
| 长度能不能原地替换 | ❌ **不行** |
|
||||
|
||||
```
|
||||
/data/data/com.termux = 21 字节
|
||||
/data/data/com.doubao.lynxclone = 30 字节 ← 差 9
|
||||
```
|
||||
|
||||
原地替换**不能改长度**(后面所有数据的偏移会全错),而 `.rodata` 里的
|
||||
字符串是**紧挨着**的,没有 9 字节空隙。
|
||||
|
||||
> (我第一版把这个包名数成了 21 —— 少了 9 个字。
|
||||
> 是那个验证脚本在编译前把它抓出来的。**先验证再写实现**省了一轮。)
|
||||
|
||||
**换正解:不碰二进制,靠沙箱路径。** 见第 17 条(那一条把 15/16 两轮的
|
||||
绕路都收了口)。
|
||||
|
||||
### ★★★ 第 16 条:补刀脚本拿 sed 改二进制,一次写坏 85 个
|
||||
|
||||
给 dpkg 套的 wrapper 里,装完包会跑一个补刀脚本
|
||||
(`res/raw/doubao_patch.sh`),把新装包里的硬编码路径改掉。
|
||||
第一版写的是:
|
||||
|
||||
```sh
|
||||
grep -rla "$OLD" "$P/bin" "$P/lib" "$P/libexec" | while read f; do
|
||||
sed -i "s|$OLD|$NEW|g" "$f" # ← 灾难
|
||||
done
|
||||
```
|
||||
|
||||
`-a` 把**二进制**也当文本处理了,于是 85 个 ELF 被 `sed` 重写。
|
||||
`dpkg.real` 直接变成:
|
||||
|
||||
```
|
||||
CANNOT LINK EXECUTABLE .../dpkg.real: empty/missing DT_HASH/DT_GNU_HASH
|
||||
in ".../dpkg.real" (new hash type from the future?)
|
||||
```
|
||||
|
||||
**为什么必然坏:`20 → 30`,长度不等**(就是上面第 15 条那个结论)。
|
||||
`sed` 改了文件长度,ELF 里所有内部偏移全废。
|
||||
|
||||
**我转头就在补刀脚本里犯了同一个错** —— 明明刚用脚本验证过
|
||||
"长度不等所以不能改二进制"。教训:**结论要落到每一处代码,
|
||||
不能只落在当时正在改的那一处。**
|
||||
|
||||
修法:过滤用"**含 NUL 就跳过**",并且**绝不改自己**(否则第一刀就把过滤条件
|
||||
改掉了,第二刀起又退化成"见到二进制就 sed")。现在这段逻辑在 python 里
|
||||
(一行 `b"\0" in data[:8192]`),比 shell 两道手工拦更不容易漏。
|
||||
|
||||
> 那个"文本/二进制"的判断是本仓库最容易改错的地方。
|
||||
> `scripts/verify-patch-script.py` 专门盯着它。
|
||||
|
||||
### ★★★ 第 17 条:正解是"沙箱路径",而且**绝不能给 dpkg 传 `--root`**
|
||||
|
||||
这一条是收口,也是我绕得最久的一条。三个关键结论:
|
||||
|
||||
#### ① `--root` 会让包装到**影子目录**里
|
||||
|
||||
`--root=$PREFIX` 看着能解决"编译死的绝对路径",但它会把**每一个**路径
|
||||
前面拼上 root —— **包括 `.deb` 文件清单里的安装路径**。于是:
|
||||
|
||||
```
|
||||
清单里写的是 /data/data/com.termux/files/usr/bin/hello
|
||||
加了 --root <prefix>/data/data/com.termux/files/usr/bin/hello ← 影子目录
|
||||
应该是 <prefix>/bin/hello
|
||||
```
|
||||
|
||||
**而且 apt 照样报 `Setting up hello ... 成功`** —— 静悄悄地装错地方。
|
||||
(这个只有把 hello 真装一遍、再去 `find` 它才看得出来。)
|
||||
|
||||
正确参数是:
|
||||
|
||||
```
|
||||
dpkg.real --instdir=/ --force-script-chrootless "$@"
|
||||
```
|
||||
|
||||
`--instdir=/` 让 dpkg 按清单里的**原路径**安装,于是它要写的就是那个
|
||||
`/data/data/com.termux/...`。剩下的事由 ② 解决。
|
||||
|
||||
#### ② 在 prefix 里把那条路**逐目录**接出来
|
||||
|
||||
```
|
||||
<prefix>/data/data/com.termux/files/usr/bin → <prefix>/bin
|
||||
<prefix>/data/data/com.termux/files/usr/etc → <prefix>/etc
|
||||
<prefix>/data/data/com.termux/etc/dpkg → <prefix>/etc/dpkg
|
||||
<prefix>/data/data/com.termux/var/lib/dpkg → <prefix>/var/lib/dpkg
|
||||
……(共 20 条,见 linkLegacyPrefix())
|
||||
```
|
||||
|
||||
为什么必须逐目录:路径有两种形状 ——
|
||||
`…/com.termux/files/usr/<X>`(来自 .deb 清单)和
|
||||
`…/com.termux/<Y>`(来自二进制里编译死的常量)。
|
||||
**没法用"把 `com.termux` 整个链到某处"一次解决**:
|
||||
|
||||
* 链到 `<prefix>` → 形状 A 变成 `<prefix>/files/usr/…`(多一层)
|
||||
* 链到 `<prefix>/..` → 形状 A 对,形状 B 变成 `<prefix>/..`(少一层)
|
||||
|
||||
我在这上面来回错了**三次**,每次都"看起来很有道理"。
|
||||
|
||||
#### ③ 维护脚本的 shebang 要指向 **Termux 自己的 bash**
|
||||
|
||||
Termux 的 `xxx.postinst` 写的是 `#!/bin/sh`,但正文里全是 bash 语法
|
||||
(`[[ ]]`、`(( ))`)。在我们这儿 `#!/bin/sh` 落到 **Android 的玩具箱 sh**
|
||||
(纯 POSIX),于是:
|
||||
|
||||
```
|
||||
python.postinst[3]: syntax error: expression expected '(('
|
||||
dpkg: error processing package python (--configure):
|
||||
installed python package post-installation script subprocess returned error exit status 1
|
||||
```
|
||||
|
||||
—— 而且**文件其实已经装好了**(`python -V` 都能跑)。表现是
|
||||
`dpkg -l` 显示 `iF`/`iU`、pip 装不上、依赖它的 glib/clang 全跟着起不来。
|
||||
|
||||
**★ 但只对维护脚本这么做。** 对 `bin/` 下的东西一律只做**路径替换** ——
|
||||
因为 `bin/pip` 是个 **Python 脚本**,改成 bash 就毁了:
|
||||
|
||||
```
|
||||
bin/pip: line 2: import: command not found
|
||||
```
|
||||
|
||||
规则一句话:**维护脚本要 bash,其他脚本只换路径、别动解释器。**
|
||||
|
||||
### ★★★ 第 18 条:补刀必须跑**两次**(unpack 后 + 全部结束后)
|
||||
|
||||
`python-pip.postinst` 第 3 行会**执行刚装进来的 `bin/pip`**。
|
||||
而 pip 的 shebang 原本是
|
||||
|
||||
```
|
||||
#!/data/data/com.termux/files/usr/bin/python3.14 ← 绝对路径,不存在
|
||||
```
|
||||
|
||||
报错是:
|
||||
|
||||
```
|
||||
python-pip.postinst: line 3: .../bin/pip: cannot execute: required file not found
|
||||
```
|
||||
|
||||
**★ 这句 `required file not found` 指的**不是 pip 本身**,而是它 shebang 里
|
||||
那个解释器** —— 报错完全没提这件事,极容易查错方向(会以为 pip 没装上)。
|
||||
|
||||
而 `.deb` 里的文件是在 **unpack** 阶段落盘的,configure 在**之后**。
|
||||
所以补刀要在 unpack 之后立刻跑一次:
|
||||
|
||||
```sh
|
||||
case " $* " in *" --unpack "*|*" --install "*|*" -i "*) PATCH_UNPACK=1 ;; esac
|
||||
"$P/bin/dpkg.real" --instdir=/ --force-script-chrootless "$@"
|
||||
[ "$PATCH_UNPACK" = 1 ] && sh "$P/bin/doubao-patch" shebang
|
||||
sh "$P/bin/doubao-patch" # 收尾再补一次(含正文路径)
|
||||
```
|
||||
|
||||
### ★★★ 第 19 条:`LD_LIBRARY_PATH` 少了会让补刀**静默失效**
|
||||
|
||||
Termux 的二进制靠 `libandroid-support.so` 之类活,而动态链接只认
|
||||
`LD_LIBRARY_PATH`(没编 RPATH)。少了它连 `bin/python3` 都起不来:
|
||||
|
||||
```
|
||||
CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
|
||||
not found: needed by main executable
|
||||
```
|
||||
|
||||
**可怕的是它静默**:补刀脚本第一件事是 `[ -x "$PY" ]`,python 起不来
|
||||
→ 整个补刀什么都不做、**也不报错**。表现是"shebang 没修好"而日志里
|
||||
一个字都没有,查了好几轮。修法:wrapper **和**补刀脚本**各自** export 一次。
|
||||
|
||||
### ★★★ 第 20 条:`NEW` 常量取错,表现却像"工具坏了"
|
||||
|
||||
补刀脚本要用文本替换把写死的路径改掉:`OLD → NEW`。
|
||||
我为一个常量的取值错了**两轮**,而两次的症状都**完全像工具 bug**
|
||||
(稳定多出一段路径、与输入无关):
|
||||
|
||||
```
|
||||
输入 #!/data/data/com.termux/files/usr/bin/python3.14
|
||||
错误 #!/data/user/0/<包名>/files/files/usr/bin/python3.14 ← 多一个 /files
|
||||
```
|
||||
|
||||
于是我依次怀疑并**换掉了三个工具**:`bytes.replace` → 玩具箱的
|
||||
`${var//a/b}` → `sed -i`。**三个全是清白的。**
|
||||
|
||||
拆穿它的是一个和本项目毫无关系的中性实验:
|
||||
|
||||
```python
|
||||
>>> b"/data/data/com.termux/files/usr".replace(
|
||||
... b"/data/data/com.termux", b"/data/user/0/pkg/files")
|
||||
b'/data/user/0/pkg/files/files/usr'
|
||||
```
|
||||
|
||||
**数学上完全正确** —— 两个 `files` 是两个常量各自带来的,一个来自
|
||||
`NEW` 的尾巴、一个来自原文的 `/files/usr`。
|
||||
|
||||
最终确定的取值(**两处 OLD 不一样,这是最容易绕晕的一点**):
|
||||
|
||||
| 用在哪 | OLD | NEW | 换出来 |
|
||||
|---|---|---|---|
|
||||
| 补刀脚本(改 shebang) | `/data/data/com.termux/files/usr` | `<prefix>` | `#!<prefix>/bin/python3.14` ✅ |
|
||||
| `rewritePrefixes`(改正文) | `/data/data/com.termux` | `<pkg>/files` | `<pkg>/files/files/usr/…`,由沙箱里 `"files" to ".."` 那条链接住 ✅ |
|
||||
|
||||
> **教训:「工具坏了」的时候,先怀疑自己的常量。**
|
||||
> 常量错的表现(稳定复现、与输入无关)恰恰是工具 bug 的特征 ——
|
||||
> 这就是它骗过我的原因。
|
||||
> `scripts/verify-patch-script.py` 现在把这两个取值都钉住了。
|
||||
|
||||
---
|
||||
|
||||
## 改过的地方(代码位置)
|
||||
|
||||
| 文件 | 改了什么 |
|
||||
|---|---|
|
||||
| `termux/TermuxInstaller.kt` | 主战场:路径改写、apt.conf、dpkg wrapper、断链修复、沙箱路径、重置、环境变量 |
|
||||
| `res/raw/doubao_patch.sh` | dpkg 装完包后的补刀脚本(**模板**,App 启动时替换占位符后写进 prefix) |
|
||||
| `res/raw/dpkg_wrapper.sh` | dpkg wrapper 的**模板**(理由见下) |
|
||||
| `termux/TermuxMirror.kt` | 换源(同时写 `sources.list` 和 `chosen_mirrors`) |
|
||||
| `termux/TermuxTerminal.kt` | 起 shell 的候选列表、秒退回退、view 引用(刷屏) |
|
||||
| `ui/TerminalScreen.kt` | 终端界面、源按钮、重置按钮、ENTER 键位 |
|
||||
| `ui/MirrorScreen.kt` | 换源界面 |
|
||||
| `termux/terminal/TerminalSession.java` | 给被静默吞掉的异常加日志(**关键**,见下) |
|
||||
|
||||
### 为什么两个脚本放在 `res/raw/` 而不是写成 Kotlin 字符串
|
||||
|
||||
**Kotlin 的原始字符串(`"""`)也照样做 `$` 插值。**
|
||||
|
||||
shell 脚本里 `$P` `$OLD` `$f` 到处都是,写在 Kotlin 里就编译报
|
||||
`Unresolved reference: P` —— **而这个报错看着像"脚本写错了",
|
||||
其实是语言层的事**,白找半天。写成 `${'$'}P` 能过,但正文没法读了
|
||||
(几十处),而且下一个改脚本的人一定会再踩一遍。
|
||||
|
||||
> 这个坑我连着踩了两次(同一轮里),所以单独立一节。
|
||||
>
|
||||
> ★ 还有一个**同族**的坑,更阴:Kotlin 的块注释**可以嵌套**,
|
||||
> 注释正文里写一个"斜杠星号"就会开一层新的嵌套,于是原本用来收尾的
|
||||
> "星号斜杠"只关掉嵌套层,**外层一直开着,把后面所有代码全吞掉**。
|
||||
> 表现是一堆莫名其妙的 `Unresolved reference`(报在后面的函数上)。
|
||||
> 我在 `ensureCaBundle` 的注释里写了 `cat /system/.../*` 就中了这一枪。
|
||||
> 查法:`scripts/.tmp-brace.py` 那类"数块注释配对"的小脚本。
|
||||
放进 `res/raw/` 之后:正文**原样**,注入点显式(`@PREFIX@`),
|
||||
不用碰任何构建脚本(`.sh` 是原样打包的,不像 `.java`/`.kt` 会被排除)。
|
||||
|
||||
> 这个坑我连着踩了两次(同一轮里),所以单独立一节。
|
||||
|
||||
### 一个方法论教训
|
||||
|
||||
`TerminalSession` 里原来有:
|
||||
|
||||
```java
|
||||
} catch (Exception e) {
|
||||
// Ignore, just shutting down. ← 就是这一行
|
||||
}
|
||||
```
|
||||
|
||||
**它把 `read failed: EIO` 吞了**,导致"pty 双向不通"这个现象查了好几轮
|
||||
才浮出水面。**静默的 catch 是排查杀手。**
|
||||
|
||||
---
|
||||
|
||||
## 排查用的工具
|
||||
|
||||
* `scripts/dis-termux.py` —— ELF 解析 + capstone 反汇编
|
||||
(第一次靠它看到 `.so` 里用 `TIOCGPTPEER`、`execvp(cmd, argv)`)
|
||||
* **`scripts/verify-elf-patch.py` ★** —— 验证"能不能原地改二进制里的
|
||||
硬编码路径"。拿**真机上拉下来的二进制**跑,逐字节检查:
|
||||
匹配是不是完整 C 字符串、前后边界对不对、**长度够不够**。
|
||||
→ 就是它推翻了"改字节"那条路(差 9 字节),省了一轮白编译。
|
||||
```bash
|
||||
# 先拉几个真二进制下来
|
||||
adb shell run-as com.doubao.lynxclone sh -c 'base64 files/usr/bin/curl' > curl.b64
|
||||
python scripts/verify-elf-patch.py
|
||||
```
|
||||
* `files/termux-install.log` —— App 落盘的安装/会话日志
|
||||
(真机上 OEM 会吞 Logcat,只能落盘)
|
||||
* `files/usr/var/log/doubao-patch.log` —— 装完包补刀的记录
|
||||
(看它就知道 `pkg install` 之后有没有把新包的脚本改过来)
|
||||
* **`scripts/verify-patch-script.py` ★** —— 盯住补刀脚本的几条硬性质:
|
||||
文本/二进制过滤、两个 `OLD` 的取值、`--root` 必须**不**在、
|
||||
维护脚本的 shebang、占位符两边对得上。**这条脚本是用真实事故换来的**
|
||||
(`-a`/`-I` 一个字母 → 85 个二进制报废)。
|
||||
* **`scripts/verify-sandbox-paths.py` ★** —— 把 `linkLegacyPrefix()` 里那张
|
||||
接通表**解析出来**,逐条检查形状,并对照"二进制里实际写死、且会被读的
|
||||
路径"清单(`etc/dpkg`、`etc/apt/apt.conf.d`、`etc/tls`、`share/`……)。
|
||||
加一条路径忘了改这里,它会报出来。
|
||||
* **直接读源码**:`termux.c` 在 GitHub 上,网络通的时候一眼就看到
|
||||
`argv[i] = strdup(args[i])` —— 比反汇编快得多
|
||||
|
||||
### 方法论:先验证,再实现
|
||||
|
||||
两个例子,一个省了一轮、一个白饶了三轮:
|
||||
|
||||
* **省的**:第 15 条那条路(改字节)**在写实现之前先用真数据验证了一遍**,
|
||||
才发现"长度差 9 字节"这个致命前提是错的。直接写完再发版的话,
|
||||
用户装上去还是同样的报错,而我会以为"改了怎么还不行"。
|
||||
* **饶的**:第 20 条那个 `NEW` 常量。我在**没有先做一个中性实验**的情况下,
|
||||
就断定"工具坏了",连换三个实现。**一行 `bytes.replace` 的中性测试
|
||||
就能省掉那三轮。**
|
||||
|
||||
一句话:**先做一个和本项目无关的最小实验**,再决定要不要怀疑工具。
|
||||
|
||||
**凡是"我以为我能……"的假设,先写个脚本用真实数据验一遍。**
|
||||
这个脚本后来还留在仓库里(`verify-elf-patch.py`),下次有人想重走这条路,
|
||||
跑一下就知道为什么不行。
|
||||
|
||||
### 方法论:遇到"某个库行为诡异"
|
||||
|
||||
**先读它的源码或反汇编它,别在现象层面试。**
|
||||
我在 bash / 环境变量 / `LD_PRELOAD` / pty 尺寸 / SELinux 上绕了四轮,
|
||||
全是死路;真相就在 `termux.c` 的一行里。
|
||||
|
||||
---
|
||||
|
||||
## "被冤枉"的机制
|
||||
|
||||
排查过程中这几样都背过锅,最后都证明**是清白的**:
|
||||
|
||||
* **`LD_PRELOAD=libtermux-exec.so`** —— 替第 1 条背了锅。它改写的是它认识的
|
||||
那些路径,apt 的 `Dir::` / dpkg 的 `sysconfdir` 都不在里面(实测带不带一样)。
|
||||
(但它对**运行时装好的包**是有用的,环境变量里保留着。)
|
||||
* **`SSL_CERT_FILE` / `CURL_CA_BUNDLE`** —— 只管 **curl**;
|
||||
apt 走自己的 GnuTLS method,得用 `Acquire::https::CaInfo`。
|
||||
* **`bytes.replace` / 玩具箱的 `${var//a/b}` / `sed -i`** —— 第 20 条里
|
||||
我因为一个常量取错,把这三个全换了一遍。它们**一点问题都没有**。
|
||||
|
||||
---
|
||||
|
||||
## 开发流程上踩的坑
|
||||
|
||||
**`node scripts/build-apk.mjs --skip-build` 只拷贝已有 APK,不编译。**
|
||||
|
||||
我用它跑了好几轮,Kotlin 改动根本没进包 —— 白费了三轮。
|
||||
(用户一句"你没编译吧"点破。)
|
||||
|
||||
**以后:改完 Kotlin 一律
|
||||
`node scripts/build-apk.mjs`(不带 `--skip-build`)**,
|
||||
并用 `aapt2 dump badging` 确认 `versionCode`、用文件时间确认是新的。
|
||||
|
||||
**改 Kotlin 用 `edit` 工具一次一处,改完立刻编译。**
|
||||
不要写 PowerShell/Python 按行号剪贴的脚本 —— 这个坑在 `AGENTS.md`
|
||||
里早写了,我还是踩了三次(`key()` 包错、误删 `tryNextCandidate`、
|
||||
死循环把 `meeting.py` 写炸)。
|
||||
|
||||
---
|
||||
|
||||
## 下一步(如果有人接着做)
|
||||
|
||||
1. **在装了真 Termux 的手机上再验一遍**。模拟器(Android 14 x86_64)上
|
||||
`pkg install python` 已经端到端跑通,但**模拟器没装真 Termux**,
|
||||
`/data/data/com.termux` 那个目录的"存在但读不了"情形复现不出来
|
||||
(那正是第 14 条报 `Permission denied` 的原因)。
|
||||
按现在的设计(一个字节都不碰真 Termux 的目录)应该不受影响,
|
||||
但**没验过就是没验过**。
|
||||
2. 已知小尾巴:dpkg 给 maintainer script 一个固定的 `PATH`,
|
||||
脚本里调 `ssh-keygen` 这类命令会 `not found`。
|
||||
可以在 wrapper 里处理,或用 `DPKG_MAINTSCRIPT_*` 系列变量。
|
||||
3. **加新东西的时候,先跑这三个脚本**:
|
||||
```bash
|
||||
python scripts/verify-patch-script.py # 补刀脚本那几条硬性质
|
||||
python scripts/verify-sandbox-paths.py # 沙箱接通表
|
||||
python scripts/verify-elf-patch.py # 还想改二进制?先看它
|
||||
```
|
||||
4. 如果还有报错:**先看 `files/usr/var/log/doubao-patch.log` 和
|
||||
`files/termux-install.log`**,再看那条报错里的路径属于哪个二进制,
|
||||
然后在五类改法里挑一类。
|
||||
★ 报错里的路径**是不是 `/data/data/com.termux/...`** 是第一条判据 ——
|
||||
是的话就是这套病根;不是的话是别的问题,别往这边查。
|
||||
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]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -109,12 +110,56 @@ for (const file of fs.readdirSync(path.join(repo, 'tools'))) {
|
||||
toolSources[file] = source.toString('base64');
|
||||
toolCount += 1;
|
||||
}
|
||||
// ★★★ 内置工具的"历史版本哈希登记表"
|
||||
//
|
||||
// 为什么需要它 —— 这里踩过一个非常隐蔽的坑:
|
||||
//
|
||||
// 内核启动时把内置工具播种到手机可写目录(用户能自己改)。
|
||||
// 为了**不许覆盖用户改过的文件**,播种时要判断"盘上这份是不是我们写的"。
|
||||
// 第一版只看一个本地指纹文件(.doubao-seed.json):
|
||||
// 指纹对得上 = 我们写的;对不上 = 用户改过 → 不覆盖。
|
||||
//
|
||||
// 问题是**老设备上那个指纹文件是空的**(第一版播种逻辑没写过它)。
|
||||
// 于是所有文件都被判成"用户改过",**升级永远不生效** ——
|
||||
// 实测 v2.0.37 给 show_ui 加了 wait 参数,真机上死活拿不到。
|
||||
//
|
||||
// 所以必须有一份"我们**以前**发过哪些内容"的记录,才能区分:
|
||||
// · 盘上这份是我们旧版本发的 → 安全覆盖
|
||||
// · 盘上这份不是任何一版我们发的 → 用户改过 → 绝不覆盖
|
||||
//
|
||||
// 这份登记表在构建时累积:每发一版就把当前哈希加进去(去重、只增不减)。
|
||||
// 存成仓库里的一个 JSON 文件,跟着代码走。
|
||||
const regPath = path.join(repo, 'tools', '.shipped-hashes.json');
|
||||
let registry = {};
|
||||
try {
|
||||
registry = JSON.parse(fs.readFileSync(regPath, 'utf8'));
|
||||
} catch {
|
||||
registry = {};
|
||||
}
|
||||
const hashOf = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 16);
|
||||
let newHashes = 0;
|
||||
for (const [name, source] of Object.entries(toolSources)) {
|
||||
const text = Buffer.from(source, 'base64').toString('utf8');
|
||||
const h = hashOf(text);
|
||||
const list = Array.isArray(registry[name]) ? registry[name] : [];
|
||||
if (!list.includes(h)) {
|
||||
list.push(h);
|
||||
newHashes += 1;
|
||||
}
|
||||
registry[name] = list;
|
||||
}
|
||||
fs.writeFileSync(regPath, JSON.stringify(registry, null, 2) + '\n', 'utf8');
|
||||
if (newHashes) log(`工具哈希登记表:新增 ${newHashes} 条`);
|
||||
|
||||
const bundledPy = [
|
||||
'"""构建时自动生成,不要手改。',
|
||||
'',
|
||||
'内置 Python 工具的源码(base64)。安卓端 Chaquopy 只有 .pyc,',
|
||||
'所以由 scripts/build-apk.mjs 在打包时把源码嵌进来,',
|
||||
'由 doubao_entry 首次启动时解码写到手机上的可写工具目录。',
|
||||
'由 doubao_entry 启动时解码写到手机上的可写工具目录。',
|
||||
'',
|
||||
'`shipped()` 返回"历史上我们发过的所有源码哈希" —— 内核靠它区分',
|
||||
'"盘上这份是我们旧版本写的(可以覆盖)" 和 "用户自己改过(不能覆盖)"。',
|
||||
'"""',
|
||||
'',
|
||||
'import base64',
|
||||
@@ -123,14 +168,23 @@ const bundledPy = [
|
||||
...Object.entries(toolSources).map(([name, b64]) => ` ${JSON.stringify(name)}: ${JSON.stringify(b64)},`),
|
||||
'}',
|
||||
'',
|
||||
'_SHIPPED = {',
|
||||
...Object.entries(registry).map(([name, list]) => ` ${JSON.stringify(name)}: ${JSON.stringify(list)},`),
|
||||
'}',
|
||||
'',
|
||||
'',
|
||||
'def sources():',
|
||||
' """返回 {文件名: 源码文本}"""',
|
||||
' return {name: base64.b64decode(data).decode("utf-8") for name, data in _DATA.items()}',
|
||||
'',
|
||||
'',
|
||||
'def shipped():',
|
||||
' """返回 {文件名: [历史哈希, ...]}"""',
|
||||
' return {name: list(v) for name, v in _SHIPPED.items()}',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.writeFileSync(path.join(pyRoot, 'bundled_tool_sources.py'), bundledPy, 'utf8');
|
||||
log(`已内置 ${toolCount} 个 Python 工具(含源码与 _protocol.py)`);
|
||||
log(`已内置 ${toolCount} 个 Python 工具(含源码、_protocol.py、历史哈希表)`);
|
||||
|
||||
// 内核源码在 android/kernel,靠 chaquopy 的 srcDir("../kernel") 引入;
|
||||
// 这里检查一下它确实在
|
||||
|
||||
115
scripts/build-deps.sh
Normal file
115
scripts/build-deps.sh
Normal file
@@ -0,0 +1,115 @@
|
||||
#!/bin/bash
|
||||
# 用 NDK 为 Android 交叉编译 dpkg 需要的静态库
|
||||
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
|
||||
NDK=/root/tb/android-ndk-r27c
|
||||
SRC=/root/tb/dl
|
||||
OUT=/root/tb/out/$ARCH
|
||||
API=24
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
export LDFLAGS=""
|
||||
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
|
||||
echo "### arch=$ARCH CC=$CC"
|
||||
"$CC" --version | head -1
|
||||
|
||||
mkdir -p "$OUT/lib" "$OUT/include" /root/tb/work
|
||||
cd /root/tb/work
|
||||
|
||||
########################################
|
||||
# libmd 1.3.0
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libmd.a" ]; then
|
||||
echo "=== libmd ==="
|
||||
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
|
||||
cd libmd-1.3.0
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static >/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/libmd.a" 2>/dev/null || echo "!! libmd 失败"
|
||||
|
||||
########################################
|
||||
# zlib
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libz.a" ]; then
|
||||
echo "=== zlib ==="
|
||||
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
|
||||
cd zlib-1.3.2
|
||||
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
|
||||
make -j"$(nproc)" libz.a >/dev/null 2>&1
|
||||
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/libz.a" 2>/dev/null || echo "!! zlib 失败"
|
||||
|
||||
########################################
|
||||
# bzip2 1.0.8
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libbz2.a" ]; then
|
||||
echo "=== bzip2 ==="
|
||||
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
|
||||
cd bzip2-1.0.8
|
||||
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
|
||||
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/libbz2.a" 2>/dev/null || echo "!! bzip2 失败"
|
||||
|
||||
########################################
|
||||
# liblzma (xz)
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/liblzma.a" ]; then
|
||||
echo "=== liblzma ==="
|
||||
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
|
||||
cd xz-5.8.4
|
||||
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,
|
||||
# 而 -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static \
|
||||
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
|
||||
--disable-scripts --disable-doc --disable-nls \
|
||||
SKIP_WERROR_CHECK=yes \
|
||||
>/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/liblzma.a" 2>/dev/null || echo "!! liblzma 失败"
|
||||
|
||||
########################################
|
||||
# libzstd
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libzstd.a" ]; then
|
||||
echo "=== libzstd ==="
|
||||
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
|
||||
cd zstd-1.5.7/lib
|
||||
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" CFLAGS="$CFLAGS" >/dev/null 2>&1
|
||||
cp libzstd.a "$OUT/lib/"
|
||||
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
|
||||
cd ../..
|
||||
fi
|
||||
ls -la "$OUT/lib/libzstd.a" 2>/dev/null || echo "!! libzstd 失败"
|
||||
|
||||
echo
|
||||
echo "=== $ARCH 产物清单 ==="
|
||||
ls -la "$OUT/lib/" "$OUT/include/" 2>/dev/null
|
||||
142
scripts/build-dpkg.sh
Normal file
142
scripts/build-dpkg.sh
Normal file
@@ -0,0 +1,142 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg
|
||||
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
|
||||
NDK=/root/tb/android-ndk-r27c
|
||||
SRC=/root/tb/src/dpkg
|
||||
DEPS=/root/tb/out/$ARCH
|
||||
OUT=/root/tb/out/$ARCH
|
||||
API=24
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ; APKARCH=x86_64 ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ; APKARCH=arm64-v8a ;;
|
||||
*) echo "未知 arch: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
# -D__ANDROID_API__ 让 configure 通过;-isystem 把我们的静态库头文件放前面
|
||||
export CPPFLAGS="-I$DEPS/include"
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
|
||||
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
|
||||
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,/data/data/com.doubao.lynxclone/files/usr/lib -Wl,--enable-new-dtags"
|
||||
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
|
||||
|
||||
BUILD=/root/tb/build/dpkg-$ARCH
|
||||
mkdir -p /root/tb/build "$BUILD"
|
||||
cd "$BUILD"
|
||||
|
||||
echo "########## 1. 准备源码树 ##########"
|
||||
# 注意:不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要
|
||||
# 一个真正的 git checkout(或发行 tarball)才能定出版本号。
|
||||
# 用 git worktree:共享 .git,树是干净的,且可以随时删掉重来。
|
||||
cd "$SRC"
|
||||
git worktree remove --force "$BUILD" 2>/dev/null || true
|
||||
rm -rf "$BUILD"
|
||||
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
|
||||
echo "git worktree 失败"; exit 1; }
|
||||
cd "$BUILD"
|
||||
echo " worktree 就绪: $(pwd)"
|
||||
|
||||
echo "########## 2. 应用 Termux 补丁 ##########"
|
||||
for p in /root/tb/patches/termux-*.patch; do
|
||||
n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n <<< 失败"
|
||||
patch -p1 -N -l -i "$p" 2>&1 | head -20
|
||||
fi
|
||||
done
|
||||
|
||||
echo "########## 3. 应用我们自己的补丁 ##########"
|
||||
for p in /root/tb/ourpatch/doubao-prefix-h.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-c.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-makefile.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-options.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-main.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-script.patch \
|
||||
/root/tb/ourpatch/doubao-android-arch.patch \
|
||||
/root/tb/ourpatch/doubao-arch-name.patch \
|
||||
/root/tb/ourpatch/doubao-debarch-name.patch; do
|
||||
n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n <<< 失败"; patch -p1 -N -l -i "$p" 2>&1 | head -20; exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "########## 4. autogen ##########"
|
||||
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
|
||||
AUTOGEN=./autogen
|
||||
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
|
||||
NOCONFIGURE=1 sh "$AUTOGEN" > "$BUILD/autogen.log" 2>&1 || {
|
||||
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
|
||||
fi
|
||||
echo " configure 存在: $([ -x configure ] && echo yes || echo no)"
|
||||
|
||||
echo "########## 5. configure ##########"
|
||||
# PERL: 宿主机是 perl 5.30,dpkg 要求 >= 5.32.1。perl 只用于构建期脚本
|
||||
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
|
||||
# perl 在哪,跳过版本探测。
|
||||
#
|
||||
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
|
||||
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
|
||||
./configure \
|
||||
--host="$TRIPLE" \
|
||||
--build="$(uname -m)-pc-linux-gnu" \
|
||||
--prefix=/data/data/com.doubao.lynxclone/files/usr \
|
||||
--bindir=/data/data/com.doubao.lynxclone/files/usr/bin \
|
||||
--libdir=/data/data/com.doubao.lynxclone/files/usr/lib \
|
||||
--sysconfdir=/data/data/com.doubao.lynxclone/files/usr/etc \
|
||||
--localstatedir=/data/data/com.doubao.lynxclone/files/usr/var \
|
||||
--disable-shared \
|
||||
--disable-dselect \
|
||||
--disable-start-stop-daemon \
|
||||
--disable-update-alternatives \
|
||||
--disable-largefile \
|
||||
--disable-nls \
|
||||
--without-selinux \
|
||||
--without-libselinux \
|
||||
--without-systemd \
|
||||
PERL=/usr/bin/perl \
|
||||
ac_cv_lib_selinux_setexecfilecon=no \
|
||||
dpkg_cv_c99_snprintf=yes \
|
||||
DPKG_PAGER=pager \
|
||||
> "$BUILD/configure.log" 2>&1 || {
|
||||
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
|
||||
|
||||
echo " ✓ configure 通过"
|
||||
|
||||
echo "########## 6. make ##########"
|
||||
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
|
||||
echo "make 失败,错误摘要:"
|
||||
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
|
||||
exit 1; }
|
||||
|
||||
echo " ✓ make 通过"
|
||||
mkdir -p "$OUT/dpkg-bin"
|
||||
# libtool 会在源码目录放一个壳脚本,真正的东西在 .libs/ 里
|
||||
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger dpkg-realpath; do
|
||||
f=""
|
||||
for cand in "src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
|
||||
"src/$b" "src/main/$b" "utils/$b"; do
|
||||
[ -f "$cand" ] && { f="$cand"; break; }
|
||||
done
|
||||
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
|
||||
cp "$f" "$OUT/dpkg-bin/$b"
|
||||
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b(可能不是 ELF)"
|
||||
done
|
||||
echo
|
||||
echo "########## 产物 ##########"
|
||||
ls -la "$OUT/dpkg-bin/"
|
||||
file "$OUT/dpkg-bin/dpkg" 2>/dev/null || true
|
||||
97
scripts/dis-termux.py
Normal file
97
scripts/dis-termux.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""把 libtermux.so 的 createSubprocess 反汇编**并解析出每个 call 的真实名字**。
|
||||
|
||||
之前只看到 `call 0x18e0` 这种裸地址,分不清 dup2 / close / execvp。
|
||||
PLT 的名字要从不多的几处推断:
|
||||
· .rela.plt 里按顺序对应 .plt 的条目(x86_64:.plt[0] 是桩头,
|
||||
真正的第 n 个 stub 对应 .rela.plt 的第 n 项)
|
||||
· 也可以直接看 call 目标是 .plt 区间 → 用 .got.plt 的 relocation 反查
|
||||
|
||||
这里用最稳的办法:解析 .rela.plt,按 (offset - got_plt_base) / 8 - 3 定位 stub。
|
||||
"""
|
||||
import struct
|
||||
import zipfile
|
||||
|
||||
from capstone import Cs, CS_ARCH_X86, CS_MODE_64
|
||||
|
||||
APK = r'C:\Users\Administrator\Documents\豆鲍\dist-android\doubao-debug.apk'
|
||||
data = zipfile.ZipFile(APK).read('lib/x86_64/libtermux.so')
|
||||
|
||||
e_shoff, = struct.unpack_from('<Q', data, 0x28)
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', data, 0x3A)
|
||||
secs = []
|
||||
for i in range(e_shnum):
|
||||
off = e_shoff + i * e_shentsize
|
||||
f = struct.unpack_from('<IIQQQQIIQQ', data, off)
|
||||
secs.append(dict(name=f[0], typ=f[1], addr=f[4], offset=f[5],
|
||||
size=f[6], link=f[7], info=f[8], entsize=f[9]))
|
||||
shstr = data[secs[e_shstrndx]['offset']:
|
||||
secs[e_shstrndx]['offset'] + secs[e_shstrndx]['size']]
|
||||
|
||||
|
||||
def sn(i):
|
||||
return shstr[i:shstr.find(b'\0', i)].decode('ascii', 'replace')
|
||||
|
||||
|
||||
for s in secs:
|
||||
s['sn'] = sn(s['name'])
|
||||
|
||||
|
||||
def by_name(n):
|
||||
return next((s for s in secs if s['sn'] == n), None)
|
||||
|
||||
|
||||
# ---- 动态符号表 ----
|
||||
dynsym = next(s for s in secs if s['typ'] == 11)
|
||||
dynstr = data[secs[dynsym['link']]['offset']:
|
||||
secs[dynsym['link']]['offset'] + secs[dynsym['link']]['size']]
|
||||
dynsyms = []
|
||||
for i in range(dynsym['size'] // 24):
|
||||
off = dynsym['offset'] + i * 24
|
||||
nm, info, other, shndx, value, size = struct.unpack_from('<IBBHQQ', data, off)
|
||||
name = dynstr[nm:dynstr.find(b'\0', nm)].decode('ascii', 'replace')
|
||||
dynsyms.append((name, value, size))
|
||||
|
||||
# ---- PLT 名表:.rela.plt 的第 n 项 -> .plt 第 n 个 stub ----
|
||||
plt = by_name('.plt')
|
||||
gotplt = by_name('.got.plt')
|
||||
relaplt = by_name('.rela.plt')
|
||||
plt_names = {}
|
||||
if plt and gotplt and relaplt:
|
||||
n = relaplt['size'] // 24
|
||||
# x86_64 PLT:每项 16 字节,第 0 项是桩头(对应 .got.plt 的前 3 个保留槽)
|
||||
stub_base = plt['addr'] + 16
|
||||
got_base = gotplt['addr'] + 24
|
||||
for i in range(n):
|
||||
off = relaplt['offset'] + i * 24
|
||||
r_offset, r_info, r_addend = struct.unpack_from('<QQq', data, off)
|
||||
sym_idx = r_info >> 32
|
||||
nm = dynsyms[sym_idx][0] if sym_idx < len(dynsyms) else '?'
|
||||
slot = (r_offset - got_base) // 8
|
||||
stub = stub_base + slot * 16
|
||||
plt_names[stub] = nm
|
||||
|
||||
print(' PLT 名字表:%d 项' % len(plt_names))
|
||||
for k in sorted(plt_names):
|
||||
print(' 0x%x -> %s' % (k, plt_names[k]))
|
||||
|
||||
# ---- 目标函数 ----
|
||||
addr = size = None
|
||||
for name, value, sz in dynsyms:
|
||||
if name == 'Java_com_termux_terminal_JNI_createSubprocess':
|
||||
addr, size = value, sz
|
||||
if addr is None:
|
||||
raise SystemExit('找不到符号')
|
||||
|
||||
text = by_name('.text')
|
||||
code = data[text['offset']:text['offset'] + text['size']]
|
||||
md = Cs(CS_ARCH_X86, CS_MODE_64)
|
||||
ins = list(md.disasm(code[addr - text['addr']:addr - text['addr'] + size], addr))
|
||||
|
||||
print('\n ---- createSubprocess 全文(%d 条指令)----' % len(ins))
|
||||
for x in ins:
|
||||
tag = ''
|
||||
if x.mnemonic == 'call' and x.op_str.startswith('0x'):
|
||||
t = int(x.op_str, 16)
|
||||
if t in plt_names:
|
||||
tag = ' <<< %s' % plt_names[t]
|
||||
print(' %04x %-9s %-40s%s' % (x.address - addr, x.mnemonic, x.op_str, tag))
|
||||
86
scripts/fake-openai.py
Normal file
86
scripts/fake-openai.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""假模型服务:把收到的请求原样存下来,回一个最小可用的 SSE。
|
||||
|
||||
用来**证明**"界面上选的值真的拼进了发给模型的消息里" ——
|
||||
光看队列空了不够,那只说明有人取走了;到底拼没拼、拼成什么样,要看请求。
|
||||
|
||||
用法:
|
||||
python scripts/fake-openai.py 18080 # 另开一个窗口
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18080
|
||||
CAPTURE = sys.argv[2] if len(sys.argv) > 2 else r"C:\DoubaoAndroid\fake-req.json"
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/v1/models"):
|
||||
body = json.dumps({"data": [{"id": "fake-model"}]}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n).decode("utf-8", "replace")
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except Exception:
|
||||
parsed = {"__raw": raw}
|
||||
|
||||
# ★ 存下来 —— 这就是"模型收到了什么"的铁证
|
||||
with open(CAPTURE, "w", encoding="utf-8") as fh:
|
||||
json.dump({"path": self.path, "body": parsed}, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"\n=== {self.path} 收到请求 ===", flush=True)
|
||||
for m in (parsed.get("messages") or []):
|
||||
role = m.get("role")
|
||||
content = m.get("content")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(
|
||||
c.get("text", "") for c in content if isinstance(c, dict)
|
||||
)
|
||||
text = (content or "")
|
||||
print(f" [{role}] {text[:400]}", flush=True)
|
||||
|
||||
# 回一个最小 SSE(OpenAI 流式格式)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.end_headers()
|
||||
|
||||
def chunk(delta, finish=None):
|
||||
obj = {
|
||||
"id": "chatcmpl-fake", "object": "chat.completion.chunk",
|
||||
"created": int(time.time()), "model": "fake-model",
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
|
||||
}
|
||||
self.wfile.write(f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode())
|
||||
self.wfile.flush()
|
||||
|
||||
chunk({"role": "assistant", "content": "我看到你在界面上选了:方案B、方案C、方案D。"})
|
||||
chunk({}, "stop")
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"假模型服务监听 127.0.0.1:{PORT}", flush=True)
|
||||
print(f"请求会存到 {CAPTURE}", flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
82
scripts/probe-ai-surfaces.py
Normal file
82
scripts/probe-ai-surfaces.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""端到端测 AI 界面三件套:宿主机 → 内核 /api/tools/run → 安卓桥。
|
||||
|
||||
★ 为什么从宿主机打而不是在设备上敲:PowerShell/adb 的多层引号会把 JSON
|
||||
搅烂(这一路上已经踩过好几次)。adb forward 之后在宿主机上用 Python 打,
|
||||
引号只有一层,看得清。
|
||||
|
||||
★ ask_user 是**阻塞**的:脚本会挂在那儿等用户在手机上点。
|
||||
所以它放在最后,并且单独一个命令跑(另一个终端截图看界面)。
|
||||
"""
|
||||
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"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=180):
|
||||
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_tool(name, args, timeout=150):
|
||||
print(f"\n--- {name} ---", flush=True)
|
||||
print(" 参数:", json.dumps(args, ensure_ascii=False)[:160], flush=True)
|
||||
t0 = time.time()
|
||||
res = call("/api/tools/run", {"name": name, "args": args, "conversationId": CONV},
|
||||
timeout=timeout)
|
||||
print(f" 耗时 {time.time() - t0:.1f}s -> {json.dumps(res, ensure_ascii=False)[:300]}",
|
||||
flush=True)
|
||||
return res
|
||||
|
||||
|
||||
which = sys.argv[1] if len(sys.argv) > 1 else "all"
|
||||
|
||||
if which in ("all", "state"):
|
||||
st = call("/api/state", method="GET")
|
||||
print("uiTools =", json.dumps((st.get("settings") or {}).get("uiTools"), ensure_ascii=False))
|
||||
|
||||
if which in ("all", "screen"):
|
||||
run_tool("show_ui", {
|
||||
"title": "测试界面",
|
||||
"html": "<h1>你好</h1><p>这是 AI 写的 HTML。</p>"
|
||||
"<table><tr><th>项</th><th>值</th></tr><tr><td>甲</td><td>1</td></tr></table>"
|
||||
"<button data-doubao-result='选了A'>选 A</button>"
|
||||
"<button data-doubao-result='选了B'>选 B</button>",
|
||||
})
|
||||
|
||||
if which in ("all", "end"):
|
||||
run_tool("end_conversation", {"reason": "这件事已经办完了,没有后续可聊的。"})
|
||||
print("\n=== 确认落盘 ===", flush=True)
|
||||
full = call(f"/api/conversations/{CONV}", method="GET").get("conversation") or {}
|
||||
print(" ended =", full.get("ended"), "| endedReason =", full.get("endedReason"), flush=True)
|
||||
|
||||
if which == "ask":
|
||||
run_tool("ask_user", {
|
||||
"question": "这个方案你要哪一个?",
|
||||
"options": [
|
||||
{"label": "方案 A", "value": "A", "description": "快但功能少"},
|
||||
{"label": "方案 B", "value": "B", "description": "慢一点但完整"},
|
||||
{"label": "都不要", "value": "none"},
|
||||
],
|
||||
}, timeout=240)
|
||||
|
||||
if which == "askmulti":
|
||||
run_tool("ask_user", {
|
||||
"question": "想装哪几个?(可多选)",
|
||||
"multiple": True,
|
||||
"options": ["python", "git", "nmap", "nodejs"],
|
||||
}, timeout=240)
|
||||
63
scripts/probe-bridge-visibility.py
Normal file
63
scripts/probe-bridge-visibility.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""验证"外部页面拿不到桥"。
|
||||
|
||||
思路:AI 页面里放一个按钮,点了之后用 JS 把 `typeof Doubao` 的结果写到页面上。
|
||||
先在初始页看一次(应该是 object),导航到 http 页之后再看一次(应该 undefined)。
|
||||
|
||||
★ 为什么不用"点外链然后在外部页面上跑 JS":外部页面我们控制不了,
|
||||
evaluateJavascript 也需要 App 侧支持。用自己页面上的按钮最直接。
|
||||
"""
|
||||
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=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"))
|
||||
|
||||
|
||||
HTML = """
|
||||
<h1>桥可见性测试</h1>
|
||||
<p id="out" style="font-size:18px">(还没检测)</p>
|
||||
<button onclick="check()" style="padding:12px 18px;border-radius:10px;border:0;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">检测 typeof Doubao</button>
|
||||
<p style="margin-top:16px">
|
||||
<a id="go" href="https://example.com">→ 导航到 example.com</a>
|
||||
</p>
|
||||
<script>
|
||||
function check() {
|
||||
var t = (typeof Doubao);
|
||||
document.getElementById('out').textContent =
|
||||
'typeof Doubao = ' + t + ' | pick 可用: ' + (t === 'object' && typeof Doubao.pick === 'function');
|
||||
}
|
||||
// 加载时自动测一次
|
||||
check();
|
||||
</script>
|
||||
"""
|
||||
|
||||
print("=== 弹「桥可见性测试」页面 ===")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "桥测试", "html": HTML},
|
||||
"conversationId": "c_main",
|
||||
})
|
||||
print(json.dumps(res, ensure_ascii=False)[:200])
|
||||
print("""
|
||||
接下来手动做(脚本没法点屏幕):
|
||||
1. 截图 —— 应显示 "typeof Doubao = object | pick 可用: true"
|
||||
2. 点链接导航到 example.com
|
||||
3. 点顶部返回键回到我们那一页
|
||||
4. 再截图 —— 回来之后应该**还是 object**(onPageFinished 里重新挂上了)
|
||||
""")
|
||||
34
scripts/probe-check-conv.py
Normal file
34
scripts/probe-check-conv.py
Normal file
@@ -0,0 +1,34 @@
|
||||
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"))
|
||||
|
||||
|
||||
convs = call("/api/conversations", method="GET").get("conversations") or []
|
||||
print("会话:")
|
||||
for c in convs:
|
||||
print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount"),
|
||||
"| updated", c.get("updatedAt"))
|
||||
|
||||
# 直接看 c_main 里到底有没有消息
|
||||
full = call("/api/conversations/c_main", method="GET").get("conversation") or {}
|
||||
msgs = full.get("messages") or []
|
||||
print(f"\nc_main 里 {len(msgs)} 条消息:")
|
||||
for m in msgs:
|
||||
print(" ", m.get("role"), "|", repr((m.get("content") or "")[:60]))
|
||||
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 "(没报)"))
|
||||
46
scripts/probe-clean-testdata.py
Normal file
46
scripts/probe-clean-testdata.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""清掉测试留下的对话数据(让模拟器上的 App 回到干净状态)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
K = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(p, d=None, m="POST"):
|
||||
b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None
|
||||
r = urllib.request.Request(
|
||||
K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"}
|
||||
)
|
||||
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode())
|
||||
|
||||
|
||||
# ★ 注意 method 是**位置参数** m,不是 method= —— 这个脚本第一版写成
|
||||
# `method="PATCH"` 直接 TypeError。写探针脚本时这种小错最多。
|
||||
call("/api/conversations/c_main", {"messages": []}, "PATCH")
|
||||
full = call("/api/conversations/c_main", None, "GET").get("conversation") or {}
|
||||
print("消息数:", len(full.get("messages") or []))
|
||||
print("ended:", full.get("ended"))
|
||||
|
||||
# 把 provider 恢复成默认(e2e 测试里改过)
|
||||
#
|
||||
# ★ 不能只传空串:内核保存时会把空值过滤掉,于是 baseUrl/model 留在假服务上,
|
||||
# 用户打开 App 会发现"模型指着 127.0.0.1:18080"而一脸懵。
|
||||
# ★ 也没有 GET /api/settings(404)—— 读当前设置要用 /api/state。
|
||||
st = call("/api/state", None, "GET")
|
||||
s = dict(st.get("settings") or {})
|
||||
s.pop("baseUrl", None)
|
||||
s.pop("model", None)
|
||||
s.pop("apiKey", None)
|
||||
s["provider"] = "ark"
|
||||
call("/api/settings", s, "PUT")
|
||||
after = (call("/api/state", None, "GET").get("settings") or {})
|
||||
print("provider:", after.get("provider"),
|
||||
"| baseUrl:", repr(after.get("baseUrl")),
|
||||
"| model:", repr(after.get("model")))
|
||||
q = call("/api/ui-result?conversationId=c_main", None, "GET")
|
||||
print("待交付队列:", q)
|
||||
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])
|
||||
86
scripts/probe-heartbeat-ui.py
Normal file
86
scripts/probe-heartbeat-ui.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""按用户截图里的样子造一个界面:心跳线 + 六个按钮。
|
||||
|
||||
★ 用户报"没有一个按键能用",而我之前测的都是朴素 HTML。
|
||||
所以这里**按他截图里的形态**造:canvas 画心跳线 + 六个中文按钮 +
|
||||
一段很长的角色扮演文案(把按钮挤到屏幕外),看按钮到底能不能点。
|
||||
|
||||
三种按钮形态都放上:
|
||||
① onclick="Doubao.sendToAi(...)" —— JS 桥
|
||||
② data-doubao-result="..." —— App 侧字符串替换(不依赖 JS)
|
||||
③ 纯 <button> 什么都没标 —— 对照,本来就不该有回传能力
|
||||
"""
|
||||
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"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=180):
|
||||
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"))
|
||||
|
||||
|
||||
HTML = """
|
||||
<h1 style="font-size:20px">今天,你归我了</h1>
|
||||
|
||||
<canvas id="beat" width="320" height="90"
|
||||
style="width:100%;background:#14161b;border-radius:10px"></canvas>
|
||||
|
||||
<p style="margin:14px 0 6px;color:#8c939d;font-size:13px">下面六个按钮,点哪个我就干哪个:</p>
|
||||
|
||||
<button onclick="Doubao.sendToAi('查岗')">① 抽查我位置</button>
|
||||
<button data-doubao-result="来点黄的">② 来点黄的</button>
|
||||
<button onclick="Doubao.sendToAi('讲个故事')">③ 讲个故事</button>
|
||||
<button data-doubao-result="夸我">④ 夸我</button>
|
||||
<button onclick="Doubao.sendToAi('唱歌')">⑤ 唱首歌</button>
|
||||
<button onclick="Doubao.close()">⑥ 关掉界面</button>
|
||||
|
||||
<div id="st" style="margin-top:12px;font-size:12px;color:#8c939d">(点一下试试,这里会显示结果)</div>
|
||||
|
||||
<script>
|
||||
// 心跳线 —— 复刻用户截图里那个效果
|
||||
var c = document.getElementById('beat'), g = c.getContext('2d');
|
||||
c.width = 320; c.height = 90;
|
||||
var t = 0;
|
||||
function draw() {
|
||||
g.clearRect(0, 0, 320, 90);
|
||||
g.strokeStyle = '#4c8dff';
|
||||
g.lineWidth = 2;
|
||||
g.beginPath();
|
||||
for (var x = 0; x < 320; x++) {
|
||||
var y = 45 + Math.sin((x + t) / 9) * Math.exp(-((x % 90) / 40)) * 26
|
||||
+ Math.sin((x + t) / 2.2) * 1.4;
|
||||
if (x === 0) g.moveTo(x, y); else g.lineTo(x, y);
|
||||
}
|
||||
g.stroke();
|
||||
t += 3;
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
draw();
|
||||
|
||||
// JS 桥可用性自检 —— 直接显示在页面上,一眼就能看出桥在不在
|
||||
document.getElementById('st').textContent =
|
||||
'typeof Doubao = ' + (typeof Doubao) +
|
||||
' | sendToAi: ' + (typeof Doubao !== 'undefined' && typeof Doubao.sendToAi === 'function');
|
||||
</script>
|
||||
"""
|
||||
|
||||
print("=== 按用户截图的形态弹一个界面 ===")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "心检", "html": HTML, "wait": True, "timeout": 90},
|
||||
"conversationId": CONV,
|
||||
}, timeout=180)
|
||||
print(json.dumps(res, ensure_ascii=False)[:400])
|
||||
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))
|
||||
47
scripts/probe-reset-provider.py
Normal file
47
scripts/probe-reset-provider.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""把模拟器上的 provider 配置恢复成默认(e2e 测试把内核指到假服务上过)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
K = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(p, d=None, m="POST"):
|
||||
b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None
|
||||
r = urllib.request.Request(
|
||||
K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"}
|
||||
)
|
||||
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode())
|
||||
|
||||
|
||||
st = call("/api/state", None, "GET")
|
||||
s = st.get("settings") or {}
|
||||
print("改之前:")
|
||||
for k in ("provider", "baseUrl", "model", "apiKey", "hasApiKey"):
|
||||
print(f" {k} = {s.get(k)!r}")
|
||||
|
||||
# ★ 显式传 **null** 表示"我要清掉它"。
|
||||
# 传空串是不行的 —— 内核把空串当"没填、别动"(那个保险是为了防
|
||||
# "前端草稿没初始化好,一次保存清空整份配置")。
|
||||
# 两条路语义不同:空串 = 没填,null = 确实要清。
|
||||
res = call("/api/settings", {
|
||||
"provider": "ark",
|
||||
"baseUrl": None,
|
||||
"model": None,
|
||||
"apiKey": None,
|
||||
}, "PUT")
|
||||
after = (res.get("settings") or {})
|
||||
print("PUT(传 null)之后:")
|
||||
for k in ("provider", "baseUrl", "model"):
|
||||
print(f" {k} = {after.get(k)!r}")
|
||||
|
||||
st2 = call("/api/state", None, "GET")
|
||||
s2 = st2.get("settings") or {}
|
||||
print("重新读 /api/state:")
|
||||
for k in ("provider", "baseUrl", "model", "hasApiKey"):
|
||||
print(f" {k} = {s2.get(k)!r}")
|
||||
48
scripts/probe-seed-bare-urls.py
Normal file
48
scripts/probe-seed-bare-urls.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""塞一条带**裸 URL** 的助手回复(旧版 extractUrls 认不出来的那种)。
|
||||
|
||||
★ 用户报"操作栏里应该有『打开网页』按钮,但没显示"。
|
||||
旧实现只认 `](` 紧挨着的 markdown 链接,裸 URL 一律漏 →
|
||||
extractUrls 返回空 → 按钮整个不显示。
|
||||
这条回复就是用来验证修好没有的。
|
||||
"""
|
||||
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"))
|
||||
|
||||
|
||||
content = (
|
||||
"给你几个链接,写法故意各不相同(旧版只有第一种能被认出来):\n\n"
|
||||
"1. 标准的:[Example 官网](https://example.com)\n"
|
||||
"2. 中间有空格的:[Example 中文] (https://example.com/index-zh)\n"
|
||||
"3. **裸 URL**:直接去 https://www.iana.org/help/example-domains 看\n"
|
||||
"4. 尖括号包裹:<https://example.org>\n"
|
||||
"5. 中文标点紧跟:也可以看 https://www.rfc-editor.org/rfc/rfc2606,里面有说明\n"
|
||||
)
|
||||
|
||||
convs = call("/api/conversations", None, "GET").get("conversations") or []
|
||||
cid = convs[0]["id"] if convs else "c_main"
|
||||
print("往", cid, "写消息…")
|
||||
|
||||
res = call(f"/api/conversations/{cid}", {"messages": [
|
||||
{"role": "user", "content": "给我几个链接"},
|
||||
{"role": "assistant", "content": content},
|
||||
]}, "PATCH")
|
||||
full = res.get("conversation") or {}
|
||||
print("现在", len(full.get("messages") or []), "条消息")
|
||||
62
scripts/probe-seed-link-msg.py
Normal file
62
scripts/probe-seed-link-msg.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""给会话塞一条带链接的助手回复,用来测「打开网页」按钮。
|
||||
|
||||
★ 为什么要造数据而不是真让模型回一条:
|
||||
真回一条要配 API key、要等流式、还有网络不确定性 —— 而我们这里要测的是
|
||||
**界面上那个按钮在不在、点了对不对**,跟回复怎么来的无关。
|
||||
直接写一条一样的消息,测起来快且稳定。
|
||||
"""
|
||||
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"))
|
||||
|
||||
|
||||
convs = call("/api/conversations", method="GET").get("conversations") or []
|
||||
print("会话数:", len(convs))
|
||||
for c in convs[:5]:
|
||||
print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount"))
|
||||
|
||||
if not convs:
|
||||
print("!! 没有会话")
|
||||
sys.exit(1)
|
||||
|
||||
cid = convs[0]["id"]
|
||||
print(f"\n往 {cid} 里塞一条带链接的回复…")
|
||||
|
||||
content = (
|
||||
"我查到了几个可能有用的页面:\n\n"
|
||||
"- [Example 官网](https://example.com)\n"
|
||||
"- [Example 中文](https://example.com/index-zh)\n\n"
|
||||
"**说明**:这两个是示例域名,用来验证「打开网页」按钮。\n"
|
||||
"还有一个没有链接的说法:这是个普通段落。"
|
||||
)
|
||||
|
||||
res = call(f"/api/conversations/{cid}", {
|
||||
"messages": [
|
||||
{"role": "user", "content": "帮我找几个网页"},
|
||||
{"role": "assistant", "content": content},
|
||||
],
|
||||
}, method="PATCH")
|
||||
print("写入结果:", json.dumps(res, ensure_ascii=False)[:200])
|
||||
|
||||
full = call(f"/api/conversations/{cid}", method="GET").get("conversation") or {}
|
||||
msgs = full.get("messages") or []
|
||||
print("现在有", len(msgs), "条消息")
|
||||
for m in msgs:
|
||||
print(" ", m.get("role"), "|", (m.get("content") or "")[:50].replace("\n", " "))
|
||||
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:])
|
||||
84
scripts/probe-show-ui-js.py
Normal file
84
scripts/probe-show-ui-js.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""测 JS 支持和"点进去"。
|
||||
|
||||
一段同时用这两个能力的页面:
|
||||
· <script> 画 canvas 柱状图 + 动态生成按钮 + 调 Doubao.pick
|
||||
· 一个 http 链接(点进去应该能在界面里打开,顶部出现返回键)
|
||||
"""
|
||||
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"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=180):
|
||||
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"))
|
||||
|
||||
|
||||
HTML = """
|
||||
<h1>JS + 链接测试</h1>
|
||||
|
||||
<p>下面这根柱状图是 <b><script></b> 用 canvas 画的:</p>
|
||||
<canvas id="c" width="300" height="140" style="background:#1d1f25;border-radius:8px"></canvas>
|
||||
|
||||
<div id="btns" style="margin-top:14px"></div>
|
||||
|
||||
<p style="margin-top:14px">一个链接:<a href="https://example.com">点我进 example.com</a></p>
|
||||
|
||||
<script>
|
||||
// ① canvas 画图
|
||||
// ★ 注意:改 canvas.width/height **会清空画布**(and 重置变换)。
|
||||
// 我第一版在画完之后设了 canvas.height,结果柱子全没了 ——
|
||||
// 那是测试 HTML 自己的 bug,不是 App 的。尺寸要在画之前定好。
|
||||
var cv = document.getElementById('c'), g = cv.getContext('2d');
|
||||
cv.height = 150;
|
||||
var data = [40, 90, 60, 130, 75];
|
||||
g.fillStyle = '#4c8dff';
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
g.fillRect(20 + i * 55, 130 - data[i], 34, data[i]);
|
||||
}
|
||||
g.fillStyle = '#e8eaed';
|
||||
g.font = '12px sans-serif';
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
g.fillText('#' + (i + 1), 24 + i * 55, 146);
|
||||
}
|
||||
|
||||
// ② 动态生成按钮,用 Doubao.pick 回传(这条是 JS-only 的能力)
|
||||
var box = document.getElementById('btns');
|
||||
['低', '中', '高'].forEach(function (lv) {
|
||||
var b = document.createElement('button');
|
||||
b.textContent = '优先级:' + lv;
|
||||
b.style.cssText = 'margin:4px 8px 0 0;padding:10px 16px;border-radius:10px;'
|
||||
+ 'border:0;background:#2a2d34;color:#e8eaed;font-size:15px';
|
||||
b.onclick = function () { Doubao.pick('优先级=' + lv); };
|
||||
box.appendChild(b);
|
||||
});
|
||||
|
||||
// ③ 证明 JS 真的跑了 —— 把当前时间写进去
|
||||
var p = document.createElement('p');
|
||||
p.style.cssText = 'color:#8c939d;font-size:12px;margin-top:16px';
|
||||
p.textContent = 'JS 执行于 ' + new Date().toLocaleTimeString();
|
||||
document.body.appendChild(p);
|
||||
</script>
|
||||
"""
|
||||
|
||||
print("=== 弹一个用 JS + 带链接的界面 ===")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "JS 测试", "html": HTML},
|
||||
"conversationId": CONV,
|
||||
})
|
||||
print(json.dumps(res, ensure_ascii=False)[:300])
|
||||
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:])
|
||||
98
scripts/probe-ui-result-e2e.py
Normal file
98
scripts/probe-ui-result-e2e.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""把内核指到假模型服务上,验证"界面上选的值"真的拼进了发给模型的消息里。
|
||||
|
||||
★ 为什么要这么绕:光看"队列空了"只能证明有人取走,证明不了它被拼进请求。
|
||||
真正要验的是**模型收到的 messages 数组里有没有那段上下文**。
|
||||
所以起一个假服务,把请求原样存下来,然后直接读它。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
KERNEL = "http://127.0.0.1:15199"
|
||||
CAPTURE = r"C:\DoubaoAndroid\fake-req.json"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
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(
|
||||
KERNEL + 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"))
|
||||
|
||||
|
||||
print("1) 把内核指到假模型服务")
|
||||
# ★ 关键:内核跑在**模拟器里**,它的 127.0.0.1 是自己,不是宿主机。
|
||||
# 两种打通方式:
|
||||
# · `adb reverse tcp:18080 tcp:18080` —— 模拟器的 18080 转到宿主机(**用这个**)
|
||||
# · 10.0.2.2 —— 只在标准 AVD 上有效,LDPlayer 不一定通
|
||||
# 实测 LDPlayer 上 `10.0.2.2` 连不上(假服务一个请求都没收到,
|
||||
# 很容易误判成代码有问题),所以用 adb reverse + 127.0.0.1。
|
||||
FAKE = "http://127.0.0.1:18080/v1"
|
||||
res = call("/api/settings", {
|
||||
"provider": "openai",
|
||||
"baseUrl": FAKE,
|
||||
"model": "fake-model",
|
||||
"apiKey": "sk-fake",
|
||||
}, method="PUT")
|
||||
st = res.get("settings") or {}
|
||||
print(" provider =", st.get("provider"), "| baseUrl =", st.get("baseUrl"),
|
||||
"| model =", st.get("model"))
|
||||
|
||||
print("\n2) 塞两个'界面上的选择'")
|
||||
for v in ("用户选了方案 B(蓝色按钮)", "用户填写了:预算 3000 元"):
|
||||
r = call("/api/ui-result", {"conversationId": CONV, "value": v})
|
||||
print(" ", v, "->", json.dumps(r, ensure_ascii=False))
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
print(" 队列:", json.dumps(q, ensure_ascii=False))
|
||||
|
||||
print("\n3) 发一句话,看模型收到什么")
|
||||
try:
|
||||
call("/api/chat", {"conversationId": CONV, "message": "我刚才在界面上选了什么?", "stream": False},
|
||||
timeout=120)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(" (内核返回不是 JSON,正常 —— 它走 SSE):", str(exc)[:80])
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
print("\n4) 假服务收到了什么")
|
||||
try:
|
||||
with open(CAPTURE, encoding="utf-8") as fh:
|
||||
cap = json.load(fh)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(" !! 读不到抓包:", exc)
|
||||
sys.exit(1)
|
||||
|
||||
msgs = (cap.get("body") or {}).get("messages") or []
|
||||
print(f" 路径 {cap.get('path')},共 {len(msgs)} 条消息")
|
||||
ok = False
|
||||
for m in msgs:
|
||||
role = m.get("role")
|
||||
content = m.get("content")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))
|
||||
text = content or ""
|
||||
mark = ""
|
||||
if "方案 B" in text or "预算 3000" in text:
|
||||
mark = " ← ★ 这就是回流进去的"
|
||||
ok = True
|
||||
print(f" [{role}] {text[:300]}{mark}")
|
||||
|
||||
print()
|
||||
if ok:
|
||||
print("✅ 界面上选的值**确实拼进了发给模型的请求**")
|
||||
else:
|
||||
print("❌ 请求里没有那些值 —— 回流链路断了")
|
||||
sys.exit(1)
|
||||
|
||||
# 收尾:把 provider 设回去,别把用户配置留在假服务上
|
||||
call("/api/settings", {"provider": "ark", "baseUrl": "", "model": "", "apiKey": ""}, method="PUT")
|
||||
print("(已把 provider 恢复成 ark)")
|
||||
115
scripts/probe-ui-result.py
Normal file
115
scripts/probe-ui-result.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""测「AI 写进网页里的接口」——用户在 AI 自己的界面里选的值能不能回到模型。
|
||||
|
||||
三步:
|
||||
1. 用 show_ui 弹一个界面,页面里有 Doubao.sendToAi / Doubao.pick / Doubao.close
|
||||
2. (手动)在手机上点那些按钮
|
||||
3. 查内核队列 —— 值应该排在那里,等下一轮对话交给模型
|
||||
"""
|
||||
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"
|
||||
CONV = "c_main"
|
||||
|
||||
HTML = """
|
||||
<h1>接口测试</h1>
|
||||
<p>点下面的按钮,值应该会回到 AI 手里(下一轮对话时)。</p>
|
||||
|
||||
<div id="log" style="margin:12px 0;padding:10px;background:#1d1f25;border-radius:8px;
|
||||
font-size:13px;color:#8c939d">(还没点)</div>
|
||||
|
||||
<button onclick="hit('sendToAi', '方案B')"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2b7bff;color:#fff;font-size:16px">Doubao.sendToAi('方案B')</button>
|
||||
|
||||
<button onclick="hit('pick', '方案C')"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">Doubao.pick('方案C')</button>
|
||||
|
||||
<button data-doubao-result="方案D"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">data-doubao-result="方案D"(不写 JS)</button>
|
||||
|
||||
<button onclick="Doubao.close()"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#3a2a2a;color:#e8eaed;font-size:16px">Doubao.close()</button>
|
||||
|
||||
<script>
|
||||
function hit(fn, v) {
|
||||
var el = document.getElementById('log');
|
||||
try {
|
||||
Doubao[fn](v);
|
||||
el.textContent = '已调 Doubao.' + fn + '("' + v + '") —— 应该已经排队了';
|
||||
el.style.color = '#6ee787';
|
||||
} catch (e) {
|
||||
el.textContent = '调用失败:' + e;
|
||||
el.style.color = '#ff7b72';
|
||||
}
|
||||
}
|
||||
document.getElementById('log').textContent =
|
||||
'typeof Doubao = ' + (typeof Doubao);
|
||||
</script>
|
||||
"""
|
||||
|
||||
|
||||
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"))
|
||||
|
||||
|
||||
which = sys.argv[1] if len(sys.argv) > 1 else "show"
|
||||
|
||||
if which == "show":
|
||||
# 打开界面能力(否则工具被第二道拦截挡住)
|
||||
call("/api/settings", {"uiTools": {"enabled": True}}, method="PUT")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "接口测试", "html": HTML},
|
||||
"conversationId": CONV,
|
||||
})
|
||||
print("show_ui ->", json.dumps(res, ensure_ascii=False)[:200])
|
||||
print("\n现在去手机上点按钮,然后跑:")
|
||||
print(" python scripts/probe-ui-result.py check")
|
||||
print(" python scripts/probe-ui-result.py send # 发一句话,看模型能不能看到那些值")
|
||||
|
||||
elif which == "check":
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
print("队列里现在有:", json.dumps(q, ensure_ascii=False))
|
||||
n = len(q.get("pending") or [])
|
||||
print(f" {n} 条" + (" ✓ 回流成功" if n else " ✗ 一条都没有 —— 回流没成功"))
|
||||
|
||||
elif which == "send":
|
||||
# 发一句话,触发一轮对话;agent_loop 会把队列里的值带上
|
||||
#
|
||||
# ★ 不需要真的配 API key:我们要验证的是"队列有没有被取走、有没有拼进
|
||||
# 发给模型的消息里"。模型调用失败是另一回事(会以 error 事件返回),
|
||||
# 而**取队列发生在调用之前** —— 所以看队列空了就说明接上了。
|
||||
print("发一句话(触发一轮对话)…")
|
||||
try:
|
||||
res = call("/api/chat", {
|
||||
"conversationId": CONV,
|
||||
"message": "我刚才选了什么?",
|
||||
"stream": False,
|
||||
}, timeout=180)
|
||||
print(json.dumps(res, ensure_ascii=False)[:800])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("请求失败(可能是没配 API key,不影响本项验证):", exc)
|
||||
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
n = len(q.get("pending") or [])
|
||||
print("\n发完之后队列:", json.dumps(q, ensure_ascii=False))
|
||||
if n == 0:
|
||||
print(" ✓ 队列被取走了 —— 接进上下文了")
|
||||
else:
|
||||
print(f" ✗ 队列还有 {n} 条 —— 没被取走,回流链路断了")
|
||||
110
scripts/publish-release.py
Normal file
110
scripts/publish-release.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
发 release:建说明 + 传 APK 附件。
|
||||
|
||||
用法:
|
||||
python scripts/publish-release.py v2.0.2 scripts/.tmp-v202.txt
|
||||
|
||||
为什么用 Python 而不是 PowerShell:
|
||||
PowerShell 的 ConvertTo-Json 处理**中文 + 多行 markdown** 会翻车 ——
|
||||
Gitea 会回 422("cannot unmarshal object into Go struct field
|
||||
CreateReleaseOption.Note of type string"),而且看不出哪里错了。
|
||||
这个坑真踩过两次,所以这个脚本固定用 Python。
|
||||
|
||||
需要的:
|
||||
· Gitea 上有这个 tag(先 git push local <tag>)
|
||||
· 本地已经构建好 dist-android/doubao-debug.apk
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request as u
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
API = 'http://192.168.100.103:8080/api/v1/repos/l/doubao-clone'
|
||||
# ★ 凭据不从仓库读(仓库是公开的)。要发版就先把这两个环境变量设上:
|
||||
# DOUBAO_GIT_USER / DOUBAO_GIT_PASS
|
||||
# 没设时退回默认值,方便本机用。
|
||||
USER = os.environ.get('DOUBAO_GIT_USER') or 'l'
|
||||
PASS = os.environ.get('DOUBAO_GIT_PASS') or '232711Aa'
|
||||
AUTH = 'Basic ' + base64.b64encode(f'{USER}:{PASS}'.encode()).decode()
|
||||
APK = os.path.join(WS, 'dist-android', 'doubao-debug.apk')
|
||||
|
||||
|
||||
def call(method, path, data=None, ctype='application/json', raw=None):
|
||||
body = raw if raw is not None else (
|
||||
json.dumps(data).encode('utf-8') if data is not None else None)
|
||||
req = u.Request(API + path, data=body, method=method,
|
||||
headers={'Authorization': AUTH, 'Content-Type': ctype})
|
||||
try:
|
||||
with u.urlopen(req, timeout=600) as r:
|
||||
text = r.read().decode('utf-8', 'ignore')
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode('utf-8', 'ignore')[:400]
|
||||
raise RuntimeError(f'HTTP {exc.code}: {detail}') from None
|
||||
return json.loads(text) if text.strip().startswith(('{', '[')) else text
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print('用法: publish-release.py <tag> [说明文件]')
|
||||
return 1
|
||||
tag = sys.argv[1]
|
||||
notes_file = sys.argv[2] if len(sys.argv) > 2 else ''
|
||||
# 附件名带版本号,下载下来能一眼看出是哪版
|
||||
ver = tag.lstrip('v')
|
||||
apk_name = f'doubao-{ver}.apk'
|
||||
|
||||
if not os.path.isfile(APK):
|
||||
print(f' ✗ 没找到 APK:{APK}(先 node scripts/build-apk.mjs)')
|
||||
return 1
|
||||
|
||||
# 说明:优先用文件,没有就留空
|
||||
note = ''
|
||||
if notes_file and os.path.isfile(notes_file):
|
||||
with open(notes_file, encoding='utf-8') as fh:
|
||||
note = fh.read()
|
||||
|
||||
# 找 release(tag 已经推上去了的话 Gitea 可能已经自动建了一个草稿)
|
||||
rels = call('GET', '/releases')
|
||||
rel = next((x for x in rels if x['tag_name'] == tag), None)
|
||||
if rel:
|
||||
rid = rel['id']
|
||||
print(f' 已有 release #{rid} {tag}')
|
||||
if note:
|
||||
r = call('PATCH', f'/releases/{rid}', {'body': note})
|
||||
print(f' ✓ 说明已更新:{len(r.get("body") or "")} 字符')
|
||||
else:
|
||||
payload = {'tag_name': tag, 'name': tag, 'body': note,
|
||||
'draft': False, 'prerelease': False}
|
||||
r = call('POST', '/releases', payload)
|
||||
rid = r['id']
|
||||
print(f' ✓ 建好 release #{rid} {tag}')
|
||||
|
||||
# 传 APK(同名附件先删掉,重发时不会堆一串)
|
||||
rel = call('GET', f'/releases/{rid}')
|
||||
for a in rel.get('assets') or []:
|
||||
if a['name'] == apk_name:
|
||||
call('DELETE', f'/releases/{rid}/assets/{a["id"]}')
|
||||
print(f' · 删掉旧的同名附件 {apk_name}')
|
||||
|
||||
size = os.path.getsize(APK)
|
||||
print(f' 上传 {apk_name}({size / 1024 / 1024:.1f} MB)…')
|
||||
with open(APK, 'rb') as fh:
|
||||
blob = fh.read()
|
||||
a = call('POST', f'/releases/{rid}/assets?name={apk_name}', raw=blob,
|
||||
ctype='application/vnd.android.package-archive')
|
||||
print(f' ✓ 附件 #{a.get("id")} {a.get("name")} '
|
||||
f'{(a.get("size") or 0) / 1024 / 1024:.1f} MB')
|
||||
print(f' 直链: {a.get("browser_download_url")}')
|
||||
|
||||
rel = call('GET', f'/releases/{rid}')
|
||||
print(f' release 现在有 {len(rel.get("assets") or [])} 个附件:')
|
||||
for x in rel.get('assets') or []:
|
||||
print(f' {x["name"]} {x["size"] / 1024 / 1024:.1f} MB')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
173
scripts/verify-ai-webview.py
Normal file
173
scripts/verify-ai-webview.py
Normal file
@@ -0,0 +1,173 @@
|
||||
"""守 AI 界面 WebView 的几条硬性质。
|
||||
|
||||
这个文件的**时序**我改了三版才对,每一版都对应一个只能实测发现的坑,
|
||||
所以必须用脚本钉住 —— 光看代码看不出"桥什么时候挂上"。
|
||||
|
||||
改过的三版(记在这儿,别再走回头路):
|
||||
|
||||
第一版:`loadDataWithBaseURL` 之前 add 桥,导航到 http(s) 时 remove。
|
||||
**问题**:外部页面在 `onPageStarted` 摘桥之前有个"已经开始加载、
|
||||
桥还在"的窗口期。
|
||||
|
||||
第二版:只在 `onPageFinished` 里判 url 是不是 `about:blank` 才 add。
|
||||
**问题**:实测页面报 `Uncaught ReferenceError: Doubao is not defined`
|
||||
—— `onPageFinished` 的回调**比页面内联 <script> 执行还晚**。
|
||||
|
||||
第三版(现在):
|
||||
· 初始 load 之前就 add(保证脚本能用到)
|
||||
· 用 `payloadLoaded` 标志挡住窗口期(导航时立刻摘)
|
||||
· 返回时靠 **页面里的标记变量** 判断"这是不是我们的页"再重挂
|
||||
(用 url 判会漏 —— 从外部页 goBack 回来时 url 不是 about:blank,
|
||||
表现是"点进去再返回,页面上的 JS 按钮全失灵")
|
||||
|
||||
用法:
|
||||
python scripts/verify-ai-webview.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
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__)))
|
||||
SRC = os.path.join(WS, "android", "app", "src", "main", "java",
|
||||
"com", "doubao", "lynxclone", "ui", "AiSurfaces.kt")
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
if not os.path.isfile(SRC):
|
||||
print(f"!! 找不到 {SRC}")
|
||||
sys.exit(1)
|
||||
|
||||
src = open(SRC, encoding="utf-8").read()
|
||||
# ★ 只去掉**块注释**,不去行注释。
|
||||
#
|
||||
# 我第一版顺手也去了 `//...`,结果把字符串里的 `"http://"` 从中间截断 ——
|
||||
# 于是下面"http(s) 有没有被放行"那条永远判不合格。**验证脚本自己有 bug
|
||||
# 比没有验证脚本更坏**:它会让人去改本来是对的代码。
|
||||
code = re.sub(r"/\*.*?\*/", "", src, flags=re.DOTALL)
|
||||
|
||||
print("=== AI 界面 WebView 的硬性质 ===")
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] JS 开着(用户要求)")
|
||||
if "javaScriptEnabled = true" in code:
|
||||
ok("javaScriptEnabled = true")
|
||||
else:
|
||||
fail("javaScriptEnabled 不是 true —— 用户要求支持 JS")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] 危险开关仍然关着")
|
||||
for name, pat in (
|
||||
("allowFileAccess", r"allowFileAccess\s*=\s*false"),
|
||||
("allowContentAccess", r"allowContentAccess\s*=\s*false"),
|
||||
("MIXED_CONTENT_NEVER_ALLOW", r"MIXED_CONTENT_NEVER_ALLOW"),
|
||||
):
|
||||
if re.search(pat, code):
|
||||
ok(f"{name} 关着")
|
||||
else:
|
||||
fail(f"{name} 没有显式关闭/设成安全值")
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
print("\n[3] 桥的挂/摘时机(三版才改对的那段)")
|
||||
has_add = "addJavascriptInterface" in code
|
||||
has_remove = "removeJavascriptInterface" in code
|
||||
if has_add and has_remove:
|
||||
ok("有 add 也有 remove")
|
||||
else:
|
||||
fail(f"缺 add({has_add}) 或 remove({has_remove})")
|
||||
|
||||
for name, pat in (
|
||||
("payloadLoaded 标志(挡窗口期)", r"payloadLoaded"),
|
||||
("bridgeAttached 标志(避免重复 add)", r"bridgeAttached"),
|
||||
("PROBE_JS 探针(判是不是我们的页)", r"PROBE_JS"),
|
||||
):
|
||||
if re.search(pat, code):
|
||||
ok(name)
|
||||
else:
|
||||
fail(f"缺 {name}")
|
||||
|
||||
# ★ add 必须出现在 loadDataWithBaseURL **之前**(否则内联脚本先跑,桥还没挂)
|
||||
i_add = code.find("addJavascriptInterface(host,")
|
||||
i_load = code.find("loadDataWithBaseURL")
|
||||
if i_add >= 0 and i_load >= 0 and i_add < i_load:
|
||||
ok("初始 add 在 loadDataWithBaseURL 之前(内联脚本能用上桥)")
|
||||
else:
|
||||
fail("初始 add 不在 load 之前 —— 页面脚本会报 Doubao is not defined")
|
||||
|
||||
# ★ 必须在 onPageFinished 里**补挂**(load 时挂的那次可能还没生效)
|
||||
if "onPageFinished" in code and re.search(r"onPageFinished[\s\S]{0,900}?addJavascriptInterface", code):
|
||||
ok("onPageFinished 里有补挂/重挂")
|
||||
else:
|
||||
fail("onPageFinished 里没有补挂 —— 页面脚本可能拿不到桥")
|
||||
|
||||
# ★ 重挂必须走探针,不能靠 url 判
|
||||
if re.search(r"evaluateJavascript", code):
|
||||
ok("用 evaluateJavascript 探针判断(不是靠 url)")
|
||||
else:
|
||||
fail("没有探针 —— 从外部页返回后桥恢复不了")
|
||||
|
||||
# ★ evaluateJavascript 的返回是**字符串**(JSON 编码),不能按 Boolean 处理
|
||||
if re.search(r"evaluateJavascript[\s\S]{0,300}?trim\(", code) or '"1"' in code or "'1'" in code:
|
||||
ok("探针返回值按字符串处理(evaluateJavascript 回调就是字符串)")
|
||||
else:
|
||||
fail("探针返回值可能被当成 Boolean —— 那条件永远不成立")
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
print("\n[4] 链接能点进去(而不是被吃掉)")
|
||||
if re.search(r'u\.startsWith\("http://"\)', code) and re.search(r"return false", code):
|
||||
ok("http(s) 返回 false → 交给 WebView 打开")
|
||||
else:
|
||||
fail("http(s) 没有被放行 —— 用户说'弹窗可再点进去'")
|
||||
if "doubao://pick" in code and "doubao://close" in code:
|
||||
ok("两种自定义协议都拦了")
|
||||
else:
|
||||
fail("自定义协议处理不全")
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
print("\n[5] 返回键 + 返回按钮")
|
||||
if "BackHandler" in code:
|
||||
ok("有 BackHandler(先回退网页、退不了才关界面)")
|
||||
else:
|
||||
fail("没有 BackHandler")
|
||||
if "canGoBack" in code:
|
||||
ok("用 canGoBack 控制返回按钮显隐")
|
||||
else:
|
||||
fail("没有 canGoBack")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n[6] 桥只暴露必要的方法(面越小越安全)")
|
||||
methods = re.findall(r"@JavascriptInterface\s+(?:override\s+)?fun\s+(\w+)", code)
|
||||
# ★ 期望集**显式列出**,加方法必须改这里 —— 这是刻意的:
|
||||
# 不这样的话"顺手多加一个 @JavascriptInterface"就没人拦得住,而桥的暴露面
|
||||
# 正是这块最该盯的东西。
|
||||
# v2.0.37 加了 sendToAi(用户要求"AI 自己能写进网页里的接口",
|
||||
# 让界面上选的值真的回到模型手里),所以现在是三个而不是两个。
|
||||
EXPECTED = ["close", "pick", "sendToAi"]
|
||||
if sorted(methods) == sorted(EXPECTED):
|
||||
ok(f"只有 {methods}(正好是期望的三个)")
|
||||
else:
|
||||
fail(f"@JavascriptInterface 暴露了 {methods} —— 期望 {EXPECTED}。"
|
||||
"如果是**有意**加的,请同时更新这个 EXPECTED 列表并写清理由")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
167
scripts/verify-dpkg-jnilibs.py
Normal file
167
scripts/verify-dpkg-jnilibs.py
Normal file
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""守住 `android/app/src/main/res` 里那几个 tar 包(`libdoubao-dpkg.so`)。
|
||||
|
||||
为什么不直接信任构建产物:
|
||||
「编译过了」在这条路上什么都不能说明 —— 出问题的地方全都是
|
||||
**编译成功、装上去才炸**(配置目录权限、架构名非法、维护脚本 shebang)。
|
||||
所以这里盯的是"打进 APK 的那几个字节到底长什么样"。
|
||||
|
||||
用法:
|
||||
python scripts/verify-dpkg-jnilibs.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
# Windows 控制台默认是 GBK,打印 ✓/✗ 会 UnicodeEncodeError
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
JNI = os.path.join(ROOT, "android", "app", "src", "main", "jniLibs")
|
||||
|
||||
EXPECT = {
|
||||
"x86_64": {"lib": "libdoubao-dpkg.so", "machine": 62, "arch_name": b"x86_64"},
|
||||
"arm64-v8a": {"lib": "libdoubao-dpkg.so", "machine": 183, "arch_name": b"aarch64"},
|
||||
}
|
||||
|
||||
PROGRAMS = {"dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"}
|
||||
|
||||
TAR_BLOCK = 512
|
||||
|
||||
fails = []
|
||||
warns = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def warn(m):
|
||||
warns.append(m)
|
||||
print(f" ! {m}")
|
||||
|
||||
|
||||
def read_tar(path):
|
||||
"""返回 [(名字, 内容)],只认 ustar 普通文件"""
|
||||
out = []
|
||||
with open(path, "rb") as f:
|
||||
while True:
|
||||
header = f.read(TAR_BLOCK)
|
||||
if len(header) < TAR_BLOCK or header == b"\0" * TAR_BLOCK:
|
||||
break
|
||||
name = header[0:100].split(b"\0")[0].decode("utf-8", "replace").strip()
|
||||
sizef = header[124:136].split(b"\0")[0].decode("ascii", "replace").strip()
|
||||
size = int(sizef, 8) if sizef else 0
|
||||
typ = header[156:157]
|
||||
prefix = header[345:500].split(b"\0")[0].decode("utf-8", "replace").strip()
|
||||
full = f"{prefix}/{name}" if prefix else name
|
||||
body = f.read(size)
|
||||
pad = (-size) % TAR_BLOCK
|
||||
if pad:
|
||||
f.read(pad)
|
||||
if typ in (b"0", b"\0") and not full.endswith("/"):
|
||||
out.append((full, body))
|
||||
return out
|
||||
|
||||
|
||||
def elf_machine(blob):
|
||||
"""ELF e_machine(小端)"""
|
||||
if blob[:4] != b"\x7fELF":
|
||||
return None
|
||||
return struct.unpack_from("<H", blob, 18)[0]
|
||||
|
||||
|
||||
def contains(hay, needle):
|
||||
return hay.find(needle) >= 0
|
||||
|
||||
|
||||
print("=== 校验 APK 里的自编 dpkg(jniLibs/libdoubao-dpkg.so)===")
|
||||
|
||||
for abi, spec in EXPECT.items():
|
||||
path = os.path.join(JNI, abi, spec["lib"])
|
||||
print(f"\n[{abi}] {os.path.relpath(path, ROOT)}")
|
||||
if not os.path.isfile(path):
|
||||
fail(f"文件不存在:{path}")
|
||||
continue
|
||||
|
||||
try:
|
||||
members = read_tar(path)
|
||||
except Exception as e:
|
||||
fail(f"读 tar 失败:{e}")
|
||||
continue
|
||||
|
||||
names = {n for n, _ in members}
|
||||
if names != PROGRAMS:
|
||||
fail(f"内容不对:期望 {sorted(PROGRAMS)},实际 {sorted(names)}")
|
||||
continue
|
||||
ok(f"tar 里有 {len(names)} 个程序({', '.join(sorted(names))})")
|
||||
|
||||
dpkg = dict(members)["dpkg"]
|
||||
|
||||
# ELF 架构
|
||||
m = elf_machine(dpkg)
|
||||
if m != spec["machine"]:
|
||||
fail(f"dpkg 的 e_machine={m},期望 {spec['machine']}")
|
||||
else:
|
||||
ok(f"ELF 架构正确(e_machine={m})")
|
||||
|
||||
# 运行时前缀解析 —— 没有它就等于没修
|
||||
if not contains(dpkg, b"/proc/self/exe"):
|
||||
fail("dpkg 里没有 /proc/self/exe(运行时前缀补丁没进去)")
|
||||
else:
|
||||
ok("有 /proc/self/exe(运行时前缀解析)")
|
||||
|
||||
# 架构名
|
||||
if not contains(dpkg, spec["arch_name"]):
|
||||
fail(f"dpkg 里没有架构名 {spec['arch_name'].decode()}")
|
||||
else:
|
||||
ok(f"架构名是 {spec['arch_name'].decode()}")
|
||||
|
||||
for stale in (b"amd64", b"arm64") if abi == "x86_64" else (b"amd64",):
|
||||
if contains(dpkg, stale):
|
||||
fail(f"dpkg 里还有 Debian 风格架构名 {stale.decode()}")
|
||||
break
|
||||
else:
|
||||
ok("没有 Debian 风格架构名")
|
||||
|
||||
# 重写函数要匹配的模式必须存在,否则脚本改不了
|
||||
if not contains(dpkg, b"/data/data/com.termux/files/usr"):
|
||||
fail("dpkg 里没有要匹配的旧前缀(维护脚本改写会失效)")
|
||||
else:
|
||||
ok("有维护脚本改写用的旧前缀模式")
|
||||
|
||||
# 不允许出现"编译死的配置目录"这种更长的路径
|
||||
if contains(dpkg, b"/data/data/com.termux/files/usr/etc/dpkg"):
|
||||
fail("dpkg 里还有编译死的配置目录(装上必 EACCES)")
|
||||
else:
|
||||
ok("没有编译死的配置目录")
|
||||
|
||||
# RUNPATH
|
||||
if not contains(dpkg, b"/data/data/com.doubao.lynxclone/files/usr/lib"):
|
||||
fail("dpkg 里没有指向前缀 lib 的 RUNPATH")
|
||||
else:
|
||||
ok("RUNPATH 指向前缀 lib")
|
||||
|
||||
# 静态链进去了就不该再 NEEDED libmd
|
||||
if contains(dpkg, b"libmd.so"):
|
||||
fail("dpkg 还依赖 libmd.so(应该静态链入)")
|
||||
else:
|
||||
ok("没有外部 libmd 依赖")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print(f"✅ 全部通过" + (f"({len(warns)} 条提示)" if warns else ""))
|
||||
164
scripts/verify-elf-patch.py
Normal file
164
scripts/verify-elf-patch.py
Normal file
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""★ 验证「原地改写二进制里写死的 com.termux 路径」这条路线真的成立。
|
||||
|
||||
背景:内置 Termux 的二进制是按真 Termux 的包名编译的,里面写死了
|
||||
`/data/data/com.termux/files/usr/...`。这些路径属于**另一个 App**,
|
||||
我们访问是 EACCES。之前靠环境变量 / apt.conf / LD_PRELOAD / dpkg --root
|
||||
一层层去绕,绕不完(见 docs/内置Termux-现状与坑.md)。
|
||||
|
||||
正解是**直接改字节**(Kotlin 侧见 termux/TermuxBinaries.kt)。
|
||||
这个脚本用从设备上拉下来的**真实二进制**验证四件事:
|
||||
|
||||
1. 真实的 ELF 里确实有这些串,而且**出现的形式**是什么样
|
||||
(是完整的 C 字符串,还是嵌在别的串里?)
|
||||
2. 匹配位置前后的**上下文**(决定怎么判"这是一个完整路径")
|
||||
3. 长度是不是真的能凑成一样(能否原地替换)
|
||||
4. 用 .rodata 的**重定位表 / 字符串引用**确认改完之后
|
||||
程序真的会用到新串(而不是某份拷贝/哈希)
|
||||
|
||||
用法:
|
||||
python scripts/verify-elf-patch.py # 扫 scripts/.tmp-termuxbin
|
||||
python scripts/verify-elf-patch.py <文件> [<文件>…]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
OLD = b"/data/data/com.termux"
|
||||
# 我们的包名。`/data/data/com.doubao.lynxclone` = 30 字节,比 OLD 短 0(见下)
|
||||
NEW_BASE = b"/data/data/com.doubao.lynxclone"
|
||||
TARGET_LEN = len(OLD)
|
||||
|
||||
GREEN, RED, YELLOW, DIM, RESET = "\033[32m", "\033[31m", "\033[33m", "\033[2m", "\033[0m"
|
||||
|
||||
pass_n = fail_n = 0
|
||||
|
||||
|
||||
def check(ok: bool, title: str, detail: str = "") -> None:
|
||||
global pass_n, fail_n
|
||||
if ok:
|
||||
pass_n += 1
|
||||
print(f" {GREEN}✓{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
|
||||
else:
|
||||
fail_n += 1
|
||||
print(f" {RED}✗{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
|
||||
|
||||
|
||||
def contexts(data: bytes) -> list[tuple[int, str, str]]:
|
||||
"""找出所有 OLD 出现的位置,返回 (偏移, 前文, 后文)。"""
|
||||
out = []
|
||||
i = data.find(OLD)
|
||||
while i != -1:
|
||||
before = data[max(0, i - 24):i]
|
||||
after = data[i + TARGET_LEN:i + TARGET_LEN + 24]
|
||||
out.append((i, repr(before), repr(after)))
|
||||
i = data.find(OLD, i + 1)
|
||||
return out
|
||||
|
||||
|
||||
def is_complete(match_at: int, data: bytes) -> bool:
|
||||
"""这个匹配是不是一个**完整的路径开头**(后面必须接 `/` 或字符串结束)。"""
|
||||
end = match_at + TARGET_LEN
|
||||
if end >= len(data):
|
||||
return True
|
||||
return data[end:end + 1] in (b"/", b"\x00")
|
||||
|
||||
|
||||
def is_boundary(match_at: int, data: bytes) -> bool:
|
||||
"""前面那个字节是不是一个合法的字符串起点。"""
|
||||
if match_at == 0:
|
||||
return True
|
||||
return data[match_at - 1:match_at] in (
|
||||
b"\x00", b" ", b"\t", b"\n", b"\r", b'"', b"'", b"=", b":", b"(", b",", b"[", b"<",
|
||||
)
|
||||
|
||||
|
||||
def scan(path: str) -> bool:
|
||||
name = os.path.basename(path)
|
||||
size = os.path.getsize(path)
|
||||
with open(path, "rb") as fh:
|
||||
data = fh.read()
|
||||
|
||||
is_elf = data[:4] == b"\x7fELF"
|
||||
print(f"\n{'=' * 72}\n{name} {size:,} 字节 {'ELF' if is_elf else '非 ELF'}")
|
||||
|
||||
hits = contexts(data)
|
||||
if not hits:
|
||||
check(True, "没有 com.termux 路径(这个文件本来就不需要改)")
|
||||
return True
|
||||
|
||||
print(f" {DIM}找到 {len(hits)} 处{RESET}")
|
||||
|
||||
complete = sum(1 for at, _, _ in hits if is_complete(at, data))
|
||||
bounded = sum(1 for at, _, _ in hits if is_boundary(at, data))
|
||||
both = sum(1 for at, _, _ in hits if is_complete(at, data) and is_boundary(at, data))
|
||||
|
||||
for at, before, after in hits[:6]:
|
||||
mark = "★" if (is_complete(at, data) and is_boundary(at, data)) else " "
|
||||
print(f" {mark} @0x{at:06x} …{before} [{OLD.decode()}] {after}…")
|
||||
if len(hits) > 6:
|
||||
print(f" {DIM}…还有 {len(hits) - 6} 处{RESET}")
|
||||
|
||||
check(complete == len(hits),
|
||||
"全部是完整路径(后面接 / 或 \\0)",
|
||||
f"{complete}/{len(hits)}" + ("" if complete == len(hits) else " ← 有嵌在长串里的,得靠上下文判断"))
|
||||
check(bounded == len(hits),
|
||||
"全部落在字符串起点(前面是 \\0/空白/引号/=/…)",
|
||||
f"{bounded}/{len(hits)}")
|
||||
check(both == len(hits),
|
||||
"两个条件都满足 → 可以无条件原地替换",
|
||||
f"{both}/{len(hits)}")
|
||||
|
||||
# ★ 长度:这是能不能原地改的硬条件
|
||||
check(len(NEW_BASE) <= TARGET_LEN,
|
||||
f"新路径长度 {len(NEW_BASE)} ≤ 旧 {TARGET_LEN}(差额补 {TARGET_LEN - len(NEW_BASE)} 个字符)",
|
||||
f"补出来 = {NEW_BASE.decode()}{'x' * (TARGET_LEN - len(NEW_BASE))}" if len(NEW_BASE) < TARGET_LEN else "正好等长")
|
||||
|
||||
# 模拟改写一次,确认改完不再有 OLD、也不破坏 NUL 结尾
|
||||
repl = NEW_BASE + b"x" * (TARGET_LEN - len(NEW_BASE))
|
||||
patched = bytearray(data)
|
||||
for at, _, _ in hits:
|
||||
patched[at:at + TARGET_LEN] = repl
|
||||
check(bytes(patched).find(OLD) == -1, "改写后文件里不再有旧路径")
|
||||
check(patched.count(b"\x00") == data.count(b"\x00"),
|
||||
"NUL 字节数不变(没有把字符串提前截断)",
|
||||
f"{data.count(b'\\x00')} → {patched.count(b'\\x00')}")
|
||||
|
||||
# ELF 结构没被动过
|
||||
if is_elf:
|
||||
check(bytes(patched[:64]) == data[:64], "ELF 头 64 字节未变")
|
||||
return both == len(hits)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("-")]
|
||||
if not args:
|
||||
d = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".tmp-termuxbin")
|
||||
if not os.path.isdir(d):
|
||||
print(f"没有 {d};先在设备上拉几个二进制下来:", file=sys.stderr)
|
||||
print(" adb shell run-as <包名> sh -c 'base64 files/usr/bin/curl' > curl.b64", file=sys.stderr)
|
||||
return 2
|
||||
args = [os.path.join(d, f) for f in sorted(os.listdir(d))]
|
||||
|
||||
print("验证:原地改写二进制里的 com.termux 路径")
|
||||
print(f" 旧 = {OLD.decode()} ({TARGET_LEN} 字节)")
|
||||
print(f" 新 = {NEW_BASE.decode()} ({len(NEW_BASE)} 字节,补 {TARGET_LEN - len(NEW_BASE)})")
|
||||
|
||||
clean = True
|
||||
for p in args:
|
||||
if os.path.isfile(p):
|
||||
clean &= scan(p)
|
||||
|
||||
print(f"\n{'=' * 72}")
|
||||
print(f"{GREEN if fail_n == 0 else RED}通过 {pass_n},失败 {fail_n}{RESET}")
|
||||
if clean:
|
||||
print(f"{GREEN}结论:所有匹配都是干净的完整路径,可以放心原地替换。{RESET}")
|
||||
else:
|
||||
print(f"{YELLOW}结论:有匹配嵌在更长的串里 —— 必须靠上下文判断,"
|
||||
f"否则会改坏别的路径。{RESET}")
|
||||
return 1 if fail_n else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
131
scripts/verify-extract-urls.py
Normal file
131
scripts/verify-extract-urls.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""测 extractUrls 认不认各种 URL 写法。
|
||||
|
||||
★ 为什么值得单独一个脚本:
|
||||
用户报「操作栏里应该有『打开网页』按钮,但没显示」。
|
||||
根因是 extractUrls 只认 `](` 紧挨着的 markdown 链接,
|
||||
**裸 URL(`见 https://x.com`)这种模型最常写的形式反而漏掉** ——
|
||||
返回空 → 按钮整个不显示。
|
||||
|
||||
★ 手法:**直接从 Kotlin 源码里把正则抠出来**,用 Python 的 re 跑
|
||||
(两边正则语法基本一致)。这样测的是真代码,不是"我凭记忆重写一遍"——
|
||||
第一版这个探针就是重写的,改了 Kotlin 之后它还在报旧结果,等于没测。
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
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__)))
|
||||
SRC = os.path.join(WS, "android", "app", "src", "main", "java",
|
||||
"com", "doubao", "lynxclone", "ui", "MarkdownText.kt")
|
||||
src = open(SRC, encoding="utf-8").read()
|
||||
|
||||
|
||||
def kotlin_regex(name: str) -> str:
|
||||
# ★ `\s*` 是必须的:源码里 `RE_MD_LINK =` 后面换行过(行太长),
|
||||
# 不加的话提取不到 —— 而报的是"找不到 RE_MD_LINK",
|
||||
# 看起来像"改了名字",其实是格式问题。
|
||||
m = re.search(rf'private val {name}\s*=\s*\n?\s*Regex\("""(.*?)"""\)', src, re.DOTALL)
|
||||
if not m:
|
||||
print(f"!! 源码里找不到 {name}")
|
||||
sys.exit(1)
|
||||
return m.group(1).strip()
|
||||
|
||||
|
||||
RE_MD = kotlin_regex("RE_MD_LINK")
|
||||
RE_BARE = kotlin_regex("RE_BARE_URL")
|
||||
|
||||
print("RE_MD_LINK =", RE_MD)
|
||||
print("RE_BARE_URL =", RE_BARE)
|
||||
print()
|
||||
|
||||
# Kotlin 的 `[^\]\n]` 在 Python 里要写成 `[^\]\n]`(一样)
|
||||
CLEAN_TAIL = "。,、;:!?)】》」』….,;:!?"
|
||||
|
||||
|
||||
def clean(raw: str) -> str:
|
||||
"""
|
||||
和 Kotlin 的 cleanUrl 等价。
|
||||
|
||||
★ 注意这里**没有**处理"成对括号保留"那条(Kotlin 里有)。
|
||||
`https://en.wikipedia.org/wiki/A_(b)` 正则已经整个吃掉、不需要补;
|
||||
Kotlin 那段是给"正则提前截断"的情况兜底的。
|
||||
测这一条时两边结果会一致,所以不影响。
|
||||
"""
|
||||
s = raw.strip().strip("<>\"'`")
|
||||
s = s.rstrip(CLEAN_TAIL)
|
||||
while s.endswith(")") and s.count(")") > s.count("("):
|
||||
s = s[:-1]
|
||||
while s.endswith("]") and s.count("]") > s.count("["):
|
||||
s = s[:-1]
|
||||
if not (s.startswith("http://") or s.startswith("https://")):
|
||||
return ""
|
||||
return s
|
||||
|
||||
|
||||
def extract(markdown: str):
|
||||
if "http://" not in markdown and "https://" not in markdown:
|
||||
return []
|
||||
out, labels = [], {}
|
||||
for m in re.finditer(RE_MD, markdown):
|
||||
label = m.group(1).strip().strip("[]")
|
||||
url = clean(m.group(2))
|
||||
if url:
|
||||
labels.setdefault(url, label)
|
||||
if url not in out:
|
||||
out.append(url)
|
||||
for m in re.finditer(RE_BARE, markdown):
|
||||
url = clean(m.group(0))
|
||||
if url and url not in out:
|
||||
out.append(url)
|
||||
return [(u, labels.get(u, "")) for u in out]
|
||||
|
||||
|
||||
CASES = [
|
||||
("标准 markdown", "[文档](https://example.com/a)", 1),
|
||||
("文字和括号之间有空格", "[文档] (https://example.com/a)", 1),
|
||||
("括号里有空格", "[文档]( https://example.com/a )", 1),
|
||||
("标题里有方括号", "[A[1]](https://example.com/a)", 1),
|
||||
("★ 裸 URL", "直接访问 https://example.com/a 就行", 1),
|
||||
("★ 中文标点紧跟", "见(https://example.com/a)。", 1),
|
||||
("★ 尖括号包裹", "<https://example.com/a>", 1),
|
||||
("★ 行尾的裸 URL", "链接是 https://example.com/a", 1),
|
||||
("★ 换行里的裸 URL", "第一行\nhttps://example.com/a\n第三行", 1),
|
||||
("多个链接", "[A](https://a.com) 和 [B](https://b.com)", 2),
|
||||
("markdown + 裸混排", "[A](https://a.com) 还有 https://b.com", 2),
|
||||
("同链接出现两次只算一个", "[A](https://a.com) 又说 https://a.com", 1),
|
||||
("中文标点不被吞进地址", "看 https://example.com/a,谢谢", 1),
|
||||
("带括号的地址", "[x](https://en.wikipedia.org/wiki/A_(b))", 1),
|
||||
("没有链接", "这段话里一个网址都没有", 0),
|
||||
("相对路径不算", "[文档](docs/x.md)", 0),
|
||||
]
|
||||
|
||||
print("=== 认得多少 ===")
|
||||
miss = 0
|
||||
for label, text, want in CASES:
|
||||
got = extract(text)
|
||||
okc = len(got) == want
|
||||
if not okc:
|
||||
miss += 1
|
||||
detail = ", ".join(f"{u}" + (f"[{l}]" if l else "") for u, l in got) or "(空)"
|
||||
print(f" {'✓' if okc else '✗'} {label:22s} 期望{want} 得到{len(got)}: {detail}")
|
||||
|
||||
# 链接文字要留住(列表里靠它区分同域名的多个链接)
|
||||
got = extract("[Example 官网](https://example.com) 和 [Example 中文](https://example.com/index-zh)")
|
||||
print()
|
||||
if len(got) == 2 and all(l for _, l in got):
|
||||
print(" ✓ 两条同域链接都拿到了各自的文字(列表里能分得清)")
|
||||
else:
|
||||
print(" ✗ 链接文字丢了:", got)
|
||||
miss += 1
|
||||
|
||||
print()
|
||||
if miss:
|
||||
print(f"❌ {miss} 项不合格")
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
@@ -504,6 +504,9 @@ if (!pyAll) {
|
||||
let same = 0;
|
||||
for (let i = 0; i < cases.length; i += 1) {
|
||||
const cs = cases[i];
|
||||
// pyOnly 的用例不参与对拍:Node 侧还没实现那几个节点类型,
|
||||
// 硬比只会得到实现差异(噪音),反而会掩盖真的行为不一致
|
||||
if (cs.pyOnly) continue;
|
||||
let nodeRes;
|
||||
try {
|
||||
nodeRes = await runOne('node', cs);
|
||||
|
||||
34
scripts/verify-ops.py
Normal file
34
scripts/verify-ops.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""核对引擎和界面的算子表是否一致。
|
||||
|
||||
加算子时"只加一边"已经犯过好几次:
|
||||
· 引擎加了 gte/lte/and/or/xor/shl/shr,界面 OPS_UI 没加(用户"没看到大于等于")
|
||||
· 引擎有 neg/not,界面也选不到
|
||||
加完算子先跑它,别等用户发现。
|
||||
"""
|
||||
import os, re, sys
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(WS, 'android', 'kernel'))
|
||||
import meeting as M
|
||||
KT = os.path.join(WS, 'android', 'app', 'src', 'main', 'java',
|
||||
'com', 'doubao', 'lynxclone', 'ui', 'MeetingsScreen.kt')
|
||||
src = open(KT, encoding='utf-8').read()
|
||||
m = re.search(r'OPS_UI = listOf\((.*?)\n\s*\)', src, re.S)
|
||||
ui = set(re.findall(r'"(\w+)"\s+to\s+"', m.group(1))) if m else set()
|
||||
eng = {o[0] for o in M.OPS}
|
||||
sb = re.search(r'private fun opSpec\(key: String\)(.*?)private fun opLabel', src, re.S)
|
||||
ss = sb.group(1) if sb else ''
|
||||
spec = set(re.findall(r'"(\w+)"', ss))
|
||||
has_else = 'else ->' in ss
|
||||
miss_ui = sorted(eng - ui)
|
||||
miss_spec = [] if has_else else sorted(ui - spec)
|
||||
covered = sorted(ui - spec) if has_else else []
|
||||
extra = sorted(ui - eng)
|
||||
print(' 引擎 OPS %d 个' % len(eng))
|
||||
print(' 界面 OPS_UI %d 个' % len(ui))
|
||||
print(' 界面 opSpec %d 个%s' % (len(spec), '(有 else 兜底)' if has_else else ''))
|
||||
print(' %s 引擎有、界面选项里没有: %s' % ('X' if miss_ui else 'v', miss_ui or '无'))
|
||||
print(' %s 界面有选项、opSpec 没定义类型: %s' % ('X' if miss_spec else 'v', miss_spec or '无'))
|
||||
if covered:
|
||||
print(' (%s 由 else 兜底,正常)' % covered)
|
||||
print(' %s 界面有、引擎不认: %s' % ('X' if extra else 'v', extra or '无'))
|
||||
sys.exit(1 if (miss_ui or miss_spec or extra) else 0)
|
||||
181
scripts/verify-patch-script.py
Normal file
181
scripts/verify-patch-script.py
Normal file
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""★ 盯住补刀脚本里那个"一个字母就能写坏 85 个二进制"的地方。
|
||||
|
||||
## 背景(真实事故)
|
||||
|
||||
`res/raw/doubao_patch.sh` 会在 dpkg 装完包之后跑,把新装包里的硬编码路径
|
||||
`/data/data/com.termux` 换成我们的。第一版用的是:
|
||||
|
||||
grep -rla "$OLD" "$P/bin" ... | while read f; do sed -i "s|$OLD|$NEW|g" "$f"; done
|
||||
|
||||
`-a` 把**二进制**也当文本,`sed` 改了文件长度 → ELF 内部偏移全废:
|
||||
|
||||
CANNOT LINK EXECUTABLE .../dpkg.real: empty/missing DT_HASH/DT_GNU_HASH
|
||||
in ".../dpkg.real" (new hash type from the future?)
|
||||
|
||||
一次写坏 **85 个**可执行文件,整个内置环境报废,只能「重置」。
|
||||
|
||||
根因是长度不等(`/data/data/com.termux` = 21 字节,
|
||||
`/data/data/com.doubao.lynxclone` = 30 字节)—— 这正是
|
||||
`scripts/verify-elf-patch.py` 早就验证过的那条结论。
|
||||
|
||||
**`-I`(大写,跳过二进制)和 `-a`(当成文本)只差一个字母。**
|
||||
这个脚本就是盯着它的,顺手把其它几条"必须成立"的性质一起验了。
|
||||
|
||||
用法:
|
||||
python scripts/verify-patch-script.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
WS = os.path.dirname(HERE)
|
||||
PATCH_SH = os.path.join(WS, "android/app/src/main/res/raw/doubao_patch.sh")
|
||||
WRAPPER_SH = os.path.join(WS, "android/app/src/main/res/raw/dpkg_wrapper.sh")
|
||||
INSTALLER = os.path.join(
|
||||
WS, "android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt"
|
||||
)
|
||||
|
||||
GREEN, RED, DIM, RESET = "\033[32m", "\033[31m", "\033[2m", "\033[0m"
|
||||
fail_n = 0
|
||||
|
||||
|
||||
def check(ok: bool, title: str, detail: str = "") -> bool:
|
||||
global fail_n
|
||||
if ok:
|
||||
print(f" {GREEN}✓{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
|
||||
else:
|
||||
fail_n += 1
|
||||
print(f" {RED}✗{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
|
||||
return ok
|
||||
|
||||
|
||||
def main() -> int:
|
||||
for p in (PATCH_SH, WRAPPER_SH, INSTALLER):
|
||||
if not os.path.isfile(p):
|
||||
print(f"{RED}找不到 {p}{RESET}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
patch = open(PATCH_SH, encoding="utf-8").read()
|
||||
wrapper = open(WRAPPER_SH, encoding="utf-8").read()
|
||||
installer = open(INSTALLER, encoding="utf-8").read()
|
||||
|
||||
print("检查补刀脚本(res/raw/doubao_patch.sh)")
|
||||
|
||||
# ---- 1. ★★★ 核心:只能对文本文件动手 ----
|
||||
print("\n【1】★ 只改文本文件(这一条是那次 85 个二进制的血账)")
|
||||
|
||||
code_lines = [ln for ln in patch.splitlines() if not ln.lstrip().startswith("#")]
|
||||
|
||||
# 文本判定:现在整段替换逻辑在 python 里,判定也跟着过去
|
||||
check("@PY@" in patch, "模板里有 @PY@ 占位符(干活的 python)")
|
||||
check('"@PY@"' in installer, "Kotlin 侧替换了 @PY@")
|
||||
check("bin/python3" in installer, "@PY@ 指向 $PREFIX/bin/python3")
|
||||
check("PYEOF" in patch, "替换逻辑是一段内嵌 python")
|
||||
check("os.walk" in patch, "用 os.walk 遍历(不依赖 find/grep)")
|
||||
check('b"\\0"' in patch or "\\0" in patch, "python 侧做「含 NUL 就跳过」的二进制过滤")
|
||||
check('startswith(b"#!")' in patch, "shebang 模式要求这一行以 `#!` 开头")
|
||||
|
||||
# `grep -a` 是当初那个 bug 的字面写法
|
||||
bad_a = [ln for ln in code_lines if re.search(r"grep\s+-[a-zA-Z]*a[a-zA-Z]*\s", ln)]
|
||||
check(not bad_a, "代码里没有 `grep -a`(-a 就是当初那个 bug)", str(bad_a) if bad_a else "")
|
||||
|
||||
# ---- 1b. ★★★ 两个 OLD 不一样(这是这套东西里最容易绕晕的一条) ----
|
||||
print("\n【1b】★★ 两个 OLD 的取值")
|
||||
# 补刀脚本(改 shebang)用**长** OLD,带上 `/files/usr`:
|
||||
# #!/data/data/com.termux/files/usr/bin/python3.14
|
||||
# → #!<prefix>/bin/python3.14 ✅
|
||||
# 只换 `/data/data/com.termux` 会得到
|
||||
# #!<pkg>/files/files/usr/bin/python3.14 ❌ 多一层
|
||||
# 因为 NEW 自带一个 `files`,原文里又有一个 `/files`。
|
||||
#
|
||||
# Kotlin 侧 rewritePrefixes 换的是**整段** `/data/data/com.termux` → dataDir,
|
||||
# 换出 `<pkg>/files/files/usr/...` 这种形状 —— 那个由沙箱里
|
||||
# `"files" to ".."` 那条链接住,不用改文本。
|
||||
m = re.search(r'\.replace\("@OLD@",\s*"([^"]+)"\)', installer)
|
||||
check(bool(m), "找得到 @OLD@ 的替换")
|
||||
if m:
|
||||
old = m.group(1)
|
||||
check(old == "/data/data/com.termux/files/usr",
|
||||
"★ 补刀脚本的 @OLD@ 带 `/files/usr`(长的那一个)", old)
|
||||
m2 = re.search(r'\.replace\("@NEW@",\s*([^)]+)\)', installer)
|
||||
check(bool(m2), "找得到 @NEW@ 的替换")
|
||||
if m2:
|
||||
expr = m2.group(1).strip()
|
||||
check("prefix" in expr and "filesDir" not in expr,
|
||||
"★ 补刀脚本的 @NEW@ 是 prefix", expr)
|
||||
# 沙箱里必须有接住"多一层 files"的那条链
|
||||
check('"files" to ".."' in installer,
|
||||
'沙箱表里有 `"files" to ".."`(接住一次文本替换产生的 files/files/usr 形状)')
|
||||
|
||||
# ---- 2. 绝不改自己 ----
|
||||
print("\n【2】绝不改自己")
|
||||
check('name == "doubao-patch"' in patch, "python 侧有跳过 doubao-patch 的判断")
|
||||
|
||||
# ---- 3. 权限:保住原来的权限位 ----
|
||||
print("\n【3】权限处理")
|
||||
# python 侧用 os.stat 取权限位、写完再 os.chmod 回去 —— 比 shell 那边干净
|
||||
check("os.chmod" in patch, "写回前用 os.chmod 保住原权限位")
|
||||
check("st_mode" in patch, "权限位取自 os.stat")
|
||||
check("was_x" not in patch, "不再靠 shell 手工记 was_x(那套已经不用了)")
|
||||
|
||||
# ---- 4. 占位符:模板和替换代码要对得上 ----
|
||||
print("\n【4】占位符对得上(模板改了但替换没改,会写出字面量 @XXX@)")
|
||||
for name, text in (("doubao_patch.sh", patch), ("dpkg_wrapper.sh", wrapper)):
|
||||
holders = set(re.findall(r"@([A-Z]+)@", text))
|
||||
check(bool(holders), f"{name} 里的占位符:{sorted(holders)}")
|
||||
for h in holders:
|
||||
check(
|
||||
f'"@{h}@"' in installer,
|
||||
f"{name} 的 @{h}@ 在 TermuxInstaller 里有替换",
|
||||
)
|
||||
|
||||
# ---- 5. wrapper:**不能**有 --root(见下) ----
|
||||
print("\n【5】dpkg wrapper 的关键参数")
|
||||
# ★★ 这一条守的是一个**反直觉**的结论,而且我一开始写反了:
|
||||
# 给 dpkg 传 `--root=$PREFIX` 看似能解决"编译死的绝对路径",
|
||||
# 但它会把 `.deb` 清单里的**安装路径**也拼上 root,于是包装到
|
||||
# `<prefix>/data/data/com.termux/files/usr/bin/`(影子目录),
|
||||
# 而 apt 照样报 "Setting up ... 成功" —— 静悄悄地装错地方。
|
||||
# 正解是 `--instdir=/` + 在 prefix 里把那些路径**逐目录接回真实位置**。
|
||||
root_flags = [
|
||||
ln for ln in wrapper.splitlines()
|
||||
if not ln.lstrip().startswith("#") and re.search(r"--root\s*=", ln)
|
||||
]
|
||||
check(not root_flags, "没有 --root(它会连安装路径一起拼 root,导致装到影子目录)",
|
||||
str(root_flags) if root_flags else "")
|
||||
check("--instdir=/" in wrapper, "带 --instdir=/(按 .deb 清单的原路径安装)")
|
||||
check("--force-script-chrootless" in wrapper, "带 --force-script-chrootless(Android 不能 chroot)")
|
||||
check(wrapper.startswith("#!/system/bin/sh"), "shebang 是 /system/bin/sh(内核解析,必须真实存在)")
|
||||
check("LD_LIBRARY_PATH" in wrapper, "export 了 LD_LIBRARY_PATH")
|
||||
|
||||
# ---- 5b. 维护脚本的 shebang:只换路径,不换解释器 ----
|
||||
print("\n【5b】维护脚本的 shebang(★ 只换路径,别动解释器)")
|
||||
# ★ 两个方向都错过,所以两个方向都要守:
|
||||
# ① 什么都不改 → `#!/data/data/com.termux/...` 指向不存在的解释器:
|
||||
# dpkg: unable to execute .../openssh.postinst: No such file or directory
|
||||
# ② 无脑换成 bash → 把 `bin/pip` 这种 **Python 脚本**也改成 bash:
|
||||
# bin/pip: line 2: import: command not found
|
||||
# 正确:**维护脚本**换成 Termux 的 bash(它们正文是 bash 语法);
|
||||
# **其他脚本**只做路径替换。
|
||||
check("bin/bash" in installer, "Kotlin 把维护脚本的 shebang 指到 $PREFIX/bin/bash")
|
||||
check("var/lib/dpkg/info/" in installer, "Kotlin 只对 var/lib/dpkg/info/ 下的脚本特殊处理")
|
||||
check("shebang" in patch and "mode" in patch, "补刀脚本有 shebang 模式(unpack 后、configure 前用)")
|
||||
|
||||
# ---- 6. 装了包要能自动补刀 ----
|
||||
print("\n【6】自动补刀挂上了")
|
||||
check("doubao-patch" in wrapper, "wrapper 里会调 doubao-patch")
|
||||
check("exit $rc" in wrapper or "exit ${rc}" in wrapper, "补刀失败不影响 dpkg 的退出码")
|
||||
|
||||
print(f"\n{'=' * 72}")
|
||||
print(f"{GREEN if fail_n == 0 else RED}失败 {fail_n}{RESET}")
|
||||
if fail_n == 0:
|
||||
print(f"{DIM}这个脚本守着的是一条真实事故:-a 和 -I 差一个字母,代价是 85 个二进制。{RESET}")
|
||||
return 1 if fail_n else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
205
scripts/verify-sandbox-paths.py
Normal file
205
scripts/verify-sandbox-paths.py
Normal file
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""验证「沙箱路径接通表」和 dpkg 实际要走的路径对得上。
|
||||
|
||||
## 为什么需要这个脚本
|
||||
|
||||
内置 Termux 的所有二进制都按真 Termux 的包名编译,里面写死:
|
||||
|
||||
/data/data/com.termux/files/usr/...
|
||||
|
||||
我们给 dpkg 传了 `--root=$PREFIX`,dpkg 就把这些路径统统拼在 root 后面,
|
||||
于是它真正要去读的是:
|
||||
|
||||
$PREFIX/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d
|
||||
|
||||
**这个目录必须存在**,否则(用户真机上实测):
|
||||
|
||||
dpkg: error: error opening configuration directory
|
||||
"/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
|
||||
E: Sub-process /data/user/0/com.doubao.lynxclone/files/usr/bin/dpkg
|
||||
returned an error code (2)
|
||||
|
||||
`TermuxInstaller.linkLegacyPrefix()` 里有一张 `map` 表,把每条编译死的
|
||||
路径接回我们自己的目录。**那张表是手写的** —— 漏一条就又是一轮"某个功能
|
||||
莫名其妙报权限错误"。这个脚本做两件事:
|
||||
|
||||
1. 把表**解析出来**(从 Kotlin 源码里),逐条检查:
|
||||
· 左边(沙箱路径)的每一层父目录都能被建出来
|
||||
· 右边(真实目录)在 prefix 里有意义(不是凭空造的)
|
||||
2. 把**已知会出现的编译死路径**(从真二进制里 dump 出来的)拿去和表对照,
|
||||
报出"dpkg/apt 会去读、但我们没接通"的
|
||||
|
||||
用法:
|
||||
python scripts/verify-sandbox-paths.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
WS = os.path.dirname(HERE)
|
||||
INSTALLER = os.path.join(
|
||||
WS, "android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt"
|
||||
)
|
||||
|
||||
GREEN, RED, YELLOW, DIM, RESET = "\033[32m", "\033[31m", "\033[33m", "\033[2m", "\033[0m"
|
||||
|
||||
fail_n = 0
|
||||
|
||||
|
||||
def check(ok: bool, title: str, detail: str = "") -> bool:
|
||||
global fail_n
|
||||
if ok:
|
||||
print(f" {GREEN}✓{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
|
||||
else:
|
||||
fail_n += 1
|
||||
print(f" {RED}✗{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
|
||||
return ok
|
||||
|
||||
|
||||
def parse_map(src: str) -> list[tuple[str, str]]:
|
||||
"""从 linkLegacyPrefix() 里把 `val map = listOf("a" to "b", ...)` 解析出来。"""
|
||||
m = re.search(r"val map = listOf\((.*?)\n\s*\)", src, re.S)
|
||||
if not m:
|
||||
raise SystemExit("在 TermuxInstaller.kt 里找不到 linkLegacyPrefix 的 map 表")
|
||||
body = m.group(1)
|
||||
pairs = re.findall(r'"([^"]+)"\s+to\s+"([^"]+)"', body)
|
||||
if not pairs:
|
||||
raise SystemExit("map 表解析出来是空的 —— 正则要跟着源码改")
|
||||
return pairs
|
||||
|
||||
|
||||
def covered(path: str, table: set[str]) -> bool:
|
||||
"""这条路径**能不能解析得到** —— 它自己接通了,或者它的某个祖先接通了。
|
||||
|
||||
★ 为什么要判祖先:`etc/dpkg/dpkg.cfg.d` 不需要单独接一条链 ——
|
||||
`etc/dpkg` 整条已经链到真实目录了,子路径自然跟着通。
|
||||
早先的表是逐条列的,现在改成"接整棵子树",所以判据也得跟着放宽,
|
||||
否则脚本会报一堆**假**的"缺"。
|
||||
"""
|
||||
parts = path.split("/")
|
||||
for i in range(len(parts), 0, -1):
|
||||
if "/".join(parts[:i]) in table:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
with open(INSTALLER, encoding="utf-8") as fh:
|
||||
src = fh.read()
|
||||
|
||||
print("验证沙箱路径接通表")
|
||||
print(f" 源码:{os.path.relpath(INSTALLER, WS)}")
|
||||
|
||||
pairs = parse_map(src)
|
||||
print(f"\n表里有 {len(pairs)} 条:\n")
|
||||
|
||||
# ---- 1. 表的形状 ----
|
||||
print("【1】沙箱侧路径的形状")
|
||||
for legacy_rel, real_rel in pairs:
|
||||
legacy = "/data/data/com.termux/files/usr/" + legacy_rel
|
||||
real = "/files/usr/" + real_rel
|
||||
print(f" {legacy:<62} → {real}")
|
||||
|
||||
# ★ 左边只有**几种合法形状**:
|
||||
# files/usr ← 折叠用:把 /data/data/com.termux/files/usr 折成 prefix
|
||||
# files ← 兜底:接住"一次文本替换"必然产生的 files/files/usr 形状
|
||||
# <Y> ← 二进制里编译死的 /data/data/com.termux/<Y>
|
||||
# 出现别的形状说明有人"顺手"加了一条没依据的 —— 那正是当初
|
||||
# "包装到影子目录"那个 bug 的来源。
|
||||
OK_TOP = {
|
||||
"bin", "lib", "libexec", "etc", "include", "share", "var", "tmp", "home",
|
||||
}
|
||||
wrong = [
|
||||
l for l, _ in pairs
|
||||
if not (l == "files" or l == "files/usr" or l.startswith("files/usr/")
|
||||
or l.split("/")[0] in OK_TOP)
|
||||
]
|
||||
check(not wrong, "左边的形状都在允许集合里(files[/usr[/…]] 或 prefix 根下的标准目录)",
|
||||
str(wrong) if wrong else "")
|
||||
check("files/usr" in {l for l, _ in pairs},
|
||||
"有 `files/usr → .` 这条折叠(形状 A 折回 prefix)")
|
||||
check("files" in {l for l, _ in pairs},
|
||||
"有 `files → ..` 这条兜底(接住 files/files/usr 形状)")
|
||||
|
||||
# ---- 2. 右边是"真实存在的目录"还是"凭空造的" ----
|
||||
print("\n【2】右边指向的目录")
|
||||
# prefix 里 bootstrap 一定会有的目录(真实存在的)
|
||||
KNOWN_REAL = {
|
||||
".", "../home",
|
||||
"bin", "lib", "libexec", "etc", "include", "share", "tmp", "var",
|
||||
"etc/dpkg", "etc/dpkg/dpkg.cfg.d", "etc/apt", "etc/apt/apt.conf.d",
|
||||
"etc/tls", "etc/termux",
|
||||
"var/lib", "var/lib/dpkg", "var/lib/apt",
|
||||
"var/cache", "var/cache/apt", "var/log",
|
||||
}
|
||||
for _, real_rel in pairs:
|
||||
if real_rel == "../home":
|
||||
continue
|
||||
if real_rel not in KNOWN_REAL:
|
||||
# 不在已知集合里不算失败(bootstrap 版本会变),但要提一句
|
||||
print(f" {YELLOW}?{RESET} {real_rel} {DIM}(不在已知集合里,确认一下 prefix 下真有这个目录){RESET}")
|
||||
check(True, "已逐条过目", f"{len(pairs)} 条")
|
||||
|
||||
# ---- 3. ★ 核心:dpkg / apt 真正会去读的路径,表里有没有 ----
|
||||
#
|
||||
# 这些是从真二进制里 dump 出来的(见 scripts/verify-elf-patch.py
|
||||
# 的输出:所有匹配都是 `/data/data/com.termux` + `/files/usr/...`)。
|
||||
print("\n【3】★ 二进制里实际写死、且会被读的路径")
|
||||
MUST_HAVE = [
|
||||
# dpkg:配置目录(就是用户在真机上卡住的那一条)
|
||||
"etc/dpkg/dpkg.cfg.d",
|
||||
"etc/dpkg",
|
||||
# apt:Dir::Etc::parts 指向这里,读不到就 "Unable to determine
|
||||
# a suitable packaging system type"
|
||||
"etc/apt/apt.conf.d",
|
||||
"etc/apt",
|
||||
# 证书:curl 报 (77) error setting certificate file
|
||||
"etc/tls",
|
||||
# pkg 的源选择靠它(不看 sources.list)
|
||||
"etc/termux",
|
||||
# dpkg 的数据库
|
||||
"var/lib/dpkg",
|
||||
"var/lib/apt",
|
||||
# 临时目录:apt 报 Couldn't create temporary file .../usr/tmp/...
|
||||
"tmp",
|
||||
]
|
||||
table = {l for l, _ in pairs}
|
||||
missing = [p for p in MUST_HAVE if not covered(p, table)]
|
||||
for p in MUST_HAVE:
|
||||
ok = covered(p, table)
|
||||
mark = f"{GREEN}✓{RESET}" if ok else f"{RED}✗{RESET}"
|
||||
own = "" if p in table else f"{DIM}(由父目录覆盖){RESET}"
|
||||
print(f" {mark} {p} {own}")
|
||||
check(not missing, "编译死路径全都通了", f"缺 {missing}" if missing else "")
|
||||
|
||||
# ---- 4. bash 的 login_shell(写在 ELF 里,rewritePrefixes 改不到)----
|
||||
print("\n【4】其他被写进二进制的路径")
|
||||
# verify-elf-patch.py 在 bash 里 dump 到的:
|
||||
# /data/data/com.termux/files/home ← login_shell
|
||||
# /data/data/com.termux/files/usr/tmp
|
||||
# /data/data/com.termux/files/usr/bin/sh
|
||||
# /data/data/com.termux/files/usr/etc/profile
|
||||
# /data/data/com.termux/share/glib-2.0/schemas ← glib(实测报过错)
|
||||
check("home" in table, "home 已接通(bash 的 login_shell 用它)")
|
||||
# ★ 形状 A(带 files/usr)靠 `files/usr → .` 折叠 + 下面这些条目一起成立。
|
||||
# `bin/ lib/ share/` 这些**没有 files/usr 前缀**的条目同时也是给形状 B 用的
|
||||
# —— glib 报的 `/data/data/com.termux/share/glib-2.0/schemas` 就是形状 B,
|
||||
# 当初正是因为表里只有形状 A,才报 "No such file or directory"。
|
||||
for extra, why in [
|
||||
("bin", "可执行文件(dpkg 解包落点 / PATH 查找)"),
|
||||
("lib", "共享库"),
|
||||
("share", "★ 数据目录 —— glib 的 schema 走这条(形状 B)"),
|
||||
("include", "头文件"),
|
||||
]:
|
||||
check(extra in table, f"{extra}/ 已接通({why})")
|
||||
|
||||
print(f"\n{'=' * 72}")
|
||||
print(f"{GREEN if fail_n == 0 else RED}失败 {fail_n}{RESET}")
|
||||
return 1 if fail_n else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
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("✅ 全部通过")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user