AI 界面能力:主动弹界面 / 弹窗 / 永久结束对话 (v2.0.35)
三个工具,**默认关**(「技能」页可开)。都是 AI 主动驱动界面,
属于"打扰性"能力 —— 装好就默认打开是产品事故。
## show_ui —— AI 自己写 HTML 弹一个全屏界面
有些东西用文字说不清:一张算出来的图表、排版好的报告卡片、宽对比表。
以前模型只能吐 markdown,表格一宽就乱。现在它能直接写 HTML。
· html 写**片段**即可,自动套一层带样式的骨架(暗色主题、表格、代码块),
模型不用每次重复写 viewport/字体/边距;想完全控制传 full_html=true
· **不阻塞**:弹出来就返回,用户看完自己关(展示语义,不该卡住对话)
· 界面里可以放 `<button data-doubao-result="值">`,用户点了那个值回到模型手里
★ 两个安全决定:
1. **禁 JS**。允许 JS 的话模型生成的一段脚本就能拿到 `@JavascriptInterface`
那个桥,等于把 App 内部接口暴露给模型。纯 CSS 足够渲染内容。
2. **可点按钮不用 JS**:App 侧把 `data-doubao-result` 做**纯字符串替换**,
改成 `doubao://pick?value=...` 链接,由 WebViewClient 拦下来。
## ask_user —— 弹选择框,等用户选完再继续
· **阻塞**(最多 120 秒):问询语义,必须拿到答案才能继续。
安卓侧用 CountDownLatch 等,跟已有的 pickFile 同一套路。
· 超时必须有 —— 用户可能锁屏走了,不能让内核工作线程永远挂着
· options 两种写法都收:对象数组 `[{label,value,description}]`
和**裸字符串数组** `["A","B"]`(模型经常这么写,只认一种就平白报错)
· 支持多选(multiple=true),选项超过 8 个自动截断并告诉模型
## end_conversation —— 永久结束这次对话
**用户明确要求的界面**:屏幕中间一个横幅,写 AI 关闭的原因。
· 落盘(PATCH /api/conversations/<id> 写 `ended` / `endedReason`),
不是界面状态 —— 只放 Compose 里的话一刷新就没了,用户重进会看到
一个能继续输入的框,而模型以为自己已经结束了
· 输入框整个不渲染,换成居中的横幅:「这次对话已结束」+ 原因 + 「开始新对话」
· 拿不到对话 id 时**明确报错**,绝不假装成功
## 动画(用户要求)
· HTML 界面:从中心长大 + 淡入(像开一扇门),退出反向
· 选择弹窗:从下方滑上来 + 淡入 + 轻微放大;遮罩淡入
· 结束横幅:从下方滑到**屏幕中间**停住 + 淡入 + 轻微放大,**不自动消失**
(它是状态不是提示,消失了用户就不知道为什么发不出消息)
· 选项选中:弹性放大 + 蓝底 + 勾
## 开关(两道拦截)
settings.uiTools.enabled,默认 false。
① 关掉时工具**对模型隐藏**(build_tool_defs 里滤掉)
② 关掉时即使模型硬编名字**也拒绝执行** —— 只做①的话,用户关掉之后
模型仍可能从历史消息里学会这个名字再调一次
界面能力的用法说明**只在开关打开时**才追加到系统提示词 —— 写进
DEFAULT_SYSTEM_PROMPT 的话会被存进用户的 settings.json,
关着的时候还在教模型"你可以用 show_ui"。
## 顺带修的两个真 bug
1. **thread-local 不跨线程**(这个最隐蔽)
`run_with_timeout` 把工具丢到**新线程**里跑,而 `threading.local()`
不跨线程继承 —— 于是工具照常执行(参数都对),只有"当前是哪次对话"
拿不到,`end_conversation` 报"拿不到当前对话 id"。
我一开始以为是 app.py 没传 conversationId,查了一圈才发现是线程。
修法:`run_python_tool` 执行前把父线程的上下文搬进工作线程。
2. **/api/tools/run 传的是假 settings**
以前传 `{'security': {'mode': 'open'}}` 空壳(为了"手动试运行不受安全模式
限制"),但界面工具的开关也在 settings 里 —— 于是用户在技能页点"试运行",
明明开关是开的却收到"已关闭"。改成拿真实设置、只覆盖 security。
## 验证
`scripts/verify-ui-tools.py`(34 项)守:开关默认关、两道拦截都在、
选项两种写法都收、拿不到对话 id 必须报错、**上下文能跨线程**、
提示词按开关追加。`scripts/probe-ai-surfaces.py` 打
`adb forward` 之后的内核接口做端到端。
真机实测(Android 14 x86_64):
show_ui → 界面渲染正常(标题栏 + 暗色表格 + 可点按钮)
ask_user 单选 → 等 21s,返回 {"choice":"B","values":["B"],"timeout":false}
ask_user 多选 → 选 2 个,返回 {"values":["python","git"]}
end_conversation → ended=True 落盘,横幅显示原因
This commit is contained in:
@@ -30,8 +30,8 @@ android {
|
|||||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||||
* 改小了会装不上)。
|
* 改小了会装不上)。
|
||||||
*/
|
*/
|
||||||
versionCode = 234
|
versionCode = 235
|
||||||
versionName = "2.0.34"
|
versionName = "2.0.35"
|
||||||
|
|
||||||
ndk {
|
ndk {
|
||||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||||
|
|||||||
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) {
|
if (port != null && port > 0) {
|
||||||
client.baseUrl = "http://127.0.0.1:$port"
|
client.baseUrl = "http://127.0.0.1:$port"
|
||||||
|
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||||
|
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||||
|
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||||
|
KernelHost.set(port)
|
||||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
|
|||||||
@@ -20,7 +20,10 @@ import android.provider.OpenableColumns
|
|||||||
import com.chaquo.python.Python
|
import com.chaquo.python.Python
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
import com.doubao.lynxclone.termux.AiSurface
|
||||||
import com.doubao.lynxclone.termux.TermuxShell
|
import com.doubao.lynxclone.termux.TermuxShell
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.concurrent.CountDownLatch
|
import java.util.concurrent.CountDownLatch
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
@@ -67,6 +70,14 @@ class NativeBridge(private val activity: Activity) {
|
|||||||
req.optString("cwd"),
|
req.optString("cwd"),
|
||||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||||
)
|
)
|
||||||
|
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
|
||||||
|
//
|
||||||
|
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
|
||||||
|
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
|
||||||
|
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
|
||||||
|
"ui_screen" -> uiScreen(req)
|
||||||
|
"ui_dialog" -> uiDialog(req)
|
||||||
|
"end_conversation" -> endConversation(req)
|
||||||
else -> JSONObject().put("error", "未知 action:$action")
|
else -> JSONObject().put("error", "未知 action:$action")
|
||||||
}
|
}
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
@@ -74,6 +85,116 @@ class NativeBridge(private val activity: Activity) {
|
|||||||
}.toString()
|
}.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||||
|
*
|
||||||
|
* **不阻塞**:弹出来就返回,用户看完自己关。理由见 [AiSurface.showScreen]。
|
||||||
|
*/
|
||||||
|
private fun uiScreen(req: JSONObject): JSONObject {
|
||||||
|
val html = req.optString("html")
|
||||||
|
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||||
|
val s = AiSurface.showScreen(
|
||||||
|
html = html,
|
||||||
|
title = req.optString("title"),
|
||||||
|
fullHtml = req.optBoolean("full_html", false),
|
||||||
|
conversationId = req.optString("conversationId"),
|
||||||
|
)
|
||||||
|
return JSONObject().put("ok", true).put("id", s.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun deviceInfo(): JSONObject {
|
private fun deviceInfo(): JSONObject {
|
||||||
val stat = StatFs(Environment.getDataDirectory().path)
|
val stat = StatFs(Environment.getDataDirectory().path)
|
||||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
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 界面。**不阻塞** —— 弹出来就返回,用户看完自己关。
|
||||||
|
*
|
||||||
|
* ★ 为什么不做成阻塞:`show_ui` 是"展示"语义,用户可能盯着看很久,
|
||||||
|
* 把内核线程占住没有意义(而且模型这时也没别的事可做,但万一它想
|
||||||
|
* 连续弹两个界面就会被卡死)。要阻塞的语义用 [ask]。
|
||||||
|
*/
|
||||||
|
fun showScreen(html: String, title: String, fullHtml: Boolean, conversationId: String): Screen {
|
||||||
|
val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId)
|
||||||
|
screen = s
|
||||||
|
notify("screen")
|
||||||
|
Log.i(TAG, "AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}")
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 用户在界面上点了带 `data-doubao-result` 的按钮(WebView 的 JS 桥转进来) */
|
||||||
|
fun screenResult(value: String) {
|
||||||
|
Log.i(TAG, "界面里点了:$value")
|
||||||
|
// 界面上的点击不阻塞任何人,所以只通知一下、让界面记一笔
|
||||||
|
lastScreenResult = value
|
||||||
|
notify("screenResult")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var lastScreenResult: String = ""
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** 用户把界面关掉了 */
|
||||||
|
fun closeScreen() {
|
||||||
|
screen = null
|
||||||
|
notify("screen")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 弹窗
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 弹一个选择弹窗,**阻塞**到用户选完或超时。
|
||||||
|
*
|
||||||
|
* ★ 超时是必须的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||||
|
* 而且因为 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")
|
||||||
|
}
|
||||||
|
}
|
||||||
466
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
466
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
@@ -0,0 +1,466 @@
|
|||||||
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.graphics.Color as AndroidColor
|
||||||
|
import android.webkit.JavascriptInterface
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
|
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.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.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) {
|
||||||
|
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||||
|
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||||
|
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||||
|
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||||
|
val shown = screen ?: last
|
||||||
|
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
Box(
|
||||||
|
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AiWebView(shown, onResult)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 渲染 AI 写的 HTML。
|
||||||
|
*
|
||||||
|
* ## 两个安全/健壮性决定
|
||||||
|
*
|
||||||
|
* 1. **禁 JS**:AI 写的 HTML 是"内容",不是"程序"。允许 JS 的话它会拿到
|
||||||
|
* `@JavascriptInterface` 那个桥,等于把 App 的内部接口暴露给一段
|
||||||
|
* 模型生成的脚本。禁掉之后照样能渲染表格/图表(纯 CSS 足够),
|
||||||
|
* 而"可点按钮"用下面 data 属性的方式实现,不需要 JS。
|
||||||
|
*
|
||||||
|
* 2. **可点按钮不用 JS 实现**:给 WebView 装一个自定义 `WebViewClient`,
|
||||||
|
* 在 `shouldOverrideUrlLoading` 里拦 `doubao://pick?value=...` 这种链接。
|
||||||
|
* 界面里写 `<button data-doubao-result="值">` 时,注入的一小段 CSS
|
||||||
|
* 做不到跳链接 —— 所以改成由 App 侧统一把 `data-doubao-result`
|
||||||
|
* 换成 `<a href="doubao://pick?...">`。**这是纯字符串替换,不跑 JS。**
|
||||||
|
*/
|
||||||
|
@SuppressLint("SetJavaScriptEnabled")
|
||||||
|
@Composable
|
||||||
|
private fun AiWebView(screen: AiSurface.Screen, onResult: (String) -> Unit) {
|
||||||
|
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||||
|
AndroidView(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
factory = { ctx ->
|
||||||
|
WebView(ctx).apply {
|
||||||
|
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||||
|
settings.javaScriptEnabled = false // 见上面第 1 条
|
||||||
|
settings.domStorageEnabled = false
|
||||||
|
settings.allowFileAccess = false
|
||||||
|
settings.allowContentAccess = false
|
||||||
|
isVerticalScrollBarEnabled = true
|
||||||
|
webViewClient = object : WebViewClient() {
|
||||||
|
override fun shouldOverrideUrlLoading(
|
||||||
|
view: WebView?,
|
||||||
|
url: String?,
|
||||||
|
): Boolean {
|
||||||
|
val u = url ?: return false
|
||||||
|
if (u.startsWith("doubao://pick")) {
|
||||||
|
val v = android.net.Uri.decode(
|
||||||
|
android.net.Uri.parse(u).getQueryParameter("value") ?: "",
|
||||||
|
)
|
||||||
|
if (v.isNotEmpty()) onResult(v)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// 外链不在这个 WebView 里开(没有浏览器能力,也没必要)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把 `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; }
|
||||||
|
.db-btn {
|
||||||
|
display: inline-block; margin: 6px 8px 0 0; padding: 10px 16px;
|
||||||
|
background: #2a2d34; color: #e8eaed !important; text-decoration: none;
|
||||||
|
border-radius: 10px; font-size: 15px;
|
||||||
|
}
|
||||||
|
</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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -112,6 +112,25 @@ fun AppRoot(
|
|||||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
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) },
|
||||||
|
)
|
||||||
|
AiDialogOverlay(
|
||||||
|
dialog = vm.aiDialog,
|
||||||
|
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import com.doubao.lynxclone.data.MeetingEvent
|
|||||||
import com.doubao.lynxclone.data.MeetingMeta
|
import com.doubao.lynxclone.data.MeetingMeta
|
||||||
import com.doubao.lynxclone.data.StreamEvent
|
import com.doubao.lynxclone.data.StreamEvent
|
||||||
import com.doubao.lynxclone.data.ToolTrace
|
import com.doubao.lynxclone.data.ToolTrace
|
||||||
|
import com.doubao.lynxclone.termux.AiSurface
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -53,8 +54,86 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
/** 模型 / 思考强度面板(底部升起) */
|
/** 模型 / 思考强度面板(底部升起) */
|
||||||
var modelPickerOpen by mutableStateOf(false)
|
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
|
||||||
|
|
||||||
private var chatJob: AtomicBoolean? = 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 的界面里点了带 data-doubao-result 的按钮 */
|
||||||
|
fun onAiScreenResult(value: String) {
|
||||||
|
AiSurface.screenResult(value)
|
||||||
|
showHint("已选择:$value")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 用户在 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 settings get() = state.settings
|
||||||
val agents: List<Agent> get() = state.agents
|
val agents: List<Agent> get() = state.agents
|
||||||
val activeAgent: Agent? get() = state.activeAgent
|
val activeAgent: Agent? get() = state.activeAgent
|
||||||
@@ -104,6 +183,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||||
messages.clear()
|
messages.clear()
|
||||||
messages.addAll(list)
|
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 +197,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||||
refresh()
|
refresh()
|
||||||
if (conv != null) openConversation(conv.id) else {
|
if (conv != null) {
|
||||||
|
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
||||||
|
conversationEnded = false
|
||||||
|
endedReason = ""
|
||||||
|
openConversation(conv.id)
|
||||||
|
} else {
|
||||||
messages.clear()
|
messages.clear()
|
||||||
activeConversationId = ""
|
activeConversationId = ""
|
||||||
|
conversationEnded = false
|
||||||
|
endedReason = ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,6 +225,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
val text = draft.trim()
|
val text = draft.trim()
|
||||||
if (text.isEmpty() && attachments.isEmpty()) return
|
if (text.isEmpty() && attachments.isEmpty()) return
|
||||||
if (streaming) return
|
if (streaming) return
|
||||||
|
// ★ 对话被 AI 结束后就挡住 —— 界面上的输入框已经换成了横幅,
|
||||||
|
// 但发送按钮/回车/历史入口都可能绕过界面判断,所以在**这里**再拦一道。
|
||||||
|
if (conversationEnded) {
|
||||||
|
showHint("这次对话已结束,请开一个新对话")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
val files = attachments.toList()
|
val files = attachments.toList()
|
||||||
draft = ""
|
draft = ""
|
||||||
@@ -464,6 +563,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
|||||||
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
||||||
saveSettings(mapOf("security" to json))
|
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,8 +309,28 @@ fun ChatScreen(vm: AppViewModel) {
|
|||||||
|
|
||||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||||
|
|
||||||
|
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)
|
InputBar(vm, onPickFile, onMic, speech)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||||
AnimatedVisibility(
|
AnimatedVisibility(
|
||||||
|
|||||||
@@ -77,6 +77,22 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
|
|||||||
@Composable
|
@Composable
|
||||||
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
|
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
|
||||||
|
|
||||||
/* ------------------------------ 动画 ------------------------------ */
|
/* ------------------------------ 动画 ------------------------------ */
|
||||||
|
|
||||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import androidx.compose.material3.Icon
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
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 mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
|
||||||
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
|
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) }
|
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
|
||||||
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||||
val toolResults = 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))
|
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("工具权限") {
|
SettingsCard("工具权限") {
|
||||||
SegmentedOptions(
|
SegmentedOptions(
|
||||||
|
|||||||
@@ -42,8 +42,29 @@ def _max_rounds(settings: dict) -> int:
|
|||||||
return max(1, min(12, value))
|
return max(1, min(12, value))
|
||||||
|
|
||||||
|
|
||||||
|
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
|
||||||
|
#
|
||||||
|
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
|
||||||
|
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
|
||||||
|
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
|
||||||
|
# 硬塞进 markdown。
|
||||||
|
#
|
||||||
|
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
|
||||||
|
# 所以措辞是"确实用文字说不清时才用"。
|
||||||
|
UI_TOOLS_HINT = '\n'.join([
|
||||||
|
'界面能力(用户已打开):',
|
||||||
|
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||||||
|
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||||||
|
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||||
|
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||||||
|
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||||||
|
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
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 +73,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
|||||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||||
emit 事件回调,直接往 SSE 里写
|
emit 事件回调,直接往 SSE 里写
|
||||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||||
|
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||||||
"""
|
"""
|
||||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||||
@@ -61,6 +83,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
|||||||
max_rounds = _max_rounds(settings)
|
max_rounds = _max_rounds(settings)
|
||||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
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'
|
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||||
|
|
||||||
emit({
|
emit({
|
||||||
@@ -148,10 +180,20 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
|||||||
for tc in tool_calls:
|
for tc in tool_calls:
|
||||||
tool_call_count += 1
|
tool_call_count += 1
|
||||||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
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:
|
try:
|
||||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||||
|
finally:
|
||||||
|
tools_runtime.clear_context()
|
||||||
if result.get('ok'):
|
if result.get('ok'):
|
||||||
raw = result.get('result')
|
raw = result.get('result')
|
||||||
payload = truncate('(无输出)' if raw is None else raw)
|
payload = truncate('(无输出)' if raw is None else raw)
|
||||||
|
|||||||
@@ -935,9 +935,24 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
self.send_json(400, {'error': '缺少 name'})
|
self.send_json(400, {'error': '缺少 name'})
|
||||||
return True
|
return True
|
||||||
try:
|
try:
|
||||||
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
|
# ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的),
|
||||||
result = tools_runtime.execute_tool(name, body.get('args') or {},
|
# 但仍要能报错。所以 mode 强制 open。
|
||||||
{'security': {'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)
|
self.send_json(200, result)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
self.send_json(500, {'ok': False, 'error': str(exc)})
|
self.send_json(500, {'ok': False, 'error': str(exc)})
|
||||||
@@ -1402,6 +1417,9 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||||
emit=emit,
|
emit=emit,
|
||||||
should_stop=cancelled,
|
should_stop=cancelled,
|
||||||
|
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||||
|
# end_conversation 会明确报错(而不是假装成功)。
|
||||||
|
conversation_id=conversation_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
store.append_messages(conversation_id, [{
|
store.append_messages(conversation_id, [{
|
||||||
|
|||||||
@@ -180,6 +180,12 @@ DEFAULT_SETTINGS = {
|
|||||||
'toolsDir': '',
|
'toolsDir': '',
|
||||||
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||||
'tools': {'python': True, 'mcp': True},
|
'tools': {'python': True, 'mcp': True},
|
||||||
|
# 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话
|
||||||
|
# (show_ui / ask_user / end_conversation)。
|
||||||
|
#
|
||||||
|
# ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、
|
||||||
|
# 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。
|
||||||
|
'uiTools': {'enabled': False},
|
||||||
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||||
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||||
'speech': {
|
'speech': {
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ import threading
|
|||||||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||||
BUNDLED_TOOL_FILES = [
|
BUNDLED_TOOL_FILES = [
|
||||||
'_protocol.py',
|
'_protocol.py',
|
||||||
|
# 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种)
|
||||||
|
'_ui_bridge.py',
|
||||||
'calc.py',
|
'calc.py',
|
||||||
'now.py',
|
'now.py',
|
||||||
'weather.py',
|
'weather.py',
|
||||||
@@ -27,6 +29,10 @@ BUNDLED_TOOL_FILES = [
|
|||||||
'web_fetch.py',
|
'web_fetch.py',
|
||||||
'shell.py',
|
'shell.py',
|
||||||
'python_run.py',
|
'python_run.py',
|
||||||
|
# AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools)
|
||||||
|
'show_ui.py',
|
||||||
|
'ask_user.py',
|
||||||
|
'end_conversation.py',
|
||||||
'_mcp_python_example.py',
|
'_mcp_python_example.py',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,68 @@ _loaded_modules: dict = {}
|
|||||||
TOOL_TIMEOUT_S = 60
|
TOOL_TIMEOUT_S = 60
|
||||||
BUILTIN_FILE_LABEL = '<内置>'
|
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')
|
runner = getattr(module, 'run')
|
||||||
|
|
||||||
payload = args if isinstance(args, dict) else {}
|
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:
|
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
|
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
# 与 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'])
|
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
|
||||||
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
|
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
|
||||||
defs = defs + node_tool_defs(settings)
|
defs = defs + node_tool_defs(settings)
|
||||||
|
# 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏
|
||||||
|
defs = filter_ui_tools(defs, settings)
|
||||||
return apply_security(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 []
|
allow = ((settings or {}).get('security') or {}).get('allow') or []
|
||||||
if name not in allow:
|
if name not in allow:
|
||||||
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
|
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):
|
if name in node_tool_names(settings):
|
||||||
return run_node_tool(name, args, settings)
|
return run_node_tool(name, args, settings)
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
#!/system/bin/sh
|
|
||||||
# 最终验收:模拟 App 给子进程的环境(childEnvMap 的效果)
|
|
||||||
PKG=com.doubao.lynxclone
|
|
||||||
P=/data/data/$PKG/files/usr
|
|
||||||
export PREFIX=$P HOME=/data/data/$PKG/files/home TMPDIR=$P/tmp
|
|
||||||
export PATH=$P/bin:$P/bin/applets:/system/bin
|
|
||||||
export LD_LIBRARY_PATH=$P/lib LD_PRELOAD=$P/lib/libtermux-exec.so
|
|
||||||
|
|
||||||
echo "===== 1. python + pip(问题 1、3)====="
|
|
||||||
$P/bin/python3 -V 2>&1 | head -1
|
|
||||||
$P/bin/python3 -c 'import encodings,json,sqlite3,ssl; print(" import 正常")' 2>&1 | head -2
|
|
||||||
$P/bin/pip3 --version 2>&1 | head -1
|
|
||||||
$P/bin/python3 -c 'import six; print(" six", six.__version__)' 2>&1 | head -2
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "===== 2. 临时目录(问题 2)====="
|
|
||||||
$P/bin/python3 -c 'import tempfile; print(" tempfile =", tempfile.gettempdir())' 2>&1 | head -2
|
|
||||||
$P/bin/mktemp 2>&1 | head -1
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "===== 3. 环境健康 ====="
|
|
||||||
echo " 未配置 = $($P/bin/dpkg -l 2>/dev/null | grep -c '^i[^i]')"
|
|
||||||
echo " 半装 = $($P/bin/dpkg -l 2>/dev/null | grep -c '^i[UFH]')"
|
|
||||||
echo " 架构 = $($P/bin/dpkg --print-architecture)"
|
|
||||||
echo " dpkg = $($P/bin/dpkg --version 2>&1 | head -1 | cut -d' ' -f6)"
|
|
||||||
echo " 源 = $(grep -m1 '^deb' $P/etc/apt/sources.list | cut -d/ -f3)"
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "===== 4. 真 Termux 仍共存 ====="
|
|
||||||
ls -ld /data/data/com.termux 2>&1 | awk '{print " " $1, $3}'
|
|
||||||
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)
|
||||||
304
scripts/verify-ui-tools.py
Normal file
304
scripts/verify-ui-tools.py
Normal file
@@ -0,0 +1,304 @@
|
|||||||
|
"""守 AI 界面三件套(show_ui / ask_user / end_conversation)的硬性质。
|
||||||
|
|
||||||
|
这些性质每一条都对应一个"想当然会出错"的地方,光看代码看不出来:
|
||||||
|
|
||||||
|
1. **开关默认关**。这三个工具会让 AI 主动往用户脸上弹东西、甚至封掉对话,
|
||||||
|
默认打开是产品事故。而且必须**默认关**(新装/老设备升上来都是关)。
|
||||||
|
2. **两道拦截都要在**:关掉时① 工具对模型隐藏,② 即使模型硬编名字也拒绝执行。
|
||||||
|
只做①的话,用户关掉之后模型仍可能从历史消息里学会这个名字再调一次。
|
||||||
|
3. **ask_user 的 options 两种写法都要收**(对象数组 / 裸字符串数组)——
|
||||||
|
模型写裸字符串数组非常常见,只认一种就会平白吃一个报错。
|
||||||
|
4. **end_conversation 拿不到对话 id 时必须报错,不能假装成功** ——
|
||||||
|
假装成功会变成"界面封了、盘上没封",用户重启后又能发消息。
|
||||||
|
5. **不占用户的消息预算**:这几个工具的规则不能渗进系统提示词的
|
||||||
|
"回答要求"编号里(那会让模型把它们当成每轮都要考虑的事)。
|
||||||
|
|
||||||
|
用法:
|
||||||
|
python scripts/verify-ui-tools.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
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__)))
|
||||||
|
KERNEL = os.path.join(WS, "android", "kernel")
|
||||||
|
TOOLS = os.path.join(WS, "tools")
|
||||||
|
sys.path.insert(0, KERNEL)
|
||||||
|
sys.path.insert(0, TOOLS)
|
||||||
|
|
||||||
|
fails = []
|
||||||
|
|
||||||
|
|
||||||
|
def fail(m):
|
||||||
|
fails.append(m)
|
||||||
|
print(f" ✗ {m}")
|
||||||
|
|
||||||
|
|
||||||
|
def ok(m):
|
||||||
|
print(f" ✓ {m}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 1
|
||||||
|
print("=== 1. 工具能被发现,spec 合法 ===")
|
||||||
|
import importlib.util
|
||||||
|
|
||||||
|
for name in ("show_ui", "ask_user", "end_conversation"):
|
||||||
|
path = os.path.join(TOOLS, name + ".py")
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
fail(f"{name}.py 不存在")
|
||||||
|
continue
|
||||||
|
spec = importlib.util.spec_from_file_location("t_" + name, path)
|
||||||
|
mod = importlib.util.module_from_spec(spec)
|
||||||
|
try:
|
||||||
|
spec.loader.exec_module(mod)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
fail(f"{name}.py 导入失败:{type(exc).__name__}: {exc}")
|
||||||
|
continue
|
||||||
|
tool = getattr(mod, "TOOL", None)
|
||||||
|
if not isinstance(tool, dict) or not tool.get("name"):
|
||||||
|
fail(f"{name}.py 没有合法的 TOOL")
|
||||||
|
continue
|
||||||
|
if not callable(getattr(mod, "run", None)):
|
||||||
|
fail(f"{name}.py 没有 run(args)")
|
||||||
|
continue
|
||||||
|
if tool["name"] != name:
|
||||||
|
fail(f"{name}.py 的 TOOL.name 是 {tool['name']},和文件名不一致")
|
||||||
|
continue
|
||||||
|
params = tool.get("parameters") or {}
|
||||||
|
if params.get("type") != "object":
|
||||||
|
fail(f"{name} 的 parameters.type 不是 object")
|
||||||
|
continue
|
||||||
|
ok(f"{name}:spec 合法(必填 {params.get('required') or '无'})")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 2
|
||||||
|
print("\n=== 2. 开关默认关 + 两道拦截 ===")
|
||||||
|
import tools_runtime as TR
|
||||||
|
|
||||||
|
if TR.ui_tools_enabled({}):
|
||||||
|
fail("空 settings 时 ui_tools_enabled 竟然是 True —— 默认必须关")
|
||||||
|
else:
|
||||||
|
ok("空 settings → 关闭")
|
||||||
|
|
||||||
|
if TR.ui_tools_enabled({"uiTools": {"enabled": True}}):
|
||||||
|
ok("uiTools.enabled=True → 打开")
|
||||||
|
else:
|
||||||
|
fail("uiTools.enabled=True 没被认成打开")
|
||||||
|
|
||||||
|
if TR.ui_tools_enabled({"uiTools": True}):
|
||||||
|
ok("uiTools=True(老写法)→ 也认")
|
||||||
|
else:
|
||||||
|
fail("uiTools=True 没被认(兼容写法失效)")
|
||||||
|
|
||||||
|
# ① 关掉时对模型隐藏
|
||||||
|
defs_off = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {})
|
||||||
|
if defs_off:
|
||||||
|
fail(f"关闭时仍把 {[d['name'] for d in defs_off]} 给了模型")
|
||||||
|
else:
|
||||||
|
ok("关闭时三个工具对模型隐藏")
|
||||||
|
|
||||||
|
defs_on = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {"uiTools": {"enabled": True}})
|
||||||
|
if len(defs_on) == len(TR.UI_TOOLS):
|
||||||
|
ok("打开时三个工具都给模型")
|
||||||
|
else:
|
||||||
|
fail(f"打开时只给了 {len(defs_on)} 个")
|
||||||
|
|
||||||
|
# ② 关掉时即使硬编名字也拒绝
|
||||||
|
res = TR.execute_tool("ask_user", {"question": "x", "options": ["a"]}, {})
|
||||||
|
if res.get("ok") is False and "关闭" in str(res.get("error")):
|
||||||
|
ok("关闭时 execute_tool 拒绝执行(第二道拦截在)")
|
||||||
|
else:
|
||||||
|
fail(f"关闭时 execute_tool 没拦住:{res}")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 3
|
||||||
|
print("\n=== 3. ask_user 的选项规整 ===")
|
||||||
|
import ask_user as AU
|
||||||
|
|
||||||
|
cases = [
|
||||||
|
(["A", "B"], 2, "裸字符串数组"),
|
||||||
|
([{"label": "A"}, {"label": "B", "value": "b"}], 2, "对象数组"),
|
||||||
|
([{"value": "only"}], 1, "只有 value 没有 label"),
|
||||||
|
([{"label": "A", "description": "说明"}], 1, "带 description"),
|
||||||
|
(["A", {"label": ""}, " ", "B"], 2, "混杂空项(应被丢掉)"),
|
||||||
|
([], 0, "空数组"),
|
||||||
|
]
|
||||||
|
for raw, want, label in cases:
|
||||||
|
got = AU._clean_options(raw)
|
||||||
|
if len(got) == want:
|
||||||
|
ok(f"{label} → {len(got)} 项")
|
||||||
|
else:
|
||||||
|
fail(f"{label}:期望 {want} 项,实际 {len(got)} 项({got})")
|
||||||
|
|
||||||
|
opts = AU._clean_options([{"label": "A"}])
|
||||||
|
if opts and opts[0]["value"] == "A":
|
||||||
|
ok("value 留空时自动用 label")
|
||||||
|
else:
|
||||||
|
fail(f"value 没回落到 label:{opts}")
|
||||||
|
|
||||||
|
# 超过 8 个要截断
|
||||||
|
many = AU._clean_options([f"opt{i}" for i in range(20)])
|
||||||
|
if len(many) == 20:
|
||||||
|
ok("规整阶段不截断(截断在 run 里做)")
|
||||||
|
else:
|
||||||
|
fail(f"规整阶段就把选项截了:{len(many)}")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 4
|
||||||
|
print("\n=== 4. 拿不到对话 id 时必须报错 ===")
|
||||||
|
import _ui_bridge as UB
|
||||||
|
|
||||||
|
# 不在工具调用上下文里 → conversation_id() 应该是空
|
||||||
|
UB_ctx = TR.current_context()
|
||||||
|
if UB_ctx == {}:
|
||||||
|
ok("不在调用中时 current_context() 是空 dict")
|
||||||
|
else:
|
||||||
|
fail(f"current_context() 不是空的:{UB_ctx}")
|
||||||
|
|
||||||
|
# push 之后能读到
|
||||||
|
TR.push_context(conversationId="c_test", toolName="end_conversation")
|
||||||
|
if TR.current_context().get("conversationId") == "c_test":
|
||||||
|
ok("push_context 之后能读到 conversationId")
|
||||||
|
else:
|
||||||
|
fail(f"push_context 没生效:{TR.current_context()}")
|
||||||
|
|
||||||
|
# ★★★ 关键:**上下文必须能跨线程** —— run_with_timeout 是在新线程里跑工具的,
|
||||||
|
# 而 threading.local() 不跨线程继承。这里直接验"另一个线程里读得到"。
|
||||||
|
import threading
|
||||||
|
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _in_other_thread():
|
||||||
|
seen["ctx"] = TR.current_context()
|
||||||
|
|
||||||
|
|
||||||
|
worker = threading.Thread(target=_in_other_thread)
|
||||||
|
worker.start()
|
||||||
|
worker.join(5)
|
||||||
|
if seen.get("ctx") == {}:
|
||||||
|
ok("另一个线程里读不到(符合 thread-local 语义 —— 所以必须显式搬过去)")
|
||||||
|
else:
|
||||||
|
fail(f"另一个线程里读到了东西,语义和预期不符:{seen.get('ctx')}")
|
||||||
|
|
||||||
|
TR.clear_context()
|
||||||
|
if TR.current_context() == {}:
|
||||||
|
ok("clear_context 之后读不到了")
|
||||||
|
else:
|
||||||
|
fail("clear_context 之后还能读到")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 5
|
||||||
|
print("\n=== 5. 工具真的执行时,上下文能送到工具手里 ===")
|
||||||
|
# 造一个假工具:它把读到的上下文写进返回值。
|
||||||
|
#
|
||||||
|
# ★★ 必须走 **run_python_tool** 这条真实路径 —— 它内部会调 run_with_timeout,
|
||||||
|
# 而那个函数是在**新线程**里跑工具的。第一版验证脚本图省事直接调了
|
||||||
|
# run_with_timeout(lambda: mod.run(...)),绕开了被修的那段代码,
|
||||||
|
# 于是"修好了没有"根本没测到(脚本报红但红得不是地方)。
|
||||||
|
# 教训:验证要走**调用方真正走的那条路**。
|
||||||
|
probe_src = '''
|
||||||
|
import os, sys
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
TOOL = {"name": "probe_ctx", "description": "探针",
|
||||||
|
"parameters": {"type": "object", "properties": {}}}
|
||||||
|
def run(args):
|
||||||
|
import tools_runtime as TR
|
||||||
|
import _ui_bridge as UB
|
||||||
|
return {"ctx": TR.current_context(), "conv": UB.conversation_id()}
|
||||||
|
'''
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
tmpdir = tempfile.mkdtemp()
|
||||||
|
open(os.path.join(tmpdir, "probe_ctx.py"), "w", encoding="utf-8").write(probe_src)
|
||||||
|
|
||||||
|
# 让 tools_runtime 去 tmpdir 里找工具(改的是 `paths.get().tools_dir`,
|
||||||
|
# 不动用户真正的工具目录)
|
||||||
|
import paths as P
|
||||||
|
|
||||||
|
_orig_tools_dir = P.get().tools_dir
|
||||||
|
P.get().tools_dir = tmpdir
|
||||||
|
TR.discover_python_tools(force=True)
|
||||||
|
try:
|
||||||
|
TR.push_context(conversationId="c_from_parent", toolName="probe_ctx")
|
||||||
|
try:
|
||||||
|
res = TR.run_python_tool("probe_ctx", {})
|
||||||
|
finally:
|
||||||
|
TR.clear_context()
|
||||||
|
finally:
|
||||||
|
P.get().tools_dir = _orig_tools_dir
|
||||||
|
TR.discover_python_tools(force=True)
|
||||||
|
|
||||||
|
got = (res or {}).get("result") if isinstance(res, dict) else None
|
||||||
|
if not isinstance(got, dict):
|
||||||
|
fail(f"探针没返回 dict:{res}")
|
||||||
|
else:
|
||||||
|
if got.get("conv") == "c_from_parent":
|
||||||
|
ok("换线程之后工具仍拿得到 conversationId(修好了)")
|
||||||
|
else:
|
||||||
|
fail(f"换线程之后 conversationId 丢了:{got}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# end_conversation.run 在没有对话 id 时应该抛错(而不是返回 ended:True)
|
||||||
|
import end_conversation as EC
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 桥不在(电脑端)会先抛"没有界面能力",两种都算"没假装成功"
|
||||||
|
out = EC.run({"reason": "测试"})
|
||||||
|
if out.get("ended") is True:
|
||||||
|
fail("没有对话 id 却报 ended=True —— 这是最坏的失败模式(界面封了、盘上没封)")
|
||||||
|
else:
|
||||||
|
ok(f"没有对话 id 时没假装成功:{out}")
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
ok(f"没有对话 id 时抛错(正确):{type(exc).__name__}")
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 6
|
||||||
|
print("\n=== 6. 界面能力的提示词只在开关打开时追加 ===")
|
||||||
|
import defaults as D
|
||||||
|
|
||||||
|
prompt = D.DEFAULT_SYSTEM_PROMPT
|
||||||
|
if "show_ui" in prompt or "ask_user" in prompt or "end_conversation" in prompt:
|
||||||
|
fail("默认提示词里点名了界面工具 —— 开关关着时会误导模型去调")
|
||||||
|
else:
|
||||||
|
ok("默认提示词里没点名界面工具(开关管得住)")
|
||||||
|
if "附件" in prompt:
|
||||||
|
ok("附件说明还在(没被覆盖)")
|
||||||
|
else:
|
||||||
|
fail("附件说明不见了")
|
||||||
|
|
||||||
|
# 追加的那段:关着不该出现,开着必须在
|
||||||
|
import agent_loop as AL
|
||||||
|
|
||||||
|
if not hasattr(AL, "UI_TOOLS_HINT"):
|
||||||
|
fail("agent_loop 里没有 UI_TOOLS_HINT")
|
||||||
|
else:
|
||||||
|
hint = AL.UI_TOOLS_HINT
|
||||||
|
if "show_ui" in hint and "ask_user" in hint and "end_conversation" in hint:
|
||||||
|
ok("UI_TOOLS_HINT 里三个工具都讲到了")
|
||||||
|
else:
|
||||||
|
fail("UI_TOOLS_HINT 没覆盖三个工具")
|
||||||
|
if "必须先在正文里" in hint:
|
||||||
|
ok("提示了 end_conversation 要先说明(这条很重要)")
|
||||||
|
else:
|
||||||
|
fail("UI_TOOLS_HINT 没要求'结束前先说明'")
|
||||||
|
|
||||||
|
# ★ 追加逻辑必须**按开关**走。这里直接验证那段代码的存在性 +
|
||||||
|
# ui_tools_enabled 的语义(真正的拼接在 run_agent 里,需要起网络,不在这儿跑)。
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
src = inspect.getsource(AL.run_agent)
|
||||||
|
if "ui_tools_enabled" in src and "UI_TOOLS_HINT" in src:
|
||||||
|
ok("run_agent 里是按开关决定要不要追加")
|
||||||
|
else:
|
||||||
|
fail("run_agent 没按开关追加提示词")
|
||||||
|
|
||||||
|
print()
|
||||||
|
if fails:
|
||||||
|
print(f"❌ {len(fails)} 项不合格:")
|
||||||
|
for m in fails:
|
||||||
|
print(" -", m)
|
||||||
|
sys.exit(1)
|
||||||
|
print("✅ 全部通过")
|
||||||
85
tools/_ui_bridge.py
Normal file
85
tools/_ui_bridge.py
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
"""
|
||||||
|
界面工具(AI 主动弹界面 / 弹窗 / 结束对话)和安卓原生桥之间的公共部分。
|
||||||
|
|
||||||
|
## 为什么单独一个模块
|
||||||
|
|
||||||
|
三个工具干的事不同,但**和安卓那一侧通话的方式完全一样**:都是往
|
||||||
|
`NativeBridge.device()` 发一个 JSON、收一个 JSON。把这段收在一处,
|
||||||
|
以后加第四个界面工具就只要写 TOOL + run,不用再抄一遍桥接代码 ——
|
||||||
|
这个仓库里"同一个逻辑抄两份,加功能时只改一份"的坑已经踩过好几次了。
|
||||||
|
|
||||||
|
## 为什么要带 conversationId
|
||||||
|
|
||||||
|
`end_conversation` 要**永久结束当前这次对话**,内核必须知道是哪一次。
|
||||||
|
内核在组装工具前会把当前对话 id 塞进 settings 的 `_conversationId`
|
||||||
|
(下划线开头,不会外泄给模型,也不会出现在 /api/state 里),
|
||||||
|
这里取出来一起发给安卓侧。
|
||||||
|
|
||||||
|
## 电脑端会怎样
|
||||||
|
|
||||||
|
没有 `_android` 桥(桌面版)时,这几个工具都**明确返回不可用**,
|
||||||
|
而不是假装成功 —— 让模型知道"这个端没有界面能力",它就不会反复重试。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
|
||||||
|
def _bridge():
|
||||||
|
"""
|
||||||
|
拿到安卓原生桥对象;电脑端返回 None。
|
||||||
|
|
||||||
|
`doubao_entry` 只在安卓上存在(它是 Chaquopy 的入口模块),
|
||||||
|
所以这里用 try/except 而不是判断平台字符串 —— 平台字符串判断错过一次
|
||||||
|
(sys.platform 在 Chaquopy 里也是 'linux',跟桌面 Linux 分不开)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import doubao_entry # noqa: PLC0415 - 电脑端没有这个模块,只能运行时导入
|
||||||
|
|
||||||
|
return getattr(doubao_entry, '_android', None)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def call_device(payload: dict) -> dict:
|
||||||
|
"""
|
||||||
|
往安卓侧发一个 device 请求。
|
||||||
|
|
||||||
|
★ 参数名要和 Kotlin 侧 `NativeBridge.device()` 的 `req.optString(...)`
|
||||||
|
对得上 —— 对不上不会报错,只会**静默拿到空字符串**,
|
||||||
|
表现是"界面弹出来但标题是空的"。所以两边都写全。
|
||||||
|
|
||||||
|
@return 安卓侧回的 JSON;桥不在时返回 {'unavailable': True, ...}
|
||||||
|
"""
|
||||||
|
bridge = _bridge()
|
||||||
|
if bridge is None:
|
||||||
|
return {
|
||||||
|
'unavailable': True,
|
||||||
|
'error': '当前环境没有界面能力(电脑端的界面在桌面窗口里,这几个工具只在手机上生效)',
|
||||||
|
}
|
||||||
|
raw = bridge.device(json.dumps(payload, ensure_ascii=False))
|
||||||
|
try:
|
||||||
|
return json.loads(str(raw))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return {'raw': str(raw)}
|
||||||
|
|
||||||
|
|
||||||
|
def conversation_id() -> str:
|
||||||
|
"""
|
||||||
|
当前对话 id。
|
||||||
|
|
||||||
|
★ 从内核的"当前调用上下文"里取。`tools_runtime.execute_tool` 在调用工具前
|
||||||
|
会把 settings 里的 `_conversationId` 放到 `_protocol` 能读到的地方 ——
|
||||||
|
见 tools_runtime.current_context()。取不到就返回空串(安卓侧会当成
|
||||||
|
"没有指定对话",只是不能结束对话,别的功能不受影响)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import tools_runtime # noqa: PLC0415
|
||||||
|
|
||||||
|
ctx = tools_runtime.current_context() or {}
|
||||||
|
return str(ctx.get('conversationId') or '')
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return ''
|
||||||
152
tools/ask_user.py
Normal file
152
tools/ask_user.py
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
"""让 AI 弹一个选择弹窗,并把用户选的那一项拿回去。
|
||||||
|
|
||||||
|
## 和 show_ui 的分工
|
||||||
|
|
||||||
|
`show_ui` 展示用 —— **不阻塞**,弹出来就返回,用户看完自己关
|
||||||
|
`ask_user` 问询用 —— **阻塞**,等用户选完才返回,模型拿到选择继续干活
|
||||||
|
|
||||||
|
这两个刻意分开:展示性的东西不该把对话卡住;而"让用户在几个方案里选一个"
|
||||||
|
必须拿到答案才能继续。
|
||||||
|
|
||||||
|
## 阻塞是怎么实现的
|
||||||
|
|
||||||
|
安卓侧 `NativeBridge.device()` 是同步的 —— 它在 UI 线程上弹出界面,
|
||||||
|
然后用一个 `CountDownLatch` 等用户点,等到(或超时)才把结果回给 Python。
|
||||||
|
Python 这边就是一次普通调用,不需要轮询。
|
||||||
|
|
||||||
|
★ 超时必须有:用户可能把手机锁屏走了,不能让内核线程永远挂着。
|
||||||
|
默认 120 秒,到点返回 `timeout: true`,模型据此知道"用户没理我"。
|
||||||
|
|
||||||
|
## 电脑端
|
||||||
|
|
||||||
|
明确返回不可用(桌面版的界面在桌面窗口里)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from _protocol import serve # noqa: E402
|
||||||
|
from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||||
|
|
||||||
|
# 等用户的秒数上限。安卓侧也有自己的上限,两边都不设的话
|
||||||
|
# 用户锁屏走了会把内核的工作线程永远占住。
|
||||||
|
TIMEOUT_S = 120
|
||||||
|
|
||||||
|
TOOL = {
|
||||||
|
"name": "ask_user",
|
||||||
|
"description": (
|
||||||
|
"弹一个选择弹窗问用户,**等用户选完**再继续(最多等 120 秒)。"
|
||||||
|
"适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。"
|
||||||
|
"options 传选项数组(每项 {label, value, description}):"
|
||||||
|
"label 是按钮上显示的字,value 是你要拿到的值(留空则用 label),"
|
||||||
|
"description 是选项下方的小字说明。"
|
||||||
|
"多选请传 multiple=true。返回里 choice/values 就是用户选的东西;"
|
||||||
|
"timeout=true 表示用户没在时限内回答。"
|
||||||
|
),
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"question": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "要问的问题",
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "选项列表",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"label": {"type": "string", "description": "按钮上显示的文字"},
|
||||||
|
"value": {"type": "string", "description": "返回给模型的值,留空则用 label"},
|
||||||
|
"description": {"type": "string", "description": "选项下方的小字说明"},
|
||||||
|
},
|
||||||
|
"required": ["label"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"multiple": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "是否允许多选,默认 false",
|
||||||
|
},
|
||||||
|
"allow_cancel": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "是否显示「取消」按钮,默认 true",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["question", "options"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_options(raw) -> list:
|
||||||
|
"""
|
||||||
|
规整选项。
|
||||||
|
|
||||||
|
★ 模型经常把 options 写成裸字符串数组(`["A", "B"]`)而不是对象数组 ——
|
||||||
|
这在 tool calling 里非常常见,直接 `.get()` 会 AttributeError。
|
||||||
|
所以两种都收下,别让模型因为格式小错就吃一个报错。
|
||||||
|
"""
|
||||||
|
out = []
|
||||||
|
for item in raw or []:
|
||||||
|
if isinstance(item, dict):
|
||||||
|
label = str(item.get("label") or item.get("value") or "").strip()
|
||||||
|
if not label:
|
||||||
|
continue
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"label": label,
|
||||||
|
"value": str(item.get("value") or label),
|
||||||
|
"description": str(item.get("description") or ""),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif isinstance(item, (str, int, float)):
|
||||||
|
text = str(item).strip()
|
||||||
|
if text:
|
||||||
|
out.append({"label": text, "value": text, "description": ""})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def run(args: dict) -> dict:
|
||||||
|
question = str(args.get("question") or "").strip()
|
||||||
|
if not question:
|
||||||
|
raise ValueError("question 不能为空")
|
||||||
|
options = _clean_options(args.get("options"))
|
||||||
|
if not options:
|
||||||
|
raise ValueError("options 至少要给一个选项")
|
||||||
|
# 选项太多按钮会挤成一屏,截断并告诉模型(而不是静默丢掉)
|
||||||
|
truncated = False
|
||||||
|
if len(options) > 8:
|
||||||
|
options = options[:8]
|
||||||
|
truncated = True
|
||||||
|
|
||||||
|
res = call_device(
|
||||||
|
{
|
||||||
|
"action": "ui_dialog",
|
||||||
|
"question": question,
|
||||||
|
"options": options,
|
||||||
|
"multiple": bool(args.get("multiple")),
|
||||||
|
"allowCancel": bool(args.get("allow_cancel", True)),
|
||||||
|
"timeoutMs": TIMEOUT_S * 1000,
|
||||||
|
"conversationId": conversation_id(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if res.get("unavailable"):
|
||||||
|
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||||
|
if res.get("error"):
|
||||||
|
raise RuntimeError(str(res["error"]))
|
||||||
|
|
||||||
|
out = {
|
||||||
|
"question": question,
|
||||||
|
"multiple": bool(res.get("multiple")),
|
||||||
|
"timeout": bool(res.get("timeout")),
|
||||||
|
"cancelled": bool(res.get("cancelled")),
|
||||||
|
"choice": res.get("choice") or "",
|
||||||
|
"values": res.get("values") or [],
|
||||||
|
}
|
||||||
|
if truncated:
|
||||||
|
out["note"] = "选项超过 8 个,只显示了前 8 个"
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
serve(TOOL, run)
|
||||||
90
tools/end_conversation.py
Normal file
90
tools/end_conversation.py
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
"""让 AI 主动**永久结束**当前这次对话。
|
||||||
|
|
||||||
|
## "永久"是什么意思
|
||||||
|
|
||||||
|
不是"这一轮说完了",而是这次对话就此封笔:
|
||||||
|
|
||||||
|
· 会话被标记 `ended`(落盘,重启 App 也还在)
|
||||||
|
· 界面上输入框变成「这次对话已结束」+ 一个「开始新对话」按钮
|
||||||
|
· 再往里发消息会被挡住(用户想继续就开新的)
|
||||||
|
|
||||||
|
## 模型什么时候该用
|
||||||
|
|
||||||
|
· 用户要的事情已经彻底办完,且没有后续可聊的("帮我查完这趟航班" → 结束)
|
||||||
|
· 用户自己说"就这样吧 / 不用了 / 结束"
|
||||||
|
· 任务走进了死胡同,继续聊下去只会兜圈子
|
||||||
|
|
||||||
|
★ 提示词里明确要求它**先说明再结束** —— 直接封笔会让人莫名其妙。
|
||||||
|
所以这个工具的 description 里写死了"要先在正文里说明已经结束"。
|
||||||
|
|
||||||
|
## 为什么要落盘而不是只改界面状态
|
||||||
|
|
||||||
|
界面状态一刷新就没了。用户关掉 App 再进来,会看到一个能继续输入的框,
|
||||||
|
而模型那边以为自己已经结束了 —— 两边状态不一致是这类功能最容易出的问题。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from _protocol import serve # noqa: E402
|
||||||
|
from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||||
|
|
||||||
|
TOOL = {
|
||||||
|
"name": "end_conversation",
|
||||||
|
"description": (
|
||||||
|
"**永久结束当前这次对话**(落盘,重启 App 也生效):之后再发消息会被挡住,"
|
||||||
|
"用户需要开一个新对话。"
|
||||||
|
"只在事情真的办完、用户说了不用了、或者继续聊只会兜圈子时才用。"
|
||||||
|
"★ 调用前必须先在正文里跟用户说明这次对话已经结束,别默默封笔。"
|
||||||
|
"reason 用一句话说明为什么结束(会给用户看)。"
|
||||||
|
),
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"reason": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "为什么结束(一句话,会给用户看)",
|
||||||
|
},
|
||||||
|
"summary": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "这次对话做了什么(可选,留作记录)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["reason"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def run(args: dict) -> dict:
|
||||||
|
reason = str(args.get("reason") or "").strip()
|
||||||
|
if not reason:
|
||||||
|
raise ValueError("reason 不能为空(要告诉用户为什么结束)")
|
||||||
|
conv = conversation_id()
|
||||||
|
if not conv:
|
||||||
|
# 拿不到对话 id 时**不能假装成功** —— 那样界面封了、盘上没封,
|
||||||
|
# 用户重启后又能发消息,而模型以为自己结束了。
|
||||||
|
raise RuntimeError("拿不到当前对话 id,无法结束对话")
|
||||||
|
|
||||||
|
res = call_device(
|
||||||
|
{
|
||||||
|
"action": "end_conversation",
|
||||||
|
"conversationId": conv,
|
||||||
|
"reason": reason,
|
||||||
|
"summary": str(args.get("summary") or ""),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if res.get("unavailable"):
|
||||||
|
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||||
|
if res.get("error"):
|
||||||
|
raise RuntimeError(str(res["error"]))
|
||||||
|
return {
|
||||||
|
"ended": True,
|
||||||
|
"conversationId": conv,
|
||||||
|
"reason": reason,
|
||||||
|
"note": "这次对话已永久结束。用户需要开新对话才能继续。",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
serve(TOOL, run)
|
||||||
89
tools/show_ui.py
Normal file
89
tools/show_ui.py
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
"""让 AI 主动弹出一个 WebView 界面(自己写 HTML)。
|
||||||
|
|
||||||
|
## 这个工具存在的意义
|
||||||
|
|
||||||
|
普通的对话是一来一回的文本。有些东西**用界面表达比用文字好得多**:
|
||||||
|
一张自己算出来的图表、一个把结果排版好的报告卡片、一个可以点的菜单、
|
||||||
|
一段带样式的对比表。以前模型只能吐 markdown,表格一宽就乱。
|
||||||
|
|
||||||
|
这个工具让模型**直接写 HTML**,App 用一个全屏 WebView 渲染出来。
|
||||||
|
|
||||||
|
## 用法约定(也是给模型看的)
|
||||||
|
|
||||||
|
· `html` 里写**片段**就行(不用 <html>/<body>),会自动套一层带样式的骨架 ——
|
||||||
|
这样模型不用每次重复写 viewport、暗色主题这些
|
||||||
|
· 想要完整控制就传 `full_html=true`,那时 html 必须是一份完整文档
|
||||||
|
· 界面里可以放按钮:`<button data-doubao-result="选了A">A</button>`
|
||||||
|
—— 用户点了之后,那个 `data-doubao-result` 的值会回到模型手里
|
||||||
|
(走 [ask_user] 那条回传通道,所以不需要模型自己写 JS)
|
||||||
|
|
||||||
|
## 电脑端
|
||||||
|
|
||||||
|
桌面版的界面在桌面窗口里,这个工具**明确返回不可用**,不假装成功。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from _protocol import serve # noqa: E402
|
||||||
|
from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||||
|
|
||||||
|
TOOL = {
|
||||||
|
"name": "show_ui",
|
||||||
|
"description": (
|
||||||
|
"在用户手机/平板上弹出一个界面,自己写 HTML 渲染(全屏 WebView)。"
|
||||||
|
"适合:图表、排版好的报告卡片、对比表、可点的菜单、任何用文字说不清的东西。"
|
||||||
|
"html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
|
||||||
|
"想完全控制就传 full_html=true。"
|
||||||
|
"界面里可以放 <button data-doubao-result=\"值\">文字</button>,"
|
||||||
|
"用户点了之后那个值会回到你手里。"
|
||||||
|
"调用后界面立刻显示、本工具立刻返回,用户看到之后再继续对话。"
|
||||||
|
),
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"html": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "要渲染的 HTML(片段即可,除非 full_html=true)",
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "顶部标题栏文字,可留空",
|
||||||
|
},
|
||||||
|
"full_html": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "true 表示 html 是一份完整文档,不再套骨架。默认 false",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["html"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def run(args: dict) -> dict:
|
||||||
|
html = str(args.get("html") or "").strip()
|
||||||
|
if not html:
|
||||||
|
raise ValueError("html 不能为空")
|
||||||
|
res = call_device(
|
||||||
|
{
|
||||||
|
"action": "ui_screen",
|
||||||
|
"html": html,
|
||||||
|
"title": str(args.get("title") or ""),
|
||||||
|
"full_html": bool(args.get("full_html")),
|
||||||
|
"conversationId": conversation_id(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if res.get("unavailable"):
|
||||||
|
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||||
|
if res.get("error"):
|
||||||
|
raise RuntimeError(str(res["error"]))
|
||||||
|
return {
|
||||||
|
"shown": True,
|
||||||
|
"bytes": len(html),
|
||||||
|
"note": "界面已弹出,用户看完会自己关掉。你不需要再重复内容。",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
serve(TOOL, run)
|
||||||
Reference in New Issue
Block a user