用户要求:"打开应用工具支持打开活动,并预设几个比如微信对话,支付宝菜鸟"
## 打开"活动"(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?`,每次用都要解包、还容易忘了赋值。
改成**传参**,编译期就保证有。
187 lines
8.6 KiB
Python
187 lines
8.6 KiB
Python
"""打开手机上的 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)
|