Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e95e17c3e | ||
|
|
b1dd740b0d | ||
|
|
103c939051 | ||
|
|
885a1f0123 | ||
|
|
ba429e67cd | ||
|
|
5f138be5fa | ||
|
|
f7454c0b60 | ||
|
|
0ad999b6e6 | ||
|
|
e18970c85f | ||
|
|
0fe43d67df | ||
|
|
f789803eae |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 235
|
||||
versionName = "2.0.35"
|
||||
versionCode = 241
|
||||
versionName = "2.0.41"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||
<!-- Android 11+ 包可见性:不声明的话查不到别的 App,也就「打开手机 app」不了 -->
|
||||
<queries>
|
||||
<package android:name="com.termux" />
|
||||
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||
@@ -28,6 +28,13 @@
|
||||
<intent>
|
||||
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||
</intent>
|
||||
<!-- ★「打开手机 app」需要的:列出所有能启动的 App。
|
||||
Android 11 起不声明这条 queries,queryIntentActivities 只会返回空列表,
|
||||
表现是"已安装的 App 一个都找不到"。 -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
|
||||
@@ -55,5 +62,19 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- ★★ 读手机通知(用户要求的工具)。
|
||||
Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户
|
||||
手动去「设置 → 通知 → 通知使用权」勾上本 App,系统才会把通知流过来。
|
||||
不声明这个 Service,权限开了也收不到任何东西。 -->
|
||||
<service
|
||||
android:name=".DoubaoNotificationListener"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Notification
|
||||
import android.os.Bundle
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* ★★ 读手机通知 —— 用户要求"加个读取手机通知的工具"。
|
||||
*
|
||||
* ## 为什么必须是个 Service
|
||||
*
|
||||
* Android **没有**"读取通知"的运行时权限。唯一合法的路是让用户手动去
|
||||
* 「设置 → 通知 → 通知使用权」里把这个 App 勾上,系统才会把通知流给我们。
|
||||
* 这个 Service 就是那个接收端 —— 不声明它,权限开了也收不到任何东西。
|
||||
*
|
||||
* ## 不落盘,只在内存里留最近的
|
||||
*
|
||||
* 通知是**高度隐私**的内容(验证码、私信、银行短信都在里面)。
|
||||
* 写进磁盘意味着卸载前一直躺在那儿,也可能被别的工具读到。
|
||||
* 只留内存,进程一死就没了 —— 用户要"读最近的通知"这个需求完全够用,
|
||||
* 而隐私面小得多。
|
||||
*
|
||||
* ★ 上限 [MAX_KEEP] 条:用户一天能收几百条通知,不限量会把内存吃满。
|
||||
*/
|
||||
class DoubaoNotificationListener : NotificationListenerService() {
|
||||
|
||||
override fun onListenerConnected() {
|
||||
super.onListenerConnected()
|
||||
connected = true
|
||||
Log.i(TAG, "通知使用权已连接")
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
super.onListenerDisconnected()
|
||||
connected = false
|
||||
Log.i(TAG, "通知使用权已断开")
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
try {
|
||||
// ★ 跳过我们自己的通知(不然"AI 读通知"会把 App 自己的提示也读进去)
|
||||
if (n.packageName == packageName) return
|
||||
record(n, removed = false)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "记通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
// ★ 只标成"已消失",**不删掉** —— 用户问"刚才那条验证码呢"的时候,
|
||||
// 通知早就被划掉了,删了就直接查不到了。
|
||||
try {
|
||||
val key = n.key ?: return
|
||||
items[key]?.let { it.removed = true; it.atRemoved = System.currentTimeMillis() }
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun record(n: StatusBarNotification, removed: Boolean) {
|
||||
val extras: Bundle = n.notification?.extras ?: Bundle()
|
||||
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = extras.getCharSequence(Notification.EXTRA_TEXT)?.toString().orEmpty()
|
||||
val big = extras.getCharSequence(Notification.EXTRA_BIG_TEXT)?.toString().orEmpty()
|
||||
val sub = extras.getCharSequence(Notification.EXTRA_SUB_TEXT)?.toString().orEmpty()
|
||||
|
||||
val item = Item(
|
||||
key = n.key ?: "${n.packageName}:${n.postTime}",
|
||||
pkg = n.packageName.orEmpty(),
|
||||
app = appLabel(n.packageName.orEmpty()),
|
||||
title = title,
|
||||
text = if (big.isNotBlank()) big else text,
|
||||
subText = sub,
|
||||
at = if (n.postTime > 0) n.postTime else System.currentTimeMillis(),
|
||||
removed = removed,
|
||||
atRemoved = 0L,
|
||||
)
|
||||
items[item.key] = item
|
||||
|
||||
// 超上限就丢最旧的。用 postTime 排(key 是字符串,排不了时间序)
|
||||
if (items.size > MAX_KEEP) {
|
||||
items.values.sortedBy { it.at }.take(items.size - MAX_KEEP).forEach { items.remove(it.key) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun appLabel(pkg: String): String = try {
|
||||
val pm = packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString()
|
||||
} catch (_: Throwable) {
|
||||
pkg
|
||||
}
|
||||
|
||||
data class Item(
|
||||
val key: String,
|
||||
val pkg: String,
|
||||
val app: String,
|
||||
val title: String,
|
||||
val text: String,
|
||||
val subText: String,
|
||||
val at: Long,
|
||||
var removed: Boolean,
|
||||
var atRemoved: Long,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DoubaoNotif"
|
||||
private const val MAX_KEEP = 200
|
||||
|
||||
/** 最近的通知(内存里,进程死了就没了 —— 见类注释里的隐私考虑) */
|
||||
private val items = ConcurrentHashMap<String, Item>()
|
||||
|
||||
/** 通知使用权连上了没有 */
|
||||
@Volatile
|
||||
var connected: Boolean = false
|
||||
|
||||
/**
|
||||
* 取最近的通知。
|
||||
*
|
||||
* @param limit 最多几条
|
||||
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
|
||||
* @param query 关键词过滤(标题/正文/App 名里含它)
|
||||
*/
|
||||
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
|
||||
var list = items.values.toList()
|
||||
if (onlyAlive) list = list.filter { !it.removed }
|
||||
if (query.isNotBlank()) {
|
||||
val q = query.lowercase()
|
||||
list = list.filter {
|
||||
it.title.lowercase().contains(q) ||
|
||||
it.text.lowercase().contains(q) ||
|
||||
it.app.lowercase().contains(q) ||
|
||||
it.pkg.lowercase().contains(q)
|
||||
}
|
||||
}
|
||||
val arr = JSONArray()
|
||||
list.sortedByDescending { it.at }.take(limit.coerceIn(1, MAX_KEEP)).forEach { it ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("app", it.app)
|
||||
.put("package", it.pkg)
|
||||
.put("title", it.title)
|
||||
.put("text", it.text)
|
||||
.put("subText", it.subText)
|
||||
.put("at", it.at)
|
||||
.put("removed", it.removed),
|
||||
)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
fun count(): Int = items.size
|
||||
|
||||
fun clear() = items.clear()
|
||||
}
|
||||
}
|
||||
@@ -39,9 +39,17 @@ import java.util.concurrent.TimeUnit
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
/**
|
||||
* 一次最多列多少个 App。
|
||||
*
|
||||
* ★ 必须有上限:手机上有 100~300 个 App,全塞给模型光这一条就几千 token,
|
||||
* 而且它多半只需要"找那一个"。要全量就用 query 过滤。
|
||||
*/
|
||||
private val APP_LIST_MAX = 120
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
/** 统一的入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
@@ -76,8 +84,40 @@ 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)
|
||||
// ---- 操作手机:通知 / 打开 App / 音量 ----
|
||||
"notifications" -> notifications(req)
|
||||
"notification_access" -> JSONObject()
|
||||
.put("granted", PhoneOps.hasNotificationAccess(activity))
|
||||
.put("kept", DoubaoNotificationListener.count())
|
||||
"notification_settings" -> {
|
||||
// 带用户去开「通知使用权」—— Android 没有这个权限的运行时申请弹窗,
|
||||
// 只能跳到设置页让他自己勾
|
||||
activity.startActivity(PhoneOps.notificationAccessIntent())
|
||||
JSONObject().put("ok", true).put("opened", "通知使用权设置页")
|
||||
}
|
||||
"notification_clear" -> {
|
||||
DoubaoNotificationListener.clear()
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
"apps" -> appsList(req)
|
||||
"app_launch" -> appLaunch(req)
|
||||
"volume" -> JSONObject().put("state", PhoneOps.volumeState(activity))
|
||||
"volume_set" -> PhoneOps.setVolume(
|
||||
activity,
|
||||
req.optString("stream", "music"),
|
||||
req.optString("mode", "set"),
|
||||
req.optInt("value", 0),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -85,21 +125,171 @@ 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 自己写的界面里,用户选了什么 —— 送回模型的那条路。**
|
||||
*
|
||||
* AI 在 `show_ui` 的 HTML 里写 `Doubao.sendToAi('值')`,那个值会打到这里,
|
||||
* 然后 POST 到内核的 `/api/ui-result` 排队。
|
||||
* 下一轮对话开始时,`agent_loop` 会把队里的东西作为上下文交给模型 ——
|
||||
* 于是模型**真的知道**用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 为什么经内核排队、而不是让 Kotlin 直接起一轮对话:
|
||||
* 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型既慢又费 token,
|
||||
* 而且用户还没说完。排队 → 下一次说话时一起带上,语义上也更对:
|
||||
* **界面上的选择是提问的一部分,不是提问本身**。
|
||||
*
|
||||
* ★ 失败不抛异常,只回 ok:false:这是"用户点了一下按钮",
|
||||
* 内核没起来不该让 App 崩(用户会看到提示,也能再点一次)。
|
||||
*/
|
||||
private fun pushUiResult(req: JSONObject): JSONObject {
|
||||
val value = req.optString("value").trim()
|
||||
val convId = req.optString("conversationId").trim()
|
||||
if (value.isEmpty()) return JSONObject().put("error", "value 是空的")
|
||||
if (convId.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
return try {
|
||||
val body = JSONObject().put("conversationId", convId).put("value", value)
|
||||
val resp = kernelPost("/api/ui-result", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,这次选择没能送出去")
|
||||
} else {
|
||||
JSONObject().put("ok", true).put("queued", resp.optInt("queued"))
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||
*
|
||||
* **不阻塞**:弹出来就返回,用户看完自己关。理由见 [AiSurface.showScreen]。
|
||||
* [wait] 由工具参数决定:
|
||||
* · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关
|
||||
* · true ——**等用户操作**:点了回传按钮或关掉界面才返回,
|
||||
* 用户点的值原样带回给模型
|
||||
*
|
||||
* ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话,
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
val s = AiSurface.showScreen(
|
||||
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,
|
||||
)
|
||||
return JSONObject().put("ok", true).put("id", s.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* 再打开一个存下来的界面。
|
||||
*
|
||||
* ★ 和 [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)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,6 +385,137 @@ class NativeBridge(private val activity: Activity) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 一下内核的接口,返回解析好的 JSON;失败返回 null。
|
||||
*
|
||||
* ★ 和 [kernelPatch] 共用同一套"直接打本机端口"的做法 ——
|
||||
* 不用 `KernelClient`(那是 ViewModel 层的东西,NativeBridge 拿不到,
|
||||
* 而且这里是内核工作线程,不该依赖 UI 层对象)。
|
||||
*/
|
||||
private fun kernelPost(path: String, body: JSONObject): JSONObject? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.post(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
return client.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val text = resp.body?.string() ?: return null
|
||||
runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 App。
|
||||
*
|
||||
* ★ 没传 query 就返回全部(截前 [APP_LIST_MAX] 个)——
|
||||
* 模型可以先看一眼有哪些 App,再决定开哪个。
|
||||
*/
|
||||
private fun appsList(req: JSONObject): JSONObject {
|
||||
val query = req.optString("query").trim()
|
||||
val all = PhoneOps.installedApps(activity)
|
||||
val out = JSONArray()
|
||||
if (query.isBlank()) {
|
||||
all.take(APP_LIST_MAX).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("apps", out)
|
||||
}
|
||||
val q = query.lowercase()
|
||||
all.filter {
|
||||
it.first.lowercase().contains(q) || it.second.lowercase().contains(q)
|
||||
}.take(30).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("matched", out.length()).put("apps", out)
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个 App。
|
||||
*
|
||||
* ★ 找不到时**明确报错并给出相近的名字** —— 让模型能自己改一个再来,
|
||||
* 而不是回一个干巴巴的"失败"(那样它只会反复重试同一个错名字)。
|
||||
*/
|
||||
private fun appLaunch(req: JSONObject): JSONObject {
|
||||
// 已经知道包名和 Activity(从上一步 app_list 拿到的)就直接开,省一次全表扫描
|
||||
val pkg = req.optString("package").trim()
|
||||
val cls = req.optString("activity").trim()
|
||||
if (pkg.isNotEmpty() && cls.isNotEmpty()) {
|
||||
val ok = PhoneOps.launchApp(activity, pkg, cls)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true).put("package", pkg)
|
||||
} else {
|
||||
JSONObject().put("error", "启动 $pkg 失败(系统拒绝了,可能被停用)")
|
||||
}
|
||||
}
|
||||
|
||||
val name = req.optString("name").trim()
|
||||
if (name.isEmpty()) {
|
||||
return JSONObject().put("error", "至少要给 name(App 名字)或 package+activity")
|
||||
}
|
||||
val hit = PhoneOps.findApp(activity, name)
|
||||
?: run {
|
||||
// 给几个名字相近的当提示
|
||||
val q = name.lowercase()
|
||||
val near = PhoneOps.installedApps(activity)
|
||||
.filter { it.first.lowercase().contains(q.take(2)) }
|
||||
.take(5)
|
||||
.map { it.first }
|
||||
return JSONObject()
|
||||
.put("error", "没找到叫「$name」的 App")
|
||||
.put("hint", if (near.isEmpty()) {
|
||||
// ★ 这里写的 action 名必须和 tools/apps.py 里 enum 的一致。
|
||||
// 第一版写的 `app_list` —— 那个名字不存在,模型照着调会失败。
|
||||
"可以用 action=list 看看装了哪些 App"
|
||||
} else {
|
||||
"名字相近的有:" + near.joinToString("、") + "。换个名字再试"
|
||||
})
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, hit.second, hit.third)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true)
|
||||
.put("label", hit.first)
|
||||
.put("package", hit.second)
|
||||
} else {
|
||||
JSONObject().put("error", "找到「${hit.first}」但启动失败(系统拒绝了)")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读通知。
|
||||
*
|
||||
* ★ 权限没开时**返回明确错误**,不是空列表。
|
||||
* 返回空列表的话模型会说"最近没有通知" —— 那是**错的**
|
||||
* (明明有几条,只是我们读不到),用户会被误导。
|
||||
*/
|
||||
private fun notifications(req: JSONObject): JSONObject {
|
||||
if (!PhoneOps.hasNotificationAccess(activity)) {
|
||||
return JSONObject()
|
||||
.put("error", "没有「通知使用权」,读不到任何通知")
|
||||
.put("granted", false)
|
||||
.put(
|
||||
"hint",
|
||||
"这个权限安卓不给运行时申请,必须用户手动开:" +
|
||||
"设置 → 通知 → 通知使用权(或「通知读取权限」)→ 找到本 App 打开。" +
|
||||
"调用 action=notification_settings 可以直接跳到那个设置页。",
|
||||
)
|
||||
}
|
||||
val arr = DoubaoNotificationListener.recent(
|
||||
limit = req.optInt("limit", 20),
|
||||
onlyAlive = req.optBoolean("onlyAlive", false),
|
||||
query = req.optString("query"),
|
||||
)
|
||||
return JSONObject()
|
||||
.put("granted", true)
|
||||
.put("count", arr.length())
|
||||
.put("notifications", arr)
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
|
||||
220
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
220
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -0,0 +1,220 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★ 三个"操作手机"的能力:读通知 / 打开 App / 调音量。
|
||||
*
|
||||
* 抽成一个文件是因为它们同类(都是"AI 要动手机"),
|
||||
* 而且都要处理"权限没给"这一种失败 —— 收在一起比较好统一口径。
|
||||
*
|
||||
* ## 一律"如实报错",不假装成功
|
||||
*
|
||||
* 通知使用权没开、找不到那个 App、音量被系统锁住 —— 这些都会**明确返回错误**,
|
||||
* 而不是返回一个空列表或者一个看起来成功的值。
|
||||
* 模型拿到"权限没开"才会去告诉用户怎么开;拿到空列表它只会说
|
||||
* "最近没有通知",那是**错的**(明明有几条,只是我们读不到)。
|
||||
*/
|
||||
object PhoneOps {
|
||||
|
||||
private const val TAG = "DoubaoPhone"
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 通知使用权开了没有 */
|
||||
fun hasNotificationAccess(ctx: Context): Boolean {
|
||||
val flat = Settings.Secure.getString(ctx.contentResolver, "enabled_notification_listeners")
|
||||
?: return false
|
||||
if (flat.isBlank()) return false
|
||||
val me = ComponentName(ctx, DoubaoNotificationListener::class.java)
|
||||
// enabled_notification_listeners 是 `pkg/cls:pkg/cls` 的形式,
|
||||
// 而且**不同 ROM 的大小写和简写不一样**,所以比对时统一转小写再找
|
||||
return flat.lowercase().split(':').any { entry ->
|
||||
val e = entry.trim()
|
||||
e == me.flattenToString().lowercase() ||
|
||||
e == me.flattenToShortString().lowercase() ||
|
||||
e.startsWith(me.packageName.lowercase() + "/")
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知使用权的设置页(带用户去开) */
|
||||
fun notificationAccessIntent(): Intent =
|
||||
Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、打开 App */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 能启动的 App 列表(系统 + 用户装的) */
|
||||
fun installedApps(ctx: Context): List<Triple<String, String, String>> {
|
||||
val pm = ctx.packageManager
|
||||
val main = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
// ★ Android 11+ 必须先在 Manifest 的 <queries> 里声明 LAUNCHER intent,
|
||||
// 否则这里返回空列表(看着像"这台手机没有 App",很误导)
|
||||
val list = if (Build.VERSION.SDK_INT >= 33) {
|
||||
pm.queryIntentActivities(
|
||||
main,
|
||||
android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
pm.queryIntentActivities(main, 0)
|
||||
}
|
||||
return list.mapNotNull { ri ->
|
||||
val pkg = ri.activityInfo?.packageName ?: return@mapNotNull null
|
||||
val cls = ri.activityInfo?.name ?: return@mapNotNull null
|
||||
val label = ri.loadLabel(pm).toString()
|
||||
Triple(label, pkg, cls)
|
||||
}.sortedBy { it.first }
|
||||
}
|
||||
|
||||
/** 模糊匹配一个 App;找不到返回 null */
|
||||
fun findApp(ctx: Context, query: String): Triple<String, String, String>? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
val all = installedApps(ctx)
|
||||
// 优先级:包名完全相同 > 名字完全相同 > 名字以它开头 > 包含 > 包名包含
|
||||
return all.firstOrNull { it.second.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase().startsWith(q) }
|
||||
?: all.firstOrNull { it.first.lowercase().contains(q) }
|
||||
?: all.firstOrNull { it.second.lowercase().contains(q) }
|
||||
}
|
||||
|
||||
/** 启动一个 App */
|
||||
fun launchApp(ctx: Context, pkg: String, cls: String): Boolean = try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "启动 $pkg/$cls 失败:${t.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、音量 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 音量流。
|
||||
*
|
||||
* ★ 用**字符串名**而不是整数常量:模型要写 `music` / `ring` 这种可读的名字,
|
||||
* 让它记 `STREAM_MUSIC = 3` 既没必要也容易错。
|
||||
*/
|
||||
private fun streamOf(name: String): Int = when (name.trim().lowercase()) {
|
||||
"ring", "ringtone", "铃声" -> AudioManager.STREAM_RING
|
||||
"alarm", "闹钟" -> AudioManager.STREAM_ALARM
|
||||
"call", "voice_call", "通话" -> AudioManager.STREAM_VOICE_CALL
|
||||
"system", "系统" -> AudioManager.STREAM_SYSTEM
|
||||
"notification", "通知" -> AudioManager.STREAM_NOTIFICATION
|
||||
else -> AudioManager.STREAM_MUSIC // 默认媒体音量(最常用)
|
||||
}
|
||||
|
||||
private fun streamName(stream: Int): String = when (stream) {
|
||||
AudioManager.STREAM_RING -> "ring"
|
||||
AudioManager.STREAM_ALARM -> "alarm"
|
||||
AudioManager.STREAM_VOICE_CALL -> "call"
|
||||
AudioManager.STREAM_SYSTEM -> "system"
|
||||
AudioManager.STREAM_NOTIFICATION -> "notification"
|
||||
else -> "music"
|
||||
}
|
||||
|
||||
/**
|
||||
* 读所有音量流的当前值。
|
||||
*
|
||||
* ★ 同时给**原始值**和**百分比**:模型想"调到一半"用百分比直观,
|
||||
* 想"加一格"用原始值准。两个都给,它自己挑。
|
||||
*/
|
||||
fun volumeState(ctx: Context): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val arr = JSONArray()
|
||||
val streams = listOf(
|
||||
AudioManager.STREAM_MUSIC, AudioManager.STREAM_RING, AudioManager.STREAM_ALARM,
|
||||
AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_SYSTEM,
|
||||
AudioManager.STREAM_NOTIFICATION,
|
||||
)
|
||||
for (s in streams) {
|
||||
val cur = am.getStreamVolume(s)
|
||||
val max = am.getStreamMaxVolume(s).coerceAtLeast(1)
|
||||
val pct = Math.round(cur * 100f / max)
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("stream", streamName(s))
|
||||
.put("current", cur)
|
||||
.put("max", max)
|
||||
.put("percent", pct)
|
||||
.put("muted", cur == 0),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("streams", arr)
|
||||
}
|
||||
|
||||
/**
|
||||
* 调音量。
|
||||
*
|
||||
* @param mode set=设成具体值 / up=加 / down=减 / mute=静音 / unmute=取消静音
|
||||
* @param value set 时的值,或 up/down 的步数(默认 1)
|
||||
*/
|
||||
fun setVolume(ctx: Context, streamArg: String, mode: String, value: Int): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val stream = streamOf(streamArg)
|
||||
val max = am.getStreamMaxVolume(stream).coerceAtLeast(1)
|
||||
val before = am.getStreamVolume(stream)
|
||||
|
||||
val target: Int = when (mode.trim().lowercase()) {
|
||||
"mute" -> 0
|
||||
"unmute" -> {
|
||||
// 取消静音:恢复到"上次非零"不好拿,用 max 的一半,至少能听见
|
||||
if (before > 0) before else (max / 2).coerceAtLeast(1)
|
||||
}
|
||||
"up" -> (before + value.coerceAtLeast(1)).coerceAtMost(max)
|
||||
"down" -> (before - value.coerceAtLeast(1)).coerceAtLeast(0)
|
||||
else -> value.coerceIn(0, max)
|
||||
}
|
||||
|
||||
// ★ DND(勿扰)开着时系统会**拒绝**改铃声/通知音量 —— 静默失败。
|
||||
// 所以改完必须**回读**确认,不能假定成功。
|
||||
var err = ""
|
||||
try {
|
||||
am.setStreamVolume(stream, target, 0)
|
||||
} catch (t: Throwable) {
|
||||
err = "${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
val after = am.getStreamVolume(stream)
|
||||
|
||||
val ok = if (err.isEmpty()) after == target else false
|
||||
val out = JSONObject()
|
||||
.put("stream", streamName(stream))
|
||||
.put("before", before)
|
||||
.put("requested", target)
|
||||
.put("current", after)
|
||||
.put("max", max)
|
||||
.put("percent", Math.round(after * 100f / max))
|
||||
.put("ok", ok)
|
||||
if (err.isNotEmpty()) out.put("error", err)
|
||||
if (!ok && err.isEmpty()) {
|
||||
// 回读和请求不一致 = 系统拦了(多半是勿扰模式)
|
||||
out.put(
|
||||
"error",
|
||||
"系统没有接受这次调整(可能开了勿扰模式,或该音量流被系统锁定)。" +
|
||||
"当前值仍是 $after。",
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||
*
|
||||
@@ -58,6 +57,10 @@ object AiSurface {
|
||||
val title: String,
|
||||
val fullHtml: Boolean,
|
||||
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,25 +93,229 @@ object AiSurface {
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。**不阻塞** —— 弹出来就返回,用户看完自己关。
|
||||
* 把界面存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
*
|
||||
* ★ 为什么不做成阻塞:`show_ui` 是"展示"语义,用户可能盯着看很久,
|
||||
* 把内核线程占住没有意义(而且模型这时也没别的事可做,但万一它想
|
||||
* 连续弹两个界面就会被卡死)。要阻塞的语义用 [ask]。
|
||||
* ## 为什么需要(用户的原话:"AI 写的界面可以再点开")
|
||||
*
|
||||
* 界面以前只活在内存里:用户一关(或者退出 App),那份 HTML 就没了。
|
||||
* 过一会儿想"刚才那个图表再看一眼"就再也找不回来,只能让 AI 重新生成 ——
|
||||
* 而重新生成的内容**和上次不一定一样**(模型有随机性),
|
||||
* 用户看到的是"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* ## 为什么不放内核(Python)那边
|
||||
*
|
||||
* 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
|
||||
* `device()` 参数。要走内核就得 Kotlin 再 POST 一次上去,多一次往返、
|
||||
* 还多一个失败点。而 App 私有目录本来就是 Kotlin 最顺手的地方。
|
||||
*
|
||||
* 存法:
|
||||
* `<app files>/ai-screens/<id>.html` 正文
|
||||
* `<app files>/ai-screens/index.json` 索引(列表只读这个)
|
||||
*/
|
||||
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
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户在界面上点了带 `data-doubao-result` 的按钮(WebView 的 JS 桥转进来) */
|
||||
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)[^>]*>.*?</\\1>"), " ")
|
||||
.replace(Regex("<[^>]+>"), " ")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
.take(120)
|
||||
|
||||
private const val KEEP_PER_CONV = 30
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。
|
||||
*
|
||||
* [wait] = false(默认):**不阻塞** —— 弹出来就返回。
|
||||
* [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。
|
||||
*
|
||||
* ★ 为什么要两种:
|
||||
* 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。
|
||||
* 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。
|
||||
* 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。
|
||||
*
|
||||
* ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile`
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★ 超时必须有:用户可能锁屏走了。不设的话内核工作线程永远挂着,
|
||||
* 而 HTTP 是每请求一线程,挂一个少一个。
|
||||
*/
|
||||
fun showScreen(
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 120_000L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(
|
||||
seq.incrementAndGet(), html, title, fullHtml, conversationId,
|
||||
waiting = wait, screenId = screenId,
|
||||
)
|
||||
screen = s
|
||||
screenClosed = false
|
||||
screenAnswer = null
|
||||
notify("screen")
|
||||
Log.i(
|
||||
TAG,
|
||||
"AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," +
|
||||
if (wait) "等用户操作(最多 ${timeoutMs / 1000}s)" else "不等待",
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
// ★ 带上 id —— 它一路回到模型的工具返回值、再进 ToolTrace,
|
||||
// 消息操作栏据此显示「界面」按钮(用户要求"可以再点开")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
// ---- 等待模式 ----
|
||||
val latch = screenLatch
|
||||
val answered = latch?.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS) ?: false
|
||||
val answer = screenAnswer
|
||||
val closed = screenClosed
|
||||
screenLatch = null
|
||||
|
||||
// 等到答案(或超时)之后把界面收掉 —— 否则用户看到一个已经"用完了"
|
||||
// 的界面还开着,会以为还能再点。
|
||||
if (answered) {
|
||||
screen = null
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
.put("waited", true)
|
||||
.put("timeout", !answered)
|
||||
.put("closed", closed)
|
||||
// 用户点的值。超时/直接关掉时是空串。
|
||||
.put("value", answer ?: "")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
/** 等用户交互用的闩。非等待模式下是 null。 */
|
||||
@Volatile
|
||||
private var screenLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var screenAnswer: String? = null
|
||||
|
||||
@Volatile
|
||||
private var screenClosed: Boolean = false
|
||||
|
||||
/**
|
||||
* 用户在界面上点了回传按钮(`Doubao.sendToAi` / `data-doubao-result`)。
|
||||
*
|
||||
* ★ 等待模式下这一下就是"用户答完了"的信号:记下值、放行。
|
||||
* 界面侧收到后会把自己收掉。
|
||||
*/
|
||||
fun screenResult(value: String) {
|
||||
Log.i(TAG, "界面里点了:$value")
|
||||
// 界面上的点击不阻塞任何人,所以只通知一下、让界面记一笔
|
||||
lastScreenResult = value
|
||||
screenAnswer = value
|
||||
screenClosed = false
|
||||
screenLatch?.countDown()
|
||||
notify("screenResult")
|
||||
}
|
||||
|
||||
@@ -119,9 +326,19 @@ object AiSurface {
|
||||
/** 用户把界面关掉了 */
|
||||
fun closeScreen() {
|
||||
screen = null
|
||||
// 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串
|
||||
screenClosed = true
|
||||
screenLatch?.countDown()
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
/** 进等待模式前由 NativeBridge 调一次,准备闩 */
|
||||
fun armScreenLatch() {
|
||||
screenLatch = CountDownLatch(1)
|
||||
screenAnswer = null
|
||||
screenClosed = false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<AiScreenItem>,
|
||||
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)
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.net.Uri
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
@@ -35,6 +39,7 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material3.Button
|
||||
@@ -44,6 +49,7 @@ import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
@@ -77,13 +83,37 @@ import com.doubao.lynxclone.termux.AiSurface
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult: (String) -> Unit) {
|
||||
fun AiHtmlScreenOverlay(
|
||||
screen: AiSurface.Screen?,
|
||||
onClose: () -> Unit,
|
||||
onResult: (String) -> Unit,
|
||||
/** 等待模式:用户点了回传按钮之后自动把界面收掉(这是"用户答完了"的信号) */
|
||||
autoCloseOnResult: Boolean = false,
|
||||
) {
|
||||
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||
val shown = screen ?: last
|
||||
|
||||
// WebView 实例 + "能不能回退"。
|
||||
// ★ 拿到了 WebView 才能调 goBack();canGoBack 要轮询(WebView 没有变更回调)。
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var canGoBack by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(web, screen) {
|
||||
while (web != null && screen != null) {
|
||||
canGoBack = web?.canGoBack() == true
|
||||
kotlinx.coroutines.delay(400)
|
||||
}
|
||||
canGoBack = false
|
||||
}
|
||||
|
||||
// 系统返回键:能回退就先回退(用户点进去了一页,返回键该带他回来),
|
||||
// 不能回退才关掉整个界面 —— 比直接关掉符合直觉。
|
||||
BackHandler(enabled = screen != null) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = screen != null,
|
||||
enter = fadeIn(tween(180)) +
|
||||
@@ -110,6 +140,25 @@ fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// 「返回上一页」只在真能回退时出现 —— 一直显示一个点了没反应的
|
||||
// 箭头比不显示更让人困惑
|
||||
AnimatedVisibility(
|
||||
visible = canGoBack,
|
||||
enter = fadeIn(tween(150)),
|
||||
exit = fadeOut(tween(120)),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { web?.goBack() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
"返回上一页",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||
contentAlignment = Alignment.Center,
|
||||
@@ -117,7 +166,17 @@ fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult
|
||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
AiWebView(shown, onResult)
|
||||
AiWebView(
|
||||
screen = shown,
|
||||
onResult = { value ->
|
||||
onResult(value)
|
||||
// ★ 等待模式下这一下就是"用户答完了" —— 把界面收掉,
|
||||
// 否则用户看到一个已经用完的界面还开着,会以为还能再点。
|
||||
if (autoCloseOnResult) onClose()
|
||||
},
|
||||
onClose = onClose,
|
||||
onWebView = { web = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,57 +184,275 @@ fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult
|
||||
/**
|
||||
* 渲染 AI 写的 HTML。
|
||||
*
|
||||
* ## 两个安全/健壮性决定
|
||||
* ## JS 开着,但 `@JavascriptInterface` 只在"我们自己那一页"暴露
|
||||
*
|
||||
* 1. **禁 JS**:AI 写的 HTML 是"内容",不是"程序"。允许 JS 的话它会拿到
|
||||
* `@JavascriptInterface` 那个桥,等于把 App 的内部接口暴露给一段
|
||||
* 模型生成的脚本。禁掉之后照样能渲染表格/图表(纯 CSS 足够),
|
||||
* 而"可点按钮"用下面 data 属性的方式实现,不需要 JS。
|
||||
* 用户要求"支持 js"。开了 JS 之后最大的风险不是 JS 本身,而是
|
||||
* **`addJavascriptInterface` 注入的那个桥**:它对**之后加载的每一个页面**
|
||||
* 都可见。AI 的页面里如果有个链接,用户点进去落到一个外部站点,
|
||||
* 那个站点的 JS 也能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
*
|
||||
* 2. **可点按钮不用 JS 实现**:给 WebView 装一个自定义 `WebViewClient`,
|
||||
* 在 `shouldOverrideUrlLoading` 里拦 `doubao://pick?value=...` 这种链接。
|
||||
* 界面里写 `<button data-doubao-result="值">` 时,注入的一小段 CSS
|
||||
* 做不到跳链接 —— 所以改成由 App 侧统一把 `data-doubao-result`
|
||||
* 换成 `<a href="doubao://pick?...">`。**这是纯字符串替换,不跑 JS。**
|
||||
* 所以这里**按 origin 收口**:
|
||||
*
|
||||
* · 初始文档用 `loadDataWithBaseURL(null, …)` 加载 —— 它的 document origin
|
||||
* 是**不透明(opaque)**的,WebView 会把它当作"没有来源"
|
||||
* · 导航到任何 **http/https** 之前,先把桥撤掉(`removeJavascriptInterface`)
|
||||
* · 外部页面在 WebView 里正常打开(用户要的"点进去"就是它),
|
||||
* 但它没有桥;而且 `onPageStarted` 里会再兜一次
|
||||
*
|
||||
* ## 依然保持关闭的那些
|
||||
*
|
||||
* · `allowFileAccess` / `allowContentAccess` —— 不让页面读本地文件
|
||||
* · `setAllowFileAccessFromFileURLs` / `setAllowUniversalAccessFromFileURLs`
|
||||
* · `mixedContentMode = NEVER` —— 不让 https 页面加载 http 资源
|
||||
*
|
||||
* ## 可点按钮的两条路都留着
|
||||
*
|
||||
* 1. `<button data-doubao-result="值">` —— App 侧字符串替换成
|
||||
* `doubao://pick?...`,由 `shouldOverrideUrlLoading` 拦。
|
||||
* **不依赖 JS**,所以页面即使 JS 出错也能用
|
||||
* 2. `Doubao.pick("值")` / `Doubao.close()` —— 给会写 JS 的模型用
|
||||
* (图表上点一个点回传、定时刷新之类)
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
private fun AiWebView(screen: AiSurface.Screen, onResult: (String) -> Unit) {
|
||||
private fun AiWebView(
|
||||
screen: AiSurface.Screen,
|
||||
onResult: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onWebView: (WebView) -> Unit = {},
|
||||
) {
|
||||
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||
// 记一下"桥还在不在",避免同一页里反复 remove/add
|
||||
val host = remember(screen.id) { AiWebHost() }
|
||||
host.onResult = onResult
|
||||
host.onClose = onClose
|
||||
|
||||
DisposableEffect(screen.id) {
|
||||
onDispose { host.detach() }
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = false // 见上面第 1 条
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
isVerticalScrollBarEnabled = true
|
||||
|
||||
/**
|
||||
* ★★ 桥的挂/摘时机 —— 这里改了两版才对,把结论记下来。
|
||||
*
|
||||
* **第一版**(错的):`loadDataWithBaseURL` 之前就 add,导航到
|
||||
* http(s) 时 remove。问题:外部页面在 `onPageStarted` 摘桥**之前**
|
||||
* 有个"已经开始加载、桥还在"的窗口期。
|
||||
*
|
||||
* **第二版**(也是错的):只在 `onPageFinished` 里判 url 是不是
|
||||
* `about:blank` 才 add。实测页面报
|
||||
* `Uncaught ReferenceError: Doubao is not defined`
|
||||
* —— `onPageFinished` 的**回调时机比页面内联 <script> 执行还晚**,
|
||||
* 脚本跑的时候桥还没挂上。
|
||||
*
|
||||
* **第三版**(现在这个):初始 load **之前就挂**(保证脚本能用到),
|
||||
* 然后靠 [AiWebHost.payloadLoaded] 这个标志挡住窗口期 ——
|
||||
* loadUrl 到别的地址时,`payloadLoaded` 已经是 true,
|
||||
* 所以立刻摘桥,外部页面**从头到尾**都碰不到它。
|
||||
*/
|
||||
addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
// 开始加载"非初始页"了 —— 说明初始页已经加载过(标志为 true),
|
||||
// 而这次是一个**导航**:立刻摘桥。
|
||||
//
|
||||
// ★ 纯锚点跳转(#xxx)不算导航,不能摘 —— 否则页面内
|
||||
// "跳到某一段"之后 JS 就废了。
|
||||
val anchorOnly = url != null && url.startsWith("about:blank#")
|
||||
if (host.payloadLoaded && !anchorOnly) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
if (!host.payloadLoaded) {
|
||||
// 初始那页加载完成。**马上补挂一次** —— 实测
|
||||
// loadDataWithBaseURL 的页面在脚本执行时桥可能还没生效,
|
||||
// 补挂之后重新 load 才稳。
|
||||
host.payloadLoaded = true
|
||||
view?.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS, null)
|
||||
return
|
||||
}
|
||||
// 之后每次加载完都探一次:**页面里有我们的标记**才重挂桥。
|
||||
//
|
||||
// ★ 为什么用"页面里有没有标记变量"而不是看 url:
|
||||
// 实测从外部页返回(goBack)时,onPageFinished 收到的 url
|
||||
// 并不是 `about:blank`,用 url 判会漏 —— 表现是
|
||||
// "点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
// 标记变量是**页面自己的属性**,页面被换掉它就没了,
|
||||
// 比 url 可靠。
|
||||
//
|
||||
// ★ 如果标记在**但桥不在**,说明这一页是我们的,
|
||||
// 而桥在上一次导航时被摘了 → 重挂。
|
||||
// 如果标记在**桥也在**,什么都不用做。
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS) { result ->
|
||||
// ★ evaluateJavascript 的回调参数是**字符串**,
|
||||
// 而且返回值经 JSON 编码("1" 带着引号)。
|
||||
// 我第一版按 Boolean 处理,条件永远不成立。
|
||||
val ok = (result ?: "").trim('"', ' ')
|
||||
if (ok == "1" && !host.bridgeAttached) {
|
||||
view.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
): Boolean {
|
||||
val u = url ?: return false
|
||||
|
||||
// ① 我们自己约定的回传协议
|
||||
if (u.startsWith("doubao://pick")) {
|
||||
val v = android.net.Uri.decode(
|
||||
android.net.Uri.parse(u).getQueryParameter("value") ?: "",
|
||||
)
|
||||
val v = Uri.decode(Uri.parse(u).getQueryParameter("value") ?: "")
|
||||
if (v.isNotEmpty()) onResult(v)
|
||||
return true
|
||||
}
|
||||
// 外链不在这个 WebView 里开(没有浏览器能力,也没必要)
|
||||
return true
|
||||
if (u.startsWith("doubao://close")) {
|
||||
onClose()
|
||||
return true
|
||||
}
|
||||
|
||||
// ② http(s):**在 WebView 里打开**(用户要的"点进去")。
|
||||
// 桥会在 onPageStarted 里被摘掉(那时 payloadLoaded 已 true),
|
||||
// 所以外部站点碰不到 App。
|
||||
if (u.startsWith("http://") || u.startsWith("https://")) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
return false
|
||||
}
|
||||
|
||||
// ③ 页内锚点(#xxx)交给 WebView 自己处理
|
||||
if (u.startsWith("#")) return false
|
||||
|
||||
// ④ 别的协议(tel: / mailto: / intent: …)交给系统
|
||||
return try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(u))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||
onWebView(this)
|
||||
}
|
||||
},
|
||||
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 给 AI 页面用的 JS 桥。
|
||||
*
|
||||
* 暴露两个方法(页面上写 `Doubao.pick("值")` / `Doubao.close()`):
|
||||
*
|
||||
* · `pick(value)` —— 回传一个值,和点 `data-doubao-result` 按钮等价。
|
||||
* 适合"图表上点一个点"、"定时刷新后回传结果"这类需要脚本的场景。
|
||||
* · `close()` —— 关掉这个界面。
|
||||
*
|
||||
* ★ 方法名和 [NAME] 都刻意短且通用,因为模型要在 HTML 里手写它们;
|
||||
* 但**只暴露这两个** —— 桥能调到的越少,万一被滥用时的损失越小。
|
||||
*
|
||||
* ★ 注意:这个对象**只挂在初始那一页**上(见 [AiWebView] 的注释)。
|
||||
* 导航到外部站点时会被 `removeJavascriptInterface` 摘掉。
|
||||
*/
|
||||
class AiWebHost {
|
||||
@Volatile
|
||||
var onResult: ((String) -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onClose: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 初始那一页(AI 写的那份 HTML)加载完成了没有。
|
||||
*
|
||||
* 用来区分"初始加载"和"用户点链接导航" —— 两者都会走 `onPageStarted`,
|
||||
* 但只有后者该摘桥。见 [AiWebView] 里那段注释。
|
||||
*/
|
||||
@Volatile
|
||||
var payloadLoaded: Boolean = false
|
||||
|
||||
/** 桥现在挂着没有。重挂前要先看它,不然会重复 add。 */
|
||||
@Volatile
|
||||
var bridgeAttached: Boolean = false
|
||||
|
||||
@JavascriptInterface
|
||||
fun pick(value: String?) {
|
||||
val v = (value ?: "").trim()
|
||||
if (v.isEmpty()) return
|
||||
onResult?.invoke(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* `pick` 的别名 —— **这是"AI 自己能写进网页里的接口"**。
|
||||
*
|
||||
* AI 在它生成的 HTML 里写:
|
||||
* ```html
|
||||
* <button onclick="Doubao.sendToAi('用户选了方案 B')">方案 B</button>
|
||||
* ```
|
||||
* 那个值就会经安卓桥 POST 到内核排队,**下一轮对话时作为上下文交给模型**。
|
||||
* 也就是模型真的能知道用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 两个名字都留着(`pick` / `sendToAi`):模型有时写这个有时写那个,
|
||||
* 收两个比让它猜、猜错了整段交互失效要省事得多。
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun sendToAi(value: String?) = pick(value)
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
|
||||
/** 页面销毁时断开引用,别把 Compose 的东西一直攥着 */
|
||||
fun detach() {
|
||||
onResult = null
|
||||
onClose = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "Doubao"
|
||||
|
||||
/**
|
||||
* 往页面里写一个标记并回读 —— 用来判断"当前这一页是不是我们自己注入的"。
|
||||
*
|
||||
* ★ 走 `evaluateJavascript` 而不是看 url:实测从外部页返回时
|
||||
* `onPageFinished` 收到的 url 不是 `about:blank`,用 url 判会漏。
|
||||
* 标记是页面自己的属性,页面被换掉它就没了,可靠得多。
|
||||
*
|
||||
* 返回 "1" 表示是我们的页。
|
||||
*/
|
||||
const val PROBE_JS =
|
||||
"(function(){try{" +
|
||||
"if(!window.__doubaoAiPage){window.__doubaoAiPage=1;}" +
|
||||
"return '1';" +
|
||||
"}catch(e){return '0';}})()"
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 `data-doubao-result="x"` 变成可点的链接,再套一层骨架 */
|
||||
private fun buildAiHtml(screen: AiSurface.Screen): String {
|
||||
val body = if (screen.fullHtml) screen.html else wrapSkeleton(screen.html)
|
||||
@@ -241,11 +518,53 @@ private fun wrapSkeleton(fragment: String): String = """
|
||||
}
|
||||
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;
|
||||
|
||||
/* ★★ 按钮 —— 这里刻意做得**非常显眼**。
|
||||
*
|
||||
* 起因:用户连着两次反馈"哪有按键,网页里的按键也点不了"、"没有一个按键能用"。
|
||||
* 实测下来**功能是好的**(点了值确实回到模型手里),问题出在**视觉**:
|
||||
*
|
||||
* · `data-doubao-result` 的按钮会被 App 改写成 `<a class="db-btn">`,
|
||||
* 拿到亮蓝整行的样式 → 看得出来能点
|
||||
* · 而 `onclick="Doubao.sendToAi(...)"` 的按钮**保持原样**,
|
||||
* 落进下面那条"普通按钮"规则 → 小灰块,在深色主题里跟正文几乎一样
|
||||
*
|
||||
* 同一屏里一半亮蓝一半灰暗,用户当然会以为"只有蓝的能点"甚至"都不能点"。
|
||||
*
|
||||
* 所以现在**所有 button / .db-btn 一律是同样显眼的实心蓝**,
|
||||
* 普通按钮那条规则删掉了。`!important` 是为了压掉模型内联的
|
||||
* `style="background:..."`(模型很爱写这个,一写就把我们的样式盖掉)。 */
|
||||
.db-btn, button, [data-doubao-result], [role=button] {
|
||||
display: block !important;
|
||||
width: 100% !important;
|
||||
margin: 10px 0 !important;
|
||||
padding: 15px 18px !important;
|
||||
background: #2b7bff !important;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none !important;
|
||||
text-align: center !important;
|
||||
border: 0 !important;
|
||||
border-radius: 12px !important;
|
||||
font-size: 16px !important;
|
||||
font-weight: 500 !important;
|
||||
line-height: 1.4 !important;
|
||||
cursor: pointer !important;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
.db-btn:active, button:active, [data-doubao-result]:active, [role=button]:active {
|
||||
background: #1e63d6 !important;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
/* 次要按钮(模型想要不那么抢眼的):加个 class 就能变灰 */
|
||||
.db-plain, button.db-plain {
|
||||
background: #262a31 !important;
|
||||
color: #e8eaed !important;
|
||||
border: 1px solid #3d4450 !important;
|
||||
}
|
||||
/* 两个按钮并排时用这个包一层 */
|
||||
.db-row { display: flex; gap: 10px; }
|
||||
.db-row > * { flex: 1; }
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
|
||||
@@ -7,7 +7,9 @@ import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -38,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<AppViewModel>(…)`:不写的话类型推断会挂
|
||||
// (报 "Not enough information to infer type argument for 'VM'"),
|
||||
// 下面那句 `vm.appContext` 就跟着报未解析引用 ——
|
||||
// 错误信息看着完全不像"泛型没写",很容易往错的方向查。
|
||||
val vm = viewModel<AppViewModel>(factory = object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): 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(
|
||||
@@ -119,18 +137,87 @@ fun AppRoot(
|
||||
* 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 ——
|
||||
* 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。
|
||||
*
|
||||
* 顺序(后写的盖在上面):选择弹窗 > HTML 界面。
|
||||
* `ask_user` 是阻塞的,用户必须先回答它,所以它压在最上面。
|
||||
* 顺序(后写的盖在上面):全屏网页 > 选择弹窗 > HTML 界面。
|
||||
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
AnimatedVisibility(
|
||||
visible = vm.notesOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
NotesScreen(
|
||||
notes = vm.notes,
|
||||
opening = vm.openingNote,
|
||||
onOpen = { vm.openNote(it) },
|
||||
onCloseNote = { vm.closeNote() },
|
||||
onDelete = { vm.deleteNote(it) },
|
||||
onBack = { vm.closeNotes() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「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() },
|
||||
onResult = { vm.onAiScreenResult(it) },
|
||||
onResult = { vm.onAiScreenResult(it, vm.aiScreen?.waiting == true) },
|
||||
autoCloseOnResult = vm.aiScreen?.waiting == true,
|
||||
)
|
||||
AiDialogOverlay(
|
||||
dialog = vm.aiDialog,
|
||||
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||
)
|
||||
|
||||
// 「网页」界面(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页显示之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
AnimatedVisibility(
|
||||
visible = vm.pickUrlFrom.isNotEmpty() || vm.urlPickerOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
UrlListScreen(
|
||||
owner = "这条回复",
|
||||
urls = vm.pickUrlFrom,
|
||||
onPick = { vm.openTypedUrl(it) },
|
||||
onClose = { vm.dismissUrlPicker() },
|
||||
)
|
||||
}
|
||||
|
||||
// 全屏看网页(点消息下方「打开网页」按钮进来)
|
||||
AnimatedVisibility(
|
||||
visible = vm.webPage != null,
|
||||
enter = slideInVertically(tween(240)) { it / 5 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 6 } + fadeOut(tween(150)),
|
||||
) {
|
||||
vm.webPage?.let { url ->
|
||||
WebPageScreen(
|
||||
url = url,
|
||||
onClose = { vm.closeWebPage() },
|
||||
// 用户在网页上点选 → 发回给 AI。走的是**普通发消息**那条路
|
||||
// (所以会正常显示在对话里、正常存历史),而不是什么隐藏通道 ——
|
||||
// 用户能看见自己"发了什么",也能反悔(重新生成)。
|
||||
onSendToAi = { text ->
|
||||
vm.closeWebPage()
|
||||
vm.sendExternal(text)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +248,22 @@ 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()
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
vm.openNotes()
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
|
||||
@@ -69,6 +69,173 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
var aiDialog by mutableStateOf<AiSurface.Dialog?>(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<List<AiScreenItem>>(emptyList())
|
||||
private set
|
||||
|
||||
/** 「AI 界面」列表界面开着没有 */
|
||||
var aiScreenListOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/* -------------------- 笔记(用户要能查看)-------------------- */
|
||||
|
||||
/**
|
||||
* 笔记列表。
|
||||
*
|
||||
* ★ 用户的原话:"notes 用户要能查看" —— 以前笔记**只有 AI 能读写**,
|
||||
* 用户在界面上完全看不到:AI 说"我记下来了",他没法确认记了什么、
|
||||
* 记错没有。这类"AI 替你做事但你无法查看"的功能,用户不会信任。
|
||||
*/
|
||||
var notes by mutableStateOf<List<com.doubao.lynxclone.data.NoteItem>>(emptyList())
|
||||
private set
|
||||
|
||||
var notesOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** 正在阅读的那条笔记(null = 在列表页) */
|
||||
var openingNote by mutableStateOf<com.doubao.lynxclone.data.NoteItem?>(null)
|
||||
private set
|
||||
|
||||
fun openNotes() {
|
||||
notesOpen = true
|
||||
openingNote = null
|
||||
refreshNotes()
|
||||
}
|
||||
|
||||
fun closeNotes() {
|
||||
notesOpen = false
|
||||
openingNote = null
|
||||
}
|
||||
|
||||
fun refreshNotes() {
|
||||
viewModelScope.launch {
|
||||
val list = runCatching {
|
||||
withContext(Dispatchers.IO) { client.notes() }
|
||||
}.getOrDefault(emptyList())
|
||||
notes = list
|
||||
}
|
||||
}
|
||||
|
||||
/** 点开一条:列表接口不带正文,这里再去读全文 */
|
||||
fun openNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
val full = runCatching {
|
||||
withContext(Dispatchers.IO) { client.note(item.file) }
|
||||
}.getOrNull()
|
||||
openingNote = full ?: item
|
||||
}
|
||||
}
|
||||
|
||||
fun closeNote() {
|
||||
openingNote = null
|
||||
}
|
||||
|
||||
fun deleteNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching { client.deleteNote(item.file) }.isSuccess
|
||||
}
|
||||
openingNote = null
|
||||
refreshNotes()
|
||||
showHint(if (ok) "已删除「${item.title.ifBlank { item.file }}」" else "删除失败")
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开 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<AiScreenItem>(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 永久结束了 —— 界面据此把输入框换成结束横幅。
|
||||
*
|
||||
@@ -81,6 +248,77 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
var endedReason by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/**
|
||||
* 正在全屏看的网页(点消息下方的「打开网页」按钮进来的);null 表示没开。
|
||||
*
|
||||
* ★ 为什么要有这个独立界面,而不是让用户去点正文里那行小字:
|
||||
* 链接做成蓝色下划线**没有可发现性** —— 用户不知道能点、也不知道点了
|
||||
* 会发生什么。产品上正确的是给一个**明确的按钮**。
|
||||
*/
|
||||
var webPage by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 一条回复里提到、或用户自己输的网页;空表示不展示那个界面。
|
||||
*
|
||||
* ★ 按项目约定:**列表这种要滚动的东西不用弹窗**,用独立全屏界面。
|
||||
* 一条回复里挂五六个链接是常事,弹窗装不下、用户还得在里面滚动 ——
|
||||
* 那还不如直接开一屏。
|
||||
*/
|
||||
var pickUrlFrom by mutableStateOf<List<FoundUrl>>(emptyList())
|
||||
private set
|
||||
|
||||
/**
|
||||
* 「网页」界面开着没有。
|
||||
*
|
||||
* ★ 为什么它和 [pickUrlFrom] 要分开:**没找到链接时也要能打开这个界面**
|
||||
* (用户可能想自己输网址)。只看 `pickUrlFrom.isNotEmpty()` 的话,
|
||||
* 一条链接都没有的回复点按钮就毫无反应。
|
||||
*/
|
||||
var urlPickerOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 打开「网页」界面。
|
||||
*
|
||||
* ★★ v2.0.39 改:**只有一个链接时也走这个界面**,不再直接跳转。
|
||||
* 上一版是"1 个就直接开",于是用户没有任何确认的机会;
|
||||
* 而且他看不到自己到底要打开哪个地址。
|
||||
* 现在统一先看一眼再决定。(用户拍板:"你要单独开个按钮")
|
||||
*/
|
||||
fun openUrlPicker(urls: List<FoundUrl>) {
|
||||
pickUrlFrom = urls
|
||||
urlPickerOpen = true
|
||||
}
|
||||
|
||||
/** 用户自己输了一个网址(或从列表里挑了一个) */
|
||||
fun openTypedUrl(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty()) return
|
||||
// 没写协议就补 https —— 用户不会每次都打 https://
|
||||
val url = if (t.startsWith("http://") || t.startsWith("https://")) t else "https://$t"
|
||||
urlPickerOpen = false
|
||||
pickUrlFrom = emptyList()
|
||||
webPage = url
|
||||
}
|
||||
|
||||
fun dismissUrlPicker() {
|
||||
pickUrlFrom = emptyList()
|
||||
urlPickerOpen = false
|
||||
}
|
||||
|
||||
/** 打开一个网页(全屏界面) */
|
||||
fun openWebPage(url: String) {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return
|
||||
pickUrlFrom = emptyList() // 进网页界面时把"选哪个"收掉
|
||||
webPage = u
|
||||
}
|
||||
|
||||
fun closeWebPage() {
|
||||
webPage = null
|
||||
}
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
init {
|
||||
@@ -105,10 +343,47 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
aiScreen = null
|
||||
}
|
||||
|
||||
/** 用户在 AI 的界面里点了带 data-doubao-result 的按钮 */
|
||||
fun onAiScreenResult(value: String) {
|
||||
/**
|
||||
* ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。
|
||||
*
|
||||
* 两条路,按界面是不是"等待模式"分流:
|
||||
*
|
||||
* · **等待模式**(`show_ui` 传了 `wait=true`):
|
||||
* 这个值直接作为工具的返回值交给模型 —— 模型**在同一个回合里**就拿到了,
|
||||
* 可以接着干活。所以这里不用再排队(排了反而会让模型看到重复信息)。
|
||||
*
|
||||
* · **不等待模式**(默认):
|
||||
* 模型这一轮已经答完了,所以值先排队(`/api/ui-result`),
|
||||
* 等用户下次说话时和那句话一起交给模型。
|
||||
*
|
||||
* ★ 提示语要**如实**区分这两种情况:
|
||||
* 等待模式说"已提交"(模型确实马上会用);
|
||||
* 不等待模式说"已记下,下次对话会告诉 AI" ——
|
||||
* 写成"已发送"会让用户以为模型马上回话,然后干等。
|
||||
*/
|
||||
fun onAiScreenResult(value: String, waiting: Boolean = false) {
|
||||
AiSurface.screenResult(value)
|
||||
showHint("已选择:$value")
|
||||
if (waiting) {
|
||||
showHint("已提交:$value")
|
||||
return
|
||||
}
|
||||
val conv = activeConversationId
|
||||
if (conv.isBlank()) {
|
||||
showHint("已选择:$value")
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching { client.pushUiResult(conv, value) }.getOrDefault(false)
|
||||
}
|
||||
showHint(
|
||||
if (ok) {
|
||||
"已记下你的选择,下次对话会告诉 AI"
|
||||
} else {
|
||||
"选择没能送出去(内核没响应),再点一次试试"
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户在 AI 的选择弹窗里点了 */
|
||||
@@ -246,6 +521,25 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
runChat(lastUser.content, emptyList())
|
||||
}
|
||||
|
||||
/**
|
||||
* 从别处(现在只有"网页点选")发一条消息给 AI。
|
||||
*
|
||||
* ★ 走的是**和手打消息完全一样的那条路** —— 所以它会正常出现在对话里、
|
||||
* 正常存进历史、也能被"重新生成"。
|
||||
* 刻意不做成什么"隐藏上下文注入":用户得看得见自己发了什么,
|
||||
* 否则模型回一句"你选的这个……"而用户根本不知道自己选过什么。
|
||||
*/
|
||||
fun sendExternal(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty() || streaming) return
|
||||
if (conversationEnded) {
|
||||
showHint("这次对话已结束,请开一个新对话")
|
||||
return
|
||||
}
|
||||
screen = Screen.Chat
|
||||
runChat(t, emptyList())
|
||||
}
|
||||
|
||||
private fun runChat(text: String, files: List<Attachment>) {
|
||||
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||
@@ -288,7 +582,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 -> {
|
||||
|
||||
@@ -613,6 +613,63 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
vm.showHint("已复制")
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
/**
|
||||
* ★★「打开网页」—— 用户明确要求"你要单独开个按钮"。
|
||||
*
|
||||
* 以前只有正文里那行蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会怎样。
|
||||
* 现在改成:回复里只要有 http(s) 链接,这里就出现一个按钮。
|
||||
*
|
||||
* · 只有 1 个链接 → 直接打开
|
||||
* · 多个链接 → 进「链接列表」全屏界面让用户挑
|
||||
* (按项目约定:列表这种要滚动的东西**不用弹窗**)
|
||||
*
|
||||
* ★ 链接是从 markdown 里现算的(`extractUrls`),不额外存状态 ——
|
||||
* 存了就要担心和 content 不同步(重新生成、编辑之后)。
|
||||
*
|
||||
* ★★ 按钮**无条件显示**(v2.0.39 改)。
|
||||
* 上一版是"这条回复里有链接才显示",于是:
|
||||
* · extractUrls 漏认写法时(裸 URL 就漏)按钮整个不见了
|
||||
* · 而且用户根本无从知道"这条能不能开网页"
|
||||
* 现在永远在,顺带还能自己在里面输网址 —— 它就是个浏览器入口。
|
||||
*/
|
||||
val urls = remember(msg.content) { extractUrls(msg.content) }
|
||||
RoundIconButton(
|
||||
Icons.Filled.Language,
|
||||
if (urls.isEmpty()) "打开网页" else "打开网页(${urls.size} 个链接)",
|
||||
tint = if (urls.isEmpty()) null else Doubao.Blue,
|
||||
) {
|
||||
vm.openUrlPicker(urls)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
|
||||
/**
|
||||
* ★★「界面」—— 再打开 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(
|
||||
|
||||
@@ -93,6 +93,55 @@ fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg
|
||||
@Composable
|
||||
fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary
|
||||
|
||||
/* ------------------------------ 打开链接 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 在系统浏览器里打开一个链接。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接**以前渲染成蓝色下划线但没有绑点击** ——
|
||||
* 看着像能点,点了完全没反应。用户会以为是"链接坏了"。
|
||||
* (这个坑是用户问"网页在哪点开"时才查出来的:我一直在讲 AI 弹的界面,
|
||||
* 而最容易想到的"点链接"其实一直是坏的。)
|
||||
*
|
||||
* ## 为什么用系统浏览器而不是应用内 WebView
|
||||
*
|
||||
* AI 弹出的那个界面里点链接是**应用内**打开的(用户明确要的"可再点进去")。
|
||||
* 但聊天正文里的链接不一样:那里没有"返回 AI 界面"这个上下文,
|
||||
* 在应用内开一个 WebView 会让用户迷失(返回键行为说不清)。
|
||||
* 交给系统浏览器,行为标准、有历史、有关闭 —— 对正文链接更合适。
|
||||
*
|
||||
* ★ 必须 try/catch:设备上可能没有浏览器(精简 ROM),
|
||||
* 或者链接协议没人能处理,那会抛 ActivityNotFoundException。
|
||||
* 不接的话点一下链接 App 就崩。
|
||||
*/
|
||||
fun openInBrowser(context: android.content.Context, url: String): Boolean {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return false
|
||||
val uri = try {
|
||||
android.net.Uri.parse(u)
|
||||
} catch (_: Throwable) {
|
||||
return false
|
||||
}
|
||||
// 只放行有 scheme 的绝对地址;相对地址点了没意义,还会让 Intent 解析失败
|
||||
if (uri.scheme.isNullOrBlank()) return false
|
||||
|
||||
return try {
|
||||
context.startActivity(
|
||||
android.content.Intent(android.content.Intent.ACTION_VIEW, uri)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.w("DoubaoLink", "打不开 $u:${t.javaClass.simpleName}: ${t.message}")
|
||||
android.widget.Toast
|
||||
.makeText(context, "打不开这个链接", android.widget.Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 动画 ------------------------------ */
|
||||
|
||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||
|
||||
@@ -13,14 +13,19 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.ExperimentalTextApi
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
@@ -99,17 +104,19 @@ fun MarkdownText(
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
is MdBlock.Heading -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
@@ -147,12 +154,14 @@ fun MarkdownText(
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
is MdBlock.Paragraph -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,6 +265,118 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** 一条回复里提到的一个网页 */
|
||||
data class FoundUrl(
|
||||
/** 完整地址 */
|
||||
val url: String,
|
||||
/** 模型给链接写的文字(`[文字](url)` 里的那个),没有就是空串 */
|
||||
val label: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 从 markdown 里抽出所有网页地址(去重、保序,带上链接文字)。
|
||||
*
|
||||
* ## ★★ 重写过一版:原来漏了 7/11 种写法
|
||||
*
|
||||
* 上一版是手写扫描器,**只认 `](` 紧挨着的 markdown 链接**。
|
||||
* 实测(`scripts/probe-extract-urls.py`)漏掉这些:
|
||||
*
|
||||
* · **裸 URL** —— `见 https://example.com`(**模型最常这么写**)
|
||||
* · `[文字] (地址)` —— 中英混排时中间常有空格
|
||||
* · `<https://example.com>` —— 尖括号包裹
|
||||
* · 中文标点紧跟着的 URL —— `见(https://…)。`
|
||||
* · 换行里的裸 URL
|
||||
* · `www.example.com`
|
||||
*
|
||||
* 后果不是"少显示一个链接",而是 **`extractUrls` 返回空 → 整个
|
||||
* 「打开网页」按钮都不显示**(用户报的"还是没有"就是这个)。
|
||||
*
|
||||
* 现在改成**正则扫全文**,两类都收:markdown 链接 + 裸 URL。
|
||||
*
|
||||
* ★ 只认 http/https。`[文档](docs/x.md)` 这种相对路径在手机上点了没意义,
|
||||
* 不算"网页"(剪掉尾巴上的中文标点和右括号,别把 `)。` 吞进地址里)。
|
||||
*/
|
||||
fun extractUrls(markdown: String): List<FoundUrl> {
|
||||
if (!markdown.contains("http://") && !markdown.contains("https://")) return emptyList()
|
||||
val out = LinkedHashSet<String>()
|
||||
val labels = HashMap<String, String>()
|
||||
|
||||
// ① markdown 链接:[文字](地址),允许中间有空格、文字里有方括号
|
||||
RE_MD_LINK.findAll(markdown).forEach { m ->
|
||||
val label = m.groupValues[1].trim().trim('[', ']')
|
||||
val url = cleanUrl(m.groupValues[2])
|
||||
if (url.isNotEmpty()) {
|
||||
if (label.isNotEmpty()) labels.putIfAbsent(url, label)
|
||||
out.add(url)
|
||||
}
|
||||
}
|
||||
|
||||
// ② 裸 URL / 尖括号包裹的 URL
|
||||
RE_BARE_URL.findAll(markdown).forEach { m ->
|
||||
val url = cleanUrl(m.value)
|
||||
if (url.isNotEmpty()) out.add(url)
|
||||
}
|
||||
|
||||
return out.map { FoundUrl(it, labels[it] ?: "") }
|
||||
}
|
||||
|
||||
/**
|
||||
* 剪掉 URL 尾巴上不属于地址的字符。
|
||||
*
|
||||
* ★ 必须做:中文回复里 URL 后面常紧跟 `)。`、`,`、`】`,
|
||||
* 不剪的话地址里会带上这些,打开必然 404。
|
||||
* 左右括号要配对判断(`.../a_(b)` 这种地址本身带括号,不能一刀切)。
|
||||
*/
|
||||
private fun cleanUrl(raw: String): String {
|
||||
var s = raw.trim().trim('<', '>', '"', '\'', '`')
|
||||
// 尾部的中文标点/空白一律剪掉
|
||||
s = s.trimEnd('。', ',', '、', ';', ':', '!', '?', ')', '】', '》', '」', '』', '…', '.', ',', ';', ':', '!', '?')
|
||||
// 去掉不配对的右括号
|
||||
while (s.endsWith(")") && s.count { it == ')' } > s.count { it == '(' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
while (s.endsWith("]") && s.count { it == ']' } > s.count { it == '[' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
if (!s.startsWith("http://") && !s.startsWith("https://")) return ""
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* markdown 链接 `[文字](地址)`。
|
||||
*
|
||||
* ★★ 地址部分用 **`(?:[^\s()]|\([^\s()]*\))+`** 而不是 `[^\s)]+`。
|
||||
*
|
||||
* 起因是一条维基百科地址:`https://en.wikipedia.org/wiki/A_(b)`
|
||||
*
|
||||
* · 用 `[^\s)]+` 的话,它在 `A_(b` 处被第一个 `)` 截断 ——
|
||||
* 然后外层那个 `\)` 匹配的是**地址里那个右括号**,
|
||||
* 于是算出来的地址是 `https://en.wikipedia.org/wiki/A_(b`(缺一个括号、点开 404)
|
||||
* · 而且裸 URL 规则会再匹配一次,得到另一个截断版本 →
|
||||
* **同一个链接在列表里出现两次,两个都不对**
|
||||
*
|
||||
* "平衡括号"这个写法让右括号只能以完整 `(…)` 的形式出现在地址里,
|
||||
* 所以维基那种地址能整个吃到,而 markdown 的收尾括号仍然能正确识别。
|
||||
*
|
||||
* ★ 文字部分用 `[^\]\n]*` 而不是 `.*?` —— 后者在长回复里可能跨行吞掉一大段。
|
||||
*/
|
||||
private val RE_MD_LINK =
|
||||
Regex("""\[([^\]\n]{1,200})]\s*\(\s*(https?://(?:[^\s()]|\([^\s()]*\))+)\s*\)""")
|
||||
|
||||
/**
|
||||
* 裸 URL(含尖括号包裹)。
|
||||
*
|
||||
* ★★ 同样用"平衡括号"写法。两种错法都踩过:
|
||||
*
|
||||
* · 允许右括号(`[^\s]+`)→ `[x](https://a.com)` 会被**再匹配一次**,
|
||||
* 同一条链接算出两个不同地址(一个还带多余的右括号)
|
||||
* · 完全禁止括号(`[^\s()]+`)→ `.../wiki/A_(b)` 被截断成 `.../wiki/A_`
|
||||
*
|
||||
* 到空白或中文标点为止(中文回复里 URL 后面常紧跟 `)。`、`,`)。
|
||||
*/
|
||||
private val RE_BARE_URL =
|
||||
Regex("""<?https?://(?:[^\s<>()\[\]{}()【】「」『』,。;:!?、]|\([^\s()]*\))+>?""")
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
@@ -264,8 +385,19 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*
|
||||
* ★ 这是个 `@Composable`:链接要用 `withLink(...)` 挂点击,
|
||||
* 而那个 API 是 composable 的(它内部要拿 `LocalTextLinkScope`)。
|
||||
*
|
||||
* ★ 还要 `@OptIn(ExperimentalTextApi::class)` —— `withLink` 标了实验 API。
|
||||
* 不 opt-in 的话报的是 `Unresolved reference 'withLink'`(不是"需要 opt-in"),
|
||||
* 很容易误判成"这个版本没有这个 API"。我是把 aar 拆开 javap 看了注解才确认的。
|
||||
*/
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString {
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
@Composable
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
val ctx = LocalContext.current
|
||||
return buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
when {
|
||||
@@ -325,8 +457,40 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
val url = text.substring(open + 1, end).trim()
|
||||
/**
|
||||
* ★★ 给链接**真正绑上点击**。
|
||||
*
|
||||
* 以前这里只有颜色和下划线,**没有 clickable** ——
|
||||
* 看着像能点、点了完全没反应。用户会以为"链接坏了"。
|
||||
* (这是用户问"网页在哪点开"时才查出来的:我一直在讲
|
||||
* AI 弹的那个界面,而最容易想到的"点链接"一直是坏的。)
|
||||
*
|
||||
* ★ 用 `withLink(LinkAnnotation.Url(...))`:这是 Compose 1.7
|
||||
* 起的方式,和 `Text()` 直接配合(不需要 ClickableText),
|
||||
* 而且**不需要在外部套 pointerInput 去算点击落在哪个字符上**。
|
||||
* 那个老办法要自己遍历 annotation 范围,容易算错。
|
||||
*/
|
||||
if (url.isNotEmpty()) {
|
||||
withLink(
|
||||
LinkAnnotation.Url(
|
||||
url = url,
|
||||
styles = TextLinkStyles(
|
||||
style = SpanStyle(
|
||||
color = linkColor,
|
||||
textDecoration = TextDecoration.Underline,
|
||||
),
|
||||
),
|
||||
linkInteractionListener = { link ->
|
||||
val target = (link as? LinkAnnotation.Url)?.url ?: url
|
||||
openInBrowser(ctx, target)
|
||||
},
|
||||
),
|
||||
) { append(label) }
|
||||
} else {
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
@@ -339,4 +503,7 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
258
android/app/src/main/java/com/doubao/lynxclone/ui/NotesScreen.kt
Normal file
258
android/app/src/main/java/com/doubao/lynxclone/ui/NotesScreen.kt
Normal file
@@ -0,0 +1,258 @@
|
||||
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.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.ContentCopy
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
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.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
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 com.doubao.lynxclone.data.NoteItem
|
||||
|
||||
/**
|
||||
* ★★ 笔记列表 —— 用户要求"notes 用户要能查看"。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 笔记以前**只有 AI 能读写**(走 notes 工具),用户在界面上完全看不到。
|
||||
* 也就是说:AI 说"我记下来了",用户没有任何办法确认它记了什么、
|
||||
* 记错没有、或者删掉记错的。这类"AI 替你做事但你无法查看"的功能,
|
||||
* 用户是不会信任的。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
* 列表要滚动(笔记会越攒越多),弹窗装不下。
|
||||
*/
|
||||
@Composable
|
||||
fun NotesScreen(
|
||||
notes: List<NoteItem>,
|
||||
opening: NoteItem?,
|
||||
onOpen: (NoteItem) -> Unit,
|
||||
onCloseNote: () -> Unit,
|
||||
onDelete: (NoteItem) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// 阅读某一条时,返回键先回到列表(而不是直接退出笔记页)——
|
||||
// 用户会觉得"我明明在笔记里,怎么一按就出去了"
|
||||
BackHandler(enabled = true) {
|
||||
if (opening != null) onCloseNote() else onBack()
|
||||
}
|
||||
|
||||
if (opening != null) {
|
||||
NoteDetail(note = opening, onBack = onCloseNote, onDelete = { onDelete(opening) })
|
||||
return
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("笔记", onBack = onBack) {
|
||||
Text(
|
||||
if (notes.isEmpty()) "还没有" else "${notes.size} 条",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
if (notes.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"还没有笔记。\n让 AI「记一下」某件事,就会出现在这里。",
|
||||
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(notes.size) { index ->
|
||||
val n = notes[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onOpen(n) }
|
||||
.padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
n.title.ifBlank { n.file },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (n.preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
n.preview,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
listOf(formatNoteTime(n.at), formatNoteBytes(n.bytes))
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(" · "),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// 删除单独一个小按钮,别和"点开"挤在一起误触
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.clickable { onDelete(n) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
"删除",
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 读某一条笔记的全文 */
|
||||
@Composable
|
||||
private fun NoteDetail(note: NoteItem, onBack: () -> Unit, onDelete: () -> Unit) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader(note.title.ifBlank { "笔记" }, onBack = onBack) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(CircleShape).clickable {
|
||||
clipboard.setText(AnnotatedString(note.content))
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.ContentCopy, "复制", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(CircleShape).clickable { onDelete() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 18.dp),
|
||||
) {
|
||||
Text(
|
||||
listOf(formatNoteTime(note.at), formatNoteBytes(note.bytes))
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(" · "),
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// 正文可能是 markdown(notes 工具写的是 .md),所以按 markdown 渲染
|
||||
MarkdownText(
|
||||
markdown = note.content,
|
||||
color = doubaoText(),
|
||||
fontSize = 15,
|
||||
lineHeight = 24,
|
||||
)
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ISO 时间 → 「今天 15:19」/「10-15 15:19」。
|
||||
*
|
||||
* ★ 解析失败就返回空串(界面上那一项直接不显示)——
|
||||
* **不要瞎猜**:用户手改过文件名的情况是有的,猜错会显示一个假时间。
|
||||
*/
|
||||
private fun formatNoteTime(iso: String): String {
|
||||
if (iso.isBlank()) return ""
|
||||
return try {
|
||||
val cleaned = iso.substringBefore('.').removeSuffix("Z")
|
||||
val dt = java.time.LocalDateTime.parse(cleaned)
|
||||
val today = java.time.LocalDate.now()
|
||||
val fmt = if (dt.toLocalDate() == today) {
|
||||
java.time.format.DateTimeFormatter.ofPattern("'今天' HH:mm")
|
||||
} else {
|
||||
java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm")
|
||||
}
|
||||
dt.format(fmt)
|
||||
} catch (_: Throwable) {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatNoteBytes(n: Int): String = when {
|
||||
n <= 0 -> ""
|
||||
n < 1024 -> "${n}B"
|
||||
n < 1024 * 1024 -> "${n / 1024}KB"
|
||||
else -> String.format(java.util.Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0)
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.TouchApp
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/**
|
||||
* ★★ 全屏看网页 —— 由一个**明确的按钮**打开,不靠去点正文里的小字。
|
||||
*
|
||||
* ## 为什么单独做这个界面
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接做成蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会发生什么(是开浏览器?还是在应用里开?)。
|
||||
* 用户的原话是"你要单独开个按钮" —— 对,产品上正确的就是给个按钮。
|
||||
*
|
||||
* 所以:消息操作栏里出现一个「打开网页」按钮(只有回复里真有链接才出现),
|
||||
* 点开就是这里 —— 一个像样的浏览器界面,而不是把用户丢给系统浏览器
|
||||
* (那样他就离开 App 了,回来还得重新找对话)。
|
||||
*
|
||||
* ## 和 AI 那个 `show_ui` 界面的区别
|
||||
*
|
||||
* `show_ui` 是 **AI 写的 HTML**,我们注入内容、页面里只有它写的东西
|
||||
* 这里 是**真的在浏览互联网**,用户能点链接、能返回、能前进
|
||||
*
|
||||
* 两者都需要 JS,但**桥只有 `show_ui` 那边有** —— 这里浏览的是外部网站,
|
||||
* 绝不能让它碰到 App 的接口(所以这个 WebView 里没有任何
|
||||
* `addJavascriptInterface`)。
|
||||
*
|
||||
* ## 安全
|
||||
*
|
||||
* 文件访问 / 跨域访问 / 混合内容全部关闭。没有注入任何 JS 桥。
|
||||
* 这是"浏览器",就该按浏览器的方式隔离。
|
||||
*
|
||||
* ## 点选模式(把网页上的东西回传给 AI)
|
||||
*
|
||||
* 顶部有个「点选」按钮。打开之后页面上的可点元素会被描上虚线边框,
|
||||
* 用户点哪个就把哪个的**文字/链接/位置**记下来,出现在底部确认条上,
|
||||
* 用户点「发给 AI」才真的发出去(点错了不至于白跑一轮模型)。
|
||||
*
|
||||
* ★ 实现上**没有挂 JS 桥** —— 用的是"注入脚本写进数组 + Kotlin 主动轮询取走",
|
||||
* 数据只从页面流向 App。理由见 [WebPick] 的注释:这里浏览的是外部网站,
|
||||
* 挂桥等于把 App 的内部接口交给互联网上任意一个站点。
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
fun WebPageScreen(
|
||||
url: String,
|
||||
onClose: () -> Unit,
|
||||
onSendToAi: (String) -> Unit = {},
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var title by remember(url) { mutableStateOf("") }
|
||||
var canBack by remember { mutableStateOf(false) }
|
||||
var canFwd by remember { mutableStateOf(false) }
|
||||
var progress by remember { mutableStateOf(0) }
|
||||
|
||||
/** 点选模式开着没有 */
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
|
||||
/**
|
||||
* 用户选中/填写的条目(**累积**)。
|
||||
*
|
||||
* ★ 累积而不是点一条发一条:用户可能在页面上选好几处、填几个框,
|
||||
* 然后一起问"这些对不对"。分开发会触发好几轮模型调用,又慢又费 token。
|
||||
*/
|
||||
val picked = remember { mutableStateListOf<PickedElement>() }
|
||||
|
||||
// WebView 没有"导航状态变了"的回调,只能轮询。
|
||||
// 400ms 在真机上完全够用(页面前进后退是用户动作,不是动画)。
|
||||
LaunchedEffect(web) {
|
||||
while (web != null) {
|
||||
canBack = web?.canGoBack() == true
|
||||
canFwd = web?.canGoForward() == true
|
||||
delay(400)
|
||||
}
|
||||
}
|
||||
|
||||
// 点选模式下:每次加载完注入一次;然后每 500ms 取一次队列。
|
||||
//
|
||||
// ★ 为什么要"每次加载完注入":用户点链接跳到新页面(或页面自己跳),
|
||||
// 新文档里没有我们注入的脚本,不重注就没法点了。
|
||||
LaunchedEffect(web, picking) {
|
||||
if (!picking || web == null) {
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
while (true) {
|
||||
delay(500)
|
||||
val w = web ?: break
|
||||
// evaluateJavascript 的返回值经 JSON 编码:脚本返回字符串 'xxx',
|
||||
// 这里拿到的是 "\"xxx\"" —— 所以要解两层
|
||||
w.evaluateJavascript(WebPick.DRAIN_JS) { raw ->
|
||||
val parsed = decodeJsonString(raw)
|
||||
if (parsed.isBlank() || parsed == "[]") return@evaluateJavascript
|
||||
runCatching {
|
||||
val arr = org.json.JSONArray(parsed)
|
||||
for (i in 0 until arr.length()) {
|
||||
val obj = arr.optJSONObject(i) ?: continue
|
||||
picked.add(
|
||||
PickedElement(
|
||||
summary = WebPick.describe(obj),
|
||||
kind = obj.optString("kind", "click"),
|
||||
url = obj.optString("url"),
|
||||
pageTitle = obj.optString("title").ifBlank { title },
|
||||
raw = obj.toString(),
|
||||
),
|
||||
)
|
||||
}
|
||||
// 只留最近 30 条,别让用户在页面上乱点把内存堆满
|
||||
while (picked.size > 30) picked.removeAt(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 系统返回键:先回退网页,退不了了才关界面
|
||||
BackHandler(enabled = true) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 6.dp, end = 6.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowBack, "后退", canBack) { web?.goBack() }
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowForward, "前进", canFwd) { web?.goForward() }
|
||||
NavIcon(Icons.Filled.Refresh, "刷新", true) { web?.reload() }
|
||||
|
||||
// 标题:能拿到网页 title 就用它,拿不到退回落 host ——
|
||||
// 只显示一长串 URL 在手机窄屏上没法看
|
||||
Column(Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||
Text(
|
||||
title.ifBlank { hostOf(url) },
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (title.isNotBlank()) {
|
||||
Text(
|
||||
hostOf(url),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NavIcon(Icons.Filled.OpenInNew, "用系统浏览器打开", true) {
|
||||
openInBrowser(ctx, web?.url ?: url)
|
||||
}
|
||||
NavIcon(Icons.Filled.Close, "关闭", true) { onClose() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 「点选」开关 —— 打开后能在网页上点东西回传给 AI。
|
||||
*
|
||||
* ★ 做成一条**常驻的横条**而不是顶部一个图标:
|
||||
* 这个能力不看说明根本发现不了(用户得先知道"能点选"才会去找按钮)。
|
||||
* 横条上写清楚现在是什么状态、点了会发生什么。
|
||||
*/
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(if (picking) doubaoAccentSoft() else doubaoCard())
|
||||
.clickable {
|
||||
if (picking) {
|
||||
web?.evaluateJavascript(WebPick.UNINSTALL_JS, null)
|
||||
picking = false
|
||||
picked.clear()
|
||||
} else {
|
||||
picking = true
|
||||
}
|
||||
}
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.TouchApp,
|
||||
null,
|
||||
tint = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
if (picking) "点选已开启 —— 点网页上任意元素,内容会带回给 AI" else "点选:把网页上的内容带回给 AI",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (picking) "关闭" else "开启",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
// 加载进度:细一条,不占地方但能让人知道"在动"
|
||||
AnimatedVisibility(
|
||||
visible = progress in 1..99,
|
||||
enter = fadeIn(tween(120)),
|
||||
exit = fadeOut(tween(300)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(progress / 100f)
|
||||
.height(2.dp)
|
||||
.background(doubaoAccent()),
|
||||
)
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { c ->
|
||||
WebView(c).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true // 正常浏览器行为
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = true
|
||||
settings.builtInZoomControls = true
|
||||
settings.displayZoomControls = false
|
||||
settings.userAgentString = settings.userAgentString + " DoubaoClone"
|
||||
|
||||
// ★ 这个 WebView 里**不挂任何 JS 桥** ——
|
||||
// 浏览的是外部网站,绝不能让它碰到 App 的接口。
|
||||
// (点选回传走的是"页面写队列 + 我们主动 evaluateJavascript 取",
|
||||
// 数据单向,页面没有办法主动调 App。见 WebPick 的注释。)
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, u: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, u, favicon)
|
||||
progress = 5
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, u: String?) {
|
||||
super.onPageFinished(view, u)
|
||||
progress = 100
|
||||
title = view?.title.orEmpty()
|
||||
// ★ 用户点链接跳到新页面(或页面自己跳)之后,
|
||||
// 新文档里没有我们注入的脚本 —— 点选模式就失效了。
|
||||
// 所以每次加载完补注一次(脚本自己防重)。
|
||||
if (picking) view?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
}
|
||||
}
|
||||
webChromeClient = object : android.webkit.WebChromeClient() {
|
||||
override fun onProgressChanged(view: WebView?, newProgress: Int) {
|
||||
progress = newProgress
|
||||
}
|
||||
|
||||
override fun onReceivedTitle(view: WebView?, t: String?) {
|
||||
if (!t.isNullOrBlank()) title = t
|
||||
}
|
||||
}
|
||||
loadUrl(url)
|
||||
web = this
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* 底部确认条:用户点中了什么,以及「发给 AI / 取消」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*/
|
||||
/**
|
||||
* 底部确认条:用户攒了哪些"选了/写了"的内容,以及
|
||||
* 「发给 AI」「清空」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持**累积多条**再一起发 —— 用户在页面上选几处、填几个框,
|
||||
* 最后一起问"这些对不对"。分开发会跑好几轮模型。
|
||||
*/
|
||||
AnimatedVisibility(
|
||||
visible = picked.isNotEmpty(),
|
||||
enter = slideInVertically(tween(220)) { it } + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(tween(180)) { it } + fadeOut(tween(120)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"已选 ${picked.size} 条,会一起发给 AI:",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"清空",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoAccent(),
|
||||
modifier = Modifier.clickable { picked.clear() },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// 条目多了要能滚 —— 但只占一段固定高度,别把网页挤没了
|
||||
Column(
|
||||
Modifier
|
||||
.heightIn(max = 120.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
picked.forEach { p ->
|
||||
Text(
|
||||
"· " + p.summary,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(11.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
androidx.compose.material3.OutlinedButton(
|
||||
onClick = { picked.clear() },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
androidx.compose.material3.Button(
|
||||
onClick = {
|
||||
onSendToAi(WebPick.buildReport(picked.toList()))
|
||||
picked.clear()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("发给 AI") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `evaluateJavascript` 的返回值是**经 JSON 编码的字符串**(脚本返回 `'abc'`
|
||||
* 时 Kotlin 拿到的是 `"\"abc\""`)。
|
||||
*
|
||||
* ★ 这个坑踩过两次([AiWebView] 的探针、这里),所以抽成一个函数,
|
||||
* 并在名字上把"要解两层"这件事写出来。
|
||||
*/
|
||||
private fun decodeJsonString(raw: String?): String {
|
||||
val s = (raw ?: "").trim()
|
||||
if (s.isEmpty() || s == "null") return ""
|
||||
return try {
|
||||
if (s.startsWith("\"")) org.json.JSONTokener(s).nextValue() as? String ?: "" else s
|
||||
} catch (_: Throwable) {
|
||||
s.trim('"')
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavIcon(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
desc: String,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
// 不能点的时候**也要占位**(否则顶部栏的图标会左右跳),
|
||||
// 但变淡 + 不响应点击
|
||||
.clickable(enabled = enabled) { onClick() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
icon,
|
||||
desc,
|
||||
tint = if (enabled) doubaoText() else doubaoTextDim().copy(alpha = 0.35f),
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 URL 里取主机名(显示用)。解析不了就原样返回。 */
|
||||
private fun hostOf(url: String): String = try {
|
||||
android.net.Uri.parse(url).host ?: url
|
||||
} catch (_: Throwable) {
|
||||
url
|
||||
}
|
||||
|
||||
/**
|
||||
* 「网页」—— **独立全屏界面**,不是弹窗。
|
||||
*
|
||||
* ## 为什么不用 AlertDialog
|
||||
*
|
||||
* 项目约定:**列表这种要滚动的东西不用弹窗**。一条回复里挂五六个链接是常事,
|
||||
* 弹窗一屏只装得下三四个,用户得在弹窗里滚动 —— 那还不如直接开一屏。
|
||||
* 而且弹窗盖住对话,用户没法一边看着回复一边挑链接。
|
||||
*
|
||||
* ## ★★ 自己输网址(v2.0.39 加)
|
||||
*
|
||||
* 用户的原话是"**你要单独开个按钮**"。既然它是个按钮,那它就不该只在
|
||||
* "这条回复恰好有链接"时才有用 —— 现在里面能直接输网址,
|
||||
* 它就是一个**浏览器入口**,任何时候按都有意义。
|
||||
* (另一个原因:`extractUrls` 曾经漏认写法,导致按钮整个不显示,
|
||||
* 用户根本不知道这功能存在。)
|
||||
*
|
||||
* 顶栏按项目约定:`← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun UrlListScreen(
|
||||
owner: String,
|
||||
urls: List<FoundUrl>,
|
||||
onPick: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
var typed by remember { mutableStateOf("") }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("网页", onBack = onClose) {
|
||||
if (urls.isNotEmpty()) {
|
||||
Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
/* ---------- 自己输网址(永远在最上面,入口要显眼)---------- */
|
||||
item {
|
||||
Column {
|
||||
Text("输入网址", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
singleLine = true,
|
||||
placeholder = { Text("example.com", fontSize = 14.sp) },
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 15.sp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
androidx.compose.material3.Button(
|
||||
onClick = { onPick(typed) },
|
||||
enabled = typed.isNotBlank(),
|
||||
) { Text("打开") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 这条回复里找到的链接 ---------- */
|
||||
if (urls.isNotEmpty()) {
|
||||
item {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// ★ 一定要写 ${owner} 而不是 $owner:紧跟中文时 Kotlin 会把
|
||||
// 后面那几个汉字当成变量名的一部分(`$owner里提到的网页` 会
|
||||
// 被解析成一个叫「owner里提到的网页」的标识符,报未解析引用)。
|
||||
Text("${owner}里提到的网页:", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
items(urls.size) { index ->
|
||||
val u = urls[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onPick(u.url) }
|
||||
.padding(horizontal = 14.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
/**
|
||||
* ★ 主标题优先用**模型给链接写的文字**。
|
||||
*
|
||||
* 以前只显示 host,于是同一域名的两条链接
|
||||
* (`https://example.com` 和
|
||||
* `https://example.com/index-zh`)
|
||||
* 看起来**一模一样**,用户根本分不出该点哪个。
|
||||
* 模型的链接文字就是为了区分它们而写的。
|
||||
*/
|
||||
Text(
|
||||
u.label.ifBlank { hostOf(u.url) },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
u.url,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
370
android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt
Normal file
370
android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt
Normal file
@@ -0,0 +1,370 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★★★ 在**真实网页**上点选,把点到的内容回传给 AI。
|
||||
*
|
||||
* ## 为什么不用 `@JavascriptInterface` 桥
|
||||
*
|
||||
* `show_ui` 那个界面里我们挂了 `Doubao` 桥,但那只挂在**我们自己注入的那一页**上,
|
||||
* 一导航到外部站点就摘掉了(见 [AiWebView] 的注释)。
|
||||
*
|
||||
* 这里不同:**用户就是在浏览外部网站**,全程都在别人的页面上。
|
||||
* 要是挂桥,等于把 App 的内部接口暴露给互联网上任意一个站点 —— 绝对不能这么干。
|
||||
*
|
||||
* ## 改用"单向队列 + 主动轮询"
|
||||
*
|
||||
* ```
|
||||
* 注入的脚本(页面里) Kotlin 侧
|
||||
* ──────────────────── ──────────────
|
||||
* 用户点了 → 写进 window.__doubaoPicks
|
||||
* setInterval 每 500ms
|
||||
* evaluateJavascript("取走队列")
|
||||
* ← 拿到 JSON
|
||||
* ```
|
||||
*
|
||||
* 数据**只从页面流向 App**,而且只有这一个取数入口(`evaluateJavascript`)。
|
||||
* 页面**没有任何办法**主动调用 App —— 它只能往一个数组里塞东西,
|
||||
* 而那个数组的内容是我们主动去读的、并且读之前会做类型和长度校验。
|
||||
*
|
||||
* ★ 注意 `evaluateJavascript` 的返回值经 JSON 编码,所以脚本里用
|
||||
* `JSON.stringify(...)` 返回**字符串**,Kotlin 这边再解一层。
|
||||
* (这个坑在 [AiWebView] 那边也踩过。)
|
||||
*/
|
||||
object WebPick {
|
||||
|
||||
/** 队列变量名。用不常见的名字,尽量不和页面自己的变量撞。 */
|
||||
private const val QUEUE = "__doubaoPicks"
|
||||
|
||||
/**
|
||||
* 注入的脚本。
|
||||
*
|
||||
* 做三件事:
|
||||
* 1. 给页面上**真正的链接/按钮**加虚线高亮(视觉提示)
|
||||
* 2. 捕获点击(**捕获阶段**,抢在页面自己的 handler 前面)
|
||||
* 3. 把点到的元素信息写进队列,并阻止这次跳转
|
||||
*
|
||||
* ★★ 改过一版:从"只能点可点元素"改成"**点哪儿抓哪儿**"。
|
||||
*
|
||||
* 第一版只给 `a,button,[role=button],...` 这些**看着能点**的元素加框,
|
||||
* 点击也只认这些。实测在 example.com 上**一个都标不出来** ——
|
||||
* 那页全是纯文本,没有任何按钮链接,于是"点选模式"看起来完全没生效。
|
||||
*
|
||||
* 我的假设错了:用户想点的不一定是"可点元素",他想点的就是
|
||||
* **页面上任意一段内容**("把这段告诉 AI")。
|
||||
* 所以现在点击用 `elementFromPoint` 抓,**点哪儿抓哪儿**;
|
||||
* 虚线框降级成纯视觉提示,不再限制能点什么。
|
||||
*
|
||||
* ★ 为什么用捕获阶段 + `preventDefault`:
|
||||
* 如果一个链接上挂着页面的点击统计脚本,冒泡阶段再加我们的监听就晚了。
|
||||
* 捕获阶段先拿到,`stopPropagation` 之后页面完全不知道被点过,
|
||||
* 也就不会跳走 —— 用户点一下是"选中",不是"跳转"。
|
||||
*
|
||||
* ★ 用 IIFE 包起来 + 可重复注入(先看有没有装过):
|
||||
* 每次页面加载完都会注入一遍,不防重会叠出好几层监听,
|
||||
* 一次点击写好几条重复记录。
|
||||
*/
|
||||
val INSTALL_JS: String = """
|
||||
(function () {
|
||||
if (window.__doubaoPickInstalled) { return '1'; }
|
||||
window.__doubaoPickInstalled = 1;
|
||||
window.$QUEUE = [];
|
||||
|
||||
// 只用来**画虚线框**(提示哪些是链接/按钮)。点击不受它限制。
|
||||
var HINT_SEL = 'a,button,[role=button],input,select,textarea,label,summary';
|
||||
|
||||
function visible(el) {
|
||||
if (!el || !el.getBoundingClientRect) { return false; }
|
||||
var r = el.getBoundingClientRect();
|
||||
if (r.width < 8 || r.height < 8) { return false; }
|
||||
var s = window.getComputedStyle(el);
|
||||
return s.display !== 'none' && s.visibility !== 'hidden' && s.opacity !== '0';
|
||||
}
|
||||
|
||||
function textOf(el) {
|
||||
var t = (el.innerText || el.textContent || el.value || el.getAttribute('aria-label')
|
||||
|| el.getAttribute('title') || el.getAttribute('placeholder') || '');
|
||||
t = t.replace(/\s+/g, ' ').trim();
|
||||
return t.slice(0, 300);
|
||||
}
|
||||
|
||||
function mark() {
|
||||
var list = document.querySelectorAll(HINT_SEL);
|
||||
for (var i = 0; i < list.length && i < 400; i++) {
|
||||
var el = list[i];
|
||||
if (el.__doubaoMarked || !visible(el)) { continue; }
|
||||
el.__doubaoMarked = 1;
|
||||
el.style.outline = '2px dashed rgba(76,141,255,.75)';
|
||||
el.style.outlineOffset = '1px';
|
||||
el.style.cursor = 'pointer';
|
||||
}
|
||||
return list.length;
|
||||
}
|
||||
|
||||
function onClick(e) {
|
||||
// ★★ 点哪儿抓哪儿:优先用坐标取元素,**不要求它"看起来能点"**。
|
||||
//
|
||||
// 第一版是"从 e.target 往上找最近的可点元素",找不到就退回 e.target ——
|
||||
// 在纯文本页面上用户点一段话,抓到的是最里层的 <b>/<span>,
|
||||
// 甚至可能是个没文字的容器。用坐标取到的是**用户真正看到的那个块**。
|
||||
var el = null;
|
||||
try {
|
||||
if (e.clientX || e.clientY) {
|
||||
el = document.elementFromPoint(e.clientX, e.clientY);
|
||||
}
|
||||
} catch (err) { el = null; }
|
||||
if (!el) { el = e.target; }
|
||||
|
||||
// 取到的可能是很里层的小元素(一个 <b>、一个 <span>)。
|
||||
// 往上走几层,让选中的是"一整段有意义的内容"而不是一个词。
|
||||
var hop = 0;
|
||||
while (el && el.parentElement && hop < 3) {
|
||||
var t = (el.innerText || el.textContent || '').trim();
|
||||
// 文字够多就停 —— 说明这一层已经是个完整段落了
|
||||
if (t.length >= 12) { break; }
|
||||
// 或者这一层本身就是链接/按钮,那也停(点链接当然要抓链接)
|
||||
if (el.matches && el.matches(HINT_SEL)) { break; }
|
||||
el = el.parentElement; hop++;
|
||||
}
|
||||
if (!el || el === document.documentElement) { el = e.target; }
|
||||
|
||||
var rec = {
|
||||
tag: (el.tagName || '').toLowerCase(),
|
||||
text: textOf(el),
|
||||
href: el.href || '',
|
||||
id: el.id || '',
|
||||
cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120),
|
||||
path: (function () {
|
||||
var p = [], n = el, d = 0;
|
||||
while (n && n.tagName && d < 4) {
|
||||
var s = n.tagName.toLowerCase();
|
||||
if (n.id) { s += '#' + n.id; }
|
||||
else if (typeof n.className === 'string' && n.className) {
|
||||
s += '.' + n.className.trim().split(/\s+/).slice(0, 2).join('.');
|
||||
}
|
||||
p.unshift(s); n = n.parentElement; d++;
|
||||
}
|
||||
return p.join(' > ');
|
||||
})(),
|
||||
title: document.title || '',
|
||||
url: location.href || '',
|
||||
kind: 'click'
|
||||
};
|
||||
window.$QUEUE.push(rec);
|
||||
|
||||
// 选中效果:给点到的那个元素一个实线高亮,然后褪成虚线
|
||||
try {
|
||||
el.style.outline = '3px solid #4c8dff';
|
||||
setTimeout(function () { el.style.outline = '2px dashed rgba(76,141,255,.75)'; }, 700);
|
||||
} catch (err) {}
|
||||
|
||||
// ★ 关键:拦掉这次点击 —— 用户是"选中"不是"跳转"。
|
||||
// 不拦的话点个链接页面就跳走了,用户根本来不及看"已选中"提示。
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户**写了什么** —— 表单输入 / 下拉选择 / 勾选框。
|
||||
*
|
||||
* ★ 用户明确要求"让 AI 知道用户选择了什么、**写了什么**"。
|
||||
* 光有"点了什么"不够:填表场景里真正重要的是填进去的内容。
|
||||
*
|
||||
* ★ 用 input/change 的**冒泡阶段**(不用捕获):这类事件页面自己也要处理
|
||||
* (自动补全、字数统计),拦掉会破坏页面功能。我们只是**旁听**,不干预。
|
||||
*
|
||||
* ★ 同一个输入框连续打字会触发很多次 input —— 每 600ms 合并一次,
|
||||
* 否则用户打十个字会往队列里塞十条,报告变得没法看。
|
||||
*/
|
||||
var pending = {};
|
||||
function labelOf(el) {
|
||||
var s = el.getAttribute('aria-label') || el.getAttribute('placeholder')
|
||||
|| el.getAttribute('name') || el.id || '';
|
||||
if (!s) {
|
||||
var lab = el.closest ? el.closest('label') : null;
|
||||
if (lab) { s = (lab.innerText || '').trim().slice(0, 60); }
|
||||
}
|
||||
if (!s && el.previousElementSibling) {
|
||||
s = (el.previousElementSibling.innerText || '').trim().slice(0, 60);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function flush(key) {
|
||||
var el = pending[key];
|
||||
if (!el) { return; }
|
||||
delete pending[key];
|
||||
var val = '';
|
||||
if (el.type === 'checkbox' || el.type === 'radio') { val = el.checked ? '已勾选' : '未勾选'; }
|
||||
else { val = (el.value || '').slice(0, 500); }
|
||||
if (!val) { return; }
|
||||
window.$QUEUE.push({
|
||||
kind: 'input',
|
||||
tag: (el.tagName || '').toLowerCase(),
|
||||
type: el.type || '',
|
||||
label: labelOf(el),
|
||||
text: val,
|
||||
href: '',
|
||||
id: el.id || '',
|
||||
cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120),
|
||||
path: '',
|
||||
title: document.title || '',
|
||||
url: location.href || ''
|
||||
});
|
||||
}
|
||||
|
||||
function onInput(e) {
|
||||
var el = e.target;
|
||||
if (!el || !el.tagName) { return; }
|
||||
var t = (el.tagName || '').toLowerCase();
|
||||
if (t !== 'input' && t !== 'textarea' && t !== 'select') { return; }
|
||||
var key = (el.id || '') + '|' + (el.name || '') + '|' +
|
||||
(el.getAttribute('placeholder') || '') + '|' + (el.type || '');
|
||||
pending[key] = el;
|
||||
if (el.__doubaoDebounce) { clearTimeout(el.__doubaoDebounce); }
|
||||
el.__doubaoDebounce = setTimeout(function () { flush(key); }, 600);
|
||||
}
|
||||
|
||||
document.addEventListener('input', onInput, false);
|
||||
document.addEventListener('change', onInput, false);
|
||||
// 失焦时立刻结算(用户填完就去点别的地方了,不等那 600ms)
|
||||
document.addEventListener('blur', function (e) {
|
||||
var el = e.target;
|
||||
if (!el || !el.tagName) { return; }
|
||||
var key = (el.id || '') + '|' + (el.name || '') + '|' +
|
||||
(el.getAttribute('placeholder') || '') + '|' + (el.type || '');
|
||||
flush(key);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('click', onClick, true);
|
||||
|
||||
// 动态加载的页面(下拉刷新、无限滚动)也要能点 —— 隔一会儿重新标一次
|
||||
var ticks = 0;
|
||||
var timer = setInterval(function () {
|
||||
mark(); ticks++;
|
||||
if (ticks > 40) { clearInterval(timer); }
|
||||
}, 1500);
|
||||
|
||||
mark();
|
||||
return '1';
|
||||
})()
|
||||
"""
|
||||
|
||||
/**
|
||||
* 取走队列(取完清空)。
|
||||
*
|
||||
* ★ 一定要"取走"而不是"读":读的话每次轮询都会把同一条记录
|
||||
* 重复报上来,用户点一下会触发十几次。
|
||||
*/
|
||||
val DRAIN_JS: String = """
|
||||
(function () {
|
||||
try {
|
||||
var q = window.$QUEUE || [];
|
||||
window.$QUEUE = [];
|
||||
return JSON.stringify(q.slice(0, 20));
|
||||
} catch (e) { return '[]'; }
|
||||
})()
|
||||
"""
|
||||
|
||||
/** 撤销高亮 + 拆掉监听(退出点选模式时调) */
|
||||
val UNINSTALL_JS: String = """
|
||||
(function () {
|
||||
try {
|
||||
window.__doubaoPickInstalled = 0;
|
||||
window.$QUEUE = [];
|
||||
var list = document.querySelectorAll('[style]');
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var el = list[i];
|
||||
if (el.__doubaoMarked) {
|
||||
el.style.outline = '';
|
||||
el.style.outlineOffset = '';
|
||||
el.style.cursor = '';
|
||||
el.__doubaoMarked = 0;
|
||||
}
|
||||
}
|
||||
return '1';
|
||||
} catch (e) { return '0'; }
|
||||
})()
|
||||
"""
|
||||
|
||||
/**
|
||||
* 把一条记录整理成给模型看的一行字。
|
||||
*
|
||||
* ★ 刻意做成**紧凑的一行**,而不是把整个 JSON 丢给模型:
|
||||
* 模型需要的是"用户干了什么",不是 DOM 的所有细节。
|
||||
* 附带页面标题和 URL,帮它知道用户在哪个页面操作的。
|
||||
*
|
||||
* ★ 分两种 `kind`:
|
||||
* · `click` —— 用户**点了/选了**一个元素(链接、按钮、一段文字)
|
||||
* · `input` —— 用户**写了**内容(输入框、下拉、勾选框)
|
||||
* 用户的原话是"让 AI 知道用户选择了什么、写了什么",就是这两类。
|
||||
*/
|
||||
fun describe(json: JSONObject): String {
|
||||
val parts = mutableListOf<String>()
|
||||
val kind = json.optString("kind", "click")
|
||||
val text = json.optString("text").trim()
|
||||
val tag = json.optString("tag")
|
||||
val type = json.optString("type")
|
||||
val label = json.optString("label").trim()
|
||||
val href = json.optString("href")
|
||||
val id = json.optString("id")
|
||||
val path = json.optString("path")
|
||||
|
||||
if (kind == "input") {
|
||||
val what = if (type == "checkbox" || type == "radio") "勾选" else "填写"
|
||||
parts.add("用户$what:${text.ifEmpty { "(空)" }}")
|
||||
if (label.isNotEmpty()) parts.add("字段:$label")
|
||||
parts.add("控件:<$tag" + (if (type.isNotEmpty()) " type=$type" else "") + ">")
|
||||
} else {
|
||||
if (text.isNotEmpty()) parts.add("内容:$text")
|
||||
parts.add("元素:<$tag>" + (if (id.isNotEmpty()) " #$id" else ""))
|
||||
if (href.isNotEmpty()) parts.add("链接:$href")
|
||||
if (path.isNotEmpty()) parts.add("位置:$path")
|
||||
}
|
||||
return parts.joinToString(";")
|
||||
}
|
||||
|
||||
/**
|
||||
* 把多条记录汇总成一段给模型的话。
|
||||
*
|
||||
* ★ 一次性发送多条(而不是点一条发一条):
|
||||
* 用户可能在页面上选了好几处、填了几个框,然后一起问"这些对不对"。
|
||||
* 分开发会触发好几轮模型调用,既慢又费 token。
|
||||
*/
|
||||
fun buildReport(items: List<PickedElement>): String = buildString {
|
||||
append("我在网页上")
|
||||
val clicks = items.count { it.kind != "input" }
|
||||
val inputs = items.count { it.kind == "input" }
|
||||
val bits = mutableListOf<String>()
|
||||
if (clicks > 0) bits.add("选了 $clicks 处")
|
||||
if (inputs > 0) bits.add("填了 $inputs 处")
|
||||
append(bits.joinToString("、").ifEmpty { "选了一些东西" })
|
||||
append(":\n")
|
||||
items.forEachIndexed { i, it ->
|
||||
append("${i + 1}. ${it.summary}\n")
|
||||
}
|
||||
val first = items.firstOrNull()
|
||||
if (first != null && first.url.isNotBlank()) append("\n页面:${first.url}")
|
||||
if (first != null && first.pageTitle.isNotBlank()) append("\n标题:${first.pageTitle}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 点选模式下用户选中/填写、但**还没决定要不要发给 AI** 的那一条。
|
||||
*
|
||||
* ★ 为什么要中间这一步(而不是点了就直接发):
|
||||
* 用户可能点错了元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而且模型会基于一个错误的前提回答。让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持累积多条:用户可以连着点好几处、填几个框,最后一起发。
|
||||
*/
|
||||
data class PickedElement(
|
||||
val summary: String,
|
||||
/** click / input —— 是"点了什么"还是"写了什么" */
|
||||
val kind: String,
|
||||
val url: String,
|
||||
val pageTitle: String,
|
||||
val raw: String,
|
||||
)
|
||||
@@ -55,6 +55,19 @@ UI_TOOLS_HINT = '\n'.join([
|
||||
'界面能力(用户已打开):',
|
||||
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||||
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||||
' 界面**支持 JavaScript**(canvas 画图、动态渲染都行)。',
|
||||
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
||||
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
||||
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
||||
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||||
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||||
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||||
' · wait=true = **等用户点一个回传按钮或关掉界面**(最多 timeout 秒,默认 120)。',
|
||||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。',
|
||||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||||
@@ -64,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:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
@@ -74,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、其它走方舟"只改那一个智能体。
|
||||
@@ -108,6 +124,37 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
convo = []
|
||||
if system_prompt.strip():
|
||||
convo.append({'role': 'system', 'content': system_prompt})
|
||||
|
||||
# ★★★ AI 界面的**数据回流**在这里进上下文。
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 里可以调 `Doubao.sendToAi(值)`,
|
||||
# 安卓桥把它 POST 到 /api/ui-result 排队;这里取走并作为
|
||||
# **一条 system 消息**插在历史前面。
|
||||
#
|
||||
# ★ 为什么是 system 而不是 user:
|
||||
# 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,
|
||||
# 而且用户点"重新生成"时会和真正那条用户消息混在一起。
|
||||
# system 的语义就是"背景信息",正合适。
|
||||
#
|
||||
# ★ 为什么要**取走**:不取走的话这轮用、下轮还用,
|
||||
# 模型会反复提同一件事,用户会以为它卡住了。
|
||||
#
|
||||
# ★ 为什么放在 messages **之前**:它是"用户接下来这句话的前提",
|
||||
# 要让模型先看到"用户在界面上选了什么",再读用户那句话。
|
||||
ui_results = store.take_pending_ui(conversation_id) if conversation_id else []
|
||||
if ui_results:
|
||||
lines = '\n'.join(f'- {v}' for v in ui_results)
|
||||
convo.append({
|
||||
'role': 'system',
|
||||
'content': (
|
||||
'用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):\n'
|
||||
f'{lines}\n'
|
||||
'请结合这些信息回答用户接下来的话;如果用户还没说话,就针对这些选择给出回应。'
|
||||
),
|
||||
})
|
||||
# 也让界面知道模型收到了 —— 前端可以据此显示"AI 已收到你的选择"
|
||||
emit({'type': 'ui_results', 'count': len(ui_results)})
|
||||
|
||||
convo.extend(messages)
|
||||
|
||||
answer = ''
|
||||
@@ -187,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -665,6 +667,203 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if pathname == '/api/conversations' and method == 'GET':
|
||||
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
|
||||
|
||||
# ---- 笔记(用户要能查看)----
|
||||
#
|
||||
# ★ 用户的原话:"notes 用户要能查看"。
|
||||
# 以前笔记只有 AI 能读写(走 notes 工具),用户看不到 ——
|
||||
# 而且路径算错落到了 App 外部私有目录,卸载还会被清掉。
|
||||
# 现在存 `<数据目录>/notes`,这几个接口让 App 列出来看。
|
||||
if pathname == '/api/notes' and method == 'GET':
|
||||
self.send_json(200, {'notes': store.list_notes()})
|
||||
return True
|
||||
|
||||
note_name = self._match_id(pathname, '/api/notes/')
|
||||
if note_name is not None:
|
||||
if method == 'GET':
|
||||
note = store.read_note(note_name)
|
||||
if note is None:
|
||||
self.send_json(404, {'error': '笔记不存在'})
|
||||
else:
|
||||
self.send_json(200, note)
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
ok = store.delete_note(note_name)
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---- AI 弹过的界面(关掉之后还能再打开)----
|
||||
#
|
||||
# ★ 用户要求:"AI 写的界面可以再点开"。
|
||||
# 每次 show_ui 都把 HTML 存一份到 <data>/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 自己写进网页里的接口"的落点。
|
||||
#
|
||||
# AI 用 show_ui 弹一个 HTML 界面,界面里可以写:
|
||||
# Doubao.sendToAi("用户选的是方案 B")
|
||||
# 那个值经安卓桥打到这里,**排队等下一次对话**。
|
||||
# 下一轮 run_agent 会把队里的东西作为上下文交给模型 ——
|
||||
# 于是"用户在 AI 自己写的界面里选了什么"真的回到了模型手里。
|
||||
#
|
||||
# ★ 为什么用"排队"而不是"直接起一轮对话":
|
||||
# 用户可能连点几下、或者在界面里选好几项再确认。
|
||||
# 每点一下就跑一轮模型既慢又费 token,而且用户还没说完。
|
||||
# 排队 → 用户下一次说话(或点界面上的提交按钮)时一起带上,
|
||||
# 语义上也更对:**界面是提问的一部分,不是提问本身**。
|
||||
if pathname == '/api/ui-result' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
conv = str(body.get('conversationId') or '')
|
||||
value = str(body.get('value') or '').strip()
|
||||
if not value:
|
||||
self.send_json(400, {'error': 'value 不能为空'})
|
||||
return True
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
n = store.add_pending_ui(conv, value)
|
||||
self.send_json(200, {'ok': True, 'queued': n})
|
||||
return True
|
||||
|
||||
if pathname == '/api/ui-result' and method == 'GET':
|
||||
parsed = urlsplit(self.path)
|
||||
params = dict(
|
||||
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||||
)
|
||||
conv = unquote(params.get('conversationId') or '')
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
self.send_json(200, {'pending': store.peek_pending_ui(conv)})
|
||||
return True
|
||||
|
||||
if pathname == '/api/conversations' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
@@ -1366,7 +1565,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:
|
||||
@@ -1420,6 +1619,8 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
# end_conversation 会明确报错(而不是假装成功)。
|
||||
conversation_id=conversation_id,
|
||||
# ★ 防无限套娃:这一轮的深度传进去,send_message 据此判断能不能再发
|
||||
send_depth=send_depth,
|
||||
)
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
@@ -33,6 +34,12 @@ BUNDLED_TOOL_FILES = [
|
||||
'show_ui.py',
|
||||
'ask_user.py',
|
||||
'end_conversation.py',
|
||||
# AI 主动往当前会话里发一条消息(带防死循环的闸,见 app.py /api/session-message)
|
||||
'send_message.py',
|
||||
# 操作手机:读通知 / 开 App / 调音量
|
||||
'notifications.py',
|
||||
'apps.py',
|
||||
'volume.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
@@ -263,37 +270,130 @@ def _module_source(name: str):
|
||||
return None
|
||||
|
||||
|
||||
def _src_hash(text: str) -> str:
|
||||
"""源码指纹前 16 位(够用,还短)"""
|
||||
return hashlib.sha256(text.encode('utf-8')).hexdigest()[:16]
|
||||
|
||||
|
||||
def _seed_tools(tools_dir: str) -> int:
|
||||
"""
|
||||
首次运行把内置工具写到手机上的可写目录。
|
||||
之后用户就能自己改、自己加(设置里的"工具目录"指向这里)。
|
||||
把内置工具写到手机上的可写目录。之后用户就能自己改、自己加
|
||||
(设置里的"工具目录"指向这里)。
|
||||
|
||||
源码来源优先级:
|
||||
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||||
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||||
2) 直接从模块读源码 —— 电脑上跑时用这条
|
||||
|
||||
## ★★★ 升级时会重新播种(这是修的一个真 bug)
|
||||
|
||||
以前这里是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
|
||||
后果:**每一次发版更新的内置工具,在老设备上一律不生效**。
|
||||
|
||||
这个 bug 的表现极具误导性:代码明明改了、APK 明明是新编的、
|
||||
`app.imy` 里也确实有新的 .pyc,但设备上跑的还是几个月前那份 ——
|
||||
因为内核加载的是**落盘的那份旧源码**。
|
||||
实测踩到:v2.0.37 加了 `show_ui` 的 `wait` 参数,设备上报的 spec 里
|
||||
根本没有这个参数,我一度以为是构建没生效。
|
||||
|
||||
## 怎么判断该不该覆盖 —— 这是这一版真正修对的地方
|
||||
|
||||
先看第一版(错的):只看一个本地指纹文件 `.doubao-seed.json`。
|
||||
|
||||
· 指纹对得上 → 我们写的 → 可以覆盖
|
||||
· 对不上 → 用户改过 → 不覆盖
|
||||
|
||||
**但老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
|
||||
于是所有文件都被判成"用户改过",**升级永远不生效**。
|
||||
实测 v2.0.37 给 show_ui 加了 `wait` 参数,真机上死活拿不到 ——
|
||||
12 个没改过的文件"内容相同"跳过,唯一改过的 show_ui 被判成用户改的。
|
||||
|
||||
第二版(现在):加一份**构建时累积的"历史版本哈希登记表"**
|
||||
(`tools/.shipped-hashes.json`,打包时嵌进 `bundled_tool_sources.shipped()`)。
|
||||
判断顺序:
|
||||
|
||||
1. 内容和我们这一版一样 → 什么都不做
|
||||
2. 内容**在历史登记表里** → 是我们以前发的某个版本 → **安全覆盖**
|
||||
3. 内容等于我们本地指纹记的 → 是我们写的 → **安全覆盖**
|
||||
4. 都不是 → 用户改过 → **绝不覆盖**
|
||||
|
||||
第 2 条是关键:它让"老设备上那份我们几个月前发的旧源码"能被认出来。
|
||||
没有它就只能靠"指纹文件",而老设备上那个是空的。
|
||||
"""
|
||||
os.makedirs(tools_dir, exist_ok=True)
|
||||
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||||
|
||||
shipped: dict = {}
|
||||
try:
|
||||
import bundled_tool_sources # type: ignore[import-not-found]
|
||||
|
||||
for name, source in bundled_tool_sources.sources().items():
|
||||
wanted[name] = source
|
||||
# ★ 历史版本哈希表:靠它认出"盘上这份是我们以前发的"
|
||||
try:
|
||||
shipped = bundled_tool_sources.shipped()
|
||||
except Exception: # noqa: BLE001 - 老版本生成的文件里没有这个函数
|
||||
shipped = {}
|
||||
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||||
pass
|
||||
|
||||
# 读上次写下的指纹
|
||||
stamp_path = os.path.join(tools_dir, '.doubao-seed.json')
|
||||
seeded: dict = {}
|
||||
try:
|
||||
with open(stamp_path, encoding='utf-8') as fh:
|
||||
loaded = json.load(fh)
|
||||
if isinstance(loaded, dict):
|
||||
seeded = loaded
|
||||
except Exception: # noqa: BLE001 - 没有/坏了都当第一版处理
|
||||
seeded = {}
|
||||
|
||||
copied = 0
|
||||
skipped_user = 0
|
||||
for filename, source in wanted.items():
|
||||
if not source:
|
||||
continue
|
||||
dest = os.path.join(tools_dir, filename)
|
||||
new_hash = _src_hash(source)
|
||||
|
||||
if os.path.exists(dest):
|
||||
continue
|
||||
with open(dest, 'w', encoding='utf-8') as fh:
|
||||
fh.write(source)
|
||||
copied += 1
|
||||
try:
|
||||
with open(dest, encoding='utf-8') as fh:
|
||||
current = fh.read()
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
cur_hash = _src_hash(current)
|
||||
if cur_hash == new_hash:
|
||||
# 已经是这一版了。**顺手把指纹补上** ——
|
||||
# 老设备上指纹是空的,不补的话下次还会走"用户改过"那条。
|
||||
seeded[filename] = cur_hash
|
||||
continue
|
||||
# 是我们以前发的某个版本?→ 可以覆盖
|
||||
ours_history = cur_hash in (shipped.get(filename) or [])
|
||||
ours_stamp = seeded.get(filename) == cur_hash
|
||||
if not ours_history and not ours_stamp:
|
||||
# 用户自己改过 —— 不覆盖。留个日志方便排查
|
||||
skipped_user += 1
|
||||
print(f'[tools] {filename} 被用户改过,保留不覆盖', file=sys.stderr, flush=True)
|
||||
continue
|
||||
# 没改过,且我们的版本变了 → 覆盖
|
||||
try:
|
||||
with open(dest, 'w', encoding='utf-8') as fh:
|
||||
fh.write(source)
|
||||
seeded[filename] = new_hash
|
||||
copied += 1
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[tools] 写 {filename} 失败:{exc}', file=sys.stderr, flush=True)
|
||||
|
||||
if copied or skipped_user:
|
||||
print(f'[tools] 播种:更新 {copied} 个,保留用户改过的 {skipped_user} 个',
|
||||
file=sys.stderr, flush=True)
|
||||
|
||||
try:
|
||||
with open(stamp_path, 'w', encoding='utf-8') as fh:
|
||||
json.dump(seeded, fh, ensure_ascii=False, indent=2)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return copied
|
||||
|
||||
|
||||
|
||||
@@ -70,6 +70,18 @@ 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')
|
||||
# ★ notes 工具的笔记存这儿("notes 用户要能查看")。
|
||||
#
|
||||
# 以前 notes.py 自己算路径:`工具文件/../data/notes` ——
|
||||
# 在安卓上会落到 **App 的外部私有目录**
|
||||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)。
|
||||
# 那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
|
||||
# 而且**卸载 App 就一起删了**。
|
||||
# 放到 data_dir 下和别的数据一起,持久、位置统一、也能通过接口读出来给界面看。
|
||||
self.notes_dir = os.path.join(self.data_dir, 'notes')
|
||||
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 +102,8 @@ 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,
|
||||
self.notes_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
@@ -14,8 +14,10 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
@@ -162,6 +164,20 @@ def write_settings(patch: dict) -> dict:
|
||||
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
|
||||
if not isinstance(patch, dict):
|
||||
patch = {}
|
||||
# ★★ 显式的"清除"通路:值传 None 就是"我要把它清掉"。
|
||||
#
|
||||
# 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是
|
||||
# "前端草稿没初始化好,一次保存清空整份配置"),但代价是
|
||||
# **用户永远清不掉自定义 Base URL / 模型名** ——
|
||||
# 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||||
# (这是我在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认,
|
||||
# 传空串怎么也改不掉。)
|
||||
#
|
||||
# 所以给一条**显式**的路:传 null。空串仍然= "没填、别动",
|
||||
# null = "确实要清掉"。两者语义不同,前端可以按需选。
|
||||
explicit_clear = {k for k, v in patch.items() if v is None}
|
||||
for key in explicit_clear:
|
||||
patch.pop(key, None)
|
||||
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||||
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||||
@@ -171,6 +187,10 @@ def write_settings(patch: dict) -> dict:
|
||||
patch.pop(key)
|
||||
current = read_settings()
|
||||
nxt = {**current, **patch}
|
||||
# 显式清除的落到默认值上(不是留着旧值,也不是变成空 —— 空会让
|
||||
# "用哪个 provider 的默认 baseUrl"这套逻辑失效)
|
||||
for key in explicit_clear:
|
||||
nxt[key] = DEFAULT_SETTINGS.get(key, '')
|
||||
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||||
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
|
||||
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||
@@ -331,6 +351,387 @@ def list_conversations() -> list:
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 弹过的界面(HTML)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 用户要求:"AI 写的界面可以再点开" —— 关掉之后(甚至重启 App 之后)
|
||||
# 还能把它调出来。所以每次 show_ui 都存一份。
|
||||
#
|
||||
# 存法:
|
||||
# <data>/screens/<id>.html 正文
|
||||
# <data>/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)[^>]*>.*?</\1>', ' ', 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
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 笔记(notes 工具写的,用户要能查看)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 用户的原话:"notes 用户要能查看"。
|
||||
# 以前笔记只有 AI 能读写(走 notes 工具),用户在界面上看不到。
|
||||
#
|
||||
# ★ 目录是 `<数据目录>/notes`(`paths.get().notes_dir`)——
|
||||
# 以前 notes.py 自己算 `工具文件/../data/notes`,在安卓上落到
|
||||
# **App 外部私有目录**(用户翻不到、卸载还会被清掉)。
|
||||
# 那些老文件由 notes.py 里的 `_migrate_once` 自动搬过来。
|
||||
#
|
||||
# ★ 文件名格式:`20261015-151925-标题.md`。时间戳前缀让排序天然按时间倒序。
|
||||
NOTE_SUFFIX = '.md'
|
||||
|
||||
|
||||
def _notes_dir() -> str:
|
||||
d = paths.get().notes_dir
|
||||
os.makedirs(d, exist_ok=True)
|
||||
# ★ 顺手把老位置的笔记搬过来。
|
||||
#
|
||||
# 以前迁移只在 `notes` 工具被调用时才跑(notes.py 的 ensure_dir)。
|
||||
# 问题是:用户装了新版之后**先打开「笔记」页面**(而不是先让 AI 写笔记),
|
||||
# 那时迁移还没跑,他看到的是**空列表** —— 以为笔记全丢了。
|
||||
# 放在这里,任何一次读笔记都会先保证迁移过。
|
||||
_migrate_legacy_notes(d)
|
||||
return d
|
||||
|
||||
|
||||
# 老位置:工具文件旁边的 `../data/notes`。
|
||||
# 在安卓上那会落到 App 的**外部**私有目录
|
||||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)——
|
||||
# 用户用文件管理器翻不到(Android 11+ 直接隐藏),卸载还会一起删掉。
|
||||
def _legacy_notes_dirs() -> list:
|
||||
dirs = []
|
||||
try:
|
||||
# 工具目录的上一级 + /data/notes
|
||||
tools_dir = paths.get().tools_dir
|
||||
if tools_dir:
|
||||
dirs.append(os.path.join(os.path.dirname(tools_dir), 'data', 'notes'))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return [d for d in dirs if d and os.path.abspath(d) != os.path.abspath(paths.get().notes_dir)]
|
||||
|
||||
|
||||
def _migrate_legacy_notes(target: str) -> None:
|
||||
"""
|
||||
把老位置的笔记搬到新位置(只做一次)。
|
||||
|
||||
★ 为什么必须搬:用户在老版本里记的笔记是**真实数据** ——
|
||||
换了目录之后文件还在老地方躺着,但 list/read 都看不到,
|
||||
表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。
|
||||
"""
|
||||
marker = os.path.join(target, '.migrated')
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
moved = 0
|
||||
for legacy in _legacy_notes_dirs():
|
||||
if not os.path.isdir(legacy):
|
||||
continue
|
||||
try:
|
||||
names = os.listdir(legacy)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
for name in names:
|
||||
if not name.endswith(NOTE_SUFFIX):
|
||||
continue
|
||||
dst = os.path.join(target, name)
|
||||
if os.path.exists(dst):
|
||||
continue # 不覆盖同名的(新位置已有)
|
||||
src = os.path.join(legacy, name)
|
||||
try:
|
||||
shutil.move(src, dst)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
# 跨设备 move 可能失败,退回复制
|
||||
try:
|
||||
shutil.copy2(src, dst)
|
||||
os.remove(src)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
with open(marker, 'w', encoding='utf-8') as fh:
|
||||
fh.write('ok\n')
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if moved:
|
||||
print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def _note_path(name: str):
|
||||
"""把文件名解析成绝对路径;不合法(穿越/非 .md)返回 None"""
|
||||
if not name or not name.endswith(NOTE_SUFFIX):
|
||||
return None
|
||||
# ★ 防目录穿越:文件名必须是纯文件名,不能带路径分隔符
|
||||
if '/' in name or '\\' in name or '..' in name:
|
||||
return None
|
||||
return os.path.join(_notes_dir(), name)
|
||||
|
||||
|
||||
def _note_title(path: str, fallback: str) -> str:
|
||||
"""标题取正文第一行的 `# 标题`;读不到就用文件名兜底"""
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
first = fh.readline().strip().lstrip('#').strip()
|
||||
return first or fallback
|
||||
except Exception: # noqa: BLE001
|
||||
return fallback
|
||||
|
||||
|
||||
def _note_time(name: str) -> str:
|
||||
"""
|
||||
从文件名前缀 `20261015-151925` 解析出时间,转成 `2026-10-15T15:19:25`。
|
||||
|
||||
★ 解析不出来就返回空串(界面上不显示时间),**不要瞎猜** ——
|
||||
用户手改过文件名的情况是有的。
|
||||
"""
|
||||
m = re.match(r'^(\d{8})-(\d{6})-', name)
|
||||
if not m:
|
||||
return ''
|
||||
d, t = m.group(1), m.group(2)
|
||||
return f'{d[0:4]}-{d[4:6]}-{d[6:8]}T{t[0:2]}:{t[2:4]}:{t[4:6]}'
|
||||
|
||||
|
||||
def list_notes() -> list:
|
||||
"""列出所有笔记(按文件名倒序 = 按时间倒序)"""
|
||||
d = _notes_dir()
|
||||
try:
|
||||
names = sorted(os.listdir(d), reverse=True)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
out = []
|
||||
for name in names:
|
||||
if not name.endswith(NOTE_SUFFIX):
|
||||
continue
|
||||
full = os.path.join(d, name)
|
||||
try:
|
||||
size = os.path.getsize(full)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
# 预览 = 去掉标题行之后的头一段
|
||||
preview = ''
|
||||
try:
|
||||
with open(full, encoding='utf-8') as fh:
|
||||
body = fh.read()
|
||||
lines = [ln.strip() for ln in body.splitlines()]
|
||||
body_lines = [ln for ln in lines[1:] if ln]
|
||||
preview = ' '.join(body_lines)[:100]
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
out.append({
|
||||
'file': name,
|
||||
'title': _note_title(full, name),
|
||||
'bytes': size,
|
||||
'at': _note_time(name),
|
||||
'preview': preview,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def read_note(name: str):
|
||||
"""读一条笔记;不存在返回 None"""
|
||||
path = _note_path(name)
|
||||
if not path or not os.path.isfile(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
text = fh.read()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return {
|
||||
'file': name,
|
||||
'title': _note_title(path, name),
|
||||
'at': _note_time(name),
|
||||
'content': text,
|
||||
'bytes': len(text.encode('utf-8')),
|
||||
}
|
||||
|
||||
|
||||
def delete_note(name: str) -> bool:
|
||||
path = _note_path(name)
|
||||
if not path or not os.path.isfile(path):
|
||||
return False
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def get_conversation(conv_id: str):
|
||||
for conv in _load_conversations()['conversations']:
|
||||
if conv.get('id') == conv_id:
|
||||
@@ -338,6 +739,69 @@ def get_conversation(conv_id: str):
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 界面的数据回流
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 界面里可以调 `Doubao.sendToAi(值)`,
|
||||
# 那个值先落到这里排队,下一轮对话开始时被取走、当作上下文交给模型。
|
||||
#
|
||||
# ★ 为什么单独存一份、而不是直接写进会话的消息列表:
|
||||
# 写进消息列表的话它会**变成一条 user 消息** —— 用户会看到一条
|
||||
# 自己没打过的消息,而且它会被当成"用户说的话"进历史。
|
||||
# 语义上它更像**附件/上下文**,不是用户的一句话。
|
||||
# 所以单独排队,由 agent_loop 拼进这一轮的上下文里。
|
||||
#
|
||||
# ★ 为什么不落盘:这是**一次性的上下文**,跨重启没有意义
|
||||
# (用户重启 App 之后那个界面早就关了,界面的选择也就失效了)。
|
||||
# 放内存里,进程重启自然清空,正合适。
|
||||
_pending_ui: dict = {}
|
||||
_pending_ui_lock = threading.Lock()
|
||||
|
||||
# 每个会话最多排多少条 —— 用户在界面上乱点不能把内存堆满
|
||||
PENDING_UI_MAX = 20
|
||||
# 单条最长多少字符 —— 界面可能回传一大段文本
|
||||
PENDING_UI_ITEM_MAX = 4000
|
||||
|
||||
|
||||
def add_pending_ui(conv_id: str, value: str) -> int:
|
||||
"""把界面上回传的一个值排进队。返回队里现在有几条。"""
|
||||
text = (value or '').strip()[:PENDING_UI_ITEM_MAX]
|
||||
if not conv_id or not text:
|
||||
return len(_pending_ui.get(conv_id) or [])
|
||||
with _pending_ui_lock:
|
||||
box = _pending_ui.setdefault(conv_id, [])
|
||||
box.append(text)
|
||||
# 超了就丢**最旧的**:用户最新点的那次最相关
|
||||
while len(box) > PENDING_UI_MAX:
|
||||
box.pop(0)
|
||||
return len(box)
|
||||
|
||||
|
||||
def peek_pending_ui(conv_id: str) -> list:
|
||||
"""看一眼(不取走)—— 给调试用的 GET 接口"""
|
||||
with _pending_ui_lock:
|
||||
return list(_pending_ui.get(conv_id) or [])
|
||||
|
||||
|
||||
def take_pending_ui(conv_id: str) -> list:
|
||||
"""
|
||||
取走并清空。
|
||||
|
||||
★ 必须"取走":不取走的话每轮对话都会把同一条又带上,
|
||||
用户会看到模型反复提同一件事。
|
||||
"""
|
||||
with _pending_ui_lock:
|
||||
return list(_pending_ui.pop(conv_id, []) or [])
|
||||
|
||||
|
||||
def clear_pending_ui(conv_id: str) -> None:
|
||||
with _pending_ui_lock:
|
||||
_pending_ui.pop(conv_id, None)
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
|
||||
@@ -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 的形状。
|
||||
|
||||
439
docs/AI界面能力.md
Normal file
439
docs/AI界面能力.md
Normal file
@@ -0,0 +1,439 @@
|
||||
# AI 界面能力 —— 让 AI 弹界面、弹窗、结束对话
|
||||
|
||||
> 三个工具:`show_ui` / `ask_user` / `end_conversation`。
|
||||
> **默认关闭**,开关在「技能」页最上面那张卡片。
|
||||
|
||||
最后更新:v2.0.35
|
||||
|
||||
---
|
||||
|
||||
## 为什么要有这三个
|
||||
|
||||
对话是一来一回的文本。有些东西**用文字表达就是不如界面**:
|
||||
|
||||
- 一张算出来的图表 → 文字只能描述趋势
|
||||
- 一列宽对比表 → markdown 一宽就乱
|
||||
- "你要 A 还是 B" → 文字问完还得等用户打字,不如弹个按钮
|
||||
|
||||
而 `end_conversation` 解决的是另一个问题:**任务真的办完了**,
|
||||
继续聊下去只会兜圈子,得有个办法干净地收尾。
|
||||
|
||||
---
|
||||
|
||||
## 分工:一个不阻塞,一个阻塞
|
||||
|
||||
| 工具 | 阻不阻塞 | 为什么 |
|
||||
|---|---|---|
|
||||
| `show_ui` | **不阻塞** | 展示语义。用户可能盯着看很久,把内核线程占住没意义 |
|
||||
| `ask_user` | **阻塞**(最多 120s) | 问询语义。拿不到答案就没法继续 |
|
||||
| `end_conversation` | 立刻返回 | 它只改状态(落盘 + 界面收输入框) |
|
||||
|
||||
超时是**必须**的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
而 HTTP 是每请求一线程,挂一个少一个。
|
||||
|
||||
---
|
||||
|
||||
## show_ui:三种收尾方式(v2.0.38 起)
|
||||
|
||||
| 用法 | 行为 | 适合 |
|
||||
|---|---|---|
|
||||
| `wait` 不传(默认) | 弹出就返回,不等 | 图表、报告这类"给用户看"的 |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**,最多 `timeout` 秒(默认 120,上限 600) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| 不调用 | 纯文字回答 | —— |
|
||||
|
||||
等待模式下用户点的值**立刻**作为工具返回值给模型,**同一个回合里**就能接着处理:
|
||||
|
||||
```
|
||||
wait=true → 阻塞 9.3s → {"waited":true,"timeout":false,"value":"方案丙(JS)"}
|
||||
```
|
||||
|
||||
- 用户直接关掉界面(没点任何按钮)→ `value=""` + `closed=true`
|
||||
- 超时 → `timeout=true`,提示词里明确要求**别反复重弹**
|
||||
|
||||
### ★ 实现上的一个竞态
|
||||
|
||||
**先备好闩再弹界面**(`AiSurface.armScreenLatch()` 在 `showScreen` 之前调)。
|
||||
顺序反了的话:用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
`countDown()` 打在空闩上,然后我们才开始等 —— 直接等满超时。
|
||||
这类"用户比代码快"的问题在真机上很容易出现,纯逻辑推理发现不了。
|
||||
|
||||
### 按钮样式:必须做得不可能看不见
|
||||
|
||||
原来的 `.db-btn` 是 `#2a2d34` 暗底 + `#e8eaed` 字 ——
|
||||
**在深色主题下和普通段落长得一模一样**。用户的原话是"哪有按键"。
|
||||
|
||||
现在:整行宽、亮蓝底 + 白字、15px padding、16px 字号、按下有反馈,
|
||||
`!important` 压掉模型内联的样式(模型经常内联 `style="background:..."`
|
||||
把它盖掉)。普通 `<button>` 也给可见边框,但没那么抢眼。
|
||||
|
||||
提示词里也加了要求:**放按钮时要做明显,别用纯文字当按钮**。
|
||||
|
||||
---
|
||||
|
||||
## ★★★ 一个让所有工具更新都失效的 bug(v2.0.38 修)
|
||||
|
||||
这个坑比它表面看起来严重得多,完整记一遍。
|
||||
|
||||
### 现象
|
||||
|
||||
`_seed_tools` 是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
|
||||
后果:**每一次发版更新的内置工具,在老设备上一律拿不到。**
|
||||
|
||||
误导性在于:代码改了 ✓、APK 重编了 ✓、`app.imy` 里确实有新 `.pyc` ✓,
|
||||
但设备上跑的还是旧那份 —— 因为内核加载的是**落盘的那份旧源码**。
|
||||
实测 v2.0.37 给 `show_ui` 加了 `wait` 参数,设备上报的 spec 里根本没这个参数,
|
||||
我一度以为是 Gradle 构建缓存没生效。
|
||||
|
||||
**用户报的"按键点不了"根因就是这个**:他手机上是 v2.0.36 那份 `show_ui`,
|
||||
而回传按钮是 v2.0.37 才接通的。
|
||||
|
||||
### 修的过程里又踩了两个坑
|
||||
|
||||
**坑一**:第一版只看本地指纹文件 `.doubao-seed.json`。
|
||||
但**老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
|
||||
于是所有文件都被判成"用户改过",**升级还是永远不生效**。
|
||||
|
||||
把中间量全打出来才看清:
|
||||
|
||||
```
|
||||
summary: {"skip-same": 12, "skip-user-edited": 1}
|
||||
show_ui.py -> skip-user-edited | same=False
|
||||
```
|
||||
|
||||
12 个没改过的是"内容相同"跳过,唯一改过的 `show_ui` 被判成用户改的。
|
||||
|
||||
**坑二(先有鸡还是先有蛋)**:于是加了一份**构建时累积的历史哈希登记表**
|
||||
(`tools/.shipped-hashes.json`),靠它认出"盘上这份是我们以前发的某个版本"。
|
||||
但登记表是这次才开始记的 —— **设备上现存的旧哈希不在表里**,还是认不出来。
|
||||
所以补了 `scripts/backfill-shipped-hashes.py`:翻 git 历史,把每个工具文件
|
||||
**出现过的每一个版本**都算一遍哈希填进去。
|
||||
|
||||
回填后确认设备上那份(`show_ui.py` sha256 前 16 位 `1882a766fe0ee833`)
|
||||
在表里了。
|
||||
|
||||
### 最终的判断顺序(4 条)
|
||||
|
||||
1. 内容和这一版一样 → 什么都不做(**顺手补指纹** —— 老设备上指纹是空的,
|
||||
不补的话下次还会走"用户改过"那条)
|
||||
2. 内容在**历史登记表**里 → 是我们以前发过的 → **安全覆盖**
|
||||
3. 内容等于本地指纹记的 → 是我们写的 → **安全覆盖**
|
||||
4. 都不是 → **用户改过 → 绝不覆盖**
|
||||
|
||||
### 实测效果
|
||||
|
||||
| | 修之前 | 修之后 |
|
||||
|---|---|---|
|
||||
| 设备上 `show_ui.py` | 3883 字节,0 处 `wait` | **7439 字节,9 处 `wait`** |
|
||||
| spec 里的 `wait` 参数 | 没有 | 有 |
|
||||
| `.doubao-seed.json` | `{}` | 14 条记录 |
|
||||
|
||||
守门脚本:`scripts/verify-seed-tools.py`(8 节),
|
||||
专门包含"老设备场景(指纹空 + 盘上是旧版本)必须覆盖"和
|
||||
"盘上内容不在历史表里 → 不许覆盖"这两条。
|
||||
|
||||
---
|
||||
|
||||
## show_ui:模型写 HTML
|
||||
|
||||
```
|
||||
{ "html": "<h1>结果</h1><table>…</table>", "title": "分析报告", "full_html": false }
|
||||
```
|
||||
|
||||
### 只写片段就行
|
||||
|
||||
默认会套一层骨架(暗色主题、表格样式、代码块、`viewport`)。
|
||||
模型不用每次重复写这些 —— 既啰嗦又容易和 App 主题打架。
|
||||
|
||||
想完全控制就传 `full_html: true`,那时 `html` 必须是一份完整文档。
|
||||
|
||||
### 可点的按钮 / 回传值:**三条路都收**
|
||||
|
||||
```html
|
||||
<button onclick="Doubao.sendToAi('值')">文字</button> <!-- 推荐 -->
|
||||
<button onclick="Doubao.pick('值')">文字</button> <!-- 等价简写 -->
|
||||
<button data-doubao-result="值">文字</button> <!-- 不写 JS 也能用 -->
|
||||
```
|
||||
|
||||
前两条走 JS 桥;第三条走**纯字符串替换**(App 侧把 `data-doubao-result`
|
||||
改成 `doubao://pick?value=...`,由 `WebViewClient` 拦下来)——
|
||||
所以页面即使 JS 出错,第三条仍然能用。
|
||||
|
||||
### ★★★ 值真的会回到模型手里(v2.0.37 才接通)
|
||||
|
||||
**上一版这里是名不副实的**:`Doubao.pick` 只是"关掉界面 + 弹个提示",
|
||||
值根本没送到模型。现在是一条完整链路:
|
||||
|
||||
```
|
||||
AI 写的 HTML: Doubao.sendToAi('用户选了方案B')
|
||||
→ JS 桥 AiWebHost.sendToAi
|
||||
→ NativeBridge 的 ui_result action → POST /api/ui-result
|
||||
→ store 里排队(内存,一次性上下文,不落盘)
|
||||
→ 下一轮 run_agent 取走,作为一条 system 消息插在历史前面
|
||||
→ 模型看到"用户在界面上选了什么"
|
||||
```
|
||||
|
||||
几个刻意的决定:
|
||||
|
||||
| 决定 | 为什么 |
|
||||
|---|---|
|
||||
| **排队**而不是"点了就起一轮对话" | 用户可能连点几下、选好几项再确认。每点一下跑一轮模型又慢又费 token,而且用户还没说完。语义上界面上的选择是**提问的一部分,不是提问本身** |
|
||||
| 插成 **system** 而不是 user | 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,而且"重新生成"时会和真正那条用户消息混在一起 |
|
||||
| **取走**而不是"读" | 不取走的话每轮都带上同一条,模型会反复提同一件事 |
|
||||
| 提示语写"已记下,**下次**对话会告诉 AI" | 不写"已发送"——后者会让用户以为模型马上回话,然后干等 |
|
||||
| 不落盘 | 一次性的上下文,跨重启没意义(界面早关了,那个选择也就失效了) |
|
||||
|
||||
想要"选完**立刻**有回应"的语义,用 `ask_user`(它是阻塞的)。
|
||||
|
||||
### 实测证据
|
||||
|
||||
起一个假的 OpenAI 兼容服务,把内核指过去,直接读它收到的请求体:
|
||||
|
||||
```
|
||||
[system] 你是豆包,…
|
||||
[system] 用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):
|
||||
- 用户选了方案 B(蓝色按钮)
|
||||
- 用户填写了:预算 3000 元
|
||||
[user] 我刚才在界面上选了什么?
|
||||
```
|
||||
|
||||
脚本:`scripts/fake-openai.py` + `scripts/probe-ui-result-e2e.py`。
|
||||
|
||||
★ 假服务在**模拟器里**连宿主机,要用 `adb reverse tcp:18080 tcp:18080`。
|
||||
`10.0.2.2` 在 LDPlayer 上**不通**(假服务一个请求都收不到,
|
||||
很容易误判成"代码有问题"——我在这儿绕了一圈)。
|
||||
|
||||
### JS 与桥:按页面收口(v2.0.36 起)
|
||||
|
||||
用户要求支持 JS。开了之后模型能写 `<script>`:canvas 画图、按数据动态生成
|
||||
界面、算完再渲染 —— 这些纯 CSS 做不到。
|
||||
|
||||
**但开 JS 之后最大的风险不是 JS 本身**,而是 `addJavascriptInterface` 注入的
|
||||
那个桥:**它对之后加载的每一个页面都可见**。AI 页面里点个链接落到外部站点,
|
||||
那个站点的脚本就能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
|
||||
所以:
|
||||
|
||||
- 桥**只挂在 AI 那一页**(初始 load 之前挂,保证内联 `<script>` 能用)
|
||||
- 一导航到 http(s) **立刻摘掉** —— 实测外部页面里 `typeof Doubao === 'undefined'`
|
||||
- 返回 AI 页时**自动恢复**(否则"点进去再返回,按钮全失灵")
|
||||
- 桥只暴露 `pick` / `close` 两个方法,面越小越好
|
||||
- `allowFileAccess` / `allowContentAccess` / 混合内容依然全关
|
||||
|
||||
### ★★ 挂桥时序改了三版才对
|
||||
|
||||
这段只能用真机实测发现,把三版的失败记下来:
|
||||
|
||||
| 版本 | 做法 | 失败表现 |
|
||||
|---|---|---|
|
||||
| 一 | load 前挂,导航时摘 | 外部页面在 `onPageStarted` 摘桥**之前**有"已开始加载、桥还在"的窗口 |
|
||||
| 二 | 只在 `onPageFinished` 里判 url 才挂 | 页面报 `Doubao is not defined` —— **`onPageFinished` 的回调比页面内联 `<script>` 执行还晚** |
|
||||
| 三 | load 前挂 + 标志挡窗口 + 返回时用**页面标记变量**判 | ✓ |
|
||||
|
||||
第三版那个"用标记变量判"也是被逼出来的:**用 url 判会漏** ——
|
||||
从外部页 `goBack()` 回来时,`onPageFinished` 收到的 url 不是 `about:blank`,
|
||||
于是桥不重挂,表现是"点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
|
||||
做法:`evaluateJavascript` 里写一个 `window.__doubaoAiPage = 1` 并回读 ——
|
||||
如果标记在、而桥不在,说明这是我们那一页且桥被摘过,重挂。
|
||||
页面被换掉标记就没了,所以外部页面不会误判。
|
||||
|
||||
★ `evaluateJavascript` 的回调参数是**字符串**(返回值经 JSON 编码),
|
||||
按 Boolean 判的话条件永远不成立 —— 我也踩了这个。
|
||||
|
||||
### 链接能点进去
|
||||
|
||||
`http/https` 在 WebView 里直接打开(以前 `return true` 吃掉了),
|
||||
顶部自动出现「←」返回键;系统返回键也先回退网页、退不了才关界面。
|
||||
别的协议(`tel:` / `mailto:` / `intent:`)交给系统。
|
||||
|
||||
---
|
||||
|
||||
## 网页(真实网站,不是你写的)
|
||||
|
||||
回复里只要有链接,消息下方就有个 🌐 **「打开网页」** 按钮。
|
||||
点开是全屏网页界面,顶部 后退/前进/刷新/用系统浏览器打开。
|
||||
|
||||
> 用户的原话是"你要单独开个按钮" —— 对。把链接做成蓝色下划线**没有可发现性**:
|
||||
> 用户不知道它能点、也不知道点了会发生什么。产品上正确的就是给个按钮。
|
||||
|
||||
### 点选:在真实网页上点内容带回给 AI
|
||||
|
||||
顶部一条「点选」横条(做成常驻横条而不是一个图标 —— 这能力不看说明发现不了)。
|
||||
打开后:
|
||||
|
||||
- 在页面上**点任意内容**(不只是链接按钮),内容会被记下来
|
||||
- 在表单里**填的字**也会被记下来(防抖 600ms,不会打十个字塞十条)
|
||||
- 攒够了点「发给 AI」,一起发出去
|
||||
|
||||
### ★ 这里**没有 JS 桥**
|
||||
|
||||
和 `show_ui` 那段的关键区别:这里浏览的是**互联网上任意站点**,
|
||||
全程都在别人的页面上。挂桥等于把 App 的内部接口交给它们。
|
||||
|
||||
所以用"单向队列 + 主动轮询":
|
||||
|
||||
```
|
||||
注入的脚本(页面里) Kotlin 侧
|
||||
──────────────────── ──────────────
|
||||
用户点了/写了 → 塞进 window.__doubaoPicks
|
||||
每 500ms evaluateJavascript("取走队列")
|
||||
← 拿到 JSON
|
||||
```
|
||||
|
||||
数据**只从页面流向 App**,页面没有任何办法主动调 App。
|
||||
|
||||
★ 改过一版:第一版只认"看着能点"的元素(`a,button,[role=button],…`),
|
||||
实测在 example.com 上**一个都标不出来**(那页全是纯文本),于是点选模式
|
||||
看起来完全没生效。用户想点的是**任意一段内容**,所以改成
|
||||
`elementFromPoint` 点哪儿抓哪儿,虚线框降级成纯视觉提示。
|
||||
|
||||
★ 点选用**捕获阶段** + `preventDefault`:抢在页面自己的 handler 前面,
|
||||
并拦掉这次跳转(用户是"选中"不是"跳转")。
|
||||
但 `input` 事件用**冒泡阶段旁听**、不拦 —— 拦了会破坏页面的自动补全、字数统计。
|
||||
|
||||
---
|
||||
|
||||
## ★ 清不掉 Base URL 的坑(v2.0.37 修)
|
||||
|
||||
`store.write_settings` 有一段"保险":空串一律当"没填、别动"。
|
||||
它防的是**"前端草稿没初始化好,一次保存清空整份配置"**,这个保险是对的。
|
||||
|
||||
但代价是:**用户永远清不掉自定义 Base URL / 模型名** ——
|
||||
删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||||
(我是在测数据回流时踩到的:想把内核从假服务指回默认,传空串怎么也改不掉。)
|
||||
|
||||
修法:加一条**显式**的清除通路 —— 传 `null` 就是"确实要清掉",落到默认值上。
|
||||
|
||||
| 传什么 | 含义 |
|
||||
|---|---|
|
||||
| `""` | 没填,别动 |
|
||||
| `null` | 确实要清掉,回到默认 |
|
||||
|
||||
Python 和 Node 两端都改了(同一段逻辑有两份,改一边就会不一致)。
|
||||
|
||||
---
|
||||
|
||||
## ask_user:弹选择框
|
||||
|
||||
```
|
||||
{ "question": "这个方案你要哪一个?",
|
||||
"options": [{"label": "方案 A", "value": "A", "description": "快但功能少"}],
|
||||
"multiple": false, "allow_cancel": true }
|
||||
```
|
||||
|
||||
### options 两种写法都收
|
||||
|
||||
模型经常写**裸字符串数组** `["A", "B"]` 而不是对象数组 —— 这在 tool calling
|
||||
里非常常见。只认一种的话它会平白吃一个 `AttributeError`,然后重试、再失败。
|
||||
所以 `_clean_options()` 两种都收,还会丢掉空项、把 `value` 回落到 `label`。
|
||||
|
||||
### 超过 8 个选项会截断
|
||||
|
||||
按钮会挤成一屏。截断的同时**告诉模型**(返回里带 `note`),
|
||||
而不是静默丢掉 —— 静默丢掉会让它以为用户看到了 20 个选项。
|
||||
|
||||
---
|
||||
|
||||
## end_conversation:永久结束
|
||||
|
||||
### 界面(用户指定)
|
||||
|
||||
**屏幕中间一个横幅,写着 AI 关闭的原因。**
|
||||
|
||||
```
|
||||
⌐ 这次对话已结束
|
||||
这件事已经办完了,没有后续可聊的。
|
||||
[ 开始新对话 ]
|
||||
```
|
||||
|
||||
- 停在**屏幕正中间**,**不自动消失** —— 它是状态不是提示,
|
||||
消失了用户就不知道为什么发不出消息了
|
||||
- 输入框整个不渲染(不是"渲染成禁用"),用户看到的就是"这儿没得输了"
|
||||
- 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
|
||||
### 必须落盘
|
||||
|
||||
`PATCH /api/conversations/<id>` 写 `ended` / `endedAt` / `endedReason`。
|
||||
|
||||
★ 只放 Compose 状态里的话,**一刷新就没了**:用户关掉 App 再进来会看到
|
||||
一个能继续输入的框,而模型以为自己已经结束了。两边状态不一致是这类功能
|
||||
最容易出的问题。
|
||||
|
||||
### 拿不到对话 id 时必须报错
|
||||
|
||||
绝不假装成功。假装成功正好会产生上面那个不一致。
|
||||
|
||||
---
|
||||
|
||||
## 开关:两道拦截,缺一不可
|
||||
|
||||
`settings.uiTools.enabled`,默认 `false`。
|
||||
|
||||
1. **对模型隐藏**(`filter_ui_tools`)—— 关掉时它根本看不到这三个工具
|
||||
2. **执行时拒绝**(`execute_tool` 里的第二道)—— 即使它硬编名字也不执行
|
||||
|
||||
★ 为什么两道都要:只做①的话,用户关掉之后模型仍可能**从历史消息里**
|
||||
学会这个名字(之前的对话里出现过)再调一次。
|
||||
|
||||
★ 提示词也按开关走:`UI_TOOLS_HINT` 只在打开时追加到系统提示词。
|
||||
写进 `DEFAULT_SYSTEM_PROMPT` 的话会被存进用户的 `settings.json` ——
|
||||
关着的时候模型还在被教"你可以用 show_ui"。
|
||||
|
||||
---
|
||||
|
||||
## 踩过的两个坑
|
||||
|
||||
### ① thread-local 不跨线程(最隐蔽的一个)
|
||||
|
||||
`end_conversation` 一直报"拿不到当前对话 id"。我以为是 `app.py` 没传
|
||||
`conversationId`,查了一圈才发现:
|
||||
|
||||
```
|
||||
app.py push_context(conversationId=…) ← 在 HTTP 工作线程 A 上
|
||||
→ execute_tool
|
||||
→ run_python_tool
|
||||
→ run_with_timeout(fn) ← 起了**线程 B**
|
||||
→ fn() → tool.run() ← 在 B 上,_ctx 是空的!
|
||||
```
|
||||
|
||||
`threading.local()` **不跨线程继承**。工具照常执行(参数都对),
|
||||
只有上下文拿不到 —— 表现和"参数没传"一模一样。
|
||||
|
||||
修法:`run_python_tool` 执行前把父线程的上下文搬进工作线程。
|
||||
验证脚本里专门留了"另一个线程里读不到(符合 thread-local 语义)"这条 ——
|
||||
说明这个语义是**故意**的,所以必须显式搬。
|
||||
|
||||
### ② `/api/tools/run` 传的是假 settings
|
||||
|
||||
以前是 `{'security': {'mode': 'open'}}` 空壳,为的是"手动试运行不受安全模式
|
||||
限制"。但界面工具的开关也在 settings 里 —— 于是用户在技能页点「试运行」,
|
||||
**开关明明是开的,却收到"已关闭"**。这个错会让人以为是开关没生效。
|
||||
|
||||
改成拿真实设置、只覆盖 `security`。
|
||||
|
||||
---
|
||||
|
||||
## 怎么测
|
||||
|
||||
```bash
|
||||
# 守门(34 项)
|
||||
python scripts/verify-ui-tools.py
|
||||
|
||||
# 端到端(需要先把内核端口转发出来)
|
||||
adb forward tcp:15199 tcp:5199
|
||||
python scripts/probe-ai-surfaces.py all # show_ui + end_conversation
|
||||
python scripts/probe-ai-surfaces.py ask # ask_user(会阻塞,等你在手机上点)
|
||||
python scripts/probe-ai-surfaces.py askmulti
|
||||
```
|
||||
|
||||
★ 为什么从宿主机打而不是在设备上敲:`adb`/PowerShell 的多层引号会把 JSON
|
||||
搅烂(这一路上踩过好几次)。转发端口之后在宿主机上用 Python 打,引号只有一层。
|
||||
|
||||
真机实测记录(Android 14 x86_64):
|
||||
|
||||
```
|
||||
show_ui → 界面渲染正常(标题栏 + 暗色表格 + 可点按钮)
|
||||
ask_user 单选 → 等 21.1s,返回 {"choice":"B","values":["B"],"timeout":false}
|
||||
ask_user 多选 → 选 2 个,返回 {"values":["python","git"],"cancelled":false}
|
||||
end_conversation → ended=True 落盘,横幅显示原因
|
||||
```
|
||||
93
scripts/backfill-shipped-hashes.py
Normal file
93
scripts/backfill-shipped-hashes.py
Normal file
@@ -0,0 +1,93 @@
|
||||
"""把 tools/*.py 在**所有历史提交**里出现过的版本哈希,回填进 tools/.shipped-hashes.json。
|
||||
|
||||
## 为什么需要这个回填
|
||||
|
||||
`_seed_tools` 靠"这份哈希是不是我们发过的"来区分
|
||||
「老设备上的旧版本(可以覆盖)」和「用户自己改的(绝不能覆盖)」。
|
||||
|
||||
但登记表是这一次才开始记的,所以**设备上现存的那些旧版本哈希不在表里**——
|
||||
升级还是会被判成"用户改过"。典型的先有鸡还是先有蛋。
|
||||
|
||||
修法:翻 git 历史,把每个工具文件**出现过的每一个版本**都算一遍哈希填进去。
|
||||
老设备上跑的一定是历史里的某一版,这样就都能认出来。
|
||||
|
||||
(只增不减:哈希多记几个没坏处,最多是"把某个用户恰好改成一模一样内容的文件"
|
||||
也当成我们的 —— 那种情况实际不可能发生。)
|
||||
|
||||
用法:
|
||||
python scripts/backfill-shipped-hashes.py # 只看,不写
|
||||
python scripts/backfill-shipped-hashes.py --write # 真写
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOLS = os.path.join(WS, "tools")
|
||||
REG = os.path.join(TOOLS, ".shipped-hashes.json")
|
||||
WRITE = "--write" in sys.argv
|
||||
|
||||
|
||||
def git(*args) -> str:
|
||||
out = subprocess.run(
|
||||
["git", "-C", WS, *args],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
||||
)
|
||||
if out.returncode != 0:
|
||||
raise RuntimeError(f"git {' '.join(args)} 失败:{out.stderr[:300]}")
|
||||
return out.stdout
|
||||
|
||||
|
||||
def h(text: str) -> str:
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
try:
|
||||
registry = json.load(open(REG, encoding="utf-8"))
|
||||
except Exception:
|
||||
registry = {}
|
||||
|
||||
files = sorted(f for f in os.listdir(TOOLS) if f.endswith(".py"))
|
||||
print(f"仓库里有 {len(files)} 个工具文件\n")
|
||||
|
||||
added_total = 0
|
||||
for name in files:
|
||||
rel = f"tools/{name}"
|
||||
# 这个文件历史上被改过的所有提交
|
||||
commits = git("log", "--all", "--format=%H", "--", rel).split()
|
||||
versions = set()
|
||||
for sha in commits:
|
||||
try:
|
||||
content = git("show", f"{sha}:{rel}")
|
||||
except RuntimeError:
|
||||
continue
|
||||
versions.add(h(content))
|
||||
# 当前工作区那份也要在(构建时会自己加,但这里保证一致)
|
||||
versions.add(h(open(os.path.join(TOOLS, name), encoding="utf-8").read()))
|
||||
|
||||
have = set(registry.get(name) or [])
|
||||
new = sorted(versions - have)
|
||||
if new:
|
||||
print(f" {name}: 历史 {len(versions)} 版,新增 {len(new)} 条")
|
||||
added_total += len(new)
|
||||
registry[name] = sorted(have | versions)
|
||||
|
||||
print(f"\n共新增 {added_total} 条")
|
||||
for name in files:
|
||||
print(f" {name}: {len(registry[name])} 条")
|
||||
|
||||
if WRITE:
|
||||
with open(REG, "w", encoding="utf-8") as fh:
|
||||
json.dump(registry, fh, ensure_ascii=False, indent=2, sort_keys=True)
|
||||
fh.write("\n")
|
||||
print(f"\n已写入 {REG}")
|
||||
else:
|
||||
print("\n(只看不写。加 --write 才真写)")
|
||||
@@ -11,6 +11,7 @@
|
||||
* 用法: node scripts/build-apk.mjs [--skip-build] [--release]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -109,12 +110,56 @@ for (const file of fs.readdirSync(path.join(repo, 'tools'))) {
|
||||
toolSources[file] = source.toString('base64');
|
||||
toolCount += 1;
|
||||
}
|
||||
// ★★★ 内置工具的"历史版本哈希登记表"
|
||||
//
|
||||
// 为什么需要它 —— 这里踩过一个非常隐蔽的坑:
|
||||
//
|
||||
// 内核启动时把内置工具播种到手机可写目录(用户能自己改)。
|
||||
// 为了**不许覆盖用户改过的文件**,播种时要判断"盘上这份是不是我们写的"。
|
||||
// 第一版只看一个本地指纹文件(.doubao-seed.json):
|
||||
// 指纹对得上 = 我们写的;对不上 = 用户改过 → 不覆盖。
|
||||
//
|
||||
// 问题是**老设备上那个指纹文件是空的**(第一版播种逻辑没写过它)。
|
||||
// 于是所有文件都被判成"用户改过",**升级永远不生效** ——
|
||||
// 实测 v2.0.37 给 show_ui 加了 wait 参数,真机上死活拿不到。
|
||||
//
|
||||
// 所以必须有一份"我们**以前**发过哪些内容"的记录,才能区分:
|
||||
// · 盘上这份是我们旧版本发的 → 安全覆盖
|
||||
// · 盘上这份不是任何一版我们发的 → 用户改过 → 绝不覆盖
|
||||
//
|
||||
// 这份登记表在构建时累积:每发一版就把当前哈希加进去(去重、只增不减)。
|
||||
// 存成仓库里的一个 JSON 文件,跟着代码走。
|
||||
const regPath = path.join(repo, 'tools', '.shipped-hashes.json');
|
||||
let registry = {};
|
||||
try {
|
||||
registry = JSON.parse(fs.readFileSync(regPath, 'utf8'));
|
||||
} catch {
|
||||
registry = {};
|
||||
}
|
||||
const hashOf = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 16);
|
||||
let newHashes = 0;
|
||||
for (const [name, source] of Object.entries(toolSources)) {
|
||||
const text = Buffer.from(source, 'base64').toString('utf8');
|
||||
const h = hashOf(text);
|
||||
const list = Array.isArray(registry[name]) ? registry[name] : [];
|
||||
if (!list.includes(h)) {
|
||||
list.push(h);
|
||||
newHashes += 1;
|
||||
}
|
||||
registry[name] = list;
|
||||
}
|
||||
fs.writeFileSync(regPath, JSON.stringify(registry, null, 2) + '\n', 'utf8');
|
||||
if (newHashes) log(`工具哈希登记表:新增 ${newHashes} 条`);
|
||||
|
||||
const bundledPy = [
|
||||
'"""构建时自动生成,不要手改。',
|
||||
'',
|
||||
'内置 Python 工具的源码(base64)。安卓端 Chaquopy 只有 .pyc,',
|
||||
'所以由 scripts/build-apk.mjs 在打包时把源码嵌进来,',
|
||||
'由 doubao_entry 首次启动时解码写到手机上的可写工具目录。',
|
||||
'由 doubao_entry 启动时解码写到手机上的可写工具目录。',
|
||||
'',
|
||||
'`shipped()` 返回"历史上我们发过的所有源码哈希" —— 内核靠它区分',
|
||||
'"盘上这份是我们旧版本写的(可以覆盖)" 和 "用户自己改过(不能覆盖)"。',
|
||||
'"""',
|
||||
'',
|
||||
'import base64',
|
||||
@@ -123,14 +168,23 @@ const bundledPy = [
|
||||
...Object.entries(toolSources).map(([name, b64]) => ` ${JSON.stringify(name)}: ${JSON.stringify(b64)},`),
|
||||
'}',
|
||||
'',
|
||||
'_SHIPPED = {',
|
||||
...Object.entries(registry).map(([name, list]) => ` ${JSON.stringify(name)}: ${JSON.stringify(list)},`),
|
||||
'}',
|
||||
'',
|
||||
'',
|
||||
'def sources():',
|
||||
' """返回 {文件名: 源码文本}"""',
|
||||
' return {name: base64.b64decode(data).decode("utf-8") for name, data in _DATA.items()}',
|
||||
'',
|
||||
'',
|
||||
'def shipped():',
|
||||
' """返回 {文件名: [历史哈希, ...]}"""',
|
||||
' return {name: list(v) for name, v in _SHIPPED.items()}',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.writeFileSync(path.join(pyRoot, 'bundled_tool_sources.py'), bundledPy, 'utf8');
|
||||
log(`已内置 ${toolCount} 个 Python 工具(含源码与 _protocol.py)`);
|
||||
log(`已内置 ${toolCount} 个 Python 工具(含源码、_protocol.py、历史哈希表)`);
|
||||
|
||||
// 内核源码在 android/kernel,靠 chaquopy 的 srcDir("../kernel") 引入;
|
||||
// 这里检查一下它确实在
|
||||
|
||||
86
scripts/fake-openai.py
Normal file
86
scripts/fake-openai.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""假模型服务:把收到的请求原样存下来,回一个最小可用的 SSE。
|
||||
|
||||
用来**证明**"界面上选的值真的拼进了发给模型的消息里" ——
|
||||
光看队列空了不够,那只说明有人取走了;到底拼没拼、拼成什么样,要看请求。
|
||||
|
||||
用法:
|
||||
python scripts/fake-openai.py 18080 # 另开一个窗口
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18080
|
||||
CAPTURE = sys.argv[2] if len(sys.argv) > 2 else r"C:\DoubaoAndroid\fake-req.json"
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/v1/models"):
|
||||
body = json.dumps({"data": [{"id": "fake-model"}]}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n).decode("utf-8", "replace")
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except Exception:
|
||||
parsed = {"__raw": raw}
|
||||
|
||||
# ★ 存下来 —— 这就是"模型收到了什么"的铁证
|
||||
with open(CAPTURE, "w", encoding="utf-8") as fh:
|
||||
json.dump({"path": self.path, "body": parsed}, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"\n=== {self.path} 收到请求 ===", flush=True)
|
||||
for m in (parsed.get("messages") or []):
|
||||
role = m.get("role")
|
||||
content = m.get("content")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(
|
||||
c.get("text", "") for c in content if isinstance(c, dict)
|
||||
)
|
||||
text = (content or "")
|
||||
print(f" [{role}] {text[:400]}", flush=True)
|
||||
|
||||
# 回一个最小 SSE(OpenAI 流式格式)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.end_headers()
|
||||
|
||||
def chunk(delta, finish=None):
|
||||
obj = {
|
||||
"id": "chatcmpl-fake", "object": "chat.completion.chunk",
|
||||
"created": int(time.time()), "model": "fake-model",
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
|
||||
}
|
||||
self.wfile.write(f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode())
|
||||
self.wfile.flush()
|
||||
|
||||
chunk({"role": "assistant", "content": "我看到你在界面上选了:方案B、方案C、方案D。"})
|
||||
chunk({}, "stop")
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"假模型服务监听 127.0.0.1:{PORT}", flush=True)
|
||||
print(f"请求会存到 {CAPTURE}", flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
63
scripts/probe-bridge-visibility.py
Normal file
63
scripts/probe-bridge-visibility.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""验证"外部页面拿不到桥"。
|
||||
|
||||
思路:AI 页面里放一个按钮,点了之后用 JS 把 `typeof Doubao` 的结果写到页面上。
|
||||
先在初始页看一次(应该是 object),导航到 http 页之后再看一次(应该 undefined)。
|
||||
|
||||
★ 为什么不用"点外链然后在外部页面上跑 JS":外部页面我们控制不了,
|
||||
evaluateJavascript 也需要 App 侧支持。用自己页面上的按钮最直接。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=120):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
HTML = """
|
||||
<h1>桥可见性测试</h1>
|
||||
<p id="out" style="font-size:18px">(还没检测)</p>
|
||||
<button onclick="check()" style="padding:12px 18px;border-radius:10px;border:0;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">检测 typeof Doubao</button>
|
||||
<p style="margin-top:16px">
|
||||
<a id="go" href="https://example.com">→ 导航到 example.com</a>
|
||||
</p>
|
||||
<script>
|
||||
function check() {
|
||||
var t = (typeof Doubao);
|
||||
document.getElementById('out').textContent =
|
||||
'typeof Doubao = ' + t + ' | pick 可用: ' + (t === 'object' && typeof Doubao.pick === 'function');
|
||||
}
|
||||
// 加载时自动测一次
|
||||
check();
|
||||
</script>
|
||||
"""
|
||||
|
||||
print("=== 弹「桥可见性测试」页面 ===")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "桥测试", "html": HTML},
|
||||
"conversationId": "c_main",
|
||||
})
|
||||
print(json.dumps(res, ensure_ascii=False)[:200])
|
||||
print("""
|
||||
接下来手动做(脚本没法点屏幕):
|
||||
1. 截图 —— 应显示 "typeof Doubao = object | pick 可用: true"
|
||||
2. 点链接导航到 example.com
|
||||
3. 点顶部返回键回到我们那一页
|
||||
4. 再截图 —— 回来之后应该**还是 object**(onPageFinished 里重新挂上了)
|
||||
""")
|
||||
34
scripts/probe-check-conv.py
Normal file
34
scripts/probe-check-conv.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=60):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
convs = call("/api/conversations", method="GET").get("conversations") or []
|
||||
print("会话:")
|
||||
for c in convs:
|
||||
print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount"),
|
||||
"| updated", c.get("updatedAt"))
|
||||
|
||||
# 直接看 c_main 里到底有没有消息
|
||||
full = call("/api/conversations/c_main", method="GET").get("conversation") or {}
|
||||
msgs = full.get("messages") or []
|
||||
print(f"\nc_main 里 {len(msgs)} 条消息:")
|
||||
for m in msgs:
|
||||
print(" ", m.get("role"), "|", repr((m.get("content") or "")[:60]))
|
||||
49
scripts/probe-check-showui-spec.py
Normal file
49
scripts/probe-check-showui-spec.py
Normal file
@@ -0,0 +1,49 @@
|
||||
"""查设备上跑的 show_ui.py 是不是新的(有没有 wait 参数)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=60):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
tools = call("/api/tools", None, "GET")
|
||||
py = (tools.get("python") or tools.get("tools") or [])
|
||||
if isinstance(py, dict):
|
||||
py = py.get("python") or []
|
||||
found = None
|
||||
for t in py:
|
||||
if t.get("name") == "show_ui":
|
||||
found = t
|
||||
break
|
||||
|
||||
if not found:
|
||||
print("!! /api/tools 里没有 show_ui;原始返回:")
|
||||
print(json.dumps(tools, ensure_ascii=False)[:1500])
|
||||
sys.exit(1)
|
||||
|
||||
print("show_ui 的 spec:")
|
||||
print(" 有 wait 参数:", "wait" in json.dumps(found.get("parameters") or {}, ensure_ascii=False))
|
||||
print(" 有 timeout 参数:", "timeout" in json.dumps(found.get("parameters") or {}, ensure_ascii=False))
|
||||
desc = found.get("description") or ""
|
||||
print(" description 里提到 wait:", "wait" in desc)
|
||||
print(" description 里提到'三种收尾':", "三种收尾" in desc)
|
||||
print()
|
||||
print("description 前 400 字:")
|
||||
print(desc[:400])
|
||||
print()
|
||||
print("工具目录:", (tools.get("dir") or tools.get("toolsDir") or "(没报)"))
|
||||
46
scripts/probe-clean-testdata.py
Normal file
46
scripts/probe-clean-testdata.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""清掉测试留下的对话数据(让模拟器上的 App 回到干净状态)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
K = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(p, d=None, m="POST"):
|
||||
b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None
|
||||
r = urllib.request.Request(
|
||||
K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"}
|
||||
)
|
||||
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode())
|
||||
|
||||
|
||||
# ★ 注意 method 是**位置参数** m,不是 method= —— 这个脚本第一版写成
|
||||
# `method="PATCH"` 直接 TypeError。写探针脚本时这种小错最多。
|
||||
call("/api/conversations/c_main", {"messages": []}, "PATCH")
|
||||
full = call("/api/conversations/c_main", None, "GET").get("conversation") or {}
|
||||
print("消息数:", len(full.get("messages") or []))
|
||||
print("ended:", full.get("ended"))
|
||||
|
||||
# 把 provider 恢复成默认(e2e 测试里改过)
|
||||
#
|
||||
# ★ 不能只传空串:内核保存时会把空值过滤掉,于是 baseUrl/model 留在假服务上,
|
||||
# 用户打开 App 会发现"模型指着 127.0.0.1:18080"而一脸懵。
|
||||
# ★ 也没有 GET /api/settings(404)—— 读当前设置要用 /api/state。
|
||||
st = call("/api/state", None, "GET")
|
||||
s = dict(st.get("settings") or {})
|
||||
s.pop("baseUrl", None)
|
||||
s.pop("model", None)
|
||||
s.pop("apiKey", None)
|
||||
s["provider"] = "ark"
|
||||
call("/api/settings", s, "PUT")
|
||||
after = (call("/api/state", None, "GET").get("settings") or {})
|
||||
print("provider:", after.get("provider"),
|
||||
"| baseUrl:", repr(after.get("baseUrl")),
|
||||
"| model:", repr(after.get("model")))
|
||||
q = call("/api/ui-result?conversationId=c_main", None, "GET")
|
||||
print("待交付队列:", q)
|
||||
57
scripts/probe-device-pyc.py
Normal file
57
scripts/probe-device-pyc.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""把设备上 show_ui.pyc 的修改时间、以及内核报的 spec 一起打出来。
|
||||
|
||||
用于回答:"我明明重建安装了,为什么设备上跑的还是旧的?"
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=60):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
# python_run 能在**内核进程里**跑(虽然是子进程,但能看文件系统)
|
||||
probe = r'''
|
||||
import os, sys, json, glob
|
||||
out = {}
|
||||
# Chaquopy 的 Python 根目录
|
||||
for p in sys.path:
|
||||
if p and os.path.isdir(p):
|
||||
for name in ("show_ui.py", "show_ui.pyc", "bundled_tool_sources.pyc"):
|
||||
f = os.path.join(p, name)
|
||||
if os.path.exists(f):
|
||||
st = os.stat(f)
|
||||
out.setdefault("found", []).append({
|
||||
"path": f, "size": st.st_size, "mtime": st.st_mtime,
|
||||
})
|
||||
out["sys_path_head"] = sys.path[:6]
|
||||
out["has_wait_in_source"] = None
|
||||
# 试着从 bundled_tool_sources 里解出 show_ui 的源码,看看有没有 wait
|
||||
try:
|
||||
import base64, bundled_tool_sources
|
||||
src = bundled_tool_sources.sources().get("show_ui.py", "")
|
||||
out["has_wait_in_source"] = ("wait" in src)
|
||||
out["source_len"] = len(src)
|
||||
out["source_head"] = src[:200]
|
||||
except Exception as e:
|
||||
out["bundled_error"] = f"{type(e).__name__}: {e}"
|
||||
print(json.dumps(out, ensure_ascii=False))
|
||||
'''
|
||||
res = call("/api/tools/run", {
|
||||
"name": "python_run", "args": {"code": probe, "timeout": 30},
|
||||
}, timeout=90)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2)[:2500])
|
||||
63
scripts/probe-device-tools-dir.py
Normal file
63
scripts/probe-device-tools-dir.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""看设备上 show_ui.py 的实际大小 / 指纹,以及播种日志。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
TOOLS = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
probe = r'''
|
||||
import os, sys, json, hashlib
|
||||
D = %r
|
||||
out = {"dir": D, "exists": os.path.isdir(D)}
|
||||
if os.path.isdir(D):
|
||||
files = []
|
||||
for name in sorted(os.listdir(D)):
|
||||
p = os.path.join(D, name)
|
||||
if os.path.isfile(p):
|
||||
st = os.stat(p)
|
||||
item = {"name": name, "size": st.st_size, "mtime": st.st_mtime}
|
||||
if name.endswith(".py"):
|
||||
txt = open(p, encoding="utf-8", errors="replace").read()
|
||||
item["has_wait"] = "wait" in txt
|
||||
item["sha16"] = hashlib.sha256(txt.encode()).hexdigest()[:16]
|
||||
files.append(item)
|
||||
out["files"] = files
|
||||
sp = os.path.join(D, ".doubao-seed.json")
|
||||
if os.path.isfile(sp):
|
||||
out["stamp_exists"] = True
|
||||
out["stamp_show_ui"] = json.load(open(sp, encoding="utf-8")).get("show_ui.py")
|
||||
else:
|
||||
out["stamp_exists"] = False
|
||||
# 内嵌源码里的那份
|
||||
try:
|
||||
import hashlib as _h
|
||||
import bundled_tool_sources
|
||||
src = bundled_tool_sources.sources().get("show_ui.py", "")
|
||||
out["bundled_len"] = len(src)
|
||||
out["bundled_sha16"] = _h.sha256(src.encode()).hexdigest()[:16]
|
||||
out["bundled_has_wait"] = "wait" in src
|
||||
except Exception as e:
|
||||
out["bundled_error"] = f"{type(e).__name__}: {e}"
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
''' % TOOLS
|
||||
|
||||
res = call("/api/tools/run", {"name": "python_run", "args": {"code": probe, "timeout": 30}}, timeout=120)
|
||||
out = (res or {}).get("result") or {}
|
||||
print(out.get("stdout") or json.dumps(out, ensure_ascii=False)[:1500])
|
||||
86
scripts/probe-heartbeat-ui.py
Normal file
86
scripts/probe-heartbeat-ui.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""按用户截图里的样子造一个界面:心跳线 + 六个按钮。
|
||||
|
||||
★ 用户报"没有一个按键能用",而我之前测的都是朴素 HTML。
|
||||
所以这里**按他截图里的形态**造:canvas 画心跳线 + 六个中文按钮 +
|
||||
一段很长的角色扮演文案(把按钮挤到屏幕外),看按钮到底能不能点。
|
||||
|
||||
三种按钮形态都放上:
|
||||
① onclick="Doubao.sendToAi(...)" —— JS 桥
|
||||
② data-doubao-result="..." —— App 侧字符串替换(不依赖 JS)
|
||||
③ 纯 <button> 什么都没标 —— 对照,本来就不该有回传能力
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=180):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
HTML = """
|
||||
<h1 style="font-size:20px">今天,你归我了</h1>
|
||||
|
||||
<canvas id="beat" width="320" height="90"
|
||||
style="width:100%;background:#14161b;border-radius:10px"></canvas>
|
||||
|
||||
<p style="margin:14px 0 6px;color:#8c939d;font-size:13px">下面六个按钮,点哪个我就干哪个:</p>
|
||||
|
||||
<button onclick="Doubao.sendToAi('查岗')">① 抽查我位置</button>
|
||||
<button data-doubao-result="来点黄的">② 来点黄的</button>
|
||||
<button onclick="Doubao.sendToAi('讲个故事')">③ 讲个故事</button>
|
||||
<button data-doubao-result="夸我">④ 夸我</button>
|
||||
<button onclick="Doubao.sendToAi('唱歌')">⑤ 唱首歌</button>
|
||||
<button onclick="Doubao.close()">⑥ 关掉界面</button>
|
||||
|
||||
<div id="st" style="margin-top:12px;font-size:12px;color:#8c939d">(点一下试试,这里会显示结果)</div>
|
||||
|
||||
<script>
|
||||
// 心跳线 —— 复刻用户截图里那个效果
|
||||
var c = document.getElementById('beat'), g = c.getContext('2d');
|
||||
c.width = 320; c.height = 90;
|
||||
var t = 0;
|
||||
function draw() {
|
||||
g.clearRect(0, 0, 320, 90);
|
||||
g.strokeStyle = '#4c8dff';
|
||||
g.lineWidth = 2;
|
||||
g.beginPath();
|
||||
for (var x = 0; x < 320; x++) {
|
||||
var y = 45 + Math.sin((x + t) / 9) * Math.exp(-((x % 90) / 40)) * 26
|
||||
+ Math.sin((x + t) / 2.2) * 1.4;
|
||||
if (x === 0) g.moveTo(x, y); else g.lineTo(x, y);
|
||||
}
|
||||
g.stroke();
|
||||
t += 3;
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
draw();
|
||||
|
||||
// JS 桥可用性自检 —— 直接显示在页面上,一眼就能看出桥在不在
|
||||
document.getElementById('st').textContent =
|
||||
'typeof Doubao = ' + (typeof Doubao) +
|
||||
' | sendToAi: ' + (typeof Doubao !== 'undefined' && typeof Doubao.sendToAi === 'function');
|
||||
</script>
|
||||
"""
|
||||
|
||||
print("=== 按用户截图的形态弹一个界面 ===")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "心检", "html": HTML, "wait": True, "timeout": 90},
|
||||
"conversationId": CONV,
|
||||
}, timeout=180)
|
||||
print(json.dumps(res, ensure_ascii=False)[:400])
|
||||
109
scripts/probe-kernel-write.py
Normal file
109
scripts/probe-kernel-write.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""让内核进程直接往工具目录写一个文件,再从宿主机看它到底有没有真的落地。
|
||||
|
||||
★ 目的:排除"FUSE / 作用域存储导致宿主机看到的是另一份视图"这种可能。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
MARK = "内核进程写的标记 abc123"
|
||||
|
||||
code = (
|
||||
"import os, json\n"
|
||||
"D = %r\n"
|
||||
"out = {}\n"
|
||||
"p = os.path.join(D, '_kernelwrite.txt')\n"
|
||||
"try:\n"
|
||||
" with open(p, 'w', encoding='utf-8') as fh:\n"
|
||||
" fh.write(%r)\n"
|
||||
" out['wrote'] = True\n"
|
||||
" out['size'] = os.path.getsize(p)\n"
|
||||
" out['readback'] = open(p, encoding='utf-8').read()\n"
|
||||
"except Exception as e:\n"
|
||||
" out['err'] = f'{type(e).__name__}: {e}'\n"
|
||||
"try:\n"
|
||||
" import paths\n"
|
||||
" out['paths_tools_dir'] = paths.get().tools_dir\n"
|
||||
"except Exception as e:\n"
|
||||
" out['paths_err'] = f'{type(e).__name__}: {e}'\n"
|
||||
"try:\n"
|
||||
" import doubao_entry as de\n"
|
||||
" out['bundled_files_count'] = len(de.BUNDLED_TOOL_FILES)\n"
|
||||
" out['bundled_files'] = list(de.BUNDLED_TOOL_FILES)\n"
|
||||
" out['seed_wrote'] = de._seed_tools(getattr(paths.get(), 'tools_dir', D))\n"
|
||||
"except Exception as e:\n"
|
||||
" import traceback\n"
|
||||
" out['seed_err'] = f'{type(e).__name__}: {e}'\n"
|
||||
" out['seed_tb'] = traceback.format_exc()[-900:]\n"
|
||||
"print(json.dumps(out, ensure_ascii=False, indent=1))\n"
|
||||
) % (D, MARK)
|
||||
|
||||
# ★ 关键:用 /api/tools/run 跑的是**内核进程**吗?
|
||||
# python_run 会 fork 子进程。但 device / shell 这类是进程内的。
|
||||
# 这里用 python_run 不够 —— 要进程内的。所以写个临时工具让内核自己 import 执行。
|
||||
probe_src = (
|
||||
"import os, sys, json\n"
|
||||
"sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n"
|
||||
"TOOL = {'name': 'probe_kw', 'description': 'x',\n"
|
||||
" 'parameters': {'type': 'object', 'properties': {}}}\n"
|
||||
"def run(args):\n"
|
||||
" out = {}\n"
|
||||
" D = %r\n"
|
||||
" p = os.path.join(D, '_kernelwrite.txt')\n"
|
||||
" try:\n"
|
||||
" with open(p, 'w', encoding='utf-8') as fh:\n"
|
||||
" fh.write(%r)\n"
|
||||
" out['wrote'] = True\n"
|
||||
" out['readback'] = open(p, encoding='utf-8').read()\n"
|
||||
" except Exception as e:\n"
|
||||
" out['write_err'] = f'{type(e).__name__}: {e}'\n"
|
||||
" try:\n"
|
||||
" import paths\n"
|
||||
" out['paths_tools_dir'] = paths.get().tools_dir\n"
|
||||
" except Exception as e:\n"
|
||||
" out['paths_err'] = f'{type(e).__name__}: {e}'\n"
|
||||
" try:\n"
|
||||
" import doubao_entry as de\n"
|
||||
" out['bundled_count'] = len(de.BUNDLED_TOOL_FILES)\n"
|
||||
" out['has_src_hash'] = hasattr(de, '_src_hash')\n"
|
||||
" out['seed_wrote'] = de._seed_tools(D)\n"
|
||||
" except Exception as e:\n"
|
||||
" import traceback\n"
|
||||
" out['seed_err'] = f'{type(e).__name__}: {e}'\n"
|
||||
" out['seed_tb'] = traceback.format_exc()[-900:]\n"
|
||||
" return out\n"
|
||||
) % (D, MARK)
|
||||
|
||||
b64 = base64.b64encode(probe_src.encode("utf-8")).decode()
|
||||
w = (
|
||||
"import base64,os;"
|
||||
"open(os.path.join('%s','probe_kw.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64)
|
||||
)
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=120):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
|
||||
time.sleep(1)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_kw", "args": {}}, timeout=120)
|
||||
res = (r or {}).get("result") or {}
|
||||
print(res.get("stdout") or json.dumps(r, ensure_ascii=False)[:2500])
|
||||
43
scripts/probe-list-and-run.py
Normal file
43
scripts/probe-list-and-run.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""列出内核发现的工具 + 试跑 probe_perm 看真实异常。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=120):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode("utf-8", "replace")
|
||||
return {"__http_error": e.code, "__body": body[:2000]}
|
||||
|
||||
|
||||
tools = call("/api/tools", None, "GET")
|
||||
py = tools.get("python") or tools.get("tools") or []
|
||||
if isinstance(py, dict):
|
||||
py = py.get("python") or []
|
||||
names = sorted(t.get("name") for t in py if isinstance(t, dict))
|
||||
print("内核发现的工具(%d 个):" % len(names))
|
||||
print(" ", names)
|
||||
print()
|
||||
for probe in ("probe_perm", "probe_seed", "probe_loaded"):
|
||||
print(f"{probe} 在列表里:", probe in names)
|
||||
|
||||
print()
|
||||
print("=== 试跑 probe_perm ===")
|
||||
r = call("/api/tools/run", {"name": "probe_perm", "args": {}})
|
||||
print(json.dumps(r, ensure_ascii=False)[:2500])
|
||||
71
scripts/probe-loaded-entry.py
Normal file
71
scripts/probe-loaded-entry.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""让设备上的内核自己报:它加载的 doubao_entry 是哪个文件、有没有新符号。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
# ★ 用 python_run 跑不了(那是子进程,看不到内核进程里已加载的模块)。
|
||||
# 所以用一个**临时工具**:内核会 import 它,它就能看到内核进程的 sys.modules。
|
||||
probe_src = '''
|
||||
import os, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_loaded", "description": "探内核加载了什么",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
|
||||
def run(args):
|
||||
out = {}
|
||||
mod = sys.modules.get("doubao_entry")
|
||||
out["doubao_entry_file"] = getattr(mod, "__file__", None) if mod else None
|
||||
out["has_src_hash"] = hasattr(mod, "_src_hash") if mod else None
|
||||
out["has_new_seed"] = None
|
||||
if mod:
|
||||
import inspect
|
||||
try:
|
||||
src = inspect.getsource(mod._seed_tools)
|
||||
out["seed_src_len"] = len(src)
|
||||
out["seed_has_fingerprint"] = "doubao-seed.json" in src
|
||||
except Exception as e:
|
||||
out["seed_src_error"] = f"{type(e).__name__}: {e}"
|
||||
# 内嵌源码里 show_ui 有没有 wait
|
||||
try:
|
||||
import bundled_tool_sources
|
||||
s = bundled_tool_sources.sources().get("show_ui.py", "")
|
||||
out["bundled_show_ui_len"] = len(s)
|
||||
out["bundled_show_ui_has_wait"] = "wait" in s
|
||||
except Exception as e:
|
||||
out["bundled_error"] = f"{type(e).__name__}: {e}"
|
||||
return out
|
||||
'''
|
||||
|
||||
# 写到可写工具目录里
|
||||
import base64
|
||||
b64 = base64.b64encode(probe_src.encode("utf-8")).decode()
|
||||
write_js = (
|
||||
"import base64,os;"
|
||||
"d='/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools';"
|
||||
"open(os.path.join(d,'probe_loaded.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('written')" % b64
|
||||
)
|
||||
r = call("/api/tools/run", {"name": "python_run", "args": {"code": write_js, "timeout": 30}}, timeout=90)
|
||||
print("写探针:", (r.get("result") or {}).get("stdout", "").strip())
|
||||
|
||||
# 让内核重新发现工具再执行
|
||||
r = call("/api/tools/run", {"name": "probe_loaded", "args": {}}, timeout=90)
|
||||
print(json.dumps((r or {}).get("result"), ensure_ascii=False, indent=1))
|
||||
80
scripts/probe-notes-migrate.py
Normal file
80
scripts/probe-notes-migrate.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""查笔记迁移为什么没生效。"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
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"
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
probe = r'''
|
||||
import os, sys, json
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_nt", "description": "x",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
def run(args):
|
||||
import notes
|
||||
out = {}
|
||||
out["notes_dir"] = notes.notes_dir()
|
||||
out["legacy_dir"] = notes._LEGACY_DIR
|
||||
out["same"] = os.path.abspath(notes.notes_dir()) == notes._LEGACY_DIR
|
||||
out["new_exists"] = os.path.isdir(notes.notes_dir())
|
||||
try:
|
||||
out["new_files"] = os.listdir(notes.notes_dir())
|
||||
except Exception as e:
|
||||
out["new_err"] = f"{type(e).__name__}: {e}"
|
||||
out["legacy_exists"] = os.path.isdir(notes._LEGACY_DIR)
|
||||
try:
|
||||
out["legacy_files"] = os.listdir(notes._LEGACY_DIR)
|
||||
except Exception as e:
|
||||
out["legacy_err"] = f"{type(e).__name__}: {e}"
|
||||
marker = os.path.join(notes.notes_dir(), ".migrated")
|
||||
out["marker_exists"] = os.path.exists(marker)
|
||||
# 手动跑一次迁移看报什么
|
||||
try:
|
||||
notes._migrate_once(notes.notes_dir())
|
||||
out["migrate_ran"] = True
|
||||
out["new_files_after"] = os.listdir(notes.notes_dir())
|
||||
except Exception as e:
|
||||
import traceback
|
||||
out["migrate_err"] = f"{type(e).__name__}: {e}"
|
||||
out["migrate_tb"] = traceback.format_exc()[-700:]
|
||||
# paths 里那个值
|
||||
try:
|
||||
import paths
|
||||
out["paths_notes_dir"] = paths.get().notes_dir
|
||||
except Exception as e:
|
||||
out["paths_err"] = f"{type(e).__name__}: {e}"
|
||||
return out
|
||||
'''
|
||||
|
||||
b64 = base64.b64encode(probe.encode("utf-8")).decode()
|
||||
w = ("import base64,os;"
|
||||
"open(os.path.join('%s','probe_nt.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64))
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}})
|
||||
time.sleep(1)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_nt", "args": {}})
|
||||
print(json.dumps((r or {}).get("result"), ensure_ascii=False, indent=1)[:1600])
|
||||
81
scripts/probe-notes-path.py
Normal file
81
scripts/probe-notes-path.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""查 notes 工具到底写到哪、能不能写。
|
||||
|
||||
★ 背景:用户要求"notes 用户要能查看"。
|
||||
notes.py 里的路径是 `工具文件/../data/notes` —— **相对工具自己算的**。
|
||||
安卓上工具在 `/storage/emulated/0/Android/data/<包名>/files/tools/`,
|
||||
于是笔记会落到 `.../files/data/notes`(**App 外部私有目录**,
|
||||
用户自己用文件管理器看不到,卸载还会被清掉)。
|
||||
先确认它到底写没写成功、写哪儿了。
|
||||
"""
|
||||
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"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
print("=== 1. 存一条笔记 ===")
|
||||
r = call("/api/tools/run", {
|
||||
"name": "notes",
|
||||
"args": {"action": "save", "title": "测试笔记", "content": "用户能查看吗?"},
|
||||
})
|
||||
print(" ", json.dumps(r, ensure_ascii=False)[:300])
|
||||
|
||||
print("\n=== 2. 列出来 ===")
|
||||
r = call("/api/tools/run", {"name": "notes", "args": {"action": "list"}})
|
||||
print(" ", json.dumps(r, ensure_ascii=False)[:400])
|
||||
|
||||
print("\n=== 3. 问内核:NOTES_DIR 究竟解析到哪个绝对路径 ===")
|
||||
probe = r'''
|
||||
import os, sys, json
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_notes", "description": "x",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
def run(args):
|
||||
import notes
|
||||
out = {
|
||||
"NOTES_DIR_raw": notes.NOTES_DIR,
|
||||
"NOTES_DIR_abs": os.path.abspath(notes.NOTES_DIR),
|
||||
"exists": os.path.isdir(os.path.abspath(notes.NOTES_DIR)),
|
||||
"writable": os.access(os.path.abspath(notes.NOTES_DIR), os.W_OK),
|
||||
"tool_file": notes.__file__,
|
||||
}
|
||||
try:
|
||||
items = os.listdir(out["NOTES_DIR_abs"])
|
||||
out["files"] = items[:10]
|
||||
out["count"] = len(items)
|
||||
except Exception as e:
|
||||
out["listdir_error"] = f"{type(e).__name__}: {e}"
|
||||
return out
|
||||
'''
|
||||
import base64
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
b64 = base64.b64encode(probe.encode("utf-8")).decode()
|
||||
w = ("import base64,os;"
|
||||
"open(os.path.join('%s','probe_notes.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64))
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}})
|
||||
import time
|
||||
time.sleep(1)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_notes", "args": {}})
|
||||
print(" ", json.dumps((r or {}).get("result"), ensure_ascii=False, indent=1)[:900])
|
||||
153
scripts/probe-phone-ops.py
Normal file
153
scripts/probe-phone-ops.py
Normal file
@@ -0,0 +1,153 @@
|
||||
"""测三个"操作手机"的工具:读通知 / 开 App / 调音量。
|
||||
|
||||
★ 这三个都属于"会真的动手机"的能力,所以除了正常路径,
|
||||
重点测**失败路径**:权限没开、App 不存在、系统拒绝改音量。
|
||||
这些必须**如实报错**,不能假装成功,也不能返回一个看着正常的空结果。
|
||||
"""
|
||||
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"
|
||||
fails = []
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
def tool(name, args):
|
||||
"""跑一个工具。
|
||||
|
||||
★ 返回的是**顶层的 {ok, result} 或 {ok:false, error}**,
|
||||
不是只有 result —— 第一版测试脚本只看了 result,于是工具抛错时
|
||||
拿到空 dict,三条断言全红,看起来像"错误信息没给",
|
||||
其实信息给得挺全(在顶层 error 里)。
|
||||
测试脚本必须按**真实响应形状**取值。
|
||||
"""
|
||||
return call("/api/tools/run", {"name": name, "args": args})
|
||||
|
||||
|
||||
def tool_err(r):
|
||||
"""从工具响应里取错误文本(顶层 error 或 result.error)"""
|
||||
if not isinstance(r, dict):
|
||||
return ""
|
||||
if r.get("error"):
|
||||
return str(r["error"])
|
||||
return str((r.get("result") or {}).get("error") or "")
|
||||
|
||||
|
||||
def check(cond, label, detail=""):
|
||||
print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
fails.append(label)
|
||||
|
||||
|
||||
print("=== 0. 三个工具都被发现了吗 ===")
|
||||
tools = call("/api/tools", None, "GET")
|
||||
py = tools.get("python") or tools.get("tools") or []
|
||||
if isinstance(py, dict):
|
||||
py = py.get("python") or []
|
||||
names = [t.get("name") for t in py if isinstance(t, dict)]
|
||||
for n in ("notifications", "apps", "volume"):
|
||||
check(n in names, f"{n} 被内核发现")
|
||||
|
||||
print("\n=== 1. 音量:读 ===")
|
||||
r = tool("volume", {"action": "get"})
|
||||
res = (r or {}).get("result") or {}
|
||||
streams = res.get("streams") or []
|
||||
check(bool(streams), f"读出 {len(streams)} 个音量流")
|
||||
for s in streams[:3]:
|
||||
print(f" {s.get('stream')}: {s.get('percent')}% ({s.get('level')})")
|
||||
|
||||
print("\n=== 2. 音量:写(set 百分比 → 自动换算成档位)===")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "set", "value": 40})
|
||||
res = (r or {}).get("result") or {}
|
||||
if res.get("error"):
|
||||
print(" (这台机器不让改媒体音量:", str(res["error"])[:80], ")")
|
||||
else:
|
||||
check(res.get("percent") is not None, f"设置后读到 {res.get('percent')}%")
|
||||
check(abs(int(res.get("percent") or 0) - 40) <= 10,
|
||||
"百分比落在 40% 附近(说明换算对了)",
|
||||
f"实际 {res.get('percent')}%")
|
||||
|
||||
print("\n=== 3. 音量:up / mute / unmute ===")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "up"})
|
||||
u = (r or {}).get("result") or {}
|
||||
check(u.get("before") is not None and u.get("current") is not None,
|
||||
"up 有前后值", f"{u.get('before')} -> {u.get('current')}")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "mute"})
|
||||
m = (r or {}).get("result") or {}
|
||||
check(m.get("current") == 0 or bool(str(m.get("error") or "")), "mute 生效或如实报错",
|
||||
f"current={m.get('current')} err={str(m.get('error'))[:40]}")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "unmute"})
|
||||
n = (r or {}).get("result") or {}
|
||||
check(int(n.get("current") or 0) > 0 or bool(str(n.get("error") or "")),
|
||||
"unmute 恢复到非零", f"current={n.get('current')}")
|
||||
|
||||
print("\n=== 4. App:列出来 ===")
|
||||
r = tool("apps", {"action": "list"})
|
||||
res = (r or {}).get("result") or {}
|
||||
check((res.get("total_installed") or 0) > 0, f"装了 {res.get('total_installed')} 个 App")
|
||||
for a in (res.get("apps") or [])[:4]:
|
||||
print(f" {a.get('label')} ({a.get('package')})")
|
||||
|
||||
print("\n=== 5. App:找一个真实存在的 ===")
|
||||
r = tool("apps", {"action": "find", "name": "设置"})
|
||||
res = (r or {}).get("result") or {}
|
||||
found = res.get("apps") or []
|
||||
check(bool(found), f"找到 {len(found)} 个含「设置」的",
|
||||
(found[0].get("label") if found else ""))
|
||||
|
||||
print("\n=== 6. ★ App:找不到时要**如实报错并给相近的名字** ===")
|
||||
r = tool("apps", {"action": "open", "name": "这个App绝对不存在xyz"})
|
||||
check(r.get("ok") is False, "没有假装打开成功", f"ok={r.get('ok')}")
|
||||
err = tool_err(r)
|
||||
check("没找到" in err, "错误说清了'没找到'", err[:90])
|
||||
check("action=" in err, "错误里给了下一步(说了该调哪个 action)", err[:110])
|
||||
|
||||
print("\n=== 7. ★ 通知:权限没开时必须报错(不是空列表)===")
|
||||
r = tool("notifications", {"action": "access"})
|
||||
res = (r or {}).get("result") or {}
|
||||
granted = bool(res.get("granted"))
|
||||
print(f" 通知使用权:{'已开' if granted else '没开'}")
|
||||
if not granted:
|
||||
r2 = tool("notifications", {"action": "list"})
|
||||
check(r2.get("ok") is False, "没权限时**工具失败**(不是返回空列表)")
|
||||
err2 = tool_err(r2)
|
||||
check("通知使用权" in err2, "错误说清了是权限问题", err2[:80])
|
||||
check("设置" in err2 and "通知使用权" in err2, "错误里说了怎么开(设置路径)",
|
||||
err2[-90:])
|
||||
else:
|
||||
r2 = tool("notifications", {"action": "list"})
|
||||
res2 = (r2 or {}).get("result") or {}
|
||||
check("notifications" in res2, f"有权限 → 读到 {res2.get('count')} 条")
|
||||
|
||||
print("\n=== 8. 通知:open_settings 能跳设置页 ===")
|
||||
r = tool("notifications", {"action": "open_settings"})
|
||||
res = (r or {}).get("result") or {}
|
||||
check(bool(res.get("opened")) or bool(res.get("error")), "跳转设置页(或如实报错)",
|
||||
str(res)[:80])
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
120
scripts/probe-reopen-screen.py
Normal file
120
scripts/probe-reopen-screen.py
Normal file
@@ -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 = """
|
||||
<h1>这是一个会被存下来的界面</h1>
|
||||
<p>关掉之后应该还能再打开,而且内容一模一样。</p>
|
||||
<canvas id="c" width="280" height="80" style="background:#14161b;border-radius:8px"></canvas>
|
||||
<button onclick="Doubao.sendToAi('点了')">一个按钮</button>
|
||||
<script>
|
||||
var cv=document.getElementById('c'),g=cv.getContext('2d');
|
||||
cv.height=80; g.strokeStyle='#4c8dff'; g.lineWidth=2; g.beginPath();
|
||||
for(var x=0;x<280;x++){ var y=40+Math.sin(x/8)*22; if(x===0)g.moveTo(x,y); else g.lineTo(x,y); }
|
||||
g.stroke();
|
||||
</script>
|
||||
<p style="color:#8c939d;font-size:12px">MARKER-7f3a(再打开时应该还能看到这行)</p>
|
||||
"""
|
||||
|
||||
|
||||
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 那行字和那条正弦波。")
|
||||
47
scripts/probe-reset-provider.py
Normal file
47
scripts/probe-reset-provider.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""把模拟器上的 provider 配置恢复成默认(e2e 测试把内核指到假服务上过)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
K = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(p, d=None, m="POST"):
|
||||
b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None
|
||||
r = urllib.request.Request(
|
||||
K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"}
|
||||
)
|
||||
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode())
|
||||
|
||||
|
||||
st = call("/api/state", None, "GET")
|
||||
s = st.get("settings") or {}
|
||||
print("改之前:")
|
||||
for k in ("provider", "baseUrl", "model", "apiKey", "hasApiKey"):
|
||||
print(f" {k} = {s.get(k)!r}")
|
||||
|
||||
# ★ 显式传 **null** 表示"我要清掉它"。
|
||||
# 传空串是不行的 —— 内核把空串当"没填、别动"(那个保险是为了防
|
||||
# "前端草稿没初始化好,一次保存清空整份配置")。
|
||||
# 两条路语义不同:空串 = 没填,null = 确实要清。
|
||||
res = call("/api/settings", {
|
||||
"provider": "ark",
|
||||
"baseUrl": None,
|
||||
"model": None,
|
||||
"apiKey": None,
|
||||
}, "PUT")
|
||||
after = (res.get("settings") or {})
|
||||
print("PUT(传 null)之后:")
|
||||
for k in ("provider", "baseUrl", "model"):
|
||||
print(f" {k} = {after.get(k)!r}")
|
||||
|
||||
st2 = call("/api/state", None, "GET")
|
||||
s2 = st2.get("settings") or {}
|
||||
print("重新读 /api/state:")
|
||||
for k in ("provider", "baseUrl", "model", "hasApiKey"):
|
||||
print(f" {k} = {s2.get(k)!r}")
|
||||
48
scripts/probe-seed-bare-urls.py
Normal file
48
scripts/probe-seed-bare-urls.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""塞一条带**裸 URL** 的助手回复(旧版 extractUrls 认不出来的那种)。
|
||||
|
||||
★ 用户报"操作栏里应该有『打开网页』按钮,但没显示"。
|
||||
旧实现只认 `](` 紧挨着的 markdown 链接,裸 URL 一律漏 →
|
||||
extractUrls 返回空 → 按钮整个不显示。
|
||||
这条回复就是用来验证修好没有的。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=60):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
content = (
|
||||
"给你几个链接,写法故意各不相同(旧版只有第一种能被认出来):\n\n"
|
||||
"1. 标准的:[Example 官网](https://example.com)\n"
|
||||
"2. 中间有空格的:[Example 中文] (https://example.com/index-zh)\n"
|
||||
"3. **裸 URL**:直接去 https://www.iana.org/help/example-domains 看\n"
|
||||
"4. 尖括号包裹:<https://example.org>\n"
|
||||
"5. 中文标点紧跟:也可以看 https://www.rfc-editor.org/rfc/rfc2606,里面有说明\n"
|
||||
)
|
||||
|
||||
convs = call("/api/conversations", None, "GET").get("conversations") or []
|
||||
cid = convs[0]["id"] if convs else "c_main"
|
||||
print("往", cid, "写消息…")
|
||||
|
||||
res = call(f"/api/conversations/{cid}", {"messages": [
|
||||
{"role": "user", "content": "给我几个链接"},
|
||||
{"role": "assistant", "content": content},
|
||||
]}, "PATCH")
|
||||
full = res.get("conversation") or {}
|
||||
print("现在", len(full.get("messages") or []), "条消息")
|
||||
62
scripts/probe-seed-link-msg.py
Normal file
62
scripts/probe-seed-link-msg.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""给会话塞一条带链接的助手回复,用来测「打开网页」按钮。
|
||||
|
||||
★ 为什么要造数据而不是真让模型回一条:
|
||||
真回一条要配 API key、要等流式、还有网络不确定性 —— 而我们这里要测的是
|
||||
**界面上那个按钮在不在、点了对不对**,跟回复怎么来的无关。
|
||||
直接写一条一样的消息,测起来快且稳定。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=60):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
convs = call("/api/conversations", method="GET").get("conversations") or []
|
||||
print("会话数:", len(convs))
|
||||
for c in convs[:5]:
|
||||
print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount"))
|
||||
|
||||
if not convs:
|
||||
print("!! 没有会话")
|
||||
sys.exit(1)
|
||||
|
||||
cid = convs[0]["id"]
|
||||
print(f"\n往 {cid} 里塞一条带链接的回复…")
|
||||
|
||||
content = (
|
||||
"我查到了几个可能有用的页面:\n\n"
|
||||
"- [Example 官网](https://example.com)\n"
|
||||
"- [Example 中文](https://example.com/index-zh)\n\n"
|
||||
"**说明**:这两个是示例域名,用来验证「打开网页」按钮。\n"
|
||||
"还有一个没有链接的说法:这是个普通段落。"
|
||||
)
|
||||
|
||||
res = call(f"/api/conversations/{cid}", {
|
||||
"messages": [
|
||||
{"role": "user", "content": "帮我找几个网页"},
|
||||
{"role": "assistant", "content": content},
|
||||
],
|
||||
}, method="PATCH")
|
||||
print("写入结果:", json.dumps(res, ensure_ascii=False)[:200])
|
||||
|
||||
full = call(f"/api/conversations/{cid}", method="GET").get("conversation") or {}
|
||||
msgs = full.get("messages") or []
|
||||
print("现在有", len(msgs), "条消息")
|
||||
for m in msgs:
|
||||
print(" ", m.get("role"), "|", (m.get("content") or "")[:50].replace("\n", " "))
|
||||
111
scripts/probe-seed-trace.py
Normal file
111
scripts/probe-seed-trace.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""在内核进程里逐行走一遍 _seed_tools 的逻辑,打印每个文件走哪个分支。
|
||||
|
||||
不猜了 —— 把中间量全打出来。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
|
||||
probe_src = '''
|
||||
import os, sys, json, traceback
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_trace", "description": "x",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
|
||||
def run(args):
|
||||
D = %r
|
||||
out = {}
|
||||
try:
|
||||
import doubao_entry as de
|
||||
import bundled_tool_sources as bts
|
||||
except Exception as e:
|
||||
return {"import_err": f"{type(e).__name__}: {e}"}
|
||||
|
||||
out["has_src_hash"] = hasattr(de, "_src_hash")
|
||||
if not out["has_src_hash"]:
|
||||
return {"verdict": "内核里加载的是**旧** doubao_entry(没有 _src_hash)"}
|
||||
|
||||
srcs = bts.sources()
|
||||
stamp_path = os.path.join(D, ".doubao-seed.json")
|
||||
try:
|
||||
seeded = json.load(open(stamp_path, encoding="utf-8"))
|
||||
except Exception:
|
||||
seeded = {}
|
||||
out["seeded_keys"] = list(seeded.keys())[:5]
|
||||
out["seeded_count"] = len(seeded)
|
||||
|
||||
rows = []
|
||||
for filename in de.BUNDLED_TOOL_FILES:
|
||||
source = srcs.get(filename)
|
||||
dest = os.path.join(D, filename)
|
||||
row = {"name": filename}
|
||||
row["src_present"] = bool(source)
|
||||
if not source:
|
||||
row["branch"] = "no-source"
|
||||
rows.append(row); continue
|
||||
new_hash = de._src_hash(source)
|
||||
row["new_hash"] = new_hash
|
||||
if os.path.exists(dest):
|
||||
current = open(dest, encoding="utf-8").read()
|
||||
cur_hash = de._src_hash(current)
|
||||
row["cur_hash"] = cur_hash
|
||||
row["same"] = (cur_hash == new_hash)
|
||||
row["seeded_for_it"] = seeded.get(filename)
|
||||
row["seeded_matches"] = (seeded.get(filename) == cur_hash)
|
||||
if cur_hash == new_hash:
|
||||
row["branch"] = "skip-same"
|
||||
elif seeded.get(filename) != cur_hash:
|
||||
row["branch"] = "skip-user-edited"
|
||||
else:
|
||||
row["branch"] = "OVERWRITE"
|
||||
else:
|
||||
row["branch"] = "CREATE"
|
||||
rows.append(row)
|
||||
out["rows"] = rows
|
||||
out["summary"] = {}
|
||||
for r in rows:
|
||||
out["summary"][r["branch"]] = out["summary"].get(r["branch"], 0) + 1
|
||||
return out
|
||||
''' % D
|
||||
|
||||
b64 = base64.b64encode(probe_src.encode("utf-8")).decode()
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=120):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
w = (
|
||||
"import base64,os;"
|
||||
"open(os.path.join('%s','probe_trace.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64)
|
||||
)
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
|
||||
time.sleep(1)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_trace", "args": {}}, timeout=120)
|
||||
res = (r or {}).get("result") or {}
|
||||
data = res if isinstance(res, dict) and "rows" in res else json.loads(res.get("stdout") or "{}")
|
||||
print("summary:", json.dumps(data.get("summary"), ensure_ascii=False))
|
||||
print("has_src_hash:", data.get("has_src_hash"))
|
||||
print("seeded_count:", data.get("seeded_count"), "keys:", data.get("seeded_keys"))
|
||||
print()
|
||||
for row in (data.get("rows") or []):
|
||||
print(" ", row.get("name"), "->", row.get("branch"),
|
||||
"| same=", row.get("same"), "| seeded_matches=", row.get("seeded_matches"))
|
||||
74
scripts/probe-seed-why.py
Normal file
74
scripts/probe-seed-why.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""把内嵌源码列表 + BUNDLED_TOOL_FILES + 播种日志一起打出来。"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
probe = '''
|
||||
import os, sys, json, traceback, inspect
|
||||
D = %r
|
||||
out = {}
|
||||
# 1) 内核进程里 doubao_entry 的 BUNDLED_TOOL_FILES
|
||||
mod = sys.modules.get("doubao_entry")
|
||||
if mod:
|
||||
out["BUNDLED_TOOL_FILES"] = list(getattr(mod, "BUNDLED_TOOL_FILES", []))
|
||||
out["_module_source_show_ui"] = None
|
||||
try:
|
||||
s = mod._module_source("show_ui")
|
||||
out["_module_source_show_ui"] = (len(s) if s else None)
|
||||
except Exception as e:
|
||||
out["_module_source_err"] = f"{type(e).__name__}: {e}"
|
||||
# 2) 内嵌源码的键
|
||||
try:
|
||||
import bundled_tool_sources
|
||||
srcs = bundled_tool_sources.sources()
|
||||
out["bundled_keys"] = sorted(srcs.keys())
|
||||
out["bundled_count"] = len(srcs)
|
||||
except Exception as e:
|
||||
out["bundled_err"] = f"{type(e).__name__}: {e}"
|
||||
# 3) 手动调一次 _seed_tools 看它报什么
|
||||
if mod:
|
||||
try:
|
||||
n = mod._seed_tools(D)
|
||||
out["manual_seed_wrote"] = n
|
||||
except Exception as e:
|
||||
out["manual_seed_err"] = f"{type(e).__name__}: {e}"
|
||||
out["manual_seed_tb"] = traceback.format_exc()[-800:]
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
'''
|
||||
|
||||
b64 = base64.b64encode(probe.encode("utf-8")).decode()
|
||||
w = (
|
||||
"import base64,os;"
|
||||
"open(os.path.join('%s','probe_seed.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64)
|
||||
)
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
|
||||
|
||||
# 让内核发现它(force 一下)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_seed", "args": {}}, timeout=120)
|
||||
res = (r or {}).get("result") or {}
|
||||
print(res.get("stdout") or json.dumps(r, ensure_ascii=False)[:1500])
|
||||
if res.get("stderr"):
|
||||
print("--- stderr ---")
|
||||
print(res["stderr"][-1200:])
|
||||
136
scripts/probe-send-message.py
Normal file
136
scripts/probe-send-message.py
Normal file
@@ -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("✅ 全部通过")
|
||||
84
scripts/probe-show-ui-js.py
Normal file
84
scripts/probe-show-ui-js.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""测 JS 支持和"点进去"。
|
||||
|
||||
一段同时用这两个能力的页面:
|
||||
· <script> 画 canvas 柱状图 + 动态生成按钮 + 调 Doubao.pick
|
||||
· 一个 http 链接(点进去应该能在界面里打开,顶部出现返回键)
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=180):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
HTML = """
|
||||
<h1>JS + 链接测试</h1>
|
||||
|
||||
<p>下面这根柱状图是 <b><script></b> 用 canvas 画的:</p>
|
||||
<canvas id="c" width="300" height="140" style="background:#1d1f25;border-radius:8px"></canvas>
|
||||
|
||||
<div id="btns" style="margin-top:14px"></div>
|
||||
|
||||
<p style="margin-top:14px">一个链接:<a href="https://example.com">点我进 example.com</a></p>
|
||||
|
||||
<script>
|
||||
// ① canvas 画图
|
||||
// ★ 注意:改 canvas.width/height **会清空画布**(and 重置变换)。
|
||||
// 我第一版在画完之后设了 canvas.height,结果柱子全没了 ——
|
||||
// 那是测试 HTML 自己的 bug,不是 App 的。尺寸要在画之前定好。
|
||||
var cv = document.getElementById('c'), g = cv.getContext('2d');
|
||||
cv.height = 150;
|
||||
var data = [40, 90, 60, 130, 75];
|
||||
g.fillStyle = '#4c8dff';
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
g.fillRect(20 + i * 55, 130 - data[i], 34, data[i]);
|
||||
}
|
||||
g.fillStyle = '#e8eaed';
|
||||
g.font = '12px sans-serif';
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
g.fillText('#' + (i + 1), 24 + i * 55, 146);
|
||||
}
|
||||
|
||||
// ② 动态生成按钮,用 Doubao.pick 回传(这条是 JS-only 的能力)
|
||||
var box = document.getElementById('btns');
|
||||
['低', '中', '高'].forEach(function (lv) {
|
||||
var b = document.createElement('button');
|
||||
b.textContent = '优先级:' + lv;
|
||||
b.style.cssText = 'margin:4px 8px 0 0;padding:10px 16px;border-radius:10px;'
|
||||
+ 'border:0;background:#2a2d34;color:#e8eaed;font-size:15px';
|
||||
b.onclick = function () { Doubao.pick('优先级=' + lv); };
|
||||
box.appendChild(b);
|
||||
});
|
||||
|
||||
// ③ 证明 JS 真的跑了 —— 把当前时间写进去
|
||||
var p = document.createElement('p');
|
||||
p.style.cssText = 'color:#8c939d;font-size:12px;margin-top:16px';
|
||||
p.textContent = 'JS 执行于 ' + new Date().toLocaleTimeString();
|
||||
document.body.appendChild(p);
|
||||
</script>
|
||||
"""
|
||||
|
||||
print("=== 弹一个用 JS + 带链接的界面 ===")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "JS 测试", "html": HTML},
|
||||
"conversationId": CONV,
|
||||
})
|
||||
print(json.dumps(res, ensure_ascii=False)[:300])
|
||||
82
scripts/probe-show-ui-modes.py
Normal file
82
scripts/probe-show-ui-modes.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""测 show_ui 的三种收尾方式:不等 / 等 / 不弹。
|
||||
|
||||
★ 等待模式是**阻塞**的:脚本会挂在那儿等用户在手机上点。
|
||||
所以它单独一个命令跑(另一个窗口截图 + 点按钮)。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
CONV = "c_main"
|
||||
|
||||
# 按钮故意写得很朴素(只靠骨架的 .db-btn 样式)——
|
||||
# 就是要验证"模型不写样式时,按钮是不是也明显、也能点"。
|
||||
HTML_PLAIN = """
|
||||
<h1>挑一个</h1>
|
||||
<p>下面这些是回传按钮,点了值会回到 AI 手里。</p>
|
||||
<button data-doubao-result="方案甲">方案甲</button>
|
||||
<button data-doubao-result="方案乙">方案乙</button>
|
||||
<button onclick="Doubao.sendToAi('方案丙(JS)')">方案丙(JS)</button>
|
||||
<button onclick="Doubao.close()">什么都不选,关掉</button>
|
||||
"""
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=300):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def run_show(args, label, timeout=300):
|
||||
print(f"\n--- {label} ---", flush=True)
|
||||
print(" 参数:", json.dumps(args, ensure_ascii=False)[:120], flush=True)
|
||||
t0 = time.time()
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui", "args": args, "conversationId": CONV,
|
||||
}, timeout=timeout)
|
||||
dt = time.time() - t0
|
||||
print(f" 耗时 {dt:.1f}s -> {json.dumps(res, ensure_ascii=False)[:500]}", flush=True)
|
||||
return res
|
||||
|
||||
|
||||
which = sys.argv[1] if len(sys.argv) > 1 else "nowait"
|
||||
|
||||
call("/api/settings", {"uiTools": {"enabled": True}}, "PUT")
|
||||
|
||||
if which == "nowait":
|
||||
# 不等:应该**立刻**返回(耗时接近 0)
|
||||
res = run_show({"title": "不等待", "html": HTML_PLAIN}, "wait=false(默认)")
|
||||
r = (res or {}).get("result") or {}
|
||||
if r.get("shown") and not r.get("waited"):
|
||||
print(" ✓ 立刻返回了(没等待)")
|
||||
else:
|
||||
print(" ✗ 行为不对:", r)
|
||||
|
||||
elif which == "wait":
|
||||
# 等:会挂在这儿直到用户在手机上点,或 60 秒超时
|
||||
res = run_show(
|
||||
{"title": "等待中", "html": HTML_PLAIN, "wait": True, "timeout": 60},
|
||||
"wait=true(等用户点,最多 60s)",
|
||||
)
|
||||
r = (res or {}).get("result") or {}
|
||||
print()
|
||||
if r.get("timeout"):
|
||||
print(" → 超时了(用户没点)")
|
||||
elif r.get("value"):
|
||||
print(f" ✓ 用户点了:{r['value']!r}")
|
||||
elif r.get("closed"):
|
||||
print(" ✓ 用户直接关掉了(value 是空串)")
|
||||
else:
|
||||
print(" ✗ 结果不对:", r)
|
||||
95
scripts/probe-tools-writable.py
Normal file
95
scripts/probe-tools-writable.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""直接测:那个工具目录到底能不能写、_seed_tools 报什么错。"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
probe = r'''
|
||||
import os, sys, json, traceback
|
||||
D = %r
|
||||
out = {"dir": D}
|
||||
out["isdir"] = os.path.isdir(D)
|
||||
out["writable"] = os.access(D, os.W_OK)
|
||||
# ① 直接写一个测试文件
|
||||
try:
|
||||
p = os.path.join(D, "_writetest.txt")
|
||||
with open(p, "w", encoding="utf-8") as fh:
|
||||
fh.write("hi")
|
||||
out["direct_write"] = "ok"
|
||||
os.remove(p)
|
||||
except Exception as e:
|
||||
out["direct_write"] = f"{type(e).__name__}: {e}"
|
||||
|
||||
# ② 内核认为的工具目录是哪个(paths)
|
||||
try:
|
||||
import paths
|
||||
out["paths_tools_dir"] = paths.get().tools_dir
|
||||
out["paths_work_dir"] = getattr(paths.get(), "work_dir", None)
|
||||
out["paths_data_dir"] = paths.get().data_dir
|
||||
except Exception as e:
|
||||
out["paths_err"] = f"{type(e).__name__}: {e}"
|
||||
|
||||
# ③ 手动调 _seed_tools,把异常抓全
|
||||
mod = sys.modules.get("doubao_entry")
|
||||
if mod:
|
||||
out["has_src_hash"] = hasattr(mod, "_src_hash")
|
||||
try:
|
||||
n = mod._seed_tools(D)
|
||||
out["seed_wrote"] = n
|
||||
except Exception as e:
|
||||
out["seed_err"] = f"{type(e).__name__}: {e}"
|
||||
out["seed_tb"] = traceback.format_exc()[-1200:]
|
||||
# ④ 看看 wanted 里到底有几个
|
||||
try:
|
||||
import bundled_tool_sources
|
||||
srcs = bundled_tool_sources.sources()
|
||||
out["bundled_count"] = len(srcs)
|
||||
out["bundled_names"] = sorted(srcs.keys())[:20]
|
||||
wanted = {}
|
||||
for name in mod.BUNDLED_TOOL_FILES:
|
||||
wanted[name] = mod._module_source(name[:-3])
|
||||
for k, v in srcs.items():
|
||||
wanted[k] = v
|
||||
out["wanted_nonempty"] = sum(1 for v in wanted.values() if v)
|
||||
out["wanted_total"] = len(wanted)
|
||||
except Exception as e:
|
||||
out["wanted_err"] = f"{type(e).__name__}: {e}"
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
''' % D
|
||||
|
||||
b64 = base64.b64encode(probe.encode("utf-8")).decode()
|
||||
w = (
|
||||
"import base64,os;"
|
||||
"open(os.path.join('%s','probe_perm.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64)
|
||||
)
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}}, timeout=90)
|
||||
try:
|
||||
r = call("/api/tools/run", {"name": "probe_perm", "args": {}}, timeout=120)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("调用 probe_perm 失败:", exc)
|
||||
sys.exit(1)
|
||||
res = (r or {}).get("result") or {}
|
||||
print(res.get("stdout") or json.dumps(r, ensure_ascii=False)[:2000])
|
||||
if res.get("stderr"):
|
||||
print("--- stderr ---")
|
||||
print(res["stderr"][-1500:])
|
||||
98
scripts/probe-ui-result-e2e.py
Normal file
98
scripts/probe-ui-result-e2e.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""把内核指到假模型服务上,验证"界面上选的值"真的拼进了发给模型的消息里。
|
||||
|
||||
★ 为什么要这么绕:光看"队列空了"只能证明有人取走,证明不了它被拼进请求。
|
||||
真正要验的是**模型收到的 messages 数组里有没有那段上下文**。
|
||||
所以起一个假服务,把请求原样存下来,然后直接读它。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
KERNEL = "http://127.0.0.1:15199"
|
||||
CAPTURE = r"C:\DoubaoAndroid\fake-req.json"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=120):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
KERNEL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
print("1) 把内核指到假模型服务")
|
||||
# ★ 关键:内核跑在**模拟器里**,它的 127.0.0.1 是自己,不是宿主机。
|
||||
# 两种打通方式:
|
||||
# · `adb reverse tcp:18080 tcp:18080` —— 模拟器的 18080 转到宿主机(**用这个**)
|
||||
# · 10.0.2.2 —— 只在标准 AVD 上有效,LDPlayer 不一定通
|
||||
# 实测 LDPlayer 上 `10.0.2.2` 连不上(假服务一个请求都没收到,
|
||||
# 很容易误判成代码有问题),所以用 adb reverse + 127.0.0.1。
|
||||
FAKE = "http://127.0.0.1:18080/v1"
|
||||
res = call("/api/settings", {
|
||||
"provider": "openai",
|
||||
"baseUrl": FAKE,
|
||||
"model": "fake-model",
|
||||
"apiKey": "sk-fake",
|
||||
}, method="PUT")
|
||||
st = res.get("settings") or {}
|
||||
print(" provider =", st.get("provider"), "| baseUrl =", st.get("baseUrl"),
|
||||
"| model =", st.get("model"))
|
||||
|
||||
print("\n2) 塞两个'界面上的选择'")
|
||||
for v in ("用户选了方案 B(蓝色按钮)", "用户填写了:预算 3000 元"):
|
||||
r = call("/api/ui-result", {"conversationId": CONV, "value": v})
|
||||
print(" ", v, "->", json.dumps(r, ensure_ascii=False))
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
print(" 队列:", json.dumps(q, ensure_ascii=False))
|
||||
|
||||
print("\n3) 发一句话,看模型收到什么")
|
||||
try:
|
||||
call("/api/chat", {"conversationId": CONV, "message": "我刚才在界面上选了什么?", "stream": False},
|
||||
timeout=120)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(" (内核返回不是 JSON,正常 —— 它走 SSE):", str(exc)[:80])
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
print("\n4) 假服务收到了什么")
|
||||
try:
|
||||
with open(CAPTURE, encoding="utf-8") as fh:
|
||||
cap = json.load(fh)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(" !! 读不到抓包:", exc)
|
||||
sys.exit(1)
|
||||
|
||||
msgs = (cap.get("body") or {}).get("messages") or []
|
||||
print(f" 路径 {cap.get('path')},共 {len(msgs)} 条消息")
|
||||
ok = False
|
||||
for m in msgs:
|
||||
role = m.get("role")
|
||||
content = m.get("content")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))
|
||||
text = content or ""
|
||||
mark = ""
|
||||
if "方案 B" in text or "预算 3000" in text:
|
||||
mark = " ← ★ 这就是回流进去的"
|
||||
ok = True
|
||||
print(f" [{role}] {text[:300]}{mark}")
|
||||
|
||||
print()
|
||||
if ok:
|
||||
print("✅ 界面上选的值**确实拼进了发给模型的请求**")
|
||||
else:
|
||||
print("❌ 请求里没有那些值 —— 回流链路断了")
|
||||
sys.exit(1)
|
||||
|
||||
# 收尾:把 provider 设回去,别把用户配置留在假服务上
|
||||
call("/api/settings", {"provider": "ark", "baseUrl": "", "model": "", "apiKey": ""}, method="PUT")
|
||||
print("(已把 provider 恢复成 ark)")
|
||||
115
scripts/probe-ui-result.py
Normal file
115
scripts/probe-ui-result.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""测「AI 写进网页里的接口」——用户在 AI 自己的界面里选的值能不能回到模型。
|
||||
|
||||
三步:
|
||||
1. 用 show_ui 弹一个界面,页面里有 Doubao.sendToAi / Doubao.pick / Doubao.close
|
||||
2. (手动)在手机上点那些按钮
|
||||
3. 查内核队列 —— 值应该排在那里,等下一轮对话交给模型
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
CONV = "c_main"
|
||||
|
||||
HTML = """
|
||||
<h1>接口测试</h1>
|
||||
<p>点下面的按钮,值应该会回到 AI 手里(下一轮对话时)。</p>
|
||||
|
||||
<div id="log" style="margin:12px 0;padding:10px;background:#1d1f25;border-radius:8px;
|
||||
font-size:13px;color:#8c939d">(还没点)</div>
|
||||
|
||||
<button onclick="hit('sendToAi', '方案B')"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2b7bff;color:#fff;font-size:16px">Doubao.sendToAi('方案B')</button>
|
||||
|
||||
<button onclick="hit('pick', '方案C')"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">Doubao.pick('方案C')</button>
|
||||
|
||||
<button data-doubao-result="方案D"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">data-doubao-result="方案D"(不写 JS)</button>
|
||||
|
||||
<button onclick="Doubao.close()"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#3a2a2a;color:#e8eaed;font-size:16px">Doubao.close()</button>
|
||||
|
||||
<script>
|
||||
function hit(fn, v) {
|
||||
var el = document.getElementById('log');
|
||||
try {
|
||||
Doubao[fn](v);
|
||||
el.textContent = '已调 Doubao.' + fn + '("' + v + '") —— 应该已经排队了';
|
||||
el.style.color = '#6ee787';
|
||||
} catch (e) {
|
||||
el.textContent = '调用失败:' + e;
|
||||
el.style.color = '#ff7b72';
|
||||
}
|
||||
}
|
||||
document.getElementById('log').textContent =
|
||||
'typeof Doubao = ' + (typeof Doubao);
|
||||
</script>
|
||||
"""
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=120):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
which = sys.argv[1] if len(sys.argv) > 1 else "show"
|
||||
|
||||
if which == "show":
|
||||
# 打开界面能力(否则工具被第二道拦截挡住)
|
||||
call("/api/settings", {"uiTools": {"enabled": True}}, method="PUT")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "接口测试", "html": HTML},
|
||||
"conversationId": CONV,
|
||||
})
|
||||
print("show_ui ->", json.dumps(res, ensure_ascii=False)[:200])
|
||||
print("\n现在去手机上点按钮,然后跑:")
|
||||
print(" python scripts/probe-ui-result.py check")
|
||||
print(" python scripts/probe-ui-result.py send # 发一句话,看模型能不能看到那些值")
|
||||
|
||||
elif which == "check":
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
print("队列里现在有:", json.dumps(q, ensure_ascii=False))
|
||||
n = len(q.get("pending") or [])
|
||||
print(f" {n} 条" + (" ✓ 回流成功" if n else " ✗ 一条都没有 —— 回流没成功"))
|
||||
|
||||
elif which == "send":
|
||||
# 发一句话,触发一轮对话;agent_loop 会把队列里的值带上
|
||||
#
|
||||
# ★ 不需要真的配 API key:我们要验证的是"队列有没有被取走、有没有拼进
|
||||
# 发给模型的消息里"。模型调用失败是另一回事(会以 error 事件返回),
|
||||
# 而**取队列发生在调用之前** —— 所以看队列空了就说明接上了。
|
||||
print("发一句话(触发一轮对话)…")
|
||||
try:
|
||||
res = call("/api/chat", {
|
||||
"conversationId": CONV,
|
||||
"message": "我刚才选了什么?",
|
||||
"stream": False,
|
||||
}, timeout=180)
|
||||
print(json.dumps(res, ensure_ascii=False)[:800])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("请求失败(可能是没配 API key,不影响本项验证):", exc)
|
||||
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
n = len(q.get("pending") or [])
|
||||
print("\n发完之后队列:", json.dumps(q, ensure_ascii=False))
|
||||
if n == 0:
|
||||
print(" ✓ 队列被取走了 —— 接进上下文了")
|
||||
else:
|
||||
print(f" ✗ 队列还有 {n} 条 —— 没被取走,回流链路断了")
|
||||
173
scripts/verify-ai-webview.py
Normal file
173
scripts/verify-ai-webview.py
Normal file
@@ -0,0 +1,173 @@
|
||||
"""守 AI 界面 WebView 的几条硬性质。
|
||||
|
||||
这个文件的**时序**我改了三版才对,每一版都对应一个只能实测发现的坑,
|
||||
所以必须用脚本钉住 —— 光看代码看不出"桥什么时候挂上"。
|
||||
|
||||
改过的三版(记在这儿,别再走回头路):
|
||||
|
||||
第一版:`loadDataWithBaseURL` 之前 add 桥,导航到 http(s) 时 remove。
|
||||
**问题**:外部页面在 `onPageStarted` 摘桥之前有个"已经开始加载、
|
||||
桥还在"的窗口期。
|
||||
|
||||
第二版:只在 `onPageFinished` 里判 url 是不是 `about:blank` 才 add。
|
||||
**问题**:实测页面报 `Uncaught ReferenceError: Doubao is not defined`
|
||||
—— `onPageFinished` 的回调**比页面内联 <script> 执行还晚**。
|
||||
|
||||
第三版(现在):
|
||||
· 初始 load 之前就 add(保证脚本能用到)
|
||||
· 用 `payloadLoaded` 标志挡住窗口期(导航时立刻摘)
|
||||
· 返回时靠 **页面里的标记变量** 判断"这是不是我们的页"再重挂
|
||||
(用 url 判会漏 —— 从外部页 goBack 回来时 url 不是 about:blank,
|
||||
表现是"点进去再返回,页面上的 JS 按钮全失灵")
|
||||
|
||||
用法:
|
||||
python scripts/verify-ai-webview.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SRC = os.path.join(WS, "android", "app", "src", "main", "java",
|
||||
"com", "doubao", "lynxclone", "ui", "AiSurfaces.kt")
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
if not os.path.isfile(SRC):
|
||||
print(f"!! 找不到 {SRC}")
|
||||
sys.exit(1)
|
||||
|
||||
src = open(SRC, encoding="utf-8").read()
|
||||
# ★ 只去掉**块注释**,不去行注释。
|
||||
#
|
||||
# 我第一版顺手也去了 `//...`,结果把字符串里的 `"http://"` 从中间截断 ——
|
||||
# 于是下面"http(s) 有没有被放行"那条永远判不合格。**验证脚本自己有 bug
|
||||
# 比没有验证脚本更坏**:它会让人去改本来是对的代码。
|
||||
code = re.sub(r"/\*.*?\*/", "", src, flags=re.DOTALL)
|
||||
|
||||
print("=== AI 界面 WebView 的硬性质 ===")
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] JS 开着(用户要求)")
|
||||
if "javaScriptEnabled = true" in code:
|
||||
ok("javaScriptEnabled = true")
|
||||
else:
|
||||
fail("javaScriptEnabled 不是 true —— 用户要求支持 JS")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] 危险开关仍然关着")
|
||||
for name, pat in (
|
||||
("allowFileAccess", r"allowFileAccess\s*=\s*false"),
|
||||
("allowContentAccess", r"allowContentAccess\s*=\s*false"),
|
||||
("MIXED_CONTENT_NEVER_ALLOW", r"MIXED_CONTENT_NEVER_ALLOW"),
|
||||
):
|
||||
if re.search(pat, code):
|
||||
ok(f"{name} 关着")
|
||||
else:
|
||||
fail(f"{name} 没有显式关闭/设成安全值")
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
print("\n[3] 桥的挂/摘时机(三版才改对的那段)")
|
||||
has_add = "addJavascriptInterface" in code
|
||||
has_remove = "removeJavascriptInterface" in code
|
||||
if has_add and has_remove:
|
||||
ok("有 add 也有 remove")
|
||||
else:
|
||||
fail(f"缺 add({has_add}) 或 remove({has_remove})")
|
||||
|
||||
for name, pat in (
|
||||
("payloadLoaded 标志(挡窗口期)", r"payloadLoaded"),
|
||||
("bridgeAttached 标志(避免重复 add)", r"bridgeAttached"),
|
||||
("PROBE_JS 探针(判是不是我们的页)", r"PROBE_JS"),
|
||||
):
|
||||
if re.search(pat, code):
|
||||
ok(name)
|
||||
else:
|
||||
fail(f"缺 {name}")
|
||||
|
||||
# ★ add 必须出现在 loadDataWithBaseURL **之前**(否则内联脚本先跑,桥还没挂)
|
||||
i_add = code.find("addJavascriptInterface(host,")
|
||||
i_load = code.find("loadDataWithBaseURL")
|
||||
if i_add >= 0 and i_load >= 0 and i_add < i_load:
|
||||
ok("初始 add 在 loadDataWithBaseURL 之前(内联脚本能用上桥)")
|
||||
else:
|
||||
fail("初始 add 不在 load 之前 —— 页面脚本会报 Doubao is not defined")
|
||||
|
||||
# ★ 必须在 onPageFinished 里**补挂**(load 时挂的那次可能还没生效)
|
||||
if "onPageFinished" in code and re.search(r"onPageFinished[\s\S]{0,900}?addJavascriptInterface", code):
|
||||
ok("onPageFinished 里有补挂/重挂")
|
||||
else:
|
||||
fail("onPageFinished 里没有补挂 —— 页面脚本可能拿不到桥")
|
||||
|
||||
# ★ 重挂必须走探针,不能靠 url 判
|
||||
if re.search(r"evaluateJavascript", code):
|
||||
ok("用 evaluateJavascript 探针判断(不是靠 url)")
|
||||
else:
|
||||
fail("没有探针 —— 从外部页返回后桥恢复不了")
|
||||
|
||||
# ★ evaluateJavascript 的返回是**字符串**(JSON 编码),不能按 Boolean 处理
|
||||
if re.search(r"evaluateJavascript[\s\S]{0,300}?trim\(", code) or '"1"' in code or "'1'" in code:
|
||||
ok("探针返回值按字符串处理(evaluateJavascript 回调就是字符串)")
|
||||
else:
|
||||
fail("探针返回值可能被当成 Boolean —— 那条件永远不成立")
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
print("\n[4] 链接能点进去(而不是被吃掉)")
|
||||
if re.search(r'u\.startsWith\("http://"\)', code) and re.search(r"return false", code):
|
||||
ok("http(s) 返回 false → 交给 WebView 打开")
|
||||
else:
|
||||
fail("http(s) 没有被放行 —— 用户说'弹窗可再点进去'")
|
||||
if "doubao://pick" in code and "doubao://close" in code:
|
||||
ok("两种自定义协议都拦了")
|
||||
else:
|
||||
fail("自定义协议处理不全")
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
print("\n[5] 返回键 + 返回按钮")
|
||||
if "BackHandler" in code:
|
||||
ok("有 BackHandler(先回退网页、退不了才关界面)")
|
||||
else:
|
||||
fail("没有 BackHandler")
|
||||
if "canGoBack" in code:
|
||||
ok("用 canGoBack 控制返回按钮显隐")
|
||||
else:
|
||||
fail("没有 canGoBack")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n[6] 桥只暴露必要的方法(面越小越安全)")
|
||||
methods = re.findall(r"@JavascriptInterface\s+(?:override\s+)?fun\s+(\w+)", code)
|
||||
# ★ 期望集**显式列出**,加方法必须改这里 —— 这是刻意的:
|
||||
# 不这样的话"顺手多加一个 @JavascriptInterface"就没人拦得住,而桥的暴露面
|
||||
# 正是这块最该盯的东西。
|
||||
# v2.0.37 加了 sendToAi(用户要求"AI 自己能写进网页里的接口",
|
||||
# 让界面上选的值真的回到模型手里),所以现在是三个而不是两个。
|
||||
EXPECTED = ["close", "pick", "sendToAi"]
|
||||
if sorted(methods) == sorted(EXPECTED):
|
||||
ok(f"只有 {methods}(正好是期望的三个)")
|
||||
else:
|
||||
fail(f"@JavascriptInterface 暴露了 {methods} —— 期望 {EXPECTED}。"
|
||||
"如果是**有意**加的,请同时更新这个 EXPECTED 列表并写清理由")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
131
scripts/verify-extract-urls.py
Normal file
131
scripts/verify-extract-urls.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""测 extractUrls 认不认各种 URL 写法。
|
||||
|
||||
★ 为什么值得单独一个脚本:
|
||||
用户报「操作栏里应该有『打开网页』按钮,但没显示」。
|
||||
根因是 extractUrls 只认 `](` 紧挨着的 markdown 链接,
|
||||
**裸 URL(`见 https://x.com`)这种模型最常写的形式反而漏掉** ——
|
||||
返回空 → 按钮整个不显示。
|
||||
|
||||
★ 手法:**直接从 Kotlin 源码里把正则抠出来**,用 Python 的 re 跑
|
||||
(两边正则语法基本一致)。这样测的是真代码,不是"我凭记忆重写一遍"——
|
||||
第一版这个探针就是重写的,改了 Kotlin 之后它还在报旧结果,等于没测。
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SRC = os.path.join(WS, "android", "app", "src", "main", "java",
|
||||
"com", "doubao", "lynxclone", "ui", "MarkdownText.kt")
|
||||
src = open(SRC, encoding="utf-8").read()
|
||||
|
||||
|
||||
def kotlin_regex(name: str) -> str:
|
||||
# ★ `\s*` 是必须的:源码里 `RE_MD_LINK =` 后面换行过(行太长),
|
||||
# 不加的话提取不到 —— 而报的是"找不到 RE_MD_LINK",
|
||||
# 看起来像"改了名字",其实是格式问题。
|
||||
m = re.search(rf'private val {name}\s*=\s*\n?\s*Regex\("""(.*?)"""\)', src, re.DOTALL)
|
||||
if not m:
|
||||
print(f"!! 源码里找不到 {name}")
|
||||
sys.exit(1)
|
||||
return m.group(1).strip()
|
||||
|
||||
|
||||
RE_MD = kotlin_regex("RE_MD_LINK")
|
||||
RE_BARE = kotlin_regex("RE_BARE_URL")
|
||||
|
||||
print("RE_MD_LINK =", RE_MD)
|
||||
print("RE_BARE_URL =", RE_BARE)
|
||||
print()
|
||||
|
||||
# Kotlin 的 `[^\]\n]` 在 Python 里要写成 `[^\]\n]`(一样)
|
||||
CLEAN_TAIL = "。,、;:!?)】》」』….,;:!?"
|
||||
|
||||
|
||||
def clean(raw: str) -> str:
|
||||
"""
|
||||
和 Kotlin 的 cleanUrl 等价。
|
||||
|
||||
★ 注意这里**没有**处理"成对括号保留"那条(Kotlin 里有)。
|
||||
`https://en.wikipedia.org/wiki/A_(b)` 正则已经整个吃掉、不需要补;
|
||||
Kotlin 那段是给"正则提前截断"的情况兜底的。
|
||||
测这一条时两边结果会一致,所以不影响。
|
||||
"""
|
||||
s = raw.strip().strip("<>\"'`")
|
||||
s = s.rstrip(CLEAN_TAIL)
|
||||
while s.endswith(")") and s.count(")") > s.count("("):
|
||||
s = s[:-1]
|
||||
while s.endswith("]") and s.count("]") > s.count("["):
|
||||
s = s[:-1]
|
||||
if not (s.startswith("http://") or s.startswith("https://")):
|
||||
return ""
|
||||
return s
|
||||
|
||||
|
||||
def extract(markdown: str):
|
||||
if "http://" not in markdown and "https://" not in markdown:
|
||||
return []
|
||||
out, labels = [], {}
|
||||
for m in re.finditer(RE_MD, markdown):
|
||||
label = m.group(1).strip().strip("[]")
|
||||
url = clean(m.group(2))
|
||||
if url:
|
||||
labels.setdefault(url, label)
|
||||
if url not in out:
|
||||
out.append(url)
|
||||
for m in re.finditer(RE_BARE, markdown):
|
||||
url = clean(m.group(0))
|
||||
if url and url not in out:
|
||||
out.append(url)
|
||||
return [(u, labels.get(u, "")) for u in out]
|
||||
|
||||
|
||||
CASES = [
|
||||
("标准 markdown", "[文档](https://example.com/a)", 1),
|
||||
("文字和括号之间有空格", "[文档] (https://example.com/a)", 1),
|
||||
("括号里有空格", "[文档]( https://example.com/a )", 1),
|
||||
("标题里有方括号", "[A[1]](https://example.com/a)", 1),
|
||||
("★ 裸 URL", "直接访问 https://example.com/a 就行", 1),
|
||||
("★ 中文标点紧跟", "见(https://example.com/a)。", 1),
|
||||
("★ 尖括号包裹", "<https://example.com/a>", 1),
|
||||
("★ 行尾的裸 URL", "链接是 https://example.com/a", 1),
|
||||
("★ 换行里的裸 URL", "第一行\nhttps://example.com/a\n第三行", 1),
|
||||
("多个链接", "[A](https://a.com) 和 [B](https://b.com)", 2),
|
||||
("markdown + 裸混排", "[A](https://a.com) 还有 https://b.com", 2),
|
||||
("同链接出现两次只算一个", "[A](https://a.com) 又说 https://a.com", 1),
|
||||
("中文标点不被吞进地址", "看 https://example.com/a,谢谢", 1),
|
||||
("带括号的地址", "[x](https://en.wikipedia.org/wiki/A_(b))", 1),
|
||||
("没有链接", "这段话里一个网址都没有", 0),
|
||||
("相对路径不算", "[文档](docs/x.md)", 0),
|
||||
]
|
||||
|
||||
print("=== 认得多少 ===")
|
||||
miss = 0
|
||||
for label, text, want in CASES:
|
||||
got = extract(text)
|
||||
okc = len(got) == want
|
||||
if not okc:
|
||||
miss += 1
|
||||
detail = ", ".join(f"{u}" + (f"[{l}]" if l else "") for u, l in got) or "(空)"
|
||||
print(f" {'✓' if okc else '✗'} {label:22s} 期望{want} 得到{len(got)}: {detail}")
|
||||
|
||||
# 链接文字要留住(列表里靠它区分同域名的多个链接)
|
||||
got = extract("[Example 官网](https://example.com) 和 [Example 中文](https://example.com/index-zh)")
|
||||
print()
|
||||
if len(got) == 2 and all(l for _, l in got):
|
||||
print(" ✓ 两条同域链接都拿到了各自的文字(列表里能分得清)")
|
||||
else:
|
||||
print(" ✗ 链接文字丢了:", got)
|
||||
miss += 1
|
||||
|
||||
print()
|
||||
if miss:
|
||||
print(f"❌ {miss} 项不合格")
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
227
scripts/verify-seed-tools.py
Normal file
227
scripts/verify-seed-tools.py
Normal file
@@ -0,0 +1,227 @@
|
||||
"""守"内置工具升级时会重新播种"这条性质。
|
||||
|
||||
## 为什么值得单独守
|
||||
|
||||
这里踩过一个**表现极具误导性**的真 bug:
|
||||
|
||||
`_seed_tools` 以前是 `if os.path.exists(dest): continue` —— 只写不存在的文件。
|
||||
后果:**每一次发版更新的内置工具,在老设备上一律不生效。**
|
||||
|
||||
误导在哪:代码改了、APK 重新编了、`app.imy` 里确实有新 .pyc,
|
||||
但设备上跑的还是旧那份 —— 因为内核加载的是**落盘的那份旧源码**。
|
||||
(v2.0.37 给 show_ui 加了 `wait` 参数,设备上报的 spec 里根本没这个参数,
|
||||
我一度以为是构建缓存没生效,查了一圈才发现是这个。)
|
||||
|
||||
所以这条性质必须钉住:**改了内容要覆盖,用户改过的不许覆盖。**
|
||||
|
||||
## 测试手法
|
||||
|
||||
`_seed_tools` 的源码来源是 `bundled_tool_sources`(构建时生成的)。
|
||||
电脑上没有那个文件,所以这里**塞一个假模块**进 `sys.modules` ——
|
||||
比给源码打补丁干净,而且测的就是真实那条路径。
|
||||
|
||||
用法:
|
||||
python scripts/verify-seed-tools.py
|
||||
"""
|
||||
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
KERNEL = os.path.join(WS, "android", "kernel")
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def install_fake_bundled(files: dict, shipped: dict = None) -> None:
|
||||
"""
|
||||
往 sys.modules 里塞一个假的 bundled_tool_sources。
|
||||
|
||||
★ 必须走模块这一层:`_seed_tools` 第二个来源是 `_module_source()`(读模块源码),
|
||||
在电脑上对 android/kernel 里的模块有效、对我们造的假工具无效。
|
||||
塞模块能同时喂到**两个来源**,测的就是设备上真实走的那条。
|
||||
|
||||
[shipped] 模拟"我们历史上发过的所有哈希"(tools/.shipped-hashes.json
|
||||
在构建时嵌进来的那份)。**这一条是修老设备升级问题的关键**,所以
|
||||
下面专门有一节测它。
|
||||
"""
|
||||
mod = types.ModuleType("bundled_tool_sources")
|
||||
|
||||
def sources():
|
||||
return {
|
||||
name: base64.b64decode(data).decode("utf-8")
|
||||
for name, data in files.items()
|
||||
}
|
||||
|
||||
def shipped_fn():
|
||||
return {k: list(v) for k, v in (shipped or {}).items()}
|
||||
|
||||
mod.sources = sources
|
||||
mod.shipped = shipped_fn
|
||||
sys.modules["bundled_tool_sources"] = mod
|
||||
|
||||
|
||||
def load_entry():
|
||||
sys.path.insert(0, KERNEL)
|
||||
spec = importlib.util.spec_from_file_location("dbe", os.path.join(KERNEL, "doubao_entry.py"))
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
V1 = "TOOL = {'name': 'demo'}\n# 第一版\n"
|
||||
V2 = "TOOL = {'name': 'demo'}\n# 第二版(修了 bug)\n"
|
||||
V3 = "TOOL = {'name': 'demo'}\n# 第三版\n"
|
||||
|
||||
|
||||
def b64(s):
|
||||
return base64.b64encode(s.encode("utf-8")).decode()
|
||||
|
||||
|
||||
print("=== 内置工具播种的硬性质 ===")
|
||||
|
||||
install_fake_bundled({"demo.py": b64(V1)})
|
||||
dbe = load_entry()
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="seedtest-")
|
||||
stamp = os.path.join(tmp, ".doubao-seed.json")
|
||||
path = os.path.join(tmp, "demo.py")
|
||||
|
||||
try:
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] 首次运行:写出来 + 留指纹")
|
||||
n = seed_n = dbe._seed_tools(tmp)
|
||||
exists = os.path.isfile(path)
|
||||
has_stamp = os.path.isfile(stamp)
|
||||
if n == 1 and exists and has_stamp:
|
||||
ok("写了 demo.py,也留了 .doubao-seed.json")
|
||||
else:
|
||||
fail(f"首次运行不对:n={n} 文件={exists} 指纹={has_stamp}")
|
||||
if open(path, encoding="utf-8").read() == V1:
|
||||
ok("内容是内置的那份")
|
||||
else:
|
||||
fail("内容不对")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] 再跑一次:内容没变就什么都不做(别每次动 mtime)")
|
||||
mt = os.stat(path).st_mtime_ns
|
||||
n = dbe._seed_tools(tmp)
|
||||
if n == 0 and os.stat(path).st_mtime_ns == mt:
|
||||
ok("空操作,mtime 没动")
|
||||
else:
|
||||
fail(f"第二次动了东西:n={n} mtime变了={os.stat(path).st_mtime_ns != mt}")
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
print("\n[3] ★ 我们发了新版本 → 必须覆盖(就是这么坏的)")
|
||||
install_fake_bundled({"demo.py": b64(V2)})
|
||||
dbe = load_entry() # 重新加载,让它拿到新的 bundled 源码
|
||||
n = dbe._seed_tools(tmp)
|
||||
content = open(path, encoding="utf-8").read()
|
||||
if n == 1 and content == V2:
|
||||
ok("旧版被覆盖成新版了(老设备现在能拿到更新)")
|
||||
else:
|
||||
fail(f"没覆盖:n={n},内容正确={content == V2}")
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
print("\n[4] ★ 用户自己改过 → 绝对不许覆盖")
|
||||
user_edit = V2 + "# 这是用户自己加的\n"
|
||||
open(path, "w", encoding="utf-8").write(user_edit)
|
||||
# 关键:**不动指纹文件** —— 于是"盘上内容 ≠ 我们上次写的" = 用户改过
|
||||
install_fake_bundled({"demo.py": b64(V3)})
|
||||
dbe = load_entry()
|
||||
n = dbe._seed_tools(tmp)
|
||||
content = open(path, encoding="utf-8").read()
|
||||
if n == 0 and content == user_edit:
|
||||
ok("用户改过的被保留了(用户的改动比'用上新版'重要)")
|
||||
else:
|
||||
fail(f"把用户改过的覆盖了:n={n},内容还在={'这是用户自己加的' in content}")
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
print("\n[5] 指纹文件坏了也不能崩、也不能乱覆盖")
|
||||
open(stamp, "w", encoding="utf-8").write("{ 这不是 json")
|
||||
n = dbe._seed_tools(tmp)
|
||||
content = open(path, encoding="utf-8").read()
|
||||
if content == user_edit:
|
||||
ok("坏指纹当成'用户改过'处理 —— 保守,不覆盖(没崩)")
|
||||
else:
|
||||
fail("坏指纹时把用户的文件覆盖了")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n[6] 用户删掉文件 → 补回来")
|
||||
os.remove(path)
|
||||
install_fake_bundled({"demo.py": b64(V3)})
|
||||
dbe = load_entry()
|
||||
n = dbe._seed_tools(tmp)
|
||||
if n == 1 and os.path.isfile(path) and open(path, encoding="utf-8").read() == V3:
|
||||
ok("删掉的内置工具被补回来了")
|
||||
else:
|
||||
fail(f"没补回来:n={n}")
|
||||
|
||||
# ---------------------------------------------------------------- 7
|
||||
print("\n[7] ★★★ 老设备:指纹文件是空的,但盘上是我们以前发的旧版本")
|
||||
#
|
||||
# 这是**真机上真实出现的场景**,也是第一版修复没修好的地方:
|
||||
# · 设备上装的是几个月前那版工具(旧源码)
|
||||
# · .doubao-seed.json 是空的(第一版播种逻辑从没写过它)
|
||||
# 只靠指纹判断的话,这份旧源码会被当成"用户改过" → **升级永远不生效**。
|
||||
# (实测 v2.0.37 给 show_ui 加了 wait 参数,真机上报的 spec 里就是没有。)
|
||||
#
|
||||
# 修法:构建时累积"我们历史上发过哪些哈希",靠它认出旧版本。
|
||||
fresh = tempfile.mkdtemp(prefix="seedtest2-")
|
||||
try:
|
||||
fresh_path = os.path.join(fresh, "demo.py")
|
||||
# 盘上是 V1(我们以前发的),指纹文件**不存在**
|
||||
open(fresh_path, "w", encoding="utf-8").write(V1)
|
||||
h1 = dbe._src_hash(V1)
|
||||
install_fake_bundled({"demo.py": b64(V3)}, shipped={"demo.py": [h1]})
|
||||
dbe = load_entry()
|
||||
n = dbe._seed_tools(fresh)
|
||||
content = open(fresh_path, encoding="utf-8").read()
|
||||
if n == 1 and content == V3:
|
||||
ok("靠历史哈希表认出了旧版本并覆盖(老设备能拿到更新了)")
|
||||
else:
|
||||
fail(f"旧版本没被覆盖:n={n} 内容正确={content == V3}")
|
||||
|
||||
# 8. 反过来:盘上的内容**不在**历史表里 → 一定是用户改的 → 不覆盖
|
||||
print("\n[8] ★ 盘上内容不在历史表里 → 判为用户改过 → 不覆盖")
|
||||
open(fresh_path, "w", encoding="utf-8").write(V1 + "# 用户手改的\n")
|
||||
n = dbe._seed_tools(fresh)
|
||||
content = open(fresh_path, encoding="utf-8").read()
|
||||
if n == 0 and "用户手改的" in content:
|
||||
ok("不在历史表里的改动被保留了")
|
||||
else:
|
||||
fail(f"把用户改的覆盖了:n={n}")
|
||||
finally:
|
||||
shutil.rmtree(fresh, ignore_errors=True)
|
||||
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
sys.modules.pop("bundled_tool_sources", None)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
264
scripts/verify-web-pick.py
Normal file
264
scripts/verify-web-pick.py
Normal file
@@ -0,0 +1,264 @@
|
||||
"""守「网页点选回传给 AI」这条链路的硬性质。
|
||||
|
||||
## 为什么这些性质值得钉住
|
||||
|
||||
这条链路最容易被"顺手写成不安全"的地方,就是**给外部网页挂 JS 桥**。
|
||||
看起来最省事:`addJavascriptInterface` 一下,页面里 `Doubao.pick(...)` 就完事。
|
||||
但这里浏览的是**互联网上任意一个站点** —— 挂桥等于把 App 的内部接口交出去。
|
||||
|
||||
所以这里守的第一条就是:**没有桥**,改用"页面写数组 + Kotlin 主动轮询取走",
|
||||
数据只从页面流向 App,页面**没有任何办法**主动调 App。
|
||||
|
||||
用法:
|
||||
python scripts/verify-web-pick.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
UI = os.path.join(WS, "android", "app", "src", "main", "java", "com", "doubao", "lynxclone", "ui")
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def read(name):
|
||||
p = os.path.join(UI, name)
|
||||
if not os.path.isfile(p):
|
||||
print(f"!! 找不到 {p}")
|
||||
sys.exit(1)
|
||||
# ★ 只去块注释,不去行注释 —— 行注释里常有 "http://" 之类的字符串,
|
||||
# 第一版验证脚本就是这么把自己坑了的(见 verify-ai-webview.py)。
|
||||
return re.sub(r"/\*.*?\*/", "", open(p, encoding="utf-8").read(), flags=re.DOTALL)
|
||||
|
||||
|
||||
web = read("WebPageScreen.kt")
|
||||
pick = read("WebPick.kt")
|
||||
root = read("AppRoot.kt")
|
||||
chat = read("ChatScreen.kt")
|
||||
vm = read("AppViewModel.kt")
|
||||
md = read("MarkdownText.kt")
|
||||
|
||||
print("=== 一、安全性(最重要)===")
|
||||
|
||||
# 1. 浏览外部网站的 WebView 绝不能挂桥
|
||||
#
|
||||
# ★ 判据要**排除注释**:源码里有一句"这个 WebView 里不挂任何 JS 桥",
|
||||
# 第一版直接在这份去块注释的文本里找 `addJavascriptInterface`,被那句话
|
||||
# 绊了个跟头(同一类误报在 verify-ai-webview.py 里也出过一次)。
|
||||
# 所以只看**去掉所有注释行**之后的代码。
|
||||
code_only = "\n".join(
|
||||
ln for ln in web.splitlines() if not ln.strip().startswith("//")
|
||||
)
|
||||
|
||||
if "addJavascriptInterface" in code_only:
|
||||
fail("WebPageScreen 里挂了 JavascriptInterface —— 浏览外部网站时绝不能这么干")
|
||||
else:
|
||||
ok("WebPageScreen 的代码里没有 addJavascriptInterface(外部页面碰不到 App)")
|
||||
|
||||
# ★ 判据要收窄:`Doubao` 这个名字在这份文件里到处都有
|
||||
# (`Doubao.Blue`、`doubaoText()`、`DoubaoClone` 的 UA),
|
||||
# 光找 "Doubao" 永远会红。真正该防的是**桥方法的调用**。
|
||||
bridge_call = re.search(r"Doubao\s*\.\s*(pick|close)\s*\(", code_only)
|
||||
if bridge_call:
|
||||
fail(f"外部浏览这条路上出现了桥方法调用:{bridge_call.group(0)}")
|
||||
else:
|
||||
ok("外部浏览这条路上没有桥方法调用(pick/close 都不在)")
|
||||
|
||||
# 2. 通信必须是"页面写队列 + App 主动取",而不是页面主动调
|
||||
if "evaluateJavascript" in web:
|
||||
ok("用 evaluateJavascript 主动取数据(单向)")
|
||||
else:
|
||||
fail("没有 evaluateJavascript,取不到页面数据")
|
||||
|
||||
if "DRAIN_JS" in web and "INSTALL_JS" in web:
|
||||
ok("注入脚本 + 取数脚本都在")
|
||||
else:
|
||||
fail("缺少注入或取数脚本")
|
||||
|
||||
# 3. 取数必须"取走"而不是"只读"(否则每轮询一次重复报一次)
|
||||
if "window.$QUEUE = [];" in pick or "window.__doubaoPicks = [];" in pick:
|
||||
ok("取数时清空队列(不会重复上报)")
|
||||
else:
|
||||
fail("取数没清空队列 —— 用户点一下会被重复上报十几次")
|
||||
|
||||
# 4. 危险开关仍然关着
|
||||
for name, pat in (
|
||||
("allowFileAccess", r"allowFileAccess\s*=\s*false"),
|
||||
("allowContentAccess", r"allowContentAccess\s*=\s*false"),
|
||||
("混合内容", r"MIXED_CONTENT_NEVER_ALLOW"),
|
||||
):
|
||||
if re.search(pat, web):
|
||||
ok(f"{name} 关着")
|
||||
else:
|
||||
fail(f"{name} 没关")
|
||||
|
||||
print("\n=== 二、点选脚本本身的正确性 ===")
|
||||
|
||||
# 点选要拦掉默认行为(用户是"选中"不是"跳转")
|
||||
if "preventDefault" in pick and "stopPropagation" in pick:
|
||||
ok("拦掉默认行为(点链接不会跳走)")
|
||||
else:
|
||||
fail("没拦默认行为 —— 点个链接页面就跳走了,用户来不及看选中提示")
|
||||
|
||||
# 捕获阶段
|
||||
if re.search(r"addEventListener\('click',\s*onClick,\s*true\)", pick):
|
||||
ok("用捕获阶段监听(抢在页面自己的 handler 前面)")
|
||||
else:
|
||||
fail("不是捕获阶段 —— 页面自己的点击脚本会先跑")
|
||||
|
||||
# 防重注入
|
||||
if "__doubaoPickInstalled" in pick:
|
||||
ok("防重注入(每次加载完补注不会叠监听)")
|
||||
else:
|
||||
fail("没有防重 —— 多次注入会叠出好几层监听,一次点击写多条重复记录")
|
||||
|
||||
# 字段要够模型用
|
||||
for field in ("text", "href", "tag", "path", "title", "url"):
|
||||
if f"{field}:" in pick:
|
||||
ok(f"记录了 {field}")
|
||||
break
|
||||
else:
|
||||
fail("记录里没有可用字段")
|
||||
|
||||
print("\n=== 三、用户体验 ===")
|
||||
|
||||
# 点错了要能反悔
|
||||
if "PickedElement" in web and "发给 AI" in web:
|
||||
ok("有「发给 AI / 取消」确认条(点错了不会白跑一轮模型)")
|
||||
else:
|
||||
fail("点了就直接发 —— 点错会触发一整轮模型调用,又慢又费 token")
|
||||
|
||||
# 发给 AI 要走普通发消息那条路
|
||||
if "sendExternal" in vm and "runChat" in vm:
|
||||
ok("走普通发消息那条路(会显示在对话里、能重新生成)")
|
||||
else:
|
||||
fail("不是我预想的路径")
|
||||
|
||||
if "sendExternal" in root:
|
||||
ok("AppRoot 把点选结果接到 ViewModel")
|
||||
else:
|
||||
fail("点选结果没接上")
|
||||
|
||||
print("\n=== 四、链接能被打开(用户之前问过的)===")
|
||||
|
||||
if "extractUrls" in md:
|
||||
ok("有 extractUrls(从 markdown 抽链接)")
|
||||
else:
|
||||
fail("没有 extractUrls")
|
||||
|
||||
if "打开网页" in chat:
|
||||
ok("消息下方有「打开网页」按钮(用户要求的『单独开个按钮』)")
|
||||
else:
|
||||
fail("没有「打开网页」按钮")
|
||||
|
||||
if "withLink" in md and "LinkAnnotation" in md:
|
||||
ok("正文里的链接也绑了点击(不只是按钮)")
|
||||
else:
|
||||
fail("正文链接没绑点击")
|
||||
|
||||
if "ExperimentalTextApi" in md:
|
||||
ok("withLink 做了 @OptIn(它是实验 API,不 opt-in 报的是 Unresolved reference)")
|
||||
else:
|
||||
fail("withLink 没有 @OptIn(ExperimentalTextApi) —— 编译会报 Unresolved reference")
|
||||
|
||||
print("\n=== 五、按项目约定:列表用全屏界面而不是弹窗 ===")
|
||||
|
||||
if "UrlListScreen" in web:
|
||||
ok("链接列表是独立全屏界面")
|
||||
else:
|
||||
fail("没有 UrlListScreen")
|
||||
|
||||
if "UrlChooser" in web or "UrlChooser" in root:
|
||||
fail("还在用弹窗版的 UrlChooser —— 项目约定是列表要全屏")
|
||||
else:
|
||||
ok("没有残留的弹窗版 UrlChooser")
|
||||
|
||||
print("\n=== 六、接口覆盖「选了 / 写了 / 关闭」三类 ===")
|
||||
|
||||
# 用户明确要求:接口要让 AI 知道用户"选择了什么、写了什么",还能"关闭这个网页"。
|
||||
|
||||
# 1. 写了什么(表单输入)
|
||||
if "addEventListener('input'" in pick or 'addEventListener("input"' in pick:
|
||||
ok("监听 input(能知道用户**写了什么**)")
|
||||
else:
|
||||
fail("没监听 input —— AI 拿不到用户填的内容")
|
||||
|
||||
if "kind: 'input'" in pick and "kind: 'click'" in pick:
|
||||
ok("两类记录分开了(click 是'选了'、input 是'写了')")
|
||||
else:
|
||||
fail("记录没有区分类型")
|
||||
|
||||
if "checkbox" in pick or "radio" in pick:
|
||||
ok("勾选框/单选框也认(值是'已勾选/未勾选')")
|
||||
else:
|
||||
fail("勾选框没处理")
|
||||
|
||||
# 输入事件不能拦(拦了会破坏页面的自动补全、字数统计)
|
||||
if re.search(r"addEventListener\('input',\s*onInput,\s*false\)", pick):
|
||||
ok("input 用冒泡阶段旁听,不拦页面自己的处理")
|
||||
else:
|
||||
fail("input 的处理方式不对(可能是捕获+拦截,会破坏页面功能)")
|
||||
|
||||
# 防抖:连续打字不能塞一堆重复记录
|
||||
if "setTimeout" in pick and "600" in pick:
|
||||
ok("输入做了防抖(打十个字不会塞十条记录)")
|
||||
else:
|
||||
fail("输入没防抖 —— 报告会变得没法看")
|
||||
|
||||
# 2. 多条累积
|
||||
if "buildReport" in pick:
|
||||
ok("有 buildReport(多条汇总成一段给模型的话)")
|
||||
else:
|
||||
fail("没有汇总函数 —— 用户选五处就得发五次")
|
||||
|
||||
if "mutableStateListOf<PickedElement>" in web:
|
||||
ok("界面侧用列表累积多条")
|
||||
else:
|
||||
fail("界面侧只存了一条")
|
||||
|
||||
# 3. 关闭这个网页
|
||||
if "closeWebPage" in vm:
|
||||
ok("有 closeWebPage(接口能关闭这个网页)")
|
||||
else:
|
||||
fail("没有关闭网页的入口")
|
||||
|
||||
if "onClose = { vm.closeWebPage() }" in root:
|
||||
ok("网页界面接上了关闭")
|
||||
else:
|
||||
fail("关闭没接上")
|
||||
|
||||
# 4. 我们自己的 HTML 页面(show_ui)那边能关闭 + 回传
|
||||
#
|
||||
# ★ 只查 "Doubao.close"(不带括号):那个字符串在 py 源码里是
|
||||
# `"\n 也可以用 Doubao.close() 关掉界面。"` 的形式,
|
||||
# `)` 后面紧跟的是 `\`,查带括号的完整串会因为转义而对不上。
|
||||
# (这是这个验证脚本第三次自己绊自己了,记一笔。)
|
||||
show_ui_src = open(os.path.join(WS, "tools", "show_ui.py"), encoding="utf-8").read()
|
||||
if "Doubao.close" in show_ui_src and "Doubao.pick" in show_ui_src:
|
||||
ok("show_ui 的说明里告诉模型能关界面、能回传(Doubao.close / Doubao.pick)")
|
||||
else:
|
||||
fail("show_ui 的说明里没告诉模型能关界面或回传")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
@@ -364,16 +364,35 @@ export function readSettings() {
|
||||
}
|
||||
|
||||
export function writeSettings(patch) {
|
||||
const clean = { ...patch };
|
||||
// ★★ 显式的"清除"通路:值传 null 就是"我要把它清掉"。
|
||||
//
|
||||
// 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是
|
||||
// "前端草稿没初始化好,一次保存清空整份配置"),但代价是
|
||||
// **用户永远清不掉自定义 Base URL / 模型名** ——
|
||||
// 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||||
// (在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认,
|
||||
// 传空串怎么也改不掉。)
|
||||
//
|
||||
// 空串 = "没填、别动",null = "确实要清掉"。两者语义不同。
|
||||
const explicitClear = new Set(
|
||||
Object.entries(patch).filter(([, v]) => v === null).map(([k]) => k)
|
||||
);
|
||||
for (const key of explicitClear) delete clean[key];
|
||||
// ★ 保险:空的关键字段一律当"没填",不许用它覆盖已有配置。
|
||||
// 这些字段在正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
// 前端曾经因为草稿没同步好就全量下发,一次保存把整份配置清空。
|
||||
// systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求,用户可能真想清掉。
|
||||
const clean = { ...patch };
|
||||
for (const key of ['baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel']) {
|
||||
if (typeof clean[key] === 'string' && clean[key].trim() === '') delete clean[key];
|
||||
}
|
||||
const current = readSettings();
|
||||
const next = { ...current, ...clean };
|
||||
// 显式清除的落到默认值上(留着旧值不对;变成空串也不对 ——
|
||||
// 那会让"用哪个 provider 的默认 baseUrl"这套逻辑失效)
|
||||
for (const key of explicitClear) {
|
||||
next[key] = DEFAULT_SETTINGS[key] ?? '';
|
||||
}
|
||||
// 子对象深合并:整体替换会把没提到的开关抹掉。
|
||||
// ★ 不是对象的直接丢掉:上游要是把嵌套对象发成了字符串(JSON 序列化踩坑),
|
||||
// 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||
|
||||
61
tools/.shipped-hashes.json
Normal file
61
tools/.shipped-hashes.json
Normal file
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"_mcp_python_example.py": [
|
||||
"74a279c17b1af512"
|
||||
],
|
||||
"_protocol.py": [
|
||||
"e289048324c38899"
|
||||
],
|
||||
"_ui_bridge.py": [
|
||||
"048c7685991715fb"
|
||||
],
|
||||
"ask_user.py": [
|
||||
"94a9734c8c934db2"
|
||||
],
|
||||
"calc.py": [
|
||||
"4d9e5a51ad8f71eb"
|
||||
],
|
||||
"end_conversation.py": [
|
||||
"b03b5b99dbd83587"
|
||||
],
|
||||
"notes.py": [
|
||||
"f2255c693b2401b5",
|
||||
"7da481daace71368"
|
||||
],
|
||||
"now.py": [
|
||||
"eb0c37b5afc1dd8b"
|
||||
],
|
||||
"python_run.py": [
|
||||
"ca82671140ada806"
|
||||
],
|
||||
"shell.py": [
|
||||
"932c45a5881ba59c"
|
||||
],
|
||||
"show_ui.py": [
|
||||
"1882a766fe0ee833",
|
||||
"6f3ce8a4c924dfdd",
|
||||
"ecea108ef1118386",
|
||||
"f80e4da69db41722",
|
||||
"5f11cf92d2a78ce1"
|
||||
],
|
||||
"weather.py": [
|
||||
"bff69719c190d3d9"
|
||||
],
|
||||
"web_fetch.py": [
|
||||
"7aaf278c29b1429a"
|
||||
],
|
||||
"web_search.py": [
|
||||
"3f999cc4ccbc64a9"
|
||||
],
|
||||
"send_message.py": [
|
||||
"f133c98b6325f3ac"
|
||||
],
|
||||
"apps.py": [
|
||||
"7215ae7bc60f6f83"
|
||||
],
|
||||
"notifications.py": [
|
||||
"3e8ba8ae55b80019"
|
||||
],
|
||||
"volume.py": [
|
||||
"255939a9c89f51a2"
|
||||
]
|
||||
}
|
||||
113
tools/apps.py
Normal file
113
tools/apps.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""打开手机上的 App。
|
||||
|
||||
## 两段式:先找、再开
|
||||
|
||||
`action=find` 按名字找(返回包名 + Activity)
|
||||
`action=open` 直接开。可以传 `name`(模糊匹配,一次搞定),
|
||||
也可以传 `package` + `activity`(从上一步 find 拿到的,更准)
|
||||
|
||||
★ 为什么 `open` 也支持只传 name:
|
||||
大多数情况模型就是想说"打开微信",让它先 find 再 open 是两次工具调用、
|
||||
多一轮往返。直接开,找不到时错误信息里**带上相近的名字**,
|
||||
它就能自己改一个再试 —— 比回一句干巴巴的"失败"有用得多。
|
||||
|
||||
## ★ 名字必须模糊匹配
|
||||
|
||||
用户说"打开抖音",但 App 列表里的名字可能是"抖音"、"抖音极速版"。
|
||||
模型说"打开微信",列表里是"WeChat"(有些 ROM 的英文名)。
|
||||
所以匹配顺序是:包名完全相同 → 名字完全相同 → 名字前缀 → 包含 → 包名包含。
|
||||
"""
|
||||
|
||||
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 # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "apps",
|
||||
"description": (
|
||||
"打开手机上的 App,或列出装了哪些 App。"
|
||||
"\n\n用法:"
|
||||
"\n· action=open(默认)—— 打开一个 App。传 name(名字,模糊匹配即可,"
|
||||
"比如「微信」「抖音」);或者传 package + activity(更准,从上一步 find 拿到的)。"
|
||||
"\n· action=find —— 按名字找,返回匹配到的 App(名字 + 包名)"
|
||||
"\n· action=list —— 列出装了的 App。传 query 过滤(不传就列一部分)"
|
||||
"\n\n★ 找不到时错误里会带相近的名字,照着改一个再试,别反复用同一个错名字。"
|
||||
"\n★ 打开 App 会让它**跑到前台盖住当前画面**,所以只在用户明确要求时才用。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["open", "find", "list"],
|
||||
"description": "要做的事,默认 open",
|
||||
},
|
||||
"name": {"type": "string", "description": "App 名字(模糊匹配),open/find 用"},
|
||||
"package": {"type": "string", "description": "包名,如 com.tencent.mm(更准)"},
|
||||
"activity": {"type": "string", "description": "Activity 全名,配合 package 用"},
|
||||
"query": {"type": "string", "description": "action=list 时的过滤词"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "open").strip().lower()
|
||||
|
||||
if action == "list":
|
||||
res = call_device({"action": "apps", "query": str(args.get("query") or "")})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"total_installed": res.get("count", 0),
|
||||
"shown": len(res.get("apps") or []),
|
||||
"apps": res.get("apps") or [],
|
||||
}
|
||||
|
||||
if action == "find":
|
||||
name = str(args.get("name") or "").strip()
|
||||
if not name:
|
||||
raise ValueError("find 需要 name")
|
||||
# 列表接口支持过滤,直接用它
|
||||
res = call_device({"action": "apps", "query": name})
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
apps = res.get("apps") or []
|
||||
if not apps:
|
||||
return {"found": 0, "note": f"没有名字或包名含「{name}」的 App"}
|
||||
return {"found": len(apps), "apps": apps}
|
||||
|
||||
# open
|
||||
payload = {
|
||||
"action": "app_launch",
|
||||
"name": str(args.get("name") or "").strip(),
|
||||
"package": str(args.get("package") or "").strip(),
|
||||
"activity": str(args.get("activity") or "").strip(),
|
||||
}
|
||||
if not payload["name"] and not payload["package"]:
|
||||
raise ValueError("open 至少需要 name 或 package")
|
||||
|
||||
res = call_device(payload)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
# ★ 把 hint(相近的名字)一起抛出去 —— 模型据此改一个再试,
|
||||
# 比只回"失败"有用得多
|
||||
hint = res.get("hint") or ""
|
||||
raise RuntimeError(f"{res['error']}。{hint}".strip())
|
||||
|
||||
return {
|
||||
"opened": True,
|
||||
"app": res.get("label") or payload["name"] or payload["package"],
|
||||
"package": res.get("package") or payload["package"],
|
||||
"note": "App 已经切到前台了。",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
120
tools/notes.py
120
tools/notes.py
@@ -1,19 +1,106 @@
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。"""
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。
|
||||
|
||||
## ★ 笔记存哪儿(改过一次,很重要)
|
||||
|
||||
以前是 `工具文件/../data/notes` —— **相对工具自己算的**。
|
||||
在安卓上工具落在 `/storage/emulated/0/Android/data/<包名>/files/tools/`,
|
||||
于是笔记写到 `.../files/data/notes`:**App 的外部私有目录**。
|
||||
那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
|
||||
而且**卸载 App 就一起删了**。
|
||||
|
||||
用户的原话是"notes 用户要能查看",所以现在:
|
||||
|
||||
1. 优先用内核给的路径(`paths.get().notes_dir` = `<数据目录>/notes`),
|
||||
和 conversations / screens 那些放一起,位置统一、持久
|
||||
2. **自动把老位置的文件搬过来**(只搬一次,搬完留个 `.migrated` 标记),
|
||||
不然用户以前记的笔记就"不见了"
|
||||
3. 电脑端没有内核的 paths 模块时,退回老算法(那边本来就是 repo 里的 tools/ 下)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
NOTES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
# 老位置:工具文件旁边的 ../data/notes(安卓上会落到 App 外部私有目录)
|
||||
_LEGACY_DIR = os.path.abspath(
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
)
|
||||
|
||||
|
||||
def notes_dir() -> str:
|
||||
"""
|
||||
笔记目录。
|
||||
|
||||
★ 每次调用现算,不在模块顶层算成常量 —— 内核的 paths 是运行时初始化的,
|
||||
顶层算会拿到还没配置好的默认值(那个默认值在安卓上是相对路径)。
|
||||
"""
|
||||
try:
|
||||
import paths # noqa: PLC0415 - 电脑端没有这个模块
|
||||
|
||||
d = paths.get().notes_dir
|
||||
if d:
|
||||
return d
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return _LEGACY_DIR
|
||||
|
||||
|
||||
def _migrate_once(target: str) -> None:
|
||||
"""
|
||||
把老位置的笔记搬到新位置(只做一次)。
|
||||
|
||||
★ 为什么必须搬:用户在老版本里记的笔记是真实数据 ——
|
||||
换了目录之后那些文件还在老地方躺着,但 list/read 都看不到了,
|
||||
表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。
|
||||
"""
|
||||
if os.path.abspath(target) == _LEGACY_DIR:
|
||||
return # 本来就是老位置(电脑端),不用搬
|
||||
marker = os.path.join(target, ".migrated")
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
try:
|
||||
os.makedirs(target, exist_ok=True)
|
||||
if os.path.isdir(_LEGACY_DIR):
|
||||
moved = 0
|
||||
for name in os.listdir(_LEGACY_DIR):
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
src = os.path.join(_LEGACY_DIR, name)
|
||||
dst = os.path.join(target, name)
|
||||
if os.path.exists(dst):
|
||||
continue # 不覆盖同名的(新位置已有)
|
||||
try:
|
||||
shutil.move(src, dst)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
# 跨设备 move 可能失败,退回复制
|
||||
try:
|
||||
shutil.copy2(src, dst)
|
||||
os.remove(src)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if moved:
|
||||
print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True)
|
||||
with open(marker, "w", encoding="utf-8") as fh:
|
||||
fh.write("ok\n")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[notes] 迁移失败:{exc}', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
TOOL = {
|
||||
"name": "notes",
|
||||
"description": "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,action=search 关键词搜索。适合记录用户偏好、待办、结论。",
|
||||
"description": (
|
||||
"本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,"
|
||||
"action=search 关键词搜索。适合记录用户偏好、待办、结论。"
|
||||
"\n★ 用户能在 App 里「笔记」页面看到、也能删,所以别往里写不该让他看到的内部草稿。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -28,7 +115,10 @@ TOOL = {
|
||||
|
||||
|
||||
def ensure_dir():
|
||||
os.makedirs(NOTES_DIR, exist_ok=True)
|
||||
d = notes_dir()
|
||||
os.makedirs(d, exist_ok=True)
|
||||
_migrate_once(d)
|
||||
return d
|
||||
|
||||
|
||||
def slug(title):
|
||||
@@ -37,35 +127,37 @@ def slug(title):
|
||||
|
||||
|
||||
def run(args):
|
||||
ensure_dir()
|
||||
d = ensure_dir()
|
||||
action = str(args.get("action", "list")).lower()
|
||||
|
||||
if action == "save":
|
||||
title = str(args.get("title", "")).strip() or "未命名"
|
||||
content = str(args.get("content", ""))
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
path = os.path.join(NOTES_DIR, f"{stamp}-{slug(title)}.md")
|
||||
path = os.path.join(d, f"{stamp}-{slug(title)}.md")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(f"# {title}\n\n{content}\n")
|
||||
return {"saved": os.path.basename(path), "title": title, "chars": len(content)}
|
||||
|
||||
if action == "list":
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
files = sorted(os.listdir(d), reverse=True)
|
||||
items = []
|
||||
for name in files[:50]:
|
||||
full = os.path.join(NOTES_DIR, name)
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
full = os.path.join(d, name)
|
||||
with open(full, encoding="utf-8") as fh:
|
||||
first = fh.readline().strip().lstrip("# ")
|
||||
items.append({"file": name, "title": first, "bytes": os.path.getsize(full)})
|
||||
return {"count": len(files), "notes": items}
|
||||
return {"count": len([f for f in files if f.endswith(".md")]), "notes": items}
|
||||
|
||||
if action == "read":
|
||||
name = str(args.get("title") or args.get("query") or "").strip()
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
files = [f for f in sorted(os.listdir(d), reverse=True) if f.endswith(".md")]
|
||||
hit = next((f for f in files if name and name in f), None)
|
||||
if not hit:
|
||||
return {"ok": False, "error": f"没找到匹配 {name} 的笔记"}
|
||||
with open(os.path.join(NOTES_DIR, hit), encoding="utf-8") as fh:
|
||||
with open(os.path.join(d, hit), encoding="utf-8") as fh:
|
||||
return {"file": hit, "content": fh.read()[:4000]}
|
||||
|
||||
if action == "search":
|
||||
@@ -73,8 +165,10 @@ def run(args):
|
||||
if not query:
|
||||
raise ValueError("search 需要 query")
|
||||
hits = []
|
||||
for name in sorted(os.listdir(NOTES_DIR), reverse=True):
|
||||
with open(os.path.join(NOTES_DIR, name), encoding="utf-8") as fh:
|
||||
for name in sorted(os.listdir(d), reverse=True):
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
with open(os.path.join(d, name), encoding="utf-8") as fh:
|
||||
text = fh.read()
|
||||
if query in text:
|
||||
idx = text.index(query)
|
||||
|
||||
156
tools/notifications.py
Normal file
156
tools/notifications.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""读手机上的通知。
|
||||
|
||||
## 这是三个"动手机"的工具之一(另两个:开 App、调音量)
|
||||
|
||||
## ★ 隐私:读到的内容可能很敏感
|
||||
|
||||
通知里有验证码、银行短信、私信 —— 这是**整个 App 里最隐私的一类数据**。
|
||||
所以:
|
||||
|
||||
· 只在**内存**里留最近 200 条,不落盘(进程一死就没了)。
|
||||
写磁盘意味着卸载前一直躺着,也可能被别的工具读到。
|
||||
· 用户要在系统设置里**手动开"通知使用权"**才能读到。
|
||||
Android 没有这个权限的运行时申请弹窗 —— 这是唯一合法的路。
|
||||
· 读之前一定先查权限,没开就**明确报错**(见下)。
|
||||
|
||||
## ★ 权限没开时返回错误,不是空列表
|
||||
|
||||
返回空列表的话模型会说"你最近没有通知" —— 那是**错的**
|
||||
(明明有好几条,只是我们读不到)。用户会被误导,
|
||||
而且他不会想到"原来是要去开个权限"。
|
||||
|
||||
所以这里返回一个带 `hint` 的错误,模型就能照着告诉用户怎么开。
|
||||
"""
|
||||
|
||||
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 # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "notifications",
|
||||
"description": (
|
||||
"读手机上的通知(最近收到的、以及已经被划掉的)。"
|
||||
"\n\n用法:"
|
||||
"\n· action=list(默认)—— 列出最近的通知。"
|
||||
"query 可以按关键词过滤(标题/正文/App 名),limit 默认 20、最多 200。"
|
||||
"\n· action=alive —— 只看**还挂在通知栏上**的(已经被用户划掉的不算)"
|
||||
"\n· action=access —— 查有没有「通知使用权」"
|
||||
"\n· action=open_settings —— 跳到系统的通知使用权设置页,让用户去开"
|
||||
"\n· action=clear —— 把已经读到的记录清掉(内存里那份)"
|
||||
"\n\n★ 第一次用之前用户必须先手动开「通知使用权」(安卓不给运行时申请)。"
|
||||
"\n 没开的时候本工具会返回错误 + 怎么开的提示 —— 请照着念给用户,"
|
||||
"\n 别自己编步骤。开了之后才能读到东西。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["list", "alive", "access", "open_settings", "clear"],
|
||||
"description": "要做的事,默认 list",
|
||||
},
|
||||
"query": {"type": "string", "description": "按关键词过滤(可选)"},
|
||||
"limit": {"type": "number", "description": "最多几条,默认 20,最多 200"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "list").strip().lower()
|
||||
|
||||
if action == "open_settings":
|
||||
res = call_device({"action": "notification_settings"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"opened": True,
|
||||
"note": (
|
||||
"已经跳到系统的「通知使用权」设置页。"
|
||||
"请让用户在那里找到本 App 并打开开关 —— 开了之后我才能读到通知。"
|
||||
),
|
||||
}
|
||||
|
||||
if action == "access":
|
||||
res = call_device({"action": "notification_access"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
granted = bool(res.get("granted"))
|
||||
out = {"granted": granted, "kept": res.get("kept", 0)}
|
||||
if not granted:
|
||||
out["note"] = (
|
||||
"还没开「通知使用权」,读不到任何通知。"
|
||||
"让用户去 设置 → 通知 → 通知使用权 里打开本 App(我也可以调 "
|
||||
"action=open_settings 直接跳过去)。"
|
||||
)
|
||||
return out
|
||||
|
||||
if action == "clear":
|
||||
res = call_device({"action": "notification_clear"})
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {"cleared": True}
|
||||
|
||||
# list / alive
|
||||
payload = {
|
||||
"action": "notifications",
|
||||
"query": str(args.get("query") or ""),
|
||||
"onlyAlive": action == "alive",
|
||||
}
|
||||
try:
|
||||
limit = int(args.get("limit") or 20)
|
||||
except (TypeError, ValueError):
|
||||
limit = 20
|
||||
payload["limit"] = max(1, min(200, limit))
|
||||
|
||||
res = call_device(payload)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
|
||||
# ★ 权限没开:把错误和"怎么开"一起抛回去。
|
||||
# 抛异常而不是返回空列表 —— 空列表会让模型说"你没有通知",那是错的。
|
||||
if res.get("error"):
|
||||
hint = res.get("hint") or ""
|
||||
raise RuntimeError(f"{res['error']}。{hint}".strip())
|
||||
|
||||
items = res.get("notifications") or []
|
||||
# 顺手整理成模型好读的形状:把时间戳变成"几分钟前"
|
||||
simplified = []
|
||||
import time
|
||||
now_ms = int(time.time() * 1000)
|
||||
for n in items:
|
||||
at = int(n.get("at") or 0)
|
||||
ago = ""
|
||||
if at:
|
||||
secs = max(0, (now_ms - at) // 1000)
|
||||
if secs < 60:
|
||||
ago = "刚刚"
|
||||
elif secs < 3600:
|
||||
ago = f"{secs // 60} 分钟前"
|
||||
elif secs < 86400:
|
||||
ago = f"{secs // 3600} 小时前"
|
||||
else:
|
||||
ago = f"{secs // 86400} 天前"
|
||||
simplified.append({
|
||||
"app": n.get("app") or n.get("package") or "",
|
||||
"title": n.get("title") or "",
|
||||
"text": n.get("text") or "",
|
||||
"ago": ago,
|
||||
# 已经被划掉的也留着 —— 用户问"刚才那条验证码呢"时它早就没了
|
||||
"gone": bool(n.get("removed")),
|
||||
})
|
||||
|
||||
return {
|
||||
"count": len(simplified),
|
||||
"only_alive": action == "alive",
|
||||
"notifications": simplified,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
151
tools/send_message.py
Normal file
151
tools/send_message.py
Normal file
@@ -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)
|
||||
125
tools/show_ui.py
125
tools/show_ui.py
@@ -32,13 +32,36 @@ from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||
TOOL = {
|
||||
"name": "show_ui",
|
||||
"description": (
|
||||
"在用户手机/平板上弹出一个界面,自己写 HTML 渲染(全屏 WebView)。"
|
||||
"在用户手机/平板上弹出一个界面,自己写 HTML 渲染(全屏 WebView,**支持 JavaScript**)。"
|
||||
"适合:图表、排版好的报告卡片、对比表、可点的菜单、任何用文字说不清的东西。"
|
||||
"html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
|
||||
"\n\n用法:"
|
||||
"\n· html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
|
||||
"想完全控制就传 full_html=true。"
|
||||
"界面里可以放 <button data-doubao-result=\"值\">文字</button>,"
|
||||
"用户点了之后那个值会回到你手里。"
|
||||
"调用后界面立刻显示、本工具立刻返回,用户看到之后再继续对话。"
|
||||
"\n· **可以用 <script>**:canvas 画图、SVG 动画、算完再渲染都行。"
|
||||
"\n· 用户的选择会回到你手里 —— 页面里调:"
|
||||
"\n Doubao.sendToAi('值') 或 Doubao.pick('值') → 回传值给你"
|
||||
"\n Doubao.close() → 关掉这个界面"
|
||||
"\n 也可以不写 JS,直接放按钮:"
|
||||
"\n <button data-doubao-result=\"值\">文字</button>"
|
||||
"\n· 普通链接(http/https)**在界面里打开**,用户可以点进去看,顶部有返回键。"
|
||||
"\n"
|
||||
"\n★★ **三种收尾方式,按需要选**(这是这个工具最重要的一个参数):"
|
||||
"\n"
|
||||
"\n wait=false(默认)—— 不等,弹出就继续。适合图表、报告这类"
|
||||
"\n \"给用户看\"的东西。用户看完自己关,你这一轮已经答完了。"
|
||||
"\n 用户后来说话时,你能看到他在界面上点过什么(会作为上下文附给你)。"
|
||||
"\n"
|
||||
"\n wait=true —— **等用户操作**(点回传按钮或关掉界面,最多 timeout 秒)。"
|
||||
"\n 适合\"弹出几个选项让用户挑,然后我接着干\"。用户点了什么会**立刻**"
|
||||
"\n 作为本工具的返回值给你,你能在**同一个回合里**继续处理。"
|
||||
"\n 用户直接关掉界面(没点任何按钮)时返回 value=空串、closed=true。"
|
||||
"\n 超时返回 timeout=true —— 那就当作用户没理你,正常收尾就行。"
|
||||
"\n"
|
||||
"\n 也可以**什么都不做**:不弹界面,直接文字回答。"
|
||||
"\n"
|
||||
"\n★ 要放让用户点的按钮时,把按钮做得**明显**:"
|
||||
"\n 深色底 + 亮色字(或亮色底 + 深色字),padding 至少 14px、字号至少 16px。"
|
||||
"\n 纯文字当按钮、或者暗底暗字,用户根本看不出那儿能点。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
@@ -55,6 +78,17 @@ TOOL = {
|
||||
"type": "boolean",
|
||||
"description": "true 表示 html 是一份完整文档,不再套骨架。默认 false",
|
||||
},
|
||||
"wait": {
|
||||
"type": "boolean",
|
||||
"description": (
|
||||
"false(默认)弹出就返回,不等用户;"
|
||||
"true 等用户点回传按钮或关掉界面再返回(最多 timeout 秒)"
|
||||
),
|
||||
},
|
||||
"timeout": {
|
||||
"type": "number",
|
||||
"description": "wait=true 时最多等多少秒,默认 120,最大 600",
|
||||
},
|
||||
},
|
||||
"required": ["html"],
|
||||
},
|
||||
@@ -65,24 +99,77 @@ 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(),
|
||||
}
|
||||
)
|
||||
|
||||
wait = bool(args.get("wait"))
|
||||
# 上限 600 秒:再长的话内核工作线程被占住太久(HTTP 是每请求一线程)。
|
||||
# 下限 5 秒:低于这个值用户根本来不及看清界面就被判超时了。
|
||||
try:
|
||||
timeout = float(args.get("timeout") or 120)
|
||||
except (TypeError, ValueError):
|
||||
timeout = 120.0
|
||||
timeout = max(5.0, min(600.0, timeout))
|
||||
|
||||
payload = {
|
||||
"action": "ui_screen",
|
||||
"html": html,
|
||||
"title": str(args.get("title") or ""),
|
||||
"full_html": bool(args.get("full_html")),
|
||||
"conversationId": conversation_id(),
|
||||
"wait": wait,
|
||||
}
|
||||
if wait:
|
||||
payload["timeoutMs"] = int(timeout * 1000)
|
||||
|
||||
res = call_device(payload)
|
||||
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": "界面已弹出,用户看完会自己关掉。你不需要再重复内容。",
|
||||
}
|
||||
|
||||
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:
|
||||
# 不等待:这一轮就到此为止。用户之后说话时,他在界面上点过什么
|
||||
# 会作为上下文附给模型(内核的待交付队列),所以这里如实说明。
|
||||
out["note"] = (
|
||||
"界面已弹出,你没有等用户。用户看完会自己关掉;"
|
||||
"他在界面上点过什么,等他下次说话时会作为上下文给你。"
|
||||
"现在可以正常收尾这一轮了。"
|
||||
"(这个界面已经存下来了,用户随时能再打开,不用你再生成一遍。)"
|
||||
)
|
||||
return out
|
||||
|
||||
# ---- 等待模式:用户点了什么 / 关掉了 / 超时 ----
|
||||
out["waited"] = True
|
||||
out["timeout"] = bool(res.get("timeout"))
|
||||
out["closed"] = bool(res.get("closed"))
|
||||
value = str(res.get("value") or "")
|
||||
out["value"] = value
|
||||
|
||||
if out["timeout"]:
|
||||
out["note"] = (
|
||||
f"等了 {timeout:.0f} 秒用户也没操作,界面已收起。"
|
||||
"当作用户暂时没空处理,别反复重弹 —— 正常收尾,等他自己来说。"
|
||||
)
|
||||
elif value:
|
||||
out["note"] = (
|
||||
"用户点了这个。**现在就按这个值继续处理**,不用再问一遍、也不用重复界面内容。"
|
||||
)
|
||||
else:
|
||||
out["note"] = (
|
||||
"用户没点任何按钮,直接把界面关掉了。"
|
||||
"通常表示他不想选 / 想自己说 —— 别重弹同一个界面,用一句话收尾就行。"
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
147
tools/volume.py
Normal file
147
tools/volume.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""调手机音量。
|
||||
|
||||
## 六种音量流分开调
|
||||
|
||||
媒体(music) / 铃声(ring) / 闹钟(alarm) / 通话(call) / 系统(system) / 通知(notification)
|
||||
|
||||
安卓把它们**分开**的 —— "把声音调小"到底指哪个?媒体和铃声是两回事。
|
||||
所以这个工具要求指定 stream(默认 music,最常用那个)。
|
||||
|
||||
## ★ 改完必须回读确认
|
||||
|
||||
勿扰模式(DND)开着的时候,系统会**拒绝**改铃声/通知音量,而且**不报错** ——
|
||||
静默失败。所以这里改完立刻回读,不一致就如实说"系统没接受这次调整"。
|
||||
|
||||
不回读的话,模型会告诉用户"已经调好了",而用户发现根本没变 ——
|
||||
比直接说"没调成"糟得多。
|
||||
|
||||
## 两种表达方式都给
|
||||
|
||||
· 想"调到一半" → mode=set + value=50(按百分比)
|
||||
· 想"加一格" → mode=up(按原始档位)
|
||||
|
||||
value 在 set 时是百分比,在 up/down 时是步数 —— 这个区别写在参数说明里了,
|
||||
因为搞混的话"加 1"会变成"加到 1%"。
|
||||
"""
|
||||
|
||||
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 # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "volume",
|
||||
"description": (
|
||||
"读或调手机音量。"
|
||||
"\n\n· action=get(默认)—— 读所有音量流的当前值"
|
||||
"\n· action=set —— 调整。用 stream 指定调哪个,mode 指定怎么调:"
|
||||
"\n stream: music(媒体,默认)/ ring(铃声)/ alarm(闹钟)/ "
|
||||
"call(通话)/ system / notification"
|
||||
"\n mode: set(设成某个值)/ up(加)/ down(减)/ mute(静音)/ unmute(取消静音)"
|
||||
"\n value: mode=set 时是**百分比 0-100**;mode=up/down 时是**档数**(默认 1)"
|
||||
"\n\n★ 安卓把媒体音量和铃声音量**分开**的 —— 用户说'把声音调小'时,"
|
||||
"\n 先想清楚他说的是哪个;拿不准就调 music 并说一句你调的是媒体音量。"
|
||||
"\n★ 勿扰模式开着时系统会拒绝改铃声/通知音量,这时候会明确告诉你没改成功。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["get", "set"],
|
||||
"description": "要做的事,默认 get",
|
||||
},
|
||||
"stream": {
|
||||
"type": "string",
|
||||
"enum": ["music", "ring", "alarm", "call", "system", "notification"],
|
||||
"description": "调哪个音量流,默认 music",
|
||||
},
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": ["set", "up", "down", "mute", "unmute"],
|
||||
"description": "怎么调,默认 set",
|
||||
},
|
||||
"value": {
|
||||
"type": "number",
|
||||
"description": "mode=set 时是百分比(0-100);mode=up/down 时是档数(默认1)",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "get").strip().lower()
|
||||
|
||||
if action == "get":
|
||||
res = call_device({"action": "volume"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
state = res.get("state") or {}
|
||||
streams = state.get("streams") or []
|
||||
# 整理成模型好读的形状:一行一个流
|
||||
out = []
|
||||
for s in streams:
|
||||
out.append({
|
||||
"stream": s.get("stream"),
|
||||
"percent": s.get("percent"),
|
||||
"level": f"{s.get('current')}/{s.get('max')}",
|
||||
"muted": s.get("muted"),
|
||||
})
|
||||
return {"streams": out}
|
||||
|
||||
stream = str(args.get("stream") or "music").strip().lower()
|
||||
mode = str(args.get("mode") or "set").strip().lower()
|
||||
try:
|
||||
raw = args.get("value")
|
||||
value = int(raw) if raw is not None else 1
|
||||
except (TypeError, ValueError):
|
||||
value = 1
|
||||
|
||||
if mode in ("up", "down") and value <= 0:
|
||||
value = 1
|
||||
|
||||
# ★ set 时 value 是百分比,要先换算成档位 ——
|
||||
# 安卓的原始值是按流的 max 算的(媒体流通常 15 档,铃声 7 档),
|
||||
# 直接把 50 当原始值会撞到上限。
|
||||
requested = value
|
||||
if mode == "set":
|
||||
# 先读一遍拿到 max,再换算
|
||||
st = call_device({"action": "volume"})
|
||||
if st.get("error"):
|
||||
raise RuntimeError(str(st["error"]))
|
||||
streams = ((st.get("state") or {}).get("streams")) or []
|
||||
cur = next((s for s in streams if s.get("stream") == stream), None)
|
||||
mx = int((cur or {}).get("max") or 15)
|
||||
pct = max(0, min(100, value))
|
||||
requested = round(pct * mx / 100.0)
|
||||
|
||||
res = call_device({
|
||||
"action": "volume_set",
|
||||
"stream": stream,
|
||||
"mode": mode,
|
||||
"value": requested,
|
||||
})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
# ★ 系统拒绝(多半是勿扰)—— 如实抛出去,别假装成功
|
||||
raise RuntimeError(str(res["error"]))
|
||||
|
||||
out = {
|
||||
"stream": res.get("stream"),
|
||||
"before": res.get("before"),
|
||||
"current": res.get("current"),
|
||||
"max": res.get("max"),
|
||||
"percent": res.get("percent"),
|
||||
}
|
||||
if mode == "set":
|
||||
out["requested_percent"] = requested if mode != "set" else value
|
||||
out["note"] = f"「{res.get('stream')}」现在是 {res.get('percent')}%。"
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
Reference in New Issue
Block a user