Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e95e17c3e | ||
|
|
b1dd740b0d | ||
|
|
103c939051 | ||
|
|
885a1f0123 |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 238
|
||||
versionName = "2.0.38"
|
||||
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,10 +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) {
|
||||
@@ -87,6 +125,37 @@ class NativeBridge(private val activity: Activity) {
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 主动往**当前会话**里发一条消息(`tools/send_message.py`)。
|
||||
*
|
||||
* 走内核的 `/api/session-message` —— 那边负责落进会话历史、
|
||||
* 以及**两道防死循环的闸**(嵌套深度、每会话条数)。
|
||||
*
|
||||
* ★ 为什么闸不在 Kotlin 这层做:内核才有会话上下文和那两处的计数。
|
||||
* 这层只转发,判断留给一处,避免两个地方规则不一致。
|
||||
*/
|
||||
private fun sessionMessage(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId").trim()
|
||||
val text = req.optString("text").trim()
|
||||
if (conv.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
if (text.isEmpty()) return JSONObject().put("error", "text 是空的")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("conversationId", conv)
|
||||
.put("text", text)
|
||||
.put("role", req.optString("role", "user"))
|
||||
.put("reply", req.optBoolean("reply", false))
|
||||
.put("depth", req.optInt("depth", 1))
|
||||
val resp = kernelPost("/api/session-message", body) ?: return JSONObject()
|
||||
.put("error", "内核没响应,消息没发出去")
|
||||
// 内核把"闸门拒绝"也放在 error 字段里(HTTP 200 + error)——
|
||||
// 所以这里原样透传,别把它当成成功。
|
||||
resp
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。**
|
||||
*
|
||||
@@ -138,17 +207,91 @@ class NativeBridge(private val activity: Activity) {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
val wait = req.optBoolean("wait", false)
|
||||
val title = req.optString("title")
|
||||
val fullHtml = req.optBoolean("full_html", false)
|
||||
val convId = req.optString("conversationId")
|
||||
|
||||
// ★★ 先存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
// 用户的原话:"AI 写的界面可以再点开"。
|
||||
// 以前界面只活在内存里,一关(或退出 App)就没了;想再看只能让 AI
|
||||
// 重新生成,而重新生成的内容不一定一样(模型有随机性)——
|
||||
// 用户会觉得"我明明看过的东西怎么变了"。
|
||||
//
|
||||
// 存失败不影响弹出(用户至少还能看这一眼),所以不抛异常。
|
||||
val saved = runCatching {
|
||||
AiSurface.saveScreen(activity, html, title, fullHtml, convId)
|
||||
}.getOrNull()
|
||||
val screenId = saved?.optString("id").orEmpty()
|
||||
|
||||
if (wait) AiSurface.armScreenLatch()
|
||||
return AiSurface.showScreen(
|
||||
html = html,
|
||||
title = req.optString("title"),
|
||||
fullHtml = req.optBoolean("full_html", false),
|
||||
conversationId = req.optString("conversationId"),
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = convId,
|
||||
wait = wait,
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
screenId = screenId,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 再打开一个存下来的界面。
|
||||
*
|
||||
* ★ 和 [uiScreen] 的区别:那个是"AI 刚写了一个新界面",
|
||||
* 这个是"用户想再看一遍**以前那个**"。后者不需要模型参与 ——
|
||||
* 内容就在磁盘上,读出来直接显示。
|
||||
*/
|
||||
private fun uiScreenReopen(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
val html = AiSurface.readScreen(activity, id)
|
||||
?: return JSONObject().put("error", "这个界面已经不在了(可能被清理或删除)")
|
||||
|
||||
// 从索引里把标题 / fullHtml 取回来,不然重开之后标题会变成"AI 界面"
|
||||
var title = ""
|
||||
var fullHtml = false
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") == id) {
|
||||
title = it.optString("title")
|
||||
fullHtml = it.optBoolean("fullHtml")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = req.optString("conversationId"),
|
||||
wait = false,
|
||||
screenId = id,
|
||||
)
|
||||
return JSONObject().put("ok", true).put("screenId", id)
|
||||
}
|
||||
|
||||
/** 列出存下来的界面(消息操作栏的「界面」按钮用它) */
|
||||
private fun uiScreenList(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId")
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
val out = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (conv.isNotBlank() && it.optString("conversationId") != conv) continue
|
||||
out.put(it)
|
||||
}
|
||||
return JSONObject().put("screens", out)
|
||||
}
|
||||
|
||||
private fun uiScreenDelete(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
AiSurface.deleteScreen(activity, id)
|
||||
return JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
@@ -267,6 +410,112 @@ class NativeBridge(private val activity: Activity) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 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
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,8 @@ object AiSurface {
|
||||
val conversationId: String,
|
||||
/** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */
|
||||
val waiting: Boolean = false,
|
||||
/** 磁盘上那一份的 id(空 = 没存)。再打开时靠它去读。 */
|
||||
val screenId: String = "",
|
||||
)
|
||||
|
||||
data class Option(val label: String, val value: String, val description: String)
|
||||
@@ -90,6 +92,133 @@ object AiSurface {
|
||||
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 把界面存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
*
|
||||
* ## 为什么需要(用户的原话:"AI 写的界面可以再点开")
|
||||
*
|
||||
* 界面以前只活在内存里:用户一关(或者退出 App),那份 HTML 就没了。
|
||||
* 过一会儿想"刚才那个图表再看一眼"就再也找不回来,只能让 AI 重新生成 ——
|
||||
* 而重新生成的内容**和上次不一定一样**(模型有随机性),
|
||||
* 用户看到的是"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* ## 为什么不放内核(Python)那边
|
||||
*
|
||||
* 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
|
||||
* `device()` 参数。要走内核就得 Kotlin 再 POST 一次上去,多一次往返、
|
||||
* 还多一个失败点。而 App 私有目录本来就是 Kotlin 最顺手的地方。
|
||||
*
|
||||
* 存法:
|
||||
* `<app files>/ai-screens/<id>.html` 正文
|
||||
* `<app files>/ai-screens/index.json` 索引(列表只读这个)
|
||||
*/
|
||||
private val screensLock = Any()
|
||||
|
||||
fun screenDir(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(ctx.filesDir, "ai-screens").apply { mkdirs() }
|
||||
|
||||
fun screenIndexFile(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(screenDir(ctx), "index.json")
|
||||
|
||||
fun loadScreenIndex(ctx: android.content.Context): JSONArray = synchronized(screensLock) {
|
||||
try {
|
||||
val text = screenIndexFile(ctx).readText()
|
||||
JSONArray(text)
|
||||
} catch (_: Throwable) {
|
||||
JSONArray()
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveScreenIndex(ctx: android.content.Context, arr: JSONArray) {
|
||||
try {
|
||||
screenIndexFile(ctx).writeText(arr.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "写界面索引失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 存下一个界面,返回它的索引项(含 id)。
|
||||
*
|
||||
* ★ 每个会话只留最近 [KEEP_PER_CONV] 个:用户跟 AI 聊久了会弹出几十个界面,
|
||||
* 列表没法看、磁盘也白占。超出时把**最旧的正文删掉**(索引项也去掉),
|
||||
* 保留最近这些。
|
||||
*/
|
||||
fun saveScreen(
|
||||
ctx: android.content.Context,
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
): JSONObject? {
|
||||
val id = "s_" + java.util.UUID.randomUUID().toString().replace("-", "").take(12)
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").writeText(html)
|
||||
val item = JSONObject()
|
||||
.put("id", id)
|
||||
.put("title", title.ifBlank { "AI 界面" })
|
||||
.put("fullHtml", fullHtml)
|
||||
.put("bytes", html.length)
|
||||
.put("conversationId", conversationId)
|
||||
.put("preview", previewOf(html))
|
||||
.put("at", System.currentTimeMillis())
|
||||
synchronized(screensLock) {
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray().put(item)
|
||||
var kept = 0
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("conversationId") != conversationId) {
|
||||
next.put(it); continue
|
||||
}
|
||||
if (kept < KEEP_PER_CONV) {
|
||||
next.put(it); kept++
|
||||
} else {
|
||||
runCatching { java.io.File(screenDir(ctx), "${it.optString("id")}.html").delete() }
|
||||
}
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
item
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "存界面失败:${t.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 读一个界面的正文 */
|
||||
fun readScreen(ctx: android.content.Context, id: String): String? {
|
||||
if (id.isBlank() || id.contains('/') || id.contains("..")) return null
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").readText()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteScreen(ctx: android.content.Context, id: String) {
|
||||
synchronized(screensLock) {
|
||||
runCatching { java.io.File(screenDir(ctx), "$id.html").delete() }
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") != id) next.put(it)
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 HTML 里抠一小段纯文字做预览(列表里靠它认出是哪个界面) */
|
||||
private fun previewOf(html: String): String =
|
||||
html.replace(Regex("(?is)<(script|style)[^>]*>.*?</\\1>"), " ")
|
||||
.replace(Regex("<[^>]+>"), " ")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
.take(120)
|
||||
|
||||
private const val KEEP_PER_CONV = 30
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。
|
||||
*
|
||||
@@ -115,8 +244,12 @@ object AiSurface {
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 120_000L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId, waiting = wait)
|
||||
val s = Screen(
|
||||
seq.incrementAndGet(), html, title, fullHtml, conversationId,
|
||||
waiting = wait, screenId = screenId,
|
||||
)
|
||||
screen = s
|
||||
screenClosed = false
|
||||
screenAnswer = null
|
||||
@@ -128,7 +261,12 @@ object AiSurface {
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
return JSONObject().put("shown", true).put("bytes", html.length)
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
// ★ 带上 id —— 它一路回到模型的工具返回值、再进 ToolTrace,
|
||||
// 消息操作栏据此显示「界面」按钮(用户要求"可以再点开")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
// ---- 等待模式 ----
|
||||
@@ -153,6 +291,7 @@ object AiSurface {
|
||||
.put("closed", closed)
|
||||
// 用户点的值。超时/直接关掉时是空串。
|
||||
.put("value", answer ?: "")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
/** 等用户交互用的闩。非等待模式下是 null。 */
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -521,14 +521,20 @@ private fun wrapSkeleton(fragment: String): String = """
|
||||
|
||||
/* ★★ 按钮 —— 这里刻意做得**非常显眼**。
|
||||
*
|
||||
* 起因:有用户反馈"哪有按键,网页里的按键也点不了"。
|
||||
* 原因之一是模型把按钮写成了纯文字、或者用了暗底暗字,
|
||||
* 在深色主题下跟普通段落长得一模一样,用户根本看不出那儿能点。
|
||||
* 起因:用户连着两次反馈"哪有按键,网页里的按键也点不了"、"没有一个按键能用"。
|
||||
* 实测下来**功能是好的**(点了值确实回到模型手里),问题出在**视觉**:
|
||||
*
|
||||
* 所以这一版把回传按钮做成:大号、实心、亮底深字、整行宽、有按下的反馈。
|
||||
* 同时提示词里也明确要求模型"把按钮做得明显"。
|
||||
* (注意 !important:模型经常内联 style="background:..." 把它盖掉。) */
|
||||
.db-btn, [data-doubao-result] {
|
||||
* · `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;
|
||||
@@ -546,25 +552,19 @@ private fun wrapSkeleton(fragment: String): String = """
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
.db-btn:active, [data-doubao-result]:active {
|
||||
.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; }
|
||||
|
||||
/* 普通按钮(模型自己写的、没标 data-doubao-result 的)也给个像样的默认样式,
|
||||
但不像回传按钮那么抢眼 —— 免得满屏都是蓝块 */
|
||||
button:not([data-doubao-result]) {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid #3d4450;
|
||||
border-radius: 10px;
|
||||
background: #232830;
|
||||
color: #e8eaed;
|
||||
font-size: 15px;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
|
||||
@@ -40,11 +40,27 @@ import com.doubao.lynxclone.data.KernelClient
|
||||
|
||||
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
|
||||
@Composable
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel =
|
||||
viewModel(factory = object : ViewModelProvider.Factory {
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel {
|
||||
// ★ 必须写 `viewModel<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(
|
||||
@@ -125,6 +141,37 @@ fun AppRoot(
|
||||
* `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() },
|
||||
@@ -136,17 +183,17 @@ fun AppRoot(
|
||||
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||
)
|
||||
|
||||
// 「要打开哪个网页?」链接列表(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页界面之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
// 「网页」界面(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页显示之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
AnimatedVisibility(
|
||||
visible = vm.pickUrlFrom.isNotEmpty(),
|
||||
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.openWebPage(it) },
|
||||
onPick = { vm.openTypedUrl(it) },
|
||||
onClose = { vm.dismissUrlPicker() },
|
||||
)
|
||||
}
|
||||
@@ -201,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 永久结束了 —— 界面据此把输入框换成结束横幅。
|
||||
*
|
||||
@@ -92,21 +259,52 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
private set
|
||||
|
||||
/**
|
||||
* 一条回复里有多个链接时,先展示这个列表让用户挑;空表示不展示。
|
||||
* 一条回复里提到、或用户自己输的网页;空表示不展示那个界面。
|
||||
*
|
||||
* ★ 按项目约定:**列表这种要滚动的东西不用弹窗**,用独立全屏界面。
|
||||
* 一条回复里挂五六个链接是常事,弹窗装不下、用户还得在里面滚动 ——
|
||||
* 那还不如直接开一屏。(`UrlChooser` 那个弹窗版本已经删掉了。)
|
||||
* 那还不如直接开一屏。
|
||||
*/
|
||||
var pickUrlFrom by mutableStateOf<List<String>>(emptyList())
|
||||
var pickUrlFrom by mutableStateOf<List<FoundUrl>>(emptyList())
|
||||
private set
|
||||
|
||||
fun askWhichUrl(urls: List<String>) {
|
||||
/**
|
||||
* 「网页」界面开着没有。
|
||||
*
|
||||
* ★ 为什么它和 [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
|
||||
}
|
||||
|
||||
/** 打开一个网页(全屏界面) */
|
||||
@@ -384,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 -> {
|
||||
|
||||
@@ -626,14 +626,46 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
*
|
||||
* ★ 链接是从 markdown 里现算的(`extractUrls`),不额外存状态 ——
|
||||
* 存了就要担心和 content 不同步(重新生成、编辑之后)。
|
||||
*
|
||||
* ★★ 按钮**无条件显示**(v2.0.39 改)。
|
||||
* 上一版是"这条回复里有链接才显示",于是:
|
||||
* · extractUrls 漏认写法时(裸 URL 就漏)按钮整个不见了
|
||||
* · 而且用户根本无从知道"这条能不能开网页"
|
||||
* 现在永远在,顺带还能自己在里面输网址 —— 它就是个浏览器入口。
|
||||
*/
|
||||
val urls = remember(msg.content) { extractUrls(msg.content) }
|
||||
if (urls.isNotEmpty()) {
|
||||
RoundIconButton(Icons.Filled.Language, "打开网页") {
|
||||
if (urls.size == 1) {
|
||||
vm.openWebPage(urls.first())
|
||||
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.askWhichUrl(urls)
|
||||
vm.openAiScreenList()
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
|
||||
@@ -265,38 +265,118 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
return out
|
||||
}
|
||||
|
||||
/** 一条回复里提到的一个网页 */
|
||||
data class FoundUrl(
|
||||
/** 完整地址 */
|
||||
val url: String,
|
||||
/** 模型给链接写的文字(`[文字](url)` 里的那个),没有就是空串 */
|
||||
val label: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 从 markdown 里抽出所有链接地址(去重、保序)。
|
||||
* 从 markdown 里抽出所有网页地址(去重、保序,带上链接文字)。
|
||||
*
|
||||
* 给"这条回复里有几个网页可看"用 —— 界面据此决定:
|
||||
* · 0 个 → 不显示「打开网页」按钮
|
||||
* · 1 个 → 直接开
|
||||
* · 多个 → 先让用户选一个
|
||||
* ## ★★ 重写过一版:原来漏了 7/11 种写法
|
||||
*
|
||||
* ★ 只认完整的绝对地址(有 scheme)。`[文档](docs/x.md)` 这种相对路径
|
||||
* 在手机上点了没意义,不算"网页"。
|
||||
* 上一版是手写扫描器,**只认 `](` 紧挨着的 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<String> {
|
||||
if (!markdown.contains("](")) return emptyList()
|
||||
fun extractUrls(markdown: String): List<FoundUrl> {
|
||||
if (!markdown.contains("http://") && !markdown.contains("https://")) return emptyList()
|
||||
val out = LinkedHashSet<String>()
|
||||
var i = 0
|
||||
while (i < markdown.length) {
|
||||
val close = markdown.indexOf(']', i)
|
||||
if (close < 0) break
|
||||
if (close + 1 < markdown.length && markdown[close + 1] == '(') {
|
||||
val end = markdown.indexOf(')', close + 1)
|
||||
if (end > close + 1) {
|
||||
val url = markdown.substring(close + 2, end).trim()
|
||||
if (url.startsWith("http://") || url.startsWith("https://")) out.add(url)
|
||||
i = end + 1
|
||||
continue
|
||||
}
|
||||
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)
|
||||
}
|
||||
i = close + 1
|
||||
}
|
||||
return out.toList()
|
||||
|
||||
// ② 裸 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()]*\))+>?""")
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -462,7 +462,7 @@ private fun hostOf(url: String): String = try {
|
||||
}
|
||||
|
||||
/**
|
||||
* 「要打开哪个网页?」—— **独立全屏界面**,不是弹窗。
|
||||
* 「网页」—— **独立全屏界面**,不是弹窗。
|
||||
*
|
||||
* ## 为什么不用 AlertDialog
|
||||
*
|
||||
@@ -470,19 +470,36 @@ private fun hostOf(url: String): String = try {
|
||||
* 弹窗一屏只装得下三四个,用户得在弹窗里滚动 —— 那还不如直接开一屏。
|
||||
* 而且弹窗盖住对话,用户没法一边看着回复一边挑链接。
|
||||
*
|
||||
* ## ★★ 自己输网址(v2.0.39 加)
|
||||
*
|
||||
* 用户的原话是"**你要单独开个按钮**"。既然它是个按钮,那它就不该只在
|
||||
* "这条回复恰好有链接"时才有用 —— 现在里面能直接输网址,
|
||||
* 它就是一个**浏览器入口**,任何时候按都有意义。
|
||||
* (另一个原因:`extractUrls` 曾经漏认写法,导致按钮整个不显示,
|
||||
* 用户根本不知道这功能存在。)
|
||||
*
|
||||
* 顶栏按项目约定:`← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun UrlListScreen(owner: String, urls: List<String>, onPick: (String) -> Unit, onClose: () -> Unit) {
|
||||
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) {
|
||||
Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
ScreenHeader("网页", onBack = onClose) {
|
||||
if (urls.isNotEmpty()) {
|
||||
Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
@@ -490,45 +507,84 @@ fun UrlListScreen(owner: String, urls: List<String>, onPick: (String) -> Unit, o
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
/* ---------- 自己输网址(永远在最上面,入口要显眼)---------- */
|
||||
item {
|
||||
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) }
|
||||
.padding(horizontal = 14.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
hostOf(u),
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
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.height(3.dp))
|
||||
Text(
|
||||
u,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
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),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ UI_TOOLS_HINT = '\n'.join([
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None,
|
||||
conversation_id: str = '') -> dict:
|
||||
conversation_id: str = '', send_depth: int = 0) -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
@@ -87,6 +87,9 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||||
send_depth `send_message` 嵌套了几层。AI 主动发消息会顺手跑一轮回复,
|
||||
那一轮就是 depth+1;超过上限时工具会被拒。
|
||||
**这是防无限套娃的关键**(见 app.py 的 /api/session-message)。
|
||||
"""
|
||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||
@@ -231,6 +234,12 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
conversationId=conversation_id,
|
||||
agentId=(agent or {}).get('id') or '',
|
||||
toolName=tc.get('name') or '',
|
||||
# ★★ 防无限套娃:send_message 触发的回复里再发消息,深度 +1。
|
||||
# 这个值一路传到(Kotlin 桥 → 内核 /api/session-message),
|
||||
# 超过 SESSION_MSG_MAX_DEPTH 就被拒。
|
||||
# **不传的话**:模型发一条 → 那轮回复里再发 → 无限套娃,
|
||||
# 一个下午能把 API 额度烧光,用户看到满屏没发过的消息。
|
||||
sendDepth=send_depth,
|
||||
)
|
||||
try:
|
||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||
|
||||
@@ -48,6 +48,8 @@ QUIET = False
|
||||
# 安卓上 Lynx 原生 fetch 没有 response.body,只能靠这个通道做"准流式"
|
||||
_RUNS = {}
|
||||
_RUNS_LOCK = threading.Lock()
|
||||
# `send_message` 触发的回复里最多再套几层(防无限套娃,见 /api/session-message)
|
||||
SESSION_MSG_MAX_DEPTH = 2
|
||||
_RUN_TTL_S = 600
|
||||
|
||||
|
||||
@@ -666,6 +668,158 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'conversations': store.list_conversations()})
|
||||
return True
|
||||
|
||||
# ---- AI 主动往会话里发一条消息(send_message 工具)----
|
||||
#
|
||||
# ★★★ 这里最危险的是**死循环**:模型发消息 → 顺手跑回复 →
|
||||
# 回复里又发消息 → ……。所以深度和条数两道闸都在 [SESSION_MSG_*]
|
||||
# 常量那边守着,任何一道超了就直接拒绝并说明原因。
|
||||
if pathname == '/api/session-message' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
conv = str(body.get('conversationId') or '')
|
||||
text = str(body.get('text') or '').strip()
|
||||
role = str(body.get('role') or 'user')
|
||||
want_reply = bool(body.get('reply'))
|
||||
try:
|
||||
depth = int(body.get('depth') or 1)
|
||||
except (TypeError, ValueError):
|
||||
depth = 1
|
||||
|
||||
if not text:
|
||||
self.send_json(400, {'error': 'text 不能为空'})
|
||||
return True
|
||||
if not conv:
|
||||
self.send_json(400, {'error': '缺少 conversationId'})
|
||||
return True
|
||||
|
||||
# 闸①:嵌套太深
|
||||
if depth > SESSION_MSG_MAX_DEPTH:
|
||||
self.send_json(200, {
|
||||
'error': (
|
||||
f'嵌套太深(第 {depth} 层)—— send_message 触发的回复里'
|
||||
f'不能再发消息,最多 {SESSION_MSG_MAX_DEPTH} 层。'
|
||||
'这是防止无限套娃把额度烧光。'
|
||||
),
|
||||
})
|
||||
return True
|
||||
# 闸②:这个会话发得太多了
|
||||
used = store.session_message_count(conv)
|
||||
if used >= store.SESSION_MSG_MAX:
|
||||
self.send_json(200, {
|
||||
'error': (
|
||||
f'这次会话你已经主动发了 {used} 条消息(上限 '
|
||||
f'{store.SESSION_MSG_MAX} 条)。'
|
||||
'别再发了,直接在你这一轮的回答里说。'
|
||||
),
|
||||
})
|
||||
return True
|
||||
|
||||
try:
|
||||
store.append_message(conv, role, text)
|
||||
except KeyError as exc:
|
||||
self.send_json(404, {'error': str(exc)})
|
||||
return True
|
||||
|
||||
if not want_reply:
|
||||
self.send_json(200, {'ok': True, 'sent': True, 'replied': False})
|
||||
return True
|
||||
|
||||
# ★ 要顺手回一轮:**必须放在后台线程**。
|
||||
# 当前这个线程正被 `send_message` 工具占着(模型还在等它的返回值),
|
||||
# 在这里同步跑一轮回复会**死锁**(等自己)。
|
||||
# 而且用 poll 那条路(和安卓端一样),事件进 _RUNS,界面能收到。
|
||||
run_id = 'r%d%s' % (int(time.time() * 1000), uuid.uuid4().hex[:5])
|
||||
with _RUNS_LOCK:
|
||||
_RUNS[run_id] = {'events': [], 'done': False, 'at': time.time()}
|
||||
|
||||
def sink_send(event):
|
||||
with _RUNS_LOCK:
|
||||
run = _RUNS.get(run_id)
|
||||
if run is None:
|
||||
return
|
||||
run['events'].append(event)
|
||||
if event.get('type') in ('done', 'error'):
|
||||
run['done'] = True
|
||||
|
||||
def sink_end():
|
||||
with _RUNS_LOCK:
|
||||
run = _RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run['done'] = True
|
||||
|
||||
worker = threading.Thread(
|
||||
target=self._perform_chat,
|
||||
args=(sink_send, sink_end, store.read_settings(), conv, text, [], {}),
|
||||
kwargs={
|
||||
'should_stop': lambda: False,
|
||||
# ★ 关键:把深度传下去。这一轮回复里模型再调 send_message 时
|
||||
# 拿到的就是 depth+1;超过上限直接被拒。
|
||||
# 不传的话是无限套娃(见 /api/session-message 上面的注释)。
|
||||
'send_depth': depth,
|
||||
},
|
||||
name='self-message-reply',
|
||||
daemon=True,
|
||||
)
|
||||
worker.start()
|
||||
self.send_json(200, {
|
||||
'ok': True, 'sent': True, 'replyStarted': True, 'runId': run_id,
|
||||
})
|
||||
return True
|
||||
|
||||
# ---- 笔记(用户要能查看)----
|
||||
#
|
||||
# ★ 用户的原话:"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 自己写进网页里的接口"的落点。
|
||||
@@ -1411,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:
|
||||
@@ -1465,6 +1619,8 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
# end_conversation 会明确报错(而不是假装成功)。
|
||||
conversation_id=conversation_id,
|
||||
# ★ 防无限套娃:这一轮的深度传进去,send_message 据此判断能不能再发
|
||||
send_depth=send_depth,
|
||||
)
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
|
||||
@@ -34,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',
|
||||
]
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -349,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:
|
||||
@@ -356,6 +739,8 @@ def get_conversation(conv_id: str):
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 界面的数据回流
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -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 的形状。
|
||||
|
||||
100
docs/AI界面能力.md
100
docs/AI界面能力.md
@@ -33,6 +33,106 @@
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
```
|
||||
|
||||
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])
|
||||
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 那行字和那条正弦波。")
|
||||
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 []), "条消息")
|
||||
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("✅ 全部通过")
|
||||
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("✅ 全部通过")
|
||||
@@ -18,7 +18,8 @@
|
||||
"b03b5b99dbd83587"
|
||||
],
|
||||
"notes.py": [
|
||||
"f2255c693b2401b5"
|
||||
"f2255c693b2401b5",
|
||||
"7da481daace71368"
|
||||
],
|
||||
"now.py": [
|
||||
"eb0c37b5afc1dd8b"
|
||||
@@ -33,7 +34,8 @@
|
||||
"1882a766fe0ee833",
|
||||
"6f3ce8a4c924dfdd",
|
||||
"ecea108ef1118386",
|
||||
"f80e4da69db41722"
|
||||
"f80e4da69db41722",
|
||||
"5f11cf92d2a78ce1"
|
||||
],
|
||||
"weather.py": [
|
||||
"bff69719c190d3d9"
|
||||
@@ -43,5 +45,17 @@
|
||||
],
|
||||
"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)
|
||||
@@ -128,6 +128,15 @@ def run(args: dict) -> dict:
|
||||
|
||||
out = {"shown": True, "bytes": len(html)}
|
||||
|
||||
# ★★ 磁盘上那份的 id —— 用户关掉界面之后还能再打开它。
|
||||
#
|
||||
# 这个 id 会一路回到模型的工具返回值、再进 App 的工具痕迹记录,
|
||||
# 消息操作栏据此显示「界面」按钮。
|
||||
# (用户的原话:"AI 写的界面可以再点开")
|
||||
screen_id = str(res.get("screenId") or "")
|
||||
if screen_id:
|
||||
out["screenId"] = screen_id
|
||||
|
||||
if not wait:
|
||||
# 不等待:这一轮就到此为止。用户之后说话时,他在界面上点过什么
|
||||
# 会作为上下文附给模型(内核的待交付队列),所以这里如实说明。
|
||||
@@ -135,6 +144,7 @@ def run(args: dict) -> dict:
|
||||
"界面已弹出,你没有等用户。用户看完会自己关掉;"
|
||||
"他在界面上点过什么,等他下次说话时会作为上下文给你。"
|
||||
"现在可以正常收尾这一轮了。"
|
||||
"(这个界面已经存下来了,用户随时能再打开,不用你再生成一遍。)"
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
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