Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52680b9eb7 | ||
|
|
6197b726a5 | ||
|
|
cead531983 | ||
|
|
2601e9ae43 |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 234
|
||||
versionName = "2.0.34"
|
||||
versionCode = 235
|
||||
versionName = "2.0.35"
|
||||
|
||||
ndk {
|
||||
// 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) {
|
||||
client.baseUrl = "http://127.0.0.1:$port"
|
||||
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||
KernelHost.set(port)
|
||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||
withContext(Dispatchers.IO) {
|
||||
|
||||
@@ -20,7 +20,10 @@ import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -67,6 +70,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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 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.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)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
/* ------------------------------ 动画 ------------------------------ */
|
||||
|
||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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, [{
|
||||
|
||||
@@ -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': {
|
||||
|
||||
@@ -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',
|
||||
]
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
> 这份文档的作用:**让这件事不依赖任何人的记忆**。
|
||||
> 换一个会话、换一个人接手,从这一页就能继续。
|
||||
|
||||
最后更新:v2.0.33
|
||||
最后更新:v2.0.34
|
||||
|
||||
---
|
||||
|
||||
@@ -123,6 +123,121 @@ $ pip install six → six 1.17.0 OK
|
||||
$ dpkg -l | grep -v ^ii → (空,全部配置完成)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ★★ v2.0.34:用户反馈单里的三条
|
||||
|
||||
### ① PYTHONPATH 把 3.13 的 .imy 硬塞给 3.14(致命)
|
||||
|
||||
```
|
||||
Fatal Python error: Failed to import encodings module
|
||||
zipimport.ZipImportError: module load failed: bad magic number
|
||||
in 'encodings': b'\xf3\r\r\n'
|
||||
```
|
||||
|
||||
**根因**:App 自己跑着一个 Chaquopy 的 CPython 3.13,它为了让自己的解释器
|
||||
找到标准库,在**进程环境里**设了 `PYTHONPATH` 指向 `files/chaquopy/*.imy`。
|
||||
而 `ProcessBuilder` / `TerminalSession` 起的都是子进程,**继承整个 App 进程
|
||||
的环境** —— 于是 Termux 里 apt 装的 python 3.14 一启动就读到 3.13 编的
|
||||
`encodings`,魔数不符(`0x0df3` vs `0x0df4`),解释器初始化直接崩。
|
||||
|
||||
**怎么验证的**(反馈单里用户自己就查对了):
|
||||
```
|
||||
$ grep -r PYTHONPATH $PREFIX/etc/ → 空(Termux 自己没设)
|
||||
$ tr '\0' '\n' < /proc/self/environ | grep PYTHONPATH → 有(父进程灌的)
|
||||
$ PYTHONPATH=…/stdlib-common.imy python3 -c 'import encodings'
|
||||
→ 一字不差复现崩溃
|
||||
```
|
||||
|
||||
**修法**:`TermuxInstaller.childEnvMap()` —— **以父环境为底**(保住
|
||||
`ANDROID_ROOT` 之类系统变量)、覆盖上 Termux 那一套、再摘掉
|
||||
`PYTHONPATH` / `PYTHONHOME` / `PYTHONSTARTUP` 等宿主 Python 变量。
|
||||
|
||||
★ 只摘子进程的,**不动 App 自己的** —— Chaquopy 那个解释器*需要*
|
||||
`PYTHONPATH` 才能找标准库,全局清掉会把内核搞死。
|
||||
|
||||
★ 所有起子进程的地方都要用它:`TermuxShell.run`、`TermuxTerminal`、
|
||||
`TermuxMirror` 的探测。注意 `environment().putAll(...)` 是**追加**,
|
||||
删不掉已有的键 —— 只 putAll 是修不掉这个 bug 的。
|
||||
|
||||
### ② pip 用不了 —— `rewritePrefixes` 的替换顺序错了
|
||||
|
||||
`pip3` 的 shebang 是 `#!/data/data/com.termux/files/usr/bin/python3.14`,
|
||||
而改写只做了 `oldData → dataDir`,产出
|
||||
|
||||
```
|
||||
#!/data/<包名>/files/files/usr/bin/python3.14 ← 多一层 files,解析不了
|
||||
#!<prefix>/bin/python3.14 ← 正确
|
||||
```
|
||||
|
||||
**为什么多一层就解析不了**:沙箱里 `files/home` 那条链只兜住了 home,
|
||||
`<pkg>/files/files/usr/...` 里的第二个 `files` 是 `<pkg>/files` 下一个
|
||||
**不存在的目录**(实测 `No such file or directory` / `Permission denied`)。
|
||||
|
||||
**修法**:**先换长路径再换短的** ——
|
||||
`/data/data/com.termux/files/usr` → `<prefix>`,然后才 `…/com.termux` → `dataDir`。
|
||||
维护脚本那支同样处理。STAMP 25→26→27,老设备进一次终端自动补跑。
|
||||
|
||||
### ③ `/tmp` 不可写 —— 只能部分修好,如实说明
|
||||
|
||||
`/tmp` 在 **root 下根本不存在**,而 root 是**只读**的:
|
||||
|
||||
```
|
||||
$ mkdir /tmp → Read-only file system
|
||||
$ ln -s … /tmp → Read-only file system
|
||||
```
|
||||
|
||||
`libtermux-exec.so` **只改写 Termux 自己那个前缀**,不管 `/tmp`
|
||||
(实测 `touch /tmp/x` 仍然失败)。`--instdir` 那条沙箱路也拦不住 ——
|
||||
内核解析的是根下的绝对路径。在 `/data/data` 下建 `com.termux` 软链也不行
|
||||
(`drwxrwx--x system system`,应用写不了)。
|
||||
|
||||
**能做的已经做了**:`TMPDIR` 一直是对的,实测**尊重 `TMPDIR` 的工具全部正常**:
|
||||
|
||||
```
|
||||
$ mktemp → <prefix>/tmp/tmp.XXXX
|
||||
$ python -c 'tempfile…' → <prefix>/tmp
|
||||
```
|
||||
|
||||
所以只有"把 `/tmp` 写死在代码里"的程序会受影响。这是 Android 的限制,
|
||||
不是能绕的技术问题。
|
||||
|
||||
### ④ 镜像同步中会把用户卡死 —— 加自动换源
|
||||
|
||||
用户卡住的那条报错其实是**清华镜像正在同步**:
|
||||
|
||||
```
|
||||
E: Failed to fetch …/Packages.bz2
|
||||
File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
```
|
||||
|
||||
实测各镜像健康度(Release 声明值 vs 实际下载值):
|
||||
|
||||
| 镜像 | 结果 |
|
||||
|---|---|
|
||||
| 清华 TUNA | 586556 vs **583395** ✗ |
|
||||
| 中科大 USTC | 585742 vs 585742 ✓ |
|
||||
| 北外 BFSU | 590396 vs 590396 ✓ |
|
||||
| 官方源 | 584437 vs 584437 ✓ |
|
||||
|
||||
而我们默认给的就是清华 —— 任何单一默认值都会偶尔把所有人卡在同一个坏源上。
|
||||
|
||||
`TermuxMirror.autoPickIfBroken()`:后台**真跑一次 `apt-get update`** 当探测
|
||||
(不自己写校验 —— apt 比我们严,而且换源后本来就要 update),
|
||||
探测失败就按源列表往下试,成功则记住并记日志。当前源能用就一个字都不改。
|
||||
|
||||
### ⑤ 附件不告知路径 —— 两端都修了
|
||||
|
||||
- 每条附件消息都带 `本地路径:<绝对路径>`(**三条分支**都要带 ——
|
||||
以前只有二进制那条带,而*恰恰是文本最需要*:超 20000 字符会截断)
|
||||
- 落盘命名从 base36 乱码换成可读的 `20260101-120000_原名.ext`,重名加 `-1`
|
||||
- 系统提示词加了两条告诉模型"那个路径是真的、可以用 shell 打开"
|
||||
- ★ **Node 版(server/src/uploads.mjs、config.mjs)也要跟上** ——
|
||||
两份实现,改一份就是"引擎改了另一端没跟上"。
|
||||
`scripts/verify-uploads-parity.py` 守这个一致性
|
||||
|
||||
---
|
||||
|
||||
### 已知的残留噪音
|
||||
|
||||
`bin/bash` 和 `bin/dash` 里还有少量编译死的 `com.termux` 路径
|
||||
|
||||
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("✅ 全部通过")
|
||||
170
scripts/verify-uploads-parity.py
Normal file
170
scripts/verify-uploads-parity.py
Normal file
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""守 Android 内核(Python)和桌面服务(Node)两份附件实现的一致性。
|
||||
|
||||
为什么要对拍:这两个端跑的是**同一个内核的另一份实现**,
|
||||
`uploads.py` 和 `uploads.mjs` 的字段名、文件命名、喂给模型的文案
|
||||
必须一模一样 —— 不一样的话"同一句话在两个端上表现不同",
|
||||
而且这种漂移**不会报错**,只会让行为悄悄分叉(这个仓库里已经有过好几次)。
|
||||
|
||||
用法:
|
||||
python scripts/verify-uploads-parity.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
PY = os.path.join(ROOT, "android", "kernel", "uploads.py")
|
||||
JS = os.path.join(ROOT, "server", "src", "uploads.mjs")
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def read(p):
|
||||
if not os.path.isfile(p):
|
||||
print(f"!! 找不到 {p}")
|
||||
sys.exit(1)
|
||||
return open(p, encoding="utf-8").read()
|
||||
|
||||
|
||||
py, js = read(PY), read(JS)
|
||||
|
||||
print("=== 附件实现两端对拍 ===")
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] 落盘文件名的形状")
|
||||
# 两边都该是 f'{stamp()}_{safeName}' 这种,且用可读时间戳
|
||||
for name, text, stamp_re in (
|
||||
("uploads.py", py, r"\d{8}-\d{6}"),
|
||||
("uploads.mjs", js, r"\d{8}-\d{6}"),
|
||||
):
|
||||
if "stamp" not in text:
|
||||
fail(f"{name} 里没有 stamp(文件名时间戳)")
|
||||
else:
|
||||
ok(f"{name} 有 stamp()")
|
||||
|
||||
if "_stamp" in py and "%Y%m%d-%H%M%S" in py:
|
||||
ok("uploads.py 的时间戳格式是 %Y%m%d-%H%M%S(可读)")
|
||||
else:
|
||||
fail("uploads.py 的时间戳格式不是可读形式")
|
||||
|
||||
if "getFullYear" in js and "padStart" in js:
|
||||
ok("uploads.mjs 的时间戳格式是 YYYYMMDD-HHMMSS(可读)")
|
||||
else:
|
||||
fail("uploads.mjs 的时间戳格式不是可读形式")
|
||||
|
||||
# 不该再用 base36 时间戳**做文件名**。
|
||||
# ★ 注意 `rid()` 里仍然用 toString(36) 生成 id —— 那是 id,不是文件名,
|
||||
# 不该一起否掉(第一版这里判宽了)。
|
||||
if re.search(r"path\.join\([^)]*toString\(36\)", js):
|
||||
fail("uploads.mjs 的文件名里还在用 base36 时间戳(不可读)")
|
||||
else:
|
||||
ok("uploads.mjs 的文件名不再用 base36 时间戳")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] 重名消歧 + 保留扩展名")
|
||||
for name, text in (("uploads.py", py), ("uploads.mjs", js)):
|
||||
if "unique" in text.lower() and "splitext" in text or "extname" in text:
|
||||
ok(f"{name} 有唯一化 + 保留扩展名")
|
||||
else:
|
||||
fail(f"{name} 缺唯一化或没保扩展名")
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
print("\n[3] 每条分支都给出本地路径")
|
||||
for name, text in (("uploads.py", py), ("uploads.mjs", js)):
|
||||
n = text.count("本地路径:")
|
||||
# 三条分支:图片 / 文本 / 二进制
|
||||
if n >= 3:
|
||||
ok(f"{name} 有 {n} 处「本地路径:」(三条分支都覆盖)")
|
||||
else:
|
||||
fail(f"{name} 只有 {n} 处「本地路径:」,应有 3 处")
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
print("\n[4] 喂给模型的文案一致")
|
||||
# ★ 不做整串字面比对 —— 两端写法本来就不同:
|
||||
# Python 是 f-string(`\n` 是真实换行),JS 是模板字符串(`\n` 是反斜杠+n),
|
||||
# ``` 代码块在 JS 里还要转义。
|
||||
# 我第一版硬比字面,结果在"转义怎么写"上反复误报,纯属浪费。
|
||||
#
|
||||
# 改成比对两件**本质**的东西:
|
||||
# · 文案里的**中文固定片段**(用户能看到的那些字)
|
||||
# · 插值位置的**变量名**
|
||||
# 这两样一致,模型看到的东西就一致;剩下的是同义写法,无所谓。
|
||||
def fragments(text):
|
||||
"""文案里的中文固定片段(去掉所有插值和反斜杠转义)"""
|
||||
out = set()
|
||||
for m in re.finditer(r"【[^】]*】", text):
|
||||
s = m.group(0)
|
||||
s = re.sub(r"\$\{[^}]*\}", "", s)
|
||||
s = re.sub(r"\{[^}]*\}", "", s)
|
||||
s = s.replace("\\", "")
|
||||
out.add(s)
|
||||
return out
|
||||
|
||||
|
||||
def vars_used(text):
|
||||
"""插值用到的变量名(两端各自的写法都归一)"""
|
||||
out = set()
|
||||
for m in re.finditer(r"\$\{([^}]*)\}", text):
|
||||
out.add(m.group(1).strip())
|
||||
for m in re.finditer(r"\{([A-Za-z_][^}]*)\}", text):
|
||||
out.add(m.group(1).strip())
|
||||
return out
|
||||
|
||||
|
||||
py_f, js_f = fragments(py), fragments(js)
|
||||
if py_f == js_f:
|
||||
ok(f"固定文案片段一致({len(py_f)} 条):{sorted(py_f)}")
|
||||
else:
|
||||
fail("固定文案片段不一致:")
|
||||
print(" python 独有:", sorted(py_f - js_f))
|
||||
print(" node 独有:", sorted(js_f - py_f))
|
||||
|
||||
# 关键变量两边都要用:路径 / 名字 / 大小
|
||||
need = {"path", "name", "size"}
|
||||
py_v, js_v = vars_used(py), vars_used(js)
|
||||
for label, used in (("uploads.py", py_v), ("uploads.mjs", js_v)):
|
||||
miss = {n for n in need if not any(n in u for u in used)}
|
||||
if miss:
|
||||
fail(f"{label} 的文案里没用到 {sorted(miss)}")
|
||||
else:
|
||||
ok(f"{label} 的文案用到了 path/name/size")
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
print("\n[5] 系统提示词的附件说明")
|
||||
dpy = read(os.path.join(ROOT, "android", "kernel", "defaults.py"))
|
||||
dcfg = read(os.path.join(ROOT, "server", "src", "config.mjs"))
|
||||
key = "关于用户发来的文件(附件):"
|
||||
if key in dpy and key in dcfg:
|
||||
ok("两端提示词都有附件说明")
|
||||
else:
|
||||
fail(f"提示词缺附件说明(python={key in dpy} node={key in dcfg})")
|
||||
|
||||
for label, text in (("defaults.py", dpy), ("config.mjs", dcfg)):
|
||||
if "本地路径" in text or "真实位置" in text:
|
||||
ok(f"{label} 提示词里告诉了模型路径可用")
|
||||
else:
|
||||
fail(f"{label} 提示词没提路径")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 两端一致")
|
||||
@@ -257,7 +257,16 @@ export const DEFAULT_SYSTEM_PROMPT = [
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
'',
|
||||
'关于用户发来的文件(附件):',
|
||||
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
|
||||
' **那个路径是文件在磁盘上的真实位置**,可以直接用 shell 或 python 工具打开它 ——',
|
||||
' 不要猜路径,也不要说"我拿不到文件"。',
|
||||
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
|
||||
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
|
||||
].join('\n');
|
||||
// ★ 上面这段必须和安卓内核 android/kernel/defaults.py 的 DEFAULT_SYSTEM_PROMPT
|
||||
// 逐字一致 —— 两边跑同一个内核,提示词不一样会让"同一句话在两个端上表现不同"。
|
||||
|
||||
export const DEFAULT_SETTINGS = {
|
||||
provider: 'ark',
|
||||
|
||||
@@ -56,12 +56,49 @@ function mimeOf(name) {
|
||||
return map[ext] || (isText(name) ? 'text/plain' : 'application/octet-stream');
|
||||
}
|
||||
|
||||
/**
|
||||
* 落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。
|
||||
*
|
||||
* ★ 以前用的是 `Date.now().toString(36)`(形如 `m5k8xk2`)—— 唯一优点是
|
||||
* 不会重名,缺点是**看见文件名完全不知道是什么时候的东西**。
|
||||
* 用户明确反馈过(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名临时件"。
|
||||
*
|
||||
* ★ 秒级精度会撞名,靠 uniquePath() 消歧,不靠时间戳本身保证唯一。
|
||||
* 和安卓内核 kernel/uploads.py 的 `_stamp()` 保持同一格式。
|
||||
*/
|
||||
function stamp() {
|
||||
const d = new Date();
|
||||
const p = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`
|
||||
+ `-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`…
|
||||
*
|
||||
* ★ 一定保留扩展名:`report.pdf` → `report-1.pdf`,不是 `report.pdf-1` ——
|
||||
* 连我们自己的 isImage()/mimeOf() 都按扩展名判断类型。
|
||||
* 和 kernel/uploads.py 的 `_unique_path()` 行为一致。
|
||||
*/
|
||||
function uniquePath(dir, safeName) {
|
||||
const ext = path.extname(safeName);
|
||||
const base = path.basename(safeName, ext);
|
||||
const s = stamp();
|
||||
for (let i = 0; i < 1000; i += 1) {
|
||||
const suffix = i === 0 ? '' : `-${i}`;
|
||||
const candidate = path.join(dir, `${s}_${base}${suffix}${ext}`);
|
||||
if (!fs.existsSync(candidate)) return candidate;
|
||||
}
|
||||
return path.join(dir, `${s}_${base}-${Math.random().toString(36).slice(2, 6)}${ext}`);
|
||||
}
|
||||
|
||||
function meta(filePath, name, { copy = true } = {}) {
|
||||
const stat = fs.statSync(filePath);
|
||||
let storedPath = filePath;
|
||||
let url = '';
|
||||
if (copy && stat.size <= COPY_LIMIT) {
|
||||
const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`);
|
||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||
const target = uniquePath(UPLOADS_DIR, safeName(name));
|
||||
fs.copyFileSync(filePath, target);
|
||||
storedPath = target;
|
||||
url = `/uploads/${path.basename(target)}`;
|
||||
@@ -82,7 +119,8 @@ export function saveUpload({ name, base64 }) {
|
||||
if (!name || !base64) throw new Error('缺少 name 或 base64');
|
||||
const buffer = Buffer.from(String(base64).replace(/^data:[^,]+,/, ''), 'base64');
|
||||
if (buffer.length > COPY_LIMIT) throw new Error(`文件超过 ${COPY_LIMIT / 1024 / 1024}MB`);
|
||||
const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`);
|
||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||
const target = uniquePath(UPLOADS_DIR, safeName(name));
|
||||
fs.writeFileSync(target, buffer);
|
||||
return {
|
||||
id: rid(),
|
||||
@@ -114,6 +152,16 @@ export function takePending() {
|
||||
|
||||
/**
|
||||
* 把附件转成模型能吃的形式。
|
||||
*
|
||||
* ★★ **每一条分支都会把落盘的绝对路径写进 text。**
|
||||
*
|
||||
* 这是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉模型
|
||||
* 文件落在哪,模型想去 shell / python 里处理它只能靠猜。之前只有"二进制"
|
||||
* 那条给了路径,而**恰恰是文本最需要** —— 超过 20000 字符会被截断,
|
||||
* 被截掉的那部分只能靠模型自己去读原文件。
|
||||
*
|
||||
* 格式和安卓内核 kernel/uploads.py 的 attachmentPayload 保持一致。
|
||||
*
|
||||
* @returns {{text: string, images: {url: string}[]}}
|
||||
*/
|
||||
export function attachmentPayload(attachment) {
|
||||
@@ -126,7 +174,7 @@ export function attachmentPayload(attachment) {
|
||||
if (isImage(attachment.name) && size <= VISION_LIMIT) {
|
||||
const b64 = fs.readFileSync(attachment.path).toString('base64');
|
||||
out.images.push({ url: `data:${attachment.mime};base64,${b64}` });
|
||||
out.text = `【图片 ${attachment.name}】`;
|
||||
out.text = `【图片 ${attachment.name}(${size} 字节)本地路径:${attachment.path}】`;
|
||||
return out;
|
||||
}
|
||||
if (isText(attachment.name) || size < 64 * 1024) {
|
||||
@@ -138,7 +186,7 @@ export function attachmentPayload(attachment) {
|
||||
}
|
||||
if (body) {
|
||||
const clipped = body.length > 20000 ? `${body.slice(0, 20000)}\n…(已截断,共 ${body.length} 字符)` : body;
|
||||
out.text = `【文件 ${attachment.name}(${size} 字节)】\n\`\`\`\n${clipped}\n\`\`\``;
|
||||
out.text = `【文件 ${attachment.name}(${size} 字节)本地路径:${attachment.path}】\n\`\`\`\n${clipped}\n\`\`\``;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
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