From f330af963abcff038076c0a3ab98111f75461dfa Mon Sep 17 00:00:00 2001 From: doubao Date: Thu, 15 Oct 2026 16:36:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=89=93=E5=BC=80=20App=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=8C=87=E5=AE=9A=E6=B4=BB=E5=8A=A8=20+=20=E9=A2=84=E8=AE=BE?= =?UTF-8?q?=E5=BF=AB=E6=8D=B7=E5=85=A5=E5=8F=A3=20(v2.0.43)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户要求:"打开应用工具支持打开活动,并预设几个比如微信对话,支付宝菜鸟" ## 打开"活动"(Activity)分三层 · **只给包名** → 自己查它的 launcher activity(不用模型去记 `com.tencent.mm.ui.LauncherUI` 这种名字,既没必要也容易记错) · **给包名 + activity** → **先直拉那个 Activity**(能直达指定页面); 直拉失败就退回标准 launcher 方式 —— App 内部的 Activity 常常没导出, 直接拉会被系统拒(`ActivityNotFoundException`) · **给预设 id / 关键词** → 走下面那张表的回退链 ## 预设快捷入口(13 个) 微信主界面 / 微信聊天列表 / 微信扫一扫 / 微信朋友圈 / 微信收付款 支付宝主界面 / 支付宝扫一扫 / 支付宝付款码 / 支付宝卡包 / 支付宝菜鸟 淘宝 / QQ / 抖音 用户说"打开微信聊天"、"开一下支付宝菜鸟"这种**带目的地**的要求时, `action=shortcut` 直达那个页面,比只打开主界面省事。 ### ★ 每个预设是一**串候选**,不是一个 因为深链 scheme 和 Activity 名字**都会随 App 版本变**。只赌一个的话, 用户那边 App 一升级就静默失效,而且报的还是笼统的"打不开",查起来很费劲。 所以每个预设按顺序试,第一个成的算: 1. 深链(最稳,scheme 通常不变) 2. 指定 Activity(有的页面有独立 Activity) 3. 退回主界面(保证"至少把 App 打开了") 返回里 `how` 说明是**哪一层**成的(uri / direct / launcher)。 ### ★ 诚实地说明这些 scheme 没法离线验证 我没法在没有真机 App 的情况下确认 `weixin://dl/chat` 一定进"聊天列表"、 `alipays://platformapi/startapp?appId=200011235` 一定开菜鸟。 这些值来自公开的深链惯例,**多数情况可用,但 App 大版本更新后可能失效**。 所以设计上做了兜底: · 全部走"多候选 + 退回主界面" —— 失效也不会变成"点了没反应" · 失败时返回**试过哪些候选 + 各自为什么失败**,而不是一句"打不开" · 错误里带 hint 说明怎么改成自己手机上的值 ## 实测(模拟器上没装微信/支付宝,正好测失败路径) · 列出 13 个预设,`installed` 标记正确 · 用关键词找预设:`微信聊天` → 微信·聊天列表;`朋友圈`;`菜鸟` → 支付宝·菜鸟裹裹; `支付宝扫一扫`;`抖音` —— 全都能找到对的 · 播不用装 App 的路径:只给包名打开 → `how=launcher act=com.android.launcher3.Launcher` ✓ · **失败路径**:错误是 `「微信 · 朋友圈」的所有打开方式都没成功;试过:uri()=没装这个 App,uri()=没装…` —— 说清了试过哪些、为什么,而不是笼统的"打不开" ✓ · 不存在的预设 → 列出可用的 id ✓ ## 顺带修的 · `apps` 工具原来没把 `how` / `activity` 透传给模型 —— 这两个字段正是 排查"为什么没进到我要的页面"的关键,丢了就只能看到一句"已打开" · 直拉和退回**都失败**时,错误里原来只说直拉那个原因,会误导 (让人以为是 activity 名字写错,其实退回主界面也失败了 —— 后者更严重) · Kotlin 可见性坑连踩两次:`run()` 的参数类型不能是 private,改成 internal 还是不行(public 函数不能暴露 internal 类型),最后用默认 public。 报错是 `Function 'public' exposes its 'private-in-class' return type`。 · `AppShortcuts.all()` 第一版用 `@Volatile var appCtx: Context?` 存上下文, 编译期就是 `Context?`,每次用都要解包、还容易忘了赋值。 改成**传参**,编译期就保证有。 --- android/app/build.gradle.kts | 4 +- .../java/com/doubao/lynxclone/AppShortcuts.kt | 261 ++++++++++++++++++ .../java/com/doubao/lynxclone/NativeBridge.kt | 63 ++++- .../java/com/doubao/lynxclone/PhoneOps.kt | 63 +++++ scripts/probe-app-shortcuts.py | 128 +++++++++ tools/.shipped-hashes.json | 4 +- tools/apps.py | 91 +++++- 7 files changed, 600 insertions(+), 14 deletions(-) create mode 100644 android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt create mode 100644 scripts/probe-app-shortcuts.py diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index bb19584..7c6da2c 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 242 - versionName = "2.0.42" + versionCode = 243 + versionName = "2.0.43" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt b/android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt new file mode 100644 index 0000000..52d4d18 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/AppShortcuts.kt @@ -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, + val shots: List, + ) + + private fun p(id: String, label: String, kw: List, vararg shots: Shot) = + Preset(id, label, kw, shots.toList()) + + // ------------------------------------------------------------------ // + // 预设表 + // + // ★ 加新预设只要往这个列表里塞一条 —— 工具说明、列表接口都是从这里生成的, + // 不存在"两边不一致"的问题(这个仓库里抄两份的坑踩过好几次)。 + // ------------------------------------------------------------------ // + + private val PRESETS: List = 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> = 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 = 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() + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt index d958540..7b0c435 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt @@ -123,6 +123,32 @@ class NativeBridge(private val activity: Activity) { } "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, @@ -457,10 +483,43 @@ class NativeBridge(private val activity: Activity) { // 已经知道包名和 Activity(从上一步 app_list 拿到的)就直接开,省一次全表扫描 val pkg = req.optString("package").trim() val cls = req.optString("activity").trim() - if (pkg.isNotEmpty() && cls.isNotEmpty()) { - val ok = PhoneOps.launchApp(activity, pkg, cls) + 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 失败(系统拒绝了,可能被停用)") } diff --git a/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt b/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt index f949f76..a24d021 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt @@ -190,6 +190,69 @@ object PhoneOps { 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 + } + /* ==================================================================== */ /* 三、音量 */ /* ==================================================================== */ diff --git a/scripts/probe-app-shortcuts.py b/scripts/probe-app-shortcuts.py new file mode 100644 index 0000000..78fa622 --- /dev/null +++ b/scripts/probe-app-shortcuts.py @@ -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("✅ 全部通过") diff --git a/tools/.shipped-hashes.json b/tools/.shipped-hashes.json index e580f98..0aef210 100644 --- a/tools/.shipped-hashes.json +++ b/tools/.shipped-hashes.json @@ -50,7 +50,9 @@ "f133c98b6325f3ac" ], "apps.py": [ - "7215ae7bc60f6f83" + "7215ae7bc60f6f83", + "4dcbb22a4b57607e", + "ea150707c2aca7f5" ], "notifications.py": [ "3e8ba8ae55b80019", diff --git a/tools/apps.py b/tools/apps.py index 76406ab..fcf5ba2 100644 --- a/tools/apps.py +++ b/tools/apps.py @@ -28,13 +28,24 @@ from _ui_bridge import call_device # noqa: E402 TOOL = { "name": "apps", "description": ( - "打开手机上的 App,或列出装了哪些 App。" - "\n\n用法:" - "\n· action=open(默认)—— 打开一个 App。传 name(名字,模糊匹配即可," - "比如「微信」「抖音」);或者传 package + activity(更准,从上一步 find 拿到的)。" + "打开手机上的 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\n★ 用户说「打开微信聊天」「开一下支付宝菜鸟」这种**带目的地**的要求时," + "\n 优先用 action=shortcut —— 它直达那个页面,比只打开 App 主界面更省事。" + "\n★ 预设打不开时会自动退回打开 App 主界面,所以最差情况也是「App 开了」。" + "\n 返回里 how 会告诉你是哪一层成功的(uri=深链 / activity=直达页面 / main=主界面)。" + "\n★ 深链和 Activity 名字**会随 App 版本变**。如果某个预设失效了," + "\n 可以让用户改 tools/apps.py 里的候选值(文件里有说明)。" "\n★ 打开 App 会让它**跑到前台盖住当前画面**,所以只在用户明确要求时才用。" ), "parameters": { @@ -42,12 +53,16 @@ TOOL = { "properties": { "action": { "type": "string", - "enum": ["open", "find", "list"], + "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 用"}, + "activity": {"type": "string", "description": "Activity 全名,配合 package 用;给包名不给它也能开"}, "query": {"type": "string", "description": "action=list 时的过滤词"}, }, }, @@ -57,6 +72,52 @@ TOOL = { 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"): @@ -101,12 +162,24 @@ def run(args: dict) -> dict: hint = res.get("hint") or "" raise RuntimeError(f"{res['error']}。{hint}".strip()) - return { + out = { "opened": True, "app": res.get("label") or payload["name"] or payload["package"], "package": res.get("package") or payload["package"], - "note": "App 已经切到前台了。", } + # ★ 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__":