Files
doubao-clone/scripts/probe-phone-ops.py
doubao 5e95e17c3e 笔记用户可查看 + 三个操作手机的工具(通知/开App/音量)(v2.0.41)
用户三条需求:
  ① "notes 用户要能查看"
  ② "加个读取手机通知的工具"
  ③ "打开手机 app 和调整手机音量的工具"

## ① notes 用户能查看了

查下去发现不只是"没界面",还有两个真问题:

**问题一:笔记写到了用户看不到的地方。**
notes.py 自己算路径 `工具文件/../data/notes` —— 在安卓上落到
**App 的外部私有目录**(`/storage/emulated/0/Android/data/<包名>/files/data/notes`)。
那地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
而且**卸载 App 就一起删了**。

**问题二:笔记只有 AI 能读写。**
AI 说"我记下来了",用户没有任何办法确认它记了什么、记错没有、删掉记错的。
这类"AI 替你做事但你无法查看"的功能,用户不会信任。

修法:
 · 路径改用内核的 `<数据目录>/notes`(和 conversations / screens 放一起)
 · **自动迁移老位置的笔记**(只搬一次,搬完留 `.migrated` 标记)——
   不搬的话用户以前记的笔记就"不见了",这类"改路径把用户数据弄丢"最不该发生
 · 迁移放在 `store._notes_dir()` 里,**任何一次读笔记都会先保证迁移过**。
   第一版只在 notes 工具被调用时才迁移,于是用户装完新版**先打开笔记页**
   会看到空列表 —— 以为笔记全丢了(实测踩到)
 · 新增 `/api/notes` 列表 / `GET /api/notes/<file>` 读 / `DELETE` 删
 · 界面:抽屉 →「笔记」→ 列表(标题 + 预览 + 时间)→ 点开看全文(markdown 渲染)、可复制、可删

## ② 读手机通知

★ Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户手动去
「设置 → 通知 → 通知使用权」勾上。所以加了个 `NotificationListenerService`。

几个刻意的决定:
 · **只在内存里留最近 200 条,不落盘**。通知里有验证码、银行短信、私信 ——
   是整个 App 最隐私的一类数据。写磁盘意味着卸载前一直躺着,也可能被别的工具读到。
 · **已划掉的也留着**(标 `gone:true`)。用户问"刚才那条验证码呢"时它早被划走了,
   删了就直接查不到。
 · **权限没开时返回错误,不是空列表**。返回空列表模型会说"你没有通知"——
   那是**错的**(明明有几条,只是我们读不到),用户会被误导。错误里带上
   "怎么开"的完整步骤,模型照着念就行。
 · `action=open_settings` 直接跳那个设置页(安卓不给申请弹窗,只能跳)。

## ③ 打开 App + 调音量

**打开 App**:两段式(`find` 找 / `open` 开),`open` 也支持只传名字。
 · Manifest 里加了 `<queries>` LAUNCHER intent —— Android 11+ 不声明这条,
   `queryIntentActivities` 只返回空列表,表现是"装了 8 个 App 一个都找不到"
 · 匹配顺序:包名完全相同 → 名字完全相同 → 前缀 → 包含 → 包名包含
 · 找不到时错误里**带上相近的名字**,模型能自己改一个再试

**调音量**:六种流分开(music/ring/alarm/call/system/notification)。
 · `mode=set` 的 value 是**百分比**,工具侧先读 max 再换算成档位 ——
   安卓原始值按流的 max 算(媒体通常 15 档、铃声 7 档),
   直接把 50 当原始值会撞上限
 · 改完**必须回读确认**:勿扰模式开着时系统会**拒绝**改铃声/通知音量而且**不报错**
   (静默失败)。不回读的话模型会告诉用户"调好了"而实际没变 —— 比说"没调成"糟得多

## 实测(Android 14 x86_64)

音量:读出 6 个流;set 40% → 实际 40%(换算对了);up 6→7;mute→0;unmute→7 ✓
App:列出 8 个;找到「设置」;不存在的名字 → 如实报错 + 指路 ✓
通知:`cmd notification post` 发一条 → 内核读到
      `{app:"Shell", title:"测试标题", text:"…12345", ago:"刚刚", gone:false}` ✓
笔记:老位置的文件被搬到新位置,界面显示 1 条、内容正确 ✓

## 顺带修的

 · `apps` 工具的"找不到"提示里写的是 `action=app_list` —— **那个 action 不存在**
   (实际叫 `list`),模型照着调会失败。改成 `action=list`。
 · 写测试脚本时踩到:工具抛错时响应是**顶层** `{ok:false, error}`,不是
   `{result:{error}}`。第一版脚本只看了 result,于是三条断言全红,
   看起来像"错误信息没给",其实给得挺全。测试脚本必须按真实响应形状取值。
2026-10-15 15:38:00 +08:00

154 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""测三个"操作手机"的工具:读通知 / 开 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("✅ 全部通过")