笔记用户可查看 + 三个操作手机的工具(通知/开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,于是三条断言全红,
   看起来像"错误信息没给",其实给得挺全。测试脚本必须按真实响应形状取值。
This commit is contained in:
doubao
2026-10-15 15:38:00 +08:00
parent b1dd740b0d
commit 5e95e17c3e
20 changed files with 1966 additions and 19 deletions

View File

@@ -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: