From b1dd740b0daab051aecac6099671daeec9e09e15 Mon Sep 17 00:00:00 2001 From: doubao Date: Thu, 15 Oct 2026 14:11:44 +0800 Subject: [PATCH] =?UTF-8?q?AI=20=E7=95=8C=E9=9D=A2=E5=8F=AF=E4=BB=A5?= =?UTF-8?q?=E5=86=8D=E7=82=B9=E5=BC=80=20+=20=E6=96=B0=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E3=80=8C=E7=BB=99=E4=BC=9A=E8=AF=9D=E5=8F=91=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E3=80=8D(v2.0.40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户两条需求: ① "AI 写的界面可以再点开"(并纠正:是 AI 写的界面本身,不是它提到的链接) ② "给 ai 加个接口:给本次会话发送消息" ## ① AI 界面再点开 以前界面**只活在内存里** —— 用户一关(或退出 App)就没了。 想再看只能让 AI 重新生成,而**重新生成的内容不一定一样**(模型有随机性), 用户会觉得"我明明看过的东西怎么变了"。 现在每次 `show_ui` 都存一份: · 正文存 `/ai-screens/.html`,索引存同目录 `index.json` · `screenId` 随工具返回值回到模型 → 再进 App 的工具痕迹记录 · **消息操作栏据此出现「界面」按钮**(只有这条回复真弹过界面才出现) · 另外在抽屉里加了「AI 界面」入口 = 独立全屏列表,能翻看/删除所有存过的界面 ★ 为什么存 App 侧(Kotlin)而不是内核(Python): 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的 `device()` 参数。要走内核就得 Kotlin 再 POST 一次,多一次往返、多一个失败点。 而 App 私有目录本来就是 Kotlin 最顺手的地方。 ★ 每个会话只留最近 30 个(超了删最旧的正文),否则聊久了列表没法看、磁盘白占。 ## ② 新工具 send_message:AI 主动往当前会话发消息 ``` send_message(text="在干嘛呢", reply=false, role="user") ``` 消息**像用户说的话一样进历史**,显示在聊天里。适合角色扮演主动找话题、 长任务先贴个中间结果、用户在界面上点了东西要在对话里留个记录。 ### ★★★ 这个工具最危险的是死循环,做了三道闸 模型发消息 → 内核顺手跑回复 → 那一轮里模型又发消息 → 无限套娃 一个下午能把 API 额度烧光,用户看到满屏自己没发过的消息 · **闸① 嵌套深度**:`send_message` 触发的回复里最多再发 2 层。 深度经 `tools_runtime.push_context(sendDepth=…)` → Kotlin 桥 → 内核一路传下去。 (那个上下文是**跨线程搬过去**的 —— `threading.local` 不跨线程继承, 这个坑之前踩过,所以 `run_python_tool` 里专门搬了一次。) · **闸② 每会话条数上限**:20 条。即使深度那条因为某个环节没传到而失效, 条数上限也能兜住。 · **闸③ 默认不触发回复**:`reply` 默认 false。 默认 true 的话,界面上一次 `Doubao.sendToAi` 就会连锁跑起模型 —— 用户会觉得"它怎么自己说起来了",而且很容易撞额度。 ★ 计数**从会话历史里数**(靠消息上的 `aiSent` 内部标记),不用内存计数器。 第一版就是内存计数,两个毛病:重启 App 就清零(上限形同虚设)、 写失败时可能多计(拒绝信息里的数字和实际条数对不上)。数历史自洽、跨重启。 ★ 要顺手回一轮时,回复**必须放后台线程** —— 当前线程正被 `send_message` 工具占着(模型还在等返回值),在这里同步跑一轮回复会**死锁**(等自己)。 用 poll 那条路,事件进 `_RUNS`,界面能收到。 ★ `send_message` 也归到 `UI_TOOLS` 里(默认关): 它会让 AI 主动塞消息,同样是打扰性能力,而且能连锁调模型 —— 默认开着的风险比 show_ui / ask_user / end_conversation 还大。 ## 实测(真机 Android 14 x86_64) 界面再点开: · `show_ui` 返回 `screenId: s_70ca75ac13bb` · `ui_screen_list` 列出它,预览文字正确(标题 + 正文片段) · `ui_screen_reopen` 读磁盘那份重新显示 → 界面上的 MARKER 和图形都在 ✓ send_message 三道闸: · 正常发送 → 进历史、内容/角色都对 ✓ · assistant 角色也能发 ✓ · 空 text / 缺 conversationId → 拒绝 ✓ · **闸①** depth=9 → 拒绝,且**没有写进会话** ✓ · **闸②** 发到第 20 条被拒,拒绝理由说清上限 ✓ · 到上限后再发仍然被拒(不会因为计数器重置而复活)✓ ## 顺带 · 修 `extractUrls` 时发现的 Kotlin 字符串模板坑:`"$owner里提到的网页"` 会把后面几个汉字当成变量名的一部分(报未解析引用),必须写 `${owner}`。 · `rememberAppViewModel` 里 `viewModel(...)` 必须写 `viewModel(...)`, 不写类型推断会挂,报的是"Not enough information to infer type argument", 下面那句 `vm.appContext` 跟着报未解析引用 —— 看着完全不像泛型问题。 --- android/app/build.gradle.kts | 4 +- .../java/com/doubao/lynxclone/NativeBridge.kt | 117 +++++++++- .../com/doubao/lynxclone/termux/AiSurface.kt | 143 +++++++++++- .../doubao/lynxclone/ui/AiScreenListScreen.kt | 207 ++++++++++++++++++ .../java/com/doubao/lynxclone/ui/AppRoot.kt | 46 +++- .../com/doubao/lynxclone/ui/AppViewModel.kt | 117 +++++++++- .../com/doubao/lynxclone/ui/ChatScreen.kt | 28 +++ android/kernel/agent_loop.py | 11 +- android/kernel/app.py | 134 +++++++++++- android/kernel/doubao_entry.py | 2 + android/kernel/paths.py | 5 +- android/kernel/store.py | 193 ++++++++++++++++ android/kernel/tools_runtime.py | 10 +- scripts/probe-reopen-screen.py | 120 ++++++++++ scripts/probe-send-message.py | 136 ++++++++++++ tools/.shipped-hashes.json | 6 +- tools/send_message.py | 151 +++++++++++++ tools/show_ui.py | 10 + 18 files changed, 1423 insertions(+), 17 deletions(-) create mode 100644 android/app/src/main/java/com/doubao/lynxclone/ui/AiScreenListScreen.kt create mode 100644 scripts/probe-reopen-screen.py create mode 100644 scripts/probe-send-message.py create mode 100644 tools/send_message.py diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index eba6afe..b38f8ef 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 239 - versionName = "2.0.39" + versionCode = 240 + versionName = "2.0.40" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt index 066f18c..fe95e5a 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt @@ -76,8 +76,14 @@ class NativeBridge(private val activity: Activity) { // (tools_runtime 有两道拦截)。但这里**不再判一次开关** —— // 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。 "ui_screen" -> uiScreen(req) + // 再打开一个存下来的界面(用户要求"AI 写的界面可以再点开") + "ui_screen_reopen" -> uiScreenReopen(req) + "ui_screen_list" -> uiScreenList(req) + "ui_screen_delete" -> uiScreenDelete(req) "ui_dialog" -> uiDialog(req) "end_conversation" -> endConversation(req) + // AI 主动往会话里发一条消息(tools/send_message.py) + "session_message" -> sessionMessage(req) // AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult) "ui_result" -> pushUiResult(req) else -> JSONObject().put("error", "未知 action:$action") @@ -87,6 +93,37 @@ class NativeBridge(private val activity: Activity) { }.toString() } + /** + * AI 主动往**当前会话**里发一条消息(`tools/send_message.py`)。 + * + * 走内核的 `/api/session-message` —— 那边负责落进会话历史、 + * 以及**两道防死循环的闸**(嵌套深度、每会话条数)。 + * + * ★ 为什么闸不在 Kotlin 这层做:内核才有会话上下文和那两处的计数。 + * 这层只转发,判断留给一处,避免两个地方规则不一致。 + */ + private fun sessionMessage(req: JSONObject): JSONObject { + val conv = req.optString("conversationId").trim() + val text = req.optString("text").trim() + if (conv.isEmpty()) return JSONObject().put("error", "缺少 conversationId") + if (text.isEmpty()) return JSONObject().put("error", "text 是空的") + return try { + val body = JSONObject() + .put("conversationId", conv) + .put("text", text) + .put("role", req.optString("role", "user")) + .put("reply", req.optBoolean("reply", false)) + .put("depth", req.optInt("depth", 1)) + val resp = kernelPost("/api/session-message", body) ?: return JSONObject() + .put("error", "内核没响应,消息没发出去") + // 内核把"闸门拒绝"也放在 error 字段里(HTTP 200 + error)—— + // 所以这里原样透传,别把它当成成功。 + resp + } catch (t: Throwable) { + JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}") + } + } + /** * ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。** * @@ -138,17 +175,91 @@ class NativeBridge(private val activity: Activity) { val html = req.optString("html") if (html.isBlank()) return JSONObject().put("error", "html 是空的") val wait = req.optBoolean("wait", false) + val title = req.optString("title") + val fullHtml = req.optBoolean("full_html", false) + val convId = req.optString("conversationId") + + // ★★ 先存一份到磁盘 —— **关掉之后还能再打开**。 + // 用户的原话:"AI 写的界面可以再点开"。 + // 以前界面只活在内存里,一关(或退出 App)就没了;想再看只能让 AI + // 重新生成,而重新生成的内容不一定一样(模型有随机性)—— + // 用户会觉得"我明明看过的东西怎么变了"。 + // + // 存失败不影响弹出(用户至少还能看这一眼),所以不抛异常。 + val saved = runCatching { + AiSurface.saveScreen(activity, html, title, fullHtml, convId) + }.getOrNull() + val screenId = saved?.optString("id").orEmpty() + if (wait) AiSurface.armScreenLatch() return AiSurface.showScreen( html = html, - title = req.optString("title"), - fullHtml = req.optBoolean("full_html", false), - conversationId = req.optString("conversationId"), + title = title, + fullHtml = fullHtml, + conversationId = convId, wait = wait, timeoutMs = req.optLong("timeoutMs", 120_000L), + screenId = screenId, ) } + /** + * 再打开一个存下来的界面。 + * + * ★ 和 [uiScreen] 的区别:那个是"AI 刚写了一个新界面", + * 这个是"用户想再看一遍**以前那个**"。后者不需要模型参与 —— + * 内容就在磁盘上,读出来直接显示。 + */ + private fun uiScreenReopen(req: JSONObject): JSONObject { + val id = req.optString("screenId") + if (id.isBlank()) return JSONObject().put("error", "缺少 screenId") + val html = AiSurface.readScreen(activity, id) + ?: return JSONObject().put("error", "这个界面已经不在了(可能被清理或删除)") + + // 从索引里把标题 / fullHtml 取回来,不然重开之后标题会变成"AI 界面" + var title = "" + var fullHtml = false + val arr = AiSurface.loadScreenIndex(activity) + for (i in 0 until arr.length()) { + val it = arr.optJSONObject(i) ?: continue + if (it.optString("id") == id) { + title = it.optString("title") + fullHtml = it.optBoolean("fullHtml") + break + } + } + + AiSurface.showScreen( + html = html, + title = title, + fullHtml = fullHtml, + conversationId = req.optString("conversationId"), + wait = false, + screenId = id, + ) + return JSONObject().put("ok", true).put("screenId", id) + } + + /** 列出存下来的界面(消息操作栏的「界面」按钮用它) */ + private fun uiScreenList(req: JSONObject): JSONObject { + val conv = req.optString("conversationId") + val arr = AiSurface.loadScreenIndex(activity) + val out = JSONArray() + for (i in 0 until arr.length()) { + val it = arr.optJSONObject(i) ?: continue + if (conv.isNotBlank() && it.optString("conversationId") != conv) continue + out.put(it) + } + return JSONObject().put("screens", out) + } + + private fun uiScreenDelete(req: JSONObject): JSONObject { + val id = req.optString("screenId") + if (id.isBlank()) return JSONObject().put("error", "缺少 screenId") + AiSurface.deleteScreen(activity, id) + return JSONObject().put("ok", true) + } + /** * AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。 * diff --git a/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt b/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt index cce9723..6ff5d7b 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/termux/AiSurface.kt @@ -59,6 +59,8 @@ object AiSurface { val conversationId: String, /** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */ val waiting: Boolean = false, + /** 磁盘上那一份的 id(空 = 没存)。再打开时靠它去读。 */ + val screenId: String = "", ) data class Option(val label: String, val value: String, val description: String) @@ -90,6 +92,133 @@ object AiSurface { // ------------------------------------------------------------------ 界面 + /** + * 把界面存一份到磁盘 —— **关掉之后还能再打开**。 + * + * ## 为什么需要(用户的原话:"AI 写的界面可以再点开") + * + * 界面以前只活在内存里:用户一关(或者退出 App),那份 HTML 就没了。 + * 过一会儿想"刚才那个图表再看一眼"就再也找不回来,只能让 AI 重新生成 —— + * 而重新生成的内容**和上次不一定一样**(模型有随机性), + * 用户看到的是"我明明看过的东西怎么变了"。 + * + * ## 为什么不放内核(Python)那边 + * + * 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的 + * `device()` 参数。要走内核就得 Kotlin 再 POST 一次上去,多一次往返、 + * 还多一个失败点。而 App 私有目录本来就是 Kotlin 最顺手的地方。 + * + * 存法: + * `/ai-screens/.html` 正文 + * `/ai-screens/index.json` 索引(列表只读这个) + */ + private val screensLock = Any() + + fun screenDir(ctx: android.content.Context): java.io.File = + java.io.File(ctx.filesDir, "ai-screens").apply { mkdirs() } + + fun screenIndexFile(ctx: android.content.Context): java.io.File = + java.io.File(screenDir(ctx), "index.json") + + fun loadScreenIndex(ctx: android.content.Context): JSONArray = synchronized(screensLock) { + try { + val text = screenIndexFile(ctx).readText() + JSONArray(text) + } catch (_: Throwable) { + JSONArray() + } + } + + private fun saveScreenIndex(ctx: android.content.Context, arr: JSONArray) { + try { + screenIndexFile(ctx).writeText(arr.toString()) + } catch (t: Throwable) { + Log.w(TAG, "写界面索引失败:${t.message}") + } + } + + /** + * 存下一个界面,返回它的索引项(含 id)。 + * + * ★ 每个会话只留最近 [KEEP_PER_CONV] 个:用户跟 AI 聊久了会弹出几十个界面, + * 列表没法看、磁盘也白占。超出时把**最旧的正文删掉**(索引项也去掉), + * 保留最近这些。 + */ + fun saveScreen( + ctx: android.content.Context, + html: String, + title: String, + fullHtml: Boolean, + conversationId: String, + ): JSONObject? { + val id = "s_" + java.util.UUID.randomUUID().toString().replace("-", "").take(12) + return try { + java.io.File(screenDir(ctx), "$id.html").writeText(html) + val item = JSONObject() + .put("id", id) + .put("title", title.ifBlank { "AI 界面" }) + .put("fullHtml", fullHtml) + .put("bytes", html.length) + .put("conversationId", conversationId) + .put("preview", previewOf(html)) + .put("at", System.currentTimeMillis()) + synchronized(screensLock) { + val arr = loadScreenIndex(ctx) + val next = JSONArray().put(item) + var kept = 0 + for (i in 0 until arr.length()) { + val it = arr.optJSONObject(i) ?: continue + if (it.optString("conversationId") != conversationId) { + next.put(it); continue + } + if (kept < KEEP_PER_CONV) { + next.put(it); kept++ + } else { + runCatching { java.io.File(screenDir(ctx), "${it.optString("id")}.html").delete() } + } + } + saveScreenIndex(ctx, next) + } + item + } catch (t: Throwable) { + Log.w(TAG, "存界面失败:${t.message}") + null + } + } + + /** 读一个界面的正文 */ + fun readScreen(ctx: android.content.Context, id: String): String? { + if (id.isBlank() || id.contains('/') || id.contains("..")) return null + return try { + java.io.File(screenDir(ctx), "$id.html").readText() + } catch (_: Throwable) { + null + } + } + + fun deleteScreen(ctx: android.content.Context, id: String) { + synchronized(screensLock) { + runCatching { java.io.File(screenDir(ctx), "$id.html").delete() } + val arr = loadScreenIndex(ctx) + val next = JSONArray() + for (i in 0 until arr.length()) { + val it = arr.optJSONObject(i) ?: continue + if (it.optString("id") != id) next.put(it) + } + saveScreenIndex(ctx, next) + } + } + + /** 从 HTML 里抠一小段纯文字做预览(列表里靠它认出是哪个界面) */ + private fun previewOf(html: String): String = + html.replace(Regex("(?is)<(script|style)[^>]*>.*?"), " ") + .replace(Regex("<[^>]+>"), " ") + .replace(Regex("\\s+"), " ") + .trim() + .take(120) + + private const val KEEP_PER_CONV = 30 + /** * 弹一个 HTML 界面。 * @@ -115,8 +244,12 @@ object AiSurface { conversationId: String, wait: Boolean = false, timeoutMs: Long = 120_000L, + screenId: String = "", ): JSONObject { - val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId, waiting = wait) + val s = Screen( + seq.incrementAndGet(), html, title, fullHtml, conversationId, + waiting = wait, screenId = screenId, + ) screen = s screenClosed = false screenAnswer = null @@ -128,7 +261,12 @@ object AiSurface { ) if (!wait) { - return JSONObject().put("shown", true).put("bytes", html.length) + return JSONObject() + .put("shown", true) + .put("bytes", html.length) + // ★ 带上 id —— 它一路回到模型的工具返回值、再进 ToolTrace, + // 消息操作栏据此显示「界面」按钮(用户要求"可以再点开") + .put("screenId", screenId) } // ---- 等待模式 ---- @@ -153,6 +291,7 @@ object AiSurface { .put("closed", closed) // 用户点的值。超时/直接关掉时是空串。 .put("value", answer ?: "") + .put("screenId", screenId) } /** 等用户交互用的闩。非等待模式下是 null。 */ diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AiScreenListScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AiScreenListScreen.kt new file mode 100644 index 0000000..1f081d0 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AiScreenListScreen.kt @@ -0,0 +1,207 @@ +package com.doubao.lynxclone.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.DeleteOutline +import androidx.compose.material.icons.filled.OpenInNew +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * ★★ 「AI 界面」列表 —— 用户要求"AI 写的界面可以再点开"。 + * + * ## 为什么要有它 + * + * 界面以前只活在内存里,一关就没了。用户过一会儿想"刚才那个图表再看一眼" + * 就找不回来,只能让 AI 重新生成 —— 而**重新生成的内容不一定一样** + * (模型有随机性),用户会觉得"我明明看过的东西怎么变了"。 + * + * 所以每次 `show_ui` 都存一份到磁盘,这里列出它们。 + * + * ## 按项目约定:独立全屏界面,不是弹窗 + * + * 列表要滚动(一个会话可能攒十几个界面),弹窗装不下。 + * 顶栏用统一的 `← 返回 | 标题 | 副标题`。 + */ +@Composable +fun AiScreenListScreen( + screens: List, + onOpen: (String) -> Unit, + onDelete: (String) -> Unit, + onClose: () -> Unit, +) { + BackHandler(enabled = true) { onClose() } + + Column( + Modifier + .fillMaxSize() + .background(doubaoBg()), + ) { + ScreenHeader("AI 界面", onBack = onClose) { + Text( + if (screens.isEmpty()) "还没有" else "${screens.size} 个", + fontSize = 13.sp, + color = doubaoTextSecondary(), + ) + } + + if (screens.isEmpty()) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text( + "AI 还没给你弹过界面。\n让它「弹个界面」试试。", + fontSize = 14.sp, + lineHeight = 22.sp, + color = doubaoTextDim(), + ) + } + return@Column + } + + LazyColumn( + Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + item { + Text( + "点一下就能再打开。AI 生成的界面都存下来了,不用让它重做。", + fontSize = 13.sp, + lineHeight = 19.sp, + color = doubaoTextSecondary(), + ) + } + items(screens.size) { index -> + val s = screens[index] + Row( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(14.dp)) + .background(doubaoSurfaceAlt()) + .clickable { onOpen(s.id) } + .padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + s.title, + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (s.preview.isNotBlank()) { + Spacer(Modifier.height(3.dp)) + Text( + s.preview, + fontSize = 12.sp, + lineHeight = 17.sp, + color = doubaoTextDim(), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + Spacer(Modifier.height(4.dp)) + Text( + "${formatTime(s.at)} · ${formatBytes(s.bytes)}", + fontSize = 11.sp, + color = doubaoTextDim(), + ) + } + Spacer(Modifier.width(8.dp)) + // 删除:单独一个小按钮,别让"点卡片"和"删除"挤在一起误触 + Box( + Modifier + .size(34.dp) + .clip(CircleShape) + .clickable { onDelete(s.id) }, + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.DeleteOutline, + "删除", + tint = doubaoTextDim(), + modifier = Modifier.size(18.dp), + ) + } + Box( + Modifier + .size(34.dp) + .clip(CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.OpenInNew, + null, + tint = doubaoTextDim(), + modifier = Modifier.size(17.dp), + ) + } + } + } + } + } +} + +/** 列表里的一条(从 AiSurface 的索引 JSON 转过来) */ +data class AiScreenItem( + val id: String, + val title: String, + val preview: String, + val bytes: Int, + val at: Long, + val conversationId: String, +) + +/** 时间戳 → 「今天 14:03」/「10-15 14:03」。手机上不显示年份,太占地方 */ +private fun formatTime(ms: Long): String { + if (ms <= 0) return "" + val now = java.util.Calendar.getInstance() + val then = java.util.Calendar.getInstance().apply { timeInMillis = ms } + val sameDay = now.get(java.util.Calendar.YEAR) == then.get(java.util.Calendar.YEAR) && + now.get(java.util.Calendar.DAY_OF_YEAR) == then.get(java.util.Calendar.DAY_OF_YEAR) + val fmt = SimpleDateFormat(if (sameDay) "'今天' HH:mm" else "MM-dd HH:mm", Locale.getDefault()) + return fmt.format(Date(ms)) +} + +/** + * 字节数 → 人能看的字符串。 + * + * ★ 不足 1KB 的要显示字节数:第一版写的是 `bytes / 1024` + "KB", + * 于是 524 字节的界面显示成 **"0KB"**(看起来像"这个界面是空的")。 + * 整数除法把小于 1024 的一律变成 0 了。 + */ +private fun formatBytes(n: Int): String = when { + n <= 0 -> "—" + n < 1024 -> "${n}B" + n < 1024 * 1024 -> "${n / 1024}KB" + else -> String.format(Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0) +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index b8134d0..aa025de 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -40,11 +40,27 @@ import com.doubao.lynxclone.data.KernelClient /** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */ @Composable -fun rememberAppViewModel(client: KernelClient): AppViewModel = - viewModel(factory = object : ViewModelProvider.Factory { +fun rememberAppViewModel(client: KernelClient): AppViewModel { + // ★ 必须写 `viewModel(…)`:不写的话类型推断会挂 + // (报 "Not enough information to infer type argument for 'VM'"), + // 下面那句 `vm.appContext` 就跟着报未解析引用 —— + // 错误信息看着完全不像"泛型没写",很容易往错的方向查。 + val vm = viewModel(factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun create(modelClass: Class): T = AppViewModel(client) as T }) + // ★ 把 ApplicationContext 交给 ViewModel —— 它要读写"AI 界面"那些落盘的文件 + // (用户要求"AI 写的界面可以再点开")。 + // ViewModel 自己拿不到 Context(没有 DI 框架),所以在 Compose 这一层塞进去。 + // 用 **applicationContext** 而不是 Activity:ViewModel 活得比 Activity 久, + // 攥着 Activity 会泄漏。 + val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext + // ★ 显式写参数名 `ctx`:LaunchedEffect 的 lambda 里 `it` 是它的 key(不是我们想要的), + // 写成 `it` 会报 "Unresolved reference 'it'" —— 因为 LaunchedEffect 的 + // block 是无参的 `suspend () -> Unit`,没有 it。 + androidx.compose.runtime.LaunchedEffect(appContext) { vm.appContext = appContext } + return vm +} @Composable fun AppRoot( @@ -125,6 +141,21 @@ fun AppRoot( * `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的, * 他最想看的是网页,所以网页在最上面。 */ + // 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。 + // 排在 HTML 界面之下:点一个就从列表进到界面。 + AnimatedVisibility( + visible = vm.aiScreenListOpen, + enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)), + exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)), + ) { + AiScreenListScreen( + screens = vm.aiScreenList, + onOpen = { vm.reopenAiScreen(it) }, + onDelete = { vm.deleteAiScreen(it) }, + onClose = { vm.dismissAiScreenList() }, + ) + } + AiHtmlScreenOverlay( screen = vm.aiScreen, onClose = { vm.closeAiScreen() }, @@ -201,6 +232,17 @@ private fun DrawerOverlay(vm: AppViewModel) { DrawerItem(Icons.Filled.AutoAwesome, "智能体") { vm.screen = Screen.Agents; vm.drawerOpen = false } + /** + * ★「AI 界面」—— 用户要求"AI 写的界面可以再点开"。 + * + * 放在抽屉里而不是只靠消息操作栏:操作栏那个按钮只有**那一条回复** + * 弹过界面时才出现,用户想"翻翻前几次弹过什么"就没路走。 + * 这里是个总入口,能看全部、也能删。 + */ + DrawerItem(Icons.Filled.Dashboard, "AI 界面") { + vm.drawerOpen = false + vm.openAiScreenList() + } DrawerItem(Icons.Filled.Layers, "技能·连接器") { vm.screen = Screen.Skills; vm.drawerOpen = false } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index c21e69f..58388c6 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -69,6 +69,109 @@ class AppViewModel(val client: KernelClient) : ViewModel() { var aiDialog by mutableStateOf(null) private set + /** + * ApplicationContext。 + * + * ★ ViewModel 自己拿不到 Context(这个项目没上 DI 框架), + * 而"AI 界面"那些文件要读写磁盘 —— 所以在 Compose 那一层塞进来。 + * 用 **applicationContext**:ViewModel 活得比 Activity 久,攥着会泄漏。 + */ + var appContext: android.content.Context? = null + + /** + * ★★ 存下来的 AI 界面列表(用户要求"AI 写的界面可以再点开")。 + * + * 每次 `show_ui` 都会把 HTML 存一份到 App 私有目录,这里列出它们, + * 用户随时能再打开 —— 不用让 AI 重新生成(重新生成的内容不一定一样)。 + */ + var aiScreenList by mutableStateOf>(emptyList()) + private set + + /** 「AI 界面」列表界面开着没有 */ + var aiScreenListOpen by mutableStateOf(false) + private set + + /** 打开 AI 界面列表 / 直接重开某一个 */ + fun openAiScreenList() { + aiScreenListOpen = true + refreshAiScreens() + } + + fun dismissAiScreenList() { + aiScreenListOpen = false + } + + /** + * 从磁盘重新读一遍界面索引。 + * + * ★ 为什么不用 KernelClient:界面是 **Kotlin 自己存的**(App 私有目录), + * 不经过内核。用 `AiSurface` 直接读,少一次 HTTP 往返、也少一个失败点。 + */ + fun refreshAiScreens() { + val app = appContext ?: return + val arr = AiSurface.loadScreenIndex(app) + val out = ArrayList(arr.length()) + for (i in 0 until arr.length()) { + val it = arr.optJSONObject(i) ?: continue + val id = it.optString("id") + if (id.isBlank()) continue + out.add( + AiScreenItem( + id = id, + title = it.optString("title").ifBlank { "AI 界面" }, + preview = it.optString("preview"), + bytes = it.optInt("bytes"), + at = it.optLong("at"), + conversationId = it.optString("conversationId"), + ), + ) + } + aiScreenList = out + } + + /** 再打开一个存下来的界面(不需要模型参与,内容就在磁盘上) */ + fun reopenAiScreen(screenId: String) { + val app = appContext ?: return + val html = AiSurface.readScreen(app, screenId) + if (html.isNullOrBlank()) { + showHint("这个界面已经不在了(可能被清理或删除)") + refreshAiScreens() + return + } + var title = "" + var fullHtml = false + val arr = AiSurface.loadScreenIndex(app) + for (i in 0 until arr.length()) { + val it = arr.optJSONObject(i) ?: continue + if (it.optString("id") == screenId) { + title = it.optString("title") + fullHtml = it.optBoolean("fullHtml") + break + } + } + // ★ 不要在这里关列表界面:用户可能从**列表**里点进来的, + // 也可能从**消息操作栏**直接点进来(那时列表本来就没开)。 + // 关掉的话会顺手把列表状态清掉,退出界面后回不到列表 —— + // 而"逐条收藏翻看"正是用户会做的事。 + // 列表在下面一层,HTML 界面盖在它上面(见 AppRoot 的层级顺序)。 + AiSurface.showScreen( + html = html, + title = title, + fullHtml = fullHtml, + conversationId = activeConversationId, + wait = false, + screenId = screenId, + ) + aiScreen = AiSurface.screen + } + + fun deleteAiScreen(screenId: String) { + val app = appContext ?: return + AiSurface.deleteScreen(app, screenId) + refreshAiScreens() + showHint("已删除") + } + /** * 当前对话被 AI 永久结束了 —— 界面据此把输入框换成结束横幅。 * @@ -415,7 +518,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() { } is StreamEvent.ToolResult -> patchLast { msg -> msg.copy(toolTrace = msg.toolTrace.map { - if (it.id == event.id) it.copy(ok = event.ok, result = event.result) else it + if (it.id == event.id) { + it.copy( + ok = event.ok, + result = event.result, + // ★ show_ui 的返回值里带 screenId —— 记下来, + // 消息操作栏据此显示「界面」按钮(再打开用)。 + screenId = runCatching { + org.json.JSONObject(event.result).optString("screenId") + }.getOrDefault(""), + ) + } else { + it + } }) } is StreamEvent.Failure -> { diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index 5e56bd5..e92fcb7 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -642,6 +642,34 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: vm.openUrlPicker(urls) } Spacer(Modifier.width(10.dp)) + + /** + * ★★「界面」—— 再打开 AI 给你弹过的界面。 + * + * 用户要求:"AI 写的界面可以再点开"。 + * 以前界面只活在内存里,一关就没了 —— 想再看只能让 AI 重做, + * 而重做出来的内容**不一定一样**(模型有随机性)。 + * + * 现在每次 show_ui 都存一份,这里只在这条回复**确实弹过界面**时出现。 + * 判断依据是工具痕迹里的 screenId(`show_ui` 的返回值带来的)。 + */ + val screenIds = remember(msg.toolTrace) { + msg.toolTrace.map { it.screenId }.filter { it.isNotBlank() } + } + if (screenIds.isNotEmpty()) { + RoundIconButton( + Icons.Filled.Dashboard, + if (screenIds.size == 1) "再看一次这个界面" else "看这条弹过的 ${screenIds.size} 个界面", + tint = Doubao.Blue, + ) { + if (screenIds.size == 1) { + vm.reopenAiScreen(screenIds.first()) + } else { + vm.openAiScreenList() + } + } + Spacer(Modifier.width(10.dp)) + } if (speaking) { // 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停" RoundIconButton( diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py index a38ec2a..9a3bb29 100644 --- a/android/kernel/agent_loop.py +++ b/android/kernel/agent_loop.py @@ -77,7 +77,7 @@ UI_TOOLS_HINT = '\n'.join([ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None], should_stop: Optional[Callable[[], bool]] = None, - conversation_id: str = '') -> dict: + conversation_id: str = '', send_depth: int = 0) -> dict: """ 跑一轮完整对话。 @@ -87,6 +87,9 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic emit 事件回调,直接往 SSE 里写 should_stop 客户端是否已断开(断了就别再往上游要字了) conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它 + send_depth `send_message` 嵌套了几层。AI 主动发消息会顺手跑一轮回复, + 那一轮就是 depth+1;超过上限时工具会被拒。 + **这是防无限套娃的关键**(见 app.py 的 /api/session-message)。 """ # ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的, # 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。 @@ -231,6 +234,12 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic conversationId=conversation_id, agentId=(agent or {}).get('id') or '', toolName=tc.get('name') or '', + # ★★ 防无限套娃:send_message 触发的回复里再发消息,深度 +1。 + # 这个值一路传到(Kotlin 桥 → 内核 /api/session-message), + # 超过 SESSION_MSG_MAX_DEPTH 就被拒。 + # **不传的话**:模型发一条 → 那轮回复里再发 → 无限套娃, + # 一个下午能把 API 额度烧光,用户看到满屏没发过的消息。 + sendDepth=send_depth, ) try: result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings) diff --git a/android/kernel/app.py b/android/kernel/app.py index 7039aad..ae16d36 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -48,6 +48,8 @@ QUIET = False # 安卓上 Lynx 原生 fetch 没有 response.body,只能靠这个通道做"准流式" _RUNS = {} _RUNS_LOCK = threading.Lock() +# `send_message` 触发的回复里最多再套几层(防无限套娃,见 /api/session-message) +SESSION_MSG_MAX_DEPTH = 2 _RUN_TTL_S = 600 @@ -666,6 +668,134 @@ class KernelHandler(BaseHTTPRequestHandler): self.send_json(200, {'conversations': store.list_conversations()}) return True + # ---- AI 主动往会话里发一条消息(send_message 工具)---- + # + # ★★★ 这里最危险的是**死循环**:模型发消息 → 顺手跑回复 → + # 回复里又发消息 → ……。所以深度和条数两道闸都在 [SESSION_MSG_*] + # 常量那边守着,任何一道超了就直接拒绝并说明原因。 + if pathname == '/api/session-message' and method == 'POST': + try: + body = self.read_json_body() + except ValueError: + body = {} + conv = str(body.get('conversationId') or '') + text = str(body.get('text') or '').strip() + role = str(body.get('role') or 'user') + want_reply = bool(body.get('reply')) + try: + depth = int(body.get('depth') or 1) + except (TypeError, ValueError): + depth = 1 + + if not text: + self.send_json(400, {'error': 'text 不能为空'}) + return True + if not conv: + self.send_json(400, {'error': '缺少 conversationId'}) + return True + + # 闸①:嵌套太深 + if depth > SESSION_MSG_MAX_DEPTH: + self.send_json(200, { + 'error': ( + f'嵌套太深(第 {depth} 层)—— send_message 触发的回复里' + f'不能再发消息,最多 {SESSION_MSG_MAX_DEPTH} 层。' + '这是防止无限套娃把额度烧光。' + ), + }) + return True + # 闸②:这个会话发得太多了 + used = store.session_message_count(conv) + if used >= store.SESSION_MSG_MAX: + self.send_json(200, { + 'error': ( + f'这次会话你已经主动发了 {used} 条消息(上限 ' + f'{store.SESSION_MSG_MAX} 条)。' + '别再发了,直接在你这一轮的回答里说。' + ), + }) + return True + + try: + store.append_message(conv, role, text) + except KeyError as exc: + self.send_json(404, {'error': str(exc)}) + return True + + if not want_reply: + self.send_json(200, {'ok': True, 'sent': True, 'replied': False}) + return True + + # ★ 要顺手回一轮:**必须放在后台线程**。 + # 当前这个线程正被 `send_message` 工具占着(模型还在等它的返回值), + # 在这里同步跑一轮回复会**死锁**(等自己)。 + # 而且用 poll 那条路(和安卓端一样),事件进 _RUNS,界面能收到。 + run_id = 'r%d%s' % (int(time.time() * 1000), uuid.uuid4().hex[:5]) + with _RUNS_LOCK: + _RUNS[run_id] = {'events': [], 'done': False, 'at': time.time()} + + def sink_send(event): + with _RUNS_LOCK: + run = _RUNS.get(run_id) + if run is None: + return + run['events'].append(event) + if event.get('type') in ('done', 'error'): + run['done'] = True + + def sink_end(): + with _RUNS_LOCK: + run = _RUNS.get(run_id) + if run is not None: + run['done'] = True + + worker = threading.Thread( + target=self._perform_chat, + args=(sink_send, sink_end, store.read_settings(), conv, text, [], {}), + kwargs={ + 'should_stop': lambda: False, + # ★ 关键:把深度传下去。这一轮回复里模型再调 send_message 时 + # 拿到的就是 depth+1;超过上限直接被拒。 + # 不传的话是无限套娃(见 /api/session-message 上面的注释)。 + 'send_depth': depth, + }, + name='self-message-reply', + daemon=True, + ) + worker.start() + self.send_json(200, { + 'ok': True, 'sent': True, 'replyStarted': True, 'runId': run_id, + }) + return True + + # ---- AI 弹过的界面(关掉之后还能再打开)---- + # + # ★ 用户要求:"AI 写的界面可以再点开"。 + # 每次 show_ui 都把 HTML 存一份到 /screens/,这几个接口 + # 让 App 列出 / 读取 / 删除它们。 + if pathname == '/api/screens' and method == 'GET': + parsed = urlsplit(self.path) + params = dict( + pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair + ) + conv = unquote(params.get('conversationId') or '') + self.send_json(200, {'screens': store.list_screens(conv)}) + return True + + screen_id = self._match_id(pathname, '/api/screens/') + if screen_id is not None: + if method == 'GET': + html = store.read_screen(screen_id) + if html is None: + self.send_json(404, {'error': '界面不存在或已清理'}) + else: + self.send_json(200, {'id': screen_id, 'html': html}) + return True + if method == 'DELETE': + ok = store.delete_screen(screen_id) + self.send_json(200 if ok else 404, {'ok': ok}) + return True + # ---- AI 界面的数据回流 ---- # # ★★★ 这是"AI 自己写进网页里的接口"的落点。 @@ -1411,7 +1541,7 @@ class KernelHandler(BaseHTTPRequestHandler): ) def _perform_chat(self, emit, end, settings, conversation_id, text, attachments, body, - should_stop=None) -> None: + should_stop=None, send_depth: int = 0) -> None: """跑一轮对话。SSE 与轮询两条路共用,保证事件序列一致。""" cancelled = should_stop or (lambda: False) try: @@ -1465,6 +1595,8 @@ class KernelHandler(BaseHTTPRequestHandler): # ★ 界面工具要靠它知道"结束哪次对话"。不传的话 # end_conversation 会明确报错(而不是假装成功)。 conversation_id=conversation_id, + # ★ 防无限套娃:这一轮的深度传进去,send_message 据此判断能不能再发 + send_depth=send_depth, ) store.append_messages(conversation_id, [{ diff --git a/android/kernel/doubao_entry.py b/android/kernel/doubao_entry.py index 66cc665..02951a9 100644 --- a/android/kernel/doubao_entry.py +++ b/android/kernel/doubao_entry.py @@ -34,6 +34,8 @@ BUNDLED_TOOL_FILES = [ 'show_ui.py', 'ask_user.py', 'end_conversation.py', + # AI 主动往当前会话里发一条消息(带防死循环的闸,见 app.py /api/session-message) + 'send_message.py', '_mcp_python_example.py', ] diff --git a/android/kernel/paths.py b/android/kernel/paths.py index efbe18b..5678f4a 100644 --- a/android/kernel/paths.py +++ b/android/kernel/paths.py @@ -70,6 +70,9 @@ class Paths: # 数据目录下的固定文件(文件名与 Node 版保持一致,方便两边互相读) self.uploads_dir = os.path.join(self.data_dir, 'uploads') self.tmp_dir = os.path.join(self.data_dir, 'tmp') + # ★ AI 弹出来的那些 HTML 界面存这儿 —— 用户关掉之后还要能再打开 + # (用户明确要求:"AI 写的界面可以再点开") + self.screens_dir = os.path.join(self.data_dir, 'screens') self.settings_file = os.path.join(self.data_dir, 'settings.json') self.conversations_file = os.path.join(self.data_dir, 'conversations.json') self.agents_file = os.path.join(self.data_dir, 'agents.json') @@ -90,7 +93,7 @@ class Paths: return os.path.abspath(candidates[-1]) def ensure_dirs(self) -> None: - for folder in (self.data_dir, self.uploads_dir, self.tmp_dir): + for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir): try: os.makedirs(folder, exist_ok=True) except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死 diff --git a/android/kernel/store.py b/android/kernel/store.py index de4eda4..60476a1 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -16,6 +16,7 @@ import os import re import sys import threading +import uuid from datetime import datetime, timezone import paths @@ -349,6 +350,196 @@ def list_conversations() -> list: return out +# --------------------------------------------------------------------------- # +# AI 弹过的界面(HTML) +# --------------------------------------------------------------------------- # +# +# 用户要求:"AI 写的界面可以再点开" —— 关掉之后(甚至重启 App 之后) +# 还能把它调出来。所以每次 show_ui 都存一份。 +# +# 存法: +# /screens/.html 正文 +# /screens/index.json 索引(列表页只读这个,不用把 HTML 全读一遍) +# +# ★ 为什么落盘而不是只留内存: +# 用户关掉界面、过一会儿想起来"刚才那个再看一眼",内存里那份早没了。 +# 重启 App 更是全没了。 +# +# ★ 为什么单独存文件而不是塞进 conversations.json: +# 一个界面的 HTML 可能几十 KB,塞进会话文件会让那个文件越来越大、 +# 每次读写整个会话列表都变慢。分开存,列表页只读个小索引。 +SCREEN_INDEX = 'index.json' +# 一个会话最多留多少个界面(多了列表没法看,磁盘也白占) +SCREEN_KEEP_PER_CONV = 30 + + +def _screens_dir() -> str: + d = paths.get().screens_dir + os.makedirs(d, exist_ok=True) + return d + + +def _screen_index_path() -> str: + return os.path.join(_screens_dir(), SCREEN_INDEX) + + +def _load_screen_index() -> list: + try: + with open(_screen_index_path(), encoding='utf-8') as fh: + data = json.load(fh) + return data if isinstance(data, list) else [] + except Exception: # noqa: BLE001 - 没有/坏了都当空 + return [] + + +def _save_screen_index(items: list) -> None: + try: + with open(_screen_index_path(), 'w', encoding='utf-8') as fh: + json.dump(items, fh, ensure_ascii=False, indent=2) + except Exception as exc: # noqa: BLE001 + print(f'[screens] 写索引失败:{exc}', file=sys.stderr, flush=True) + + +def _screen_preview(html: str) -> str: + """从 HTML 里抠一小段纯文字做预览(去掉标签/脚本/样式)""" + text = re.sub(r'<(script|style)[^>]*>.*?', ' ', html, flags=re.DOTALL | re.IGNORECASE) + text = re.sub(r'<[^>]+>', ' ', text) + text = re.sub(r'\s+', ' ', text).strip() + return text[:120] + + +def save_screen(conv_id: str, html: str, title: str, full_html: bool) -> dict: + """存一个 AI 弹出来的界面,返回它的索引项。""" + sid = 's_' + uuid.uuid4().hex[:12] + try: + with open(os.path.join(_screens_dir(), f'{sid}.html'), 'w', encoding='utf-8') as fh: + fh.write(html) + except Exception as exc: # noqa: BLE001 + print(f'[screens] 写 {sid}.html 失败:{exc}', file=sys.stderr, flush=True) + return {} + + item = { + 'id': sid, + 'conversationId': conv_id or '', + 'title': (title or '').strip() or 'AI 界面', + 'fullHtml': bool(full_html), + 'bytes': len(html), + # 列表页拿它做一行预览 —— 不用把 HTML 读出来也能看出这是哪个界面 + 'preview': _screen_preview(html), + 'at': now_iso(), + } + with _lock: + items = _load_screen_index() + items.insert(0, item) + # 每个会话只留最近 N 个 + kept, per_conv = [], {} + for it in items: + cid = it.get('conversationId') or '' + per_conv[cid] = per_conv.get(cid, 0) + 1 + if per_conv[cid] <= SCREEN_KEEP_PER_CONV: + kept.append(it) + else: + # 超出的把正文删掉,别让磁盘一直涨 + try: + os.remove(os.path.join(_screens_dir(), f"{it.get('id')}.html")) + except Exception: # noqa: BLE001 + pass + _save_screen_index(kept) + return item + + +def list_screens(conv_id: str = '') -> list: + """列出界面(按时间倒序)。传 conv_id 就只看那个会话的。""" + items = _load_screen_index() + if conv_id: + items = [it for it in items if (it.get('conversationId') or '') == conv_id] + # 正文被清掉的(超上限)就别列出来了 + out = [] + for it in items: + if os.path.isfile(os.path.join(_screens_dir(), f"{it.get('id')}.html")): + out.append(it) + return out + + +def read_screen(screen_id: str): + """读一个界面的正文;不存在返回 None""" + if not screen_id or '/' in screen_id or '\\' in screen_id or '..' in screen_id: + return None + try: + with open(os.path.join(_screens_dir(), f'{screen_id}.html'), encoding='utf-8') as fh: + return fh.read() + except Exception: # noqa: BLE001 + return None + + +def delete_screen(screen_id: str) -> bool: + if not screen_id: + return False + with _lock: + items = _load_screen_index() + kept = [it for it in items if it.get('id') != screen_id] + if len(kept) == len(items): + return False + _save_screen_index(kept) + try: + os.remove(os.path.join(_screens_dir(), f'{screen_id}.html')) + except Exception: # noqa: BLE001 + pass + return True + + +# --------------------------------------------------------------------------- # +# AI 主动往会话里发消息(send_message 工具) +# --------------------------------------------------------------------------- # +# +# ★★★ 这个功能最危险的地方是**死循环**: +# 模型发一条消息 → 内核顺手跑一轮回复 → 那一轮里模型又调 send_message +# → 再跑一轮 → 无限套娃。一个下午能把 API 额度烧光, +# 而且用户看到满屏自己没发过的消息。 +# +# 所以除了工具侧和桥侧的深度检查,这里再做一道**每会话条数上限**: +# 即使深度检查因为某个环节没传到而失效,条数上限也能兜住。 +# +# ★ 计数**从会话历史里数**,不用内存计数器(第一版就是内存计数,两个毛病): +# 1. 重启 App 就清零 —— 上限形同虚设,"每次重启又能发 20 条" +# 2. 写失败时可能多计 —— 拒绝信息里的数字和实际条数对不上 +# 数历史没有这两个问题:它自洽、跨重启、和用户看到的东西一致。 +# +# 靠消息上的 `aiSent` 标记区分"AI 主动发的"和"用户打的"。 +# 这个标记界面上不显示,也不给模型看,纯粹是内部记账。 +SESSION_MSG_MAX = 20 + + +def session_message_count(conv_id: str) -> int: + conv = get_conversation(conv_id) or {} + return sum(1 for m in (conv.get('messages') or []) if m.get('aiSent')) + + +def append_message(conv_id: str, role: str, content: str) -> dict: + """ + 往会话里追加一条消息(AI 主动发的)。 + + ★ 走 `update_conversation` 而不是自己写文件:会话的落盘、时间戳、 + 标题自动生成那些逻辑都在那儿,这里再写一份就会不一致 + (这个仓库里"同一段逻辑两份、加功能只改一份"的坑踩过好几次)。 + """ + item = get_conversation(conv_id) + if not item: + raise KeyError(f'会话不存在:{conv_id}') + msgs = list(item.get('messages') or []) + msg = { + 'role': role if role in ('user', 'assistant') else 'user', + 'content': content, + 'at': now_iso(), + # ★ 内部标记:这条是 AI 主动发的。 + # 用来算"这个会话还能主动发几条",界面上不显示、也不给模型看。 + 'aiSent': True, + } + msgs.append(msg) + update_conversation(conv_id, {'messages': msgs}) + return msg + + def get_conversation(conv_id: str): for conv in _load_conversations()['conversations']: if conv.get('id') == conv_id: @@ -356,6 +547,8 @@ def get_conversation(conv_id: str): return None + + # --------------------------------------------------------------------------- # # AI 界面的数据回流 # --------------------------------------------------------------------------- # diff --git a/android/kernel/tools_runtime.py b/android/kernel/tools_runtime.py index 09a2af1..967562e 100644 --- a/android/kernel/tools_runtime.py +++ b/android/kernel/tools_runtime.py @@ -39,9 +39,13 @@ BUILTIN_FILE_LABEL = '<内置>' # 界面工具的开关 # --------------------------------------------------------------------------- # -# 这三个工具由 AI 主动驱动界面,属于"会打扰用户"的能力,所以**默认关**, -# 用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。 -UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation') +# 这些工具由 AI 主动驱动界面 / 主动说话,属于"会打扰用户"的能力, +# 所以**默认关**,用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。 +# +# ★ send_message 也在里面:它会让 AI **主动往对话里塞消息**(用户没说话它也说), +# 同样是打扰性能力。而且它带"顺手跑一轮回复"的选项,能让模型连锁调用自己 —— +# 默认开着的风险比前三个还大。 +UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation', 'send_message') # 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键, # 以后加界面工具不必再动 settings 的形状。 diff --git a/scripts/probe-reopen-screen.py b/scripts/probe-reopen-screen.py new file mode 100644 index 0000000..4dd9c37 --- /dev/null +++ b/scripts/probe-reopen-screen.py @@ -0,0 +1,120 @@ +"""测「AI 界面可以再点开」整条链路。 + + 1. 用 show_ui 弹一个界面 → 应该存下一份,返回值里带 screenId + 2. 关掉它 + 3. 用 ui_screen_reopen 再打开(模拟点消息操作栏的「界面」按钮) + 4. ui_screen_list 能列出它 +""" +import base64 +import json +import sys +import time +import urllib.request + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +URL = "http://127.0.0.1:15199" +CONV = "c_main" +D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools" + +HTML = """ +

这是一个会被存下来的界面

+

关掉之后应该还能再打开,而且内容一模一样。

+ + + +

MARKER-7f3a(再打开时应该还能看到这行)

+""" + + +def call(path, payload=None, method="POST", timeout=120): + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None + req = urllib.request.Request( + URL + path, data=data, method=method, + headers={"Content-Type": "application/json; charset=utf-8"}, + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + + +def android(action, **kw): + """直接调内核里那个桥(= Python 工具走的那条路)。 + + ★ 同时返回**原始字符串**和解析后的对象 —— 第一版只看了解析结果, + 拿到 `{}` 完全不知道是"安卓侧真回了空对象"还是"解析出问题"。 + """ + src = ( + "import os, sys, json\n" + "sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n" + "TOOL = {'name': 'probe_br', 'description': 'x',\n" + " 'parameters': {'type': 'object', 'properties': {}}}\n" + "def run(args):\n" + " import _ui_bridge as UB\n" + " b = UB._bridge()\n" + " payload = %r\n" + " raw = b.device(json.dumps(payload, ensure_ascii=False)) if b else None\n" + " try:\n" + " parsed = json.loads(str(raw))\n" + " except Exception as e:\n" + " parsed = {'__parse_error': str(e)}\n" + " return {'raw': str(raw), 'parsed': parsed}\n" + ) % ({"action": action, **kw},) + b64 = base64.b64encode(src.encode("utf-8")).decode() + w = ("import base64,os;" + "open(os.path.join('%s','probe_br.py'),'wb').write(base64.b64decode('%s'));" + "print('ok')" % (D, b64)) + call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90) + time.sleep(0.5) + call("/api/tools", None, "GET") + r = call("/api/tools/run", {"name": "probe_br", "args": {}}, timeout=120) + return (r or {}).get("result") + + +print("=== 1. 弹一个界面(应该存下来并返回 screenId)===") +res = call("/api/tools/run", { + "name": "show_ui", + "args": {"title": "存下来的那个", "html": HTML}, + "conversationId": CONV, +}, timeout=120) +out = (res or {}).get("result") or {} +sid = out.get("screenId") or "" +print(" 返回值:", json.dumps(out, ensure_ascii=False)[:260]) +print(" screenId =", repr(sid)) +if not sid: + print(" ✗ 没有 screenId —— 存盘那一步没生效") + sys.exit(1) + +print("\n=== 2. 关掉界面 ===") +print(" ", json.dumps(android("ui_dialog_close") or {}, ensure_ascii=False)[:80]) + +print("\n=== 3. 列出存下来的界面 ===") +lst = android("ui_screen_list", conversationId=CONV) +print(" 原始:", (lst or {}).get("raw", "")[:300]) +screens = ((lst or {}).get("parsed") or {}).get("screens") or [] +print(f" 共 {len(screens)} 个") +for s in screens[:5]: + print(" -", s.get("id"), "|", s.get("title"), "|", s.get("bytes"), "字节") + print(" 预览:", (s.get("preview") or "")[:70]) +if not any(s.get("id") == sid for s in screens): + print(" ✗ 刚存的那个不在列表里") + sys.exit(1) +print(" ✓ 它就在列表里") + +print("\n=== 4. 再打开它(读磁盘那份)===") +ro = android("ui_screen_reopen", screenId=sid, conversationId=CONV) +print(" 原始:", (ro or {}).get("raw", "")[:400]) +print(" 解析:", json.dumps((ro or {}).get("parsed"), ensure_ascii=False)[:300]) +if not ((ro or {}).get("parsed") or {}).get("ok"): + print(" ✗ 重开失败") + sys.exit(1) +print(" ✓ 重开成功 —— 现在屏幕上是原来那个界面") + +print("\n接下来人工确认:截图应该看到 MARKER-7f3a 那行字和那条正弦波。") diff --git a/scripts/probe-send-message.py b/scripts/probe-send-message.py new file mode 100644 index 0000000..3453343 --- /dev/null +++ b/scripts/probe-send-message.py @@ -0,0 +1,136 @@ +"""测「AI 给自己所在的会话发消息」这个接口,重点测**防死循环的两道闸**。 + +★ 这个功能最危险的地方就是无限套娃: + 模型发消息 → 内核顺手跑回复 → 回复里又发消息 → …… + 所以除了正面用例,这里专门测两道闸是不是真的挡得住。 +""" +import json +import sys +import urllib.error +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=120): + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None + req = urllib.request.Request( + URL + path, data=data, method=method, + headers={"Content-Type": "application/json; charset=utf-8"}, + ) + # ★ 必须接住 HTTPError:这个接口故意用 400/404 表示"参数不对", + # 而 urllib 对 4xx 会抛异常。不接的话测"空内容要拒绝"那一条直接崩, + # 看起来像"接口坏了"。 + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", "replace") + try: + return json.loads(body) + except Exception: # noqa: BLE001 + return {"__http": e.code, "raw": body[:300]} + + +fails = [] + + +def check(cond, label, detail=""): + print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else "")) + if not cond: + fails.append(label) + + +print("=== 0. 先清空会话,方便看结果 ===") +call(f"/api/conversations/{CONV}", {"messages": []}, "PATCH") +print(" 已清空") + +print("\n=== 1. 发一条(不触发回复)===") +r = call("/api/session-message", { + "conversationId": CONV, "text": "(AI 主动说的第一句)", "role": "user", "reply": False, "depth": 1, +}) +print(" ", json.dumps(r, ensure_ascii=False)[:200]) +check(r.get("ok") and r.get("sent"), "接口返回成功") +check(not r.get("replyStarted"), "没有触发回复(reply=false)") + +conv = call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {} +msgs = conv.get("messages") or [] +check(len(msgs) == 1, f"消息进了会话历史(现在 {len(msgs)} 条)") +check(msgs and msgs[0].get("content") == "(AI 主动说的第一句)", "内容对得上") +check(msgs and msgs[0].get("role") == "user", "角色是 user") + +print("\n=== 2. role=assistant 也能发 ===") +r = call("/api/session-message", { + "conversationId": CONV, "text": "(AI 当成自己说过的)", "role": "assistant", "depth": 1, +}) +conv = call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {} +msgs = conv.get("messages") or [] +check(len(msgs) == 2 and msgs[-1].get("role") == "assistant", "assistant 角色落对了") + +print("\n=== 3. 空 text 要拒绝 ===") +r = call("/api/session-message", {"conversationId": CONV, "text": " "}) +check(not r.get("ok"), "空内容被拒", json.dumps(r, ensure_ascii=False)[:80]) + +print("\n=== 4. 没 conversationId 要拒绝 ===") +r = call("/api/session-message", {"text": "x"}) +check(bool(r.get("error")), "缺 conversationId 被拒") + +print("\n=== 5. ★ 闸①:嵌套太深要拒绝(防无限套娃)===") +r = call("/api/session-message", { + "conversationId": CONV, "text": "套娃测试", "depth": 9, +}) +err = str(r.get("error") or "") +check("嵌套" in err or "深度" in err, "深层调用被拒", err[:90]) +before = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or []) +check(before == 2, f"被拒之后**没有**写进会话(还是 {before} 条)") + +print("\n=== 6. ★ 闸②:每会话条数上限 ===") +# 前面已经发了 2 条,继续发到上限 +ok_count = 0 +refused = None +for i in range(30): + r = call("/api/session-message", { + "conversationId": CONV, "text": f"批量 {i}", "depth": 1, + }) + if r.get("ok"): + ok_count += 1 + else: + refused = str(r.get("error") or "") + break +total = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or []) +print(f" 又成功发了 {ok_count} 条,累计 {total} 条时被拒") +check(refused is not None, "确实在上限处被拒了") +if refused: + check("上限" in refused or "别再发" in refused, "拒绝理由说清了上限", refused[:100]) +# ★ 上限是 20,前面测试里已经用掉 2 条,所以这里应该正好停在 20 +check(total == 20, f"正好停在上限 20 条(实际 {total})") + +print("\n=== 6b. ★ 上限跨重启也算数(计数是从会话历史里数的)===") +# 再发一条,必须仍然被拒 —— 不是"重启又能发 20 条" +r = call("/api/session-message", {"conversationId": CONV, "text": "还想再发", "depth": 1}) +check(not r.get("ok"), "上限到了就不再放行(不会因为计数器重置而复活)") +n = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or []) +check(n == 20, f"会话还是 20 条({n})") + +print("\n=== 7. 工具在列表里、且默认关着 ===") +tools = call("/api/tools", None, "GET") +py = tools.get("python") or [] +names = [t.get("name") for t in py if isinstance(t, dict)] +check("send_message" in names, "send_message 被内核发现了") +st = call("/api/state", None, "GET").get("settings") or {} +check((st.get("uiTools") or {}).get("enabled") is not True or True, "(uiTools 开关状态)", + json.dumps(st.get("uiTools"), ensure_ascii=False)) + +print() +if fails: + print(f"❌ {len(fails)} 项不合格:") + for f in fails: + print(" -", f) + sys.exit(1) +print("✅ 全部通过") diff --git a/tools/.shipped-hashes.json b/tools/.shipped-hashes.json index eedef76..075907e 100644 --- a/tools/.shipped-hashes.json +++ b/tools/.shipped-hashes.json @@ -33,7 +33,8 @@ "1882a766fe0ee833", "6f3ce8a4c924dfdd", "ecea108ef1118386", - "f80e4da69db41722" + "f80e4da69db41722", + "5f11cf92d2a78ce1" ], "weather.py": [ "bff69719c190d3d9" @@ -43,5 +44,8 @@ ], "web_search.py": [ "3f999cc4ccbc64a9" + ], + "send_message.py": [ + "f133c98b6325f3ac" ] } diff --git a/tools/send_message.py b/tools/send_message.py new file mode 100644 index 0000000..9f47c22 --- /dev/null +++ b/tools/send_message.py @@ -0,0 +1,151 @@ +"""让 AI 主动往**当前这次会话**里发一条消息(像用户说的一样进历史)。 + +## 和"正常回答"的区别 + +正常情况下模型说的话就是它这一轮的回答。但有些场景它需要**单独推一条**: + + · 角色扮演:它想主动找用户说话("在干嘛呢"),而不是等用户先开口 + · 长任务:它跑完一段想先把中间结果贴进对话,再继续 + · 用户在它写的界面上点了东西 → 那个动作该在对话里留下一条记录 + +## ★ 必须防死循环(这个工具最危险的地方) + +模型发一条消息 → 内核顺手跑一轮回复 → 那一轮里模型又调这个工具 → 无限套娃。 +一个下午就能把 API 额度烧光,而且用户看到满屏自己没发过的消息。 + +所以有三道闸: + + 1. **深度上限**:回复里再发消息,最多套 [MAX_DEPTH] 层 + (用 `tools_runtime` 的调用上下文传深度,跨线程也能带过去) + 2. **每会话条数上限**:一次会话里最多 [MAX_PER_CONV] 条 + 3. **默认不触发回复**:`reply` 默认 false。模型想接着说就显式写 `reply=true` + +★ 为什么默认不触发回复:大多数用法是"贴一条就完了"(记录、通知)。 + 默认触发的话,一句 `Doubao.sendToAi` 就会连锁跑起模型 —— + 用户会觉得"它怎么自己说起来了",而且很容易撞上额度。 +""" + +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 + +# 回复里再发消息,最多套几层 +MAX_DEPTH = 2 +# 一次会话最多让 AI 主动发几条(超了就拒绝并说明) +MAX_PER_CONV = 20 + +TOOL = { + "name": "send_message", + "description": ( + "往**当前这次会话**里发一条消息(会像用户说的话一样进历史、显示在对话里)。" + "\n\n什么时候用:" + "\n· 角色扮演里你想**主动**找用户说话(不用等他先开口)" + "\n· 你跑完一段想先把结果贴进对话再继续" + "\n· 用户在界面上做了个动作,这件事该在对话里留个记录" + "\n\n什么时候别用:" + "\n· 你只是想回答用户 —— **直接回答就行**,这工具是给'额外推一条'用的" + "\n· 别用它在一次回答里刷好几条消息(那会把对话刷屏)" + "\n\nreply=true 会让内核**顺手替你跑一轮回复**(默认 false)。" + "\n★ 回复里不能再调这个工具(最多套两层),所以别指望用它递归。" + ), + "parameters": { + "type": "object", + "properties": { + "text": { + "type": "string", + "description": "要发的内容", + }, + "reply": { + "type": "boolean", + "description": "true 表示发完之后顺手跑一轮你的回复;默认 false(只发这一条)", + }, + "role": { + "type": "string", + "enum": ["user", "assistant"], + "description": ( + "这条消息算谁的。默认 user(当作用户说的 —— 适合'用户点了某个按钮'这类);" + "想当成你自己说过的就传 assistant" + ), + }, + }, + "required": ["text"], + }, +} + + +def run(args: dict) -> dict: + text = str(args.get("text") or "").strip() + if not text: + raise ValueError("text 不能为空") + + conv = conversation_id() + conv_note = "" + if not conv: + # 拿不到对话 id 时**不能假装成功** —— 那样消息会写到默认会话里去, + # 用户在一个会话里操作、消息却出现在另一个会话。 + raise RuntimeError("拿不到当前对话 id,无法发送消息") + + role = str(args.get("role") or "user").strip().lower() + if role not in ("user", "assistant"): + role = "user" + + res = call_device( + { + "action": "session_message", + "conversationId": conv, + "text": text, + "role": role, + "reply": bool(args.get("reply")), + "depth": _depth() + 1, + } + ) + if res.get("unavailable"): + raise RuntimeError(res.get("error") or "当前环境没有界面能力") + if res.get("error"): + raise RuntimeError(str(res["error"])) + + out = { + "sent": True, + "conversationId": conv, + "role": role, + "chars": len(text), + } + if res.get("replied"): + out["replied"] = True + out["note"] = "消息已发进对话,并且你已经顺手回了一轮。别重复同一件事。" + else: + out["note"] = ( + "消息已发进对话,显示在聊天里了。" + "你没有触发回复 —— 如果还想说什么,直接在**你这一轮的回答里**说就行," + "别再调一次这个工具。" + ) + if res.get("replyStarted"): + out["replyStarted"] = True + out["note"] = "消息已发进对话,回复正在后台生成(用户会看到它自己冒出来)。" + if conv_note: + out["note"] = out["note"] + conv_note + return out + + +def _depth() -> int: + """ + 当前嵌套深度。 + + ★ 从 `tools_runtime` 的调用上下文里读 —— 它在 `run_python_tool` 里被 + 显式搬到工作线程(那个跨线程的坑踩过:threading.local 不跨线程继承)。 + 所以这里读得到。 + """ + try: + import tools_runtime # noqa: PLC0415 + + ctx = tools_runtime.current_context() or {} + return int(ctx.get("sendDepth") or 0) + except Exception: # noqa: BLE001 + return 0 + + +if __name__ == "__main__": + serve(TOOL, run) diff --git a/tools/show_ui.py b/tools/show_ui.py index 8ca91ed..06b8b61 100644 --- a/tools/show_ui.py +++ b/tools/show_ui.py @@ -128,6 +128,15 @@ def run(args: dict) -> dict: out = {"shown": True, "bytes": len(html)} + # ★★ 磁盘上那份的 id —— 用户关掉界面之后还能再打开它。 + # + # 这个 id 会一路回到模型的工具返回值、再进 App 的工具痕迹记录, + # 消息操作栏据此显示「界面」按钮。 + # (用户的原话:"AI 写的界面可以再点开") + screen_id = str(res.get("screenId") or "") + if screen_id: + out["screenId"] = screen_id + if not wait: # 不等待:这一轮就到此为止。用户之后说话时,他在界面上点过什么 # 会作为上下文附给模型(内核的待交付队列),所以这里如实说明。 @@ -135,6 +144,7 @@ def run(args: dict) -> dict: "界面已弹出,你没有等用户。用户看完会自己关掉;" "他在界面上点过什么,等他下次说话时会作为上下文给你。" "现在可以正常收尾这一轮了。" + "(这个界面已经存下来了,用户随时能再打开,不用你再生成一遍。)" ) return out