Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4850ea12af | |||
| 2c259d4270 | |||
| 39813985b5 | |||
|
|
f330af963a | ||
|
|
74c87686ef | ||
|
|
5e95e17c3e |
@@ -123,10 +123,16 @@ if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `android/nodekit/`**(独立模块)。
|
||||
节点类型、引脚、算子、配色、几何、形状**只有那一份** ——
|
||||
`MeetingsScreen.kt` 里**不要再写 `when (node.type)` 的长表**(默认标题、颜色、
|
||||
引脚、配置面板标题都从库查)。
|
||||
加一种节点看 [docs/节点库.md](docs/节点库.md) 的清单,改完跑
|
||||
`python scripts/verify-nodekit.py`(它会拿库和 Python 引擎逐项对拍)。
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`opSpec` / 变量类型选择器 / 列表渲染。
|
||||
`Ops.ALL` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
|
||||
28
README.md
28
README.md
@@ -322,7 +322,30 @@ mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
---
|
||||
|
||||
@@ -593,6 +616,11 @@ node scripts/device-state.mjs <serial> # 看设备内核当前设
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
python scripts/verify-ui-tools.py # interface 工具的参数与提示词
|
||||
python scripts/verify-extract-urls.py # 「打开网页」的链接抽取
|
||||
python scripts/verify-ai-webview.py # AI 界面里的 JS 桥
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 240
|
||||
versionName = "2.0.40"
|
||||
versionCode = 245
|
||||
versionName = "2.0.45"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -181,6 +181,10 @@ chaquopy {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// 会议节点定义库:节点类型 / 引脚 / 算子 / 几何 / 形状的唯一一份定义
|
||||
// (以前散在 MeetingsScreen.kt 里,同一样东西写 6 遍 —— 见 docs/节点库.md)
|
||||
implementation(project(":nodekit"))
|
||||
|
||||
// 原生 UI 用 Compose
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
|
||||
@@ -17,7 +17,17 @@
|
||||
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||
<!-- ★★ 发通知(用户要求"还可以发送通知")。
|
||||
Android 13(API 33) 起这是**运行时权限**,新装的 App **默认是拒绝的** ——
|
||||
不申请的话 `NotificationManager.notify()` 不报错但通知**不显示**。
|
||||
实测踩到:渠道建出来了(importance=3),但 App 级 `importance=NONE`,
|
||||
通知栏里什么都没有,而调用方还以为成功了。
|
||||
声明了不算完,还得在运行时 requestPermissions —— 见 MainActivity。 -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- 通知带声音/震动需要它(Android 13+ 才有这个权限名) -->
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
|
||||
<!-- Android 11+ 包可见性:不声明的话查不到别的 App,也就「打开手机 app」不了 -->
|
||||
<queries>
|
||||
<package android:name="com.termux" />
|
||||
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||
@@ -28,6 +38,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 +72,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>
|
||||
|
||||
261
android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt
Normal file
261
android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt
Normal file
@@ -0,0 +1,261 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.Intent
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★★ 「预设快捷入口」—— 一句话直达某个 App 的某个页面。
|
||||
*
|
||||
* 用户要求:"打开应用工具支持打开活动,并预设几个比如微信对话,支付宝菜鸟"
|
||||
*
|
||||
* ## 为什么每个预设是一**串**候选而不是一个
|
||||
*
|
||||
* 深链 scheme 和 Activity 名字**都会随 App 版本变**。
|
||||
* 只赌一个的话,用户那边 App 一升级这个功能就静默失效了 ——
|
||||
* 而且报的还是"打不开",查起来很费劲。
|
||||
*
|
||||
* 所以每个预设给一组候选,**按顺序试,第一个成的算**:
|
||||
* 1. 深链(最稳,scheme 通常不变)
|
||||
* 2. 指定 Activity(有的页面有独立 Activity)
|
||||
* 3. 退回主界面(保证"至少把 App 打开了",不会让用户觉得功能坏了)
|
||||
*
|
||||
* ★ 每个候选都标了 `kind`,返回里如实说**是哪一个成的** ——
|
||||
* 万一以后要调,一眼看得出走到哪一层了。
|
||||
*
|
||||
* ## ★ 诚实说明:这些 scheme 没法离线验证
|
||||
*
|
||||
* 我没法在没有真机 App 的情况下确认 `weixin://` 一定进"聊天列表"、
|
||||
* `alipays://platformapi/startapp?appId=200011235` 一定开菜鸟。
|
||||
* 这些值来自公开的深链惯例,**大多数情况可用,但 App 大版本更新后可能失效**。
|
||||
*
|
||||
* 所以设计上:
|
||||
* · 全部走"多候选 + 退回主界面",失效也不会让功能变成"点了没反应"
|
||||
* · 返回里带 `how`(哪一条成的)和 `tried`(试过哪些),方便排查
|
||||
* · 用户可以在 `tools/apps.py` 的说明里看到怎么改用自己手机上的值
|
||||
*/
|
||||
object AppShortcuts {
|
||||
|
||||
private const val WECHAT = "com.tencent.mm"
|
||||
private const val ALIPAY = "com.eg.android.AlipayGphone"
|
||||
private const val TAOBAO = "com.taobao.taobao"
|
||||
private const val QQ = "com.tencent.mobileqq"
|
||||
private const val DOUYIN = "com.ss.android.ugc.aweme"
|
||||
|
||||
/**
|
||||
* 一个候选:怎么打开。
|
||||
*
|
||||
* ★ 可见性跟着用的地方走:`run()` 的参数/返回类型里出现了它,
|
||||
* 所以它至少要**一样宽**。Kotlin 不允许 public 函数暴露 private/internal 类型
|
||||
* (报 "Function 'public' exposes its 'private-in-class' return type")。
|
||||
* 这个坑连着踩了两次(先 private 后 internal),索性都用默认的 public。
|
||||
*/
|
||||
data class Shot(
|
||||
val kind: String, // uri / activity / main
|
||||
val pkg: String,
|
||||
val uri: String = "",
|
||||
val cls: String = "",
|
||||
val note: String = "",
|
||||
)
|
||||
|
||||
/** 一个预设:名字 + 关键词 + 一串候选 */
|
||||
data class Preset(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val keywords: List<String>,
|
||||
val shots: List<Shot>,
|
||||
)
|
||||
|
||||
private fun p(id: String, label: String, kw: List<String>, vararg shots: Shot) =
|
||||
Preset(id, label, kw, shots.toList())
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// 预设表
|
||||
//
|
||||
// ★ 加新预设只要往这个列表里塞一条 —— 工具说明、列表接口都是从这里生成的,
|
||||
// 不存在"两边不一致"的问题(这个仓库里抄两份的坑踩过好几次)。
|
||||
// ------------------------------------------------------------------ //
|
||||
|
||||
private val PRESETS: List<Preset> = listOf(
|
||||
// ---------------- 微信 ----------------
|
||||
p(
|
||||
"wechat", "微信(主界面)", listOf("微信", "wechat", "weixin"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "微信主 scheme"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-chat", "微信 · 聊天列表", listOf("微信聊天", "微信对话", "聊天列表", "wechat chat"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/chat", note = "聊天列表"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-scan", "微信 · 扫一扫", listOf("微信扫一扫", "扫码", "扫一扫", "wechat scan"),
|
||||
Shot("uri", WECHAT, uri = "weixin://scanqrcode", note = "扫一扫"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-moments", "微信 · 朋友圈", listOf("朋友圈", "moments", "wechat moments"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/moments", note = "朋友圈"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-pay", "微信 · 收付款", listOf("微信支付", "微信收付款", "付款码", "wechat pay"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/offline", note = "收付款(付款码)"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
|
||||
// ---------------- 支付宝 ----------------
|
||||
p(
|
||||
"alipay", "支付宝(主界面)", listOf("支付宝", "alipay", "zhifubao"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "支付宝主 scheme"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-scan", "支付宝 · 扫一扫", listOf("支付宝扫一扫", "支付宝扫码", "alipay scan"),
|
||||
// 200011235 是支付宝"扫一扫"的公开 appId;后面那个通用端口是备选
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=200011235", note = "扫一扫"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?saId=10000007", note = "通用启动端口"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-pay", "支付宝 · 付款码", listOf("支付宝付款", "支付宝收付款", "付款码", "alipay pay"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=20000056", note = "付款码"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-cainiao", "支付宝 · 菜鸟裹裹", listOf("菜鸟", "菜鸟裹裹", "快递", "cainiao"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=200011235&url=%2Fwww%2Fcainiao.html", note = "菜鸟"),
|
||||
// 菜鸟也有独立 App,装了就直接开它
|
||||
Shot("uri", "com.cainiao.wireless", uri = "cainiao://", note = "菜鸟独立 App"),
|
||||
Shot("main", "com.cainiao.wireless", note = "菜鸟独立 App 主界面"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-card", "支付宝 · 卡包", listOf("卡包", "支付宝卡包", "alipay card"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=20000021", note = "卡包"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
|
||||
// ---------------- 别的常用的 ----------------
|
||||
p(
|
||||
"taobao", "淘宝", listOf("淘宝", "taobao"),
|
||||
Shot("uri", TAOBAO, uri = "taobao://", note = "淘宝主 scheme"),
|
||||
Shot("main", TAOBAO),
|
||||
),
|
||||
p(
|
||||
"qq", "QQ", listOf("qq", "腾讯qq"),
|
||||
Shot("uri", QQ, uri = "mqq://", note = "QQ 主 scheme"),
|
||||
Shot("main", QQ),
|
||||
),
|
||||
p(
|
||||
"douyin", "抖音", listOf("抖音", "douyin", "tiktok"),
|
||||
Shot("uri", DOUYIN, uri = "snssdk1128://", note = "抖音主 scheme"),
|
||||
Shot("main", DOUYIN),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 全部预设。
|
||||
*
|
||||
* ★ Context 当**参数**传,不存一个可空的全局变量 ——
|
||||
* 第一版用 `@Volatile var appCtx`,于是编译期类型是 `Context?`,
|
||||
* 每次用都要解包,还容易忘了先赋值(那样"装了没有"永远返回 false)。
|
||||
* 传参是编译期就能保证的。
|
||||
*/
|
||||
fun all(ctx: android.content.Context): List<Map<String, Any>> = PRESETS.map { p ->
|
||||
mapOf(
|
||||
"id" to p.id,
|
||||
"label" to p.label,
|
||||
"keywords" to p.keywords,
|
||||
// 只看第一个候选那个 App 装了没有 —— 后面的候选可能包含没装的备选
|
||||
"installed" to PhoneOps.isInstalled(ctx, p.shots.first().pkg),
|
||||
"app" to p.shots.first().pkg,
|
||||
)
|
||||
}
|
||||
|
||||
fun ids(): List<String> = PRESETS.map { it.id }
|
||||
|
||||
/** 按 id 或关键词找一个预设 */
|
||||
fun find(query: String): Preset? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
PRESETS.firstOrNull { it.id.equals(q, ignoreCase = true) }?.let { return it }
|
||||
PRESETS.firstOrNull { it.label.lowercase() == q }?.let { return it }
|
||||
PRESETS.firstOrNull { it.keywords.any { k -> k.lowercase() == q } }?.let { return it }
|
||||
// 先匹配 label 里的,再匹配关键词 —— 避免"微信"先命中"微信扫一扫"那种歧义
|
||||
PRESETS.firstOrNull { it.label.lowercase().contains(q) }?.let { return it }
|
||||
return PRESETS.firstOrNull { p ->
|
||||
p.keywords.any { k -> k.lowercase().contains(q) || q.contains(k.lowercase()) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一个预设:按候选顺序试,第一个成的算。
|
||||
*
|
||||
* ★ 全失败时返回**试过哪些 + 各自为什么失败** ——
|
||||
* 只回一句"打不开"的话,用户和模型都不知道下一步该干嘛。
|
||||
*/
|
||||
fun run(ctx: android.content.Context, preset: Preset): JSONObject {
|
||||
val tried = JSONArray()
|
||||
for (shot in preset.shots) {
|
||||
if (!PhoneOps.isInstalled(ctx, shot.pkg)) {
|
||||
tried.put(JSONObject().put("kind", shot.kind).put("pkg", shot.pkg)
|
||||
.put("error", "没装这个 App"))
|
||||
continue
|
||||
}
|
||||
val err: String? = when (shot.kind) {
|
||||
"uri" -> PhoneOps.launchUri(ctx, shot.uri)
|
||||
"activity" -> PhoneOps.launchActivity(ctx, shot.pkg, shot.cls)
|
||||
else -> if (PhoneOps.launchApp(ctx, shot.pkg, mainActivityOf(ctx, shot.pkg))) {
|
||||
null
|
||||
} else {
|
||||
"启动主界面失败"
|
||||
}
|
||||
}
|
||||
if (err == null) {
|
||||
return JSONObject()
|
||||
.put("ok", true)
|
||||
.put("shortcut", preset.id)
|
||||
.put("label", preset.label)
|
||||
.put("how", shot.kind)
|
||||
.put("detail", shot.note)
|
||||
.put("tried", tried)
|
||||
}
|
||||
tried.put(JSONObject().put("kind", shot.kind)
|
||||
.put("detail", shot.note)
|
||||
.put("error", err))
|
||||
}
|
||||
return JSONObject()
|
||||
.put("error", "「${preset.label}」的所有打开方式都没成功")
|
||||
.put("tried", tried)
|
||||
.put(
|
||||
"hint",
|
||||
"多半是这个 App 没装,或者它的版本改了深链。可以先用 action=open 打开 App 主界面," +
|
||||
"或者在 tools/apps.py 里把这个预设的链接改成你手机上的实际值。",
|
||||
)
|
||||
}
|
||||
|
||||
/** 拿一个包的 launcher activity */
|
||||
fun mainActivityOf(ctx: android.content.Context, pkg: String): String {
|
||||
val i = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(android.content.Intent.CATEGORY_LAUNCHER)
|
||||
.setPackage(pkg)
|
||||
val list = if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
ctx.packageManager.queryIntentActivities(
|
||||
i, android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ctx.packageManager.queryIntentActivities(i, 0)
|
||||
}
|
||||
return list.firstOrNull()?.activityInfo?.name.orEmpty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
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
|
||||
instance = this
|
||||
// ★ 连上的瞬间就把当前挂着的通知同步进来 —— 不然用户装完 App 立刻问
|
||||
// "我最近收到什么通知了",答案是空的(那些通知在他装 App 之前就收到了)
|
||||
syncActive()
|
||||
Log.i(TAG, "通知使用权已连接,当前挂着 ${items.size} 条")
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
super.onListenerDisconnected()
|
||||
connected = false
|
||||
if (instance === this) instance = null
|
||||
Log.i(TAG, "通知使用权已断开")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
if (instance === this) instance = null
|
||||
}
|
||||
|
||||
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) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一条通知。
|
||||
*
|
||||
* ★ 可见性要 **internal**(不能 private):`companion object` 里的
|
||||
* `syncActive()` 要调它,而 Kotlin 的 private 成员**只对同一个类体可见**,
|
||||
* 伴生对象不算 —— 写成 private 会报"cannot access"。
|
||||
*/
|
||||
internal 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,
|
||||
)
|
||||
// ★ 标题和正文都空的就**不进列表**。
|
||||
//
|
||||
// 这类通知真实存在:媒体控制、正在进行的下载、某些 App 的纯图标通知 ——
|
||||
// 它们的文字要么在 RemoteViews 里(`extras` 取不到),要么压根没有。
|
||||
// 留着的话用户/模型会看到一条"什么都没有"的条目,纯噪音。
|
||||
// (实测:`cmd notification post` 发的测试通知就有一条是这样的。)
|
||||
if (item.title.isBlank() && item.text.isBlank()) return
|
||||
|
||||
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>()
|
||||
|
||||
/**
|
||||
* 当前活着的 service 实例。
|
||||
*
|
||||
* ★ 必须有它:`getActiveNotifications()` 是 **service 自己**的方法,
|
||||
* 不是静态的。没有实例就调不到,也就拿不到"系统里现在挂着哪些通知"。
|
||||
*/
|
||||
@Volatile
|
||||
private var instance: DoubaoNotificationListener? = null
|
||||
|
||||
/** 通知使用权连上了没有 */
|
||||
@Volatile
|
||||
var connected: Boolean = false
|
||||
|
||||
/**
|
||||
* ★★★ 把系统里**当前还挂着的**通知同步进来。
|
||||
*
|
||||
* ## 为什么必须有这个(用户报"还是没有读到"的根因)
|
||||
*
|
||||
* 第一版只在 `onNotificationPosted` 里记 —— 也就是说**只有本进程活着的
|
||||
* 那段时间收到的通知才算数**。而进程一重启(用户升级 App、或者系统杀后台)
|
||||
* 内存就清空了,那之前收到的通知**全都看不到**。
|
||||
*
|
||||
* 用户的期望是"读我手机上现在的通知" —— 那本来就该包含
|
||||
* **在他打开 App 之前就收到的那些**。
|
||||
*
|
||||
* `NotificationListenerService.getActiveNotifications()` 正好干这个:
|
||||
* 系统把当前通知栏上挂着的全给它。所以每次读之前先同步一遍。
|
||||
*
|
||||
* ★ 拿不到实例(service 没起来)时不报错,就用手上已有的 ——
|
||||
* 至少比什么都不给强。
|
||||
*/
|
||||
fun syncActive() {
|
||||
val svc = instance ?: return
|
||||
try {
|
||||
for (sbn in svc.activeNotifications ?: emptyArray()) {
|
||||
if (sbn.packageName == svc.packageName) continue
|
||||
svc.record(sbn, removed = false)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "同步当前通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取最近的通知。
|
||||
*
|
||||
* @param limit 最多几条
|
||||
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
|
||||
* @param query 关键词过滤(标题/正文/App 名里含它)
|
||||
*/
|
||||
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
|
||||
// ★ 先跟系统对一次账,把"我们没见过的、但此刻挂着的"补进来
|
||||
syncActive()
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -35,10 +35,32 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private val client = KernelClient()
|
||||
|
||||
companion object {
|
||||
/** 发通知权限的请求码(只要不和别的撞就行) */
|
||||
private const val REQ_NOTIF = 0x4D32
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// ★★ 申请「发通知」权限(用户要求"还可以发送通知")。
|
||||
//
|
||||
// Android 13(API 33) 起这是**运行时权限**,新装的 App **默认拒绝** ——
|
||||
// 不申请的话 `NotificationManager.notify()` 不报错、但通知**根本不显示**。
|
||||
// 实测踩到:渠道建出来了(importance=3),App 级却是 `importance=NONE`,
|
||||
// 通知栏里什么都没有,而工具还返回"发送成功"。
|
||||
//
|
||||
// ★ 只在 33+ 申请:低版本没这个权限,申请了系统会直接忽略(但会打日志)。
|
||||
// ★ 用户拒绝也不影响别的功能 —— 只是发通知会失败,而且工具会如实报错。
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
val need = checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
if (need) {
|
||||
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIF)
|
||||
}
|
||||
}
|
||||
|
||||
var kernelUrl by mutableStateOf("")
|
||||
var status by mutableStateOf("正在启动本地内核…")
|
||||
var termuxReady by mutableStateOf(false)
|
||||
|
||||
@@ -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 {
|
||||
@@ -86,6 +94,68 @@ class NativeBridge(private val activity: Activity) {
|
||||
"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)
|
||||
}
|
||||
// ★ AI 主动发一条通知(用户要求"还可以发送通知")
|
||||
"notification_post" -> {
|
||||
val title = req.optString("title")
|
||||
val text = req.optString("text")
|
||||
if (title.isBlank() && text.isBlank()) {
|
||||
JSONObject().put("error", "title 和 text 至少要给一个")
|
||||
} else {
|
||||
PhoneOps.postNotification(
|
||||
activity, title, text, req.optBoolean("autoCancel", true),
|
||||
)
|
||||
}
|
||||
}
|
||||
"apps" -> appsList(req)
|
||||
"app_launch" -> appLaunch(req)
|
||||
// ★ 预设快捷入口(用户要求"预设几个比如微信对话,支付宝菜鸟")
|
||||
"app_shortcuts" -> {
|
||||
val arr = JSONArray()
|
||||
AppShortcuts.all(activity).forEach { m ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("id", m["id"])
|
||||
.put("label", m["label"])
|
||||
.put("app", m["app"])
|
||||
.put("installed", m["installed"])
|
||||
.put("keywords", JSONArray(m["keywords"] as List<*>)),
|
||||
)
|
||||
}
|
||||
JSONObject().put("shortcuts", arr)
|
||||
}
|
||||
"app_shortcut_open" -> {
|
||||
val key = req.optString("shortcut").ifBlank { req.optString("name") }
|
||||
val hit = AppShortcuts.find(key)
|
||||
if (hit == null) {
|
||||
JSONObject()
|
||||
.put("error", "没有叫「$key」的预设快捷入口")
|
||||
.put("hint", "可以用的有:" + AppShortcuts.ids().joinToString("、"))
|
||||
} else {
|
||||
AppShortcuts.run(activity, hit)
|
||||
}
|
||||
}
|
||||
"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) {
|
||||
@@ -170,6 +240,9 @@ class NativeBridge(private val activity: Activity) {
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**(用户要求"AI 询问界面不要限时")。
|
||||
* 想限时得模型显式传 timeout。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
@@ -198,7 +271,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
fullHtml = fullHtml,
|
||||
conversationId = convId,
|
||||
wait = wait,
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
screenId = screenId,
|
||||
)
|
||||
}
|
||||
@@ -263,8 +336,12 @@ class NativeBridge(private val activity: Activity) {
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点或超时 ——
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**。用户的原话是"AI 询问界面不要限时":
|
||||
* 他在思考的时候弹窗到点自己消失、模型还收到 timeout 当成"用户不理我",
|
||||
* 这一轮就答非所问了。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
@@ -292,7 +369,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -378,6 +455,145 @@ 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()) {
|
||||
// ★ 只给包名不给 activity 是**最常见的用法**(比如"打开微信"),
|
||||
// 这时候自己去查它的 launcher activity —— 让模型去记
|
||||
// `com.tencent.mm.ui.LauncherUI` 这种名字既没必要也容易记错。
|
||||
val realCls = cls.ifEmpty { AppShortcuts.mainActivityOf(activity, pkg) }
|
||||
if (realCls.isEmpty()) {
|
||||
return JSONObject()
|
||||
.put("error", "找不到 $pkg 的启动入口(可能没装,或者它没有可启动的界面)")
|
||||
}
|
||||
// ★ 有 activity 时先试"直接拉起那个 Activity"(能直达指定页面),
|
||||
// 失败再退回标准 launcher 方式 —— App 内部 Activity 常常没导出,
|
||||
// 直接拉会被系统拒。
|
||||
if (cls.isNotEmpty()) {
|
||||
val directErr = PhoneOps.launchActivity(activity, pkg, cls)
|
||||
if (directErr == null) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", cls).put("how", "direct")
|
||||
}
|
||||
// 直拉失败就退回标准方式;两者都失败才报错
|
||||
if (PhoneOps.launchApp(activity, pkg, realCls)) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
.put("note", "没法直达指定页面($directErr),已经打开 App 主界面")
|
||||
}
|
||||
// ★ 两边都失败:错误里**两个原因都要说**。
|
||||
// 只说直拉那个的话会误导 —— 用户/模型以为是"activity 名字写错了",
|
||||
// 其实退回主界面也失败了(那才是更严重的问题)。
|
||||
return JSONObject().put(
|
||||
"error",
|
||||
"启动 $pkg 失败:直达指定页面不行($directErr)," +
|
||||
"退回主界面也不行($realCls 打不开)。这个 App 可能被停用了。",
|
||||
)
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, pkg, realCls)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
} 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
|
||||
|
||||
367
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
367
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -0,0 +1,367 @@
|
||||
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)
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 四、发通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 通知渠道 id。
|
||||
*
|
||||
* ★ Android 8+ 必须挂在渠道上,否则通知**直接被丢掉**(连报错都没有)。
|
||||
* 渠道的重要性用 DEFAULT:太低会被折叠成静音,用户根本注意不到;
|
||||
* 太高(HIGH)会弹横幅 —— 对"AI 提醒你一件事"这种场景
|
||||
* 弹横幅太打扰了,DEFAULT 正合适(有声音 + 进通知栏,不弹横幅)。
|
||||
*/
|
||||
private const val CHANNEL_ID = "doubao_ai"
|
||||
private const val CHANNEL_NAME = "AI 提醒"
|
||||
|
||||
private fun ensureChannel(ctx: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
if (nm.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
val ch = android.app.NotificationChannel(
|
||||
CHANNEL_ID, CHANNEL_NAME, android.app.NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "豆包主动发出来的提醒"
|
||||
enableVibration(true)
|
||||
}
|
||||
nm.createNotificationChannel(ch)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 发一条通知 —— 用户要求"还可以发送通知"。
|
||||
*
|
||||
* 用途:AI 说到点提醒你什么、长任务跑完了通知一声。
|
||||
*
|
||||
* ★ 点通知要能回到 App:用 `PendingIntent` 打开 MainActivity。
|
||||
* 不给 PendingIntent 的话点了没反应 —— 用户会觉得"这通知是死的"。
|
||||
*
|
||||
* ★ 用 `System.currentTimeMillis()` 当通知 id:每条独立存在,不会互相覆盖。
|
||||
* 固定 id 的话后一条会把前一条顶掉("我刚收到的提醒怎么没了")。
|
||||
*/
|
||||
fun postNotification(ctx: Context, title: String, text: String, autoCancel: Boolean): JSONObject {
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
ensureChannel(ctx)
|
||||
|
||||
val t = title.trim().ifBlank { "豆包" }
|
||||
val body = text.trim()
|
||||
|
||||
// 点通知打开 App
|
||||
val open = Intent(ctx, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
var flags = android.app.PendingIntent.FLAG_UPDATE_CURRENT
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags = flags or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
}
|
||||
val pi = android.app.PendingIntent.getActivity(ctx, 0, open, flags)
|
||||
|
||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
android.app.Notification.Builder(ctx, CHANNEL_ID)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
android.app.Notification.Builder(ctx)
|
||||
}
|
||||
builder
|
||||
.setSmallIcon(ctx.applicationInfo.icon) // ★ 不给 smallIcon 通知**不会显示**
|
||||
.setContentTitle(t)
|
||||
.setContentText(body)
|
||||
.setAutoCancel(autoCancel)
|
||||
.setContentIntent(pi)
|
||||
// 正文长的话展开显示(否则通知栏只显示一行,被截断)
|
||||
if (body.length > 40) {
|
||||
builder.setStyle(android.app.Notification.BigTextStyle().bigText(body))
|
||||
}
|
||||
|
||||
val id = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
|
||||
return try {
|
||||
nm.notify(id, builder.build())
|
||||
JSONObject().put("ok", true).put("id", id)
|
||||
.put("title", t)
|
||||
.put("chars", body.length)
|
||||
} catch (t2: Throwable) {
|
||||
Log.w(TAG, "发通知失败:${t2.message}")
|
||||
JSONObject().put("error", "发通知失败:${t2.javaClass.simpleName}: ${t2.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、打开 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
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接拉起某个 Activity(不一定是 launcher 那个)。
|
||||
*
|
||||
* 用途:微信的某些页面有独立 Activity,用它能直达。
|
||||
*
|
||||
* ★ 会被系统拦的情况很多:Activity 没导出(`android:exported=false`)、
|
||||
* 被 App 的权限保护、或者版本更新后改了名字。
|
||||
* 所以**返回具体原因**,不要只回一个 false —— 模型据此决定要不要退回主界面。
|
||||
*/
|
||||
fun launchActivity(ctx: Context, pkg: String, cls: String): String? = try {
|
||||
ctx.startActivity(
|
||||
Intent().setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
null
|
||||
} catch (t: Throwable) {
|
||||
"${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
|
||||
/**
|
||||
* 用自定义 scheme 打开(深链)。
|
||||
*
|
||||
* ★ 这是"预设快捷入口"的主力:像 `weixin://`、`alipays://` 这种,
|
||||
* 比猜 Activity 名字稳得多 —— Activity 名字随版本变,scheme 通常不变。
|
||||
*
|
||||
* ★ 必须查 `resolveActivity`:没装那个 App、或者它不认这个 scheme 时,
|
||||
* `startActivity` 会抛 `ActivityNotFoundException`。
|
||||
* 先查一遍能给出**更准确的错误**("没装"vs"不认这个链接")。
|
||||
*/
|
||||
fun launchUri(ctx: Context, uri: String): String? {
|
||||
val parsed = try {
|
||||
android.net.Uri.parse(uri)
|
||||
} catch (t: Throwable) {
|
||||
return "链接解析失败:${t.message}"
|
||||
}
|
||||
val intent = Intent(Intent.ACTION_VIEW, parsed).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val hit = if (Build.VERSION.SDK_INT >= 33) {
|
||||
ctx.packageManager.resolveActivity(
|
||||
intent, android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ctx.packageManager.resolveActivity(intent, 0)
|
||||
}
|
||||
if (hit == null) {
|
||||
return "没有 App 能处理这个链接(对应 App 没装,或者版本不认这个 scheme)"
|
||||
}
|
||||
return try {
|
||||
ctx.startActivity(intent)
|
||||
null
|
||||
} catch (t: Throwable) {
|
||||
"${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
}
|
||||
|
||||
/** 某个包装了没有 */
|
||||
fun isInstalled(ctx: Context, pkg: String): Boolean = try {
|
||||
ctx.packageManager.getApplicationInfo(pkg, 0)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -234,8 +234,10 @@ object AiSurface {
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★ 超时必须有:用户可能锁屏走了。不设的话内核工作线程永远挂着,
|
||||
* 而 HTTP 是每请求一线程,挂一个少一个。
|
||||
* ★★ [timeoutMs] <= 0 表示**不限时**(等用户到天荒地老),这是默认。
|
||||
* 以前默认 120 秒,用户明确要求"AI 询问界面不要限时"——
|
||||
* 他可能看着界面想很久,120 秒到点界面自己收掉,体验很差。
|
||||
* 现在想限时得由模型显式传 timeout。
|
||||
*/
|
||||
fun showScreen(
|
||||
html: String,
|
||||
@@ -243,7 +245,7 @@ object AiSurface {
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 120_000L,
|
||||
timeoutMs: Long = 0L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(
|
||||
@@ -257,7 +259,7 @@ object AiSurface {
|
||||
Log.i(
|
||||
TAG,
|
||||
"AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," +
|
||||
if (wait) "等用户操作(最多 ${timeoutMs / 1000}s)" else "不等待",
|
||||
if (wait) "等用户操作(${waitLabel(timeoutMs)})" else "不等待",
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
@@ -271,7 +273,7 @@ object AiSurface {
|
||||
|
||||
// ---- 等待模式 ----
|
||||
val latch = screenLatch
|
||||
val answered = latch?.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS) ?: false
|
||||
val answered = latch?.let { awaitUser(it, timeoutMs) } ?: false
|
||||
val answer = screenAnswer
|
||||
val closed = screenClosed
|
||||
screenLatch = null
|
||||
@@ -342,10 +344,18 @@ object AiSurface {
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完或超时。
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完。
|
||||
*
|
||||
* ★ 超时是必须的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
* 而且因为 HTTP 是每请求一线程,挂一个少一个。
|
||||
* ★★ [timeoutMs] <= 0 = **不限时**(默认)。这是用户明确要求的:
|
||||
* "AI 询问界面不要限时" —— 他可能对着选项想很久,或者在忙别的事,
|
||||
* 120 秒到点弹窗自己消失、模型收到 `timeout=true` 以为他不想理,
|
||||
* 然后自说自话往下走 —— 整轮就废了。
|
||||
*
|
||||
* ★ 放行的方式(用户总得有一个出口,不然内核线程永远挂着):
|
||||
* · 点任意一个选项 → [answerDialog] → countDown
|
||||
* · 点「取消」(`allowCancel` 默认 true)→ 同上,`cancelled=true`
|
||||
* · 关掉 App → 进程结束,线程一起没了
|
||||
* 所以只要界面上留着取消按钮,无限等就不会变成死锁。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
@@ -364,9 +374,9 @@ object AiSurface {
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,最多等 ${timeoutMs / 1000}s)")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,${waitLabel(timeoutMs)})")
|
||||
|
||||
val answered = latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
val answered = awaitUser(latch, timeoutMs)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
@@ -384,6 +394,27 @@ object AiSurface {
|
||||
return a
|
||||
}
|
||||
|
||||
/**
|
||||
* 等用户动作。
|
||||
*
|
||||
* [timeoutMs] <= 0 → **无限等**(`await()` 不带超时);否则最多等那么久。
|
||||
* 返回 true 表示等到了。
|
||||
*
|
||||
* ★ 只有这一个地方做等待,[ask] 和 [showScreen] 都走它 ——
|
||||
* 两处各写一遍的话,"不限时"这种改动迟早只改到一处。
|
||||
*/
|
||||
private fun awaitUser(latch: CountDownLatch, timeoutMs: Long): Boolean =
|
||||
if (timeoutMs <= 0L) {
|
||||
latch.await()
|
||||
true
|
||||
} else {
|
||||
latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
/** 日志里怎么描述等待时长 */
|
||||
private fun waitLabel(timeoutMs: Long): String =
|
||||
if (timeoutMs <= 0L) "不限时,等用户回答" else "最多等 ${timeoutMs / 1000}s"
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
|
||||
@@ -141,6 +141,53 @@ fun AppRoot(
|
||||
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
// 「更多功能」—— 抽屉里放不下的入口收在这儿
|
||||
AnimatedVisibility(
|
||||
visible = vm.moreSheetOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MoreSheetScreen(
|
||||
onOpenAiScreens = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openAiScreenList()
|
||||
},
|
||||
onOpenSkills = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Skills
|
||||
},
|
||||
onOpenMeetings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Meetings
|
||||
},
|
||||
onOpenTerminal = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Terminal
|
||||
},
|
||||
onOpenSettings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
onClose = { vm.moreSheetOpen = false },
|
||||
)
|
||||
}
|
||||
|
||||
// 「笔记」—— 用户要能查看 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(
|
||||
@@ -228,32 +275,27 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 抽屉分两层(改过一次,用户反馈"太挤了对话都没了")。
|
||||
*
|
||||
* 原来 9 个入口平铺,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能(用户 90% 打开抽屉是为了切对话)。
|
||||
*
|
||||
* 现在:
|
||||
* · 第一层只放**天天用的**三个:新话题 / 智能体 / 笔记
|
||||
* · 其余的收进「更多功能」一个入口,点开是独立全屏页(按项目约定,
|
||||
* 列表这种要滚动的东西不用弹窗或折叠面板)
|
||||
*/
|
||||
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
|
||||
SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
}
|
||||
/**
|
||||
* ★「AI 界面」—— 用户要求"AI 写的界面可以再点开"。
|
||||
*
|
||||
* 放在抽屉里而不是只靠消息操作栏:操作栏那个按钮只有**那一条回复**
|
||||
* 弹过界面时才出现,用户想"翻翻前几次弹过什么"就没路走。
|
||||
* 这里是个总入口,能看全部、也能删。
|
||||
*/
|
||||
DrawerItem(Icons.Filled.Dashboard, "AI 界面") {
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
vm.openAiScreenList()
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.AccountTree, "会议模式") {
|
||||
vm.screen = Screen.Meetings; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Terminal, "终端") {
|
||||
vm.screen = Screen.Terminal; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Settings, "设置") {
|
||||
vm.screen = Screen.Settings; vm.drawerOpen = false
|
||||
vm.openNotes()
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
@@ -263,9 +305,13 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Apps, "更多功能") {
|
||||
vm.drawerOpen = false
|
||||
vm.moreSheetOpen = true
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
SectionLabel("对话", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
|
||||
@@ -91,6 +91,78 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
var aiScreenListOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 「更多功能」页开着没有。
|
||||
*
|
||||
* ★ 抽屉原来平铺 9 个入口,把对话列表挤没了(用户反馈"太挤了对话都没了")。
|
||||
* 现在只留天天用的,其余收进这一页。
|
||||
*/
|
||||
var moreSheetOpen by mutableStateOf(false)
|
||||
|
||||
/* -------------------- 笔记(用户要能查看)-------------------- */
|
||||
|
||||
/**
|
||||
* 笔记列表。
|
||||
*
|
||||
* ★ 用户的原话:"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
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.ExperimentalTextApi
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
@@ -24,9 +25,12 @@ import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
@@ -39,11 +43,28 @@ import androidx.compose.ui.unit.sp
|
||||
* 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。
|
||||
*
|
||||
* 支持:
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、> 引用、--- 分隔线、普通段落
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、- [ ] 任务列表、> 引用、--- 分隔线、
|
||||
* **| 表格 |**、普通段落
|
||||
* 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接)
|
||||
*
|
||||
* 不支持(有意为之):表格、嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 不支持(有意为之):嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 而且做全了就得处理各种边界,性价比很低。
|
||||
*
|
||||
* ## ★★ 表格是补上的,起因是用户截图:"表格没做"
|
||||
*
|
||||
* 之前这里明确写着"不支持表格",理由是"聊天里几乎不出现"—— **判断错了**。
|
||||
* 复盘为什么错得这么离谱:
|
||||
*
|
||||
* · 内核的 `speech.py` **早就**在按"表格会被渲染"处理朗读文本了
|
||||
* (`_MD_TABLE_SEP` / `_MD_PIPE` 把竖线和分隔行剥掉)。也就是说
|
||||
* **朗读那条路认为表格存在,渲染这条路不存在** —— 两端不一致,
|
||||
* 而我一直没发现,因为语音和界面是分开测的。
|
||||
* · 这个模型(用户的"病娇女友"智能体)非常爱用表格算账,
|
||||
* 截图里那张"一个月开销"表就是。宽表塞进聊天流的后果不是"少个表格",
|
||||
* 而是**满屏竖线 + 换行错位,整段没法读**。
|
||||
*
|
||||
* 所以现在按 GFM 表格实现。教训:**别用"几乎不出现"当不做某个 Markdown
|
||||
* 元素的理由** —— 去内核里看看朗读/复制那些旁路是不是已经假设它存在了。
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
@@ -146,6 +167,32 @@ fun MarkdownText(
|
||||
)
|
||||
}
|
||||
|
||||
// 任务列表:方框 + 文字。勾上的加删除线(进度一眼能看出来)
|
||||
is MdBlock.Task -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (block.checked) "☑" else "☐",
|
||||
fontSize = fontSize.sp,
|
||||
color = if (block.checked) Doubao.Blue else color.copy(alpha = 0.55f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = if (block.checked) color.copy(alpha = 0.6f) else color,
|
||||
textDecoration = if (block.checked) TextDecoration.LineThrough else null,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Table -> MarkdownTable(
|
||||
block = block,
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
)
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -167,6 +214,153 @@ fun MarkdownText(
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 表格渲染 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 一张表。
|
||||
*
|
||||
* ## 为什么是"横向滚动 + 按内容算列宽",而不是等分
|
||||
*
|
||||
* 手机屏宽就 360dp 左右,而这类表格(模型最爱拿它算账)常见的形态是
|
||||
* **第一列很长、后面几列很短**:
|
||||
*
|
||||
* 吃(早150+午363+晚510+零食150) | 1173 | 大头还是晚饭
|
||||
*
|
||||
* 等分的话第一列必然折成三行、而"1173"那一列白白空着一大片。
|
||||
* 按内容量宽 + 整张表横向滚动,窄表看起来就是正常表格,
|
||||
* 宽表右滑能看全 —— 比挤成一坨强。
|
||||
*
|
||||
* ## 列宽怎么算
|
||||
*
|
||||
* 用 [rememberTextMeasurer] 把每一列的所有单元格量一遍取最大值,
|
||||
* 夹在 [MIN_COL_W] 和 [MAX_COL_W] 之间:
|
||||
* · 下限防止"一个月"这种短列被压成一条缝
|
||||
* · 上限防止某一格特别长(模型爱写长句)把整列撑到几屏宽
|
||||
*
|
||||
* ★ 量宽是 `remember(block)` 的:流式输出时每个字都在变,
|
||||
* 每帧重量一遍 20 多个单元格也还好(表格行数一般不超过 15)。
|
||||
*/
|
||||
@Composable
|
||||
private fun MarkdownTable(
|
||||
block: MdBlock.Table,
|
||||
color: Color,
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
val cols = block.header.size
|
||||
val cellStyle = remember(fontSize) { TextStyle(fontSize = (fontSize - 2).sp) }
|
||||
|
||||
val headBg = if (isDark()) Color(0xFF232A36) else Color(0xFFEDF1F7)
|
||||
val lineColor = color.copy(alpha = 0.14f)
|
||||
|
||||
// 量出来的是 px,除上 density 换成 dp(Compose 里布局一律用 dp)
|
||||
// ★ density / measurer 也进 key:系统字号一变(或旋转)就得重量,
|
||||
// 不然列宽还是照着旧字号的
|
||||
val widths: List<Dp> = remember(block, fontSize, density, measurer) {
|
||||
val pad = with(density) { (CELL_PAD_H * 2).toPx() }
|
||||
// 每列额外留一点余量:测量和真实排版总有一点差(字体 hinting、
|
||||
// 中英文混排的字距),差一点点就会让表头折成两行 —— 很难看
|
||||
val slack = with(density) { 2.dp.toPx() }
|
||||
val minW = with(density) { MIN_COL_W.toPx() }
|
||||
val maxW = with(density) { MAX_COL_W.toPx() }
|
||||
// ★★ 表头是 SemiBold,量它必须用**粗体**的 style。
|
||||
// 用常规字重量的话算出来的列宽偏窄,表头就会被挤到折行 ——
|
||||
// 实测"一个月"三个字被折成"一个"/"月",就是这么来的。
|
||||
val headStyle = cellStyle.copy(fontWeight = FontWeight.SemiBold)
|
||||
(0 until cols).map { c ->
|
||||
var w = 0
|
||||
for (r in -1 until block.rows.size) {
|
||||
val raw = if (r < 0) block.header[c] else block.rows[r][c]
|
||||
val plain = stripInlineMarks(raw)
|
||||
if (plain.isEmpty()) continue
|
||||
val style = if (r < 0) headStyle else cellStyle
|
||||
val measured = measurer.measure(AnnotatedString(plain), style).size.width
|
||||
if (measured > w) w = measured
|
||||
}
|
||||
(((w + pad + slack).coerceIn(minW, maxW)) / density.density).dp
|
||||
}
|
||||
}
|
||||
val totalWidth = widths.fold(0.dp) { acc, w -> acc + w }
|
||||
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
|
||||
Column(Modifier.clip(RoundedCornerShape(10.dp))) {
|
||||
// 表头:整行底色 + 加粗
|
||||
Row(Modifier.width(totalWidth).background(headBg)) {
|
||||
for (c in 0 until cols) {
|
||||
TableCell(
|
||||
text = block.header[c],
|
||||
width = widths[c],
|
||||
align = block.aligns[c],
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
bold = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(Modifier.width(totalWidth).height(1.dp).background(lineColor))
|
||||
for ((r, row) in block.rows.withIndex()) {
|
||||
if (r > 0) Box(Modifier.width(totalWidth).height(1.dp).background(lineColor))
|
||||
Row(Modifier.width(totalWidth)) {
|
||||
for (c in 0 until cols) {
|
||||
TableCell(
|
||||
text = row[c],
|
||||
width = widths[c],
|
||||
align = block.aligns[c],
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TableCell(
|
||||
text: String,
|
||||
width: Dp,
|
||||
align: TextAlign,
|
||||
color: Color,
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
bold: Boolean = false,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.width(width)
|
||||
.padding(horizontal = CELL_PAD_H, vertical = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
// 单元格里也走行内解析 —— `**合计**`、`` `code` ``、链接都要生效
|
||||
inline(text, linkColor),
|
||||
fontSize = (fontSize - 2).sp,
|
||||
lineHeight = (lineHeight - 4).coerceAtLeast(fontSize).sp,
|
||||
fontWeight = if (bold) FontWeight.SemiBold else null,
|
||||
textAlign = align,
|
||||
color = color,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 单元格左右内边距 */
|
||||
private val CELL_PAD_H = 10.dp
|
||||
|
||||
/** 列宽下限:短列别被压成一条缝 */
|
||||
private val MIN_COL_W = 56.dp
|
||||
|
||||
/** 列宽上限:一格特别长时让它折行,别把整列撑出几屏 */
|
||||
private val MAX_COL_W = 240.dp
|
||||
|
||||
/* ------------------------------ 块级解析 ------------------------------ */
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
@@ -177,15 +371,146 @@ internal sealed interface MdBlock {
|
||||
data class Quote(val text: String) : MdBlock
|
||||
data class Code(val text: String, val lang: String = "") : MdBlock
|
||||
data object Divider : MdBlock
|
||||
|
||||
/** `- [ ] 待办` / `- [x] 做完了` */
|
||||
data class Task(val checked: Boolean, val text: String) : MdBlock
|
||||
|
||||
/**
|
||||
* 表格。
|
||||
*
|
||||
* [rows] 里每行的列数**已经补齐到 [header] 的长度**(缺的填空串)——
|
||||
* 模型偶尔会漏写某一行的某一列,渲染时按列取下标会越界。
|
||||
* 补在这里而不是渲染时,是因为对齐信息 [aligns] 也是按列来的,
|
||||
* 两处各补一次迟早会不一致。
|
||||
*/
|
||||
data class Table(
|
||||
val header: List<String>,
|
||||
val rows: List<List<String>>,
|
||||
val aligns: List<TextAlign>,
|
||||
) : MdBlock
|
||||
}
|
||||
|
||||
private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$")
|
||||
private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$")
|
||||
/** `- [ ] 待办` / `- [x] 已经做了`。**必须排在 [RE_BULLET] 前面判**,否则被当成普通项目符号 */
|
||||
private val RE_TASK = Regex("^\\s*[-*+]\\s+\\[([ xX])]\\s*(.*)$")
|
||||
private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$")
|
||||
private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$")
|
||||
private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$")
|
||||
private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$")
|
||||
|
||||
/** 表格分隔行里的一格:`---`、`:--`、`--:`、`:--:` 都算 */
|
||||
private val RE_TABLE_SEP_CELL = Regex("^:?-{1,}:?$")
|
||||
|
||||
/* ------------------------------ 表格 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 这一行像不像表格行。
|
||||
*
|
||||
* 判据是**至少两个竖线**(`|` 的数量,转义的 `\|` 不算)。
|
||||
* 两端有没有竖线都收 —— 合法 GFM 两种写法都允许:
|
||||
*
|
||||
* | 项目 | 钱 | 项目 | 钱
|
||||
* |---|---| ---|---
|
||||
*
|
||||
* ★ 为什么门槛定在 2 而不是 1:正文里"或者 a | b"这种带一个竖线的句子
|
||||
* 不算少,定 1 会把它们吃掉。
|
||||
*/
|
||||
private fun looksLikeTableRow(line: String): Boolean =
|
||||
line.replace("\\|", "").count { it == '|' } >= 2
|
||||
|
||||
/**
|
||||
* 拆一行表格。
|
||||
*
|
||||
* ★ 转义的竖线(`\|`)要**先换成占位符再切**,否则 `a \| b | c` 会被切成三格。
|
||||
* 占位符用 `\u0001`(正文里不可能出现的控制字符),切完换回来。
|
||||
*/
|
||||
internal fun splitTableRow(line: String): List<String> {
|
||||
var s = line.trim()
|
||||
if (s.startsWith("|")) s = s.substring(1)
|
||||
// 末尾的竖线要去掉,但如果它是转义的(`… \|`)就不是分隔符
|
||||
if (s.endsWith("|") && !s.endsWith("\\|")) s = s.dropLast(1)
|
||||
s = s.replace("\\|", "\u0001")
|
||||
return s.split('|').map { it.replace("\u0001", "|").trim() }
|
||||
}
|
||||
|
||||
/** `|---|:--:|---:|` 这种分隔行 */
|
||||
internal fun isTableSeparator(line: String): Boolean {
|
||||
if (!line.contains('-')) return false
|
||||
val cells = splitTableRow(line)
|
||||
if (cells.isEmpty()) return false
|
||||
return cells.all { it.isNotEmpty() && RE_TABLE_SEP_CELL.matches(it) }
|
||||
}
|
||||
|
||||
/** 分隔行里的冒号决定这一列的对齐方式 */
|
||||
private fun alignOf(cell: String): TextAlign = when {
|
||||
cell.startsWith(":") && cell.endsWith(":") -> TextAlign.Center
|
||||
cell.endsWith(":") -> TextAlign.End
|
||||
else -> TextAlign.Start
|
||||
}
|
||||
|
||||
private class TableRead(val block: MdBlock.Table, val next: Int)
|
||||
|
||||
/**
|
||||
* 从 [start] 行开始读一张表,读不出来返回 null(那就按普通段落处理)。
|
||||
*
|
||||
* 两种情况都认:
|
||||
* ① 标准 GFM —— 表头行 + `|---|---|` 分隔行 + 数据行
|
||||
* ② 模型忘了写分隔行,但**连着两行列数一致**(兜底)
|
||||
*
|
||||
* ★ 数据行读到"不像表格行"就停。不设这个终点的话,表格后面紧跟的正文
|
||||
* 会被一路吃进来(模型写表格后面常常直接接一段总结)。
|
||||
*/
|
||||
private fun readTable(lines: List<String>, start: Int): TableRead? {
|
||||
val headLine = lines.getOrNull(start) ?: return null
|
||||
if (!looksLikeTableRow(headLine)) return null
|
||||
val head = splitTableRow(headLine)
|
||||
if (head.size < 2) return null
|
||||
|
||||
val second = lines.getOrNull(start + 1)
|
||||
val aligns: List<TextAlign>
|
||||
val bodyStart: Int
|
||||
if (second != null && isTableSeparator(second)) {
|
||||
val sep = splitTableRow(second)
|
||||
// 分隔行少写几格(模型手抖)时按表头列数补成左对齐,别让下标越界
|
||||
aligns = (0 until head.size).map { c -> alignOf(sep.getOrElse(c) { "---" }) }
|
||||
bodyStart = start + 2
|
||||
} else if (second != null && looksLikeTableRow(second) && splitTableRow(second).size == head.size) {
|
||||
aligns = List(head.size) { TextAlign.Start }
|
||||
bodyStart = start + 1
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
val rows = ArrayList<List<String>>()
|
||||
var i = bodyStart
|
||||
while (i < lines.size && looksLikeTableRow(lines[i])) {
|
||||
val cells = splitTableRow(lines[i])
|
||||
if (cells.size < 2) break
|
||||
// ★ 按表头列数补齐 / 截断:模型偶尔多写一列或少写一列,
|
||||
// 不补的话渲染时按下标取会越界,截断是为了不让一行的多余列把整表撑歪
|
||||
rows.add((0 until head.size).map { c -> cells.getOrElse(c) { "" } })
|
||||
i += 1
|
||||
}
|
||||
if (rows.isEmpty()) return null
|
||||
return TableRead(MdBlock.Table(head, rows, aligns), i)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把行内标记去掉,只留纯文字 —— 给"量列宽"用。
|
||||
*
|
||||
* ★ 量宽必须用剥过的文本:`| **合计** |` 里的 `**` 不显示,
|
||||
* 按原文量出来的列会白白宽出一截。
|
||||
*/
|
||||
internal fun stripInlineMarks(s: String): String =
|
||||
RE_STRIP_LINK.replace(s) { it.groupValues[1] }
|
||||
.replace("~~", "")
|
||||
.replace("**", "")
|
||||
.replace("`", "")
|
||||
.replace("*", "")
|
||||
|
||||
private val RE_STRIP_LINK = Regex("\\[([^\\]]*)]\\([^)]*\\)")
|
||||
|
||||
internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
val out = ArrayList<MdBlock>()
|
||||
val lines = src.replace("\r\n", "\n").split("\n")
|
||||
@@ -216,6 +541,17 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
continue
|
||||
}
|
||||
|
||||
// 表格:多行结构,得像代码块那样整块吃掉(不能按行在 when 里判)
|
||||
if (looksLikeTableRow(line)) {
|
||||
val table = readTable(lines, i)
|
||||
if (table != null) {
|
||||
flushPara()
|
||||
out.add(table.block)
|
||||
i = table.next
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
when {
|
||||
line.isBlank() -> flushPara()
|
||||
|
||||
@@ -243,6 +579,13 @@ internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
continue
|
||||
}
|
||||
|
||||
// ★ 任务列表必须排在普通项目符号前面 —— `- [x] 干完了` 也满足 RE_BULLET
|
||||
RE_TASK.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_TASK.find(line)!!
|
||||
out.add(MdBlock.Task(m.groupValues[1].isNotBlank(), m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_BULLET.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim()))
|
||||
|
||||
243
android/app/src/main/java/com/doubao/lynxclone/ui/MeetNodeKit.kt
Normal file
243
android/app/src/main/java/com/doubao/lynxclone/ui/MeetNodeKit.kt
Normal file
@@ -0,0 +1,243 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import com.doubao.lynxclone.data.CustomNodeDef
|
||||
import com.doubao.lynxclone.data.MeetingNode
|
||||
import com.doubao.nodekit.CastKinds
|
||||
import com.doubao.nodekit.CustomNodePins
|
||||
import com.doubao.nodekit.JudgeKinds
|
||||
import com.doubao.nodekit.NodeCatalog
|
||||
import com.doubao.nodekit.NodeGeometry
|
||||
import com.doubao.nodekit.NodeSpecs
|
||||
import com.doubao.nodekit.NodeStyles
|
||||
import com.doubao.nodekit.NodeView
|
||||
import com.doubao.nodekit.Ops
|
||||
import com.doubao.nodekit.PinDecl
|
||||
import com.doubao.nodekit.PinKind
|
||||
import com.doubao.nodekit.PinSpec
|
||||
|
||||
/*
|
||||
* 会议节点库(`:nodekit`)和 App 之间的**唯一一层胶水**。
|
||||
*
|
||||
* ## 这层为什么必须存在,而且必须**薄**
|
||||
*
|
||||
* 库不认 App 的 `MeetingNode` / `CustomNodeDef`(那是刻意的,见 nodekit/Pins.kt 的
|
||||
* NodeView 注释)。所以中间要有人做转换。
|
||||
*
|
||||
* 危险的地方在于:这层一旦开始"顺手做点事"(补个默认值、改个判断、加个特例),
|
||||
* 它就变成了**第二份定义** —— 而这次的整个目的就是把散在 6 个地方的节点定义
|
||||
* 收成一份。所以这里只有三件事:
|
||||
*
|
||||
* 1. `MeetingNode` → [NodeView](纯字段搬运,**一个判断都不许有**)
|
||||
* 2. 库的 `Int` 颜色 → Compose 的 `Color`
|
||||
* 3. 库的扁平 API → App 原来的函数名(这样 `MeetingsScreen.kt` 里几百个
|
||||
* 调用点一行都不用改 —— 迁移的风险全压在这一层,而它能一眼看完全文)
|
||||
*
|
||||
* ★ 反过来也成立:**这里的每个 `fun` 都必须能在库里找到对应物**。
|
||||
* `scripts/verify-nodekit.py` 会检查这一点(数一遍适配层的函数是不是都只是转发)。
|
||||
*/
|
||||
|
||||
/* ------------------------------ 1. 类型转换 ------------------------------ */
|
||||
|
||||
/** App 的自定义节点定义 → 库只要的"引脚部分" */
|
||||
fun CustomNodeDef.toPins(): CustomNodePins = CustomNodePins(
|
||||
inputs = inputs.map { PinDecl(it.name, it.type) },
|
||||
outputs = outputs.map { PinDecl(it.name, it.type) },
|
||||
)
|
||||
|
||||
/**
|
||||
* App 的节点 → 库认识的节点视图。
|
||||
*
|
||||
* ★ [varTypes] 是必须的:写变量的入口类型、读变量的出口类型都按变量登记表查,
|
||||
* 写死 `str` 的话 num 变量的线接不到运算节点上(这个 bug 真出现过)。
|
||||
*/
|
||||
fun MeetingNode.nodeView(
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): NodeView = NodeView(
|
||||
type = type,
|
||||
op = op,
|
||||
varName = varName,
|
||||
valueType = valueType,
|
||||
castTo = castTo,
|
||||
customKey = customKey,
|
||||
custom = custom.firstOrNull { it.key == customKey }?.toPins(),
|
||||
varTypes = varTypes,
|
||||
)
|
||||
|
||||
/* ------------------------------ 2. 引脚 ------------------------------ */
|
||||
|
||||
/** 输入引脚。实现只有一句:转成 NodeView 交给库 */
|
||||
fun inputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): List<PinSpec> = NodeSpecs.inputPins(node.nodeView(custom, varTypes))
|
||||
|
||||
/** 输出引脚。同上 */
|
||||
fun outputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): List<PinSpec> = NodeSpecs.outputPins(node.nodeView(custom, varTypes))
|
||||
|
||||
/* ------------------------------ 3. 几何 ------------------------------ */
|
||||
|
||||
/** 卡片宽度(画布上所有布局都按它算) */
|
||||
internal const val NODE_W = NodeGeometry.WIDTH
|
||||
|
||||
/** 顶部彩色标题栏的高度 */
|
||||
internal const val HEADER_H = NodeGeometry.HEADER_H
|
||||
|
||||
/** 一行引脚占的高度 */
|
||||
internal const val PIN_ROW_H = NodeGeometry.PIN_ROW_H
|
||||
|
||||
/** 引脚下面的内容区 */
|
||||
internal const val BODY_H = NodeGeometry.BODY_H
|
||||
|
||||
/** 引脚画多大 / 命中范围多大 */
|
||||
internal const val PORT_R = NodeGeometry.PORT_R
|
||||
internal const val PORT_HIT = NodeGeometry.PORT_HIT
|
||||
|
||||
/** 画布右下留的空白 */
|
||||
internal const val CANVAS_MARGIN = NodeGeometry.MARGIN
|
||||
|
||||
/** 节点高矮跟着引脚数走 */
|
||||
fun nodeHeight(
|
||||
node: MeetingNode,
|
||||
customDefs: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): Float = NodeGeometry.height(node.nodeView(customDefs, varTypes))
|
||||
|
||||
/** 第 index 个引脚的坐标 */
|
||||
fun pinPos(node: MeetingNode, index: Int, isOutput: Boolean): Offset =
|
||||
NodeGeometry.pinPos(node.x, node.y, index, isOutput)
|
||||
|
||||
/** 按 (种类, 分支) 找输出引脚的序号 */
|
||||
fun outPinIndex(node: MeetingNode, kind: String, branch: String): Int =
|
||||
NodeGeometry.outPinIndex(node.nodeView(), kind, branch)
|
||||
|
||||
/** 输入端口的位置 */
|
||||
fun portIn(
|
||||
node: MeetingNode,
|
||||
kind: String,
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
pinKey: String = "",
|
||||
): Offset = NodeGeometry.portIn(node.nodeView(varTypes = varTypes), node.x, node.y, kind, pinKey)
|
||||
|
||||
/** 输出端口的位置 */
|
||||
fun portOut(
|
||||
node: MeetingNode,
|
||||
kind: String,
|
||||
branch: String,
|
||||
pinKey: String = "",
|
||||
): Offset = NodeGeometry.portOut(node.nodeView(), node.x, node.y, kind, branch, pinKey)
|
||||
|
||||
/** 画布要多大 */
|
||||
fun canvasSize(nodes: List<MeetingNode>): Pair<Float, Float> =
|
||||
NodeGeometry.canvasSize(nodes.map { Triple(it.x, it.y, nodeHeight(it)) })
|
||||
|
||||
/** 平移量的夹取 */
|
||||
fun clampPan(
|
||||
x: Float, y: Float,
|
||||
viewW: Float, viewH: Float,
|
||||
contentW: Float, contentH: Float,
|
||||
): Pair<Float, Float> = NodeGeometry.clampPan(x, y, viewW, viewH, contentW, contentH)
|
||||
|
||||
/* ------------------------------ 4. 配色 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 节点标题栏颜色。
|
||||
*
|
||||
* ★ 这里没有 `when` —— 颜色在库里跟着节点类型走(`NodeCatalog`)。
|
||||
* 以前这个函数是 31 行的 when,加一种节点忘改它就少一个颜色,
|
||||
* 而且**不报错**(默默落到"智能体蓝")。
|
||||
*/
|
||||
fun nodeColor(type: String): Color = Color(NodeCatalog.color(type))
|
||||
|
||||
/** 数据引脚按类型上色 */
|
||||
fun pinColor(kind: String): Color = Color(NodeStyles.pinColor(kind))
|
||||
|
||||
/** 按**引脚**算颜色:收全部类型的引脚是紫的 */
|
||||
fun pinColorOf(pin: PinSpec): Color = Color(NodeStyles.pinColorOf(pin))
|
||||
|
||||
/**
|
||||
* 引脚的边框色。
|
||||
*
|
||||
* ★ 库给的是不透明色,这里统一加 0.85 的透明度 —— 描边比填充淡一点才好看。
|
||||
* 这个"淡一点"是**渲染方的事**,所以留在这一层(库不该知道我们要多淡)。
|
||||
*/
|
||||
fun pinBorder(kind: String): Color = pinColor(kind).copy(alpha = 0.85f)
|
||||
|
||||
/** 执行引脚的描边色(白引脚描在浅色背景上,不描边看不见) */
|
||||
val EXEC_BORDER: Color = Color(NodeStyles.EXEC_BORDER)
|
||||
|
||||
/** 连线的颜色(数据线按类型、exec 线按分支真假) */
|
||||
fun wireColor(pin: PinSpec): Color = Color(NodeStyles.wireColor(pin))
|
||||
|
||||
/**
|
||||
* 一条线的类型说明(鼠标/长按提示里用)。
|
||||
*
|
||||
* ★ 这**不是** `PinKind.label`:那是"文本/数字/真假"(说数据类型),
|
||||
* 这是"str 数据线/执行线"(说线的种类)。用户看到的是后者。
|
||||
*/
|
||||
fun kindLabel(kind: String): String = when (kind) {
|
||||
PinKind.EXEC -> "执行线"
|
||||
PinKind.BOOL -> "bool 数据线"
|
||||
PinKind.NUM -> "num 数据线"
|
||||
PinKind.LEGACY_DATA -> "str 数据线"
|
||||
else -> "str 数据线"
|
||||
}
|
||||
|
||||
/** 变量类型的中文名 */
|
||||
fun typeLabel(type: String): String = PinKind.label(type)
|
||||
|
||||
/**
|
||||
* 变量 / 值节点的类型选项。
|
||||
*
|
||||
* ★ 这四项以前在界面里**逐字重复了三处**(变量管理、值节点、转换节点),
|
||||
* 加一种类型必然漏改一处 —— 而漏改的表现是"某个界面选不到新类型",
|
||||
* 不报错、也没人会发现。现在只有这一份。
|
||||
*/
|
||||
val VARIABLE_TYPE_OPTIONS: List<Pair<String, String>> =
|
||||
PinKind.DATA.map { it to PinKind.labelWithKey(it) }
|
||||
|
||||
/**
|
||||
* 转换节点的目标类型选项。
|
||||
*
|
||||
* ★ 单独一份而不是复用 [VARIABLE_TYPE_OPTIONS]:这两个列表**现在**内容一样,
|
||||
* 但意思不同("变量能是什么类型" vs "能转成什么类型")——
|
||||
* 将来变量加了新类型,不代表转换也支持。混用一次就分不开了。
|
||||
*/
|
||||
val CAST_TYPE_OPTIONS: List<Pair<String, String>> =
|
||||
CastKinds.ALL.map { it to PinKind.labelWithKey(it) }
|
||||
|
||||
/**
|
||||
* 判断条件的可选项。
|
||||
*
|
||||
* ★ 正常情况下用内核给的(`meetingMeta.judgeKinds`,那是权威);这里只是
|
||||
* **meta 还没加载到时的兜底** —— 以前 meta 为空时那个选择器是空的,
|
||||
* 用户点开一片空白,会以为界面坏了。
|
||||
*/
|
||||
val JUDGE_KIND_OPTIONS: List<Pair<String, String>> = JudgeKinds.ALL
|
||||
|
||||
/* ------------------------------ 5. 算子 ------------------------------ */
|
||||
|
||||
/** `(键, 显示名)` 列表 —— 配置面板里的下拉项 */
|
||||
val OPS_UI: List<Pair<String, String>> = Ops.ALL.map { it.key to it.label }
|
||||
|
||||
/** 算子的显示名 */
|
||||
fun opLabel(key: String): String = Ops.label(key)
|
||||
|
||||
/**
|
||||
* 算子的 `(入口类型, 出口类型, 要几个输入)`。
|
||||
*
|
||||
* ★ 保留这个三元组而不是直接换成 `Ops.of()`:调用点有 4 处(引脚表 + 配置面板),
|
||||
* 换签名要动它们全部,而它们本来就是按三元组用的。
|
||||
* `opSpec` 自己只有三行,且**不含任何规则**(规则在 `Ops.ALL` 那张表里)。
|
||||
*/
|
||||
fun opSpec(key: String): Triple<String, String, Int> {
|
||||
val op = Ops.of(key)
|
||||
return Triple(op.inType, op.outType, op.arity)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,147 @@
|
||||
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.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.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.Layers
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
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.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* ★★ 「更多功能」—— 抽屉里放不下的那些入口收在这儿。
|
||||
*
|
||||
* ## 为什么要这么改(用户反馈:"太挤了对话都没了")
|
||||
*
|
||||
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
|
||||
*
|
||||
* 现在抽屉第一层只留天天用的(新话题 / 智能体 / 笔记 / 模型),
|
||||
* 其余收进这里。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
* `← 返回 | 标题`,和别的全屏界面一套顶栏。
|
||||
* 不用折叠面板:折叠起来每次都要展开一次,反而更麻烦。
|
||||
*/
|
||||
@Composable
|
||||
fun MoreSheetScreen(
|
||||
onOpenAiScreens: () -> Unit,
|
||||
onOpenSkills: () -> Unit,
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("更多功能", onBack = onClose)
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Dashboard,
|
||||
title = "AI 界面",
|
||||
subtitle = "AI 弹过的界面都存着,点一下就能再打开",
|
||||
) { onOpenAiScreens() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
title = "技能 · 连接器",
|
||||
subtitle = "Python 工具、MCP 服务、界面能力开关",
|
||||
) { onOpenSkills() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.AccountTree,
|
||||
title = "会议模式",
|
||||
subtitle = "多个智能体一起讨论,可以搭流程图",
|
||||
) { onOpenMeetings() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Terminal,
|
||||
title = "终端",
|
||||
subtitle = "内置 Termux,真 Linux 环境",
|
||||
) { onOpenTerminal() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Settings,
|
||||
title = "设置",
|
||||
subtitle = "模型、语音、外观、数据",
|
||||
) { onOpenSettings() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoreRow(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(subtitle, fontSize = 12.sp, lineHeight = 17.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.doubao.nodekit.NodeCatalog
|
||||
import com.doubao.nodekit.NodeShape
|
||||
import com.doubao.nodekit.NodeShapes
|
||||
|
||||
/*
|
||||
* 节点形状的小图标。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 节点的"形状"在库里是一个字段([NodeShape]),但字段本身用户看不见 ——
|
||||
* 得有人把它画出来。这里就是那个"画"的地方,两处用它:
|
||||
*
|
||||
* · 「加节点」面板里每个类型前面的缩略图 —— **选之前**就看出这是起点、
|
||||
* 判断、循环还是纯数据节点
|
||||
* · 节点卡片标题栏左边的小白形状 —— 图大了以后靠它认节点
|
||||
*
|
||||
* ## 为什么不直接在库里写 @Composable
|
||||
*
|
||||
* 库刻意不依赖 Compose **运行时**(只依赖 `Path` 那几个值类型),
|
||||
* 这样它才能被单元测试直接跑、也不用拖着 compose runtime 走。
|
||||
* 画的那一步(`Canvas` / `drawPath`)留在 App 这边。
|
||||
*
|
||||
* 形状的**路径**仍然只有一份 —— 库里的 `NodeShapes.path()`。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 按节点类型画形状徽标(自动取该类型的颜色)。
|
||||
*
|
||||
* 用在「加节点」面板那种"还没创建、只知道类型"的地方。
|
||||
*/
|
||||
@Composable
|
||||
fun NodeShapeBadge(
|
||||
type: String,
|
||||
size: Dp = 22.dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
NodeShapeBadge(
|
||||
shape = NodeCatalog.shape(type),
|
||||
color = Color(NodeCatalog.color(type)),
|
||||
size = size,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按形状 + 颜色画徽标。
|
||||
*
|
||||
* [filled] = true 时填色(面板里用,颜色淡一点做底 + 描边),
|
||||
* false 时只描边(标题栏里用白色描边太重,所以那边直接填白)。
|
||||
*/
|
||||
@Composable
|
||||
fun NodeShapeBadge(
|
||||
shape: NodeShape,
|
||||
color: Color,
|
||||
size: Dp = 22.dp,
|
||||
strokeWidth: Dp = 1.6.dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Canvas(modifier.size(size)) {
|
||||
val p = NodeShapes.thumbPath(shape, this.size.width)
|
||||
// 淡底 + 实描边:小尺寸下只有描边会看不清,只有实心又显得太重
|
||||
drawPath(p, color = color.copy(alpha = 0.16f))
|
||||
drawPath(p, color = color, style = Stroke(width = strokeWidth.toPx()))
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// 顶层构建脚本:只声明插件版本
|
||||
plugins {
|
||||
id("com.android.application") version "8.7.3" apply false
|
||||
// nodekit 是安卓库(要和 app 用同一个 AGP,版本必须一致)
|
||||
id("com.android.library") version "8.7.3" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
|
||||
// Kotlin 2.0 起 Compose 编译器是独立插件
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
|
||||
|
||||
@@ -62,14 +62,15 @@ UI_TOOLS_HINT = '\n'.join([
|
||||
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||||
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||||
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||||
' · wait=true = **等用户点一个回传按钮或关掉界面**(最多 timeout 秒,默认 120)。',
|
||||
' · wait=true = **等用户点一个回传按钮或关掉界面**(默认不限时,会一直等)。',
|
||||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。一般别传 timeout。',
|
||||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||||
' 它会**一直等你选完**再继续(默认不限时),所以你不用在正文里再问一遍、',
|
||||
' 更不能自己替用户假设一个答案往下写。',
|
||||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||||
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||||
])
|
||||
|
||||
@@ -768,6 +768,30 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
})
|
||||
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 写的界面可以再点开"。
|
||||
|
||||
@@ -248,6 +248,17 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待",
|
||||
被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。
|
||||
这个取舍必须让用户知道,所以超时消息里写清楚。
|
||||
|
||||
★★ `timeout_s <= 0` = **不限时**(一直等到它跑完)。
|
||||
|
||||
给"停下来等用户"的那类工具用(`ask_user` / `show_ui` 的 wait 模式)——
|
||||
它们的耗时**完全取决于用户什么时候点**,60 秒的上限只会造成:
|
||||
弹窗还开着、用户 5 分钟后才选,而模型早就收到"工具执行超时"、
|
||||
于是按自己猜的答案往下写了。
|
||||
|
||||
为什么默认仍然是 60 秒:这是"工具里写了死循环"的安全网
|
||||
(不让整个内核跟着卡死)。会等用户的工具属于**设计上就该慢**,
|
||||
由工具自己声明 `WAIT_FOR_USER = True` 来豁免,见 tools_runtime。
|
||||
"""
|
||||
box = {}
|
||||
|
||||
@@ -259,9 +270,13 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
|
||||
thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True)
|
||||
thread.start()
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
if timeout_s and timeout_s > 0:
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
else:
|
||||
# 不限时:join() 不带参数就是一直等
|
||||
thread.join()
|
||||
if 'error' in box:
|
||||
raise box['error']
|
||||
return box.get('value')
|
||||
|
||||
@@ -36,6 +36,10 @@ BUNDLED_TOOL_FILES = [
|
||||
'end_conversation.py',
|
||||
# AI 主动往当前会话里发一条消息(带防死循环的闸,见 app.py /api/session-message)
|
||||
'send_message.py',
|
||||
# 操作手机:读通知 / 开 App / 调音量
|
||||
'notifications.py',
|
||||
'apps.py',
|
||||
'volume.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
|
||||
@@ -158,6 +158,10 @@ CAST_KINDS = (
|
||||
('str', '转成文本'),
|
||||
('bool', '转成真假'),
|
||||
('num', '转成数字'),
|
||||
# ★ 补上 list:`_cast_to()` 一直允许 list(它按 PIN_TYPES 校验),
|
||||
# 界面上的转换节点也一直能选 list —— 只有这份清单少写了一项。
|
||||
# (对拍脚本 scripts/verify-nodekit.py 抓出来的)
|
||||
('list', '转成列表'),
|
||||
)
|
||||
|
||||
# (键, 名字, 输入类型, 输出类型, 要几个输入)
|
||||
|
||||
@@ -73,6 +73,15 @@ class Paths:
|
||||
# ★ 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')
|
||||
@@ -93,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, self.screens_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,6 +14,7 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
@@ -540,6 +541,197 @@ def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
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:
|
||||
|
||||
@@ -35,6 +35,33 @@ _loaded_modules: dict = {}
|
||||
TOOL_TIMEOUT_S = 60
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 会"停下来等用户"的工具:执行超时对它们不适用
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 这个坑很隐蔽,记下来:
|
||||
#
|
||||
# 用户要求"AI 询问界面不要限时",我把弹窗那侧改成了无限等(`AiSurface.ask`),
|
||||
# 实测弹窗确实 135 秒还在 —— **但工具调用在 60 秒时就被内核判超时了**,
|
||||
# 模型收到的是"工具执行超时(60s)",用户五分钟后点的那个选项**根本回不到
|
||||
# 模型手里**。表现就是"弹窗还在、但 AI 已经自己往下写了"。
|
||||
#
|
||||
# 所以"不限时"必须**三处一起改**才算数:
|
||||
# ① 界面侧等多久(AiSurface)
|
||||
# ② 内核侧给工具多少时间(这里)
|
||||
# ③ 工具自己声明的 timeout(tools/ask_user.py、tools/show_ui.py)
|
||||
#
|
||||
# 判定方式:工具模块里声明 `WAIT_FOR_USER = True`。
|
||||
# 放在工具文件里而不是在这个列表里硬编码 —— 加新工具时不会漏(写工具的人
|
||||
# 自己知道它会不会等用户)。
|
||||
def _waits_for_user(name: str, spec: dict, module) -> bool:
|
||||
"""这个工具会不会停下来等用户交互"""
|
||||
if spec.get('_builtin'):
|
||||
return bool((BUILTIN_TOOLS.get(name) or {}).get('WAIT_FOR_USER'))
|
||||
return bool(getattr(module, 'WAIT_FOR_USER', False))
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 界面工具的开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -320,8 +347,12 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
_ctx.value = None
|
||||
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S)
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死。
|
||||
# ★ 会等用户的工具(ask_user / show_ui 的 wait 模式)**不限时** ——
|
||||
# 它们的耗时取决于用户什么时候点,给上限等于"用户想久了 AI 就自己编"。
|
||||
# 见 _waits_for_user 的注释。
|
||||
budget = 0 if _waits_for_user(name, spec, module) else TOOL_TIMEOUT_S
|
||||
outcome = run_with_timeout(_invoke, budget)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
|
||||
77
android/nodekit/build.gradle.kts
Normal file
77
android/nodekit/build.gradle.kts
Normal file
@@ -0,0 +1,77 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
/*
|
||||
* ★ 刻意**不挂** `org.jetbrains.kotlin.plugin.compose`。
|
||||
*
|
||||
* 这个库里没有任何 `@Composable` 函数 —— 唯一用到 Compose 的地方是
|
||||
* [com.doubao.nodekit.NodeShapes],而它只用 `Path` / `Rect` / `CornerRadius`
|
||||
* 这些**普通值类型**(画形状是渲染方的事,库只负责给出路径)。
|
||||
*
|
||||
* 挂了那个插件就必须把 compose runtime 也塞进 classpath,
|
||||
* 否则报 "The Compose Compiler requires the Compose Runtime to be on the
|
||||
* class path" —— 一个纯规则库不该被拖进运行时依赖。
|
||||
*/
|
||||
}
|
||||
|
||||
/**
|
||||
* 会议节点定义库。
|
||||
*
|
||||
* ## 为什么是独立 module 而不是 app 里的一个包
|
||||
*
|
||||
* 这套"节点形式"(有哪些节点、每个节点什么引脚、什么颜色、什么形状、
|
||||
* 卡片多高、连线从哪儿出去)以前**全散在 MeetingsScreen.kt 的 8485 行里**,
|
||||
* 而且全是 `private`,同一个概念在 6 个地方各写一遍。
|
||||
*
|
||||
* 抽成独立 module 的目的是让"不能复用"变成**编译期就做不到**:
|
||||
* · 库看不到 app 的 `MeetingNode` / `CustomNodeDef`,只能收自己定义的
|
||||
* [com.doubao.nodekit.NodeView] —— 于是"节点定义"和"节点数据"被迫分开
|
||||
* · 库看不到 `isDark()` / `Doubao.Blue` / `AppViewModel` —— 于是主题色
|
||||
* 只能靠**参数**传进来,不会偷偷依赖界面状态
|
||||
* · 别的地方(积木编辑器、以后别的项目)能直接依赖它
|
||||
*
|
||||
* ## 刻意不依赖 Compose
|
||||
*
|
||||
* 库里的定义、引脚表、算子表、几何计算**一行 Compose 都没有**,
|
||||
* 只依赖标准库。原因:
|
||||
* · 这些是"规则",规则不该长在渲染框架上
|
||||
* · 不依赖 Compose 才能被**单元测试**直接跑(JVM 上不需要起 Android)
|
||||
* · 颜色用 `Int`(ARGB)存,渲染方自己 `Color(int)` 转
|
||||
*
|
||||
* 唯一带 Compose 的是 [com.doubao.nodekit.NodeShapes](形状的 Path),
|
||||
* 它单独一个文件,不用形状的人不受影响。
|
||||
*/
|
||||
android {
|
||||
namespace = "com.doubao.nodekit"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
// ★ 不开 compose:库里没有 @Composable,见文件头的 plugins 注释
|
||||
compose = false
|
||||
}
|
||||
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// 形状用到 Compose 的 Path / Rect / CornerRadius(都是普通值类型,不是 @Composable)。
|
||||
// 版本跟 app 的 compose-bom 走 —— 这里用 implementation 而不是锁死版本,
|
||||
// 免得和 app 的 compose 版本打架
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui-graphics")
|
||||
}
|
||||
216
android/nodekit/src/main/java/com/doubao/nodekit/Catalog.kt
Normal file
216
android/nodekit/src/main/java/com/doubao/nodekit/Catalog.kt
Normal file
@@ -0,0 +1,216 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/**
|
||||
* 节点类型。
|
||||
*
|
||||
* ## ★★ 这就是"节点形式"的清单,以前它被抄了 6 遍
|
||||
*
|
||||
* 1. `android/kernel/meeting.py:46` `NODE_TYPES`(13 种,权威)
|
||||
* 2. `android/kernel/app.py:1054` `/api/meeting/meta` 的 `nodeTypes`(12 种,漏 custom)
|
||||
* 3. `server/src/meeting.mjs:26` `NODE_TYPES`(6 种,落后)
|
||||
* 4. `MeetingsScreen.kt:7025` `nodeColor()` 的 when
|
||||
* 5. `MeetingsScreen.kt:3695` `inputPins()` 的 when
|
||||
* 6. `MeetingsScreen.kt:3893` `outputPins()` 的 when
|
||||
*
|
||||
* 结果是"加一种节点要改 6 个地方",漏一个的表现是**界面上少一个颜色分支**
|
||||
* 或者**引脚画不出来**,而且不报错。
|
||||
*
|
||||
* 现在 Kotlin 这边只有 [NodeCatalog] 这一份。引擎那边是 Python,跨语言没法
|
||||
* 共享代码,所以用 `scripts/verify-nodekit.py` **守门对拍**(这是这个仓库里
|
||||
* 跨语言一致性的标准做法)。
|
||||
*/
|
||||
object NodeKind {
|
||||
const val START = "start"
|
||||
const val AGENT = "agent"
|
||||
const val JUDGE = "judge"
|
||||
const val END = "end"
|
||||
const val VAR = "var"
|
||||
const val READVAR = "readvar"
|
||||
const val WHILE = "while"
|
||||
const val VALUE = "value"
|
||||
const val CAST = "cast"
|
||||
const val OP = "op"
|
||||
const val PY = "py"
|
||||
const val CUSTOM = "custom"
|
||||
const val BRANCH = "branch"
|
||||
|
||||
/** 全部内置类型。顺序 = 「加节点」面板里的顺序 */
|
||||
val ALL: List<String> = listOf(
|
||||
START, AGENT, JUDGE, BRANCH, WHILE, END,
|
||||
VAR, READVAR, VALUE, CAST, OP, PY, CUSTOM,
|
||||
)
|
||||
|
||||
/**
|
||||
* 用户能手动加的类型。
|
||||
*
|
||||
* ★ `custom` 不在里面:它不是"加一个节点",而是"先在 `nodes/` 目录里
|
||||
* 放一个 .py 声明",走的是另一条路(见 NodeManager)。
|
||||
*
|
||||
* ★ 注释里别写 `nodes/` 加通配符那种路径 —— Kotlin 的块注释**可以嵌套**,
|
||||
* 里面出现一个斜杠加星号就把整个注释吃掉了,报的错还是"缺少 }"
|
||||
* (我在这里踩过,找了半天)。
|
||||
*/
|
||||
val ADDABLE: List<String> = ALL.filter { it != CUSTOM }
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点在画布上的**形状**。
|
||||
*
|
||||
* ## 形状即语法
|
||||
*
|
||||
* 这条原则在积木编辑器里是落地的(帽形 / C 型 / 六边形),但在**会议画布上
|
||||
* 一直是"全是圆角矩形"** —— 唯一的类型区分是标题栏的颜色。用户看不出
|
||||
* "这个节点是起点还是终点、是判断还是动作",只能靠读标题。
|
||||
*
|
||||
* 现在每种类型声明自己的形状,画布上有两处用到它:
|
||||
* · 「加节点」面板里每个类型前面有一个形状缩略图(选之前就看出是什么)
|
||||
* · 节点卡片标题栏左边有一个小徽标(在图上也能认出来)
|
||||
*
|
||||
* 形状的含义(这条得和积木编辑器保持一致,别自成一套):
|
||||
*
|
||||
* Hat 帽形 事件入口 —— 整张图从这里开始,没有输入
|
||||
* Diamond 菱形 分支判断 —— 一进两出,走哪条看条件
|
||||
* Loop 六边形 循环 —— 条件成立就回去
|
||||
* Capsule 胶囊 纯数据节点 —— 没有 exec,不在执行链上,值是被"拉"的
|
||||
* Terminal 圆角粗边 终点 —— 交出结果,没有输出
|
||||
* Rect 圆角矩形 普通动作 —— 一进一出
|
||||
*/
|
||||
enum class NodeShape {
|
||||
Hat, Diamond, Loop, Capsule, Terminal, Rect,
|
||||
}
|
||||
|
||||
/**
|
||||
* 一种节点类型的全部元数据。
|
||||
*
|
||||
* [color] 是 `Int`(ARGB)而不是 Compose 的 `Color`:库不依赖 Compose,
|
||||
* 渲染方自己 `Color(spec.color)` 转一下。
|
||||
*/
|
||||
data class NodeSpec(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val desc: String,
|
||||
/** 标题栏颜色 */
|
||||
val color: Int,
|
||||
val shape: NodeShape,
|
||||
/** 卡片上没写标题时显示什么 */
|
||||
val defaultTitle: String,
|
||||
/**
|
||||
* 纯节点:没有 exec 引脚,不在执行链上。
|
||||
*
|
||||
* ★ 这不是"有没有数据引脚",而是"**会不会被执行到**" ——
|
||||
* 读变量 / 值 / 运算 / 转换都是纯节点,它们的值是被下游
|
||||
* 节点运行时**拉取**的。这就是"读变量为什么只有输出、没有 exec 入"的答案。
|
||||
*/
|
||||
val pure: Boolean = false,
|
||||
/** 有循环体(可以往里拖节点)*/
|
||||
val container: Boolean = false,
|
||||
) {
|
||||
/** 是不是"多条 exec 出口"的节点(判断 / 分支 / while) */
|
||||
val branching: Boolean
|
||||
get() = key == NodeKind.JUDGE || key == NodeKind.BRANCH || key == NodeKind.WHILE
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点目录:**唯一一份**节点类型表。
|
||||
*
|
||||
* 加一种节点时,改这里的 `ALL` 加一条 —— 颜色、形状、默认标题、引脚
|
||||
* ([NodeSpecs])、配置面板(使用方)都从这一条走。
|
||||
*/
|
||||
object NodeCatalog {
|
||||
/**
|
||||
* 颜色。
|
||||
*
|
||||
* ★ 取值有个原则:**同一族的东西同色系**(变量/运算都是青,值/转换都是紫),
|
||||
* 用户靠颜色记"这类节点干什么"。但判断(橙黄)和分支(橙红)特意
|
||||
* 分开了 —— 它们长得像、用途完全不同(判断按规则算、分支直接收真假)。
|
||||
*/
|
||||
private const val GREEN = 0xFF34A853.toInt()
|
||||
private const val ORANGE = 0xFFF29900.toInt()
|
||||
private const val ORANGE_RED = 0xFFE8710A.toInt()
|
||||
private const val PURPLE = 0xFF7B61FF.toInt()
|
||||
private const val LIGHT_PURPLE = 0xFF9C6ADE.toInt()
|
||||
private const val DEEP_PURPLE = 0xFF7E57C2.toInt()
|
||||
private const val TEAL = 0xFF00A0A0.toInt()
|
||||
private const val DEEP_TEAL = 0xFF00897B.toInt()
|
||||
private const val SLATE = 0xFF37474F.toInt()
|
||||
private const val MAGENTA = 0xFFAD1457.toInt()
|
||||
private const val RED = 0xFFD93025.toInt()
|
||||
|
||||
/** 普通智能体节点的颜色。和 App 主题的 `Doubao.Blue` 是同一个值 */
|
||||
const val DEFAULT_COLOR = 0xFF2B7BFF.toInt()
|
||||
|
||||
val ALL: List<NodeSpec> = listOf(
|
||||
NodeSpec(
|
||||
NodeKind.START, "开始事件", "整张图从这里开始(exec 起点)",
|
||||
GREEN, NodeShape.Hat, "初始输入",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.AGENT, "智能体", "一个智能体处理一轮",
|
||||
DEFAULT_COLOR, NodeShape.Rect, "智能体",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.JUDGE, "判断", "按条件分 true / false 两条路",
|
||||
ORANGE, NodeShape.Diamond, "判断",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.BRANCH, "分支", "收一个真假,走真/假两条 exec(和判断的区别:判断按规则算,分支直接收)",
|
||||
ORANGE_RED, NodeShape.Diamond, "分支",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.WHILE, "while 循环", "条件为真就跑循环体,像 C 的 while",
|
||||
RED, NodeShape.Loop, "while 循环", container = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.END, "最终输出", "汇总结果",
|
||||
PURPLE, NodeShape.Terminal, "最终输出",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.VAR, "写变量", "把内容存进一个变量,后面任何节点都能读",
|
||||
TEAL, NodeShape.Rect, "写变量",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.READVAR, "读变量", "纯节点:取变量当前值(只出数据,没有 exec)",
|
||||
TEAL, NodeShape.Capsule, "读变量", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.VALUE, "值", "纯节点:一个写死的值,接到智能体的数据输入",
|
||||
LIGHT_PURPLE, NodeShape.Capsule, "值", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.CAST, "转换", "纯节点:str / bool / num / list 互转",
|
||||
DEEP_PURPLE, NodeShape.Capsule, "转换", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.OP, "运算", "纯节点:+ − × ÷ % 拼接 取反 比较 逻辑",
|
||||
DEEP_TEAL, NodeShape.Capsule, "运算", pure = true,
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.PY, "Python", "写一段 Python(run(ctx)),也可以给智能体当工具调",
|
||||
SLATE, NodeShape.Rect, "Python",
|
||||
),
|
||||
NodeSpec(
|
||||
NodeKind.CUSTOM, "自定义", "用户自己在 nodes/ 里写的节点",
|
||||
MAGENTA, NodeShape.Rect, "自定义",
|
||||
),
|
||||
)
|
||||
|
||||
private val BY_KEY: Map<String, NodeSpec> = ALL.associateBy { it.key }
|
||||
|
||||
/** 查一种类型。查不到给一个"安全默认"(老数据里可能有已经删掉/改名的类型) */
|
||||
fun of(key: String): NodeSpec =
|
||||
BY_KEY[key] ?: NodeSpec(
|
||||
key, if (key.isBlank()) "节点" else key, "", DEFAULT_COLOR,
|
||||
NodeShape.Rect, if (key.isBlank()) "节点" else key,
|
||||
)
|
||||
|
||||
fun color(key: String): Int = of(key).color
|
||||
|
||||
fun label(key: String): String = of(key).label
|
||||
|
||||
fun shape(key: String): NodeShape = of(key).shape
|
||||
|
||||
/** 卡片上的标题(用户没自己写时) */
|
||||
fun defaultTitle(key: String): String = of(key).defaultTitle
|
||||
|
||||
fun isPure(key: String): Boolean = of(key).pure
|
||||
}
|
||||
169
android/nodekit/src/main/java/com/doubao/nodekit/Geometry.kt
Normal file
169
android/nodekit/src/main/java/com/doubao/nodekit/Geometry.kt
Normal file
@@ -0,0 +1,169 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
|
||||
/**
|
||||
* 节点的几何:卡片多高、第 n 个引脚在哪儿、一条线该从哪个点出发。
|
||||
*
|
||||
* ## 为什么这套尺寸值得单独拎出来
|
||||
*
|
||||
* 因为它**同时被四个地方用**,任何一处不一致就出鬼:
|
||||
*
|
||||
* 1. 卡片布局(`NodeCard` 的实际高度)
|
||||
* 2. 引脚绘制(Canvas 上的圆点位置)
|
||||
* 3. 连线绘制与命中(贝塞尔曲线的端点)
|
||||
* 4. 拖拽吸附 / 端口命中范围
|
||||
*
|
||||
* 以前这四处的常量都在 `MeetingsScreen.kt` 里各写一遍,而且已经出现了
|
||||
* **两个再也用不到的死常量**(`NODE_H = 88f`、`CANVAS_W/H`)—— 高度改成
|
||||
* 由 [height] 算了以后没人删它们,看代码的人会以为高度还是 88。
|
||||
*
|
||||
* ## 尺寸是"UE 蓝图式"的:标题栏 + 引脚行 + 内容区
|
||||
*
|
||||
* ┌────────────┐ ← WIDTH = 116
|
||||
* │ 标题栏 │ ← HEADER_H = 24
|
||||
* ├──●───────●─┤ ← 一行引脚 PIN_ROW_H = 21(引脚垂直居中在这行里)
|
||||
* ├──●───────●─┤
|
||||
* │ 内容预览 │ ← BODY_H = 34
|
||||
* └────────────┘
|
||||
*
|
||||
* 卡片高度**跟着引脚数走**:判断节点两行出线、智能体进出各两种,就高一些。
|
||||
*/
|
||||
object NodeGeometry {
|
||||
|
||||
/** 卡片宽度。定这个值的坑:内容区的说明文字两行 24 + 底部 14,留点余量 */
|
||||
const val WIDTH = 116f
|
||||
|
||||
/** 顶部彩色标题栏的高度 */
|
||||
const val HEADER_H = 24f
|
||||
|
||||
/** 一行引脚占的高度 */
|
||||
const val PIN_ROW_H = 21f
|
||||
|
||||
/** 引脚下面的内容区(预览文字 + 路数) */
|
||||
const val BODY_H = 34f
|
||||
|
||||
/** 引脚画多大 */
|
||||
const val PORT_R = 5.5f
|
||||
|
||||
/** 引脚的命中半径。比画出来的大一圈 —— 手指没那么准 */
|
||||
const val PORT_HIT = 19f
|
||||
|
||||
/** 画布右下留多少空白(节点能拖到多远)*/
|
||||
const val MARGIN = 900f
|
||||
|
||||
/**
|
||||
* 节点卡片的高度。
|
||||
*
|
||||
* ★ 高度只看**引脚个数**,类型不影响 —— 所以查不到变量类型时
|
||||
* (名字不对但行数还是 1)也画得对。
|
||||
*/
|
||||
fun height(view: NodeView): Float {
|
||||
val rows = maxOf(
|
||||
NodeSpecs.inputPins(view).size,
|
||||
NodeSpecs.outputPins(view).size,
|
||||
1,
|
||||
)
|
||||
return HEADER_H + rows * PIN_ROW_H + BODY_H
|
||||
}
|
||||
|
||||
/**
|
||||
* 第 [index] 个引脚的坐标。
|
||||
*
|
||||
* 在标题栏下面第 index 行、垂直居中;输入贴左边、输出贴右边 ——
|
||||
* 和蓝图一致,连线从节点边缘出发 / 接入。
|
||||
*/
|
||||
fun pinPos(nodeX: Float, nodeY: Float, index: Int, isOutput: Boolean): Offset {
|
||||
val y = nodeY + HEADER_H + PIN_ROW_H * index + PIN_ROW_H / 2f
|
||||
val x = if (isOutput) nodeX + WIDTH else nodeX
|
||||
return Offset(x, y)
|
||||
}
|
||||
|
||||
/** 按 (种类, 分支) 找输出引脚的序号;找不到就退回第一条(老数据容错) */
|
||||
fun outPinIndex(view: NodeView, kind: String, branch: String): Int {
|
||||
val pins = NodeSpecs.outputPins(view)
|
||||
val exact = pins.indexOfFirst {
|
||||
it.kind == kind && (it.kind != PinKind.EXEC || it.key == branch)
|
||||
}
|
||||
if (exact >= 0) return exact
|
||||
val byBranch = pins.indexOfFirst { it.kind == PinKind.EXEC && it.key == branch }
|
||||
return if (byBranch >= 0) byBranch else 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 输入端口的位置。
|
||||
*
|
||||
* data 线接"值/输入"那条;exec 线接"▶"那条。
|
||||
* 找不到对应种类时退回第一条 —— 老会议里没有 kind 字段,边一律当 exec,
|
||||
* 而老图的节点只有一条入线,退回第一条正好对上。
|
||||
*/
|
||||
fun portIn(
|
||||
view: NodeView,
|
||||
nodeX: Float,
|
||||
nodeY: Float,
|
||||
kind: String,
|
||||
/** 边上记的引脚 key。有就**按 key 精确定位** ——
|
||||
* 运算的 A/B 都是 num,不靠它分不开(表现就是两条线都落在 A 上、B 收不到) */
|
||||
pinKey: String = "",
|
||||
): Offset {
|
||||
val pins = NodeSpecs.inputPins(view)
|
||||
if (pinKey.isNotBlank()) {
|
||||
val byKey = pins.indexOfFirst { it.key == pinKey }
|
||||
if (byKey >= 0) return pinPos(nodeX, nodeY, byKey, isOutput = false)
|
||||
}
|
||||
// ★ 按"这个入口能不能接 kind"来找,不是 kind 相等 ——
|
||||
// while 的条件入口能接 bool 和 str,两种情况都得能定位到同一条引脚。
|
||||
val index = pins.indexOfFirst { it.accepts_(kind) }
|
||||
return pinPos(nodeX, nodeY, if (index >= 0) index else 0, isOutput = false)
|
||||
}
|
||||
|
||||
/** 输出端口的位置 */
|
||||
fun portOut(
|
||||
view: NodeView,
|
||||
nodeX: Float,
|
||||
nodeY: Float,
|
||||
kind: String,
|
||||
branch: String,
|
||||
/** 边上记的引脚 key(同 [portIn];只有自定义节点有多个同名类型的数据出口时才用得上) */
|
||||
pinKey: String = "",
|
||||
): Offset {
|
||||
val pins = NodeSpecs.outputPins(view)
|
||||
if (pinKey.isNotBlank()) {
|
||||
val byKey = pins.indexOfFirst { it.key == pinKey }
|
||||
if (byKey >= 0) return pinPos(nodeX, nodeY, byKey, isOutput = true)
|
||||
}
|
||||
return pinPos(nodeX, nodeY, outPinIndex(view, kind, branch), isOutput = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 画布要多大(所有节点都要装得下,再留一圈边)。
|
||||
*
|
||||
* [sizes] 是每个节点的 (x, y, 高度)。
|
||||
*/
|
||||
fun canvasSize(sizes: List<Triple<Float, Float, Float>>): Pair<Float, Float> {
|
||||
var maxX = 0f
|
||||
var maxY = 0f
|
||||
for ((x, y, h) in sizes) {
|
||||
if (x + WIDTH > maxX) maxX = x + WIDTH
|
||||
if (y + h > maxY) maxY = y + h
|
||||
}
|
||||
return Pair(maxX + MARGIN, maxY + MARGIN)
|
||||
}
|
||||
|
||||
/**
|
||||
* 平移量的夹取:内容比视口小的时候不允许拖出空白。
|
||||
*
|
||||
* ★ `minOf(0f, ...)` 是必须的:内容比视口小时的合法范围是
|
||||
* `[viewW - contentW, 0]`,而那个上界是**负数**;
|
||||
* 直接用 `coerceIn(viewW - contentW, 0f)` 反而对。
|
||||
* 写反了的表现是"小图能拖到天上去"。
|
||||
*/
|
||||
fun clampPan(
|
||||
x: Float, y: Float,
|
||||
viewW: Float, viewH: Float,
|
||||
contentW: Float, contentH: Float,
|
||||
): Pair<Float, Float> = Pair(
|
||||
x.coerceIn(minOf(0f, viewW - contentW), 0f),
|
||||
y.coerceIn(minOf(0f, viewH - contentH), 0f),
|
||||
)
|
||||
}
|
||||
138
android/nodekit/src/main/java/com/doubao/nodekit/NodeShapes.kt
Normal file
138
android/nodekit/src/main/java/com/doubao/nodekit/NodeShapes.kt
Normal file
@@ -0,0 +1,138 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.geometry.RoundRect
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.PathOperation
|
||||
|
||||
/**
|
||||
* 形状的画法。
|
||||
*
|
||||
* ## 形状即语法(这次是真的落在会议画布上了)
|
||||
*
|
||||
* 积木编辑器里形状一直是语法(帽形 = 事件、C 型 = 容器、六边形 = 真假值)。
|
||||
* 但**会议画布上所有节点都是圆角矩形** —— 用户只能靠标题栏颜色和文字认节点。
|
||||
* 颜色有 13 种,记不住;形状只有 6 种,一眼能认。
|
||||
*
|
||||
* 所以 [NodeShape] 是 [NodeCatalog] 里每种节点的一个字段,这里负责把它画出来。
|
||||
* 用到的两处:
|
||||
*
|
||||
* 1. 「加节点」面板里每个类型前面的**缩略图** —— 选之前就看出这是起点还是判断
|
||||
* 2. 节点卡片标题栏左边的**小徽标** —— 在密密麻麻的图上也能认出来
|
||||
*
|
||||
* ## 为什么形状是"圆角矩形 + 局部变形"而不是纯菱形/纯六边形
|
||||
*
|
||||
* 因为节点卡片里要装东西:标题栏 24 + 引脚行 21×N + 内容 34。
|
||||
* 画成真正的菱形,四个角全是空的,引脚反而没地方放(引脚必须贴在左右边缘上,
|
||||
* 那是连线出发的位置,不能为了形状把线挪走)。
|
||||
*
|
||||
* 所以每种形状都只在**边缘**做变化,中间那块留给内容和引脚:
|
||||
*
|
||||
* Hat 顶部凸一个圆顶 ("这是起点")
|
||||
* Diamond 四角斜切 ("这里分叉")
|
||||
* Loop 左右两端收成尖 ("会回到这里")
|
||||
* Capsule 左右全圆(胶囊) ("它不执行,只提供值")
|
||||
* Terminal 上边两角斜切 ("到这里结束")
|
||||
* Rect 普通圆角矩形 ("普通动作")
|
||||
*/
|
||||
object NodeShapes {
|
||||
|
||||
/** 普通圆角半径 */
|
||||
const val RADIUS = 8f
|
||||
|
||||
/** 斜切量占短边的比例 */
|
||||
private const val CHAMFER = 0.22f
|
||||
|
||||
/**
|
||||
* 画一个形状。
|
||||
*
|
||||
* [w] / [h] 是外接矩形;画出来的东西**不会超出**这个矩形
|
||||
* (除了 [NodeShape.Hat] 的圆顶 —— 它也会被压在里面,只是主体下移)。
|
||||
*/
|
||||
fun path(shape: NodeShape, w: Float, h: Float): Path {
|
||||
if (w <= 0f || h <= 0f) return Path()
|
||||
val cut = minOf(w, h) * CHAMFER
|
||||
return when (shape) {
|
||||
NodeShape.Rect -> roundRectPath(w, h, RADIUS)
|
||||
|
||||
NodeShape.Capsule -> roundRectPath(w, h, minOf(w, h) / 2f)
|
||||
|
||||
// 帽形:下面一个圆角矩形,上面扣一个圆顶(两者求并集)
|
||||
NodeShape.Hat -> {
|
||||
val dome = h * 0.22f
|
||||
val body = roundRectPath(w, h - dome, RADIUS)
|
||||
body.translate(Offset(0f, dome))
|
||||
val cap = Path().apply {
|
||||
addOval(Rect(w * 0.16f, 0f, w * 0.84f, dome * 2f))
|
||||
}
|
||||
// ★ op 会改第一个参数(base)本身,所以先算 base 再传
|
||||
Path().apply {
|
||||
op(body, cap, PathOperation.Union)
|
||||
}
|
||||
}
|
||||
|
||||
// 菱形(其实是四角斜切的矩形,见类注释)
|
||||
NodeShape.Diamond -> polyPath(
|
||||
listOf(
|
||||
Offset(cut, 0f), Offset(w - cut, 0f),
|
||||
Offset(w, cut), Offset(w, h - cut),
|
||||
Offset(w - cut, h), Offset(cut, h),
|
||||
Offset(0f, h - cut), Offset(0f, cut),
|
||||
),
|
||||
)
|
||||
|
||||
// 循环:左右两端收成尖(六边形),"从这里会绕回去"
|
||||
NodeShape.Loop -> polyPath(
|
||||
listOf(
|
||||
Offset(0f, h / 2f),
|
||||
Offset(cut * 1.4f, 0f), Offset(w - cut * 1.4f, 0f),
|
||||
Offset(w, h / 2f),
|
||||
Offset(w - cut * 1.4f, h), Offset(cut * 1.4f, h),
|
||||
),
|
||||
)
|
||||
|
||||
// 终点:上边两角斜切,底部保持圆角("往下收口")
|
||||
NodeShape.Terminal -> polyPath(
|
||||
listOf(
|
||||
Offset(cut, 0f), Offset(w - cut, 0f),
|
||||
Offset(w, cut), Offset(w, h - RADIUS),
|
||||
Offset(w - RADIUS, h), Offset(RADIUS, h),
|
||||
Offset(0f, h - RADIUS), Offset(0f, cut),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩略图路径(加节点面板里用的小图标)。
|
||||
*
|
||||
* 画在 [size] × [size] 的方框里。**方框比形状本身大一圈**,
|
||||
* 这样描边不会贴边被裁掉。
|
||||
*/
|
||||
fun thumbPath(shape: NodeShape, size: Float): Path {
|
||||
val pad = size * 0.10f
|
||||
val inner = size - pad * 2
|
||||
val p = path(shape, inner, inner * 0.82f)
|
||||
p.translate(Offset(pad, pad))
|
||||
return p
|
||||
}
|
||||
|
||||
private fun roundRectPath(w: Float, h: Float, radius: Float): Path = Path().apply {
|
||||
addRoundRect(
|
||||
RoundRect(
|
||||
rect = Rect(0f, 0f, w, h),
|
||||
cornerRadius = CornerRadius(radius, radius),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** 顶点列表 → 闭合多边形。斜切处是硬边(小图标上看不出来,也没必要圆) */
|
||||
private fun polyPath(pts: List<Offset>): Path = Path().apply {
|
||||
if (pts.isEmpty()) return@apply
|
||||
moveTo(pts[0].x, pts[0].y)
|
||||
for (i in 1 until pts.size) lineTo(pts[i].x, pts[i].y)
|
||||
close()
|
||||
}
|
||||
}
|
||||
132
android/nodekit/src/main/java/com/doubao/nodekit/Ops.kt
Normal file
132
android/nodekit/src/main/java/com/doubao/nodekit/Ops.kt
Normal file
@@ -0,0 +1,132 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/**
|
||||
* 一个算子。
|
||||
*
|
||||
* [arity] 是要几个输入引脚(1 = 单目,比如"取反""逻辑非")。
|
||||
*/
|
||||
data class Op(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val inType: String,
|
||||
val outType: String,
|
||||
val arity: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* 算子表(`op` 节点的下拉项)。
|
||||
*
|
||||
* ## ★★ 以前这张表被拆成三份,散在两个文件里
|
||||
*
|
||||
* `MeetingsScreen.kt:3615` `OPS_UI` —— 只有 (键, 名字)
|
||||
* `MeetingsScreen.kt:3643` `opSpec` —— 只有 (入类型, 出类型, 元数)
|
||||
* `android/kernel/meeting.py:207` `OPS` —— 权威的完整表
|
||||
*
|
||||
* 于是加一个算子要改三个地方,而且"名字在 A、类型在 B"这种拆法必然出现
|
||||
* **A 加了 B 忘了** —— 历史上真的发生过:单目运算 `neg` / `not` 引擎里有、
|
||||
* 界面上选不到(原来有个 `scripts/verify-ops.py` 专门抓这个,现在并进
|
||||
* `scripts/verify-nodekit.py` 了 —— 那个脚本会拿这张表和引擎逐项对拍)。
|
||||
*
|
||||
* 现在这里是**唯一一份**,而且每一项都是**原子**的(不会只加一半)。
|
||||
* 守门脚本 `scripts/verify-nodekit.py` 会拿它和 `meeting.py` 的 `OPS` 逐项对拍。
|
||||
*
|
||||
* ★ 顺序就是界面上的显示顺序 —— 分组的空行靠注释表达,别在中间插项,
|
||||
* 要加就加在对应分组的末尾。
|
||||
*/
|
||||
object Ops {
|
||||
/** 和引擎 `meeting.py` 的 `OPS` 一一对应,顺序也一样 */
|
||||
val ALL: List<Op> = listOf(
|
||||
Op("add", "加 +", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("sub", "减 −", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("mul", "乘 ×", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("div", "除 ÷", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("mod", "取余 %", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("concat", "拼接", PinKind.STR, PinKind.STR, 2),
|
||||
Op("eq", "等于 =(数字)", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("ne", "不等于 ≠(数字)", PinKind.NUM, PinKind.BOOL, 2),
|
||||
// ★ 文本相等单独一份:数字相等和文本相等**不是一回事** ——
|
||||
// "01" 和 "1" 作为文本不等、作为数字相等
|
||||
Op("streq", "文本等于 ==", PinKind.STR, PinKind.BOOL, 2),
|
||||
Op("strne", "文本不等于 !=", PinKind.STR, PinKind.BOOL, 2),
|
||||
Op("gt", "大于 >", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("lt", "小于 <", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("gte", "大于等于 ≥", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("lte", "小于等于 ≤", PinKind.NUM, PinKind.BOOL, 2),
|
||||
Op("neg", "取反(负号)", PinKind.NUM, PinKind.NUM, 1),
|
||||
Op("not", "逻辑非 !", PinKind.BOOL, PinKind.BOOL, 1),
|
||||
// ---- 逻辑运算:两边都是真假,结果也是真假 ----
|
||||
Op("and", "与 and", PinKind.BOOL, PinKind.BOOL, 2),
|
||||
Op("or", "或 or", PinKind.BOOL, PinKind.BOOL, 2),
|
||||
Op("xor", "异或 xor", PinKind.BOOL, PinKind.BOOL, 2),
|
||||
// ---- 位运算:整数才有的操作,结果为数字 ----
|
||||
Op("shl", "左移 <<", PinKind.NUM, PinKind.NUM, 2),
|
||||
Op("shr", "右移 >>", PinKind.NUM, PinKind.NUM, 2),
|
||||
// ---- 列表 ----
|
||||
Op("append", "追加到列表", PinKind.LIST, PinKind.LIST, 2),
|
||||
Op("clear", "清空列表", PinKind.LIST, PinKind.LIST, 1),
|
||||
)
|
||||
|
||||
private val BY_KEY: Map<String, Op> = ALL.associateBy { it.key }
|
||||
|
||||
/**
|
||||
* 查一个算子。
|
||||
*
|
||||
* ★ 查不到时**退回加法**(和以前的 `else -> Triple("num","num",2)` 行为一致)——
|
||||
* 老会议里可能有已经删掉的算子名,那时卡片还得画得出来。
|
||||
*/
|
||||
fun of(key: String): Op = BY_KEY[key] ?: BY_KEY.getValue("add")
|
||||
|
||||
/** 显示名。查不到就原样显示那个键(用户至少知道存的是什么) */
|
||||
fun label(key: String): String = BY_KEY[key]?.label ?: key
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换节点的目标类型。
|
||||
*
|
||||
* ★ 含 `list` —— 不然"把列表转成文本"这种最基本的转换做不了。
|
||||
*
|
||||
* ★★ 注意引擎那边的 `CAST_KINDS` **只列了 str / bool / num 三项**(而且全仓库
|
||||
* 没有任何地方读它,是一份死数据)。真正的类型校验在 `_cast_to()` 里,
|
||||
* 用的是 `PIN_TYPES`(**含 list**)。也就是说:引擎行为支持 list,
|
||||
* 只是那份清单没跟上。这里按**行为**写(4 项),那一份也已经补齐。
|
||||
*/
|
||||
object CastKinds {
|
||||
val ALL: List<String> = listOf(PinKind.STR, PinKind.BOOL, PinKind.NUM, PinKind.LIST)
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断节点的条件种类。
|
||||
*
|
||||
* ★★ 这份**必须和引擎的 `JUDGE_KINDS` 逐字一致** —— 判断条件不是"界面自己
|
||||
* 存的字符串",而是引擎按它分派的(`meeting.py` 里有一大段
|
||||
* `if kind == ...`)。界面上多一项,用户选了会在运行时报
|
||||
* "不认识的判断条件";少一项,那个能力就等于没有。
|
||||
*
|
||||
* `ai`(让模型判断)是最后一项,也是最贵的一项 —— 它会真的去调一次模型,
|
||||
* 所以放在最后、措辞上也别鼓励用户首选(能算的就别问模型)。
|
||||
*/
|
||||
object JudgeKinds {
|
||||
val ALL: List<Pair<String, String>> = listOf(
|
||||
"contains" to "包含关键词",
|
||||
"not_contains" to "不包含关键词",
|
||||
"longer_than" to "字数多于",
|
||||
"shorter_than" to "字数少于",
|
||||
"empty" to "为空",
|
||||
"not_empty" to "不为空",
|
||||
"ai" to "让模型判断",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 写变量节点遇到**列表**变量时的两种模式。
|
||||
*
|
||||
* 这是最容易搞混的一处:
|
||||
* · `append` 往里**加一项**(默认)—— "把每个结果都攒起来"要的就是它
|
||||
* · `replace` 整个**换掉**
|
||||
*/
|
||||
object ListModes {
|
||||
val ALL: List<Pair<String, String>> = listOf(
|
||||
"append" to "追加一项",
|
||||
"replace" to "整个覆盖",
|
||||
)
|
||||
}
|
||||
147
android/nodekit/src/main/java/com/doubao/nodekit/Pins.kt
Normal file
147
android/nodekit/src/main/java/com/doubao/nodekit/Pins.kt
Normal file
@@ -0,0 +1,147 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/*
|
||||
* 引脚:类型、定义、以及"算引脚需要知道哪些节点信息"。
|
||||
*
|
||||
* ## 这一层存在的理由
|
||||
*
|
||||
* 引脚类型这件事以前在仓库里有 **5 份**:
|
||||
*
|
||||
* android/kernel/meeting.py PIN_TYPES = ('str','bool','num','list')
|
||||
* server/src/meeting.mjs PIN_TYPES = ['str','bool','num'] ← 缺 list
|
||||
* android/kernel/custom_nodes.py PIN_KINDS = ('exec','str','bool','num','list')
|
||||
* ui/NodeDecl.kt PIN_TYPES_FOR_DECL = [...]
|
||||
* ui/MeetingsScreen.kt ANY_DATA = ["str","bool","num","list"]
|
||||
*
|
||||
* 内容还不一样(Node 那份没有 list,于是"列表变量"在 Web 端根本连不上)。
|
||||
* 现在这里是**唯一一份**,其余地方一律引用它。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 引脚类型。
|
||||
*
|
||||
* 和引擎的 `PIN_TYPES`(`android/kernel/meeting.py`)**必须一字不差** ——
|
||||
* `scripts/verify-nodekit.py` 会去比对,对不上就报错。
|
||||
*/
|
||||
object PinKind {
|
||||
/** 执行引脚:只排顺序、不传数据 */
|
||||
const val EXEC = "exec"
|
||||
const val STR = "str"
|
||||
const val BOOL = "bool"
|
||||
const val NUM = "num"
|
||||
const val LIST = "list"
|
||||
|
||||
/**
|
||||
* 老会议里的 `data` 类型 —— 当 `str` 处理。
|
||||
*
|
||||
* ★ 不能删:第一版会议数据里边上写的就是 `data`,删了老图全部接线失效。
|
||||
*/
|
||||
const val LEGACY_DATA = "data"
|
||||
|
||||
/** 数据引脚的类型(不含 exec)。就是引擎的 `PIN_TYPES`。 */
|
||||
val DATA: List<String> = listOf(STR, BOOL, NUM, LIST)
|
||||
|
||||
/** 什么数据类型都能接的引脚(`accepts = ANY`) */
|
||||
val ANY: List<String> = DATA
|
||||
|
||||
/** 声明一个引脚时能选的类型(含 exec)。自定义节点的声明界面用。 */
|
||||
val DECLARABLE: List<String> = listOf(EXEC, STR, BOOL, NUM, LIST)
|
||||
|
||||
fun label(kind: String): String = when (kind) {
|
||||
EXEC -> "执行"
|
||||
STR -> "文本"
|
||||
BOOL -> "真假"
|
||||
NUM -> "数字"
|
||||
LIST -> "列表"
|
||||
LEGACY_DATA -> "文本"
|
||||
else -> kind
|
||||
}
|
||||
|
||||
/** `文本 str` 这种带英文的写法(选择器里用,用户要能对上引擎里的名字) */
|
||||
fun labelWithKey(kind: String): String = "${label(kind)} $kind"
|
||||
|
||||
/** 显示名字时把老类型归一到新名字 */
|
||||
fun normalize(kind: String): String =
|
||||
if (kind == LEGACY_DATA) STR else kind
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个引脚。
|
||||
*
|
||||
* [accepts] 是"这个入口能接哪些类型",空表示只接自己这种 [kind]。
|
||||
* 为什么要它:`while` 的条件入口只收 `bool` 的话,用户没法把变量(文本)接上去,
|
||||
* 于是给成 `bool + str + num` —— 判断真假由引擎的 `truthy()` 负责。
|
||||
*
|
||||
* [branch] 是 exec 出口的分支名。判断节点的 true/false、while 的 body/done、
|
||||
* 自定义节点的多路出口都是同一套机制:连线时把分支名写进边里,引擎才知道走哪条。
|
||||
*/
|
||||
data class PinSpec(
|
||||
val kind: String,
|
||||
val key: String,
|
||||
val label: String,
|
||||
val accepts: List<String> = emptyList(),
|
||||
val branch: String = "",
|
||||
) {
|
||||
/** 能不能接下 [fromKind] 这条线 */
|
||||
fun accepts_(fromKind: String): Boolean =
|
||||
(if (accepts.isEmpty()) listOf(kind) else accepts).contains(fromKind)
|
||||
|
||||
/** 是不是"什么都能接"的宽入口 */
|
||||
val isAny: Boolean
|
||||
get() = kind != PinKind.EXEC && accepts.containsAll(PinKind.ANY)
|
||||
}
|
||||
|
||||
/** 自定义节点声明里的一个引脚(从内核的 `nodes/` 目录下的 .py 读来的) */
|
||||
data class PinDecl(val name: String, val type: String)
|
||||
|
||||
/**
|
||||
* 一个自定义节点声明的**引脚部分**。
|
||||
*
|
||||
* ★ 只搬引脚,不搬"这个节点叫什么、在哪个文件里" ——
|
||||
* 库只关心"怎么画引脚",别的一概不管(那是使用方的事)。
|
||||
*/
|
||||
data class CustomNodePins(
|
||||
val inputs: List<PinDecl> = emptyList(),
|
||||
val outputs: List<PinDecl> = emptyList(),
|
||||
) {
|
||||
val dataInputs: List<PinDecl> get() = inputs.filter { it.type != PinKind.EXEC }
|
||||
val execOutputs: List<PinDecl> get() = outputs.filter { it.type == PinKind.EXEC }
|
||||
val dataOutputs: List<PinDecl> get() = outputs.filter { it.type != PinKind.EXEC }
|
||||
}
|
||||
|
||||
/**
|
||||
* 算引脚需要的**全部**节点信息。
|
||||
*
|
||||
* ## 为什么不让库直接用使用方的节点类
|
||||
*
|
||||
* 因为那样库就"反向依赖"了使用方 —— 这是库最容易腐化的地方:
|
||||
* 一开始只是读两个字段,后来慢慢开始读 `status`、读 `output`、读主题色,
|
||||
* 最后库和 app 长在一起,换个人根本拿不走。
|
||||
*
|
||||
* 所以库只认这个小结构,使用方自己写一行转换:
|
||||
*
|
||||
* fun MeetingNode.view(varTypes: Map<String, String>) = NodeView(
|
||||
* type = type, op = op, varName = varName, valueType = valueType,
|
||||
* castTo = castTo, customKey = customKey, varTypes = varTypes,
|
||||
* )
|
||||
*
|
||||
* ★ 字段全给默认值,这样"只想画个 value 节点"的人不用写一堆空参数。
|
||||
*/
|
||||
data class NodeView(
|
||||
/** 节点类型,见 [NodeKind] */
|
||||
val type: String,
|
||||
/** 运算节点的算子(`add` / `concat` / …),见 [Ops] */
|
||||
val op: String = "add",
|
||||
/** 写变量 / 读变量引用的变量名 */
|
||||
val varName: String = "",
|
||||
/** 值节点的类型:`str` / `bool` / `num` / `list` */
|
||||
val valueType: String = PinKind.STR,
|
||||
/** 转换节点要转成什么类型 */
|
||||
val castTo: String = PinKind.STR,
|
||||
/** 自定义节点对应哪份声明([custom] 里的 key) */
|
||||
val customKey: String = "",
|
||||
/** 自定义节点的引脚声明(内核里读来的),没有就退回一个宽松默认 */
|
||||
val custom: CustomNodePins? = null,
|
||||
/** 变量登记表:变量名 → 类型。写/读变量的引脚类型按它查 */
|
||||
val varTypes: Map<String, String> = emptyMap(),
|
||||
)
|
||||
230
android/nodekit/src/main/java/com/doubao/nodekit/Specs.kt
Normal file
230
android/nodekit/src/main/java/com/doubao/nodekit/Specs.kt
Normal file
@@ -0,0 +1,230 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/*
|
||||
* 引脚表:每种节点有哪些输入 / 输出引脚。
|
||||
*
|
||||
* ## 从哪搬来的
|
||||
*
|
||||
* 逐字搬自 `MeetingsScreen.kt` 的 `inputPins()`(原 3695 行)和
|
||||
* `outputPins()`(原 3893 行)。搬的时候**没改任何规则** —— 这两张表是
|
||||
* 界面和引擎之间最容易出错的地方,历史上的坑(写变量的 list 入口、
|
||||
* 读变量的 num 出口)全在这里,重写一遍只会把老坑再踩一遍。
|
||||
*
|
||||
* 改的只有两件事:
|
||||
* 1. `node.type` 之类改成 `view.type`(库不认使用方的节点类)
|
||||
* 2. 自定义节点的引脚从 `CustomNodeDef` 改成 [CustomNodePins](只取引脚部分)
|
||||
*
|
||||
* ## ★ 和引擎的关系
|
||||
*
|
||||
* 引擎那边是 `meeting.py` 的 `NODE_DATA_IN` / `NODE_DATA_OUT` 两张字典
|
||||
* **加上** `_data_in_type()` / `_data_out_type()` 两个特判函数。
|
||||
* 界面这边只有一个 when。两边靠 `scripts/verify-nodekit.py` 对拍。
|
||||
*/
|
||||
|
||||
object NodeSpecs {
|
||||
|
||||
/**
|
||||
* 输入引脚(从上到下)。
|
||||
*
|
||||
* ★ **纯节点**(读变量 / 值)没有 exec 入:它们是蓝图里的 Get / 常量,
|
||||
* 不在执行链上,值是被需要的节点运行时拉取的 —— 这就是"读变量只有输出"的真正原因。
|
||||
* ★ 开始事件也没有 exec 入:它是整张图的起点。
|
||||
*/
|
||||
fun inputPins(view: NodeView): List<PinSpec> = when (view.type) {
|
||||
|
||||
NodeKind.CUSTOM -> {
|
||||
val d = view.custom
|
||||
if (d == null) {
|
||||
// 定义还没加载到:给一个宽松默认(不收 exec、一个文本入口),
|
||||
// 免得卡片画不出引脚、用户以为节点坏了
|
||||
listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输入", accepts = PinKind.ANY),
|
||||
)
|
||||
} else {
|
||||
buildList {
|
||||
// 自己声明的 exec 入口(没有就不画 —— 纯数据节点)
|
||||
d.inputs.filter { it.type == PinKind.EXEC }
|
||||
.forEach { add(PinSpec(PinKind.EXEC, "", "▶")) }
|
||||
d.dataInputs.forEach { p ->
|
||||
add(PinSpec(p.type, p.name, p.name, accepts = listOf(p.type)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 分支:收一个真假,走真/假两条 exec
|
||||
NodeKind.BRANCH -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
// 条件收得宽一点:变量和上游多半给的是 "true"/"1" 这类文本
|
||||
PinSpec(PinKind.BOOL, "", "条件", accepts = listOf(PinKind.BOOL, PinKind.STR, PinKind.NUM)),
|
||||
)
|
||||
|
||||
NodeKind.START, NodeKind.READVAR, NodeKind.VALUE -> emptyList()
|
||||
|
||||
// Python 节点:执行节点 —— 上游什么都要能收(它就是拿来处理任意内容的)
|
||||
NodeKind.PY -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输入", accepts = PinKind.ANY),
|
||||
)
|
||||
|
||||
// 转换:什么都收(出口类型在配置面板里选)
|
||||
NodeKind.CAST -> listOf(PinSpec(PinKind.STR, "", "值", accepts = PinKind.ANY))
|
||||
|
||||
// 运算:入口类型由算子决定(加法要数字、拼接要文本),单目只有一个入口
|
||||
NodeKind.OP -> {
|
||||
val key = view.op.ifBlank { "add" }
|
||||
val spec = Ops.of(key)
|
||||
if (spec.arity == 1) {
|
||||
listOf(PinSpec(spec.inType, "a", if (spec.inType == PinKind.NUM) "数" else "值"))
|
||||
} else if (key == "append") {
|
||||
// ★ 追加的第二个入口是"要加进去的东西",**什么类型都行** ——
|
||||
// 往里塞一句话、一个数字、一个真假都对。
|
||||
listOf(
|
||||
PinSpec(PinKind.LIST, "a", "列表"),
|
||||
PinSpec(PinKind.STR, "b", "加什么", accepts = PinKind.ANY),
|
||||
)
|
||||
} else {
|
||||
listOf(
|
||||
PinSpec(spec.inType, "a", "A"),
|
||||
PinSpec(spec.inType, "b", "B"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NodeKind.WHILE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
// 条件:bool 最自然,但变量是字符串,所以两种都收(见 PinSpec 注释)
|
||||
PinSpec(PinKind.BOOL, "", "条件", accepts = listOf(PinKind.BOOL, PinKind.STR, PinKind.NUM)),
|
||||
)
|
||||
|
||||
NodeKind.JUDGE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "值"),
|
||||
)
|
||||
|
||||
// 写变量:入口类型**按变量登记表**,而且**严格**(和读变量的出口对称)。
|
||||
//
|
||||
// 之前写成"不卡类型"是治错了病:让用户难受的不是"卡得严",
|
||||
// 是"接不上还不说为什么"。所以现在:
|
||||
// · 类型跟着变量走(颜色也变,一眼知道这个入口要什么)
|
||||
// · 不匹配就接不上,但**当场弹出说明**告诉他加转换节点
|
||||
NodeKind.VAR -> {
|
||||
val declType = view.varTypes[view.varName] ?: PinKind.STR
|
||||
// ★ 列表变量:入口是 **str**(追加的是"一项内容",不是整个列表)。
|
||||
// 入口写成 list 的话,用户得先拼一个 JSON 数组才能往里加一项 —— 太别扭了。
|
||||
val vt = if (declType == PinKind.LIST) PinKind.STR else declType
|
||||
val vtLabel = if (declType == PinKind.LIST) "追加的文本" else PinKind.label(vt)
|
||||
listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(vt, "", vtLabel, accepts = listOf(vt)),
|
||||
)
|
||||
}
|
||||
|
||||
// ★ end(最终输出)**什么类型都收** —— 引擎那边 NODE_DATA_IN['end']
|
||||
// 就是四种全要。这里写死 str 的话,数字/列表接到最终输出会被界面拒掉。
|
||||
NodeKind.END -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "值", accepts = PinKind.ANY),
|
||||
)
|
||||
|
||||
else -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输入"),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出引脚(从上到下)。
|
||||
*
|
||||
* ★ 判断节点有**两条 exec 出线**(真/假)—— 相当于蓝图里的 Branch。
|
||||
* ★ while 有**两条 exec 出线**(循环体/结束)—— 相当于蓝图里的 While Loop。
|
||||
* ★ 写变量**没有数据出线**(存进去的值不从它往下传),但有 exec 出线。
|
||||
* ★ 纯节点(读变量 / 值 / 运算 / 转换)**只有数据出线**,没有任何 exec 引脚。
|
||||
*/
|
||||
fun outputPins(view: NodeView): List<PinSpec> = when (view.type) {
|
||||
|
||||
NodeKind.CUSTOM -> {
|
||||
val d = view.custom
|
||||
if (d == null) {
|
||||
listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
} else {
|
||||
buildList {
|
||||
// 多个 exec 出口 = N 路分支,每条一个引脚(名字就是分支名)
|
||||
d.execOutputs.forEach {
|
||||
add(PinSpec(PinKind.EXEC, it.name, it.name, branch = it.name))
|
||||
}
|
||||
d.dataOutputs.forEachIndexed { i, p ->
|
||||
add(
|
||||
PinSpec(
|
||||
p.type,
|
||||
p.name,
|
||||
p.name + if (i > 0) "(接不了线)" else "",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 分支:真 / 假两条 exec 出口
|
||||
NodeKind.BRANCH -> listOf(
|
||||
PinSpec(PinKind.EXEC, "true", "真 ▶"),
|
||||
PinSpec(PinKind.EXEC, "false", "假 ▶"),
|
||||
)
|
||||
|
||||
NodeKind.END -> emptyList()
|
||||
|
||||
// ★ 读变量的出口类型**必须按变量登记表**,不能写死 str。
|
||||
//
|
||||
// 写死 str 的后果:一个 num 变量 → 读变量 → 运算 的线**接不上**
|
||||
// (运算的 num 入口只收 num,而读变量声称自己给 str)。
|
||||
// 引擎那边 _data_out_type 本来就是对的做法,界面这份是漏了
|
||||
// —— 用户报的"运算为啥不给数字类型连"就是这个。
|
||||
NodeKind.READVAR -> listOf(
|
||||
PinSpec(view.varTypes[view.varName] ?: PinKind.STR, "", "值"),
|
||||
)
|
||||
|
||||
// Python 节点:执行节点,交出文本
|
||||
NodeKind.PY -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
|
||||
// 转换:出口类型就是它要转成的那个类型
|
||||
NodeKind.CAST -> listOf(PinSpec(view.castTo.ifBlank { PinKind.STR }, "", "值"))
|
||||
|
||||
// 运算:出口类型由算子决定(加法出数字、比较出真假)
|
||||
NodeKind.OP -> listOf(PinSpec(Ops.of(view.op.ifBlank { "add" }).outType, "", "结果"))
|
||||
|
||||
// 值节点的类型由它自己选 —— 这决定了它能接到哪去
|
||||
NodeKind.VALUE -> listOf(
|
||||
PinSpec(view.valueType.ifBlank { PinKind.STR }, "", "值"),
|
||||
)
|
||||
|
||||
NodeKind.JUDGE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "true", "真 ▶"),
|
||||
PinSpec(PinKind.EXEC, "false", "假 ▶"),
|
||||
)
|
||||
|
||||
NodeKind.WHILE -> listOf(
|
||||
PinSpec(PinKind.EXEC, "body", "循环体 ▶"),
|
||||
PinSpec(PinKind.EXEC, "done", "结束 ▶"),
|
||||
)
|
||||
|
||||
NodeKind.VAR -> listOf(PinSpec(PinKind.EXEC, "", "▶"))
|
||||
|
||||
NodeKind.START -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
|
||||
else -> listOf(
|
||||
PinSpec(PinKind.EXEC, "", "▶"),
|
||||
PinSpec(PinKind.STR, "", "输出"),
|
||||
)
|
||||
}
|
||||
}
|
||||
85
android/nodekit/src/main/java/com/doubao/nodekit/Styles.kt
Normal file
85
android/nodekit/src/main/java/com/doubao/nodekit/Styles.kt
Normal file
@@ -0,0 +1,85 @@
|
||||
package com.doubao.nodekit
|
||||
|
||||
/**
|
||||
* 引脚 / 连线的配色。
|
||||
*
|
||||
* ★ 全部是 `Int`(ARGB)。库不依赖 Compose,渲染方自己转:
|
||||
*
|
||||
* Color(NodeStyles.pinColor(pin.kind))
|
||||
*
|
||||
* ## 为什么颜色要集中在这
|
||||
*
|
||||
* 以前这几个颜色常量散在 `MeetingsScreen.kt` 里,同一个绿写了 6 遍
|
||||
* (`0xFF34A853` 出现在 nodeColor、pinColor、画连线、结果界面…),
|
||||
* 而且**语义相同的两个值写法不同**:
|
||||
*
|
||||
* pinColor("exec") = 0xFFECEFF1 EXEC_COLOR = 0xFFE8EAED ← 两个"白"
|
||||
* nodeColor("start") = 0xFF34A853 画线时的"真"分支 = 0xFF34A853
|
||||
*
|
||||
* 改一个忘一个的表现是"同一个意思两种颜色",肉眼很难发现。
|
||||
*/
|
||||
object NodeStyles {
|
||||
|
||||
/** 执行引脚:白。它不传值,所以是"无色"的 —— 和彩色数据引脚形成对比 */
|
||||
const val EXEC_FILL = 0xFFECEFF1.toInt()
|
||||
|
||||
/** 执行引脚的描边(描在白引脚外面,浅色背景下才看得见) */
|
||||
const val EXEC_BORDER = 0xFF5F6368.toInt()
|
||||
|
||||
/** 能接任何类型的引脚:紫。**一眼看出"这个入口不挑"** */
|
||||
const val ANY_FILL = 0xFF9C27B0.toInt()
|
||||
|
||||
/** 认不出的类型:灰 */
|
||||
const val UNKNOWN_FILL = 0xFF9AA0A6.toInt()
|
||||
|
||||
/** 数据引脚按类型上色 */
|
||||
fun pinColor(kind: String): Int = when (kind) {
|
||||
PinKind.EXEC -> EXEC_FILL
|
||||
PinKind.STR -> 0xFF34A853.toInt()
|
||||
PinKind.NUM -> 0xFF1A73E8.toInt()
|
||||
PinKind.BOOL -> 0xFFE53935.toInt()
|
||||
PinKind.LIST -> 0xFFF9A825.toInt()
|
||||
// 老会议里没有 kind 字段的数据线,一律当文本
|
||||
PinKind.LEGACY_DATA -> 0xFF34A853.toInt()
|
||||
else -> UNKNOWN_FILL
|
||||
}
|
||||
|
||||
/**
|
||||
* 按**引脚**算颜色(而不是只看 kind):收全部类型的引脚是紫的。
|
||||
*
|
||||
* ★ 为什么不能只看 kind:`end` / `py` / `cast` 的入口 kind 是 `str`,
|
||||
* 但它们**什么都收** —— 画成绿色的话用户以为只能连文本进来。
|
||||
*/
|
||||
fun pinColorOf(pin: PinSpec): Int =
|
||||
if (pin.isAny) ANY_FILL else pinColor(pin.kind)
|
||||
|
||||
/** 引脚的描边色 */
|
||||
fun pinBorder(kind: String): Int =
|
||||
if (kind == PinKind.EXEC) EXEC_BORDER else pinColor(kind)
|
||||
|
||||
fun pinBorderOf(pin: PinSpec): Int =
|
||||
if (pin.kind == PinKind.EXEC) EXEC_BORDER else pinColorOf(pin)
|
||||
|
||||
/**
|
||||
* 一条 exec 出线的颜色。
|
||||
*
|
||||
* ★ 真/假分支用绿/红是**刻意**的:这两条线在画布上并排走,
|
||||
* 颜色一样的话用户根本分不清哪条是"条件成立"。
|
||||
* 其他 exec 出口(body/done/自定义分支)用统一的描边色。
|
||||
*/
|
||||
fun execWireColor(key: String): Int = when (key) {
|
||||
"true" -> 0xFF34A853.toInt()
|
||||
"false" -> 0xFFEA4335.toInt()
|
||||
"body" -> 0xFF4C97FF.toInt()
|
||||
"done" -> 0xFF5F6368.toInt()
|
||||
else -> EXEC_BORDER
|
||||
}
|
||||
|
||||
/** 一条连线的颜色(数据线按类型,exec 线按分支) */
|
||||
fun wireColor(pin: PinSpec): Int =
|
||||
if (pin.kind == PinKind.EXEC) execWireColor(pin.key) else pinColorOf(pin)
|
||||
|
||||
/** 运行状态:正在跑 / 出错 / 正常。使用方拿它给卡片描边 */
|
||||
const val RUNNING = 0xFF1A73E8.toInt()
|
||||
const val ERROR = 0xFFD93025.toInt()
|
||||
}
|
||||
@@ -16,3 +16,5 @@ dependencyResolutionManagement {
|
||||
|
||||
rootProject.name = "DoubaoLynxClone"
|
||||
include(":app")
|
||||
// 会议节点定义库(节点类型 / 引脚 / 算子 / 几何 / 形状)—— 见 nodekit/,文档 docs/节点库.md
|
||||
include(":nodekit")
|
||||
|
||||
@@ -25,11 +25,45 @@
|
||||
| 工具 | 阻不阻塞 | 为什么 |
|
||||
|---|---|---|
|
||||
| `show_ui` | **不阻塞** | 展示语义。用户可能盯着看很久,把内核线程占住没意义 |
|
||||
| `ask_user` | **阻塞**(最多 120s) | 问询语义。拿不到答案就没法继续 |
|
||||
| `ask_user` | **阻塞**(默认**不限时**,见下) | 问询语义。拿不到答案就没法继续 |
|
||||
| `end_conversation` | 立刻返回 | 它只改状态(落盘 + 界面收输入框) |
|
||||
|
||||
超时是**必须**的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
而 HTTP 是每请求一线程,挂一个少一个。
|
||||
### ★★ 不限时(v2.0.45 起):要三处一起改才算数
|
||||
|
||||
原来是 120 秒上限,用户明确要求去掉:"AI 询问界面不要限时"。理由很实在:
|
||||
|
||||
> 用户看到选项、去翻了下手机算个数、回来弹窗没了;模型收到 `timeout=true`,
|
||||
> 理解成"用户不想理我",于是**按自己猜的答案往下写** —— 这一轮整个废掉。
|
||||
|
||||
现在的默认是**一直等**,放行出口是:点任意选项 / 点「取消」/ 关掉 App。
|
||||
模型真想限时得自己传 `timeout`(`ask_user` 1~3600 秒,`show_ui` 5~3600 秒)。
|
||||
|
||||
**这个改动必须同时改三处**,只改一两处的表现是"看起来改了其实没生效":
|
||||
|
||||
| # | 改哪儿 | 不改的后果 |
|
||||
|---|---|---|
|
||||
| ① | `AiSurface.ask` / `showScreen`(界面侧等多久) | 弹窗到点自己消失 |
|
||||
| ② | `tools_runtime` 的**工具执行超时** | 弹窗还开着,但内核 60 秒就把这次调用判超时、把结果丢了 |
|
||||
| ③ | 工具自己声明的 `timeout` | 工具主动提前放弃 |
|
||||
|
||||
②最隐蔽:`TOOL_TIMEOUT_S = 60` 是"工具里写了死循环"的安全网,
|
||||
而等用户的工具**设计上就该慢**。所以它们在自己的文件里声明
|
||||
`WAIT_FOR_USER = True`,内核据此把超时预算设成 0(不限时)。
|
||||
|
||||
> 实测记录:只改 ①③ 时,弹窗 135 秒确实还在,但工具在 **60.0 秒**返回了
|
||||
> `{"ok":false,"error":"工具执行超时(60s)"}` —— 用户后来点的选项根本回不到
|
||||
> 模型手里。补上 ② 之后同一个探针在 **66.2 秒**返回
|
||||
> `{"choice":"B","timeout":false}`。
|
||||
> 探针:`scripts/probe-ask-user-forever.py`;守门:`scripts/verify-ui-tools.py`。
|
||||
|
||||
### 客户端那条长连接为什么不会断
|
||||
|
||||
对话是 SSE 长连接,等待期间可能几分钟没有正常数据。两端都不会断:
|
||||
|
||||
- 内核每 **15 秒**发一个 `: ping` 心跳(`app.py` 的 `_ping_loop`)
|
||||
- 客户端 `readTimeout` 是 **120 秒**(`KernelClient`)—— 它管的是"两次数据之间的最大间隔",不是总时长
|
||||
|
||||
所以心跳只要 < 120 秒就安全。
|
||||
|
||||
---
|
||||
|
||||
@@ -38,7 +72,7 @@
|
||||
| 用法 | 行为 | 适合 |
|
||||
|---|---|---|
|
||||
| `wait` 不传(默认) | 弹出就返回,不等 | 图表、报告这类"给用户看"的 |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**,最多 `timeout` 秒(默认 120,上限 600) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**(默认**不限时**;显式传 `timeout` 则 5~3600 秒) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| 不调用 | 纯文字回答 | —— |
|
||||
|
||||
等待模式下用户点的值**立刻**作为工具返回值给模型,**同一个回合里**就能接着处理:
|
||||
@@ -48,7 +82,7 @@ wait=true → 阻塞 9.3s → {"waited":true,"timeout":false,"value":"方案丙
|
||||
```
|
||||
|
||||
- 用户直接关掉界面(没点任何按钮)→ `value=""` + `closed=true`
|
||||
- 超时 → `timeout=true`,提示词里明确要求**别反复重弹**
|
||||
- 只有显式设了 `timeout` 才可能 `timeout=true`,提示词里要求**别反复重弹**
|
||||
|
||||
### ★ 实现上的一个竞态
|
||||
|
||||
|
||||
339
docs/节点库.md
Normal file
339
docs/节点库.md
Normal file
@@ -0,0 +1,339 @@
|
||||
# 会议节点库(`:nodekit`)
|
||||
|
||||
> 会议编辑器里「**节点是什么形式**」的那套定义 —— 有哪些节点、每个节点什么引脚、
|
||||
> 什么颜色、什么形状、卡片多高、连线从哪儿出去 —— 从 `MeetingsScreen.kt` 里
|
||||
> 抽成了一个**独立模块**,定义只有一份,别处可以直接依赖。
|
||||
|
||||
代码在 [`android/nodekit/`](../android/nodekit/)。
|
||||
App 侧的接入层是 [`ui/MeetNodeKit.kt`](../android/app/src/main/java/com/doubao/lynxclone/ui/MeetNodeKit.kt)。
|
||||
|
||||
---
|
||||
|
||||
## 一、为什么要抽(不是为了好看)
|
||||
|
||||
改造前实测的现状 —— **同一个「节点类型」概念在 6 个地方各写一遍**:
|
||||
|
||||
| # | 位置 | 内容 |
|
||||
|---|---|---|
|
||||
| 1 | `android/kernel/meeting.py:46` | `NODE_TYPES`,13 种(唯一完整的) |
|
||||
| 2 | `android/kernel/app.py:1054` | 给界面的 `nodeTypes`,**12 种**(漏了 custom) |
|
||||
| 3 | `server/src/meeting.mjs:26` | Node 引擎的 `NODE_TYPES`,**6 种** |
|
||||
| 4 | `MeetingsScreen.kt` `nodeColor()` | 13 分支的 `when` |
|
||||
| 5 | `MeetingsScreen.kt` `inputPins()` | 13 分支的 `when` |
|
||||
| 6 | `MeetingsScreen.kt` `outputPins()` | 13 分支的 `when` |
|
||||
|
||||
还有第 7 处(`NodeCard` 里算默认标题的 `when`)、第 8 处(配置面板标题的 `when`)。
|
||||
|
||||
**引脚类型清单 5 份**,内容还不一样:
|
||||
|
||||
```
|
||||
android/kernel/meeting.py PIN_TYPES = ('str','bool','num','list')
|
||||
server/src/meeting.mjs PIN_TYPES = ['str','bool','num'] ← 缺 list
|
||||
android/kernel/custom_nodes.py PIN_KINDS = ('exec','str','bool','num','list')
|
||||
app/ui/NodeDecl.kt PIN_TYPES_FOR_DECL = [...]
|
||||
app/ui/MeetingsScreen.kt ANY_DATA = ["str","bool","num","list"]
|
||||
```
|
||||
|
||||
**变量类型选项在界面里逐字重复 3 处**,**算子表被拆成"键+名字"和"类型+元数"
|
||||
放两个文件**。
|
||||
|
||||
这不是"代码不够优雅",它已经造成过真实故障:
|
||||
|
||||
- 单目运算 `neg` / `not` —— 引擎里有、**界面上选不到**(原来有个 `scripts/verify-ops.py` 专门抓这个,现在并进 `verify-nodekit.py` 了)
|
||||
- 写变量节点的 `list` 入口漏了 —— 列表变量**根本写不进去**
|
||||
- 读变量出口写死 `str` —— num 变量接不到运算节点(用户报"运算为啥不给数字类型连")
|
||||
- 判断条件 `ai`(让模型判断)、`longer_than`(字数多于)—— 引擎支持,别处没列
|
||||
|
||||
抽库的目的就是让这些"漏一处"**在编译期或脚本里暴露**,而不是等用户报。
|
||||
|
||||
---
|
||||
|
||||
## 二、库里有什么
|
||||
|
||||
```
|
||||
android/nodekit/src/main/java/com/doubao/nodekit/
|
||||
├── Pins.kt 引脚类型常量(PinKind)、PinSpec、NodeView、CustomNodePins
|
||||
├── Catalog.kt 节点类型清单(NodeKind)+ 每种类型的元数据(NodeCatalog / NodeSpec)
|
||||
├── Specs.kt 引脚表:inputPins() / outputPins()
|
||||
├── Ops.kt 算子表、转换类型、判断条件、列表写模式
|
||||
├── Styles.kt 引脚/连线配色
|
||||
├── Geometry.kt 尺寸、节点高度、引脚坐标、画布大小、平移夹取
|
||||
└── NodeShapes.kt 形状的画法(6 种形状 → Path)
|
||||
```
|
||||
|
||||
规模约 940 行,**7 个文件各管一件事**。
|
||||
|
||||
### 三条设计约束
|
||||
|
||||
**① 不依赖 Compose 运行时。**
|
||||
除了 `NodeShapes.kt`(它只用 `Path` / `Rect` / `CornerRadius` 这些普通值类型),
|
||||
其余文件连 `@Composable` 都没有,颜色用 `Int`(ARGB)存。好处:能在 JVM 上直接
|
||||
单测、不被拖进 UI 依赖、换任何渲染方式都能用。
|
||||
|
||||
`nodekit/build.gradle.kts` 里**刻意没有挂** `org.jetbrains.kotlin.plugin.compose` ——
|
||||
挂了就必须往 classpath 塞 compose runtime,一个纯规则库不该有这个包袱。
|
||||
|
||||
**② 不认使用方的节点类。**
|
||||
库不知道 `MeetingNode` 是什么,它只要一个 [`NodeView`](../android/nodekit/src/main/java/com/doubao/nodekit/Pins.kt):
|
||||
|
||||
```kotlin
|
||||
data class NodeView(
|
||||
val type: String,
|
||||
val op: String = "add",
|
||||
val varName: String = "",
|
||||
val valueType: String = PinKind.STR,
|
||||
val castTo: String = PinKind.STR,
|
||||
val customKey: String = "",
|
||||
val custom: CustomNodePins? = null,
|
||||
val varTypes: Map<String, String> = emptyMap(),
|
||||
)
|
||||
```
|
||||
|
||||
这是**防腐蚀**的关键:库一旦能直接摸使用方的节点对象,就会慢慢开始读
|
||||
`status`、读 `output`、读主题色,最后和 App 长在一起,谁也拿不走。
|
||||
|
||||
**③ 颜色是 `Int`,透明度是渲染方的事。**
|
||||
`NodeStyles.pinColor(kind)` 返回 `Int`,App 那边 `Color(...)` 转一下;
|
||||
`pinBorder` 要"淡一点"(`alpha = 0.85`)是 App 加的 —— **库不该知道我们要多淡**。
|
||||
|
||||
---
|
||||
|
||||
## 三、怎么用
|
||||
|
||||
### 依赖
|
||||
|
||||
```kotlin
|
||||
// android/app/build.gradle.kts
|
||||
dependencies {
|
||||
implementation(project(":nodekit"))
|
||||
}
|
||||
```
|
||||
|
||||
(`settings.gradle.kts` 里 `include(":nodekit")`,根 `build.gradle.kts` 声明
|
||||
`com.android.library` 插件版本。)
|
||||
|
||||
### 算引脚
|
||||
|
||||
```kotlin
|
||||
val view = NodeView(type = "var", varName = "结果", varTypes = mapOf("结果" to "num"))
|
||||
|
||||
NodeSpecs.inputPins(view) // [PinSpec(exec,"","▶"), PinSpec(num,"","数字",accepts=[num])]
|
||||
NodeSpecs.outputPins(view) // [PinSpec(exec,"","▶")]
|
||||
NodeGeometry.height(view) // 24 + 1*21 + 34 = 79.0
|
||||
```
|
||||
|
||||
### 画卡片 / 画引脚
|
||||
|
||||
```kotlin
|
||||
// 颜色
|
||||
Color(NodeCatalog.color(node.type))
|
||||
Color(NodeStyles.pinColor(pin.kind))
|
||||
Color(NodeStyles.pinColorOf(pin)) // "什么都收"的入口是紫色
|
||||
|
||||
// 位置
|
||||
val p = NodeGeometry.pinPos(node.x, node.y, index, isOutput = true)
|
||||
val q = NodeGeometry.portIn(view, node.x, node.y, kind = "str", pinKey = "a")
|
||||
|
||||
// 形状(形状缩略图和卡片徽标都用它)
|
||||
val path = NodeShapes.thumbPath(NodeShape.Hat, size = 24f)
|
||||
```
|
||||
|
||||
App 侧的 `ui/MeetNodeKit.kt` 是**唯一一层胶水**:把 `MeetingNode` 转成 `NodeView`、
|
||||
把 `Int` 转成 `Color`、把库的 API 换成 App 原来用的函数名(这样几百个调用点
|
||||
一行都不用改)。它刻意很薄 —— **胶水层一开始"顺手做点事",它就变成第二份定义了**。
|
||||
|
||||
---
|
||||
|
||||
## 四、节点类型表
|
||||
|
||||
13 种。**这张表就是 `NodeCatalog.ALL`**,加类型只改这一处。
|
||||
|
||||
| 类型 | 名字 | 形状 | 颜色 | 输入引脚 | 输出引脚 | 说明 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `start` | 开始事件 | **帽形** | 绿 `34A853` | — | exec, str | 整张图的起点,没有输入 |
|
||||
| `agent` | 智能体 | 矩形 | 蓝 `2B7BFF` | exec, str | exec, str | 一个智能体处理一轮 |
|
||||
| `judge` | 判断 | **菱形** | 橙 `F29900` | exec, str | exec×2(真/假) | 按规则算,走两条路 |
|
||||
| `branch` | 分支 | **菱形** | 橙红 `E8710A` | exec, bool | exec×2(真/假) | 直接收真假,不自己算 |
|
||||
| `while` | while 循环 | **六边形** | 红 `D93025` | exec, bool | exec×2(体/结束) | 条件真就跑循环体 |
|
||||
| `end` | 最终输出 | **终点** | 紫 `7B61FF` | exec, str(收全部) | — | 汇总结果 |
|
||||
| `var` | 写变量 | 矩形 | 青 `00A0A0` | exec, 按变量类型 | exec | 存进变量 |
|
||||
| `readvar` | 读变量 | **胶囊** | 青 `00A0A0` | — | 按变量类型 | **纯节点** |
|
||||
| `value` | 值 | **胶囊** | 淡紫 `9C6ADE` | — | 按 `valueType` | **纯节点** |
|
||||
| `cast` | 转换 | **胶囊** | 深紫 `7E57C2` | str(收全部) | 按 `castTo` | **纯节点** |
|
||||
| `op` | 运算 | **胶囊** | 深青 `00897B` | 按算子 1~2 个 | 按算子 | **纯节点** |
|
||||
| `py` | Python | 矩形 | 深灰蓝 `37474F` | exec, str(收全部) | exec, str | 用户写代码 |
|
||||
| `custom` | 自定义 | 矩形 | 洋红 `AD1457` | 来自 `nodes/` 声明 | 来自声明 | 用户加的节点 |
|
||||
|
||||
**纯节点**(`readvar` / `value` / `cast` / `op`)的意思是"**不在执行链上**"——
|
||||
它们没有 exec 引脚,值是被下游节点运行时**拉取**的。这就是"读变量为什么只有输出、
|
||||
没有 exec 入"的答案。
|
||||
|
||||
### 引脚类型
|
||||
|
||||
`exec` / `str` / `bool` / `num` / `list`(外加老数据的 `data`,当 `str` 处理)。
|
||||
|
||||
- `exec` 只排顺序**不传数据**,画成白色小三角
|
||||
- 数据引脚按类型上色:绿 str、蓝 num、红 bool、橙 list
|
||||
- **`accepts` 含全部四种的入口是紫色** —— `end` / `py` / `cast` / 写变量 / `branch` 的条件
|
||||
都是"什么都收",画成绿色的话用户会以为只能接文本
|
||||
|
||||
### 算子(23 个,`Ops.ALL`)
|
||||
|
||||
算术 `add sub mul div mod`、拼接 `concat`、比较 `eq ne streq strne gt lt gte lte`、
|
||||
单目 `neg not`、逻辑 `and or xor`、位运算 `shl shr`、列表 `append clear`。
|
||||
|
||||
判断条件 7 种(`JudgeKinds`)、转换目标 4 种(`CastKinds`)、
|
||||
列表写模式 2 种(`ListModes`)。
|
||||
|
||||
---
|
||||
|
||||
## 五、形状即语法
|
||||
|
||||
这条原则在**积木编辑器**里一直是落地的(帽形 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
但**会议画布上以前所有节点都是圆角矩形** —— 用户只能靠标题栏颜色和 10sp 的小字认节点。
|
||||
颜色有 13 种,记不住;形状只有 6 种,不用记。
|
||||
|
||||
所以 `NodeCatalog` 里每种类型带一个 `shape` 字段,用在两处:
|
||||
|
||||
1. **「加节点」面板里每个类型前面的缩略图** —— *选之前*就看出这是起点、判断、循环还是纯数据节点
|
||||
2. **节点卡片标题栏左边的小徽标** —— 图大了以后靠它认节点
|
||||
|
||||
| 形状 | 含义 | 谁用 |
|
||||
|---|---|---|
|
||||
| `Hat` 帽形 | 事件入口,只能待在最上面 | `start` |
|
||||
| `Diamond` 菱形(四角斜切) | 一进两出,走哪条看条件 | `judge` `branch` |
|
||||
| `Loop` 六边形 | 条件成立就绕回来 | `while` |
|
||||
| `Capsule` 胶囊 | 不执行,只提供值(等待被"拉") | `readvar` `value` `cast` `op` |
|
||||
| `Terminal` 上边切角 | 到这里结束 | `end` |
|
||||
| `Rect` 圆角矩形 | 普通动作 | `agent` `var` `py` `custom` |
|
||||
|
||||
**形状是"圆角矩形 + 局部变形",不是纯菱形/纯六边形** —— 因为卡片里要装东西
|
||||
(标题栏 24 + 引脚行 21×N + 内容 34),画成尖菱形四个角全是空的,而引脚必须紧贴
|
||||
左右边缘(那是连线的出发点,不能为了形状把线挪走)。
|
||||
|
||||
画法在 `NodeShapes.path()`,渲染在 App 的
|
||||
[`ui/NodeShapeBadge.kt`](../android/app/src/main/java/com/doubao/lynxclone/ui/NodeShapeBadge.kt)(`Canvas` + `drawPath`)。
|
||||
|
||||
---
|
||||
|
||||
## 六、加一种节点:清单
|
||||
|
||||
以前要改 6 处,现在改 2~3 处:
|
||||
|
||||
1. **`nodekit/Catalog.kt`** —— `NodeKind` 加常量、`NodeCatalog.ALL` 加一条
|
||||
(名字、描述、颜色、形状、默认标题、是否纯节点)
|
||||
2. **`nodekit/Specs.kt`** —— `inputPins()` / `outputPins()` 加分支
|
||||
3. **`android/kernel/meeting.py`** —— `NODE_TYPES` 加类型、`NODE_DATA_IN/OUT` 加表项、
|
||||
执行引擎加 `elif node_type == '...'` 分支
|
||||
4. **`MeetingsScreen.kt` 的 `NodeConfigDialog`** —— 加配置面板分支
|
||||
(标题已经不用改了,它从库里取)
|
||||
|
||||
**然后跑 `python scripts/verify-nodekit.py`** —— 它会告诉你哪一步漏了。
|
||||
|
||||
---
|
||||
|
||||
## 七、和引擎的关系 + 守门
|
||||
|
||||
节点定义是**跨语言**的:界面在 Kotlin,执行在 Python(`android/kernel/meeting.py`)。
|
||||
两边没法共享代码,所以只能"两边都写 + 一个脚本盯着"。
|
||||
|
||||
```bash
|
||||
python scripts/verify-nodekit.py
|
||||
```
|
||||
|
||||
它查 8 项:
|
||||
|
||||
| | 查什么 | 严格程度 |
|
||||
|---|---|---|
|
||||
| A | `NodeKind.ALL` vs `NODE_TYPES` | 集合必须相等 |
|
||||
| B | `PinKind.DATA` vs `PIN_TYPES` | 必须相等 |
|
||||
| C | `Ops.ALL` vs `OPS` | **逐项**(键/名字/入口类型/出口类型/元数) |
|
||||
| D | `JudgeKinds.ALL` vs `JUDGE_KINDS` | 必须相等 |
|
||||
| E | `CastKinds.ALL` ⊇ `CAST_KINDS` 的键 | 引擎有的界面必须有 |
|
||||
| F | `ListModes.ALL` 的键 | 必须是 `append` / `replace` |
|
||||
| G | `NodeSpecs.inputPins` vs `NODE_DATA_IN` | 宽松(见下) |
|
||||
| H | `NodeSpecs.outputPins` vs `NODE_DATA_OUT` | 宽松(见下) |
|
||||
|
||||
**G/H 为什么宽松**:界面的入参**故意比引擎宽**(`end` 收四种、`cast` 什么都收),
|
||||
因为界面卡太严会让用户"连了、一保存就被丢掉",而引擎才是最终把关的。
|
||||
所以只查**方向性**:引擎说要收的,界面必须也收得下。
|
||||
|
||||
**入口类型由配置决定的节点**(`op` 看算子、`cast` 看 `castTo`、`var` 看变量登记表、
|
||||
`custom` 看声明)静态对拍必然误报 —— 引擎给那几张表的是"宽松兜底值",不是真实要求。
|
||||
这类在脚本里显式跳过。
|
||||
|
||||
### 已知差异(脚本会报但不判失败)
|
||||
|
||||
- **`server/src/meeting.mjs` 是第二份引擎,明确落后**:只有 6 种节点、`PIN_TYPES` 缺 `list`。
|
||||
`scripts/verify-meeting.mjs` 里标注了"pyOnly 的用例不参与对拍"。
|
||||
- **引擎的 `NODE_DATA_OUT['judge'] = 'bool'`**,但界面上的判断节点只有 true/false
|
||||
两条 exec 出线、没有 bool 数据出口。也就是说引擎允许"把判断结果当数据接出去",
|
||||
界面做不到。不影响现有用法(判断的用途就是分叉),要用到时再处理。
|
||||
|
||||
---
|
||||
|
||||
## 八、踩过的坑(改这个库之前先看这一节)
|
||||
|
||||
**① Kotlin 的块注释可以嵌套。**
|
||||
在 `/** ... */` 里写 `nodes/*.py` 这种路径,那个 `/*` 会把注释吃掉,
|
||||
报的错是"缺少 `}`"和一堆莫名其妙的"未解析引用",完全指不到真正的位置。
|
||||
(写 `nodes/` 目录下的 .py 就没事。)
|
||||
|
||||
**② 库不需要 Compose 编译器插件。**
|
||||
`NodeShapes.kt` 里没有 `@Composable`,只用了 `Path` 这种值类型。挂了
|
||||
`org.jetbrains.kotlin.plugin.compose` 就必须往 classpath 塞 compose runtime,
|
||||
否则报 `The Compose Compiler requires the Compose Runtime to be on the class path`。
|
||||
|
||||
**③ 守门脚本的常量要从对的地方抠。**
|
||||
第一版 `verify-nodekit.py` 从 `Ops.kt` 里找 `object PinKind` —— 找不到,
|
||||
于是 24 个算子全报"不一致"。常量表在 `Pins.kt`。
|
||||
|
||||
**④ 别凭印象写清单。**
|
||||
第一版库里的 `JudgeKinds` 是照着"想当然"写的(`eq` / `gt` / `truthy` …),
|
||||
和引擎的 `JUDGE_KINDS` 完全对不上 —— 引擎是
|
||||
`contains` / `not_contains` / `longer_than` / `shorter_than` / `empty` / `not_empty` / `ai`。
|
||||
**是守门脚本抓出来的。** 这就是为什么每张表都要有对拍。
|
||||
|
||||
**⑤ 形状必须真的被用上。**
|
||||
这个仓库里已经有一批"定义了但没人用"的东西(`BlockShapes.kt` 的 `BooleanSlot` /
|
||||
`DropdownSlot`、`NodeBlockEditor.kt` 的 `shapeOf`、`MeetingsScreen.kt` 的
|
||||
`NODE_H` / `CANVAS_W` / `EXEC_COLOR`)。所以这次形状**落地在加节点面板和卡片徽标上**,
|
||||
不是"先定义着,以后再说"。
|
||||
|
||||
**⑥ 迁移用脚本 + 断言,不要手改。**
|
||||
删掉 `MeetingsScreen.kt` 里那 865 行用的是
|
||||
[`scripts/migrate-nodekit-strip.py`](../scripts/migrate-nodekit-strip.py):
|
||||
按行号删,但**每段都带内容断言**,对不上就整个中止、一个字节都不写。
|
||||
(PowerShell 的 `String.Replace` 匹配失败不报错;按行号剪贴算错下标把整个文件
|
||||
追加过一遍 —— 这两个坑这个仓库都踩过。)
|
||||
|
||||
---
|
||||
|
||||
## 九、迁移记录
|
||||
|
||||
| 项 | 迁移前 | 迁移后 |
|
||||
|---|---|---|
|
||||
| 节点类型清单(Kotlin) | 4 份(`nodeColor`/`inputPins`/`outputPins`/默认标题)+ 配置面板标题 | **1 份**(`NodeCatalog`) |
|
||||
| 引脚表 | `MeetingsScreen.kt` 两个长 `when`(326 行) | `Specs.kt`(197 行) |
|
||||
| 算子表 | 3 份、拆在两个文件 | **1 份**(`Ops.ALL`) |
|
||||
| 变量类型选项 | 界面里逐字重复 3 处 | 1 份(`VARIABLE_TYPE_OPTIONS`) |
|
||||
| 颜色常量 | 散落,同一个绿写 6 遍、两个不同的"白" | `Styles.kt` + `Catalog.kt` |
|
||||
| 几何常量 | `MeetingsScreen.kt`,含 3 个死常量 | `Geometry.kt`(死的删了) |
|
||||
| `MeetingsScreen.kt` | 8485 行 | **−865 行** |
|
||||
|
||||
**顺手修掉的两个 bug**(都是抽库时"同一个东西有第 N 份"暴露出来的):
|
||||
|
||||
- 节点的**配置面板标题**以前只认 4 种类型,打开 Python / 运算 / 转换 / 值 / while /
|
||||
分支 / 自定义节点时,标题一律写着**「最终输出」** —— 用户会以为点错了节点
|
||||
- 引擎的 `CAST_KINDS` 只列了 3 项(少了 `list`),而 `_cast_to()` 一直是按
|
||||
`PIN_TYPES`(含 list)校验的 —— 清单和实际行为不一致(已补齐)
|
||||
|
||||
---
|
||||
|
||||
## 相关
|
||||
|
||||
- [`android/nodekit/`](../android/nodekit/) —— 库本体
|
||||
- [`ui/MeetNodeKit.kt`](../android/app/src/main/java/com/doubao/lynxclone/ui/MeetNodeKit.kt) —— App 侧的接入层(唯一一层胶水)
|
||||
- [`ui/NodeShapeBadge.kt`](../android/app/src/main/java/com/doubao/lynxclone/ui/NodeShapeBadge.kt) —— 形状的渲染
|
||||
- [`scripts/verify-nodekit.py`](../scripts/verify-nodekit.py) —— 跨语言对拍守门
|
||||
- [`android/kernel/meeting.py`](../android/kernel/meeting.py) —— 执行引擎(Python 侧的权威定义)
|
||||
183
scripts/migrate-nodekit-strip.py
Normal file
183
scripts/migrate-nodekit-strip.py
Normal file
@@ -0,0 +1,183 @@
|
||||
"""把 MeetingsScreen.kt 里那些**已经搬进 :nodekit 的定义**删掉。
|
||||
|
||||
## 为什么要写脚本而不是手改
|
||||
|
||||
要删的有 19 段、合计约 1200 行,散在 8485 行的文件里。手工删两次的代价:
|
||||
|
||||
· PowerShell 的 `String.Replace` **匹配失败不报错**,删不掉还不知道
|
||||
· 按行号剪贴会算错下标(这个仓库里真的把整个文件追加过一遍)
|
||||
|
||||
所以这里按行号删,但**每段都带断言** —— 断言的文本对不上就整个中止,
|
||||
一个字节都不写。宁可报错,不要写坏。
|
||||
|
||||
## 断言里为什么用"内容"而不是"行号"
|
||||
|
||||
行号是我读了文件得到的,但删除过程中只要有一段错位,后面全错。
|
||||
把每段的关键行内容一起断言,等于顺手校验了行号没算错。
|
||||
|
||||
用法:
|
||||
python scripts/migrate-nodekit-strip.py # 预演(只检查,不写)
|
||||
python scripts/migrate-nodekit-strip.py --write # 真的写
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
KT = os.path.join(
|
||||
HERE, "..", "android", "app", "src", "main", "java",
|
||||
"com", "doubao", "lynxclone", "ui", "MeetingsScreen.kt",
|
||||
)
|
||||
|
||||
# (起始行, 结束行, [(行号, 必须包含的文本), ...]) —— 行号 1-based,闭区间
|
||||
BLOCKS = [
|
||||
(545, 555, [
|
||||
(545, "private const val NODE_W = 116f"),
|
||||
(547, "private const val NODE_H = 88f"),
|
||||
(553, "private const val CANVAS_W = 900f"),
|
||||
(555, "private const val CANVAS_H = 800f"),
|
||||
]),
|
||||
(3527, 3583, [
|
||||
(3529, "一个引脚。照 UE 蓝图分四类"),
|
||||
(3553, "private data class PinSpec("),
|
||||
(3579, "fun accepts_(fromKind: String): Boolean"),
|
||||
(3583, "}"),
|
||||
]),
|
||||
(3601, 3603, [
|
||||
(3601, "任何数据类型都能接"),
|
||||
(3603, 'private val ANY_DATA = listOf("str", "bool", "num", "list")'),
|
||||
]),
|
||||
(3607, 3637, [
|
||||
(3609, "运算表。必须和引擎里的"),
|
||||
(3615, "private val OPS_UI = listOf("),
|
||||
(3635, '"append" to "追加到列表"'),
|
||||
(3637, ")"),
|
||||
]),
|
||||
(3641, 3667, [
|
||||
(3643, "private fun opSpec(key: String)"),
|
||||
(3665, 'else -> Triple("num", "num", 2)'),
|
||||
(3667, "}"),
|
||||
]),
|
||||
(3671, 3675, [
|
||||
(3673, "private fun opLabel(key: String)"),
|
||||
(3675, "OPS_UI.firstOrNull"),
|
||||
]),
|
||||
(3679, 3871, [
|
||||
(3681, "节点的输入引脚。"),
|
||||
(3695, "private fun inputPins("),
|
||||
(3871, "}"),
|
||||
]),
|
||||
(3875, 4041, [
|
||||
(3877, "右边一列的引脚(从上到下)。"),
|
||||
(3893, "private fun outputPins("),
|
||||
(4041, "}"),
|
||||
]),
|
||||
(4045, 4067, [
|
||||
(4045, "UE 蓝图式的节点尺寸"),
|
||||
(4051, "private const val HEADER_H = 24f"),
|
||||
(4065, "private const val PORT_R = 5.5f"),
|
||||
(4067, "private const val PORT_HIT = 19f"),
|
||||
]),
|
||||
(4071, 4091, [
|
||||
(4073, "private fun nodeHeight("),
|
||||
(4091, "}"),
|
||||
]),
|
||||
(4095, 4115, [
|
||||
(4097, "引脚的几何位置"),
|
||||
(4107, "private fun pinPos(node: MeetingNode, index: Int, isOutput: Boolean)"),
|
||||
(4115, "}"),
|
||||
]),
|
||||
(4119, 4133, [
|
||||
(4119, "找输出引脚的序号"),
|
||||
(4121, "private fun outPinIndex("),
|
||||
(4133, "}"),
|
||||
]),
|
||||
(4137, 4195, [
|
||||
(4139, "输入端口的位置。"),
|
||||
(4151, "private fun portIn("),
|
||||
(4195, "}"),
|
||||
]),
|
||||
(4199, 4227, [
|
||||
(4199, "输出端口的位置"),
|
||||
(4201, "private fun portOut("),
|
||||
(4227, "}"),
|
||||
]),
|
||||
(4727, 4739, [
|
||||
(4727, "变量类型的中文名"),
|
||||
(4729, "private fun typeLabel(type: String)"),
|
||||
(4739, "}"),
|
||||
]),
|
||||
(5665, 5765, [
|
||||
(5665, "连线种类的中文名"),
|
||||
(5709, "private val ANY_COLOR = Color(0xFF9C27B0)"),
|
||||
(5715, "private fun pinColorOf(pin: PinSpec): Color"),
|
||||
(5723, "private fun pinColor(kind: String): Color"),
|
||||
(5747, "private fun pinBorder(kind: String): Color"),
|
||||
(5753, "private fun kindLabel(kind: String): String"),
|
||||
(5765, "}"),
|
||||
]),
|
||||
(5841, 5843, [
|
||||
(5841, "private val EXEC_COLOR = Color(0xFFE8EAED)"),
|
||||
(5843, "private val EXEC_BORDER = Color(0xFF5F6368)"),
|
||||
]),
|
||||
(5917, 5971, [
|
||||
(5919, "画布能铺多远(dp)。"),
|
||||
(5931, "private const val CANVAS_MARGIN = 900f"),
|
||||
(5937, "private fun canvasSize(nodes: List<MeetingNode>)"),
|
||||
(5957, "private fun clampPan("),
|
||||
(5971, ")"),
|
||||
]),
|
||||
(7025, 7055, [
|
||||
(7025, "private fun nodeColor(type: String): Color"),
|
||||
(7053, "else -> Doubao.Blue"),
|
||||
(7055, "}"),
|
||||
]),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
write = "--write" in sys.argv
|
||||
with io.open(KT, encoding="utf-8") as fh:
|
||||
lines = fh.read().split("\n")
|
||||
total = len(lines)
|
||||
print(f"{os.path.basename(KT)}:{total} 行")
|
||||
|
||||
# 先全部断言,一处不对就退出(不写文件)
|
||||
for start, end, checks in BLOCKS:
|
||||
if not (1 <= start <= end <= total):
|
||||
print(f"!! 区块 {start}-{end} 越界(文件只有 {total} 行)")
|
||||
return 1
|
||||
for ln, want in checks:
|
||||
got = lines[ln - 1] if 1 <= ln <= total else "<越界>"
|
||||
if want not in got:
|
||||
print(f"!! 第 {ln} 行断言失败")
|
||||
print(f" 期望包含:{want}")
|
||||
print(f" 实际内容:{got}")
|
||||
return 1
|
||||
print(f"断言全过({len(BLOCKS)} 段)")
|
||||
|
||||
# 从后往前删,前面的行号才不会偏移
|
||||
removed = 0
|
||||
for start, end, _ in sorted(BLOCKS, key=lambda b: -b[0]):
|
||||
del lines[start - 1:end]
|
||||
removed += end - start + 1
|
||||
print(f" 删除 {start}-{end}({end - start + 1} 行)")
|
||||
|
||||
print(f"合计删除 {removed} 行,剩 {len(lines)} 行")
|
||||
if not write:
|
||||
print("(预演模式,没有写文件。加 --write 才真写)")
|
||||
return 0
|
||||
|
||||
with io.open(KT, "w", encoding="utf-8", newline="") as fh:
|
||||
fh.write("\n".join(lines))
|
||||
print("已写入")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
128
scripts/probe-app-shortcuts.py
Normal file
128
scripts/probe-app-shortcuts.py
Normal file
@@ -0,0 +1,128 @@
|
||||
"""测「预设快捷入口」+ 打开 Activity。
|
||||
|
||||
★ 关键测的是**回退链**:深链失败 → 退回主界面,而不是"点了没反应"。
|
||||
emulator 上没装微信/支付宝,所以正好能测"没装"那条路。
|
||||
同时用**装了的 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):
|
||||
return call("/api/tools/run", {"name": name, "args": args})
|
||||
|
||||
|
||||
def err_of(r):
|
||||
if not isinstance(r, dict):
|
||||
return ""
|
||||
return str(r.get("error") or (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("=== 1. 列出预设 ===")
|
||||
r = tool("apps", {"action": "shortcuts"})
|
||||
res = (r or {}).get("result") or {}
|
||||
items = res.get("shortcuts") or []
|
||||
check(len(items) >= 10, f"有 {len(items)} 个预设")
|
||||
for it in items[:6]:
|
||||
mark = "装了" if it.get("installed") else "没装"
|
||||
print(f" [{mark}] {it.get('id'):18s} {it.get('label')}")
|
||||
|
||||
print()
|
||||
print("=== 2. 预设里要有用户点名的那两个 ===")
|
||||
ids = [it.get("id") for it in items]
|
||||
labels = " ".join(it.get("label") or "" for it in items)
|
||||
check("wechat-chat" in ids, "有「微信 · 聊天列表」", "wechat-chat")
|
||||
check("alipay-cainiao" in ids, "有「支付宝 · 菜鸟裹裹」", "alipay-cainiao")
|
||||
check("菜鸟" in labels, "菜鸟那个标签里有「菜鸟」二字")
|
||||
check("扫一扫" in labels, "也有扫一扫这类常用的")
|
||||
|
||||
print()
|
||||
print("=== 3. ★ 用关键词找预设(用户会说「打开微信聊天」)===")
|
||||
for kw in ("微信聊天", "朋友圈", "菜鸟", "支付宝扫一扫", "抖音"):
|
||||
r = tool("apps", {"action": "shortcut", "shortcut": kw})
|
||||
res = (r or {}).get("result") or {}
|
||||
err = err_of(r)
|
||||
if res.get("opened"):
|
||||
check(True, f"「{kw}」→ {res.get('label')}", f"how={res.get('how')}")
|
||||
else:
|
||||
# 没装这些 App,所以必然失败 —— 但**必须是"没装"这种可解释的失败**
|
||||
check("没装" in err or "没成功" in err, f"「{kw}」失败但理由可解释", err[:80])
|
||||
|
||||
print()
|
||||
print("=== 4. ★★ 失败时必须说明「试过哪些、各自为什么失败」 ===")
|
||||
r = tool("apps", {"action": "shortcut", "shortcut": "朋友圈"})
|
||||
err = err_of(r)
|
||||
check("试过" in err, "错误里列出了试过哪些候选", err[:110])
|
||||
check("没装" in err, "说清了是没装(而不是笼统的'打不开')")
|
||||
check("hint" in json.dumps(r, ensure_ascii=False) or "action=open" in err,
|
||||
"给了下一步建议")
|
||||
|
||||
print()
|
||||
print("=== 5. 不存在的预设要给可选项 ===")
|
||||
r = tool("apps", {"action": "shortcut", "shortcut": "根本不存在的预设xyz"})
|
||||
err = err_of(r)
|
||||
check("没有叫" in err, "说清了没有这个预设", err[:70])
|
||||
check("wechat" in err or "可以用的有" in err, "列出了可用的预设")
|
||||
|
||||
print()
|
||||
print("=== 6. 打开 Activity:只给包名也能开(自己查 launcher activity)===")
|
||||
r = tool("apps", {"action": "list"})
|
||||
res = (r or {}).get("result") or {}
|
||||
apps = res.get("apps") or []
|
||||
if apps:
|
||||
pkg = apps[0].get("package")
|
||||
r2 = tool("apps", {"action": "open", "package": pkg})
|
||||
res2 = (r2 or {}).get("result") or {}
|
||||
check(bool(res2.get("opened")) or bool(err_of(r2)),
|
||||
f"用包名打开 {pkg}", f"how={res2.get('how')} act={res2.get('activity')}")
|
||||
check(bool(res2.get("activity")) or bool(err_of(r2)),
|
||||
"返回了自己查到的 activity 名", str(res2.get("activity"))[:60])
|
||||
|
||||
print()
|
||||
print("=== 7. 给了 activity 就直达(activity 没导出时退回主界面)===")
|
||||
if apps:
|
||||
pkg = apps[0].get("package")
|
||||
r3 = tool("apps", {"action": "open", "package": pkg, "activity": pkg + ".NoSuchActivity"})
|
||||
res3 = (r3 or {}).get("result") or {}
|
||||
err3 = err_of(r3)
|
||||
if res3.get("opened"):
|
||||
check(True, "坏 activity 名 → 自动退回主界面", f"how={res3.get('how')} note={res3.get('note')}")
|
||||
else:
|
||||
check(bool(err3), "或者如实报错", err3[:80])
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
72
scripts/probe-ask-user-forever.py
Normal file
72
scripts/probe-ask-user-forever.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""验证:`ask_user` 弹窗**不限时**(用户要求"AI 询问界面不要限时")。
|
||||
|
||||
## 怎么验
|
||||
|
||||
以前是 120 秒到点自己消失。所以要证明"改了",必须**跨过 120 秒那条线**:
|
||||
调一次 ask_user,然后在 5 秒 / 130 秒两个时刻截图:
|
||||
|
||||
· 5 秒:弹窗在(说明调通了)
|
||||
· 130 秒:**弹窗还在**(说明真的不限时了。旧版这时候已经没了)
|
||||
· 再点一下选项:请求返回,`timeout` 是 false、`choice` 是点的那个
|
||||
|
||||
★ 这个脚本会**阻塞到用户点为止**(那正是它要测的东西),所以必须后台跑。
|
||||
|
||||
用法:
|
||||
adb forward tcp:15199 tcp:5199
|
||||
python scripts/probe-ask-user-forever.py
|
||||
"""
|
||||
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"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=900):
|
||||
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 main():
|
||||
print("调 ask_user —— 这个请求会一直挂着,直到有人在弹窗上点一下", flush=True)
|
||||
t0 = time.time()
|
||||
try:
|
||||
r = call("/api/tools/run", {
|
||||
"name": "ask_user",
|
||||
"args": {
|
||||
"question": "不限时测试:随便点一个(我不催你)",
|
||||
"options": [
|
||||
{"label": "选项 A", "value": "A"},
|
||||
{"label": "选项 B", "value": "B"},
|
||||
{"label": "选项 C", "value": "C"},
|
||||
],
|
||||
},
|
||||
}, timeout=900)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"!! 请求失败({time.time() - t0:.1f} 秒后):{exc}", flush=True)
|
||||
return 1
|
||||
|
||||
dt = time.time() - t0
|
||||
print(f"\n等了 {dt:.1f} 秒才返回(旧版 120 秒就会 timeout)", flush=True)
|
||||
print(json.dumps(r, ensure_ascii=False)[:500], flush=True)
|
||||
|
||||
if dt > 125 and not (r.get("result") or {}).get("timeout"):
|
||||
print("\n✅ 不限时生效:超过 120 秒仍然等到了用户的选择", flush=True)
|
||||
return 0
|
||||
print("\n? 结果需要人工看一眼(可能点得太快,或 timeout 语义不对)", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
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("✅ 全部通过")
|
||||
113
scripts/probe-seed-table-msg.py
Normal file
113
scripts/probe-seed-table-msg.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""给会话塞一条带**表格**的助手回复,用来测 Markdown 表格渲染。
|
||||
|
||||
★ 为什么要造数据而不是真让模型回一条:
|
||||
真回一条要配 API key、要等流式、还有网络不确定性 —— 而这里要测的是
|
||||
**表格在界面上渲染成什么样**,跟回复怎么来的无关。
|
||||
直接写一条一样的消息,测起来快且稳定(和 probe-seed-link-msg.py 同一套路)。
|
||||
|
||||
★ 内容就是用户截图里那张"一个月开销"表(原样抄的),
|
||||
外加对齐、兜底、不该被当成表格的几种边界。
|
||||
|
||||
用法:
|
||||
adb forward tcp:15199 tcp:5199
|
||||
python scripts/probe-seed-table-msg.py
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
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 = """先算:顶你个肺,话费 36(8+28 套餐),行,这笔比老子拍脑袋的省了一截,能多给你剩下一百来块。给你重新排一遍:
|
||||
|
||||
| 项目 | 一个月 | 备注 |
|
||||
|---|---|---|
|
||||
| 吃(早150+午363+晚510+零食150) | 1173 | 大头还是晚饭 |
|
||||
| 话费 | 36 | 8+28,不能再低就别硬压 |
|
||||
| 交通 | 120 | 地铁公交 |
|
||||
| 日用(纸巾洗发水牙膏) | 50 | |
|
||||
| 社交/应急 | 100 | 留个口子,别不设 |
|
||||
| 合计 | **1479** | |
|
||||
| 2000 剩 | ≈ 521 | |
|
||||
|
||||
顶你个肺,比之前估的 397 多了 124 —— 就省在话费和别的地方,说明你这数报得挺细。521 是能活的,但还是那句话:这钱是底线,不是零花钱。
|
||||
|
||||
对齐方式:
|
||||
|
||||
| 左边 | 中间 | 右边 |
|
||||
|:---|:---:|---:|
|
||||
| a | b | 1 |
|
||||
| 长一点的文字 | 中 | 2000 |
|
||||
|
||||
没写分隔行也认(兜底):
|
||||
|
||||
| 兜底表头 | 值 |
|
||||
| 第一行 | 1 |
|
||||
| 第二行 | 2 |
|
||||
|
||||
下面这行不算表格(只有一个竖线):a | b 就是普通文字。
|
||||
|
||||
只有一列的也不算表格:
|
||||
|
||||
| 只有一列 |
|
||||
|
||||
- [x] 已经做完的事
|
||||
- [ ] 还没做的事
|
||||
|
||||
表格后面紧跟正文不能被吞:
|
||||
|
||||
| 尾表 | x |
|
||||
|---|---|
|
||||
| 只一行 | 1 |
|
||||
|
||||
这句话必须**单独成段**显示出来,不能被吃进上面那张表里。"""
|
||||
|
||||
|
||||
def main():
|
||||
convs = call("/api/conversations", method="GET").get("conversations") or []
|
||||
print("会话数:", len(convs))
|
||||
for c in convs[:5]:
|
||||
print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount"))
|
||||
|
||||
if not convs:
|
||||
print("!! 没有会话,先在 App 里发一条消息")
|
||||
sys.exit(1)
|
||||
|
||||
cid = convs[0]["id"]
|
||||
print(f"\n往 {cid} 里塞一条带表格的回复…")
|
||||
|
||||
res = call(f"/api/conversations/{cid}", {
|
||||
"messages": [
|
||||
{"role": "user", "content": "帮我算算一个月最少花多少"},
|
||||
{"role": "assistant", "content": CONTENT},
|
||||
],
|
||||
}, method="PATCH")
|
||||
print("写入结果:", json.dumps(res, ensure_ascii=False)[:200])
|
||||
|
||||
full = call(f"/api/conversations/{cid}", method="GET").get("conversation") or {}
|
||||
msgs = full.get("messages") or []
|
||||
print("现在有", len(msgs), "条消息")
|
||||
for m in msgs:
|
||||
print(" ", m.get("role"), "|", (m.get("content") or "")[:60].replace("\n", " "))
|
||||
print("\n去 App 里打开这个会话,看表格渲染。")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -21,6 +21,15 @@ import sys
|
||||
import urllib.error
|
||||
import urllib.request as u
|
||||
|
||||
# ★★ 不加重定向的话,Windows 控制台默认 GBK,脚本里那些 `✓` 会直接
|
||||
# UnicodeEncodeError 崩掉 —— 而且**崩在创建 release 之后、传附件之前**:
|
||||
# 结果是"release 建好了、说明也写上了,就是没有 APK"。
|
||||
# 这个坑真踩过(v2.0.44 发版时),所以所有会打 ✓ 的脚本都要这一行。
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
API = 'http://192.168.100.103:8080/api/v1/repos/l/doubao-clone'
|
||||
# ★ 凭据不从仓库读(仓库是公开的)。要发版就先把这两个环境变量设上:
|
||||
|
||||
453
scripts/verify-nodekit.py
Normal file
453
scripts/verify-nodekit.py
Normal file
@@ -0,0 +1,453 @@
|
||||
"""守门:`:nodekit` 库里的节点定义,和 Python 引擎的**对拍**。
|
||||
|
||||
## 为什么必须有这个脚本
|
||||
|
||||
节点体系是**跨语言**的:定义在 Kotlin(界面画引脚、配色、算几何),
|
||||
执行在 Python(`android/kernel/meeting.py`)。两边没法共享代码,
|
||||
只能靠"两边都写一份 + 一个脚本盯着"。
|
||||
|
||||
而这次的教训正是**没有这个脚本的后果**。抽查发现的现状:
|
||||
|
||||
节点类型清单 4 份,三套内容(引擎 13 种 / 界面 12 种 / Node 6 种)
|
||||
引脚类型清单 5 份,内容不一样(Node 那份缺 list)
|
||||
算子表 3 份,拆成"键+名字"和"类型+元数"放两个文件
|
||||
变量类型选项 界面里逐字重复 3 处
|
||||
"什么都能接"的入参 引擎说"不卡类型",Node 说"一律什么都能接",语义相反
|
||||
|
||||
其中已经造成过真实故障:
|
||||
· 单目运算 `neg`/`not` 引擎里有、界面选不到
|
||||
· 写变量的 list 入口漏了,列表变量根本写不进去
|
||||
· 读变量出口写死 str,num 变量接不到运算节点
|
||||
|
||||
★ 这个脚本**吸收了原来的 `scripts/verify-ops.py`**(已删除)—— 那份只守算子表
|
||||
的键名,而且是靠正则去 `MeetingsScreen.kt` 里抠 `OPS_UI` / `opSpec` 两个地方。
|
||||
现在算子表只有一份(`Ops.ALL`),这里的 C 节逐项比 5 个字段(键/名字/入口类型/
|
||||
出口类型/元数),比它严,就不留两份重复的守门逻辑了。
|
||||
|
||||
## 这个脚本查什么
|
||||
|
||||
A. 节点类型清单 `NodeKind.ALL` == meeting.py 的 `NODE_TYPES`
|
||||
B. 引脚数据类型 `PinKind.DATA` == meeting.py 的 `PIN_TYPES`
|
||||
C. 算子表 `Ops.ALL` == meeting.py 的 `OPS`(键/名字/类型/元数,逐项)
|
||||
D. 判断条件种类 `JudgeKinds.ALL` == meeting.py 的 `JUDGE_KINDS`
|
||||
E. 转换目标类型 `CastKinds.ALL` == meeting.py 的 `CAST_KINDS`
|
||||
F. 列表写模式 `ListModes.ALL` == meeting.py 的 `LIST_OPS` 的风格(键集合)
|
||||
G. 数据入口类型 `NodeSpecs.inputPins` ~ meeting.py 的 `NODE_DATA_IN`(**宽松对拍**,见下)
|
||||
H. 数据出口类型 `NodeSpecs.outputPins` ~ meeting.py 的 `NODE_DATA_OUT`
|
||||
|
||||
★ G/H 为什么是"宽松对拍":界面那边的入参**故意比引擎宽**(比如 `end` 的入口
|
||||
收四种类型、`cast` 什么都收),因为界面卡太严会让用户"连了保存被丢",
|
||||
而引擎才是最终把关的。所以这里只查**方向性**:
|
||||
· 引擎说要收的类型,界面必须也能收(否则用户连不上)
|
||||
· 界面声明的出口类型,引擎不能完全没有这个概念
|
||||
查反了会把正确的宽容设计判成错误。
|
||||
|
||||
## 已知落后(只警告,不判失败)
|
||||
|
||||
`server/src/meeting.mjs` 是第二份引擎,**明确落后**(只有 6 种节点、没有 list)。
|
||||
它在 `scripts/verify-meeting.mjs` 里被标注为"pyOnly 的用例不参与对拍"。
|
||||
这里把它列出来提醒,但不算这次改造的失败项 —— 修它是另一件事。
|
||||
|
||||
用法:
|
||||
python scripts/verify-nodekit.py
|
||||
"""
|
||||
import ast
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
NK = os.path.join(REPO, "android", "nodekit", "src", "main", "java", "com", "doubao", "nodekit")
|
||||
MEETING_PY = os.path.join(REPO, "android", "kernel", "meeting.py")
|
||||
MEETING_MJS = os.path.join(REPO, "server", "src", "meeting.mjs")
|
||||
|
||||
fails = []
|
||||
warns = []
|
||||
|
||||
|
||||
def fail(msg):
|
||||
fails.append(msg)
|
||||
print(f" ✗ {msg}")
|
||||
|
||||
|
||||
def warn(msg):
|
||||
warns.append(msg)
|
||||
print(f" ! {msg}")
|
||||
|
||||
|
||||
def ok(msg):
|
||||
print(f" ✓ {msg}")
|
||||
|
||||
|
||||
def read(path):
|
||||
with io.open(path, encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 引擎侧
|
||||
|
||||
def py_consts(path):
|
||||
"""把模块顶层的字面量赋值抠出来(不 import,免得拖进内核依赖)"""
|
||||
tree = ast.parse(read(path))
|
||||
out = {}
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Assign):
|
||||
for t in node.targets:
|
||||
if isinstance(t, ast.Name):
|
||||
try:
|
||||
out[t.id] = ast.literal_eval(node.value)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Kotlin 侧
|
||||
|
||||
def kt_consts(src, obj):
|
||||
"""抠某个 object 里的 `const val X = "y"`"""
|
||||
m = re.search(r"object\s+%s\s*\{(.*?)\n\}" % obj, src, re.S)
|
||||
body = m.group(1) if m else src
|
||||
return dict(re.findall(r'const val (\w+)\s*=\s*"([^"]*)"', body))
|
||||
|
||||
|
||||
def kt_names_to_values(expr, consts):
|
||||
"""`listOf(START, PinKind.STR)` → ['start', 'str'];已经带引号的直接用
|
||||
|
||||
★ 两种写法都见得到:Catalog.kt 里是裸常量名(`START`),
|
||||
Ops.kt 里是带对象前缀的(`PinKind.STR`)—— 都得认。
|
||||
"""
|
||||
out = []
|
||||
for raw in expr.split(","):
|
||||
item = raw.strip()
|
||||
if not item:
|
||||
continue
|
||||
if item.startswith('"'):
|
||||
out.append(item.strip('"'))
|
||||
else:
|
||||
out.append(consts.get(item.split(".")[-1], f"<未知常量 {item}>"))
|
||||
return out
|
||||
|
||||
|
||||
def kt_object_body(src, obj):
|
||||
"""抠 object X { ... } 的正文(按大括号配平,别用正则偷懒)"""
|
||||
m = re.search(r"object\s+%s\s*\{" % obj, src)
|
||||
if not m:
|
||||
return ""
|
||||
i = src.index("{", m.start())
|
||||
depth = 0
|
||||
for j in range(i, len(src)):
|
||||
if src[j] == "{":
|
||||
depth += 1
|
||||
elif src[j] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return src[i + 1:j]
|
||||
return ""
|
||||
|
||||
|
||||
def kt_section(body, decl):
|
||||
"""抠 `val XXX: ... = <expr>` 的表达式(按括号配平到行尾或配平结束)"""
|
||||
m = re.search(re.escape(decl) + r"\s*(?::[^=]*)?=\s*", body)
|
||||
if not m:
|
||||
return ""
|
||||
start = m.end()
|
||||
depth = 0
|
||||
for j in range(start, len(body)):
|
||||
c = body[j]
|
||||
if c in "([{":
|
||||
depth += 1
|
||||
elif c in ")]}":
|
||||
if depth == 0:
|
||||
return body[start:j]
|
||||
depth -= 1
|
||||
elif c == "\n" and depth == 0:
|
||||
# 表达式可能跨行(listOf( 后面换行)—— 到深度 0 且遇到空行为止
|
||||
nxt = body[j:j + 2]
|
||||
if nxt.strip() == "" and depth == 0:
|
||||
return body[start:j]
|
||||
return body[start:]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 各节
|
||||
|
||||
def check_node_types(cat_src, py):
|
||||
print("\nA. 节点类型清单(NodeKind.ALL vs meeting.py NODE_TYPES)")
|
||||
consts = kt_consts(cat_src, "NodeKind")
|
||||
all_expr = kt_section(kt_object_body(cat_src, "NodeKind"), "val ALL: List<String>")
|
||||
kt = kt_names_to_values(re.sub(r"^listOf\(", "", all_expr.strip()).rstrip(")"), consts)
|
||||
want = list(py.get("NODE_TYPES") or ())
|
||||
if not kt:
|
||||
fail("没从 Catalog.kt 抠出 NodeKind.ALL(正则或代码结构变了)")
|
||||
return
|
||||
# ★ 比**集合**不比顺序:库里的顺序是「加节点」面板的展示顺序(刻意的),
|
||||
# 引擎那个元组的顺序只是历史写法,没有语义
|
||||
if set(kt) == set(want) and len(kt) == len(want):
|
||||
ok(f"{len(kt)} 种,和引擎一致(顺序不同是正常的,见脚本注释)")
|
||||
if kt != want:
|
||||
print(f" 库(面板顺序):{' '.join(kt)}")
|
||||
print(f" 引擎(历史顺序):{' '.join(want)}")
|
||||
else:
|
||||
only_kt = [x for x in kt if x not in want]
|
||||
only_py = [x for x in want if x not in kt]
|
||||
if only_kt:
|
||||
fail(f"库里有、引擎没有的节点类型:{only_kt}")
|
||||
if only_py:
|
||||
fail(f"引擎有、库里没有的节点类型:{only_py}(界面加不出来)")
|
||||
|
||||
|
||||
def check_pin_types(pins_src, py):
|
||||
print("\nB. 引脚数据类型(PinKind.DATA vs meeting.py PIN_TYPES)")
|
||||
consts = kt_consts(pins_src, "PinKind")
|
||||
expr = kt_section(kt_object_body(pins_src, "PinKind"), "val DATA: List<String>")
|
||||
kt = kt_names_to_values(re.sub(r"^listOf\(", "", expr.strip()).rstrip(")"), consts)
|
||||
want = list(py.get("PIN_TYPES") or ())
|
||||
if kt == want:
|
||||
ok(f"{kt}")
|
||||
else:
|
||||
fail(f"不一致 —— 库:{kt},引擎:{want}")
|
||||
|
||||
|
||||
def check_ops(ops_src, pins_src, py):
|
||||
print("\nC. 算子表(Ops.ALL vs meeting.py OPS)")
|
||||
# ★ 常量表在 Pins.kt 的 `object PinKind` 里,不在 Ops.kt ——
|
||||
# 一开始从 Ops.kt 抠,结果 `PinKind.NUM` 没被换成 "num",24 个算子全报错
|
||||
consts = kt_consts(pins_src, "PinKind")
|
||||
body = kt_object_body(ops_src, "Ops")
|
||||
expr = kt_section(body, "val ALL: List<Op>")
|
||||
got = []
|
||||
for m in re.finditer(
|
||||
r'Op\(\s*"([^"]+)"\s*,\s*"([^"]+)"\s*,\s*PinKind\.(\w+)\s*,\s*PinKind\.(\w+)\s*,\s*(\d+)\s*\)',
|
||||
expr,
|
||||
):
|
||||
got.append((
|
||||
m.group(1), m.group(2),
|
||||
consts.get(m.group(3), m.group(3)), consts.get(m.group(4), m.group(4)),
|
||||
int(m.group(5)),
|
||||
))
|
||||
want = [tuple(x) for x in (py.get("OPS") or ())]
|
||||
if not got:
|
||||
fail("没从 Ops.kt 抠出 Op(...) 条目(正则或代码结构变了)")
|
||||
return
|
||||
if got == want:
|
||||
ok(f"{len(got)} 个算子逐项一致(键 / 名字 / 入口类型 / 出口类型 / 元数)")
|
||||
return
|
||||
wing = {o[0]: o for o in want}
|
||||
gong = {o[0]: o for o in got}
|
||||
for k in [x for x in gong if x not in wing]:
|
||||
fail(f"库里多出算子 {k}(引擎没有)")
|
||||
for k in [x for x in wing if x not in gong]:
|
||||
fail(f"库里缺算子 {k}(引擎有,界面选不到 —— 就是 neg/not 那个坑)")
|
||||
for k in [x for x in gong if x in wing and gong[x] != wing[x]]:
|
||||
fail(f"算子 {k} 不一致:库 {gong[k]},引擎 {wing[k]}")
|
||||
|
||||
|
||||
def check_pairs(label, kt_file, obj, decl, py_key, py):
|
||||
print(f"\n{label}")
|
||||
src = read(kt_file)
|
||||
body = kt_object_body(src, obj)
|
||||
expr = kt_section(body, decl)
|
||||
kt = re.findall(r'"([^"]+)"\s*to\s*"([^"]*)"', expr)
|
||||
want = [tuple(x) for x in (py.get(py_key) or ())]
|
||||
if not kt:
|
||||
fail(f"没从 {os.path.basename(kt_file)} 抠出 {obj}.{decl}")
|
||||
return
|
||||
if kt == want:
|
||||
ok(f"{len(kt)} 项一致")
|
||||
else:
|
||||
fail(f"不一致\n 库:{kt}\n 引擎:{want}")
|
||||
|
||||
|
||||
def check_cast_and_list(ops_src, pins_src, py):
|
||||
print("\nE. 转换目标类型(CastKinds.ALL ⊇ meeting.py CAST_KINDS 的键)")
|
||||
consts = kt_consts(pins_src, "PinKind")
|
||||
body = kt_object_body(ops_src, "CastKinds")
|
||||
expr = kt_section(body, "val ALL")
|
||||
kt = kt_names_to_values(re.sub(r"^listOf\(", "", expr.strip()).rstrip(")"), consts)
|
||||
want = [k for k, _ in (py.get("CAST_KINDS") or ())]
|
||||
if not kt or kt[0].startswith("<未知"):
|
||||
fail(f"没从 Ops.kt 抠出 CastKinds.ALL(拿到的是 {kt})")
|
||||
elif all(w in kt for w in want):
|
||||
ok(f"库 {kt},引擎清单 {want}(库多出来的是引擎**行为上**支持的,见 Ops.kt 注释)")
|
||||
else:
|
||||
fail(f"引擎能转 {want},库只列了 {kt} —— 用户会选不到")
|
||||
|
||||
print("\nF. 列表写模式(ListModes.ALL 的键)")
|
||||
body = kt_object_body(ops_src, "ListModes")
|
||||
expr = kt_section(body, "val ALL")
|
||||
keys = [k for k, _ in re.findall(r'"([^"]+)"\s*to\s*"([^"]*)"', expr)]
|
||||
if keys == ["append", "replace"]:
|
||||
ok(f"{keys}(引擎的 listMode 就是这两个值)")
|
||||
else:
|
||||
fail(f"键不对:{keys},应该是 ['append', 'replace']")
|
||||
|
||||
|
||||
# 入口类型由**配置**决定的节点(运算看算子、转换看 castTo、写变量看变量登记表、
|
||||
# 自定义看声明)—— 引擎那边这几张表给的是"宽松兜底值",不是真实要求,
|
||||
# 静态对拍必然误报,所以单独列出来跳过
|
||||
CONFIG_DRIVEN_IN = {"OP", "CAST", "VAR", "CUSTOM"}
|
||||
|
||||
# 出口类型由配置决定的,同理;judge 也在这里 —— 它不是"配错了",
|
||||
# 而是一个**已知的设计差异**,下面单独 warn(不判失败)
|
||||
CONFIG_DRIVEN_OUT = {"READVAR", "CAST", "OP", "VALUE", "VAR", "CUSTOM", "JUDGE"}
|
||||
|
||||
|
||||
def pins_of_types(specs_src):
|
||||
"""粗解析 NodeSpecs:每个 `NodeKind.X -> ...` 分支里所有 PinSpec 的
|
||||
(kind, 这个入口能接什么)。给宽松对拍用,不追求还原控制流。"""
|
||||
src = read(specs_src)
|
||||
out_in, out_out = {}, {}
|
||||
for fn, dest in (("inputPins", out_in), ("outputPins", out_out)):
|
||||
m = re.search(r"fun\s+%s\(view: NodeView\): List<PinSpec> = when \(view\.type\) \{" % fn, src)
|
||||
if not m:
|
||||
continue
|
||||
seg = src[m.end():]
|
||||
nxt = re.search(r"\n fun |\n private fun ", seg)
|
||||
if nxt:
|
||||
seg = seg[:nxt.start()]
|
||||
for arm in re.finditer(r"NodeKind\.(\w+)\s*->\s*(.*?)(?=\n NodeKind\.|\Z)", seg, re.S):
|
||||
name, bodytxt = arm.group(1), arm.group(2)
|
||||
dest[name] = re.findall(
|
||||
r'PinSpec\(PinKind\.(\w+)[^)]*?(?:accepts\s*=\s*([^)]*?))?\)',
|
||||
bodytxt, re.S,
|
||||
)
|
||||
return out_in, out_out
|
||||
|
||||
|
||||
def accepts_of(kind: str, accepts_expr: str) -> list:
|
||||
"""一个 PinSpec 实际能接哪些类型"""
|
||||
a = (accepts_expr or "").strip()
|
||||
if not a:
|
||||
return [kind]
|
||||
if "ANY" in a:
|
||||
return ["STR", "BOOL", "NUM", "LIST"]
|
||||
names = re.findall(r'PinKind\.(\w+)|"(\w+)"', a)
|
||||
flat = [x or y for x, y in names]
|
||||
return flat or [kind]
|
||||
|
||||
|
||||
def check_pins_loose(specs_src, py):
|
||||
print("\nG/H. 引脚类型(宽松对拍:引擎要的,界面必须收得下)")
|
||||
kt_in, kt_out = pins_of_types(specs_src)
|
||||
if not kt_in or not kt_out:
|
||||
warn("没能从 Specs.kt 抠出引脚表(结构变了),这一节跳过")
|
||||
return
|
||||
|
||||
p2k = {"str": "STR", "bool": "BOOL", "num": "NUM", "list": "LIST"}
|
||||
data_in = py.get("NODE_DATA_IN") or {}
|
||||
data_out = py.get("NODE_DATA_OUT") or {}
|
||||
|
||||
checked = bad = 0
|
||||
for typ, accepts in data_in.items():
|
||||
name = typ.upper()
|
||||
if name in CONFIG_DRIVEN_IN:
|
||||
continue
|
||||
pins = kt_in.get(name)
|
||||
if not pins:
|
||||
continue
|
||||
# 数据入口 = 第一个非 exec 引脚(exec 只排顺序)
|
||||
data_pins = [(k, accepts_of(k, a)) for k, a in pins if k != "EXEC"]
|
||||
if not data_pins:
|
||||
continue
|
||||
checked += 1
|
||||
covered = set()
|
||||
for _, acc in data_pins:
|
||||
covered |= set(acc)
|
||||
missing = [a for a in accepts if p2k.get(a, "?") not in covered]
|
||||
if missing:
|
||||
bad += 1
|
||||
fail(f"引擎说 {typ} 的入口能接 {list(accepts)},界面只接了 {sorted(covered)}")
|
||||
if not bad:
|
||||
ok(f"入口方向一致(严格查了 {checked} 种类型;{sorted(CONFIG_DRIVEN_IN)} 由配置决定,跳过)")
|
||||
|
||||
checked = bad = 0
|
||||
for typ, out_type in data_out.items():
|
||||
name = typ.upper()
|
||||
if name in CONFIG_DRIVEN_OUT:
|
||||
continue
|
||||
pins = kt_out.get(name)
|
||||
if not pins:
|
||||
continue
|
||||
data_pins = [k for k, _ in pins if k != "EXEC"]
|
||||
checked += 1
|
||||
want = p2k.get(out_type)
|
||||
if want and want not in data_pins:
|
||||
bad += 1
|
||||
fail(f"引擎说 {typ} 的出口是 {out_type},界面给的数据出口是 {data_pins}")
|
||||
if not bad:
|
||||
ok(f"出口方向一致(严格查了 {checked} 种类型;{sorted(CONFIG_DRIVEN_OUT)} 由配置决定,跳过)")
|
||||
|
||||
# ★ judge 是个**已知的设计差异**:引擎的 NODE_DATA_OUT['judge'] = 'bool',
|
||||
# 而界面上判断节点只有 true/false 两条 exec 出线,没有 bool 数据出口。
|
||||
# 也就是说引擎允许"把判断结果当数据接出去",界面做不到。
|
||||
# 这不影响现有用法(判断的用途就是分叉),所以只提醒。
|
||||
if "judge" in data_out and "JUDGE" in kt_out:
|
||||
data_pins = [k for k, _ in kt_out["JUDGE"] if k != "EXEC"]
|
||||
if not data_pins:
|
||||
warn(
|
||||
"引擎的 NODE_DATA_OUT['judge']='bool',但界面的判断节点只有 "
|
||||
"true/false 两条 exec 出线、没有 bool 数据出口 —— 既有差异,"
|
||||
"要用『判断结果接给别的节点』时才需要处理"
|
||||
)
|
||||
|
||||
|
||||
def check_node_engine():
|
||||
print("\n已知落后:server/src/meeting.mjs(第二份引擎)")
|
||||
if not os.path.exists(MEETING_MJS):
|
||||
warn("没有 server/src/meeting.mjs")
|
||||
return
|
||||
src = read(MEETING_MJS)
|
||||
m = re.search(r"NODE_TYPES\s*=\s*\[([^\]]*)\]", src)
|
||||
node_types = re.findall(r"'([^']+)'", m.group(1)) if m else []
|
||||
m = re.search(r"PIN_TYPES\s*=\s*\[([^\]]*)\]", src)
|
||||
pin_types = re.findall(r"'([^']+)'", m.group(1)) if m else []
|
||||
ok_py = py_consts(MEETING_PY)
|
||||
warn(
|
||||
f"Node 引擎只有 {len(node_types)} 种节点(Python 有 {len(ok_py.get('NODE_TYPES', []))} 种)、"
|
||||
f"引脚类型 {pin_types}(缺 list)—— 这是**已知落后**,不在本次改造范围"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.exists(MEETING_PY):
|
||||
print(f"找不到 {MEETING_PY}")
|
||||
return 1
|
||||
py = py_consts(MEETING_PY)
|
||||
|
||||
cat = read(os.path.join(NK, "Catalog.kt"))
|
||||
pins = read(os.path.join(NK, "Pins.kt"))
|
||||
ops_path = os.path.join(NK, "Ops.kt")
|
||||
ops = read(ops_path)
|
||||
specs = os.path.join(NK, "Specs.kt")
|
||||
|
||||
print("=" * 70)
|
||||
print("nodekit ↔ Python 引擎 对拍")
|
||||
print("=" * 70)
|
||||
|
||||
check_node_types(cat, py)
|
||||
check_pin_types(pins, py)
|
||||
check_ops(ops, pins, py)
|
||||
check_pairs("D. 判断条件种类(JudgeKinds.ALL vs meeting.py JUDGE_KINDS)",
|
||||
ops_path, "JudgeKinds", "val ALL", "JUDGE_KINDS", py)
|
||||
check_cast_and_list(ops, pins, py)
|
||||
check_pins_loose(specs, py)
|
||||
check_node_engine()
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
if fails:
|
||||
print(f"失败 {len(fails)} 项:")
|
||||
for f in fails:
|
||||
print(f" · {f.splitlines()[0]}")
|
||||
return 1
|
||||
print(f"全部通过(警告 {len(warns)} 条)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,34 +0,0 @@
|
||||
"""核对引擎和界面的算子表是否一致。
|
||||
|
||||
加算子时"只加一边"已经犯过好几次:
|
||||
· 引擎加了 gte/lte/and/or/xor/shl/shr,界面 OPS_UI 没加(用户"没看到大于等于")
|
||||
· 引擎有 neg/not,界面也选不到
|
||||
加完算子先跑它,别等用户发现。
|
||||
"""
|
||||
import os, re, sys
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(WS, 'android', 'kernel'))
|
||||
import meeting as M
|
||||
KT = os.path.join(WS, 'android', 'app', 'src', 'main', 'java',
|
||||
'com', 'doubao', 'lynxclone', 'ui', 'MeetingsScreen.kt')
|
||||
src = open(KT, encoding='utf-8').read()
|
||||
m = re.search(r'OPS_UI = listOf\((.*?)\n\s*\)', src, re.S)
|
||||
ui = set(re.findall(r'"(\w+)"\s+to\s+"', m.group(1))) if m else set()
|
||||
eng = {o[0] for o in M.OPS}
|
||||
sb = re.search(r'private fun opSpec\(key: String\)(.*?)private fun opLabel', src, re.S)
|
||||
ss = sb.group(1) if sb else ''
|
||||
spec = set(re.findall(r'"(\w+)"', ss))
|
||||
has_else = 'else ->' in ss
|
||||
miss_ui = sorted(eng - ui)
|
||||
miss_spec = [] if has_else else sorted(ui - spec)
|
||||
covered = sorted(ui - spec) if has_else else []
|
||||
extra = sorted(ui - eng)
|
||||
print(' 引擎 OPS %d 个' % len(eng))
|
||||
print(' 界面 OPS_UI %d 个' % len(ui))
|
||||
print(' 界面 opSpec %d 个%s' % (len(spec), '(有 else 兜底)' if has_else else ''))
|
||||
print(' %s 引擎有、界面选项里没有: %s' % ('X' if miss_ui else 'v', miss_ui or '无'))
|
||||
print(' %s 界面有选项、opSpec 没定义类型: %s' % ('X' if miss_spec else 'v', miss_spec or '无'))
|
||||
if covered:
|
||||
print(' (%s 由 else 兜底,正常)' % covered)
|
||||
print(' %s 界面有、引擎不认: %s' % ('X' if extra else 'v', extra or '无'))
|
||||
sys.exit(1 if (miss_ui or miss_spec or extra) else 0)
|
||||
@@ -295,6 +295,76 @@ else:
|
||||
else:
|
||||
fail("run_agent 没按开关追加提示词")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ★★ 会等用户的工具必须**豁免工具超时**
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用户要求"AI 询问界面不要限时"。这个需求**要三处一起改才算数**:
|
||||
# ① 界面侧等多久(AiSurface.ask / showScreen)
|
||||
# ② 内核侧给工具多少时间(tools_runtime 的 TOOL_TIMEOUT_S)
|
||||
# ③ 工具自己声明的 timeout
|
||||
# 只改 ①③ 的后果实测过:弹窗 135 秒还开着,**但工具调用 60 秒就被内核判超时**,
|
||||
# 模型收到"工具执行超时(60s)",用户五分钟后点的选项根本回不到模型手里 ——
|
||||
# 表现是"弹窗还在、AI 已经自己往下写了"。这种"看起来改了其实没生效"最坑,
|
||||
# 所以在这里钉住。
|
||||
print("\n=== 等用户的工具不被工具超时掐掉 ===")
|
||||
|
||||
import inspect # noqa: E402 - 上面那个分支里才 import,这里保证一定有
|
||||
|
||||
import tools_runtime as TR
|
||||
|
||||
for tool_name in ("ask_user", "show_ui"):
|
||||
path = os.path.join(TOOLS, f"{tool_name}.py")
|
||||
src = open(path, encoding="utf-8").read()
|
||||
if "WAIT_FOR_USER = True" in src:
|
||||
ok(f"{tool_name}.py 声明了 WAIT_FOR_USER = True")
|
||||
else:
|
||||
fail(f"{tool_name}.py 没声明 WAIT_FOR_USER —— 内核会在 60 秒时把这次调用判超时")
|
||||
|
||||
if hasattr(TR, "_waits_for_user"):
|
||||
ok("tools_runtime 里有 _waits_for_user")
|
||||
else:
|
||||
fail("tools_runtime 没有 _waits_for_user,豁免逻辑不见了")
|
||||
|
||||
_src = inspect.getsource(TR.run_python_tool)
|
||||
if "_waits_for_user" in _src and "budget" in _src:
|
||||
ok("run_python_tool 是按它决定超时预算的")
|
||||
else:
|
||||
fail("run_python_tool 没用 _waits_for_user 决定预算")
|
||||
|
||||
# 引擎侧:0 必须真的等于"不限时"
|
||||
import builtin_tools as BT
|
||||
|
||||
if "thread.join()" in inspect.getsource(BT.run_with_timeout):
|
||||
ok("run_with_timeout 支持 timeout<=0 = 不限时")
|
||||
else:
|
||||
fail("run_with_timeout 不支持不限时(join 那支不见了)")
|
||||
|
||||
# 仿真一遍:给一个"永远不返回"的任务配 0 预算,它必须**不返回**
|
||||
# (真跑起来要等到天荒地老,所以这里用一个 20ms 后自己结束的任务代替,
|
||||
# 验证的是"0 走的是无限等待那支"而不是"0 立刻超时")
|
||||
import threading as _th
|
||||
|
||||
_done = _th.Event()
|
||||
|
||||
|
||||
def _slow():
|
||||
_done.wait(0.05)
|
||||
return "ok"
|
||||
|
||||
|
||||
_r = BT.run_with_timeout(_slow, 0)
|
||||
if _r == "ok":
|
||||
ok("预算 0 时会一直等到任务真的跑完(不是立刻超时)")
|
||||
else:
|
||||
fail(f"预算 0 的行为不对,拿到 {_r!r}")
|
||||
|
||||
# 反面:非豁免工具仍然是 60 秒(安全网还在,别为了这个把超时全关了)
|
||||
if TR.TOOL_TIMEOUT_S == 60:
|
||||
ok("普通工具的超时还是 60 秒(死循环的安全网没丢)")
|
||||
else:
|
||||
fail(f"TOOL_TIMEOUT_S 被改成 {TR.TOOL_TIMEOUT_S},普通工具的兜底变了")
|
||||
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
"048c7685991715fb"
|
||||
],
|
||||
"ask_user.py": [
|
||||
"94a9734c8c934db2"
|
||||
"94a9734c8c934db2",
|
||||
"c4728d5dfd765a99",
|
||||
"3adcd9b3c634cc22"
|
||||
],
|
||||
"calc.py": [
|
||||
"4d9e5a51ad8f71eb"
|
||||
@@ -18,7 +20,8 @@
|
||||
"b03b5b99dbd83587"
|
||||
],
|
||||
"notes.py": [
|
||||
"f2255c693b2401b5"
|
||||
"f2255c693b2401b5",
|
||||
"7da481daace71368"
|
||||
],
|
||||
"now.py": [
|
||||
"eb0c37b5afc1dd8b"
|
||||
@@ -34,7 +37,9 @@
|
||||
"6f3ce8a4c924dfdd",
|
||||
"ecea108ef1118386",
|
||||
"f80e4da69db41722",
|
||||
"5f11cf92d2a78ce1"
|
||||
"5f11cf92d2a78ce1",
|
||||
"fc8c411abd1addeb",
|
||||
"a6f1bdaa5de71fcc"
|
||||
],
|
||||
"weather.py": [
|
||||
"bff69719c190d3d9"
|
||||
@@ -47,5 +52,17 @@
|
||||
],
|
||||
"send_message.py": [
|
||||
"f133c98b6325f3ac"
|
||||
],
|
||||
"apps.py": [
|
||||
"7215ae7bc60f6f83",
|
||||
"4dcbb22a4b57607e",
|
||||
"ea150707c2aca7f5"
|
||||
],
|
||||
"notifications.py": [
|
||||
"3e8ba8ae55b80019",
|
||||
"5c006bc7be02d5f3"
|
||||
],
|
||||
"volume.py": [
|
||||
"255939a9c89f51a2"
|
||||
]
|
||||
}
|
||||
|
||||
186
tools/apps.py
Normal file
186
tools/apps.py
Normal file
@@ -0,0 +1,186 @@
|
||||
"""打开手机上的 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· action=open(默认)—— 打开一个 App。"
|
||||
"\n 传 name(名字,模糊匹配即可,比如「微信」「抖音」);"
|
||||
"\n 或者传 package(包名,更准)、package + activity(直达某个页面)"
|
||||
"\n· action=shortcut —— **走预设快捷入口**,一句话直达某 App 的某个页面。"
|
||||
"\n 传 shortcut(预设 id 或关键词,比如 wechat-chat / 朋友圈 / 支付宝扫一扫 / 菜鸟)"
|
||||
"\n 已有的预设:微信主界面 / 微信聊天列表 / 微信扫一扫 / 微信朋友圈 / 微信收付款 /"
|
||||
"\n 支付宝主界面 / 支付宝扫一扫 / 支付宝付款码 / 支付宝卡包 / 支付宝菜鸟 /"
|
||||
"\n 淘宝 / QQ / 抖音"
|
||||
"\n· action=shortcuts —— 列出全部预设(含装了没有)"
|
||||
"\n· action=find —— 按名字找,返回匹配到的 App(名字 + 包名)"
|
||||
"\n· action=list —— 列出装了的 App。传 query 过滤(不传就列一部分)"
|
||||
"\n\n★ 用户说「打开微信聊天」「开一下支付宝菜鸟」这种**带目的地**的要求时,"
|
||||
"\n 优先用 action=shortcut —— 它直达那个页面,比只打开 App 主界面更省事。"
|
||||
"\n★ 预设打不开时会自动退回打开 App 主界面,所以最差情况也是「App 开了」。"
|
||||
"\n 返回里 how 会告诉你是哪一层成功的(uri=深链 / activity=直达页面 / main=主界面)。"
|
||||
"\n★ 深链和 Activity 名字**会随 App 版本变**。如果某个预设失效了,"
|
||||
"\n 可以让用户改 tools/apps.py 里的候选值(文件里有说明)。"
|
||||
"\n★ 打开 App 会让它**跑到前台盖住当前画面**,所以只在用户明确要求时才用。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["open", "shortcut", "shortcuts", "find", "list"],
|
||||
"description": "要做的事,默认 open",
|
||||
},
|
||||
"name": {"type": "string", "description": "App 名字(模糊匹配),open/find 用"},
|
||||
"shortcut": {
|
||||
"type": "string",
|
||||
"description": "预设快捷入口的 id 或关键词,如 wechat-chat / 朋友圈 / 菜鸟",
|
||||
},
|
||||
"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 == "shortcuts":
|
||||
res = call_device({"action": "app_shortcuts"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
items = res.get("shortcuts") or []
|
||||
# ★ 把"没装的"排到后面:模型挑的时候会优先挑能用的
|
||||
items.sort(key=lambda x: (not x.get("installed"), x.get("label") or ""))
|
||||
return {
|
||||
"count": len(items),
|
||||
"installed": sum(1 for x in items if x.get("installed")),
|
||||
"shortcuts": items,
|
||||
}
|
||||
|
||||
if action == "shortcut":
|
||||
key = str(args.get("shortcut") or args.get("name") or "").strip()
|
||||
if not key:
|
||||
raise ValueError("shortcut 需要给 shortcut(预设 id 或关键词)")
|
||||
res = call_device({"action": "app_shortcut_open", "shortcut": key})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
# ★ 把"试过哪些候选"一起抛出去。只回一句"打不开"的话,
|
||||
# 用户和模型都不知道下一步干嘛(是没装?还是版本改了深链?)
|
||||
tried = res.get("tried") or []
|
||||
detail = ""
|
||||
if tried:
|
||||
detail = ";试过:" + ",".join(
|
||||
f"{t.get('kind')}({t.get('detail') or ''})={t.get('error')}" for t in tried
|
||||
)
|
||||
hint = res.get("hint") or ""
|
||||
raise RuntimeError(f"{res['error']}{detail}。{hint}".strip())
|
||||
return {
|
||||
"opened": True,
|
||||
"shortcut": res.get("shortcut"),
|
||||
"label": res.get("label"),
|
||||
"how": res.get("how"),
|
||||
"detail": res.get("detail") or "",
|
||||
"note": (
|
||||
"已经打开了。"
|
||||
+ ("" if res.get("how") == "uri" else
|
||||
"(没能直达指定页面,退回打开 App 主界面了)")
|
||||
),
|
||||
}
|
||||
|
||||
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())
|
||||
|
||||
out = {
|
||||
"opened": True,
|
||||
"app": res.get("label") or payload["name"] or payload["package"],
|
||||
"package": res.get("package") or payload["package"],
|
||||
}
|
||||
# ★ how / activity 要透传出去 —— 它们说明"走到了哪一层":
|
||||
# how=direct 直达指定页面 / launcher 开的是主界面。
|
||||
# 排查"为什么没进到我想要的那个页面"时,这两个字段是关键。
|
||||
if res.get("activity"):
|
||||
out["activity"] = res.get("activity")
|
||||
if res.get("how"):
|
||||
out["how"] = res.get("how")
|
||||
# Kotlin 侧在"直拉失败、退回主界面"时会带一句 note,别丢掉
|
||||
if res.get("note"):
|
||||
out["note"] = res["note"]
|
||||
else:
|
||||
out["note"] = "App 已经切到前台了。"
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
@@ -14,8 +14,18 @@
|
||||
然后用一个 `CountDownLatch` 等用户点,等到(或超时)才把结果回给 Python。
|
||||
Python 这边就是一次普通调用,不需要轮询。
|
||||
|
||||
★ 超时必须有:用户可能把手机锁屏走了,不能让内核线程永远挂着。
|
||||
默认 120 秒,到点返回 `timeout: true`,模型据此知道"用户没理我"。
|
||||
## ★★ 不限时(用户明确要求:"AI 询问界面不要限时")
|
||||
|
||||
`TIMEOUT_S = 0` 表示**一直等**。原来默认 120 秒,问题很实在:
|
||||
|
||||
· 用户看到选项、去翻了下手机算个数、回来弹窗没了;
|
||||
· 模型收到 `timeout=true`,理解成"用户不想理我",于是自说自话往下走;
|
||||
· 用户回来发现 AI 已经按它自己猜的答案干完了 —— 这一轮整个废掉。
|
||||
|
||||
"等用户回答"这件事本来就不该有截止时间:**要问就好好等,不想等就别问**。
|
||||
所以默认无限等,模型真想限时得自己传 `timeout`(有上限,见下)。
|
||||
|
||||
放行的出口(不会死锁):点任意选项 / 点「取消」/ 关掉 App。
|
||||
|
||||
## 电脑端
|
||||
|
||||
@@ -29,20 +39,32 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||
|
||||
# 等用户的秒数上限。安卓侧也有自己的上限,两边都不设的话
|
||||
# 用户锁屏走了会把内核的工作线程永远占住。
|
||||
TIMEOUT_S = 120
|
||||
# 等用户的秒数。**0 = 不限时**(默认)。
|
||||
TIMEOUT_S = 0
|
||||
|
||||
# 模型显式传 timeout 时的上限:1 小时。再长没有意义 ——
|
||||
# 用户多半是走了,而内核那条 HTTP 工作线程会一直占着。
|
||||
MAX_TIMEOUT_S = 3600
|
||||
|
||||
# ★★ 告诉内核:这个工具**会停下来等用户**,别拿 60 秒的工具超时卡它。
|
||||
#
|
||||
# 不声明的话后果很隐蔽:弹窗还开着(界面侧是不限时的),
|
||||
# 但内核 60 秒就把这次调用判成"工具执行超时"、把结果丢掉了 ——
|
||||
# 用户五分钟后点的那个选项**根本回不到模型手里**,模型已经开始自己编了。
|
||||
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
|
||||
WAIT_FOR_USER = True
|
||||
|
||||
TOOL = {
|
||||
"name": "ask_user",
|
||||
"description": (
|
||||
"弹一个选择弹窗问用户,**等用户选完**再继续(最多等 120 秒)。"
|
||||
"弹一个选择弹窗问用户,**等用户选完**再继续(默认不限时,会一直等)。"
|
||||
"适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。"
|
||||
"options 传选项数组(每项 {label, value, description}):"
|
||||
"label 是按钮上显示的字,value 是你要拿到的值(留空则用 label),"
|
||||
"description 是选项下方的小字说明。"
|
||||
"多选请传 multiple=true。返回里 choice/values 就是用户选的东西;"
|
||||
"timeout=true 表示用户没在时限内回答。"
|
||||
"cancelled=true 表示用户点了取消,timeout=true 表示你显式设了 timeout 且等超了。"
|
||||
"★ 默认一直等用户 —— 别在正文里催,也别自己替用户假设答案。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
@@ -72,6 +94,13 @@ TOOL = {
|
||||
"type": "boolean",
|
||||
"description": "是否显示「取消」按钮,默认 true",
|
||||
},
|
||||
"timeout": {
|
||||
"type": "number",
|
||||
"description": (
|
||||
"等用户的秒数。**默认 0 = 不限时**(推荐,别乱传)。"
|
||||
f"只有确实需要「用户不在就算了」的场景才传,上限 {MAX_TIMEOUT_S} 秒。"
|
||||
),
|
||||
},
|
||||
},
|
||||
"required": ["question", "options"],
|
||||
},
|
||||
@@ -106,6 +135,27 @@ def _clean_options(raw) -> list:
|
||||
return out
|
||||
|
||||
|
||||
def _timeout_ms(args: dict) -> int:
|
||||
"""
|
||||
算等多久。0 = 不限时。
|
||||
|
||||
★ 默认 0:模型不传就是一直等。这是刻意的 —— "问用户"这件事
|
||||
没有一个合理的截止时间,120 秒的默认值只会制造"AI 不等我就自己决定"。
|
||||
★ 模型传了才限时,并且夹在 [1, MAX_TIMEOUT_S]:传负数/0 会退化成"等 1 秒",
|
||||
那是模型写错了,不该让它把弹窗变成一闪而过。
|
||||
"""
|
||||
raw = args.get("timeout")
|
||||
if raw in (None, "", 0, "0"):
|
||||
return TIMEOUT_S * 1000
|
||||
try:
|
||||
sec = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return TIMEOUT_S * 1000
|
||||
if sec <= 0:
|
||||
return TIMEOUT_S * 1000
|
||||
return int(max(1.0, min(float(MAX_TIMEOUT_S), sec)) * 1000)
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
question = str(args.get("question") or "").strip()
|
||||
if not question:
|
||||
@@ -119,6 +169,7 @@ def run(args: dict) -> dict:
|
||||
options = options[:8]
|
||||
truncated = True
|
||||
|
||||
timeout_ms = _timeout_ms(args)
|
||||
res = call_device(
|
||||
{
|
||||
"action": "ui_dialog",
|
||||
@@ -126,7 +177,7 @@ def run(args: dict) -> dict:
|
||||
"options": options,
|
||||
"multiple": bool(args.get("multiple")),
|
||||
"allowCancel": bool(args.get("allow_cancel", True)),
|
||||
"timeoutMs": TIMEOUT_S * 1000,
|
||||
"timeoutMs": timeout_ms,
|
||||
"conversationId": conversation_id(),
|
||||
}
|
||||
)
|
||||
@@ -145,6 +196,9 @@ def run(args: dict) -> dict:
|
||||
}
|
||||
if truncated:
|
||||
out["note"] = "选项超过 8 个,只显示了前 8 个"
|
||||
# ★ 用户点了取消:不是"没回答",别让模型以为可以照自己的意思继续
|
||||
if out["cancelled"]:
|
||||
out["note"] = "用户点了取消,不想在这几个选项里选。停下来问他想怎么做,别自己替他决定。"
|
||||
return out
|
||||
|
||||
|
||||
|
||||
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)
|
||||
|
||||
192
tools/notifications.py
Normal file
192
tools/notifications.py
Normal file
@@ -0,0 +1,192 @@
|
||||
"""读手机上的通知。
|
||||
|
||||
## 这是三个"动手机"的工具之一(另两个:开 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· action=notify —— 发一条通知给用户。传 title(标题)和 text(正文)。"
|
||||
"\n ★ 这是**会打扰用户**的动作(他手机会响/震)——只在真的值得提醒时用:"
|
||||
"\n 定时提醒、长任务跑完了、用户让你过一会儿告诉他。"
|
||||
"\n 别用它来重复你已经在对话里说过的话。"
|
||||
"\n 点了通知会回到本 App。"
|
||||
"\n\n★ 读通知之前用户必须先手动开「通知使用权」(安卓不给运行时申请)。"
|
||||
"\n 没开的时候本工具会返回错误 + 怎么开的提示 —— 请照着念给用户,"
|
||||
"\n 别自己编步骤。**发通知不需要这个权限。**"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["list", "alive", "access", "open_settings", "clear", "notify"],
|
||||
"description": "要做的事,默认 list",
|
||||
},
|
||||
"query": {"type": "string", "description": "按关键词过滤(可选)"},
|
||||
"limit": {"type": "number", "description": "最多几条,默认 20,最多 200"},
|
||||
"title": {"type": "string", "description": "action=notify 时的通知标题"},
|
||||
"text": {"type": "string", "description": "action=notify 时的通知正文"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "list").strip().lower()
|
||||
|
||||
# ★ 发通知放在最前面:它**不需要**通知使用权(那权限只管读),
|
||||
# 所以不能被下面读路径的权限检查拦住。
|
||||
if action == "notify":
|
||||
title = str(args.get("title") or "").strip()
|
||||
text = str(args.get("text") or "").strip()
|
||||
if not title and not text:
|
||||
raise ValueError("notify 至少要给 title 或 text")
|
||||
res = call_device({
|
||||
"action": "notification_post",
|
||||
"title": title,
|
||||
"text": text,
|
||||
"autoCancel": True,
|
||||
})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有通知能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"sent": True,
|
||||
"title": res.get("title") or title,
|
||||
"chars": res.get("chars", len(text)),
|
||||
"note": (
|
||||
"通知已经发出去了,用户手机会响/震一下。"
|
||||
"点它会回到本 App。"
|
||||
"**别为了同一件事再发一条** —— 用户会烦。"
|
||||
),
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -29,6 +29,16 @@ 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
|
||||
|
||||
# wait=true 时的等待秒数上限 / 下限。0 = 不限时(默认,见 run)。
|
||||
MIN_TIMEOUT_S = 5.0
|
||||
MAX_TIMEOUT_S = 3600.0
|
||||
|
||||
# ★★ 告诉内核:这个工具在 wait=true 时**会停下来等用户**,别拿 60 秒的
|
||||
# 工具超时卡它(wait=false 时它立刻就返回,不受影响)。
|
||||
# 不声明的后果和 ask_user 那边一样:界面还开着,模型却已经收到"工具超时"。
|
||||
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
|
||||
WAIT_FOR_USER = True
|
||||
|
||||
TOOL = {
|
||||
"name": "show_ui",
|
||||
"description": (
|
||||
@@ -51,11 +61,12 @@ TOOL = {
|
||||
"\n \"给用户看\"的东西。用户看完自己关,你这一轮已经答完了。"
|
||||
"\n 用户后来说话时,你能看到他在界面上点过什么(会作为上下文附给你)。"
|
||||
"\n"
|
||||
"\n wait=true —— **等用户操作**(点回传按钮或关掉界面,最多 timeout 秒)。"
|
||||
"\n wait=true —— **等用户操作**(点回传按钮或关掉界面,**默认不限时,一直等**)。"
|
||||
"\n 适合\"弹出几个选项让用户挑,然后我接着干\"。用户点了什么会**立刻**"
|
||||
"\n 作为本工具的返回值给你,你能在**同一个回合里**继续处理。"
|
||||
"\n 用户直接关掉界面(没点任何按钮)时返回 value=空串、closed=true。"
|
||||
"\n 超时返回 timeout=true —— 那就当作用户没理你,正常收尾就行。"
|
||||
"\n ★ 别自己传 timeout —— 用户在想事情的时候界面自己消失很难受。"
|
||||
"\n 只有\"用户不在就算了\"的场景才传(秒,上限 3600)。"
|
||||
"\n"
|
||||
"\n 也可以**什么都不做**:不弹界面,直接文字回答。"
|
||||
"\n"
|
||||
@@ -82,12 +93,15 @@ TOOL = {
|
||||
"type": "boolean",
|
||||
"description": (
|
||||
"false(默认)弹出就返回,不等用户;"
|
||||
"true 等用户点回传按钮或关掉界面再返回(最多 timeout 秒)"
|
||||
"true 等用户点回传按钮或关掉界面再返回(**默认不限时**)"
|
||||
),
|
||||
},
|
||||
"timeout": {
|
||||
"type": "number",
|
||||
"description": "wait=true 时最多等多少秒,默认 120,最大 600",
|
||||
"description": (
|
||||
"wait=true 时最多等多少秒。**默认 0 = 不限时**,一般别传。"
|
||||
"只有确实要\"用户不在就算了\"时才传(5–3600)"
|
||||
),
|
||||
},
|
||||
},
|
||||
"required": ["html"],
|
||||
@@ -95,19 +109,37 @@ TOOL = {
|
||||
}
|
||||
|
||||
|
||||
def _timeout_seconds(args: dict) -> float:
|
||||
"""
|
||||
算等多久。**0 = 不限时**(默认)。
|
||||
|
||||
★ 模型传了才限时,并且夹在 [MIN_TIMEOUT_S, MAX_TIMEOUT_S]。
|
||||
传负数 / 0 / 垃圾值一律退回"不限时"—— 那些都是模型写错了,
|
||||
不该让它把界面变成一闪而过。
|
||||
"""
|
||||
raw = args.get("timeout")
|
||||
if raw in (None, "", 0, "0"):
|
||||
return 0.0
|
||||
try:
|
||||
sec = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
if sec <= 0:
|
||||
return 0.0
|
||||
return max(MIN_TIMEOUT_S, min(MAX_TIMEOUT_S, sec))
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
html = str(args.get("html") or "").strip()
|
||||
if not html:
|
||||
raise ValueError("html 不能为空")
|
||||
|
||||
wait = bool(args.get("wait"))
|
||||
# 上限 600 秒:再长的话内核工作线程被占住太久(HTTP 是每请求一线程)。
|
||||
# 下限 5 秒:低于这个值用户根本来不及看清界面就被判超时了。
|
||||
try:
|
||||
timeout = float(args.get("timeout") or 120)
|
||||
except (TypeError, ValueError):
|
||||
timeout = 120.0
|
||||
timeout = max(5.0, min(600.0, timeout))
|
||||
# ★★ 默认 0 = **不限时**(用户要求"AI 询问界面不要限时")。
|
||||
# 以前默认 120 秒、上限 600,结果是用户还在看界面它自己没了。
|
||||
# 模型显式传了才限时:下限 5 秒(低于这个值用户来不及看清界面),
|
||||
# 上限 1 小时(再长没意义,那条 HTTP 工作线程会一直占着)。
|
||||
timeout = _timeout_seconds(args)
|
||||
|
||||
payload = {
|
||||
"action": "ui_screen",
|
||||
@@ -156,8 +188,10 @@ def run(args: dict) -> dict:
|
||||
out["value"] = value
|
||||
|
||||
if out["timeout"]:
|
||||
mins = timeout / 60
|
||||
waited = f"{timeout:.0f} 秒" if timeout < 120 else f"约 {mins:.0f} 分钟"
|
||||
out["note"] = (
|
||||
f"等了 {timeout:.0f} 秒用户也没操作,界面已收起。"
|
||||
f"等了{waited}用户也没操作(你显式设了 timeout),界面已收起。"
|
||||
"当作用户暂时没空处理,别反复重弹 —— 正常收尾,等他自己来说。"
|
||||
)
|
||||
elif value:
|
||||
|
||||
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