笔记用户可查看 + 三个操作手机的工具(通知/开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

@@ -0,0 +1,161 @@
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
Log.i(TAG, "通知使用权已连接")
}
override fun onListenerDisconnected() {
super.onListenerDisconnected()
connected = false
Log.i(TAG, "通知使用权已断开")
}
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) {
}
}
private 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,
)
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>()
/** 通知使用权连上了没有 */
@Volatile
var connected: Boolean = false
/**
* 取最近的通知。
*
* @param limit 最多几条
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
* @param query 关键词过滤(标题/正文/App 名里含它)
*/
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
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()
}
}

View File

@@ -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,30 @@ 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)
}
"apps" -> appsList(req)
"app_launch" -> appLaunch(req)
"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) {
@@ -378,6 +410,112 @@ 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() && cls.isNotEmpty()) {
val ok = PhoneOps.launchApp(activity, pkg, cls)
return if (ok) {
JSONObject().put("ok", true).put("package", pkg)
} 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

View File

@@ -0,0 +1,220 @@
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)
/* ==================================================================== */
/* 二、打开 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
}
/* ==================================================================== */
/* 三、音量 */
/* ==================================================================== */
/**
* 音量流。
*
* ★ 用**字符串名**而不是整数常量:模型要写 `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
}
}

View File

@@ -141,6 +141,22 @@ fun AppRoot(
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
* 他最想看的是网页,所以网页在最上面。
*/
// 「笔记」—— 用户要能查看 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(
@@ -243,6 +259,11 @@ private fun DrawerOverlay(vm: AppViewModel) {
vm.drawerOpen = false
vm.openAiScreenList()
}
// 「笔记」—— 用户要能查看 AI 替他记了什么
DrawerItem(Icons.Filled.EditNote, "笔记") {
vm.drawerOpen = false
vm.openNotes()
}
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
vm.screen = Screen.Skills; vm.drawerOpen = false
}

View File

@@ -91,6 +91,70 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
var aiScreenListOpen by mutableStateOf(false)
private set
/* -------------------- 笔记(用户要能查看)-------------------- */
/**
* 笔记列表。
*
* ★ 用户的原话:"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

View 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)
}