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:
doubao
2026-10-14 15:36:52 +08:00
parent 6197b726a5
commit 52680b9eb7
23 changed files with 2011 additions and 39 deletions

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 234
versionName = "2.0.34"
versionCode = 235
versionName = "2.0.35"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View 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()

View File

@@ -70,6 +70,10 @@ class MainActivity : ComponentActivity() {
}
if (port != null && port > 0) {
client.baseUrl = "http://127.0.0.1:$port"
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
KernelHost.set(port)
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
// 否则内核里的 device 工具会返回"没有安卓原生桥"
withContext(Dispatchers.IO) {

View File

@@ -20,7 +20,10 @@ import android.provider.OpenableColumns
import com.chaquo.python.Python
import org.json.JSONArray
import org.json.JSONObject
import com.doubao.lynxclone.termux.AiSurface
import com.doubao.lynxclone.termux.TermuxShell
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -67,6 +70,14 @@ class NativeBridge(private val activity: Activity) {
req.optString("cwd"),
(req.optDouble("timeout", 60.0) * 1000).toLong(),
)
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
//
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
"ui_screen" -> uiScreen(req)
"ui_dialog" -> uiDialog(req)
"end_conversation" -> endConversation(req)
else -> JSONObject().put("error", "未知 action:$action")
}
} catch (t: Throwable) {
@@ -74,6 +85,116 @@ class NativeBridge(private val activity: Activity) {
}.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 {
val stat = StatFs(Environment.getDataDirectory().path)
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0

View File

@@ -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")
}
}

View 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) }
}
}
}
}

View File

@@ -112,6 +112,25 @@ fun AppRoot(
Text(vm.hint, color = Color.White, fontSize = 13.sp)
}
}
/* ---------------- AI 主动弹出来的东西 ----------------
*
* ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西,
* 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 ——
* 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。
*
* 顺序(后写的盖在上面):选择弹窗 > HTML 界面。
* `ask_user` 是阻塞的,用户必须先回答它,所以它压在最上面。
*/
AiHtmlScreenOverlay(
screen = vm.aiScreen,
onClose = { vm.closeAiScreen() },
onResult = { vm.onAiScreenResult(it) },
)
AiDialogOverlay(
dialog = vm.aiDialog,
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
)
}
}

View File

@@ -16,6 +16,7 @@ import com.doubao.lynxclone.data.MeetingEvent
import com.doubao.lynxclone.data.MeetingMeta
import com.doubao.lynxclone.data.StreamEvent
import com.doubao.lynxclone.data.ToolTrace
import com.doubao.lynxclone.termux.AiSurface
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.CancellationException
@@ -53,8 +54,86 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
/** 模型 / 思考强度面板(底部升起) */
var modelPickerOpen by mutableStateOf(false)
/* -------------------- AI 主动弹出来的东西 -------------------- */
/**
* AI 弹的全屏 HTML 界面(`show_ui` 工具);null 表示没有。
*
* 数据源是 [AiSurface](内核线程往里写),这里通过监听器同步过来 ——
* 内核永远不直接碰 Compose。
*/
var aiScreen by mutableStateOf<AiSurface.Screen?>(null)
private set
/** AI 弹的选择弹窗(`ask_user` 工具);null 表示没有 */
var aiDialog by mutableStateOf<AiSurface.Dialog?>(null)
private set
/**
* 当前对话被 AI 永久结束了 —— 界面据此把输入框换成结束横幅。
*
* ★ 这是从内核读回来的**落盘状态**(Conversation.ended),不是本地开关。
*/
var conversationEnded by mutableStateOf(false)
private set
/** AI 给出的结束原因(屏幕中间那个横幅上写的就是它) */
var endedReason by mutableStateOf("")
private set
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 agents: List<Agent> get() = state.agents
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())
messages.clear()
messages.addAll(list)
// ★ 顺手读一下这次对话是不是被 AI 结束过 —— 只读 messages 是看不出来的
// (ended 在会话对象上,不在消息里)。
val meta = runCatching {
withContext(Dispatchers.IO) { client.conversationMeta(id) }
}.getOrNull()
conversationEnded = meta?.ended == true
endedReason = meta?.endedReason.orEmpty()
}
}
@@ -111,9 +197,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
viewModelScope.launch {
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
refresh()
if (conv != null) openConversation(conv.id) else {
if (conv != null) {
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
conversationEnded = false
endedReason = ""
openConversation(conv.id)
} else {
messages.clear()
activeConversationId = ""
conversationEnded = false
endedReason = ""
}
}
}
@@ -132,6 +225,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
val text = draft.trim()
if (text.isEmpty() && attachments.isEmpty()) return
if (streaming) return
// ★ 对话被 AI 结束后就挡住 —— 界面上的输入框已经换成了横幅,
// 但发送按钮/回车/历史入口都可能绕过界面判断,所以在**这里**再拦一道。
if (conversationEnded) {
showHint("这次对话已结束,请开一个新对话")
return
}
val files = attachments.toList()
draft = ""
@@ -464,6 +563,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
saveSettings(mapOf("security" to json))
}
/**
* AI 界面能力(show_ui / ask_user / end_conversation)开关。
*
* ★ 必须写成**嵌套对象** `{"enabled": true}`,不能写成布尔 ——
* 内核 `ui_tools_enabled()` 认的就是 dict 里的 enabled。
* 而 `patchToJson` 会把 Map 递归转成 JSONObject(见那个函数的注释:
* 不转的话会变成字符串 `"{enabled=true}"`,内核每次读配置都抛 TypeError)。
* 所以这里传 Map 进去,让它走那条已经修好的转换路径。
*/
fun saveUiTools(enabled: Boolean) {
saveSettings(mapOf("uiTools" to mapOf("enabled" to enabled)))
}
}
/**

View File

@@ -309,7 +309,27 @@ fun ChatScreen(vm: AppViewModel) {
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
InputBar(vm, onPickFile, onMic, speech)
if (vm.conversationEnded) {
/**
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
*
* `Modifier.weight(1f)` 让它占掉原本给消息列表之外的全部剩余空间,
* 横幅在**这块区域的中心**(也就是视觉上的屏幕中下部)。
* 要的是"正中间",但顶部还有标题栏、下面还有输入法安全区,
* 放在这块剩余区域的中心在观感上才是居中的。
*
* 输入框在此处**整个不渲染** —— 用户看到的就是"这儿没得输了",
* 而不是一个点了没反应的框。
*/
Box(Modifier.weight(1f).fillMaxWidth()) {
EndedBanner(
reason = vm.endedReason,
onNewConversation = { vm.newTopic() },
)
}
} else {
InputBar(vm, onPickFile, onMic, speech)
}
}
val thinkingVisible = vm.thinkingIndex in vm.messages.indices

View File

@@ -77,6 +77,22 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
@Composable
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
/** 主色(AI 界面/弹窗里强调"选中"用) */
@Composable
fun doubaoAccent() = if (isDark()) Color(0xFF6EA8FF) else Doubao.Blue
/** 主色的浅底(选中项的背景) */
@Composable
fun doubaoAccentSoft() = if (isDark()) Color(0xFF1B2A44) else Color(0xFFEAF1FF)
/** 比 surface 稍亮/稍暗一档的容器底色(弹窗里的选项行) */
@Composable
fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg
/** 三级文字色(比 secondary 更淡,用于说明小字) */
@Composable
fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary
/* ------------------------------ 动画 ------------------------------ */
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */

View File

@@ -27,6 +27,7 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -72,6 +73,12 @@ fun SkillsScreen(vm: AppViewModel) {
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
// AI 界面能力的开关。改一下立刻存 —— 这个开关不需要"应用"按钮,
// 用户拨完就想生效(跟下面的权限白名单不一样,那个要挑一堆再一起提交)。
var uiToolsOn by remember(vm.settings.uiToolsEnabled) {
mutableStateOf(vm.settings.uiToolsEnabled)
}
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
@@ -105,6 +112,50 @@ fun SkillsScreen(vm: AppViewModel) {
) {
Spacer(Modifier.height(2.dp))
/* ============ ⓪ AI 界面能力(show_ui / ask_user / end_conversation)============
*
* 为什么单独一个卡片、而且默认关:这三个工具会让 AI **主动往用户脸上
* 弹东西**(HTML 界面、选择弹窗),甚至**把对话封掉** ——
* 属于"打扰性"能力,不该装好就默认打开。
*/
SettingsCard("AI 界面能力") {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("允许 AI 弹出界面和弹窗", fontSize = 15.sp, color = doubaoText())
Spacer(Modifier.height(3.dp))
Text(
"打开后 AI 才能用这三个工具。关掉时它们对模型完全隐藏。",
fontSize = 12.sp,
color = doubaoTextSecondary(),
lineHeight = 17.sp,
)
}
Switch(
checked = uiToolsOn,
onCheckedChange = {
uiToolsOn = it
vm.saveUiTools(it)
},
)
}
Spacer(Modifier.height(10.dp))
FormHint(
"· show_ui —— AI 自己写 HTML 弹一个全屏界面(图表、卡片、对比表)\n" +
"· ask_user —— 弹一个选择框,等用户选完再继续(最多 120 秒)\n" +
"· end_conversation —— AI 永久结束这次对话。屏幕中间会出现一条" +
"写着原因的横幅,之后要开新对话才能继续",
)
if (!uiToolsOn) {
Spacer(Modifier.height(6.dp))
Text(
"当前:关闭(模型看不到这三个工具)",
fontSize = 12.sp,
color = doubaoTextDim(),
)
}
}
/* ==================== ① 工具权限 ==================== */
SettingsCard("工具权限") {
SegmentedOptions(

View File

@@ -42,8 +42,29 @@ def _max_rounds(settings: dict) -> int:
return max(1, min(12, value))
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
#
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
# 硬塞进 markdown。
#
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
# 所以措辞是"确实用文字说不清时才用"。
UI_TOOLS_HINT = '\n'.join([
'界面能力(用户已打开):',
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
])
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
should_stop: Optional[Callable[[], bool]] = None) -> dict:
should_stop: Optional[Callable[[], bool]] = None,
conversation_id: str = '') -> dict:
"""
跑一轮完整对话。
@@ -52,6 +73,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
agent 当前智能体(systemPrompt 覆盖全局的)
emit 事件回调,直接往 SSE 里写
should_stop 客户端是否已断开(断了就别再往上游要字了)
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
"""
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
@@ -61,6 +83,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
max_rounds = _max_rounds(settings)
mode = (settings.get('security') or {}).get('mode') or 'open'
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
# ★★ 界面能力的用法**只在开关打开时才追加**。
#
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
# 按开关动态追加,两边永远一致。
#
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
if tools_runtime.ui_tools_enabled(settings):
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
thinking_level = settings.get('thinkingLevel') or 'auto'
emit({
@@ -148,10 +180,20 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
for tc in tool_calls:
tool_call_count += 1
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
# ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话",
# 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local,
# 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。
tools_runtime.push_context(
conversationId=conversation_id,
agentId=(agent or {}).get('id') or '',
toolName=tc.get('name') or '',
)
try:
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
finally:
tools_runtime.clear_context()
if result.get('ok'):
raw = result.get('result')
payload = truncate('(无输出)' if raw is None else raw)

View File

@@ -935,9 +935,24 @@ class KernelHandler(BaseHTTPRequestHandler):
self.send_json(400, {'error': '缺少 name'})
return True
try:
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
result = tools_runtime.execute_tool(name, body.get('args') or {},
{'security': {'mode': 'open'}})
# ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的),
# 但仍要能报错。所以 mode 强制 open。
#
# ★★ 但**不能**只传一个空壳 settings(以前就是 {'security':...}):
# 界面工具(show_ui/ask_user/end_conversation)的开关也在 settings 里,
# 空壳会让它们**永远被第二道拦截挡住** —— 用户在技能页点"试运行",
# 明明开关是开的,却收到"已关闭"。这个错会让人以为是开关没生效。
# 所以拿真实设置、只覆盖 security。
live = store.read_settings() or {}
settings = {**live, 'security': {'mode': 'open', 'allow': []}}
tools_runtime.push_context(
conversationId=str(body.get('conversationId') or ''),
toolName=name,
)
try:
result = tools_runtime.execute_tool(name, body.get('args') or {}, settings)
finally:
tools_runtime.clear_context()
self.send_json(200, result)
except Exception as exc: # noqa: BLE001
self.send_json(500, {'ok': False, 'error': str(exc)})
@@ -1402,6 +1417,9 @@ class KernelHandler(BaseHTTPRequestHandler):
messages=[*history, {'role': 'user', 'content': user_content}],
emit=emit,
should_stop=cancelled,
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
# end_conversation 会明确报错(而不是假装成功)。
conversation_id=conversation_id,
)
store.append_messages(conversation_id, [{

View File

@@ -180,6 +180,12 @@ DEFAULT_SETTINGS = {
'toolsDir': '',
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
'tools': {'python': True, 'mcp': True},
# 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话
# (show_ui / ask_user / end_conversation)。
#
# ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、
# 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。
'uiTools': {'enabled': False},
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
'speech': {

View File

@@ -20,6 +20,8 @@ import threading
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
BUNDLED_TOOL_FILES = [
'_protocol.py',
# 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种)
'_ui_bridge.py',
'calc.py',
'now.py',
'weather.py',
@@ -27,6 +29,10 @@ BUNDLED_TOOL_FILES = [
'web_fetch.py',
'shell.py',
'python_run.py',
# AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools)
'show_ui.py',
'ask_user.py',
'end_conversation.py',
'_mcp_python_example.py',
]

View File

@@ -35,6 +35,68 @@ _loaded_modules: dict = {}
TOOL_TIMEOUT_S = 60
BUILTIN_FILE_LABEL = '<内置>'
# --------------------------------------------------------------------------- #
# 界面工具的开关
# --------------------------------------------------------------------------- #
# 这三个工具由 AI 主动驱动界面,属于"会打扰用户"的能力,所以**默认关**,
# 用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。
UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation')
# 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键,
# 以后加界面工具不必再动 settings 的形状。
UI_TOOL_SETTINGS_KEY = 'uiTools'
# --------------------------------------------------------------------------- #
# 当前调用上下文(线程局部)
# --------------------------------------------------------------------------- #
#
# ★ 为什么需要它:工具要拿到"当前是哪次对话"才能结束对话,但工具签名是
# run(args) —— 只有模型给的参数,没有对话信息。
#
# 已有先例是往 settings 里塞 `nodeTools`(会议节点工具),但那是**工具定义**,
# 不是**运行时上下文**;上下文每轮都在变,塞进 settings 会和"设置"的语义混在一起。
#
# 所以单独开一个 thread-local:agent_loop 在执行工具前 push,
# 执行完 pop。HTTP 是每请求一线程,thread-local 天然隔离,不会串。
_ctx = threading.local()
def push_context(**kw) -> None:
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)"""
_ctx.value = dict(kw)
def clear_context() -> None:
_ctx.value = None
def current_context() -> dict:
"""当前工具调用的上下文;不在调用中时返回空 dict"""
return dict(getattr(_ctx, 'value', None) or {})
def ui_tools_enabled(settings: dict) -> bool:
"""
界面工具开了没有。
★ 默认 **False**:这三个工具会让 AI 主动弹界面/弹窗、甚至结束对话,
对用户是"打扰性"能力,不该装好就默认打开。
"""
box = (settings or {}).get(UI_TOOL_SETTINGS_KEY)
if isinstance(box, dict):
return box.get('enabled') is True
if isinstance(box, bool):
return box
return False
def filter_ui_tools(specs: list, settings: dict) -> list:
"""开关关着时,把界面工具从工具表里摘掉(模型根本看不到,也就不会调)。"""
if ui_tools_enabled(settings):
return specs
return [s for s in specs if s.get('name') not in UI_TOOLS]
# --------------------------------------------------------------------------- #
# 目录与文件
@@ -235,9 +297,27 @@ def run_python_tool(name: str, args: dict) -> dict:
runner = getattr(module, 'run')
payload = args if isinstance(args, dict) else {}
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
# 工作线程里 current_context() 永远是空的。
#
# 这个坑的表现特别隐蔽:工具照常执行(参数都对),只有"当前是哪次对话"
# 拿不到,于是 end_conversation 报"拿不到当前对话 id"。我一开始以为是
# app.py 没传 conversationId,查了一圈才发现是线程的问题。
ctx = current_context()
def _invoke():
if ctx:
_ctx.value = dict(ctx)
try:
return runner(payload)
finally:
if ctx:
_ctx.value = None
try:
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S)
outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S)
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
@@ -381,6 +461,8 @@ def build_tool_defs(settings: dict) -> list:
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
defs = defs + node_tool_defs(settings)
# 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏
defs = filter_ui_tools(defs, settings)
return apply_security(defs, settings)
@@ -393,6 +475,15 @@ def execute_tool(name: str, args: dict, settings: dict) -> dict:
allow = ((settings or {}).get('security') or {}).get('allow') or []
if name not in allow:
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
# ★ 界面工具的第二道拦截:开关关着时,即使模型硬编名字也不执行。
# (第一道是 build_tool_defs 里根本不把它给模型看。)
# 两道都要有 —— 只藏不给看的话,用户把工具关掉之后模型仍可能
# 从历史消息里学会这个名字再调一次。
if name in UI_TOOLS and not ui_tools_enabled(settings):
return {
'ok': False,
'error': f'界面工具「{name}」已关闭。请在「技能」页打开"AI 界面能力"后再用。',
}
# 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义)
if name in node_tool_names(settings):
return run_node_tool(name, args, settings)