Compare commits
129 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e0ae716e98 | |||
| ca65ec36c8 | |||
| 62a613a1e2 | |||
| dd66541446 | |||
| 3a0869eab8 | |||
| 849e2e5beb | |||
| aa5b0226f9 | |||
| 155f95c982 | |||
| 7ccdc4516a | |||
| 8acfc0ed0d | |||
| 693e75dad2 | |||
| 91675f21fb | |||
| 91a4ba2ab4 | |||
| 5a65320a5d | |||
| 946bf8bc55 | |||
| 050a3b2385 | |||
| ab8296901d | |||
| c09df1d0a2 | |||
| 31c62fafc2 | |||
| 7498810c70 | |||
| 57a9ff4ea1 | |||
| ab063d0674 | |||
| 3d5c02e7a9 | |||
| 4ed6c6a4ee | |||
| f665b83b34 | |||
| 1c07e37932 | |||
| daccc3fd10 | |||
| e62dd7b87b | |||
| 8ccf009958 | |||
| ff1c2e3400 | |||
| bea9debe15 | |||
| 8ac14bdaa2 | |||
| f84c68762b | |||
| 5878ec7a7f | |||
| 77b4f3d74f | |||
| fbfd50eb56 | |||
| 5a7ed44226 | |||
| 0b80ca4830 | |||
| c1da6486a4 | |||
| f877bd6ee8 | |||
| c9e0d689c0 | |||
| cceffd77ec | |||
| 2142e119c6 | |||
| 4ad2ea8e90 | |||
| bbc32dcb46 | |||
| 778c19b088 | |||
| 7e7aea0f48 | |||
| 4effa968ac | |||
| 76d6445ed6 | |||
| b55ce63c6e | |||
| 28a2ede206 | |||
| 1a9229aa75 | |||
| e11e178810 | |||
| 6bcb5d72f8 | |||
| b693f22f61 | |||
| 6e5ea9d3b6 | |||
| 08eecb9e0a | |||
| 182c0005a4 | |||
| 9ff60e684b | |||
| f8ab075f5e | |||
| 56b15f1d19 | |||
| d3a327da26 | |||
| 4b94e3eef3 | |||
| d557dbd2e3 | |||
| a6840f383e | |||
| 9024810558 | |||
| ef42aa70ca | |||
| a87eca329a | |||
| fd72ad06a1 | |||
| 2a25cf623f | |||
| c7fed95650 | |||
| d82c3d3176 | |||
| 4850ea12af | |||
| 2c259d4270 | |||
| 39813985b5 | |||
|
|
f330af963a | ||
|
|
74c87686ef | ||
|
|
5e95e17c3e | ||
|
|
b1dd740b0d | ||
|
|
103c939051 | ||
|
|
885a1f0123 | ||
|
|
ba429e67cd | ||
|
|
5f138be5fa | ||
|
|
f7454c0b60 | ||
|
|
0ad999b6e6 | ||
|
|
e18970c85f | ||
|
|
0fe43d67df | ||
|
|
f789803eae | ||
|
|
52680b9eb7 | ||
|
|
6197b726a5 | ||
|
|
cead531983 | ||
|
|
2601e9ae43 | ||
|
|
8123fff9ca | ||
|
|
c25e94583a | ||
|
|
ecb6e6f924 | ||
|
|
028d67c3ec | ||
| 982c64939b | |||
| b39c23b4dd | |||
| 82fbbe8887 | |||
| 9dc26ed427 | |||
| 85238013a1 | |||
| 97793231c1 | |||
| 59e12a7261 | |||
| dd7bce574e | |||
| 71703c173c | |||
| ed97ec6c63 | |||
| 0f618ba2b0 | |||
| 04f00d1114 | |||
| 754ff80b2b | |||
| 19fe7a6af6 | |||
| 659a212465 | |||
| 626ac89ac8 | |||
| df909f3dd6 | |||
| 5c157c3044 | |||
| 7705a3eb7e | |||
| 52feef35cd | |||
| d88a7aa8aa | |||
| fb105377a9 | |||
| a536b7ba27 | |||
| 519250b109 | |||
| cfdf10a035 | |||
| 7f3dbb4002 | |||
| bec25b71ac | |||
| 19a03724bb | |||
| 5ed71f4f1b | |||
| 3266afd1a4 | |||
| bc6a172888 | |||
| 4883cedfeb | |||
| c8c3dfd59c |
103
.gitignore
vendored
103
.gitignore
vendored
@@ -1,89 +1,22 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 依赖(几百 MB,clone 后 `npm run install:all` 自己装)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
node_modules/
|
||||
.npm-cache/
|
||||
desktop/node_modules/
|
||||
desktop/dist-staging/
|
||||
# 仓库根现在只放说明和两个目录;工程在 豆鲍/(它有自己的 .gitignore)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 构建产物
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
dist-android/
|
||||
dist-win/
|
||||
app/dist/
|
||||
web/dist/
|
||||
android/app/build/
|
||||
android/build/
|
||||
android/.gradle/
|
||||
android/local.properties
|
||||
build/
|
||||
.gradle/
|
||||
*.tsbuildinfo
|
||||
*.apk
|
||||
*.aab
|
||||
*.exe
|
||||
*_boot.zip
|
||||
# 编辑器工作区:放导出的包、手改的 JSON、批量脚本 —— 都是本地活儿,不进版本库。
|
||||
# ★ README.md 不忽略(那是这个文件夹的说明,要提交)。
|
||||
豆鲍编辑器/*.json
|
||||
豆鲍编辑器/*.zip
|
||||
豆鲍编辑器/*.db
|
||||
豆鲍编辑器/*.sqlite
|
||||
豆鲍编辑器/备份/
|
||||
豆鲍编辑器/tmp/
|
||||
|
||||
# 打包中间产物(electron 二进制与暂存目录都很大)
|
||||
android/app/src/main/assets/main.lynx.bundle
|
||||
.rasterize-*
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 密钥 / 个人配置 —— 这些**绝不能**提交
|
||||
#
|
||||
# settings.json 里有 apiKey 字段(现在是占位值,但随时可能填真 Key);
|
||||
# mcp.servers.json 里有本机绝对路径。
|
||||
# 示例文件(*.example.*)是给别人做模板用的,要提交。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
server/.env
|
||||
server/.env.*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.local
|
||||
server/config/settings.json
|
||||
tools/mcp.servers.json
|
||||
app/config/settings.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 运行时数据
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
server/data/
|
||||
data/
|
||||
phone-verify-result.json
|
||||
*.log
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Termux 的两个 bootstrap(各 28 MB,共 56 MB)
|
||||
#
|
||||
# 这两个 .so 是**手动**从 Termux 的 APK 里取出来放进 jniLibs 的,
|
||||
# 仓库里没有脚本能重新生成(fetch-termux.mjs 只把 APK 下到缓存)。
|
||||
# 56 MB 的二进制不适合跟着代码走,所以单独排除;
|
||||
# 要构建 APK 见 README「4.2 APK 里到底装了什么」。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
android/app/src/main/jniLibs/*/libtermux-bootstrap.so
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Python
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 编辑器 / 系统
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
*.swp
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
# 系统 / 编辑器垃圾
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.log
|
||||
*.tmp
|
||||
__pycache__/
|
||||
|
||||
# 调试时生成的临时探针
|
||||
.tmp/
|
||||
.tmp-*
|
||||
# 本地工作产物:任何以 .tmp 开头的临时目录(探针数据、临时脚本等)+
|
||||
# Windows 文件权限诊断报告
|
||||
.tmp-*/
|
||||
.acl-recovery/
|
||||
|
||||
168
AGENTS.md
168
AGENTS.md
@@ -1,147 +1,51 @@
|
||||
# 项目约定
|
||||
# AGENTS.md(入口)
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
**项目约定在 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)** ——
|
||||
代码托管(两个 remote、推送注意事项)和界面约定(少用弹窗、能开界面就开界面、
|
||||
全屏界面骨架、几个反复踩的坑)都在那份里。
|
||||
|
||||
---
|
||||
请以那份为准,本文只做入口。
|
||||
|
||||
# 代码托管
|
||||
## 这个仓库的目录
|
||||
|
||||
## 两个 remote,同一个仓库
|
||||
```
|
||||
豆鲍/ 完整工程(android / server / web / desktop / scripts / docs …)
|
||||
豆鲍编辑器/ 独立「豆鲍编辑器」:桌面 app + Windows exe + APK,
|
||||
给豆包世界状态等系统写 Python 脚本用(见它的 README)
|
||||
.git/
|
||||
```
|
||||
|
||||
| remote | 地址 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `local` | `http://192.168.100.103:8080/l/doubao-clone.git` | **在家/局域网,优先用这个**(快) |
|
||||
| `origin` | `https://git.xnhw.cc/l/doubao-clone.git` | 不在局域网时 |
|
||||
|
||||
两个地址指向**同一台服务器**(`git.xnhw.cc` 在外网解析到 `64.49.47.22`,
|
||||
局域网里就是 `192.168.100.103:8080`)。推哪个都行,别同时推两遍。
|
||||
|
||||
服务是 **Noir's Git**(Gitea 系)。
|
||||
|
||||
## 推送
|
||||
**所有工程操作都从 `豆鲍/` 里执行**:
|
||||
|
||||
```bash
|
||||
git push local main # 日常
|
||||
git push local --tags # 标签
|
||||
cd 豆鲍
|
||||
python scripts/probe-agent-system.py # 探针
|
||||
node scripts/build-apk.mjs # 构建 APK
|
||||
```
|
||||
|
||||
`local` 的凭据存在 `.git/config` 的 remote URL 里(`.git` 不属于仓库内容,
|
||||
不会被提交)—— 所以不用每次输密码。
|
||||
## 三条最容易忘的
|
||||
|
||||
## 一个坑:push 报 401 时会**假装卡住**
|
||||
1. **改内核必须跑 `py_compile`** —— Gradle 不编译 Python,语法错误要等手机上
|
||||
启动内核才炸,那时整个 App 不可用。
|
||||
2. **改了就要重新构建再验证** —— 这个仓库里"改了没生效"绝大多数是因为
|
||||
改动晚于上一次构建,而不是代码错。
|
||||
3. **探针必须走生产同一条调用路径**(`handle()` / `execute_tool`),
|
||||
不能直接调内部函数 —— 探针能绕过的那一层,就是下次会出问题的那一层。
|
||||
4. **每次功能改动先递增版本号**(两个产品各管各的):
|
||||
- **豆鲍 App**(本仓库主体):`python scripts/bump-version.py`(版本唯一来源
|
||||
`android/app/build.gradle.kts` 的 `versionCode` / `versionName`),再
|
||||
`node scripts/build-apk.mjs`。构建脚本会打印版本,版本没变会提醒你还没 bump。
|
||||
- **豆鲍编辑器**:`python 豆鲍编辑器/scripts/bump_version.py`(版本唯一来源
|
||||
`豆鲍编辑器/VERSION`),再构建;编辑器构建脚本会校验版本一致。
|
||||
|
||||
这个服务器上 `receive-pack`(推送)要认证,而 `upload-pack`(拉取)不用。
|
||||
凭据不对时 git 会**挂在等密码输入上,一行输出都没有** ——
|
||||
看起来像网络卡死,其实是在等 stdin。
|
||||
## 安卓模拟器(要装 App / 截图验证时看这份)
|
||||
|
||||
所以:
|
||||
- 脚本里推之前先设 `GIT_TERMINAL_PROMPT=0`(让它直接失败而不是等)
|
||||
- 或者直接确认 remote URL 里有凭据
|
||||
|
||||
排查顺序:
|
||||
```bash
|
||||
git ls-remote <url> # GET 通不通(不需要认证也能通)
|
||||
curl -i "<url>/info/refs?service=git-receive-pack" # 401 就是认证问题
|
||||
```powershell
|
||||
cd 豆鲍
|
||||
powershell -ExecutionPolicy Bypass -File scripts\emulator-up.ps1 # 拉起 doubao14(emulator-5558)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 界面约定
|
||||
|
||||
适用于本仓库的 Android / Compose 界面。
|
||||
|
||||
## 少用弹窗,能开界面就开界面
|
||||
|
||||
用户明确要求:**尽量减少弹窗那种,能加界面就加界面。**
|
||||
|
||||
理由(也是判断标准):
|
||||
|
||||
- **弹窗装不下东西**。一屏对话框的高度大概只够三四行内容,一旦要放的
|
||||
东西超过这个量(列表、代码框、多组配置),用户就得在弹窗里滚动 ——
|
||||
那还不如直接开一屏。
|
||||
- **弹窗会互相压**。弹窗里再弹一个(比如"变量管理"里点"新建",
|
||||
或者"节点管理"里点"编辑")在手机上是灾难:返回键的行为变得说不清,
|
||||
用户也不知道自己在第几层。
|
||||
- **弹窗盖住上下文**。这个 App 的会议画布本身就是要看着的,
|
||||
一个盖住半屏的对话框让人没法一边看图一边改配置。
|
||||
|
||||
### 该怎么做
|
||||
|
||||
| 内容量 | 用什么 |
|
||||
|---|---|
|
||||
| 一次确认("要删除吗") | `AlertDialog` ✓ 弹窗合适 |
|
||||
| 纯菜单(两三个入口,点完就走) | 底部弹层或 `AlertDialog` ✓ |
|
||||
| 列表 / 多组配置 / 代码 / 任何要滚动的 | **独立全屏界面**,顶栏 `← 返回` + 标题 + 右侧动作 |
|
||||
|
||||
### 全屏界面的骨架
|
||||
|
||||
统一用同一套顶栏,别各写各的(不然返回的位置、标题的大小、
|
||||
右边按钮的样式会到处不一样):
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
```
|
||||
|
||||
参考实现:`NodeBlockEditorScreen`(`NodeBlockEditor.kt`)的顶栏。
|
||||
|
||||
### 返回键
|
||||
|
||||
全屏界面要能被系统返回键关掉(用状态变量控制显示时,
|
||||
记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 ——
|
||||
比弹窗还糟。
|
||||
|
||||
## 全屏化的进度
|
||||
|
||||
**已经改完全屏的**:
|
||||
- ✅ 节点管理 `NodeManagerScreen`
|
||||
- ✅ 节点编辑 `NodeCodeScreen`(代码框占满剩余高度)
|
||||
- ✅ 积木编辑器 `NodeBlockEditorScreen`
|
||||
|
||||
**还欠着的**:
|
||||
- [ ] 变量管理 `VarManagerDialog` → 全屏
|
||||
- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层
|
||||
- [ ] 导入会议 `ImportDialog` → 全屏
|
||||
- [ ] 节点配置 `NodeConfigDialog` → 全屏(字段很多)
|
||||
|
||||
**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。
|
||||
|
||||
### 改全屏时踩的坑:界面的 return 顺序
|
||||
|
||||
全屏界面是用状态变量 + `return@Composable` 实现的,于是**谁在上面谁优先**:
|
||||
|
||||
```kotlin
|
||||
blockEdit?.let { ...; return@MeetingEditorScreen } // 积木编辑器
|
||||
if (showNodeMgr) { ...; return@MeetingEditorScreen } // 节点管理
|
||||
if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
```
|
||||
|
||||
在下面的界面要显示时,**必须先把它上面的那个状态关掉** ——
|
||||
否则上面的先 return,下面的永远轮不到渲染。
|
||||
表现是"点了没反应",其实状态全对了,只是没机会画(这个 bug 真出现过)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」),
|
||||
事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走
|
||||
`applyMeetingEvent`。
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
- **代码框不能软换行**。` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
就是语法。这个 Compose 版本(BOM 2024.09.03)的 `BasicTextField`
|
||||
经典重载选不中,所以用"把输入框塞进足够宽的横向滚动容器"来达到同样效果。
|
||||
- **代码框要有高度上限**。只写 `heightIn(min=...)` 的话,文件一长框就长到
|
||||
屏幕外,把底下的补全条顶出去,用户够不着。
|
||||
- **改了没生效就先怀疑工具**。PowerShell 的 `String.Replace` **匹配失败不报错**;
|
||||
按行号剪贴会算错下标(甚至把整个文件追加一遍);
|
||||
`git checkout -- <文件>` 会还原**这一轮所有未提交的改动**。
|
||||
改完立刻 grep 确认,动手前先断言下标有效。
|
||||
- **莫名其妙的"未解析引用"先数括号**。漏一个 `}` 会让后面所有顶层声明
|
||||
全部报未解析,错误信息看着完全不像是括号问题(报的是 `PrimaryButton`
|
||||
找不到这种)。
|
||||
坑和完整操作(装 APK、截图、点按、抓内核日志、连设备内核 API)都在
|
||||
[`豆鲍/docs/安卓模拟器-操作手册.md`](豆鲍/docs/安卓模拟器-操作手册.md)。
|
||||
|
||||
详细约定见 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)。
|
||||
|
||||
649
README.md
649
README.md
@@ -1,638 +1,25 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆鲍 · 豆包 App 复刻
|
||||
|
||||
[](LICENSE)
|
||||
工程在 **[`豆鲍/`](豆鲍/)**,说明看 **[`豆鲍/README.md`](豆鲍/README.md)**。
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
```
|
||||
豆鲍/ 完整工程(Android 原生 + Python 内核 + Node 服务端 + 网页 + 桌面版)
|
||||
豆鲍编辑器/ 编辑器工作区(放导出的包、手改的 JSON、批量改数据的脚本)
|
||||
```
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||
> 「豆包」是字节跳动的商标。
|
||||
|
||||
| 平台 | 产物 | 界面 | 内核 |
|
||||
|---|---|---|---|
|
||||
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | Lynx(旧版,仍在) | Node(随 Electron 启动) |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | Lynx(旧版,仍在) | Node |
|
||||
|
||||
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||
|
||||
| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
|
||||
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
|
||||
|
||||
---
|
||||
|
||||
## 1. 快速开始
|
||||
|
||||
### 浏览器 / 桌面版
|
||||
## 最快验证它能跑
|
||||
|
||||
```bash
|
||||
npm run install:all # app(Lynx 客户端)+ server(Node 内核)
|
||||
npm run build
|
||||
npm start # 打开 http://127.0.0.1:5199/
|
||||
cd 豆鲍
|
||||
|
||||
# 1) 探针:不需要设备、不需要网络,在电脑上把内核逻辑逐条断言
|
||||
python scripts/probe-agent-system.py
|
||||
python scripts/probe-group-chat.py
|
||||
# … 一共八个,见 README
|
||||
|
||||
# 2) 构建 APK
|
||||
node scripts/build-apk.mjs
|
||||
# → dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**exe 必须放纯英文路径**,见 §7.1)。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
```bash
|
||||
npm run apk # 产出 dist-android/doubao-debug.apk(约 88 MB)
|
||||
adb install -r dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
装完打开 App → 抽屉 →「设置」→ 选提供商、填 API Key → 保存。
|
||||
第一次启动会解压内置 Termux(约 95 MB、3226 个文件),**约 10~30 秒**,界面上有进度。
|
||||
|
||||
---
|
||||
|
||||
## 2. 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Android App(原生 Kotlin + Compose,主力) │
|
||||
│ │
|
||||
│ ui/ ChatScreen Drawer Settings Skills Agents Profile │
|
||||
│ ModelPickerSheet TerminalScreen ← 7 个页面 │
|
||||
│ │ │
|
||||
│ │ KernelClient(OkHttp + 轮询流式) │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ Python 内核(Chaquopy 内嵌 CPython 3.13) │ │
|
||||
│ │ android/kernel/ —— 监听 127.0.0.1:5199 │ │
|
||||
│ │ · providers 10 家兼容厂商 + 思考强度映射 │ │
|
||||
│ │ · agent_loop 多轮工具循环 │ │
|
||||
│ │ · tools import 加载 tools/*.py │ │
|
||||
│ │ · mcp_client 手写 JSON-RPC(http/stdio/inproc)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ 进程内直调(Chaquopy 桥) │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 内置 Termux($PREFIX = /data/user/0/<pkg>/files/usr) │
|
||||
│ │ · bash 5.x / apt / pkg / 388 个命令 │ │
|
||||
│ │ · libtermux.so → forkpty(真 tty) │ │
|
||||
│ │ · TerminalView → ANSI 渲染(Termux 源码 vendored)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 设备能力 NativeBridge:定位 / 陀螺仪 / 加速度计 │ │
|
||||
│ │ 磁性 / 光线 / 气压 / 电量 / 剪贴板 / 选文件 │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
电脑上的 Web/exe 版仍然用 **Node 内核 + Lynx 界面**。两个内核**接口逐字段一致**,
|
||||
所以安卓端把界面换成 Compose 之后,后端一行都不用改。
|
||||
|
||||
怎么做到一致的:`android/kernel/` 是照 `server/src/` 的契约重写的纯标准库实现
|
||||
(`http.server` + `urllib` + 手写 JSON-RPC),不依赖任何第三方包 —— 因为安卓上装不进来。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能
|
||||
|
||||
### 3.1 智能体
|
||||
抽屉 →「智能体」。每个智能体有独立头像(9 种)和系统提示词,聊天时覆盖全局提示词,顶部显示当前智能体。
|
||||
内置 4 个(豆包 / 代码搭子 / 文案师 / 数据分析),可自建。存 `<数据目录>/agents.json`。
|
||||
|
||||
### 3.2 模型、提供商与思考强度(抽屉里的「模型」那一栏)
|
||||
|
||||
**支持 10 家,而且它们全都是同一个协议**(`POST {baseUrl}/chat/completions`),
|
||||
所以内核里只有一份实现,差别只在三件事:地址、模型名、**思考强度用哪个字段传**。
|
||||
|
||||
| key | 提供商 | Base URL | 思考强度怎么传 |
|
||||
|---|---|---|---|
|
||||
| `ark` | 火山方舟(豆包) | `https://ark.cn-beijing.volces.com/api/v3` | 顶层 `thinking: {type}` |
|
||||
| `openai` | OpenAI 官方 | `https://api.openai.com/v1` | `reasoning_effort` |
|
||||
| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | 不发(模型自己决定) |
|
||||
| `kimi` | Kimi(月之暗面) | `https://api.moonshot.cn/v1` | 不发 |
|
||||
| `zhipu` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | 顶层 `thinking: {type}` |
|
||||
| `dashscope` | 通义千问(阿里云) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | 不发 |
|
||||
| `siliconflow` | 硅基流动 | `https://api.siliconflow.cn/v1` | 不发 |
|
||||
| `openrouter` | OpenRouter(聚合) | `https://openrouter.ai/api/v1` | `reasoning_effort` |
|
||||
| `ollama` | 本地 Ollama | `http://127.0.0.1:11434/v1` | 不发 |
|
||||
| `custom` | 自定义兼容网关 | 自己填 | 不发 |
|
||||
|
||||
**为什么不是"非 ark 即 openai"**:这个判断以前写死成两家名字。
|
||||
现在厂商多了,各自认的字段不一样,而**给不认 `reasoning_effort` 的服务发这个字段,有些会直接 400**。
|
||||
所以改成每个预设自己声明 `thinkingMode`(`ark` / `effort` / `none`),**认不出来的一律 `none`**(什么都不发,最安全)。
|
||||
|
||||
| 强度 | `thinkingMode: ark` | `thinkingMode: effort` | `thinkingMode: none` |
|
||||
|---|---|---|---|
|
||||
| 快速 | `thinking={type:"disabled"}` | 推理模型 `reasoning_effort=minimal` | 不发 |
|
||||
| 自动 | 不传,交给模型 | 不传 | 不传 |
|
||||
| 低 / 中 / 高 | `thinking={type:"enabled"}` | `reasoning_effort=low/medium/high` | 不传 |
|
||||
|
||||
另外:`thinkingMode: effort` 且模型名匹配 `o1|o3|o4|gpt-5|gpt-6` 时,
|
||||
会自动剥掉 `temperature`/`top_p` 等采样参数,并把 `max_tokens` 换成 `max_completion_tokens`
|
||||
(这些模型"传默认值"也算传,会 400)。
|
||||
|
||||
两份内核(Node / Python)在这件事上**逐字段对拍 50/50 一致**(10 家 × 5 档),
|
||||
脚本:`node scripts/parity-thinking.mjs`。
|
||||
|
||||
### 3.3 思考过程怎么显示
|
||||
1. **正文里**:回答上方一个 `✨ 深度思考 ›` 入口,思考中显示跳动小点
|
||||
(这里不再拼思考强度 —— 强度本身就叫"深度思考",拼出来会变成"深度思考 · 深度思考")
|
||||
2. **点开**:底部升起「**思考过程**」弹层(左上角 X),先列这轮调了哪些工具,再是完整思维链
|
||||
3. 思维链**已落库**,刷新/切会话都不丢
|
||||
|
||||
### 3.4 界面:照着豆包抠的,带完整动效
|
||||
|
||||
安卓端是原生 Compose 重写的,视觉对着豆包真机截图一项项抠:
|
||||
|
||||
- **纯白底**(不是浅灰)——豆包的层级靠"白底 + 浅灰卡片"表达,用灰底会一股系统设置味
|
||||
- 顶部三段式:左边 ☰ / ✎,中间「头像 + 智能体名 + ›」(点开就是模型面板),右边 📞 / 🔊
|
||||
- 空会话时:168dp 蓝色圆环大头像 + 灰色问候气泡 + 白底描边快捷胶囊(对话 / AI创作 / 出行用豆包 / 豆包)
|
||||
- 用户气泡:`#2B7BFF` 蓝底、右下角收窄成 4dp(气泡"尾巴")
|
||||
- 助手气泡:`#F2F3F5` 灰底、左下角收窄;下面一排 5 个圆形小按钮(复制/朗读/赞/踩/分享)+ 右侧重新生成
|
||||
- 输入框:52dp 高的大圆角描边胶囊,左边相机、右边麦克风;**有内容时右侧才变成蓝色圆形发送键**
|
||||
- 出错的回复是浅红底 + 红字,不是普通气泡
|
||||
- 设置 / 我的 / 技能 / 智能体各页共用同一套小部件(`ScreenHeader` / `SettingsCard` / `FormField` …),
|
||||
所以在主题层改一次颜色,7 个页面一起变
|
||||
|
||||
动效(都是 Compose 原生动画,没引第三方库):
|
||||
|
||||
| 位置 | 动效 |
|
||||
|---|---|
|
||||
| 抽屉 | 从左滑入 + 遮罩淡入,关闭反向 |
|
||||
| 页面切换 | 淡入 + 轻微横向位移(`AnimatedContent`) |
|
||||
| 消息气泡 | 出现时淡入 + 上移 10dp(`AppearOnce`) |
|
||||
| 思考 / 模型面板 | 从底部升起,收起时降下去 |
|
||||
| "正在输入" | 三个小点依次跳动(`TypingDots`,错开 130ms) |
|
||||
| 按钮 | 按下缩到 0.86~0.94 回弹(`collectIsPressedAsState` + spring) |
|
||||
| 抽屉列表项 | 按下时背景色渐变 |
|
||||
|
||||
> 顺带一个坑:底部面板的**滚动区会吃掉点击**。如果面板顶到状态栏,
|
||||
> "点遮罩关闭"就只剩状态栏那条能点,等于失效。所以面板限高 85%、并且都带明确的 X 按钮。
|
||||
|
||||
### 3.5 设置不会被保存清空(三道防线)
|
||||
|
||||
之前有个真 bug:**一保存设置,整份配置被清空**。根因是首屏 `state` 还在路上时,
|
||||
设置页草稿还是"全空"的,而保存按钮把草稿**全量**下发;`/api/settings` 是浅合并,
|
||||
空字符串就等于把它清掉。现在三道防线:
|
||||
|
||||
1. **界面只发改动过的字段**(`SettingsDraft.changesAgainst`)——没动过的键根本不出现
|
||||
2. **草稿只在服务端设置真的变了时重建**(存一份 `snapshot` 对比),
|
||||
不会再被无关的 state 刷新冲掉正在输入的内容
|
||||
3. **内核拒收空的关键字段**(`provider` / `baseUrl` / `model` / `apiKey` / `nickname` / `thinkingLevel`)——
|
||||
前端再出 bug 也清不掉配置。`systemPrompt` / `toolsDir` 故意不在此列:它们"留空"是合理需求
|
||||
|
||||
验证脚本(都会先正常保存一次验证不掉字段,再按"旧版 bug 的形状"下发一堆空值验证被忽略):
|
||||
|
||||
- `node scripts/probe-settings-wipe.mjs http://127.0.0.1:5199`(电脑 / Node 内核)
|
||||
- `node scripts/device-settings-attack.mjs emulator-5556 5199`(设备 / Python 内核)
|
||||
|
||||
### 3.6 工具
|
||||
|
||||
| 工具 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `shell` | 终端执行命令,带超时与黑名单 | ✅ 优先走内置 Termux |
|
||||
| `python_run` | 执行 Python 代码 / .py 文件,`action=libs` 列可用库 | ✅ 进程内 exec(CPython 3.13.9) |
|
||||
| `device` | **手机能力**:设备信息、定位、传感器、剪贴板 | ✅ 安卓专属 |
|
||||
| `calc` `now` `get_weather` `notes` `web_fetch` | `tools/*.py`,自己写的 | ✅ 同一份代码 |
|
||||
| `mcp__*` | MCP 服务暴露的工具 | ✅ 见 3.8 |
|
||||
|
||||
**`device` 工具**(安卓)实测能力:
|
||||
- `info`:型号/厂商/系统/SDK/ABI/存储/屏幕/电量
|
||||
- `location`:GPS 经纬度(真机实测 `纬度, 经度 ±35m`)
|
||||
- `sensors` / `sensor`:列出并采样(真机 46 个传感器,加速度计 z≈9.7 m/s² 就是重力)
|
||||
- `clipboard_get` / `clipboard_set`
|
||||
- `termux_available` / `termux_run`:走内置 Termux
|
||||
|
||||
### 3.7 自己写工具
|
||||
往工具目录丢一个 `.py`(`_` 开头跳过):
|
||||
|
||||
```python
|
||||
TOOL = {
|
||||
"name": "word_count",
|
||||
"description": "统计一段文字的字数",
|
||||
"parameters": {"type": "object", "properties": {"text": {"type": "string"}},
|
||||
"required": ["text"]},
|
||||
}
|
||||
def run(args): # 同步或 async 都行
|
||||
return {"count": len(args["text"])}
|
||||
```
|
||||
|
||||
工具目录:安卓在 `files/tools/`(可通过设置里的 `toolsDir` 改),电脑在 `tools/`。
|
||||
内置工具在首次启动时会**播种**到可写目录,改坏了删掉重启就恢复。
|
||||
|
||||
> 为什么安卓上要播种、还要把源码 base64 打进 APK:Chaquopy 打的是 `.pyc`,
|
||||
> 运行时 `loader.get_source()` 拿不到源码,所以构建脚本额外生成了 `bundled_tool_sources.py`。
|
||||
|
||||
### 3.8 MCP:三种传输,安卓也能跑
|
||||
抽屉 →「技能·连接器」→「MCP 服务」,图形化和原始 JSON 两个 Tab,保存时校验并自动重连。
|
||||
|
||||
| 传输 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `http` | 标准 Streamable HTTP / SSE | ✅ |
|
||||
| `stdio` | 起一个子进程用管道通信 | ✅ 用内置 Termux 的 python/node |
|
||||
| `inproc` | 同进程内直接调用(自己写的 Python 服务) | ✅ 安卓推荐,最省事 |
|
||||
|
||||
实测:filesystem 服务 14 个工具、memory 9 个工具、自己写的 Python 服务 3 个工具,全部连接并调用成功。
|
||||
|
||||
> 为什么手写 JSON-RPC 而不用官方 `mcp` SDK:它依赖 pydantic v2,Chaquopy 装不进来。
|
||||
|
||||
### 3.9 文件上传 / 权限模式
|
||||
- **上传**:输入框左侧相机/加号 → 选文件 → 上传到内核 → 挂到输入框 → 随消息发送 → 气泡里显示
|
||||
- **权限模式**:`open` 全放行 / `restricted` 只放 `allow` 白名单。限制模式下未授权工具
|
||||
**列都不列出来**,执行时再拦一道
|
||||
|
||||
### 3.10 语音:朗读 + 语音输入
|
||||
|
||||
**引擎放在内核里,音频采集/播放在端上。** 这么分的好处:API Key 只存一份,
|
||||
浏览器 / 安卓 / exe 三端白捡同一个能力,厂商鉴权差异全在一个文件里。
|
||||
|
||||
| | 引擎 | 说明 |
|
||||
|---|---|---|
|
||||
| **朗读** | `system` | 设备自带 TTS(安卓 `TextToSpeech`)。**不联网、不要 Key**,默认就是它 |
|
||||
| | `volc` | **火山语音合成 —— 豆包同款音色** |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/speech`(`tts-1` + alloy/nova/…) |
|
||||
| **语音输入** | `system` | 设备自带识别(安卓 `SpeechRecognizer`) |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/transcriptions`(`whisper-1` 等) |
|
||||
|
||||
**火山那个接口有两个坑**(对着[官方文档](https://docs.volcengine.com/docs/DoubaoVoice/HTTPone-timecompositenon-streaminginterface-V1notrecommended?lang=zh)
|
||||
和两个第三方实现核对过,并且用 mock 抓了实际发出的请求):
|
||||
|
||||
1. 鉴权头是 `Authorization: Bearer;{token}` —— **分号,不是空格**。写成空格会判鉴权失败。
|
||||
实测抓到的请求:`Authorization="Bearer;tok-abc"`
|
||||
2. 成功判定看 body 里的 `code === 3000`,**HTTP 200 也可能带错误码**;
|
||||
返回的 `data` 是**纯 base64**(不是 data URL),解出来就是音频字节
|
||||
|
||||
接口:
|
||||
|
||||
```
|
||||
POST /api/tts {"text": "..."}
|
||||
→ {"ok":true, "engine":"system"} 用设备自带,界面自己念
|
||||
→ {"ok":true, "engine":"volc", "mime":"audio/mpeg", "audio":"<base64>"}
|
||||
→ {"ok":false, "error":"..."} 失败原因给人话
|
||||
|
||||
POST /api/stt <body 就是音频原始字节,不套 JSON/base64>
|
||||
头: X-Audio-Filename / X-Audio-Type
|
||||
→ {"ok":true, "engine":"openai", "text":"..."}
|
||||
|
||||
GET /api/speech → 当前配置 + 可选音色
|
||||
```
|
||||
|
||||
> 两个接口**失败也返回 HTTP 200 + `ok:false`**:缺 Key、厂商报错都是预期内的失败,
|
||||
> 界面要的是把原因显示出来,而不是让 fetch 抛网络异常(那样错误信息就丢了)。
|
||||
|
||||
安卓端(`speech/AudioIo.kt` + `speech/SpeechController.kt`):
|
||||
|
||||
- **录音**用 `AudioRecord` 直接拿 PCM,套 44 字节 WAV 头(16kHz 单声道 16bit ——
|
||||
Whisper 最常见的输入格式,30 秒才 1 MB)。不用 `MediaRecorder` 是因为它只吐 m4a/aac,还得再解码
|
||||
- **播放**云端音频走 `MediaPlayer`(`setDataSource` 只认路径/FD,所以 base64 落盘成临时文件再播)
|
||||
- **系统 TTS** 会**按句切分**再排队 —— `speak()` 单次上限约 4000 字符,整段塞进去会被截断
|
||||
- 念之前**剥掉 markdown**(`**加粗**`、代码块、链接),否则会念出一堆星号
|
||||
- **云端失败自动退回系统 TTS**:用户点了朗读却一点动静都没有是最差的体验
|
||||
- 录音时**先停朗读**,否则会把自己的声音录进去(自我循环)
|
||||
- 录音权限**第一次点麦克风才申请**,不在启动时要
|
||||
- 录音时输入框整条换成「正在听…」+ 实时音量画的小波形
|
||||
|
||||
验证:`node scripts/verify-speech.mjs py|node` —— **21 项断言,两份内核都跑**
|
||||
(语音在 Node 和 Python 里是分别实现的,只验一份不算数)。
|
||||
mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权头。
|
||||
|
||||
### 3.11 通话模式(设计好了,还没做)
|
||||
|
||||
顶部那个 📞 现在是提示。真要做的话按这个来(**不要一上来就上全双工**):
|
||||
|
||||
| 阶段 | 做法 | 为什么 |
|
||||
|---|---|---|
|
||||
| A(推荐先做) | **半双工**:按一次开始录 → 静音自动断句 → STT → 内核 → TTS 播 → 循环 | 复用现有的 STT/TTS,1 天能出可用版本 |
|
||||
| B | 全双工实时(OpenAI Realtime / 火山实时对话,WebSocket) | 延迟 300ms 级、能自然打断,但强依赖网络,改造量 3~5 天 |
|
||||
|
||||
阶段 A 要处理的四件事(都会真实咬人):
|
||||
|
||||
1. **自我循环**:TTS 在播时开麦会把 AI 自己的声音录进去 → 播之前必须先停麦,
|
||||
或者做回声消除(`AudioSource.VOICE_COMMUNICATION` + AEC)
|
||||
2. **音频焦点**:`TextToSpeech` 和 `AudioRecord` 不能同时持有 → 用 `AudioManager` 协调
|
||||
3. **VAD 断句**:靠静音时长判断"说完了"。阈值调不好要么打断用户、要么一直不响应;
|
||||
建议"连续 800ms 低于阈值算说完",并且**开口就打断 TTS**(barge-in)——这是"像通话"的关键手感
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 4. 安卓端:内置 Termux 是怎么塞进去的
|
||||
|
||||
### 4.1 一条硬限制决定了整个方案
|
||||
|
||||
**Android 10(API 29)起有 W^X 限制:`targetSdk ≥ 29` 的应用不允许执行自己数据目录里的二进制。**
|
||||
而 Termux 把 bash/python/node 全解压在自己的私有目录再 exec —— 它能这么干,**唯一原因是它 `targetSdk = 28`**
|
||||
(实测核对:`dumpsys package com.termux` → `targetSdk=28`)。
|
||||
|
||||
所以这个 APK 也锁 **`targetSdk = 28`**。代价是上不了应用商店(个人工具无所谓);
|
||||
换来的是完整 Linux 用户态:`bash`、`apt`、`pkg`、以及 `pkg install python nodejs-lts`。
|
||||
|
||||
### 4.2 APK 里到底装了什么
|
||||
|
||||
```
|
||||
APK 88.4 MB
|
||||
├─ lib/arm64-v8a/libtermux-bootstrap.so 28.0 MB ← Termux 根文件系统(其实是 zip)
|
||||
├─ lib/x86_64/libtermux-bootstrap.so 28.1 MB ← 同上,模拟器用
|
||||
├─ lib/<abi>/libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号)
|
||||
├─ lib/<abi>/libpython3.13.so ← Chaquopy 的 CPython
|
||||
├─ assets/chaquopy/** ← 内核 + 9 个 Python 工具
|
||||
└─ java/com/termux/{terminal,view}/** ← Termux 的终端模拟器源码(vendored)
|
||||
```
|
||||
|
||||
Termux 的终端库**没有发布到任何 Maven 仓库**(Maven Central 没有,JitPack 也不通),
|
||||
所以是 vendored 源码 + 改了两处 `import com.termux.view.R` 指向我们自己的 R 类。
|
||||
Apache-2.0 声明见 `android/app/src/main/assets/TERMUX_LICENSE.txt`。
|
||||
|
||||
### 4.3 安装流程(移植自 Termux 的 `TermuxInstaller.java`)
|
||||
|
||||
1. 从 APK 里取出 `libtermux-bootstrap.so`
|
||||
2. **切掉 ELF 头**得到纯 zip(见 4.4 ①)
|
||||
3. 解压到 `files/usr`(3226 个文件),给 `bin/ lib/ libexec/` 下的文件补可执行位
|
||||
4. 读 `SYMLINKS.txt`(1146 行,格式 `目标←链接路径`),**用 `/system/bin/sh` 批量 `ln -sf`**
|
||||
—— Java 的 File API 建不了符号链接
|
||||
5. **改写脚本 shebang**(见 4.4 ④)
|
||||
6. 写一份自己的 `etc/doubao.bashrc`
|
||||
|
||||
进度会写进 `files/termux-install.log`(见 §7.6,为什么不用 Logcat)。
|
||||
|
||||
### 4.4 踩过的四个坑(都和你想象的不一样)
|
||||
|
||||
**① `libtermux-bootstrap.so` 不是纯 zip,是「ELF 头 + zip」**
|
||||
文件前 1328 字节是 ELF 头(Android 要求 `lib/` 下的东西得像 ELF,Termux 就把 zip 接在后面)。
|
||||
- `ZipInputStream` 按本地文件头顺序扫,**实测一个条目都读不出来**;
|
||||
- `ZipFile` 走中央目录,但它**不会**像桌面 JVM 那样自动跳过前缀 ——
|
||||
真机 Android 16 上直接报 `Entry at offset zero has invalid LFH signature 464c457f`
|
||||
(`464c457f` 就是 `\x7FELF` 的小端十六进制)。模拟器上碰巧宽松能过,真机不行。
|
||||
|
||||
所以现在的做法:**自己扫第一个 `PK\x03\x04`、把前缀切掉**,再交给 `ZipFile`。
|
||||
|
||||
**② `bin/su` 写不进去(ENOENT)**
|
||||
父目录存在、权限也对,就是 `open` 失败。安卓对这个文件名有额外限制。
|
||||
处理方式:**单个文件失败就跳过并记日志**,不让一个怪文件毁掉整次安装(其余 3226 个照常)。
|
||||
|
||||
**③ 必须设 `LD_PRELOAD` + `TERMUX__PREFIX`(双下划线)**
|
||||
Termux 的二进制里写死了 `/data/data/com.termux/files/usr`。`libtermux-exec.so` 负责把这些路径
|
||||
重写到真实 prefix,但它认的环境变量是:
|
||||
`TERMUX__PREFIX`(**不是** `TERMUX_PREFIX`)、`TERMUX_APP__DATA_DIR`。
|
||||
少一个,bash 就会去读**别的包**的 `/etc/profile`,报 `Permission denied`。
|
||||
|
||||
**④ 脚本的 shebang 也得改**
|
||||
`bin/getprop`、`bin/pkg` 这些是 shell 脚本,第一行写死 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
内核解析 shebang 时不会经过 termux-exec,照样 EACCES("bad interpreter")。
|
||||
安装时统一把 `bin/ libexec/` 下 79 个脚本的 shebang 前缀改成我们的 prefix 就好了。
|
||||
|
||||
### 4.5 终端界面(真终端 + 控制台退路)
|
||||
|
||||
用 Termux 自己的 `TerminalView` + `libtermux.so` 的 `forkpty` —— 真 pty、真 ANSI,
|
||||
所以 `vim`/`top` 这类全屏程序都能跑。Compose 里用 `AndroidView` 包一层,底下加了手机必备的功能键排:
|
||||
`ESC / TAB / CTRL+C / CTRL+D / ↑↓←→ / HOME / END / | / / / - / ENTER`(没这排连 vim 都退不出来)。
|
||||
|
||||
**但 pty 不是每台机器都给用**。实测 realme(Android 16)上:
|
||||
|
||||
```
|
||||
/dev/pts → Permission denied
|
||||
mount → devpts on /dev/pts type devpts (mode=600,ptmxmode=000)
|
||||
python openpty → OSError: out of pty devices
|
||||
```
|
||||
|
||||
`/dev/pts` 被挂成 `mode=600` 且 `ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||
于是 TerminalSession 一起来就退出(界面上只留一句 `[Process completed]`)。
|
||||
这不是 SELinux 拒绝(logcat 里没有任何 avc),是挂载参数定的,应用侧绕不过去。
|
||||
|
||||
所以做成两条路,**自动切换**:
|
||||
|
||||
| 情况 | 走哪条 |
|
||||
|---|---|
|
||||
| pty 可用(多数设备 / 模拟器) | Termux 的 TerminalView,真终端 |
|
||||
| 会话建起来 2 秒内就退出(判定 pty 不可用) | 自动切「控制台模式」:命令框 + 输出区,跑的是**同一条 Termux bash**,只是没有 tty |
|
||||
|
||||
代价只是没有全屏 TUI 和交互式提示符,跑命令、装包(`pkg install python`)都正常。
|
||||
|
||||
### 4.6 和内核怎么接
|
||||
|
||||
内核里的 `shell` 工具优先走内置 Termux(返回里带 `via: "termux"`),
|
||||
`device` 工具的 `termux_run` / `termux_available` 也走同一条路。
|
||||
因为 Termux 现在就在本进程里,不需要跨进程 intent、也不需要用户去开 `allow-external-apps`。
|
||||
|
||||
### 4.7 安卓端其余细节(Chaquopy / 界面)
|
||||
|
||||
- **Chaquopy 17.0.0** 内嵌 CPython 3.13.9:没有 `python` 可执行文件(所以 `python_run` 是**进程内 exec**,
|
||||
不能起子进程);运行时 pip 只能装纯 Python 轮子;`mcp` 官方 SDK 用不了(要 pydantic v2)
|
||||
- **刻意不装任何第三方包**:Chaquopy 每次构建都要连云 pip,网络一抖整个 APK 就构建不出来
|
||||
(实测 `Could not find a version that satisfies the requirement requests`)。
|
||||
内核只用标准库(`urllib`/`http.server`/`json`),所以留零依赖换来"离线也能构建"。
|
||||
要 requests/numpy 就走内置 Termux:`pkg install python && pip install requests`
|
||||
- **界面**:状态栏不遮挡顶栏(`windowInsetsPadding(WindowInsets.safeDrawing)`)、
|
||||
输入框跟随输入法(`imePadding`)、深色模式自动适配
|
||||
- **流式**:Lynx 那边用 SSE;安卓原生 Compose 走的是**轮询通道**
|
||||
(`transport: "poll"` + `GET /api/chat/poll?runId=&cursor=`),
|
||||
两条件事件类型完全一致,客户端 200ms 取一次增量
|
||||
|
||||
---
|
||||
|
||||
## 5. 我实际验证了什么
|
||||
|
||||
### 5.1 安卓端(原生 Compose + 内置 Termux)
|
||||
|
||||
真机(RMX5090 / Android 16 / arm64-v8a):`node scripts/verify-phone.mjs <serial>` → **17/18**。
|
||||
模拟器(Android 14 / x86_64):17/18(唯一失败的是"定位",模拟器没有 GPS)。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 构建 | ✅ `assembleDebug` 成功,APK 88.4 MB |
|
||||
| 内核启动 | ✅ `GET /api/health` → `{"ok":true,…}` |
|
||||
| 智能体 / 工具 | ✅ 4 个智能体;8 个内置工具 + MCP 工具 |
|
||||
| 内置 Termux | ✅ 首次解压 3226 个文件 / 388 个命令 / 1146 个符号链接 |
|
||||
| shell | ✅ 真机 `Linux localhost 6.6.118-android15 … aarch64 Android`,`via: termux`,stderr 干净 |
|
||||
| pkg / apt | ✅ 可执行(79 个脚本的 shebang 已修正) |
|
||||
| python_run | ✅ CPython 3.13.9 aarch64(进程内) |
|
||||
| 联网 | ✅ urllib 与 requests 都 200 |
|
||||
| device 信息 | ✅ 型号 / 厂商 / 系统 / SDK / 存储 / 电量 |
|
||||
| 传感器 | ✅ 真机 46 个;加速度计 z≈9.7 m/s²、陀螺仪有数据 |
|
||||
| 定位 | ✅ 真机 `纬度, 经度 ±35m` |
|
||||
| MCP(Python 写的服务) | ✅ 连接 + 列工具 + 调用成功 |
|
||||
| 设置保存 | ✅ 保存前后逐字段一致(含 API Key / 系统提示词),空值攻击被忽略 |
|
||||
| 思考强度映射 | ✅ 两份内核对拍 50/50 一致 |
|
||||
| 界面 | ✅ 对话 / 抽屉 / 终端 / 设置 / 模型面板 截图见文首 |
|
||||
|
||||
### 5.2 其他平台
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 浏览器渲染 | ✅ 无头 Edge + CDP,5 个页面全部渲染,控制台无异常 |
|
||||
| 端到端工具调用 | ✅ mock 模型 → 请求 `calc` → Python 返回 → 第二轮流式回答 → 落库 |
|
||||
| Python 工具 | ✅ `calc` `now` `get_weather`(实时数据) `notes` `web_fetch` 全部通过 |
|
||||
| MCP | ✅ filesystem 14 工具、memory 9 工具连接成功;6 类校验错误全部拦截 |
|
||||
| Windows exe | ✅ 冷启动、界面渲染、内置内核、MCP 自动连接 |
|
||||
|
||||
### 5.3 没有 API Key 也能把链路跑通
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假的 OpenAI 兼容服务,监听 5299
|
||||
node scripts/verify-phone.mjs emulator-5556 # 或对真机跑
|
||||
```
|
||||
|
||||
mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式回答"来演,
|
||||
所以能验证完整的 界面 → 内核 → 工具调用 → 流式返回 链路,**不消耗任何额度**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 给 Lynx 界面(Web / exe)的注意事项
|
||||
|
||||
安卓端已经不用 Lynx 了,这一节只对 Web/exe 有效:
|
||||
|
||||
- **Fresco 必须先初始化**,否则图片不显示;**Fresco 不能解码 SVG**,图标要预先栅格化成 PNG
|
||||
- Lynx 的 `fetch` 没有 `response.body`,所以流式走轮询通道
|
||||
- 状态栏/布局用 `safe-area` 相关变量,别写死 px
|
||||
- 动画(`breathe` 那种)在某些模拟器上会破坏图片绘制,已改成不影响绘制的写法
|
||||
|
||||
---
|
||||
|
||||
## 7. 打包踩坑记录
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 384 MB)
|
||||
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||
|
||||
### 7.2 Android APK
|
||||
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||
否则 `nativeLibraryDir` 是空的,`.so` 全在 APK 里,取 bootstrap 时得从 `applicationInfo.sourceDir` 读
|
||||
- **`targetSdk = 28`**(见 4.1),`abiFilters = ["arm64-v8a", "x86_64"]`
|
||||
- 构建脚本会把 `tools/*.py` 拷进 `app/src/main/python/` 并生成 `bundled_tool_sources.py`
|
||||
- 构建暂存目录用 ASCII 路径(`C:\DoubaoAndroid`),中文路径会让 Gradle/Chaquopy 出问题
|
||||
- **别并发跑两次 Gradle**:会互相踩坏 Chaquopy 的 venv(`Scripts/python.exe does not exist`)
|
||||
|
||||
### 7.3 Chaquopy / 内嵌 Python
|
||||
- `.pyc`-only 打包导致 `loader.get_source()` 失败 → 工具源码用 base64 内嵌
|
||||
- 每次构建都会连云 pip → 已改为零第三方依赖(见 4.7)
|
||||
|
||||
### 7.4 Android 15+ 的 edge-to-edge
|
||||
强制 edge-to-edge 后,状态栏会压住顶栏、输入法会盖住输入框。
|
||||
Compose 里统一在根布局吃 `WindowInsets.safeDrawing`,滚动页再叠 `imePadding()`。
|
||||
|
||||
### 7.5 工具链(Windows)
|
||||
- **Node 20+ 不能直接 `spawn` `.bat`/`.cmd`**(`status=null`),必须 `shell: true`
|
||||
- **PowerShell 会把命令行里的 JSON 引号搅坏**:所有内联 node/python 脚本都写成文件再跑
|
||||
- **PowerShell 的 `Get-Content` / `Set-Content` 会按 GBK 读写 UTF-8 文件**,
|
||||
一读一写就把中文文档转成乱码(本文档就被这么毁过一次)。
|
||||
改文本一律用编辑器工具,别用这两个 cmdlet 做"读进来再写回去"
|
||||
- **Kotlin 的块注释会嵌套**:在 KDoc 里写 `lib/*.so` 里的 `/*` 会开一个嵌套注释,
|
||||
把后面的代码全吞掉,报错却指向文件末尾之外的行
|
||||
|
||||
### 7.6 安卓 `org.json` 不会把 `Map` 转成 JSON 对象(踩过一次大的)
|
||||
|
||||
`json.put("speech", mapOf("autoRead" to true))` **不会**产生 `{"speech":{"autoRead":true}}`,
|
||||
而是把 Map 原样存进去,序列化出来是 `{"speech":"{autoRead=true}"}` —— **值是字符串**。
|
||||
|
||||
这一个坑连锁出四件事:
|
||||
|
||||
1. 内核把字符串写进了 `settings.json`(`speech` 本来是对象,被字符串顶掉了)
|
||||
2. 之后**每一次**读配置(`{**默认, **字符串}`)都抛 `TypeError`
|
||||
3. `/api/state` 从此永远返回 `{"error":"'str' object is not a mapping"}`
|
||||
4. App 把这个错误 JSON 解析成了「全默认状态」,而且**不抛异常**,所以还弹了"已保存"
|
||||
|
||||
用户看到的就是:**点一下语音按钮,模型变「未设置」、昵称变回「我」、会话列表全空**。
|
||||
|
||||
修了三处(缺一不可):
|
||||
- **安卓**:`patchToJson()` 显式递归把 Map/List 转成 `JSONObject`/`JSONArray`(见 `AppViewModel.kt`)
|
||||
- **内核写**:`tools`/`security`/`speech` 这几个子对象,补丁里不是字典就**直接忽略**,
|
||||
宁可这次改动不生效,也不写出读不回来的配置
|
||||
- **内核读**:发现子对象不是字典就**回落默认值**(自愈)——
|
||||
一个坏字段不该让 `/api/state` 永久 500,更不该把用户其它数据一起拖没
|
||||
|
||||
> 为什么之前没暴露:只有**嵌套对象**才触发,而在此之前 App 从没发过嵌套补丁
|
||||
> (`tools` 那两个开关从来没在设置页点过)。教训是——
|
||||
> **跨语言边界传结构化数据时,别信任何一侧的隐式转换**,两端都要有"形状不对就拒绝"的防线。
|
||||
|
||||
### 7.7 部分 ROM 会吞掉应用日志
|
||||
realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一条都看不到**。
|
||||
所以安装进度、终端会话退出原因等关键信息都**落盘**到 `files/termux-install.log`,
|
||||
用 `adb shell run-as com.doubao.lynxclone cat files/termux-install.log` 读。
|
||||
|
||||
---
|
||||
|
||||
## 8. 已知限制
|
||||
|
||||
- **`targetSdk = 28` 上不了应用商店**(个人侧载没问题)。要上架就得回到"外装 Termux + 桥接"那条路
|
||||
- **pty 在部分 ROM 上不可用**(4.5),自动降级成控制台模式,没有全屏 TUI
|
||||
- **内嵌 CPython 没有 `python` 可执行文件**,`python_run` 是进程内 exec,不能起子进程
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发
|
||||
npm run dev # 起 Node 内核 + Lynx 热更
|
||||
npm run build # 构建 Lynx bundle
|
||||
npm run apk # 构建 APK(--clean 可彻底重建)
|
||||
npm run exe # 打包 Windows exe
|
||||
|
||||
# 验证
|
||||
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
node scripts/mock-llm.mjs # 监听 5299
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 参考
|
||||
|
||||
- 火山方舟:<https://www.volcengine.com/docs/82379/1298454>
|
||||
- OpenAI Chat Completions:<https://platform.openai.com/docs/api-reference/chat>
|
||||
- Termux(Apache-2.0):<https://github.com/termux/termux-app>
|
||||
- Chaquopy:<https://chaquo.com/chaquopy/doc/current/>
|
||||
- 调研笔记(`docs/`):
|
||||
- `ai-chat-backend-api-research.md`(Ark/OpenAI/MCP 接口细节与证据强度)
|
||||
- `lynx-ui-research.md`(豆包界面还原的调研)
|
||||
|
||||
---
|
||||
|
||||
## 11. 许可
|
||||
|
||||
本项目采用 **MIT License**,见 [LICENSE](LICENSE)。
|
||||
|
||||
它**包含或依赖**第三方作品,各自的授权独立于 MIT,使用时请一并遵守:
|
||||
|
||||
| 组件 | 授权 | 用在哪 |
|
||||
|---|---|---|
|
||||
| [Termux](https://github.com/termux/termux-app) | **Apache-2.0** | 终端模拟器源码(vendored)+ pty 的 JNI 库 |
|
||||
| [Chaquopy](https://chaquo.com/chaquopy/) | MIT | APK 内嵌 CPython |
|
||||
| [Jetpack Compose / AndroidX](https://developer.android.com/jetpack) | Apache-2.0 | 安卓界面 |
|
||||
| [LynxJS](https://github.com/lynx-family/lynx) | Apache-2.0 | Web / 桌面版界面 |
|
||||
| [Electron](https://github.com/electron/electron) | MIT | Windows 桌面版打包 |
|
||||
|
||||
Termux 的完整许可在 `android/app/src/main/assets/TERMUX_LICENSE.txt` 与 `APACHE-2.0.txt`。
|
||||
|
||||
> **商标声明**:「豆包」是字节跳动的商标。本项目是出于学习目的的界面复刻,
|
||||
> 与字节跳动无任何关联,不含任何来自豆包 App 的代码或素材。
|
||||
> 界面配色与布局照着公开截图量出,图标使用 Material Icons。
|
||||
|
||||
> **注意**:本仓库**不包含** Termux 的 bootstrap(`libtermux-bootstrap.so`,两个 ABI 共 56 MB),
|
||||
> 因此直接 clone 下来构建 APK 会缺这个文件。补法见 §4.2 与 §4.3。
|
||||
|
||||
约定见 [`AGENTS.md`](AGENTS.md)(入口)和 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)(详细)。
|
||||
|
||||
@@ -1,371 +0,0 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.net.Uri
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 暴露给 Python 内核的原生能力。
|
||||
*
|
||||
* Chaquopy 允许 Python 直接调这个类的方法(`from java import jclass` 那套),
|
||||
* 所以内核里的 `device` 工具、剪贴板钩子、选文件钩子都落到这里。
|
||||
*
|
||||
* 线程约定:device() 可能阻塞几秒(采传感器、等定位),
|
||||
* 它只会在内核的 HTTP 工作线程上被调用,**不会**卡住 UI 线程。
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
JSONObject(payloadJson)
|
||||
} catch (e: Exception) {
|
||||
JSONObject()
|
||||
}
|
||||
val action = req.optString("action", "info")
|
||||
return try {
|
||||
when (action) {
|
||||
"info" -> deviceInfo()
|
||||
"battery" -> batteryInfo()
|
||||
"location" -> locationInfo()
|
||||
"sensors" -> sensorList()
|
||||
"sensor" -> sensorSample(req.optString("sensor"), req.optDouble("duration", 1.5))
|
||||
"clipboard_get" -> JSONObject().put("text", readClipboard())
|
||||
"clipboard_set" -> {
|
||||
setClipboard(req.optString("text"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// 内置 Termux:完整 Linux 用户态(真 bash / 真 pkg / 真子进程)
|
||||
"termux_available" -> JSONObject().put("installed", TermuxShell.isReady(activity))
|
||||
"termux_run" -> TermuxShell.run(
|
||||
activity,
|
||||
req.optString("command"),
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}.toString()
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
val totalGb = stat.totalBytes / 1024.0 / 1024.0 / 1024.0
|
||||
return JSONObject()
|
||||
.put("platform", "Android")
|
||||
.put("model", Build.MODEL)
|
||||
.put("manufacturer", Build.MANUFACTURER)
|
||||
.put("brand", Build.BRAND)
|
||||
.put("device", Build.DEVICE)
|
||||
.put("android", Build.VERSION.RELEASE)
|
||||
.put("sdk", Build.VERSION.SDK_INT)
|
||||
.put("abis", JSONArray(Build.SUPPORTED_ABIS.toList()))
|
||||
.put("storage_free_gb", String.format("%.1f", freeGb))
|
||||
.put("storage_total_gb", String.format("%.1f", totalGb))
|
||||
.put("screen", screenInfo())
|
||||
.put("battery", batteryInfo())
|
||||
}
|
||||
|
||||
private fun screenInfo(): String {
|
||||
val metrics = activity.resources.displayMetrics
|
||||
return "${metrics.widthPixels}x${metrics.heightPixels} @${metrics.density}x"
|
||||
}
|
||||
|
||||
private fun batteryInfo(): JSONObject {
|
||||
val bm = activity.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
|
||||
return JSONObject()
|
||||
.put("level_percent", bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1)
|
||||
.put("charging", bm?.isCharging ?: false)
|
||||
}
|
||||
|
||||
/** 定位:先拿最后已知位置,拿不到就等一次单次更新(最多 8 秒) */
|
||||
private fun locationInfo(): JSONObject {
|
||||
val lm = activity.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
?: return JSONObject().put("error", "没有 LocationManager")
|
||||
val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
|
||||
var best: Location? = null
|
||||
for (p in providers) {
|
||||
try {
|
||||
if (!lm.isProviderEnabled(p)) continue
|
||||
val loc = lm.getLastKnownLocation(p) ?: continue
|
||||
if (best == null || loc.time > best!!.time) best = loc
|
||||
} catch (t: SecurityException) {
|
||||
return JSONObject().put("error", "缺少定位权限(ACCESS_FINE_LOCATION)")
|
||||
} catch (_: Throwable) {
|
||||
// 某些机型会抛 IllegalArgumentException,忽略继续
|
||||
}
|
||||
}
|
||||
if (best == null) {
|
||||
val latch = CountDownLatch(1)
|
||||
var fresh: Location? = null
|
||||
val listener = object : android.location.LocationListener {
|
||||
override fun onLocationChanged(location: Location) {
|
||||
fresh = location
|
||||
latch.countDown()
|
||||
}
|
||||
// 老 API 要求实现,留着空实现
|
||||
override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
|
||||
override fun onProviderEnabled(provider: String) {}
|
||||
override fun onProviderDisabled(provider: String) {}
|
||||
}
|
||||
try {
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, listener)
|
||||
} catch (_: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(8, TimeUnit.SECONDS)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
} finally {
|
||||
try {
|
||||
lm.removeUpdates(listener)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
best = fresh
|
||||
}
|
||||
if (best == null) {
|
||||
return JSONObject()
|
||||
.put("available", false)
|
||||
.put("hint", "没拿到定位:确认已开定位开关、已授予权限、或在室内 GPS 信号差时稍后再试")
|
||||
}
|
||||
return JSONObject()
|
||||
.put("available", true)
|
||||
.put("latitude", best!!.latitude)
|
||||
.put("longitude", best!!.longitude)
|
||||
.put("accuracy_m", best!!.accuracy.toDouble())
|
||||
.put("provider", best!!.provider)
|
||||
.put("age_seconds", (System.currentTimeMillis() - best!!.time) / 1000.0)
|
||||
}
|
||||
|
||||
private val keywordToType = mapOf(
|
||||
"accelerometer" to Sensor.TYPE_ACCELEROMETER,
|
||||
"gyroscope" to Sensor.TYPE_GYROSCOPE,
|
||||
"magnetic" to Sensor.TYPE_MAGNETIC_FIELD,
|
||||
"light" to Sensor.TYPE_LIGHT,
|
||||
"pressure" to Sensor.TYPE_PRESSURE,
|
||||
"proximity" to Sensor.TYPE_PROXIMITY,
|
||||
"gravity" to Sensor.TYPE_GRAVITY,
|
||||
"linear_acceleration" to Sensor.TYPE_LINEAR_ACCELERATION,
|
||||
"rotation_vector" to Sensor.TYPE_ROTATION_VECTOR,
|
||||
"step_counter" to Sensor.TYPE_STEP_COUNTER,
|
||||
"humidity" to Sensor.TYPE_RELATIVE_HUMIDITY,
|
||||
"temperature" to Sensor.TYPE_AMBIENT_TEMPERATURE,
|
||||
"game_rotation_vector" to Sensor.TYPE_GAME_ROTATION_VECTOR,
|
||||
)
|
||||
|
||||
private fun sensorManager(): SensorManager? =
|
||||
activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
|
||||
|
||||
private fun sensorList(): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val arr = JSONArray()
|
||||
for (s in sm.getSensorList(Sensor.TYPE_ALL)) {
|
||||
val key = keywordToType.entries.firstOrNull { it.value == s.type }?.key
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("key", key ?: "type_${s.type}")
|
||||
.put("name", s.name)
|
||||
.put("vendor", s.vendor)
|
||||
.put("type", s.type)
|
||||
.put("power_ma", s.power.toDouble()),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("count", arr.length()).put("sensors", arr)
|
||||
}
|
||||
|
||||
/** 采样:注册监听 duration 秒,返回样本序列与统计 */
|
||||
private fun sensorSample(key: String, duration: Double): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val name = key.ifBlank { "accelerometer" }
|
||||
val type = keywordToType[name] ?: return JSONObject()
|
||||
.put("error", "不认识的传感器:$name(可用:${keywordToType.keys.joinToString(", ")})")
|
||||
val sensor = sm.getDefaultSensor(type)
|
||||
?: return JSONObject().put("error", "这台设备没有 $name 传感器")
|
||||
|
||||
val seconds = duration.coerceIn(0.2, 10.0)
|
||||
val samples = mutableListOf<FloatArray>()
|
||||
val latch = CountDownLatch(1)
|
||||
val listener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
if (samples.size < 500) samples.add(event.values.copyOf())
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
|
||||
}
|
||||
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME)
|
||||
try {
|
||||
// 用 latch 等不到就超时,靠 await 的返回值判断即可
|
||||
latch.await((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
|
||||
} finally {
|
||||
sm.unregisterListener(listener)
|
||||
}
|
||||
if (samples.isEmpty()) return JSONObject().put("error", "$name 在采样期内没出数据")
|
||||
|
||||
val dims = samples.first().size
|
||||
val stats = JSONArray()
|
||||
for (d in 0 until dims) {
|
||||
val values = samples.map { it[d].toDouble() }
|
||||
stats.put(
|
||||
JSONObject()
|
||||
.put("avg", values.average())
|
||||
.put("min", values.min())
|
||||
.put("max", values.max())
|
||||
.put("last", values.last()),
|
||||
)
|
||||
}
|
||||
val last = JSONArray()
|
||||
samples.last().forEach { last.put(it.toDouble()) }
|
||||
return JSONObject()
|
||||
.put("sensor", name)
|
||||
.put("unit", unitOf(name))
|
||||
.put("sample_count", samples.size)
|
||||
.put("seconds", seconds)
|
||||
.put("axes", axisNames(dims))
|
||||
.put("last", last)
|
||||
.put("stats", stats)
|
||||
}
|
||||
|
||||
private fun axisNames(dims: Int): JSONArray {
|
||||
val names = listOf("x", "y", "z", "w")
|
||||
val arr = JSONArray()
|
||||
for (i in 0 until dims) arr.put(names.getOrElse(i) { "v$i" })
|
||||
return arr
|
||||
}
|
||||
|
||||
private fun unitOf(name: String): String = when (name) {
|
||||
"accelerometer", "gravity", "linear_acceleration" -> "m/s^2"
|
||||
"gyroscope" -> "rad/s"
|
||||
"magnetic" -> "uT"
|
||||
"light" -> "lx"
|
||||
"pressure" -> "hPa"
|
||||
"proximity" -> "cm"
|
||||
"humidity" -> "%"
|
||||
"temperature" -> "°C"
|
||||
else -> ""
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 剪贴板 / 选文件
|
||||
|
||||
@Suppress("unused")
|
||||
fun setClipboard(text: String) {
|
||||
activity.runOnUiThread {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("doubao", text))
|
||||
}
|
||||
}
|
||||
|
||||
private fun readClipboard(): String {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = cm.primaryClip ?: return ""
|
||||
if (clip.itemCount == 0) return ""
|
||||
return clip.getItemAt(0).coerceToText(activity).toString()
|
||||
}
|
||||
|
||||
/** 内核请求"用户选个文件"时调用;把选中的文件复制到 App 私有目录再返回路径 */
|
||||
@Volatile
|
||||
private var pickLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var pickedUris: List<Uri> = emptyList()
|
||||
|
||||
@Suppress("unused")
|
||||
fun pickFile(): Array<String> {
|
||||
val latch = CountDownLatch(1)
|
||||
pickLatch = latch
|
||||
pickedUris = emptyList()
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = "*/*"
|
||||
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||
}
|
||||
activity.startActivityForResult(intent, REQ_PICK)
|
||||
} catch (t: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
|
||||
/** MainActivity 的 onActivityResult 转进来 */
|
||||
fun onPicked(data: Intent?) {
|
||||
val uris = mutableListOf<Uri>()
|
||||
data?.clipData?.let { clip ->
|
||||
for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri)
|
||||
}
|
||||
data?.data?.let { uris.add(it) }
|
||||
pickedUris = uris
|
||||
pickLatch?.countDown()
|
||||
}
|
||||
|
||||
private fun copyIntoCache(uri: Uri): String? = try {
|
||||
val name = displayName(uri) ?: "upload_${System.currentTimeMillis()}"
|
||||
val dir = File(activity.cacheDir, "picked").apply { mkdirs() }
|
||||
val dest = File(dir, name)
|
||||
activity.contentResolver.openInputStream(uri)?.use { input ->
|
||||
dest.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
dest.absolutePath
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun displayName(uri: Uri): String? = try {
|
||||
activity.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
/** 安卓上没有"打开文件夹",直接返回提示(设置页会显示不可用) */
|
||||
@Suppress("unused")
|
||||
fun reveal(path: String): String? = null
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
entry.callAttr("set_android_bridge", bridge)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.util.zip.ZipInputStream
|
||||
|
||||
/**
|
||||
* 把 Termux 的根文件系统(bootstrap)装进应用私有目录。
|
||||
*
|
||||
* 这套逻辑是从 Termux 自己的 `TermuxInstaller.java` 移植过来的(Apache-2.0),
|
||||
* 关键就三步:
|
||||
* 1. 从 `lib/<abi>/libtermux-bootstrap.so` 读 zip(它其实就是个改了名的 zip,
|
||||
* 放在 lib 目录是为了让系统在安装时原样解出来、不被压缩)
|
||||
* 2. 逐条解压到 files/usr,并给 bin/ lib/ 下的文件加可执行位
|
||||
* 3. 读 SYMLINKS.txt(格式 `目标←链接路径`),**用 /system/bin/sh 建符号链接**
|
||||
* —— Java 的 File API 建不了符号链接,只能借 shell
|
||||
*
|
||||
* 为什么必须 targetSdk=28:Android 10 起 targetSdk>=29 的应用不允许执行自己数据目录里的二进制,
|
||||
* 而 bash/python 全在这个目录里。Termux 自己也是锁 28 才活下来的。
|
||||
*/
|
||||
object TermuxInstaller {
|
||||
|
||||
private const val TAG = "DoubaoTermux"
|
||||
private const val BOOTSTRAP_LIB = "libtermux-bootstrap.so"
|
||||
private const val ARROW = "\u2190" // SYMLINKS.txt 里的分隔符
|
||||
|
||||
fun prefix(context: Context): File = File(context.filesDir, "usr")
|
||||
fun home(context: Context): File = File(context.filesDir, "home")
|
||||
fun bashPath(context: Context): String = File(prefix(context), "bin/bash").absolutePath
|
||||
|
||||
/** 装没装:看 bash 在不在(Termux 的 bootstrap 一定带 bash) */
|
||||
fun isInstalled(context: Context): Boolean =
|
||||
File(prefix(context), "bin/bash").exists() && File(prefix(context), "bin/login").exists()
|
||||
|
||||
/** 剩余没装的标记文件,避免半途失败后反复重来 */
|
||||
private fun stampFile(context: Context) = File(context.filesDir, ".termux-bootstrap-ok")
|
||||
|
||||
/**
|
||||
* 安装日志。
|
||||
*
|
||||
* 为什么要写文件而不是只打 Logcat:部分国产 ROM(实测 realme/ColorOS)会把应用自己打的
|
||||
* log 全过滤掉,出问题时 adb logcat 里一条都看不到,只能靠落盘来诊断。
|
||||
* 位置:files/termux-install.log,可以直接 `adb shell run-as <包名> cat files/termux-install.log`
|
||||
*/
|
||||
private fun logFile(context: Context) = File(context.filesDir, "termux-install.log")
|
||||
|
||||
fun trace(context: Context, message: String) { Log.i(TAG, message)
|
||||
try {
|
||||
logFile(context).appendText("${System.currentTimeMillis()} $message\n")
|
||||
} catch (_: Throwable) {
|
||||
// 落盘失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装(幂等)。要在后台线程调用。progress 会报告阶段,给界面显示。
|
||||
* @return true 表示装好(或本来就装好了)
|
||||
*/
|
||||
fun install(context: Context, progress: (String) -> Unit): Boolean {
|
||||
trace(context, "install() 开始;isInstalled=${isInstalled(context)} stamp=${stampFile(context).exists()}")
|
||||
if (stampFile(context).exists() && isInstalled(context)) {
|
||||
// 已经装过也别直接返回:rc 文件是 App 生成的,升级 App 后要跟着更新
|
||||
writeBashRc(context)
|
||||
progress("Termux 环境已就绪")
|
||||
return true
|
||||
}
|
||||
|
||||
val prefix = prefix(context)
|
||||
if (prefix.exists()) prefix.deleteRecursively()
|
||||
prefix.mkdirs()
|
||||
trace(context, "prefix 准备完成:$prefix")
|
||||
|
||||
return try {
|
||||
progress("正在解压运行环境(约 95 MB,首次会慢一点)…")
|
||||
trace(context, "开始解压 bootstrap")
|
||||
val count = extractBootstrap(context, prefix)
|
||||
trace(context, "解压结束,文件数=$count")
|
||||
if (count < 50) {
|
||||
progress("解压结果不对:只出来 $count 个文件")
|
||||
return false
|
||||
}
|
||||
|
||||
progress("正在建立符号链接…")
|
||||
createSymlinks(prefix)
|
||||
trace(context, "符号链接完成")
|
||||
|
||||
progress("正在准备目录…")
|
||||
File(prefix, "tmp").mkdirs()
|
||||
File(prefix, "var").mkdirs()
|
||||
home(context).mkdirs()
|
||||
writeBashRc(context)
|
||||
|
||||
progress("正在修正脚本的解释器路径…")
|
||||
val fixed = fixShebangs(context)
|
||||
trace(context, "改写了 $fixed 个脚本的 shebang")
|
||||
|
||||
val binCount = File(prefix, "bin").list()?.size ?: 0
|
||||
stampFile(context).writeText("ok")
|
||||
progress("Termux 环境安装完成($binCount 个命令)")
|
||||
trace(context, "安装完成:files=$count bin=$binCount")
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
trace(context, "安装失败:${t.javaClass.simpleName}: ${t.message}")
|
||||
progress("安装失败:${t.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压 bootstrap。
|
||||
*
|
||||
* ★ 这里有个坑:`libtermux-bootstrap.so` **不是纯 zip**,而是
|
||||
* 「1328 字节的 ELF 头 + 一个完整 zip」(Android 要求 lib 下的 so 得像 ELF,
|
||||
* Termux 就把 zip 接在 ELF 头后面)。
|
||||
* `ZipInputStream` 是按本地文件头顺序扫的,在安卓上实测一个条目都读不出来;
|
||||
* 而 `ZipFile` 走的是文件尾的中央目录,能直接跳过前面的 ELF 头 —— 所以先落盘再用 ZipFile。
|
||||
*
|
||||
* 注意注释里千万别写 "lib" 加斜杠星号那种通配(Kotlin 块注释会嵌套,会把后面代码全注释掉)。
|
||||
*/
|
||||
private fun extractBootstrap(context: Context, targetDir: File): Int {
|
||||
val cacheZip = File(context.cacheDir, "termux-bootstrap.zip")
|
||||
try {
|
||||
// ① 从 APK 里把那份 .so 原样拷出来
|
||||
val apk = File(context.applicationInfo.sourceDir)
|
||||
val abi = android.os.Build.SUPPORTED_ABIS.firstOrNull() ?: "arm64-v8a"
|
||||
val candidates = listOf(abi, "arm64-v8a", "x86_64")
|
||||
var copied = false
|
||||
java.util.zip.ZipFile(apk).use { apkZip ->
|
||||
for (candidate in candidates) {
|
||||
val entry = apkZip.getEntry("lib/$candidate/$BOOTSTRAP_LIB") ?: continue
|
||||
Log.i(TAG, "bootstrap 来自 APK: lib/$candidate/$BOOTSTRAP_LIB (${entry.size} 字节)")
|
||||
apkZip.getInputStream(entry).use { input ->
|
||||
cacheZip.outputStream().use { out -> input.copyTo(out, 256 * 1024) }
|
||||
}
|
||||
copied = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!copied) {
|
||||
// 退路:有些打包方式会把 .so 解到 nativeLibraryDir
|
||||
val fromLib = File(context.applicationInfo.nativeLibraryDir, BOOTSTRAP_LIB)
|
||||
if (!fromLib.exists()) throw IllegalStateException("APK 里找不到 $BOOTSTRAP_LIB")
|
||||
fromLib.copyTo(cacheZip, overwrite = true)
|
||||
Log.i(TAG, "bootstrap 来自 nativeLibraryDir")
|
||||
}
|
||||
|
||||
// ② 把 ELF 头切掉,得到纯 zip
|
||||
//
|
||||
// ★ 为什么必须切:安卓的 ZipFile **不会**像桌面 JVM 那样自动跳过前缀,
|
||||
// 它按中央目录里记的偏移去读,读到文件开头是 ELF 就报
|
||||
// "Entry at offset zero has invalid LFH signature 464c457f"
|
||||
// (464c457f 就是 \x7FELF 的小端十六进制)。
|
||||
// 模拟器上碰巧宽松能过,真机 Android 16 直接失败 —— 所以自己切最稳。
|
||||
val pureZip = File(context.cacheDir, "termux-bootstrap-pure.zip")
|
||||
val zipOffset = stripPrefix(cacheZip, pureZip)
|
||||
trace(context, "ELF 前缀 ${zipOffset} 字节,已切掉")
|
||||
|
||||
// ③ 用 ZipFile 读纯 zip
|
||||
var count = 0
|
||||
var skipped = 0
|
||||
java.util.zip.ZipFile(pureZip).use { zip ->
|
||||
val entries = zip.entries()
|
||||
while (entries.hasMoreElements()) {
|
||||
val entry = entries.nextElement()
|
||||
val name = entry.name
|
||||
if (name.startsWith("..") || name.contains("../")) continue
|
||||
val outFile = File(targetDir, name)
|
||||
if (entry.isDirectory) {
|
||||
outFile.mkdirs()
|
||||
continue
|
||||
}
|
||||
val parent = outFile.parentFile
|
||||
if (parent != null && !parent.exists()) parent.mkdirs()
|
||||
|
||||
// ★ 单个文件失败不能把整次安装毁掉:安卓上有个别人为拦的怪名字
|
||||
// (比如 bin/su 会 ENOENT),跳过去照样能用。
|
||||
try {
|
||||
zip.getInputStream(entry).use { input ->
|
||||
FileOutputStream(outFile).use { out -> input.copyTo(out, 256 * 1024) }
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
skipped += 1
|
||||
if (skipped <= 5) {
|
||||
Log.w(
|
||||
TAG,
|
||||
"跳过 $name(${t.javaClass.simpleName}: ${t.message})" +
|
||||
" parent=${parent?.absolutePath} exists=${parent?.exists()}" +
|
||||
" isDir=${parent?.isDirectory}",
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// bin/ lib/ libexec/ 和根目录下的东西要可执行
|
||||
val rel = name.replace('\\', '/')
|
||||
if (rel.startsWith("bin/") || rel.startsWith("lib/") ||
|
||||
rel.startsWith("libexec/") || !rel.contains('/')
|
||||
) {
|
||||
outFile.setExecutable(true, false)
|
||||
}
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "解压完成,$count 个文件(跳过 $skipped 个)")
|
||||
pureZip.delete()
|
||||
return count
|
||||
} finally {
|
||||
cacheZip.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `ELF 头 + zip` 切成纯 zip,返回被切掉的前缀长度。
|
||||
* ZIP 的第一个本地文件头签名是 `PK\x03\x04`;ELF 头只有一千多字节,扫前 64KB 足够。
|
||||
*/
|
||||
private fun stripPrefix(src: File, dst: File): Long {
|
||||
FileInputStream(src).use { input ->
|
||||
val head = ByteArray(64 * 1024)
|
||||
val n = input.read(head)
|
||||
if (n <= 4) throw IllegalStateException("bootstrap 文件太小($n 字节)")
|
||||
|
||||
var offset = -1
|
||||
for (i in 0 until n - 3) {
|
||||
if (head[i] == 0x50.toByte() && head[i + 1] == 0x4b.toByte() &&
|
||||
head[i + 2] == 0x03.toByte() && head[i + 3] == 0x04.toByte()
|
||||
) {
|
||||
offset = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if (offset < 0) throw IllegalStateException("在文件头 64KB 里找不到 ZIP 签名(PK\\x03\\x04)")
|
||||
|
||||
FileOutputStream(dst).use { out ->
|
||||
out.write(head, offset, n - offset)
|
||||
input.copyTo(out, 256 * 1024)
|
||||
}
|
||||
return offset.toLong()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建符号链接。Java 建不了 symlink,只能把上千条 ln -s 拼成脚本交给 /system/bin/sh 执行。
|
||||
* SYMLINKS.txt 里的相对路径是相对 prefix 的,所以 cwd 必须设成 prefix。
|
||||
*/
|
||||
private fun createSymlinks(prefix: File) {
|
||||
val symlinksFile = File(prefix, "SYMLINKS.txt")
|
||||
if (!symlinksFile.exists()) {
|
||||
Log.w(TAG, "没有 SYMLINKS.txt,跳过")
|
||||
return
|
||||
}
|
||||
|
||||
val commands = symlinksFile.readLines()
|
||||
.filter { it.contains(ARROW) }
|
||||
.map { line ->
|
||||
val idx = line.indexOf(ARROW)
|
||||
val target = line.substring(0, idx)
|
||||
val link = line.substring(idx + ARROW.length)
|
||||
"ln -sf '$target' '$link'"
|
||||
}
|
||||
symlinksFile.delete()
|
||||
|
||||
if (commands.isEmpty()) return
|
||||
|
||||
// 一次别塞太多,命令行有长度上限
|
||||
commands.chunked(200).forEach { chunk ->
|
||||
val script = chunk.joinToString(" ; ")
|
||||
val proc = ProcessBuilder("/system/bin/sh", "-c", script)
|
||||
.directory(prefix)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val output = proc.inputStream.bufferedReader().readText()
|
||||
val code = proc.waitFor()
|
||||
if (code != 0) {
|
||||
Log.w(TAG, "建链接返回 $code:${output.take(400)}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写一份我们自己的 bash rc。
|
||||
*
|
||||
* 为什么需要:Termux 的 bash 是带着编译期路径 `/data/data/com.termux/files/usr/etc/profile`
|
||||
* 构建的,而我们的 prefix 是 `/data/user/0/<我们的包名>/files/usr`。
|
||||
* termux-exec 只重写 **exec 的路径**,管不到 bash 自己 open("/etc/profile"),
|
||||
* 所以登录式 bash 一启动就会报 "Permission denied"。
|
||||
*
|
||||
* ★ 这里**故意不去 source Termux 自带的 etc/profile**:
|
||||
* 真机实测 source 之后 bash 会立刻退出,终端上只留一句 "[Process completed]"
|
||||
* (那份 profile 里有一堆 dpkg/init 的假设,在别人的 prefix 下不成立)。
|
||||
* 交互式终端真正需要的变量这里手工设全就够了。
|
||||
*/
|
||||
private fun writeBashRc(context: Context) {
|
||||
val prefix = prefix(context).absolutePath
|
||||
val home = home(context).absolutePath
|
||||
val rc = File(prefix, "etc/doubao.bashrc")
|
||||
rc.parentFile?.mkdirs()
|
||||
rc.writeText(
|
||||
"""
|
||||
# 由豆包 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||
export PREFIX="$prefix"
|
||||
export HOME="$home"
|
||||
export TMPDIR="$prefix/tmp"
|
||||
export PATH="$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin"
|
||||
export LD_LIBRARY_PATH="$prefix/lib"
|
||||
export LD_PRELOAD="$prefix/lib/libtermux-exec.so"
|
||||
export TERM=xterm-256color
|
||||
export LANG=en_US.UTF-8
|
||||
export COLORTERM=truecolor
|
||||
cd "${'$'}HOME" 2>/dev/null || cd /
|
||||
export PS1='\[\e[32m\]\u@termux\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '
|
||||
echo "豆包内置 Termux —— 试试 pkg install python"
|
||||
""".trimIndent() + "\n",
|
||||
Charsets.UTF_8,
|
||||
)
|
||||
trace(context, "已写入 bash rc: ${rc.absolutePath}")
|
||||
}
|
||||
|
||||
/**
|
||||
* 把脚本里 shebang 的硬编码前缀改成我们自己的。
|
||||
*
|
||||
* 为什么必须做:Termux 的 bin 下不少命令(getprop、pkg 之类)是 shell 脚本,
|
||||
* 第一行写死了 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
* 那个路径属于**另一个包**,我们 exec 它会 EACCES ——
|
||||
* 表现是 "bad interpreter: Permission denied"。
|
||||
* termux-exec 只重写 execve 的参数,管不到内核解析 shebang 这一步,所以直接改文件最省事。
|
||||
*/
|
||||
private fun fixShebangs(context: Context): Int {
|
||||
val prefix = prefix(context)
|
||||
val oldPrefix = "/data/data/com.termux/files/usr"
|
||||
val newPrefix = prefix.absolutePath
|
||||
var fixed = 0
|
||||
|
||||
val dirs = listOf(File(prefix, "bin"), File(prefix, "libexec"), File(prefix, "libexec/termux-am"))
|
||||
for (dir in dirs) {
|
||||
val files = dir.listFiles() ?: continue
|
||||
for (file in files) {
|
||||
if (!file.isFile || file.length() > 512 * 1024) continue
|
||||
val head = try {
|
||||
file.inputStream().use { input ->
|
||||
val buf = ByteArray(256)
|
||||
val n = input.read(buf)
|
||||
if (n <= 0) return@use "" else String(buf, 0, n, Charsets.UTF_8)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
continue
|
||||
}
|
||||
if (!head.startsWith("#!$oldPrefix")) continue
|
||||
|
||||
try {
|
||||
val text = file.readText(Charsets.UTF_8)
|
||||
file.writeText(text.replaceFirst(oldPrefix, newPrefix), Charsets.UTF_8)
|
||||
file.setExecutable(true, false)
|
||||
fixed += 1
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "改 shebang 失败:${file.name}", t)
|
||||
}
|
||||
}
|
||||
}
|
||||
return fixed
|
||||
}
|
||||
|
||||
/** 交互式终端应该跑的 shell(配我们自己的 rc) */
|
||||
fun interactiveShellArgs(context: Context): Array<String> =
|
||||
arrayOf("--rcfile", File(prefix(context), "etc/doubao.bashrc").absolutePath, "-i")
|
||||
|
||||
/** 装完之后给内核/工具用的环境变量(Termux 的标准一套) */
|
||||
fun environment(context: Context): Map<String, String> {
|
||||
val prefix = prefix(context).absolutePath
|
||||
val home = home(context).absolutePath
|
||||
val filesDir = context.filesDir.absolutePath
|
||||
val legacy = "/data/data/${context.packageName}/files"
|
||||
return mapOf(
|
||||
"PREFIX" to prefix,
|
||||
"HOME" to home,
|
||||
"TMPDIR" to "$prefix/tmp",
|
||||
"PATH" to "$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin",
|
||||
"LD_LIBRARY_PATH" to "$prefix/lib",
|
||||
// ★ 这个 LD_PRELOAD 是 Termux 能在 Android 上正常跑命令的关键:
|
||||
// 它把二进制里写死的 /data/data/com.termux/files/usr 重写到我们自己的 prefix。
|
||||
// 不开的话 bash 会去找别的 App 的 profile,报 Permission denied。
|
||||
"LD_PRELOAD" to "$prefix/lib/libtermux-exec.so",
|
||||
/**
|
||||
* ★ 下面这两个是 termux-exec 用来确定"真实 prefix"的变量(从它的 .so 里扫出来的符号名):
|
||||
* TERMUX__PREFIX —— 注意是**双下划线**,写成 TERMUX_PREFIX 它不认
|
||||
* TERMUX_APP__DATA_DIR —— 应用数据目录
|
||||
* 少一个路径重写就不生效,表现是 bash 去读 /data/data/com.termux/... 然后权限拒绝。
|
||||
*/
|
||||
"TERMUX__PREFIX" to prefix,
|
||||
"TERMUX__ROOTFS" to "/",
|
||||
"TERMUX_APP__DATA_DIR" to filesDir,
|
||||
"TERMUX_APP__LEGACY_DATA_DIR" to legacy,
|
||||
"TERMUX_APP__PACKAGE_NAME" to context.packageName,
|
||||
"TERMUX_APP__APP_VERSION_NAME" to "0.3.0",
|
||||
"TERMUX_IS_DEBUGGABLE_BUILD" to "1",
|
||||
"LANG" to "en_US.UTF-8",
|
||||
"LC_ALL" to "en_US.UTF-8",
|
||||
"TERM" to "xterm-256color",
|
||||
"TZ" to "Asia/Shanghai",
|
||||
"ANDROID_ROOT" to "/system",
|
||||
"ANDROID_DATA" to "/data",
|
||||
"EXTERNAL_STORAGE" to "/sdcard",
|
||||
"TERMUX_VERSION" to "0.118.3",
|
||||
"TERMUX_MAIN_PACKAGE_FORMAT" to "debian",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
|
||||
/**
|
||||
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||
*
|
||||
* 为什么不用 `Runtime.exec` 拼一个假终端:那样跑不了 vim/top、没有颜色、没有方向键,
|
||||
* 也不是 tty,很多命令行为会不一样。Termux 这套是完整 pty + ANSI 渲染。
|
||||
*/
|
||||
class TermuxTerminal(private val context: Context) {
|
||||
|
||||
@Volatile
|
||||
var session: TerminalSession? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* 开一个登录 shell。Termux 的标准做法就是跑 `$PREFIX/bin/login`,
|
||||
* 它会按 /etc/profile 把 PATH、PS1、动态库路径都准备好。
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val env = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
|
||||
val client = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(context, "终端会话结束,退出码=${finishedSession.exitStatus}")
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线,用 Termux 的默认值 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
val created = TerminalSession(
|
||||
"$prefix/bin/bash",
|
||||
home,
|
||||
// 用我们自己的 rc:Termux 的 bash 带的是编译期路径 /data/data/com.termux/...,
|
||||
// 直接当登录 shell 跑会去读别的包的 profile,报权限拒绝
|
||||
TermuxInstaller.interactiveShellArgs(context),
|
||||
env,
|
||||
2000,
|
||||
client,
|
||||
)
|
||||
session = created
|
||||
return created
|
||||
}
|
||||
|
||||
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||
fun viewClient(): TerminalViewClient = object : TerminalViewClient {
|
||||
override fun onScale(scale: Float): Float = scale
|
||||
override fun onSingleTapUp(e: MotionEvent) {
|
||||
// 点一下就把软键盘叫出来,手机上最常用
|
||||
(e.source)
|
||||
}
|
||||
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = false
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = true
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) {}
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = false
|
||||
override fun readAltKey(): Boolean = false
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {}
|
||||
// TerminalViewClient 也继承了 Logger,这 7 个必须实现
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
try {
|
||||
session?.finishIfRunning()
|
||||
} catch (t: Throwable) {
|
||||
Log.w("DoubaoTermux", "关闭会话失败", t)
|
||||
}
|
||||
session = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 给 Compose 的 AndroidView 用:把 view 绑上会话 */
|
||||
fun bindSession(view: TerminalView, terminal: TermuxTerminal, onTitle: (String) -> Unit, onExit: () -> Unit) {
|
||||
val s = terminal.session ?: terminal.createSession(onTitle, onExit)
|
||||
if (view.currentSession !== s) {
|
||||
view.attachSession(s)
|
||||
}
|
||||
view.requestFocus()
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
import com.doubao.lynxclone.data.KernelClient
|
||||
|
||||
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
|
||||
@Composable
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel =
|
||||
viewModel(factory = object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T = AppViewModel(client) as T
|
||||
})
|
||||
|
||||
@Composable
|
||||
fun AppRoot(
|
||||
client: KernelClient,
|
||||
termuxReady: Boolean,
|
||||
termuxStatus: String,
|
||||
onInstallTermux: () -> Unit,
|
||||
) {
|
||||
val vm = rememberAppViewModel(client)
|
||||
LaunchedEffect(Unit) { vm.refresh() }
|
||||
|
||||
// 提示条 2.5 秒后自动消失
|
||||
LaunchedEffect(vm.hint) {
|
||||
if (vm.hint.isNotBlank()) {
|
||||
kotlinx.coroutines.delay(2500)
|
||||
vm.hint = ""
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg())
|
||||
// edge-to-edge 下得自己吃系统栏/输入法内边距
|
||||
.windowInsetsPadding(WindowInsets.safeDrawing),
|
||||
) {
|
||||
// 页面切换带淡入 + 轻微位移,不然是"啪"一下就换了
|
||||
AnimatedContent(
|
||||
targetState = vm.screen,
|
||||
transitionSpec = {
|
||||
val forward = targetState != Screen.Chat
|
||||
val dir = if (forward) 1 else -1
|
||||
(slideInHorizontally(tween(240)) { it / 14 * dir } + fadeIn(tween(200))) togetherWith
|
||||
(slideOutHorizontally(tween(200)) { -it / 14 * dir } + fadeOut(tween(150)))
|
||||
},
|
||||
label = "screen",
|
||||
) { screen ->
|
||||
when (screen) {
|
||||
Screen.Chat -> ChatScreen(vm)
|
||||
Screen.Profile -> ProfileScreen(vm)
|
||||
Screen.Settings -> SettingsScreen(vm)
|
||||
Screen.Skills -> SkillsScreen(vm)
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
Screen.Meetings -> MeetingsScreen(vm)
|
||||
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||
}
|
||||
}
|
||||
|
||||
// 抽屉:左边滑进来 + 遮罩淡入
|
||||
AnimatedVisibility(
|
||||
visible = vm.drawerOpen,
|
||||
enter = slideInHorizontally(tween(260)) { -it } + fadeIn(tween(180)),
|
||||
exit = slideOutHorizontally(tween(220)) { -it } + fadeOut(tween(150)),
|
||||
) {
|
||||
DrawerOverlay(vm)
|
||||
}
|
||||
|
||||
if (vm.hint.isNotBlank()) {
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(24.dp)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(Color(0xE61F2329))
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 抽屉 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DrawerOverlay(vm: AppViewModel) {
|
||||
Row(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxHeight()
|
||||
.width(300.dp)
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 20.dp, end = 16.dp, top = 18.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("豆包", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Icon(
|
||||
Icons.Filled.Search, "搜索", tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable { vm.showHint("搜索还没做") },
|
||||
)
|
||||
}
|
||||
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.AccountTree, "会议模式") {
|
||||
vm.screen = Screen.Meetings; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Terminal, "终端") {
|
||||
vm.screen = Screen.Terminal; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Settings, "设置") {
|
||||
vm.screen = Screen.Settings; vm.drawerOpen = false
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
ConversationRow(vm, vm.state.conversations[i])
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.screen = Screen.Profile; vm.drawerOpen = false }
|
||||
.padding(horizontal = 20.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).background(Doubao.Blue),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(vm.settings.nickname.take(1), color = Color.White, fontSize = 14.sp)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(vm.settings.nickname, fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.background(Doubao.Scrim)
|
||||
.clickable { vm.drawerOpen = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerItem(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
trailing: String = "",
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val bg by animateColorAsState(
|
||||
targetValue = if (pressed) doubaoCard() else Color.Transparent,
|
||||
animationSpec = tween(120),
|
||||
label = "itemBg",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Text(label, fontSize = 16.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (trailing.isNotBlank()) {
|
||||
Text(trailing, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConversationRow(vm: AppViewModel, conv: Conversation) {
|
||||
val active = conv.id == vm.activeConversationId
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (active) doubaoCard() else Color.Transparent)
|
||||
.clickable { vm.openConversation(conv.id) }
|
||||
.padding(horizontal = 10.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(RoundedCornerShape(19.dp)).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(conv.title.take(1), color = Doubao.Blue, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(conv.title, fontSize = 15.sp, color = doubaoText(), maxLines = 1)
|
||||
Text(
|
||||
conv.preview.ifBlank { "还没有消息" },
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp).clickable { vm.deleteConversation(conv) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 文案小工具 ------------------------------ */
|
||||
|
||||
fun shortModel(model: String): String = when {
|
||||
model.isBlank() -> "未设置"
|
||||
model.startsWith("ep-") -> "接入点 ${model.take(8)}"
|
||||
model.startsWith("doubao-seed-2-1-pro") -> "豆包 Pro"
|
||||
model.startsWith("doubao-seed-1-8") -> "豆包 1.8"
|
||||
model.startsWith("doubao-seed-1-6") -> "豆包 1.6"
|
||||
model.startsWith("doubao") -> "豆包"
|
||||
model.startsWith("deepseek-r1") -> "DeepSeek R1"
|
||||
model.startsWith("deepseek") -> "DeepSeek"
|
||||
model.startsWith("gpt-5") -> if (model.contains("mini")) "GPT-5 mini" else "GPT-5"
|
||||
model.startsWith("gpt-4o") -> if (model.contains("mini")) "GPT-4o mini" else "GPT-4o"
|
||||
else -> if (model.length > 16) model.take(14) + "…" else model
|
||||
}
|
||||
|
||||
fun thinkingLabel(level: String): String = when (level) {
|
||||
"off" -> "快速"
|
||||
"low" -> "低"
|
||||
"medium" -> "中"
|
||||
"high" -> "深度思考"
|
||||
else -> "自动"
|
||||
}
|
||||
@@ -1,508 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.AppState
|
||||
import com.doubao.lynxclone.data.Attachment
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
import com.doubao.lynxclone.data.KernelClient
|
||||
import com.doubao.lynxclone.data.MeetingEvent
|
||||
import com.doubao.lynxclone.data.MeetingMeta
|
||||
import com.doubao.lynxclone.data.StreamEvent
|
||||
import com.doubao.lynxclone.data.ToolTrace
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */
|
||||
enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal, Meetings }
|
||||
|
||||
/**
|
||||
* 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。
|
||||
*/
|
||||
class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
var state by mutableStateOf(AppState())
|
||||
private set
|
||||
var screen by mutableStateOf(Screen.Chat)
|
||||
var drawerOpen by mutableStateOf(false)
|
||||
var loading by mutableStateOf(true)
|
||||
var bootError by mutableStateOf("")
|
||||
var hint by mutableStateOf("")
|
||||
|
||||
val messages = mutableStateListOf<ChatMessage>()
|
||||
var activeConversationId by mutableStateOf("c_main")
|
||||
var streaming by mutableStateOf(false)
|
||||
private set
|
||||
var draft by mutableStateOf("")
|
||||
val attachments = mutableStateListOf<Attachment>()
|
||||
/** 正在看「思考过程」的消息下标;-1 表示没开 */
|
||||
var thinkingIndex by mutableStateOf(-1)
|
||||
/** 模型 / 思考强度面板(底部升起) */
|
||||
var modelPickerOpen by mutableStateOf(false)
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
val settings get() = state.settings
|
||||
val agents: List<Agent> get() = state.agents
|
||||
val activeAgent: Agent? get() = state.activeAgent
|
||||
|
||||
fun refresh(onDone: (() -> Unit)? = null) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
state = withContext(Dispatchers.IO) { client.state() }
|
||||
bootError = ""
|
||||
} catch (e: Exception) {
|
||||
bootError = e.message ?: "连不上内核"
|
||||
} finally {
|
||||
loading = false
|
||||
onDone?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun showHint(text: String) {
|
||||
hint = text
|
||||
}
|
||||
|
||||
/** 点赞/点踩:只改本地状态(没接后端反馈接口),点同一个再点一次就取消 */
|
||||
fun onFeedback(index: Int, kind: String) {
|
||||
if (index !in messages.indices) return
|
||||
val current = messages[index]
|
||||
messages[index] = current.copy(feedback = if (current.feedback == kind) null else kind)
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动朗读开关。
|
||||
*
|
||||
* 声音那边由 SpeechController 立即生效;这里负责**落盘**,
|
||||
* 否则退出 App 再进来又变回关的,用户会以为没保存上。
|
||||
*/
|
||||
fun setAutoRead(on: Boolean) {
|
||||
saveSettings(mapOf("speech" to mapOf("autoRead" to on)))
|
||||
}
|
||||
|
||||
/* ------------------------------ 会话 ------------------------------ */
|
||||
|
||||
fun openConversation(id: String) {
|
||||
activeConversationId = id
|
||||
drawerOpen = false
|
||||
screen = Screen.Chat
|
||||
viewModelScope.launch {
|
||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||
messages.clear()
|
||||
messages.addAll(list)
|
||||
}
|
||||
}
|
||||
|
||||
fun newTopic() {
|
||||
viewModelScope.launch {
|
||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||
refresh()
|
||||
if (conv != null) openConversation(conv.id) else {
|
||||
messages.clear()
|
||||
activeConversationId = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteConversation(conv: Conversation) {
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.deleteConversation(conv.id) } }
|
||||
refresh()
|
||||
showHint("已删除「${conv.title}」")
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 发消息 ------------------------------ */
|
||||
|
||||
fun send() {
|
||||
val text = draft.trim()
|
||||
if (text.isEmpty() && attachments.isEmpty()) return
|
||||
if (streaming) return
|
||||
|
||||
val files = attachments.toList()
|
||||
draft = ""
|
||||
attachments.clear()
|
||||
runChat(text, files)
|
||||
}
|
||||
|
||||
fun regenerate() {
|
||||
if (streaming) return
|
||||
val lastUser = messages.lastOrNull { it.role == "user" } ?: return
|
||||
// 去掉最后一条助手回复再重来
|
||||
while (messages.isNotEmpty() && messages.last().role != "user") messages.removeAt(messages.size - 1)
|
||||
runChat(lastUser.content, emptyList())
|
||||
}
|
||||
|
||||
private fun runChat(text: String, files: List<Attachment>) {
|
||||
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||
streaming = true
|
||||
|
||||
val cancel = AtomicBoolean(false)
|
||||
chatJob = cancel
|
||||
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
client.chat(
|
||||
conversationId = activeConversationId.ifBlank { "c_main" },
|
||||
message = text,
|
||||
attachments = files,
|
||||
agentId = activeAgent?.id,
|
||||
cancelled = cancel,
|
||||
) { event -> onStreamEvent(event) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
|
||||
showHint("出错了:${e.message}")
|
||||
} finally {
|
||||
streaming = false
|
||||
chatJob = null
|
||||
patchLast { it.copy(pending = false) }
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
|
||||
private fun onStreamEvent(event: StreamEvent) {
|
||||
viewModelScope.launch {
|
||||
when (event) {
|
||||
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
|
||||
is StreamEvent.Reasoning -> patchLast { it.copy(reasoning = it.reasoning + event.text) }
|
||||
is StreamEvent.ToolCall -> patchLast {
|
||||
it.copy(toolTrace = it.toolTrace + ToolTrace(id = event.id, name = event.name))
|
||||
}
|
||||
is StreamEvent.ToolResult -> patchLast { msg ->
|
||||
msg.copy(toolTrace = msg.toolTrace.map {
|
||||
if (it.id == event.id) it.copy(ok = event.ok, result = event.result) else it
|
||||
})
|
||||
}
|
||||
is StreamEvent.Failure -> {
|
||||
val text = if (event.hint.isNotBlank()) "出错了:${event.message}|${event.hint}" else "出错了:${event.message}"
|
||||
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { text }) }
|
||||
showHint(text)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun patchLast(fn: (ChatMessage) -> ChatMessage) {
|
||||
for (i in messages.indices.reversed()) {
|
||||
if (messages[i].role == "assistant") {
|
||||
messages[i] = fn(messages[i])
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 设置 / 工具 ------------------------------ */
|
||||
|
||||
fun saveSettings(patch: Map<String, Any?>, onDone: (() -> Unit)? = null) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val json = patchToJson(patch)
|
||||
state = withContext(Dispatchers.IO) { client.saveSettings(json) }
|
||||
showHint("已保存")
|
||||
} catch (e: Exception) {
|
||||
showHint("保存失败:${e.message}")
|
||||
} finally {
|
||||
onDone?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setThinkingLevel(level: String) = saveSettings(mapOf("thinkingLevel" to level))
|
||||
fun setModel(model: String) = saveSettings(mapOf("model" to model))
|
||||
fun runTool(name: String, args: JSONObject, onResult: (Boolean, String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val res = withContext(Dispatchers.IO) { client.runTool(name, args) }
|
||||
onResult(res.ok, if (res.ok) res.result.toString() else res.error)
|
||||
} catch (e: Exception) {
|
||||
onResult(false, e.message ?: "执行失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveMcpConfig(text: String, onResult: (Boolean, String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val json = withContext(Dispatchers.IO) { client.saveMcpConfig(text) }
|
||||
refresh()
|
||||
val results = json.optJSONArray("results")
|
||||
val summary = if (results != null) {
|
||||
(0 until results.length()).joinToString(",") { i ->
|
||||
val item = results.optJSONObject(i) ?: return@joinToString ""
|
||||
val ok = item.optBoolean("ok")
|
||||
"${item.optString("name")}${if (ok) "✓" else "✗" + item.optString("error")}"
|
||||
}
|
||||
} else ""
|
||||
onResult(json.optBoolean("ok"), if (json.optBoolean("ok")) "已重连:$summary" else json.optString("error"))
|
||||
} catch (e: Exception) {
|
||||
onResult(false, e.message ?: "保存失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 简化的协程入口。
|
||||
*
|
||||
* 页面里到处写 `viewModelScope.launch { try { … } catch (e) { showHint(…) } }`
|
||||
* 太啰嗦,而且很容易漏 catch(漏了就是静默失败,最难查)。
|
||||
* 统一走这里:出错一律弹提示。
|
||||
*/
|
||||
fun launch(block: suspend () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
block()
|
||||
} catch (e: Exception) {
|
||||
showHint(e.message ?: "操作失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 会议模式 ------------------------------ */
|
||||
|
||||
/** 编辑器要用的元信息(节点类型 / 判断条件 / 可用智能体)。进页面时拉一次。 */
|
||||
var meetingMeta by mutableStateOf(MeetingMeta())
|
||||
private set
|
||||
|
||||
private var meetingMetaLoaded = false
|
||||
|
||||
fun ensureMeetingMeta() {
|
||||
if (meetingMetaLoaded) return
|
||||
launch {
|
||||
meetingMeta = client.meetingMeta()
|
||||
meetingMetaLoaded = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新拉一次 meta。
|
||||
*
|
||||
* ★ 导入/删掉节点文件之后必须调它 —— 自定义节点是**运行期从磁盘读**的,
|
||||
* 不重拉的话界面上还是旧的那一套引脚,用户会以为导入没生效。
|
||||
* (ensureMeetingMeta 有 loaded 缓存,所以这里要单独一个不走缓存的入口。)
|
||||
*/
|
||||
fun reloadMeetingMeta() {
|
||||
launch {
|
||||
meetingMeta = client.meetingMeta()
|
||||
meetingMetaLoaded = true
|
||||
}
|
||||
}
|
||||
|
||||
/** 列出 nodes/ 里的自定义节点文件 */
|
||||
suspend fun nodeFiles(): org.json.JSONArray = client.nodeFiles()
|
||||
|
||||
/** 读一个自定义节点的源码 */
|
||||
suspend fun readNode(file: String): org.json.JSONObject = client.readNode(file)
|
||||
|
||||
/** 导入一个自定义节点文件;成功返回节点名,失败抛异常(错误信息给用户看) */
|
||||
suspend fun importNodeFile(file: String, code: String): String {
|
||||
val res = client.importNode(file, code)
|
||||
reloadMeetingMeta()
|
||||
return res.optString("label").ifBlank { file }
|
||||
}
|
||||
|
||||
/** 删掉一个自定义节点文件 */
|
||||
suspend fun deleteNodeFile(file: String) {
|
||||
client.deleteNode(file)
|
||||
reloadMeetingMeta()
|
||||
}
|
||||
|
||||
private var meetingJob: Job? = null
|
||||
|
||||
/**
|
||||
* 跑一场会议。事件边收边回调。
|
||||
*
|
||||
* 同时只能跑一场:再点一次运行会先掐掉上一场 —— 否则两个图同时往
|
||||
* 同一批节点上写输出,界面上会看到内容互相覆盖。
|
||||
*/
|
||||
fun runMeeting(
|
||||
meetingId: String,
|
||||
input: String,
|
||||
onEvent: (MeetingEvent) -> Unit,
|
||||
onError: (String) -> Unit,
|
||||
) {
|
||||
meetingJob?.cancel()
|
||||
val cancelled = AtomicBoolean(false)
|
||||
meetingJob = viewModelScope.launch {
|
||||
// ★ 事件在 IO 线程上产生,但**必须回主线程再交给界面**。
|
||||
//
|
||||
// 之前直接在 IO 线程里改 Compose 状态(mutableStateMapOf),
|
||||
// 结果是"日志里事件全收到了、节点上就是不显示"—— 状态写进去了,
|
||||
// 界面却不一定重组。用 Channel 过一道,既保证在主线程执行,
|
||||
// 又保证顺序(trySend 是有序的)。
|
||||
val events = Channel<MeetingEvent>(Channel.UNLIMITED)
|
||||
val consumer = launch {
|
||||
for (ev in events) onEvent(ev)
|
||||
}
|
||||
try {
|
||||
val seen = LinkedHashMap<String, Int>()
|
||||
client.runMeeting(meetingId, input, cancelled) { ev ->
|
||||
seen[ev.type] = (seen[ev.type] ?: 0) + 1
|
||||
events.trySend(ev)
|
||||
}
|
||||
android.util.Log.i(
|
||||
"DoubaoMeeting",
|
||||
"事件统计: " + seen.entries.joinToString(", ") { "${it.key}=${it.value}" },
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
events.close()
|
||||
consumer.cancel()
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
onError(e.message ?: "运行失败")
|
||||
} finally {
|
||||
events.close()
|
||||
}
|
||||
consumer.join()
|
||||
}
|
||||
}
|
||||
|
||||
fun stopMeeting() {
|
||||
meetingJob?.cancel()
|
||||
meetingJob = null
|
||||
}
|
||||
|
||||
fun saveAgent(id: String?, draft: Agent, onDone: () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val body = JSONObject()
|
||||
.put("name", draft.name)
|
||||
.put("avatar", draft.avatar)
|
||||
.put("systemPrompt", draft.systemPrompt)
|
||||
// 内核字段叫 tagline;UI 上叫"一句话介绍"
|
||||
.put("tagline", draft.greeting)
|
||||
// 智能体自己的模型与语音(留空 = 继承全局)
|
||||
.put("provider", draft.provider)
|
||||
.put("model", draft.model)
|
||||
.put("baseUrl", draft.baseUrl)
|
||||
.put("ttsEngine", draft.ttsEngine)
|
||||
.put("ttsVoice", draft.ttsVoice)
|
||||
// 0 = 跟随全局。语速合法范围是 0.5~2.0,0 不可能是有效值
|
||||
if (draft.ttsSpeed > 0) body.put("ttsSpeed", draft.ttsSpeed)
|
||||
withContext(Dispatchers.IO) {
|
||||
if (id.isNullOrBlank()) client.createAgent(body) else client.updateAgent(id, body)
|
||||
}
|
||||
refresh()
|
||||
onDone()
|
||||
} catch (e: Exception) {
|
||||
showHint("保存失败:${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAgent(id: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.deleteAgent(id) } }
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
fun useAgent(id: String) {
|
||||
saveSettings(mapOf("activeAgentId" to id))
|
||||
}
|
||||
|
||||
/* ------------------------------ 附件 ------------------------------ */
|
||||
|
||||
fun addAttachment(file: Attachment) {
|
||||
if (attachments.none { it.id == file.id }) attachments.add(file)
|
||||
}
|
||||
|
||||
fun removeAttachment(id: String) {
|
||||
attachments.removeAll { it.id == id }
|
||||
}
|
||||
|
||||
fun uploadAndAttach(name: String, mime: String, bytes: ByteArray) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val file = withContext(Dispatchers.IO) { client.uploadFile(name, mime, bytes, false) }
|
||||
// uploadFile 现在失败会抛异常并带上内核原话,所以走到这儿基本就是成功;
|
||||
// 留个兜底是因为万一内核换了个返回形状,也不能静默什么都不做
|
||||
if (file != null) {
|
||||
addAttachment(file)
|
||||
showHint("已添加 ${file.name}")
|
||||
} else {
|
||||
showHint("上传失败:内核没有返回文件信息")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
showHint("上传失败:${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 从内核拉待处理附件(比如 Termux 里刚生成的文件) */
|
||||
fun syncPendingUploads() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val json = withContext(Dispatchers.IO) { client.state() }
|
||||
state = json
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 工具权限:切模式 / 勾白名单 */
|
||||
fun saveSecurity(mode: String, allow: List<String>) {
|
||||
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
||||
saveSettings(mapOf("security" to json))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把补丁 Map 转成 JSONObject。
|
||||
*
|
||||
* ★ 为什么必须显式递归转换,不能直接 `json.put(k, mapOf(...))`:
|
||||
*
|
||||
* Android 的 org.json **不会**把 `Map` 自动当成 JSON 对象 —— `put(String, Object)`
|
||||
* 只是把 Map 原样塞进内部表,`toString()` 时按普通对象处理,
|
||||
* 于是发出去的是 `{"speech":"{autoRead=true}"}`:值是**字符串**而不是对象。
|
||||
*
|
||||
* 内核那边 `speech` 本来是个 dict,被字符串覆盖之后,之后**每一次**读配置
|
||||
* (`{**默认, **字符串}`)都会抛 TypeError,`/api/state` 从此一直返回
|
||||
* `{"error":"'str' object is not a mapping"}`;而 App 把这个错误 JSON 解析成了
|
||||
* 「全默认状态」且不抛异常 —— 表现就是:
|
||||
* **点一下语音按钮,模型变"未设置"、昵称变"我"、会话列表全空,还弹"已保存"。**
|
||||
*
|
||||
* 这个坑很隐蔽:只有"嵌套对象"才会触发,而在此之前 App 从没发过嵌套补丁。
|
||||
*/
|
||||
fun patchToJson(patch: Map<String, Any?>): JSONObject {
|
||||
val json = JSONObject()
|
||||
for ((key, value) in patch) {
|
||||
json.put(key, toJsonValue(value))
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
private fun toJsonValue(value: Any?): Any = when (value) {
|
||||
null -> JSONObject.NULL
|
||||
is JSONObject, is JSONArray -> value
|
||||
is Map<*, *> -> {
|
||||
val obj = JSONObject()
|
||||
for ((k, v) in value) obj.put(k.toString(), toJsonValue(v))
|
||||
obj
|
||||
}
|
||||
is List<*> -> {
|
||||
val arr = JSONArray()
|
||||
for (item in value) arr.put(toJsonValue(item))
|
||||
arr
|
||||
}
|
||||
else -> value
|
||||
}
|
||||
@@ -1,874 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.provider.OpenableColumns
|
||||
import android.util.Log
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.doubao.lynxclone.speech.SpeechController
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val TAG = "ChatScreen"
|
||||
|
||||
/**
|
||||
* 附件大小上限,和内核对齐:uploads.COPY_LIMIT 是 100MB,
|
||||
* 而 base64 会让体积涨 1/3,正好卡在内核 /api/upload 那条 150MB 的请求体上限内。
|
||||
* 客户端先挡一道,免得几百 MB 的流量白传一趟再被拒。
|
||||
*
|
||||
* ⚠ 内存:读进来是 100MB 的 ByteArray,再 base64 成 133MB 的字符串,
|
||||
* 峰值两百多 MB。低端机上大文件有被系统杀掉的风险 —— 真要传超大文件,
|
||||
* 正确做法是分片上传,不是继续抬这个数。
|
||||
*/
|
||||
private const val MAX_UPLOAD_BYTES = 100 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* 对话页。
|
||||
*
|
||||
* 视觉对着豆包真机截图抠的:纯白底、顶部三段式(左右图标 + 居中智能体名)、
|
||||
* 大头像 + 灰色问候气泡、白底描边快捷胶囊、输入框是大圆角描边胶囊、发送键是蓝色圆钮。
|
||||
* 动效:气泡淡入上移、思考面板从底部升起、typing 三点跳动、按钮按下回弹。
|
||||
*/
|
||||
@Composable
|
||||
private fun ScrollToBottomChip(
|
||||
visible: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn() + slideInVertically { it / 2 },
|
||||
exit = fadeOut() + slideOutVertically { it / 2 },
|
||||
modifier = modifier,
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
color = doubaoCard(),
|
||||
border = BorderStroke(1.dp, doubaoBorder()),
|
||||
shadowElevation = 3.dp,
|
||||
onClick = onClick,
|
||||
) {
|
||||
Row(
|
||||
Modifier.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown,
|
||||
"回到底部",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(3.dp))
|
||||
Text("回到底部", color = Doubao.Blue, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ChatScreen(vm: AppViewModel) {
|
||||
val agent = vm.activeAgent
|
||||
val listState = rememberLazyListState()
|
||||
val context = LocalContext.current
|
||||
|
||||
// ★ 必须声明在 picker 之前:picker 的回调要捕获它
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// ★ 用 OpenDocument 而不是 GetContent。
|
||||
//
|
||||
// GetContent 走的是 ACTION_GET_CONTENT —— **任何 App 都能注册这个 intent**。
|
||||
// 实测在真机上点「附件」直接打开了豆包 App 的拍照界面
|
||||
// (com.larus.nova/…CameraCaptureActivity),压根选不到文件,
|
||||
// 这就是"无法上传文件"的直接原因。
|
||||
//
|
||||
// OpenDocument 走 ACTION_OPEN_DOCUMENT,只有系统文档提供者(文件/相册)能响应,
|
||||
// 抢不走;顺带还拿到长期可读权限。
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
// 读文件放 IO 线程:手机上随手一张照片就几 MB,在主线程 readBytes
|
||||
// 轻则掉帧重则 ANR。回调本身是在主线程跑的。
|
||||
val picked = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val resolver = context.contentResolver
|
||||
// 文件名必须查 OpenableColumns:文档 URI 的 lastPathSegment 是
|
||||
// "image:1234" 这种内部 id,不是文件名,直接拿来当文件名会很难看
|
||||
val display = runCatching {
|
||||
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||
}.getOrNull()
|
||||
val name = display?.takeIf { it.isNotBlank() }
|
||||
?: uri.lastPathSegment?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
|
||||
?: "upload"
|
||||
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
Log.i(TAG, "选到文件 name=$name mime=$mime size=${bytes?.size ?: -1}")
|
||||
Triple(name, mime, bytes)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "读文件失败", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
if (picked == null) {
|
||||
vm.showHint("读取文件失败,换个文件试试")
|
||||
return@launch
|
||||
}
|
||||
val (name, mime, bytes) = picked
|
||||
// 以前 bytes 为 null 时是**静默什么都不做**的 —— 用户点了半天没反应也没提示。
|
||||
// 每种失败都得说清楚。
|
||||
when {
|
||||
bytes == null -> vm.showHint("打不开这个文件(可能已被移动或没有权限)")
|
||||
bytes.isEmpty() -> vm.showHint("「$name」是空文件")
|
||||
bytes.size > MAX_UPLOAD_BYTES ->
|
||||
vm.showHint("「$name」${bytes.size / 1024 / 1024}MB,超过了 ${MAX_UPLOAD_BYTES / 1024 / 1024}MB 上限")
|
||||
else -> vm.uploadAndAttach(name, mime, bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
// OpenDocument 要的是 MIME 数组,不是单个字符串
|
||||
val onPickFile: () -> Unit = { picker.launch(arrayOf("*/*")) }
|
||||
|
||||
// ---------------- 语音 ----------------
|
||||
val speech = remember { SpeechController(context, vm.client, scope) }
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { speech.release() }
|
||||
}
|
||||
// 设置里的开关同步到控制器
|
||||
LaunchedEffect(vm.state.speech.autoRead) { speech.autoRead = vm.state.speech.autoRead }
|
||||
// 控制器自己产生的提示(云端失败、没听清…)也走统一的提示条
|
||||
LaunchedEffect(speech.notice) {
|
||||
if (speech.notice.isNotBlank()) {
|
||||
vm.showHint(speech.notice)
|
||||
speech.notice = ""
|
||||
}
|
||||
}
|
||||
|
||||
// 录音权限:用户第一次点麦克风时才要,不在启动时要
|
||||
val micPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) speech.startRecording() else vm.showHint("没有录音权限,去系统设置里给一下")
|
||||
}
|
||||
val onMic: () -> Unit = {
|
||||
when {
|
||||
speech.recording -> speech.stopRecording { text -> vm.draft = text }
|
||||
speech.transcribing -> vm.showHint("还在识别上一段…")
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
|
||||
== PackageManager.PERMISSION_GRANTED -> speech.startRecording()
|
||||
else -> micPermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}
|
||||
|
||||
// 自动朗读:最后一条回复从「进行中」变成「已落地」时念出来
|
||||
//
|
||||
// ★ key 里**不能带 content.length**。带上它的话,流式过程中的每一次增量、
|
||||
// 以及回复落地后 vm.refresh() 把消息换成本地存储版本,都会让这个 effect 重跑;
|
||||
// 而 speak() 对"同一条 + 正在播"的语义是**停止**(手动再点一次就是停),
|
||||
// 于是每重跑一次就把朗读掐掉一次 —— 表现就是"读一半就不读了、时长不定"。
|
||||
// 这里只留 size + pending:只在"多了一条消息 / 它从进行中变成完成"时重跑。
|
||||
val lastMsg = vm.messages.lastOrNull()
|
||||
val lastDoneKey = lastMsg?.let { "${vm.messages.size}:${it.pending}" }
|
||||
LaunchedEffect(lastDoneKey) {
|
||||
val msg = vm.messages.lastOrNull() ?: return@LaunchedEffect
|
||||
if (msg.role == "assistant" && !msg.pending && !msg.error && msg.content.isNotBlank()) {
|
||||
// 内容还在变(流式)时别念,等它稳定一下
|
||||
delay(600)
|
||||
val now = vm.messages.lastOrNull()
|
||||
if (now === msg && !now.pending && now.content == msg.content) {
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 新消息 / 流式增量都滚到底,但**只在用户本来就贴着底部时**才跟。
|
||||
//
|
||||
// ★ 这里曾经有两个叠在一起的毛病,表现是"输出过长的回答时拉不下来":
|
||||
// 1. animateScrollToItem(index) 是把这一项的**顶部**对齐到视口顶部。
|
||||
// 长回答比一屏高得多,所以它压根没"滚到底",只是回到那条回答的开头。
|
||||
// 2. 流式输出时 content.length 每一帧都在变 → 这个 effect 每一帧重跑 →
|
||||
// 用户刚往下滑一点就被拽回开头,等于根本滑不动。
|
||||
// 现在:贴着底部才跟;跟的时候用 scrollToItem + 大 offset 滚到**内容末尾**;
|
||||
// 用户自己往上翻了就完全不打扰(要回底部有下面的按钮)。
|
||||
val atBottom by remember {
|
||||
derivedStateOf {
|
||||
val info = listState.layoutInfo
|
||||
val last = info.visibleItemsInfo.lastOrNull() ?: return@derivedStateOf true
|
||||
last.index >= vm.messages.size - 1 &&
|
||||
last.offset + last.size <= info.viewportEndOffset + 24
|
||||
}
|
||||
}
|
||||
val contentLen = vm.messages.lastOrNull()?.content?.length ?: 0
|
||||
LaunchedEffect(vm.messages.size, contentLen) {
|
||||
if (vm.messages.isEmpty() || !atBottom) return@LaunchedEffect
|
||||
// 不用 animate:流式时每帧都要跟,动画会互相打架,看起来就是抖
|
||||
listState.scrollToItem(vm.messages.size - 1, Int.MAX_VALUE)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (vm.messages.isEmpty()) {
|
||||
val tagline = agent?.greeting.orEmpty().trim()
|
||||
val looksLikeSentence = tagline.length >= 12 &&
|
||||
(tagline.endsWith("。") || tagline.endsWith("!") ||
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
item { AppearOnce { HeroSection(greeting) } }
|
||||
}
|
||||
items(vm.messages.size) { index ->
|
||||
AppearOnce(offsetY = 10.dp) {
|
||||
MessageItem(vm, index, vm.messages[index], speech)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 「回到底部」:长回答往上翻之后,得有个一键回去的路。
|
||||
// 只在用户确实翻上去了、且内容装不下一屏时才出现,平时不占地方。
|
||||
//
|
||||
// ★ 这里必须抽成独立 composable,不能直接在这儿写 AnimatedVisibility:
|
||||
// 我们现在在 Box 里,但外层还有个 Column,Kotlin 会解析到
|
||||
// ColumnScope.AnimatedVisibility 那个重载,报"不能在这个上下文调用"。
|
||||
// 放到一个没有 receiver 的函数里,就只会解析到顶层那个。
|
||||
ScrollToBottomChip(
|
||||
visible = !atBottom && vm.messages.isNotEmpty(),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp),
|
||||
) {
|
||||
scope.launch { listState.animateScrollToItem(vm.messages.size - 1, Int.MAX_VALUE) }
|
||||
}
|
||||
}
|
||||
|
||||
if (vm.messages.isEmpty()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
listOf("对话", "AI创作", "出行用豆包", "豆包").forEach { label ->
|
||||
DoubaoPill(text = label, onClick = { vm.draft = label })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
|
||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||
AnimatedVisibility(
|
||||
visible = thinkingVisible,
|
||||
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
|
||||
) {
|
||||
val index = vm.thinkingIndex
|
||||
if (index in vm.messages.indices) ThinkingSheet(vm.messages[index]) { vm.thinkingIndex = -1 }
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = vm.modelPickerOpen,
|
||||
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
|
||||
) {
|
||||
ModelPickerSheet(vm) { vm.modelPickerOpen = false }
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechController) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
HeaderIcon(Icons.Filled.Menu, "菜单") { vm.drawerOpen = true }
|
||||
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
|
||||
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.clickable { vm.modelPickerOpen = true }
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
}
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Icon(Icons.Filled.ChevronRight, null, tint = doubaoText(), modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
|
||||
HeaderIcon(Icons.Filled.Call, "通话") { vm.showHint("通话模式还没做(方案在 README 里)") }
|
||||
// 这个喇叭是「自动朗读」开关:开了之后每条新回复自动念
|
||||
HeaderIcon(
|
||||
if (speech.autoRead) Icons.Filled.VolumeUp else Icons.Filled.VolumeOff,
|
||||
if (speech.autoRead) "自动朗读已开" else "自动朗读已关",
|
||||
tint = if (speech.autoRead) Doubao.Blue else null,
|
||||
) {
|
||||
val next = !speech.autoRead
|
||||
speech.autoRead = next
|
||||
vm.setAutoRead(next)
|
||||
vm.showHint(if (next) "新回复会自动朗读" else "已关闭自动朗读")
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"AI 生成可能有误 注意核实",
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HeaderIcon(
|
||||
icon: ImageVector,
|
||||
desc: String,
|
||||
tint: androidx.compose.ui.graphics.Color? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.86f else 1f, tween(110), label = "hdr")
|
||||
Box(
|
||||
Modifier
|
||||
.size(44.dp)
|
||||
.scale(scale)
|
||||
.clip(CircleShape)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, desc, tint = tint ?: doubaoText(), modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 空态大头像 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun HeroSection(greeting: String) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||
}
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(doubaoBubble())
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val speaking = speech.speakingIndex == index
|
||||
|
||||
if (msg.role == "user") {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
msg.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoBubble())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.Image, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(file.name, fontSize = 13.sp, color = doubaoText(), maxLines = 1)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
if (msg.content.isNotBlank()) {
|
||||
Box(
|
||||
Modifier
|
||||
.widthIn(max = 288.dp)
|
||||
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
|
||||
.background(Doubao.Blue)
|
||||
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||
val hasReasoning = msg.reasoning.isNotBlank()
|
||||
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||
|
||||
if (hasReasoning || hasTrace || msg.pending) {
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { vm.thinkingIndex = index }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.AutoAwesome, null, tint = Doubao.Blue, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
when {
|
||||
// 强度本身就叫"深度思考",拼上去会变成"深度思考 · 深度思考"
|
||||
hasReasoning -> "深度思考"
|
||||
hasTrace -> "执行过程"
|
||||
else -> "深度思考中"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
if (hasReasoning || hasTrace) {
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
} else {
|
||||
TypingDots(dot = 4.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
msg.toolTrace.forEach { trace ->
|
||||
var open by remember(trace.id) { mutableStateOf(false) }
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { open = !open }
|
||||
.padding(horizontal = 12.dp, vertical = 9.dp),
|
||||
) {
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Build, null, tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(trace.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
when (trace.ok) {
|
||||
true -> "完成"
|
||||
false -> "失败"
|
||||
null -> "进行中"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = if (trace.ok == false) Doubao.Error else Doubao.Blue,
|
||||
)
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
}
|
||||
if (open && trace.result.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
trace.result.take(800),
|
||||
fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.widthIn(max = 300.dp)
|
||||
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
when {
|
||||
// 助手回复按 Markdown 渲染(代码块、标题、列表、粗体…)。
|
||||
// 用户那条不渲染:用户输入里的 `2 * 3 * 4`、`_x_` 会被当成标记,
|
||||
// 显示出来跟输入的不一样会让人以为打错了。
|
||||
msg.content.isNotBlank() -> if (msg.error) {
|
||||
Text(msg.content, fontSize = 16.sp, lineHeight = 26.sp, color = Doubao.Error)
|
||||
} else {
|
||||
SelectionContainer {
|
||||
MarkdownText(
|
||||
markdown = msg.content,
|
||||
color = doubaoText(),
|
||||
fontSize = 16,
|
||||
lineHeight = 26,
|
||||
)
|
||||
}
|
||||
}
|
||||
msg.pending -> TypingDots()
|
||||
else -> Text("…", color = doubaoTextSecondary(), fontSize = 16.sp)
|
||||
}
|
||||
}
|
||||
|
||||
if (!msg.pending && msg.content.isNotBlank() && !msg.error) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RoundIconButton(Icons.Filled.ContentCopy, "复制") {
|
||||
clipboard.setText(AnnotatedString(msg.content))
|
||||
vm.showHint("已复制")
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
if (speaking) {
|
||||
// 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停"
|
||||
RoundIconButton(
|
||||
Icons.Filled.Stop, "停止朗读",
|
||||
tint = Doubao.Blue,
|
||||
bg = doubaoHeroRing(),
|
||||
) { speech.stopSpeaking() }
|
||||
} else {
|
||||
RoundIconButton(Icons.Filled.VolumeUp, "朗读") {
|
||||
// 手动点朗读时清掉"自动朗读念过了"的记录:
|
||||
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
|
||||
speech.forgetAutoRead()
|
||||
speech.speak(msg.content, index)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RoundIconButton(
|
||||
Icons.Filled.ThumbUp, "赞",
|
||||
tint = if (msg.feedback == "up") Doubao.Blue else null,
|
||||
) { vm.onFeedback(index, "up") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RoundIconButton(
|
||||
Icons.Filled.ThumbDown, "踩",
|
||||
tint = if (msg.feedback == "down") Doubao.Blue else null,
|
||||
) { vm.onFeedback(index, "down") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RoundIconButton(Icons.Filled.Share, "分享") { vm.showHint("分享还没做") }
|
||||
Spacer(Modifier.weight(1f))
|
||||
RoundIconButton(Icons.Filled.Refresh, "重新生成") { vm.regenerate() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 附件 / 输入栏 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun AttachmentStrip(vm: AppViewModel) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
vm.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 10.dp, vertical = 7.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.AttachFile, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
Spacer(Modifier.width(5.dp))
|
||||
Text(file.name, fontSize = 12.sp, color = doubaoText(), maxLines = 1)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.Filled.Close, "移除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(14.dp).clickable { vm.removeAttachment(file.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputBar(
|
||||
vm: AppViewModel,
|
||||
onPickFile: () -> Unit,
|
||||
onMic: () -> Unit,
|
||||
speech: SpeechController,
|
||||
) {
|
||||
val canSend = vm.draft.isNotBlank() || vm.attachments.isNotEmpty()
|
||||
val sendSource = remember { MutableInteractionSource() }
|
||||
val sendPressed by sendSource.collectIsPressedAsState()
|
||||
val sendScale by animateFloatAsState(if (sendPressed) 0.88f else 1f, tween(110), label = "send")
|
||||
|
||||
// 录音时把输入框整条换成"正在听…",跟豆包按住说话一个观感
|
||||
if (speech.recording || speech.transcribing) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.08f))
|
||||
.border(1.dp, Doubao.Blue, RoundedCornerShape(26.dp))
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (speech.transcribing) Icons.Filled.HourglassTop else Icons.Filled.Mic,
|
||||
null, tint = Doubao.Blue, modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
if (speech.transcribing) "识别中…" else "正在听…",
|
||||
fontSize = 15.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
// 简易波形:用实时音量画几根高低不同的柱子,能看出"在收音"
|
||||
Row(
|
||||
Modifier.weight(1f).height(24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
val amp = if (speech.transcribing) 8 else speech.level
|
||||
repeat(18) { i ->
|
||||
// 中间高两边低,再叠加实时音量,看着像声波
|
||||
val shape = 1f - kotlin.math.abs(i - 8.5f) / 10f
|
||||
val h = (6 + amp * shape * 0.16f).coerceIn(4f, 24f)
|
||||
Box(
|
||||
Modifier
|
||||
.width(3.dp)
|
||||
.height(h.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.35f + 0.5f * shape)),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Doubao.Blue)
|
||||
.clickable { onMic() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Check, "完成", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), RoundedCornerShape(26.dp))
|
||||
.padding(horizontal = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (vm.attachments.isEmpty()) Icons.Filled.PhotoCamera else Icons.Filled.Add,
|
||||
"附件",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable(onClick = onPickFile),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
|
||||
if (vm.draft.isEmpty()) {
|
||||
Text("发消息或按住说话…", fontSize = 15.sp, color = Doubao.TextTertiary)
|
||||
}
|
||||
BasicTextField(
|
||||
value = vm.draft,
|
||||
onValueChange = { vm.draft = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = TextStyle(fontSize = 15.sp, color = doubaoText()),
|
||||
cursorBrush = SolidColor(Doubao.Blue),
|
||||
maxLines = 3,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||
keyboardActions = KeyboardActions(onSend = { vm.send() }),
|
||||
)
|
||||
}
|
||||
if (!canSend) {
|
||||
Icon(
|
||||
Icons.Filled.Mic, "语音输入", tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable(onClick = onMic),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (canSend) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.scale(sendScale)
|
||||
.clip(CircleShape)
|
||||
.background(Doubao.Blue)
|
||||
.clickable(interactionSource = sendSource, indication = null) { vm.send() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.ArrowUpward, "发送", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), CircleShape)
|
||||
.clickable(onClick = onPickFile),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Add, "更多", tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 思考过程弹层 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(Doubao.Scrim).clickable(onClick = onClose),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 560.dp)
|
||||
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable(enabled = false) {}
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||
) {
|
||||
// 顶上那条小横杠:一眼看出是从底部拉起来的
|
||||
Box(
|
||||
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
|
||||
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
|
||||
)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RoundIconButton(Icons.Filled.Close, "关闭", size = 30.dp, iconSize = 15.dp, onClick = onClose)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text("思考过程", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Spacer(Modifier.width(30.dp))
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
LazyColumn(Modifier.fillMaxWidth()) {
|
||||
if (msg.toolTrace.isNotEmpty()) {
|
||||
items(msg.toolTrace.size) { i ->
|
||||
val trace = msg.toolTrace[i]
|
||||
Row(Modifier.padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.Build, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"${if (trace.ok == false) "失败" else "已调用"} ${trace.name}",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Text(
|
||||
msg.reasoning.ifBlank { "这次没有返回思维链(模型不支持,或思考强度被关掉了)。" },
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* 极简 Markdown 渲染。
|
||||
*
|
||||
* 为什么自己写而不引库:
|
||||
* 项目一直坚持"零第三方依赖"(安卓端构建要能离线完成),而 Markdown 渲染
|
||||
* 在这个规模下不需要一个几百 KB 的库 —— 聊天里真正会出现的就那几种:标题、
|
||||
* 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。
|
||||
*
|
||||
* 支持:
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、> 引用、--- 分隔线、普通段落
|
||||
* 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接)
|
||||
*
|
||||
* 不支持(有意为之):表格、嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 而且做全了就得处理各种边界,性价比很低。
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
markdown: String,
|
||||
// ★ color 不能给默认值:默认参数里不能调用 @Composable 函数
|
||||
// (doubaoText() 是 @Composable,写成 `color: Color = doubaoText()` 直接编译不过)
|
||||
color: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
linkColor: Color = Doubao.Blue,
|
||||
fontSize: Int = 16,
|
||||
lineHeight: Int = 26,
|
||||
) {
|
||||
val blocks = remember(markdown) { parseMarkdown(markdown) }
|
||||
val codeBg = if (isDark()) Color(0xFF1B1F27) else Color(0xFFF3F4F6)
|
||||
val quoteBar = Doubao.Blue.copy(alpha = 0.55f)
|
||||
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (block in blocks) {
|
||||
when (block) {
|
||||
is MdBlock.Code -> {
|
||||
// 代码块单独一块:等宽字体 + 底色 + 可横向滚动(长行不折行更好读)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(codeBg)
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
block.text.trimEnd(),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = (fontSize - 3).sp,
|
||||
lineHeight = (fontSize + 5).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Quote -> {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
// 左边一条竖线,跟正文区分开
|
||||
Box(
|
||||
Modifier
|
||||
.width(3.dp)
|
||||
.heightIn(min = 20.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(quoteBar),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color.copy(alpha = 0.85f),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Numbered -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"${block.number}.",
|
||||
fontSize = fontSize.sp,
|
||||
color = color.copy(alpha = 0.7f),
|
||||
modifier = Modifier.width(22.dp),
|
||||
)
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 2.dp)
|
||||
.height(1.dp)
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 块级解析 ------------------------------ */
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
data class Paragraph(val text: String) : MdBlock
|
||||
data class Heading(val level: Int, val text: String) : MdBlock
|
||||
data class Bullet(val text: String) : MdBlock
|
||||
data class Numbered(val number: String, val text: String) : MdBlock
|
||||
data class Quote(val text: String) : MdBlock
|
||||
data class Code(val text: String, val lang: String = "") : MdBlock
|
||||
data object Divider : MdBlock
|
||||
}
|
||||
|
||||
private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$")
|
||||
private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$")
|
||||
private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$")
|
||||
private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$")
|
||||
private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$")
|
||||
private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$")
|
||||
|
||||
internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
val out = ArrayList<MdBlock>()
|
||||
val lines = src.replace("\r\n", "\n").split("\n")
|
||||
val para = StringBuilder()
|
||||
var i = 0
|
||||
|
||||
fun flushPara() {
|
||||
if (para.isNotBlank()) out.add(MdBlock.Paragraph(para.toString().trim()))
|
||||
para.setLength(0)
|
||||
}
|
||||
|
||||
while (i < lines.size) {
|
||||
val line = lines[i]
|
||||
|
||||
// 代码块:``` 开头到下一个 ```(或文件结束)
|
||||
val fence = RE_FENCE.find(line)
|
||||
if (fence != null) {
|
||||
flushPara()
|
||||
val lang = fence.groupValues[1]
|
||||
val body = StringBuilder()
|
||||
i += 1
|
||||
while (i < lines.size && RE_FENCE.find(lines[i]) == null) {
|
||||
body.append(lines[i]).append('\n')
|
||||
i += 1
|
||||
}
|
||||
i += 1 // 跳过收尾的 ```
|
||||
out.add(MdBlock.Code(body.toString(), lang))
|
||||
continue
|
||||
}
|
||||
|
||||
when {
|
||||
line.isBlank() -> flushPara()
|
||||
|
||||
RE_DIVIDER.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Divider)
|
||||
}
|
||||
|
||||
RE_HEADING.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_HEADING.find(line)!!
|
||||
out.add(MdBlock.Heading(m.groupValues[1].length, m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_QUOTE.matches(line) -> {
|
||||
flushPara()
|
||||
// 连续的引用行合成一段
|
||||
val q = StringBuilder()
|
||||
while (i < lines.size && RE_QUOTE.matches(lines[i])) {
|
||||
if (q.isNotEmpty()) q.append(' ')
|
||||
q.append(RE_QUOTE.find(lines[i])!!.groupValues[1])
|
||||
i += 1
|
||||
}
|
||||
out.add(MdBlock.Quote(q.toString().trim()))
|
||||
continue
|
||||
}
|
||||
|
||||
RE_BULLET.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim()))
|
||||
}
|
||||
|
||||
RE_NUMBERED.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_NUMBERED.find(line)!!
|
||||
out.add(MdBlock.Numbered(m.groupValues[1], m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
else -> {
|
||||
if (para.isNotEmpty()) para.append('\n')
|
||||
para.append(line)
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
flushPara()
|
||||
return out
|
||||
}
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 行内标记 → AnnotatedString。
|
||||
*
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*/
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
when {
|
||||
// 行内代码:`code`
|
||||
text[i] == '`' -> {
|
||||
val end = text.indexOf('`', i + 1)
|
||||
if (end > i) {
|
||||
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp)) {
|
||||
append(text.substring(i + 1, end))
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 粗斜体 / 粗体 / 斜体:***x***、**x**、*x*
|
||||
text.startsWith("***", i) || text.startsWith("**", i) || text[i] == '*' -> {
|
||||
val marker = when {
|
||||
text.startsWith("***", i) -> "***"
|
||||
text.startsWith("**", i) -> "**"
|
||||
else -> "*"
|
||||
}
|
||||
val end = text.indexOf(marker, i + marker.length)
|
||||
// 找不到收尾、或者里面是空的,就当普通字符
|
||||
if (end > i + marker.length) {
|
||||
val inner = text.substring(i + marker.length, end)
|
||||
val style = when (marker) {
|
||||
"***" -> SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic)
|
||||
"**" -> SpanStyle(fontWeight = FontWeight.Bold)
|
||||
else -> SpanStyle(fontStyle = FontStyle.Italic)
|
||||
}
|
||||
withStyle(style) { append(inner) }
|
||||
i = end + marker.length
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 删除线:~~x~~
|
||||
text.startsWith("~~", i) -> {
|
||||
val end = text.indexOf("~~", i + 2)
|
||||
if (end > i + 2) {
|
||||
withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) {
|
||||
append(text.substring(i + 2, end))
|
||||
}
|
||||
i = end + 2
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 链接:[文字](地址)
|
||||
text[i] == '[' -> {
|
||||
val close = text.indexOf(']', i)
|
||||
val open = if (close > 0 && close + 1 < text.length && text[close + 1] == '(') close + 1 else -1
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||
import com.termux.view.TerminalView
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* 内置 Termux 终端。
|
||||
*
|
||||
* 这里是**真的终端**,不是"命令框":
|
||||
* - 进程侧用 Termux 的 pty(libtermux.so 的 JNI 直接调 forkpty),所以是 tty,能跑 vim/top
|
||||
* - 渲染侧用 Termux 的 TerminalView,ANSI 颜色、光标、选区都是现成的
|
||||
*
|
||||
* 手机上没有 Esc/Tab/方向键,所以额外加了一排功能键 —— 没有它连 vim 都退不出来。
|
||||
*/
|
||||
@Composable
|
||||
fun TerminalScreen(
|
||||
vm: AppViewModel,
|
||||
termuxReady: Boolean,
|
||||
termuxStatus: String,
|
||||
onInstallTermux: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val terminal = remember { TermuxTerminal(context) }
|
||||
var title by remember { mutableStateOf("termux") }
|
||||
/** pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台 */
|
||||
var ptyFailed by remember { mutableStateOf(false) }
|
||||
var startedAt by remember { mutableStateOf(0L) }
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { terminal.destroy() }
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后 2 秒内就结束,说明 bash 拿不到 tty(stdin 直接 EOF)
|
||||
val onSessionExit = {
|
||||
if (startedAt > 0 && System.currentTimeMillis() - startedAt < 2000) {
|
||||
ptyFailed = true
|
||||
TermuxInstaller.trace(context, "pty 不可用(会话秒退),切换到命令控制台")
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(Color(0xFF14161A))) {
|
||||
// ---------------- 顶部栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(Color(0xFF1C1F24)).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
IconButton(onClick = { vm.screen = Screen.Chat }) {
|
||||
Icon(Icons.Filled.ArrowBack, "返回", tint = Color.White)
|
||||
}
|
||||
Text(title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.weight(1f))
|
||||
IconButton(onClick = {
|
||||
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
|
||||
terminal.session?.write("\u0003".toByteArray(), 0, 1)
|
||||
}) { Icon(Icons.Filled.Stop, "Ctrl+C", tint = Color.White) }
|
||||
IconButton(onClick = {
|
||||
terminal.session?.write("clear\n".toByteArray(), 0, 6)
|
||||
}) { Icon(Icons.Filled.DeleteSweep, "清屏", tint = Color.White) }
|
||||
}
|
||||
|
||||
// ---------------- 环境状态 / 安装入口 ----------------
|
||||
if (!termuxReady) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
if (termuxStatus.isBlank()) "正在准备内置 Termux 环境…" else termuxStatus,
|
||||
color = Color(0xFFFFD08A),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
if (termuxStatus.contains("失败")) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
TextButton(onClick = onInstallTermux) { Text("重试安装") }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Surface(color = Color(0xFF16301F), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Termux 已内置 · ${TermuxInstaller.prefix(context).absolutePath}\n" +
|
||||
"试试点上面的 + 装东西:pkg install python nodejs-lts",
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 终端本体 ----------------
|
||||
if (termuxReady && ptyFailed) {
|
||||
// pty 用不了 → 命令控制台(跑的是同一条 Termux bash,只是没有 tty)
|
||||
Box(Modifier.weight(1f).fillMaxWidth().background(Color(0xFF14161A))) {
|
||||
CommandConsole(
|
||||
onRun = { command, done ->
|
||||
vm.runTool("shell", org.json.JSONObject().put("command", command)) { ok, text ->
|
||||
done(ok, text)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
} else if (termuxReady) {
|
||||
AndroidView(
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
factory = { ctx ->
|
||||
TerminalView(ctx, null).apply {
|
||||
setTerminalViewClient(terminal.viewClient())
|
||||
setTextSize(28)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
try {
|
||||
val session = terminal.session ?: run {
|
||||
startedAt = System.currentTimeMillis()
|
||||
terminal.createSession(onTitle = { title = it }, onExit = onSessionExit)
|
||||
}
|
||||
if (view.currentSession !== session) {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
title = "会话启动失败:${t.message}"
|
||||
ptyFailed = true
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
// 没就绪时给一块占位区,别留空白让人以为卡死了
|
||||
Box(
|
||||
Modifier.weight(1f).fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"内置 Termux 环境还没装好,装好后这里就是真终端。",
|
||||
color = Color(0xFF8A93A0),
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 功能键(手机没键盘,必须有这一排) ----------------
|
||||
if (termuxReady) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(Color(0xFF1C1F24))
|
||||
.horizontalScroll(rememberScrollState()).padding(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
data class Key(val label: String, val bytes: String)
|
||||
val keys = listOf(
|
||||
Key("ESC", "\u001b"),
|
||||
Key("TAB", "\t"),
|
||||
Key("CTRL+C", "\u0003"),
|
||||
Key("CTRL+D", "\u0004"),
|
||||
Key("↑", "\u001b[A"),
|
||||
Key("↓", "\u001b[B"),
|
||||
Key("←", "\u001b[D"),
|
||||
Key("→", "\u001b[C"),
|
||||
Key("HOME", "\u001b[H"),
|
||||
Key("END", "\u001b[F"),
|
||||
Key("|", "|"),
|
||||
Key("/", "/"),
|
||||
Key("-", "-"),
|
||||
Key("ENTER", "\n"),
|
||||
)
|
||||
keys.forEach { key ->
|
||||
Surface(
|
||||
shape = RoundedCornerShape(6.dp),
|
||||
color = Color(0xFF2A2F37),
|
||||
modifier = Modifier.padding(end = 6.dp).clickable {
|
||||
val s = terminal.session ?: return@clickable
|
||||
val bytes = key.bytes.toByteArray()
|
||||
s.write(bytes, 0, bytes.size)
|
||||
},
|
||||
) {
|
||||
Text(
|
||||
key.label,
|
||||
color = Color(0xFFD7DAE0),
|
||||
fontSize = 12.sp,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 9.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 4.7 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 44 KiB |
Binary file not shown.
@@ -1,182 +0,0 @@
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
open 所有工具都交给模型
|
||||
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||||
|
||||
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||||
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Callable, Optional
|
||||
|
||||
import store
|
||||
import tools_runtime
|
||||
from providers import stream_chat
|
||||
|
||||
MAX_TOOL_RESULT_CHARS = 6000
|
||||
|
||||
|
||||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||
if isinstance(text, str):
|
||||
out = text
|
||||
else:
|
||||
try:
|
||||
out = json.dumps(text, ensure_ascii=False)
|
||||
except (TypeError, ValueError):
|
||||
out = str(text)
|
||||
return f'{out[:max_len]}\n…(已截断)' if len(out) > max_len else out
|
||||
|
||||
|
||||
def _max_rounds(settings: dict) -> int:
|
||||
raw = settings.get('maxRounds')
|
||||
try:
|
||||
value = int(float(raw))
|
||||
except (TypeError, ValueError):
|
||||
value = 6
|
||||
if not value: # 0 / 空 都按默认 6 处理(对应 JS 的 `Number(x) || 6`)
|
||||
value = 6
|
||||
return max(1, min(12, value))
|
||||
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
settings 当前设置
|
||||
messages [{role, content}] 历史(不含 system)
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
"""
|
||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||
provider = store.provider_info(settings, agent)
|
||||
provider_key = provider.get('provider') or settings.get('provider')
|
||||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
'type': 'start',
|
||||
'provider': provider_key,
|
||||
'model': provider.get('model'),
|
||||
'tools': len(tool_defs),
|
||||
'mode': mode,
|
||||
'thinkingLevel': thinking_level,
|
||||
'agent': {'id': agent.get('id'), 'name': agent.get('name')} if agent else None,
|
||||
})
|
||||
|
||||
convo = []
|
||||
if system_prompt.strip():
|
||||
convo.append({'role': 'system', 'content': system_prompt})
|
||||
convo.extend(messages)
|
||||
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
round_text = ''
|
||||
tool_calls = []
|
||||
|
||||
for event in stream_chat(
|
||||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||||
provider=provider_key,
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=convo,
|
||||
tools=tool_defs if tool_defs else None,
|
||||
temperature=settings.get('temperature'),
|
||||
thinking_level=thinking_level,
|
||||
should_stop=should_stop,
|
||||
):
|
||||
kind = event.get('type')
|
||||
if kind == 'text':
|
||||
round_text += event['text']
|
||||
# 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||||
# 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||||
answer += event['text']
|
||||
emit({'type': 'delta', 'text': event['text'], 'round': round_index})
|
||||
elif kind == 'reasoning':
|
||||
reasoning_all += event['text']
|
||||
emit({'type': 'reasoning', 'text': event['text'], 'round': round_index})
|
||||
elif kind == 'tool_calls':
|
||||
tool_calls = event.get('toolCalls') or []
|
||||
elif kind == 'usage':
|
||||
usage = event.get('usage')
|
||||
|
||||
if not tool_calls:
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
'role': 'assistant',
|
||||
'content': round_text or '',
|
||||
'tool_calls': [
|
||||
{
|
||||
'id': tc.get('id'),
|
||||
'type': 'function',
|
||||
'function': {
|
||||
'name': tc.get('name'),
|
||||
# 参数原样回传:模型可能给出坏 JSON,服务端往往还能自己纠正
|
||||
'arguments': tc.get('argsRaw') or json.dumps(tc.get('args') or {}, ensure_ascii=False),
|
||||
},
|
||||
}
|
||||
for tc in tool_calls
|
||||
],
|
||||
})
|
||||
|
||||
for tc in tool_calls:
|
||||
tool_call_count += 1
|
||||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||||
try:
|
||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if result.get('ok'):
|
||||
raw = result.get('result')
|
||||
payload = truncate('(无输出)' if raw is None else raw)
|
||||
else:
|
||||
payload = f"调用失败:{result.get('error') or '未知错误'}"
|
||||
emit({
|
||||
'type': 'tool_result',
|
||||
'id': tc.get('id'),
|
||||
'name': tc.get('name'),
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': max_rounds,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
'truncated': True,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,264 +0,0 @@
|
||||
"""
|
||||
常量表:提供商预设、默认设置、内置智能体。
|
||||
|
||||
这些值必须和 Node 版 server/src/config.mjs、server/src/agents.mjs 逐字段一致,
|
||||
否则 Lynx 前端读到的设置会出现"字段名对但默认值不同"的细微差异。
|
||||
"""
|
||||
|
||||
DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||
[
|
||||
'你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。',
|
||||
'',
|
||||
'回答要求:',
|
||||
'1. 用简体中文回答,除非用户要求其他语言。',
|
||||
'2. 先给结论,再给必要的解释,避免空话和过度铺垫。',
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
]
|
||||
)
|
||||
|
||||
# 提供商预设。
|
||||
#
|
||||
# 全都是 **OpenAI 兼容协议**(POST {baseUrl}/chat/completions),区别只有
|
||||
# baseUrl、模型名,以及"思考强度怎么传"。
|
||||
#
|
||||
# thinkingMode 就是在说这件事,别写死成"非 ark 即 openai":
|
||||
# 'ark' → 顶层 thinking: {type: enabled|disabled}(火山方舟、智谱 GLM 同形状)
|
||||
# 'effort' → reasoning_effort: low|medium|high(OpenAI 推理模型、OpenRouter 透传)
|
||||
# 'none' → 什么都不发。★ 安全默认值:给不认 reasoning_effort 的服务发这个字段,
|
||||
# 有些会直接 400。DeepSeek / Kimi / 通义 / 硅基流动 的思考由模型自己决定。
|
||||
PROVIDER_PRESETS = {
|
||||
'ark': {
|
||||
'label': '火山方舟(豆包)',
|
||||
'baseUrl': 'https://ark.cn-beijing.volces.com/api/v3',
|
||||
'apiKeyEnv': 'ARK_API_KEY',
|
||||
'defaultModel': 'doubao-seed-2-1-pro-260628',
|
||||
'modelHint': '填模型 ID(如 doubao-seed-2-1-pro-260628)或推理接入点 ID(ep-xxxxxxxx)',
|
||||
'docs': 'https://www.volcengine.com/docs/82379/1298454',
|
||||
'thinkingMode': 'ark',
|
||||
'models': [
|
||||
'doubao-seed-2-1-pro-260628',
|
||||
'doubao-seed-1-8-251228',
|
||||
'deepseek-r1-250528',
|
||||
],
|
||||
},
|
||||
'openai': {
|
||||
'label': 'OpenAI 官方',
|
||||
'baseUrl': 'https://api.openai.com/v1',
|
||||
'apiKeyEnv': 'OPENAI_API_KEY',
|
||||
'defaultModel': 'gpt-4o-mini',
|
||||
'modelHint': '填 model 名称;推理模型(o 系 / gpt-5 系)会自动剥离 temperature 等参数',
|
||||
'docs': 'https://platform.openai.com/docs/api-reference/chat',
|
||||
'thinkingMode': 'effort',
|
||||
'models': ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-5-mini'],
|
||||
},
|
||||
'deepseek': {
|
||||
'label': 'DeepSeek',
|
||||
'baseUrl': 'https://api.deepseek.com/v1',
|
||||
'apiKeyEnv': 'DEEPSEEK_API_KEY',
|
||||
'defaultModel': 'deepseek-chat',
|
||||
'modelHint': 'deepseek-chat 是通用对话;deepseek-reasoner 会自动返回思维链',
|
||||
'docs': 'https://api-docs.deepseek.com/zh-cn/',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['deepseek-chat', 'deepseek-reasoner'],
|
||||
},
|
||||
'kimi': {
|
||||
'label': 'Kimi(月之暗面)',
|
||||
'baseUrl': 'https://api.moonshot.cn/v1',
|
||||
'apiKeyEnv': 'MOONSHOT_API_KEY',
|
||||
'defaultModel': 'kimi-k2-0905-preview',
|
||||
'modelHint': 'Kimi K2 支持工具调用;moonshot-v1-* 是上一代长文本模型',
|
||||
'docs': 'https://platform.moonshot.cn/docs/api/chat',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['kimi-k2-0905-preview', 'kimi-latest', 'moonshot-v1-128k'],
|
||||
},
|
||||
'zhipu': {
|
||||
'label': '智谱 GLM',
|
||||
'baseUrl': 'https://open.bigmodel.cn/api/paas/v4',
|
||||
'apiKeyEnv': 'ZHIPU_API_KEY',
|
||||
'defaultModel': 'glm-4.6',
|
||||
'modelHint': 'GLM 的思考开关和方舟同形状(顶层 thinking),已按这个发',
|
||||
'docs': 'https://docs.bigmodel.cn/cn/guide/develop/openai/introduction',
|
||||
'thinkingMode': 'ark',
|
||||
'models': ['glm-4.6', 'glm-4.5', 'glm-4-flash'],
|
||||
},
|
||||
'dashscope': {
|
||||
'label': '通义千问(阿里云)',
|
||||
'baseUrl': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
'apiKeyEnv': 'DASHSCOPE_API_KEY',
|
||||
'defaultModel': 'qwen-plus',
|
||||
'modelHint': 'Qwen3 系列自己会思考,这里不发思考参数',
|
||||
'docs': 'https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['qwen3-max', 'qwen-plus', 'qwen-turbo'],
|
||||
},
|
||||
'siliconflow': {
|
||||
'label': '硅基流动',
|
||||
'baseUrl': 'https://api.siliconflow.cn/v1',
|
||||
'apiKeyEnv': 'SILICONFLOW_API_KEY',
|
||||
'defaultModel': 'deepseek-ai/DeepSeek-V3',
|
||||
'modelHint': '模型名带斜杠(组织/模型),例如 deepseek-ai/DeepSeek-V3',
|
||||
'docs': 'https://docs.siliconflow.cn/cn/api-reference/chat-completions/chat-completions',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['deepseek-ai/DeepSeek-V3', 'Qwen/Qwen3-235B-A22B', 'THUDM/glm-4-9b-chat'],
|
||||
},
|
||||
'openrouter': {
|
||||
'label': 'OpenRouter(聚合)',
|
||||
'baseUrl': 'https://openrouter.ai/api/v1',
|
||||
'apiKeyEnv': 'OPENROUTER_API_KEY',
|
||||
'defaultModel': 'openai/gpt-4o-mini',
|
||||
'modelHint': '一个 Key 调各家模型,模型名是「厂商/模型」;会透传 reasoning_effort',
|
||||
'docs': 'https://openrouter.ai/docs/api-reference/overview',
|
||||
'thinkingMode': 'effort',
|
||||
'models': ['openai/gpt-4o-mini', 'deepseek/deepseek-chat', 'anthropic/claude-3.5-sonnet'],
|
||||
},
|
||||
'ollama': {
|
||||
'label': '本地 Ollama',
|
||||
'baseUrl': 'http://127.0.0.1:11434/v1',
|
||||
'apiKeyEnv': 'OLLAMA_API_KEY',
|
||||
'defaultModel': 'qwen2.5:7b',
|
||||
'modelHint': '本地跑,Key 随便填(Ollama 不校验)。手机连电脑要填电脑的局域网 IP',
|
||||
'docs': 'https://github.com/ollama/ollama/blob/main/docs/openai.md',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['qwen2.5:7b', 'llama3.1:8b', 'deepseek-r1:7b'],
|
||||
},
|
||||
'custom': {
|
||||
'label': '自定义(任意兼容网关)',
|
||||
'baseUrl': '',
|
||||
'apiKeyEnv': 'CUSTOM_API_KEY',
|
||||
'defaultModel': '',
|
||||
'modelHint': '填完整的 /v1 地址和模型名,只要兼容 OpenAI 的 chat/completions 就能用',
|
||||
'docs': '',
|
||||
'thinkingMode': 'none',
|
||||
'models': [],
|
||||
},
|
||||
}
|
||||
|
||||
# 各家控制台「申请 API Key」的直达链接。
|
||||
#
|
||||
# 为什么单独一张表、而不是塞进每个预设里:这些地址会变
|
||||
# (实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com,
|
||||
# 旧地址 301 跳过去),集中一处以后好改。
|
||||
# 已逐个访问核实过可达(返回 200 或 302 到登录页都算通)。
|
||||
PROVIDER_CONSOLE_URLS = {
|
||||
'ark': 'https://console.volcengine.com/ark/region:cn-beijing/apiKey',
|
||||
'openai': 'https://platform.openai.com/api-keys',
|
||||
'deepseek': 'https://platform.deepseek.com/api_keys',
|
||||
'kimi': 'https://platform.kimi.com/console/api-keys',
|
||||
'zhipu': 'https://open.bigmodel.cn/usercenter/apikeys',
|
||||
'dashscope': 'https://bailian.console.aliyun.com/?apiKey=1',
|
||||
'siliconflow': 'https://cloud.siliconflow.cn/account/ak',
|
||||
'openrouter': 'https://openrouter.ai/keys',
|
||||
'ollama': 'https://ollama.com/download',
|
||||
'custom': '',
|
||||
}
|
||||
for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
if _key in PROVIDER_PRESETS:
|
||||
PROVIDER_PRESETS[_key]['consoleUrl'] = _url
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
'apiKey': '',
|
||||
'temperature': 0.7,
|
||||
'maxRounds': 6,
|
||||
# 思考强度:off / low / medium / high / auto
|
||||
# - 方舟:映射到顶层 thinking 字段
|
||||
# - OpenAI:映射到 reasoning_effort(推理模型)
|
||||
'thinkingLevel': 'auto',
|
||||
# 额外工具目录(留空则用内置 tools/);安卓端可以指到手机上的目录
|
||||
'toolsDir': '',
|
||||
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||
'tools': {'python': True, 'mcp': True},
|
||||
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||
'speech': {
|
||||
'ttsEngine': 'system', # system | volc | openai
|
||||
'ttsVoice': '', # volc: voice_type;openai: alloy/nova/...
|
||||
'ttsSpeed': 1.0,
|
||||
'autoRead': False, # 新回复自动念出来
|
||||
'sttEngine': 'system', # system | openai
|
||||
'sttModel': 'whisper-1',
|
||||
'sttLanguage': '', # 留空 = 自动判断
|
||||
'volcAppId': '',
|
||||
'volcToken': '',
|
||||
'volcCluster': 'volcano_tts',
|
||||
'volcEncoding': 'mp3',
|
||||
'openaiApiKey': '', # 留空则复用主对话的 Key
|
||||
'openaiBaseUrl': '', # 留空则复用主对话的 Base URL
|
||||
'ttsModel': 'tts-1',
|
||||
},
|
||||
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
|
||||
'security': {'mode': 'open', 'allow': []},
|
||||
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
|
||||
'pythonBin': '',
|
||||
'nickname': '我',
|
||||
'doubaoId': '378269252',
|
||||
'activeAgentId': 'a_doubao',
|
||||
}
|
||||
|
||||
SECRET_KEYS = {'apiKey'}
|
||||
|
||||
# 内置智能体(前端有同名头像,靠 avatar 字段对应)
|
||||
DEFAULT_AGENTS = [
|
||||
{
|
||||
'id': 'a_doubao',
|
||||
'name': '豆包',
|
||||
'avatar': 'doubao',
|
||||
'tagline': '通用助手',
|
||||
'systemPrompt': '',
|
||||
'builtin': True,
|
||||
},
|
||||
{
|
||||
'id': 'a_coder',
|
||||
'name': '代码搭子',
|
||||
'avatar': 'coder',
|
||||
'tagline': '只聊代码,直接给能跑的',
|
||||
'systemPrompt': '\n'.join(
|
||||
[
|
||||
'你是一个资深工程师。',
|
||||
'1. 先给可以直接复制运行的代码,再解释关键点。',
|
||||
'2. 代码里不要有省略号,不要写"此处省略"。',
|
||||
'3. 指出你方案里的坑和替代做法。',
|
||||
'4. 涉及文件读写、执行命令时优先调用可用工具。',
|
||||
]
|
||||
),
|
||||
'builtin': True,
|
||||
},
|
||||
{
|
||||
'id': 'a_writer',
|
||||
'name': '文案师',
|
||||
'avatar': 'writer',
|
||||
'tagline': '写东西、改稿子',
|
||||
'systemPrompt': '\n'.join(
|
||||
[
|
||||
'你是中文文案编辑。',
|
||||
'1. 先问清楚用途、受众、字数要求,信息不全就按最常见的场景先给一版。',
|
||||
'2. 给成品,不要给"写作思路"。',
|
||||
'3. 口语化、短句、少用形容词堆砌,别用"赋能/闭环/抓手"这类词。',
|
||||
]
|
||||
),
|
||||
'builtin': True,
|
||||
},
|
||||
{
|
||||
'id': 'a_analyst',
|
||||
'name': '数据分析',
|
||||
'avatar': 'analyst',
|
||||
'tagline': '算数、看数据、讲结论',
|
||||
'systemPrompt': '\n'.join(
|
||||
[
|
||||
'你是数据分析师。',
|
||||
'1. 任何计算都必须调用 calc 工具,不要心算。',
|
||||
'2. 先给结论,再给口径和数据来源。',
|
||||
'3. 样本不足或数据可疑时直接说出来。',
|
||||
]
|
||||
),
|
||||
'builtin': True,
|
||||
},
|
||||
]
|
||||
|
||||
# 可选头像(前端有同名 SVG,这里只做白名单校验)
|
||||
AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'robot', 'star', 'cloud', 'custom']
|
||||
@@ -1,508 +0,0 @@
|
||||
"""
|
||||
持久化:设置 / 会话 / 智能体。
|
||||
|
||||
对应 Node 版的 config.mjs(设置)+ store.mjs(会话)+ agents.mjs(智能体),
|
||||
文件名也保持一致(settings.json / conversations.json / agents.json),
|
||||
这样安卓内核和桌面内核可以共用同一个数据目录。
|
||||
|
||||
为什么用 JSON 文件而不是 SQLite:
|
||||
* 数据量极小(几条会话、几个智能体),前端还要能直接看到/改这些文件;
|
||||
* 安卓上 Chaquopy 自带 sqlite3,但跨端"人肉可读"更重要;
|
||||
* 写盘走"临时文件 + 原子替换",避免安卓被杀进程时留下半个 JSON。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS
|
||||
|
||||
_lock = threading.RLock()
|
||||
_conv_state = None # 会话状态在内存里缓存(和 Node 版 store.mjs 一样只 load 一次)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 通用小工具
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def now_iso() -> str:
|
||||
"""
|
||||
和 JS 的 new Date().toISOString() 完全一致的格式:
|
||||
2025-01-01T12:00:00.000Z(毫秒精度 + Z 后缀)。
|
||||
前端会把这些字符串直接排序/展示,格式不一致会出现"时间跳来跳去"。
|
||||
"""
|
||||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def _read_json(file_path: str):
|
||||
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
return None
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as fh:
|
||||
return json.load(fh)
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f'[store] {os.path.basename(file_path)} 解析失败:{exc}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _write_json(file_path: str, payload) -> None:
|
||||
"""原子写:先写 .tmp 再 os.replace,避免掉电/被杀时留下半个文件。"""
|
||||
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
||||
tmp = f'{file_path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as fh:
|
||||
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, file_path)
|
||||
|
||||
|
||||
def _as_text(value) -> str:
|
||||
"""JS 的 String(x):None 会变成空串而不是 'None'。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 设置
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_dotenv_loaded = False
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""
|
||||
极简 .env 解析。Node 版读 server/.env;Python 版读数据目录和内核目录下的 .env,
|
||||
这样安卓上把 key 放在数据目录里就能用,不需要动源码目录。
|
||||
"""
|
||||
global _dotenv_loaded
|
||||
if _dotenv_loaded:
|
||||
return
|
||||
_dotenv_loaded = True
|
||||
p = paths.get()
|
||||
for folder in (p.data_dir, os.path.dirname(os.path.abspath(__file__))):
|
||||
env_file = os.path.join(folder, '.env')
|
||||
if not os.path.isfile(env_file):
|
||||
continue
|
||||
try:
|
||||
with open(env_file, 'r', encoding='utf-8') as fh:
|
||||
lines = fh.read().splitlines()
|
||||
except OSError:
|
||||
continue
|
||||
for raw in lines:
|
||||
line = raw.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
key, _, value = line.partition('=')
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
|
||||
value = value[1:-1]
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
def mask_settings(settings: dict) -> dict:
|
||||
"""脱敏:apiKey / 语音 Token 只回掩码 + has* 标志(前端据此显示"已配置")。"""
|
||||
out = dict(settings)
|
||||
out['apiKey'] = '••••••••' if settings.get('apiKey') else ''
|
||||
out['hasApiKey'] = bool(settings.get('apiKey'))
|
||||
speech = dict(out.get('speech') or {})
|
||||
speech['volcToken'] = '••••••••' if speech.get('volcToken') else ''
|
||||
speech['volcApiKey'] = '••••••••' if speech.get('volcApiKey') else ''
|
||||
speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else ''
|
||||
out['speech'] = speech
|
||||
return out
|
||||
|
||||
|
||||
def read_settings() -> dict:
|
||||
"""读设置:默认值 + 文件 + 环境变量兜底(字段与 Node 版一致)。"""
|
||||
_load_dotenv()
|
||||
stored = _read_json(paths.get().settings_file) or {}
|
||||
if not isinstance(stored, dict):
|
||||
stored = {}
|
||||
settings = dict(DEFAULT_SETTINGS)
|
||||
settings.update(stored)
|
||||
# 子对象要深合并,否则用户只改 security.allow 会把 security.mode 冲掉。
|
||||
# ★ 而且必须防住"子对象被非字典值覆盖":曾经前端把嵌套 Map 序列化成了字符串
|
||||
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
|
||||
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||||
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
|
||||
for key in ('tools', 'security', 'speech'):
|
||||
defaults = DEFAULT_SETTINGS.get(key) or {}
|
||||
raw = stored.get(key)
|
||||
if not isinstance(raw, dict):
|
||||
if raw is not None:
|
||||
print(f'[config] settings.json 里的 {key} 不是对象,已回落默认值', file=sys.stderr, flush=True)
|
||||
raw = {}
|
||||
settings[key] = {**defaults, **raw}
|
||||
if not isinstance(settings['security'].get('allow'), list):
|
||||
settings['security']['allow'] = []
|
||||
settings.pop('hasApiKey', None)
|
||||
|
||||
# 环境变量兜底:没填 key 时用 .env / 系统环境变量里的
|
||||
preset = _preset_of(settings)
|
||||
if not settings.get('apiKey') and preset.get('apiKeyEnv'):
|
||||
settings['apiKey'] = os.environ.get(preset['apiKeyEnv'], '')
|
||||
return settings
|
||||
|
||||
|
||||
def _preset_of(settings: dict) -> dict:
|
||||
from defaults import PROVIDER_PRESETS # 局部导入,避免循环依赖
|
||||
|
||||
return PROVIDER_PRESETS.get(settings.get('provider')) or PROVIDER_PRESETS['ark']
|
||||
|
||||
|
||||
def write_settings(patch: dict) -> dict:
|
||||
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
|
||||
if not isinstance(patch, dict):
|
||||
patch = {}
|
||||
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||||
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||||
# systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求。
|
||||
for key in ('baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel'):
|
||||
if key in patch and isinstance(patch[key], str) and not patch[key].strip():
|
||||
patch.pop(key)
|
||||
current = read_settings()
|
||||
nxt = {**current, **patch}
|
||||
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||||
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
|
||||
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||
for key in ('tools', 'security', 'speech'):
|
||||
if key not in patch:
|
||||
continue
|
||||
if isinstance(patch[key], dict):
|
||||
nxt[key] = {**(current.get(key) or {}), **patch[key]}
|
||||
else:
|
||||
nxt[key] = current.get(key) or {}
|
||||
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||
if patch.get('apiKey') == '••••••••':
|
||||
nxt['apiKey'] = current.get('apiKey', '')
|
||||
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
|
||||
# 这个掩码会跟着 patch 回来。不处理的话真 Token 就被这八个点覆盖了,
|
||||
# 下次朗读直接报"缺 Token" —— 这类"看一眼就坏"的 bug 最难查。
|
||||
speech_next = nxt.get('speech')
|
||||
if isinstance(speech_next, dict):
|
||||
speech_cur = current.get('speech') or {}
|
||||
for secret in ('volcToken', 'volcApiKey', 'openaiApiKey'):
|
||||
if speech_next.get(secret) == '••••••••':
|
||||
speech_next[secret] = speech_cur.get(secret, '')
|
||||
# ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。
|
||||
# 引擎名一空,界面上一张卡片都不会高亮(看起来就是"设置被清空了");
|
||||
# 模型名一空,朗读/识别会直接调不通。
|
||||
# 注意 ttsVoice / volcAppId / sttLanguage 不在此列 —— 它们留空是合理需求
|
||||
# (留空 = 用引擎默认音色 / 还没填)。
|
||||
for key in ('ttsEngine', 'sttEngine', 'sttModel', 'ttsModel', 'volcCluster', 'volcEncoding'):
|
||||
if key in speech_next and isinstance(speech_next[key], str) and not speech_next[key].strip():
|
||||
speech_next[key] = speech_cur.get(key) or DEFAULT_SETTINGS['speech'].get(key, '')
|
||||
nxt['speech'] = speech_next
|
||||
nxt.pop('hasApiKey', None)
|
||||
_write_json(paths.get().settings_file, nxt)
|
||||
return nxt
|
||||
|
||||
|
||||
def provider_info(settings: dict, agent: dict = None) -> dict:
|
||||
"""
|
||||
当前提供商的完整信息(预设 + 生效的 baseUrl/model)。
|
||||
|
||||
★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。
|
||||
这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事,
|
||||
不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。
|
||||
"""
|
||||
agent = agent or {}
|
||||
provider_key = (agent.get('provider') or '').strip() or settings.get('provider')
|
||||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||||
return {
|
||||
**preset,
|
||||
'provider': provider_key,
|
||||
# baseUrl 也是三层:智能体 > 全局 > 预设
|
||||
'baseUrl': (agent.get('baseUrl') or '').strip() or settings.get('baseUrl') or preset.get('baseUrl', ''),
|
||||
'model': (agent.get('model') or '').strip() or settings.get('model') or preset.get('defaultModel', ''),
|
||||
}
|
||||
|
||||
|
||||
def agent_or_empty(agent_id: str) -> dict:
|
||||
"""按 id 找智能体;找不到返回空 dict(调用方按"没指定"处理)。
|
||||
|
||||
包一层是因为 get_agent 返回 None,而调用方(会议引擎、朗读路由)基本都是
|
||||
"有就用、没有就继承全局"的语义,到处写 `or {}` 太啰嗦。
|
||||
"""
|
||||
return get_agent(agent_id) or {}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 会话
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _rid_conv() -> str:
|
||||
# 和 Node 的 `c_${Date.now().toString(36)}_${random}` 同风格;不必逐字符相同
|
||||
return f'c_{_ts36()}_{_rand36(5)}'
|
||||
|
||||
|
||||
def _ts36() -> str:
|
||||
return _base36(int(datetime.now(timezone.utc).timestamp() * 1000))
|
||||
|
||||
|
||||
def _base36(num: int) -> str:
|
||||
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
|
||||
if num == 0:
|
||||
return '0'
|
||||
out = ''
|
||||
while num:
|
||||
num, rem = divmod(num, 36)
|
||||
out = digits[rem] + out
|
||||
return out
|
||||
|
||||
|
||||
def _rand36(length: int) -> str:
|
||||
import random
|
||||
|
||||
return ''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz') for _ in range(length))
|
||||
|
||||
|
||||
def _fresh_state() -> dict:
|
||||
stamp = now_iso()
|
||||
return {
|
||||
'conversations': [
|
||||
{
|
||||
'id': 'c_main',
|
||||
'title': '主对话',
|
||||
'agentId': 'a_doubao',
|
||||
'pinned': True,
|
||||
'createdAt': stamp,
|
||||
'updatedAt': stamp,
|
||||
'messages': [],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _load_conversations() -> dict:
|
||||
global _conv_state
|
||||
with _lock:
|
||||
if _conv_state is None:
|
||||
state = _read_json(paths.get().conversations_file)
|
||||
if state is None:
|
||||
state = _fresh_state()
|
||||
if not isinstance(state.get('conversations'), list) or not state['conversations']:
|
||||
state = _fresh_state()
|
||||
_conv_state = state
|
||||
return _conv_state
|
||||
|
||||
|
||||
def _persist_conversations() -> None:
|
||||
_write_json(paths.get().conversations_file, _load_conversations())
|
||||
|
||||
|
||||
def _preview_of(messages: list) -> str:
|
||||
"""列表预览:取最后一条有内容的消息,用户消息加"我:"前缀。"""
|
||||
for msg in reversed(messages or []):
|
||||
content = msg.get('content')
|
||||
if not content:
|
||||
continue
|
||||
text = re.sub(r'\s+', ' ', _as_text(content)).strip()
|
||||
if not text:
|
||||
continue
|
||||
tag = '我:' if msg.get('role') == 'user' else ''
|
||||
return f'{tag}{text[:30]}…' if len(text) > 30 else f'{tag}{text}'
|
||||
return ''
|
||||
|
||||
|
||||
def list_conversations() -> list:
|
||||
"""列表:带最后一条消息预览,置顶优先 + 更新时间倒序。"""
|
||||
items = list(_load_conversations()['conversations'])
|
||||
items.sort(
|
||||
key=lambda c: (1 if c.get('pinned') else 0, _as_text(c.get('updatedAt'))),
|
||||
reverse=True,
|
||||
)
|
||||
out = []
|
||||
for conv in items:
|
||||
messages = conv.get('messages') or []
|
||||
meta = {k: v for k, v in conv.items() if k != 'messages'}
|
||||
meta['messageCount'] = len(messages)
|
||||
meta['preview'] = _preview_of(messages)
|
||||
out.append(meta)
|
||||
return out
|
||||
|
||||
|
||||
def get_conversation(conv_id: str):
|
||||
for conv in _load_conversations()['conversations']:
|
||||
if conv.get('id') == conv_id:
|
||||
return conv
|
||||
return None
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
'title': title,
|
||||
'agentId': agent_id or '',
|
||||
'pinned': False,
|
||||
'createdAt': now_iso(),
|
||||
'updatedAt': now_iso(),
|
||||
'messages': [],
|
||||
}
|
||||
with _lock:
|
||||
_load_conversations()['conversations'].insert(0, item)
|
||||
_persist_conversations()
|
||||
return item
|
||||
|
||||
|
||||
def update_conversation(conv_id: str, patch: dict):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
with _lock:
|
||||
if isinstance(patch, dict):
|
||||
item.update(patch)
|
||||
item['updatedAt'] = now_iso()
|
||||
_persist_conversations()
|
||||
return item
|
||||
|
||||
|
||||
def delete_conversation(conv_id: str) -> bool:
|
||||
with _lock:
|
||||
state = _load_conversations()
|
||||
index = next((i for i, c in enumerate(state['conversations']) if c.get('id') == conv_id), -1)
|
||||
if index < 0:
|
||||
return False
|
||||
state['conversations'].pop(index)
|
||||
# 删光了就把"主对话"补回来,界面上不能出现空列表
|
||||
if not state['conversations']:
|
||||
state['conversations'].extend(_fresh_state()['conversations'])
|
||||
_persist_conversations()
|
||||
return True
|
||||
|
||||
|
||||
def append_messages(conv_id: str, messages: list):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
with _lock:
|
||||
item.setdefault('messages', []).extend(messages)
|
||||
item['updatedAt'] = now_iso()
|
||||
_persist_conversations()
|
||||
return item
|
||||
|
||||
|
||||
def auto_title(conv_id: str, text: str) -> None:
|
||||
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item or item.get('title') not in ('新对话', '主对话'):
|
||||
return
|
||||
title = re.sub(r'\s+', ' ', _as_text(text)).strip()[:18]
|
||||
if title:
|
||||
update_conversation(conv_id, {'title': title})
|
||||
|
||||
|
||||
def store_file_path() -> str:
|
||||
return paths.get().conversations_file
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 智能体可以独立指定的字段。**留空一律表示"继承全局设置"** ——
|
||||
# 这样"代码搭子走 DeepSeek、文案师用另一个音色"只改那一个智能体,
|
||||
# 而全局设置仍然是没配过的智能体的默认值。
|
||||
#
|
||||
# 提成常量是为了 create / update 两边不会漂移:
|
||||
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
|
||||
# 表现就是"界面上填了、保存后再打开又变空了"。
|
||||
AGENT_FIELDS = (
|
||||
'provider', # 走哪家(留空 = 全局)
|
||||
'model', # 用哪个模型
|
||||
'baseUrl', # 自定义网关地址
|
||||
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
|
||||
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
|
||||
'ttsSpeed', # 语速
|
||||
)
|
||||
|
||||
|
||||
def _rid_agent() -> str:
|
||||
return f'a_{_ts36()}_{_rand36(4)}'
|
||||
|
||||
|
||||
def list_agents() -> list:
|
||||
file_path = paths.get().agents_file
|
||||
if not os.path.isfile(file_path):
|
||||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||
return [dict(a) for a in DEFAULT_AGENTS]
|
||||
data = _read_json(file_path)
|
||||
if not isinstance(data, dict) or not isinstance(data.get('agents'), list) or not data['agents']:
|
||||
print('[store] agents.json 损坏,重建内置智能体', file=sys.stderr)
|
||||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||
return [dict(a) for a in DEFAULT_AGENTS]
|
||||
return data['agents']
|
||||
|
||||
|
||||
def get_agent(agent_id: str | None):
|
||||
if not agent_id:
|
||||
return None
|
||||
for agent in list_agents():
|
||||
if agent.get('id') == agent_id:
|
||||
return agent
|
||||
return None
|
||||
|
||||
|
||||
def create_agent(payload: dict) -> dict:
|
||||
payload = payload or {}
|
||||
state = {'agents': list_agents()}
|
||||
agent = {
|
||||
'id': _rid_agent(),
|
||||
'name': _as_text(payload.get('name') or '新智能体')[:24],
|
||||
'avatar': payload.get('avatar') or 'custom',
|
||||
'tagline': _as_text(payload.get('tagline'))[:40],
|
||||
'systemPrompt': _as_text(payload.get('systemPrompt')),
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
}
|
||||
# 智能体自己的模型/语音(留空 = 继承全局)
|
||||
for key in AGENT_FIELDS:
|
||||
if payload.get(key) is not None:
|
||||
agent[key] = _as_text(payload.get(key))
|
||||
state['agents'].append(agent)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
|
||||
|
||||
def update_agent(agent_id: str, patch: dict):
|
||||
state = {'agents': list_agents()}
|
||||
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
|
||||
if not agent:
|
||||
return None
|
||||
patch = patch or {}
|
||||
for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS):
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = patch[key]
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
|
||||
|
||||
def delete_agent(agent_id: str) -> bool:
|
||||
state = {'agents': list_agents()}
|
||||
index = next((i for i, a in enumerate(state['agents']) if a.get('id') == agent_id), -1)
|
||||
if index < 0:
|
||||
return False
|
||||
state['agents'].pop(index)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return True
|
||||
|
||||
|
||||
def reset_runtime_cache() -> None:
|
||||
"""测试/热重载用:丢掉会话内存缓存(设置本来就不缓存)。"""
|
||||
global _conv_state, _dotenv_loaded
|
||||
with _lock:
|
||||
_conv_state = None
|
||||
_dotenv_loaded = False
|
||||
168
desktop/main.cjs
168
desktop/main.cjs
@@ -1,168 +0,0 @@
|
||||
/**
|
||||
* 豆包 · LynxJS 复刻 —— Electron 桌面壳(CommonJS)
|
||||
*
|
||||
* 为什么用 CJS:Electron 主进程在 ESM 下解析 'electron' 会命中 npm 包
|
||||
* (那个包的 index.js 只导出二进制路径),拿不到 app/BrowserWindow。
|
||||
* 内核本身是 ESM,用动态 import() 加载即可。
|
||||
*
|
||||
* 主进程做三件事:
|
||||
* 1. 进程内直接启动 AI 内核(不额外起 node 子进程)
|
||||
* 2. 开一个手机比例窗口,加载 ?frame=0 的界面
|
||||
* 3. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去
|
||||
*/
|
||||
const { app, BrowserWindow, Menu, shell, dialog, clipboard } = require('electron');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
|
||||
/**
|
||||
* 可选:开一个 CDP 调试端口,方便用脚本截图/验证桌面窗口。
|
||||
*
|
||||
* 为什么需要:Electron 的界面只有真窗口才渲染得出来,光跑 curl 验不了;
|
||||
* 有了这个端口就能用 scripts/screenshot.mjs 附着上去截图(设 CDP_PORT 即可)。
|
||||
* 默认不开,避免平时多一个监听端口。
|
||||
*/
|
||||
if (process.env.DOUBAO_CDP_PORT) {
|
||||
app.commandLine.appendSwitch('remote-debugging-port', String(process.env.DOUBAO_CDP_PORT));
|
||||
app.commandLine.appendSwitch('remote-allow-origins', '*');
|
||||
}
|
||||
|
||||
// 打包后应用根目录是 resources/app(若打成 asar 则是 resources/app.asar);开发时是仓库根
|
||||
const appRoot = app.isPackaged
|
||||
? [
|
||||
path.join(process.resourcesPath, 'app'),
|
||||
path.join(process.resourcesPath, 'app.asar'),
|
||||
].find((p) => fs.existsSync(p)) || path.join(process.resourcesPath, 'app')
|
||||
: path.resolve(__dirname, '..');
|
||||
|
||||
// 打包后的自有资源放在 <appRoot>/runtime,开发时直接用仓库根
|
||||
const bundledRuntime = path.join(appRoot, 'runtime');
|
||||
const runtimeRoot = fs.existsSync(bundledRuntime) ? bundledRuntime : appRoot;
|
||||
|
||||
process.env.DOUBAO_RESOURCES = runtimeRoot;
|
||||
process.env.DOUBAO_TOOLS = path.join(runtimeRoot, 'tools');
|
||||
process.env.DOUBAO_DATA = path.join(app.getPath('userData'), 'data');
|
||||
|
||||
const serverEntry = path.join(appRoot, 'server', 'src', 'index.mjs');
|
||||
|
||||
// 给内核挂几个桌面能力钩子:定位配置文件、用系统浏览器打开链接、原生选文件、写剪贴板。
|
||||
// 内核自己不认识 Electron,有钩子就用,没有就降级。
|
||||
globalThis.__doubaoReveal = (target) => shell.showItemInFolder(target);
|
||||
globalThis.__doubaoOpenExternal = (url) => shell.openExternal(url);
|
||||
globalThis.__doubaoClipboard = (text) => clipboard.writeText(String(text));
|
||||
globalThis.__doubaoPickFile = async () => {
|
||||
const result = await dialog.showOpenDialog({
|
||||
title: '选择要发给豆包的文件',
|
||||
buttonLabel: '发送',
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
filters: [
|
||||
{
|
||||
name: '常用文件',
|
||||
extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'txt', 'md', 'json', 'csv',
|
||||
'log', 'yml', 'yaml', 'py', 'js', 'ts', 'tsx', 'html', 'css', 'pdf'],
|
||||
},
|
||||
{ name: '所有文件', extensions: ['*'] },
|
||||
],
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
};
|
||||
|
||||
let kernel = null;
|
||||
let win = null;
|
||||
|
||||
/** 启动内核:默认 5199,被占用就换随机端口 */
|
||||
async function startKernelWithFallback() {
|
||||
const { startKernel } = await import(pathToFileURL(serverEntry).href);
|
||||
const preferred = Number(process.env.DOUBAO_PORT || 5199);
|
||||
try {
|
||||
return await startKernel({ port: preferred, quiet: true });
|
||||
} catch (err) {
|
||||
if (err && err.code === 'EADDRINUSE') {
|
||||
console.warn(`[desktop] 端口 ${preferred} 被占用,改用随机端口`);
|
||||
return startKernel({ port: 0, quiet: true });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(url) {
|
||||
win = new BrowserWindow({
|
||||
width: 420,
|
||||
height: 900,
|
||||
minWidth: 360,
|
||||
minHeight: 620,
|
||||
title: '豆包',
|
||||
backgroundColor: '#ffffff',
|
||||
autoHideMenuBar: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
spellcheck: false,
|
||||
},
|
||||
});
|
||||
|
||||
// 界面是移动端比例,菜单栏只会碍事:去掉,改用快捷键
|
||||
Menu.setApplicationMenu(null);
|
||||
win.once('ready-to-show', () => win.show());
|
||||
|
||||
win.webContents.on('before-input-event', (event, input) => {
|
||||
const key = (input.key || '').toLowerCase();
|
||||
if (key === 'f12' || (input.control && input.shift && key === 'i')) {
|
||||
win.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
} else if (input.control && key === 'r') {
|
||||
win.webContents.reload();
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// 外链交给系统浏览器
|
||||
win.webContents.setWindowOpenHandler(({ url: target }) => {
|
||||
if (/^https?:/i.test(target)) shell.openExternal(target);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
win.webContents.on('will-navigate', (event, target) => {
|
||||
if (!target.startsWith(url)) {
|
||||
event.preventDefault();
|
||||
if (/^https?:/i.test(target)) shell.openExternal(target);
|
||||
}
|
||||
});
|
||||
|
||||
win.loadURL(`${url}?frame=0`);
|
||||
return win;
|
||||
}
|
||||
|
||||
// 只允许开一个实例,第二次启动就把已有窗口拉到前面
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', () => {
|
||||
if (win) {
|
||||
if (win.isMinimized()) win.restore();
|
||||
win.focus();
|
||||
}
|
||||
});
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
app.setAppUserModelId('com.doubao.lynxclone');
|
||||
try {
|
||||
kernel = await startKernelWithFallback();
|
||||
createWindow(kernel.url);
|
||||
console.log(`[desktop] 内核就绪:${kernel.url} 资源:${runtimeRoot}`);
|
||||
console.log(`[desktop] 数据目录:${process.env.DOUBAO_DATA}`);
|
||||
} catch (err) {
|
||||
dialog.showErrorBox('豆包启动失败', String((err && err.stack) || (err && err.message) || err));
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', async () => {
|
||||
try {
|
||||
if (kernel) await kernel.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
NOTES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
|
||||
TOOL = {
|
||||
"name": "notes",
|
||||
"description": "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,action=search 关键词搜索。适合记录用户偏好、待办、结论。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["save", "list", "read", "search"], "description": "要做的操作"},
|
||||
"title": {"type": "string", "description": "save 时的标题"},
|
||||
"content": {"type": "string", "description": "save 时的正文"},
|
||||
"query": {"type": "string", "description": "search 时的关键词"},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ensure_dir():
|
||||
os.makedirs(NOTES_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def slug(title):
|
||||
safe = re.sub(r'[\\/:*?"<>|\s]+', "-", title.strip())[:40]
|
||||
return safe or "note"
|
||||
|
||||
|
||||
def run(args):
|
||||
ensure_dir()
|
||||
action = str(args.get("action", "list")).lower()
|
||||
|
||||
if action == "save":
|
||||
title = str(args.get("title", "")).strip() or "未命名"
|
||||
content = str(args.get("content", ""))
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
path = os.path.join(NOTES_DIR, f"{stamp}-{slug(title)}.md")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(f"# {title}\n\n{content}\n")
|
||||
return {"saved": os.path.basename(path), "title": title, "chars": len(content)}
|
||||
|
||||
if action == "list":
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
items = []
|
||||
for name in files[:50]:
|
||||
full = os.path.join(NOTES_DIR, name)
|
||||
with open(full, encoding="utf-8") as fh:
|
||||
first = fh.readline().strip().lstrip("# ")
|
||||
items.append({"file": name, "title": first, "bytes": os.path.getsize(full)})
|
||||
return {"count": len(files), "notes": items}
|
||||
|
||||
if action == "read":
|
||||
name = str(args.get("title") or args.get("query") or "").strip()
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
hit = next((f for f in files if name and name in f), None)
|
||||
if not hit:
|
||||
return {"ok": False, "error": f"没找到匹配 {name} 的笔记"}
|
||||
with open(os.path.join(NOTES_DIR, hit), encoding="utf-8") as fh:
|
||||
return {"file": hit, "content": fh.read()[:4000]}
|
||||
|
||||
if action == "search":
|
||||
query = str(args.get("query", "")).strip()
|
||||
if not query:
|
||||
raise ValueError("search 需要 query")
|
||||
hits = []
|
||||
for name in sorted(os.listdir(NOTES_DIR), reverse=True):
|
||||
with open(os.path.join(NOTES_DIR, name), encoding="utf-8") as fh:
|
||||
text = fh.read()
|
||||
if query in text:
|
||||
idx = text.index(query)
|
||||
hits.append({"file": name, "excerpt": text[max(0, idx - 60): idx + 120]})
|
||||
if len(hits) >= 20:
|
||||
break
|
||||
return {"query": query, "hits": hits}
|
||||
|
||||
raise ValueError(f"不支持的 action: {action}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
227
web/index.html
227
web/index.html
@@ -1,227 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<title>豆包 · LynxJS 复刻</title>
|
||||
<link rel="stylesheet" href="/static/css/client.css" />
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
background: radial-gradient(120% 120% at 50% 0%, #23262f 0%, #0e1014 60%);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
|
||||
'Microsoft YaHei', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.stage {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 28px;
|
||||
}
|
||||
.phone {
|
||||
position: relative;
|
||||
width: 390px;
|
||||
height: 844px;
|
||||
border-radius: 42px;
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 30px 70px rgba(0, 0, 0, 0.6), 0 0 0 10px #1b1e25,
|
||||
0 0 0 11px #33373f;
|
||||
}
|
||||
.phone > lynx-view {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.side {
|
||||
color: #9aa3b2;
|
||||
font-size: 13px;
|
||||
line-height: 1.9;
|
||||
max-width: 280px;
|
||||
}
|
||||
.side h1 {
|
||||
font-size: 17px;
|
||||
color: #e8ecf3;
|
||||
margin: 0 0 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.side code {
|
||||
background: #1b1f27;
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
color: #9fd0ff;
|
||||
}
|
||||
.side button {
|
||||
margin-top: 12px;
|
||||
background: #2b7bff;
|
||||
color: #fff;
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
padding: 9px 14px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.side .tip {
|
||||
margin-top: 8px;
|
||||
color: #6b7482;
|
||||
font-size: 12px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.side {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@media (max-width: 460px), (max-height: 880px) {
|
||||
.phone {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
/* 桌面客户端模式:?frame=0 —— 去掉手机外壳,铺满窗口 */
|
||||
html.frameless .stage {
|
||||
display: block;
|
||||
}
|
||||
html.frameless .phone {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
html.frameless .side {
|
||||
display: none;
|
||||
}
|
||||
/* 拖拽上传遮罩 */
|
||||
#drop-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(43, 123, 255, 0.14);
|
||||
border: 3px dashed #2b7bff;
|
||||
box-sizing: border-box;
|
||||
color: #2b7bff;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
}
|
||||
#drop-mask.on {
|
||||
display: flex;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="stage">
|
||||
<div class="phone">
|
||||
<lynx-view url="/main.web.bundle"></lynx-view>
|
||||
</div>
|
||||
<aside class="side">
|
||||
<h1>豆包 · LynxJS 复刻</h1>
|
||||
界面由 <code>ReactLynx</code> 渲染,跑在 <code>@lynx-js/web-core</code> 上。<br />
|
||||
AI 内核在 <code>/api</code>:火山方舟 / OpenAI + MCP + Python 工具。<br />
|
||||
左上角 <code>☰</code> 是会话抽屉,右上角 <code>✎</code> 是内核设置。
|
||||
<div>
|
||||
<button id="pick">选择文件发给豆包</button>
|
||||
<div class="tip">也可以直接把文件拖进这个窗口。</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<div id="drop-mask">松手即可发送文件</div>
|
||||
<input id="file-input" type="file" multiple style="display: none" />
|
||||
|
||||
<script>
|
||||
// ?page=drawer|profile|settings|skills|agents 指定首屏;?frame=0 进桌面客户端模式
|
||||
(function () {
|
||||
var params = new URLSearchParams(location.search);
|
||||
if (params.get('frame') === '0') {
|
||||
document.documentElement.classList.add('frameless');
|
||||
}
|
||||
var wanted = params.get('page');
|
||||
if (wanted) {
|
||||
document
|
||||
.querySelector('lynx-view')
|
||||
.setAttribute('global-props', JSON.stringify({ initialPage: wanted }));
|
||||
}
|
||||
})();
|
||||
|
||||
/**
|
||||
* 文件上传:浏览器和桌面版共用同一条路 ——
|
||||
* 传到 /api/upload 并标记为 pending,Lynx 界面轮询到之后自动挂到输入框上。
|
||||
*/
|
||||
(function () {
|
||||
var mask = document.getElementById('drop-mask');
|
||||
|
||||
function readAsDataUrl(file) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var reader = new FileReader();
|
||||
reader.onload = function () {
|
||||
resolve(reader.result);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
async function upload(files) {
|
||||
for (var i = 0; i < files.length; i += 1) {
|
||||
var file = files[i];
|
||||
try {
|
||||
var dataUrl = await readAsDataUrl(file);
|
||||
await fetch('/api/upload', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: file.name, dataUrl: dataUrl, pending: true }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[upload] 失败', file.name, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var depth = 0;
|
||||
window.addEventListener('dragenter', function (e) {
|
||||
e.preventDefault();
|
||||
depth += 1;
|
||||
mask.classList.add('on');
|
||||
});
|
||||
window.addEventListener('dragover', function (e) {
|
||||
e.preventDefault();
|
||||
});
|
||||
window.addEventListener('dragleave', function (e) {
|
||||
e.preventDefault();
|
||||
depth = Math.max(0, depth - 1);
|
||||
if (depth === 0) mask.classList.remove('on');
|
||||
});
|
||||
window.addEventListener('drop', function (e) {
|
||||
e.preventDefault();
|
||||
depth = 0;
|
||||
mask.classList.remove('on');
|
||||
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) {
|
||||
upload(e.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
|
||||
var pick = document.getElementById('pick');
|
||||
var input = document.getElementById('file-input');
|
||||
if (pick && input) {
|
||||
pick.addEventListener('click', function () {
|
||||
input.click();
|
||||
});
|
||||
input.addEventListener('change', function () {
|
||||
if (input.files && input.files.length) upload(input.files);
|
||||
input.value = '';
|
||||
});
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script type="module" src="/static/js/client.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
0
.gitattributes → 豆鲍/.gitattributes
vendored
0
.gitattributes → 豆鲍/.gitattributes
vendored
106
豆鲍/.gitignore
vendored
Normal file
106
豆鲍/.gitignore
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 依赖(几百 MB,clone 后 `npm run install:all` 自己装)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
node_modules/
|
||||
.npm-cache/
|
||||
desktop/node_modules/
|
||||
desktop/dist-staging/
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 构建产物
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
dist-android/
|
||||
dist-win/
|
||||
dist-docs/
|
||||
app/dist/
|
||||
web/dist/
|
||||
android/app/build/
|
||||
android/build/
|
||||
android/.gradle/
|
||||
android/local.properties
|
||||
build/
|
||||
.gradle/
|
||||
*.tsbuildinfo
|
||||
*.apk
|
||||
*.aab
|
||||
*.exe
|
||||
*_boot.zip
|
||||
|
||||
# 打包中间产物(electron 二进制与暂存目录都很大)
|
||||
android/app/src/main/assets/main.lynx.bundle
|
||||
.rasterize-*
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 密钥 / 个人配置 —— 这些**绝不能**提交
|
||||
#
|
||||
# settings.json 里有 apiKey 字段(现在是占位值,但随时可能填真 Key);
|
||||
# mcp.servers.json 里有本机绝对路径。
|
||||
# 示例文件(*.example.*)是给别人做模板用的,要提交。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
server/.env
|
||||
server/.env.*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.local
|
||||
server/config/settings.json
|
||||
tools/mcp.servers.json
|
||||
app/config/settings.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 运行时数据
|
||||
#
|
||||
# ★ 注意:这里的 `data/` 规则**不能写成裸 `data/`** —— gitignore 的 `data/`
|
||||
# 会匹配**任何一层**名叫 data 的目录,于是把安卓的源码包
|
||||
# `android/app/src/main/java/com/doubao/lynxclone/data/`(KernelClient.kt /
|
||||
# Models.kt …)也一起忽略了:那些文件从来没进过 git,新克隆构建不了。
|
||||
# 只忽略**确实是运行时数据**的三处:仓库根 / server / 内核。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
/data/
|
||||
server/data/
|
||||
android/kernel/data/
|
||||
phone-verify-result.json
|
||||
*.log
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Termux 的两个 bootstrap(各 28 MB,共 56 MB)
|
||||
#
|
||||
# 这两个 .so 是**手动**从 Termux 的 APK 里取出来放进 jniLibs 的,
|
||||
# 仓库里没有脚本能重新生成(fetch-termux.mjs 只把 APK 下到缓存)。
|
||||
# 56 MB 的二进制不适合跟着代码走,所以单独排除;
|
||||
# 要构建 APK 见 README「4.2 APK 里到底装了什么」。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
android/app/src/main/jniLibs/*/libtermux-bootstrap.so
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Python
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 编辑器 / 系统
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
*.swp
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
.DS_Store
|
||||
|
||||
# 调试时生成的临时探针
|
||||
.tmp/
|
||||
.tmp-*
|
||||
|
||||
# 豆包网页版参考镜像(第三方资源,仅本地研究/对照用,不入库)
|
||||
reference/doubao-web-mirror/
|
||||
|
||||
# 嵌入式 Python 缓存(打包 exe 时自动下载;体积 ~10MB,不入库)
|
||||
desktop/build-cache/
|
||||
|
||||
# 豆包网页版抓取脚本的产物
|
||||
.tmp-scrape/
|
||||
542
豆鲍/AGENTS.md
Normal file
542
豆鲍/AGENTS.md
Normal file
@@ -0,0 +1,542 @@
|
||||
# 项目约定
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
|
||||
---
|
||||
|
||||
# 代码托管
|
||||
|
||||
## 两个 remote,同一个仓库
|
||||
|
||||
| remote | 地址 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `local` | `http://192.168.100.103:8080/l/doubao-clone.git` | **在家/局域网,优先用这个**(快) |
|
||||
| `origin` | `https://git.xnhw.cc/l/doubao-clone.git` | 不在局域网时 |
|
||||
|
||||
两个地址指向**同一台服务器**(`git.xnhw.cc` 在外网解析到 `64.49.47.22`,
|
||||
局域网里就是 `192.168.100.103:8080`)。推哪个都行,别同时推两遍。
|
||||
|
||||
服务是 **Noir's Git**(Gitea 系)。
|
||||
|
||||
## 推送
|
||||
|
||||
```bash
|
||||
git push local main # 日常
|
||||
git push local --tags # 标签
|
||||
```
|
||||
|
||||
`local` 的凭据存在 `.git/config` 的 remote URL 里(`.git` 不属于仓库内容,
|
||||
不会被提交)—— 所以不用每次输密码。
|
||||
|
||||
## 一个坑:push 报 401 时会**假装卡住**
|
||||
|
||||
这个服务器上 `receive-pack`(推送)要认证,而 `upload-pack`(拉取)不用。
|
||||
凭据不对时 git 会**挂在等密码输入上,一行输出都没有** ——
|
||||
看起来像网络卡死,其实是在等 stdin。
|
||||
|
||||
所以:
|
||||
- 脚本里推之前先设 `GIT_TERMINAL_PROMPT=0`(让它直接失败而不是等)
|
||||
- 或者直接确认 remote URL 里有凭据
|
||||
|
||||
排查顺序:
|
||||
```bash
|
||||
git ls-remote <url> # GET 通不通(不需要认证也能通)
|
||||
curl -i "<url>/info/refs?service=git-receive-pack" # 401 就是认证问题
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 界面约定
|
||||
|
||||
适用于本仓库的 Android / Compose 界面。
|
||||
|
||||
## 少用弹窗,能开界面就开界面
|
||||
|
||||
用户明确要求:**尽量减少弹窗那种,能加界面就加界面。**
|
||||
|
||||
理由(也是判断标准):
|
||||
|
||||
- **弹窗装不下东西**。一屏对话框的高度大概只够三四行内容,一旦要放的
|
||||
东西超过这个量(列表、代码框、多组配置),用户就得在弹窗里滚动 ——
|
||||
那还不如直接开一屏。
|
||||
- **弹窗会互相压**。弹窗里再弹一个(比如"变量管理"里点"新建",
|
||||
或者"节点管理"里点"编辑")在手机上是灾难:返回键的行为变得说不清,
|
||||
用户也不知道自己在第几层。
|
||||
- **弹窗盖住上下文**。这个 App 的会议画布本身就是要看着的,
|
||||
一个盖住半屏的对话框让人没法一边看图一边改配置。
|
||||
|
||||
### 该怎么做
|
||||
|
||||
| 内容量 | 用什么 |
|
||||
|---|---|
|
||||
| 一次确认("要删除吗") | `AlertDialog` ✓ 弹窗合适 |
|
||||
| 纯菜单(两三个入口,点完就走) | 底部弹层或 `AlertDialog` ✓ |
|
||||
| 列表 / 多组配置 / 代码 / 任何要滚动的 | **独立全屏界面**,顶栏 `← 返回` + 标题 + 右侧动作 |
|
||||
|
||||
### 全屏界面的骨架
|
||||
|
||||
统一用同一套顶栏,别各写各的(不然返回的位置、标题的大小、
|
||||
右边按钮的样式会到处不一样):
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
```
|
||||
|
||||
参考实现:`NodeBlockEditorScreen`(`NodeBlockEditor.kt`)的顶栏。
|
||||
|
||||
### 返回键
|
||||
|
||||
全屏界面要能被系统返回键关掉(用状态变量控制显示时,
|
||||
记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 ——
|
||||
比弹窗还糟。
|
||||
|
||||
## 全屏化的进度
|
||||
|
||||
**已经改完全屏的**:
|
||||
- ✅ 节点管理 `NodeManagerScreen`
|
||||
- ✅ 节点编辑 `NodeCodeScreen`(代码框占满剩余高度)
|
||||
- ✅ 积木编辑器 `NodeBlockEditorScreen`
|
||||
|
||||
**还欠着的**:
|
||||
- [ ] 变量管理 `VarManagerDialog` → 全屏
|
||||
- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层
|
||||
- [ ] 导入会议 `ImportDialog` → 全屏
|
||||
- [ ] 节点配置 `NodeConfigDialog` → 全屏(字段很多)
|
||||
|
||||
**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。
|
||||
|
||||
### 改全屏时踩的坑:界面的 return 顺序
|
||||
|
||||
全屏界面是用状态变量 + `return@Composable` 实现的,于是**谁在上面谁优先**:
|
||||
|
||||
```kotlin
|
||||
blockEdit?.let { ...; return@MeetingEditorScreen } // 积木编辑器
|
||||
if (showNodeMgr) { ...; return@MeetingEditorScreen } // 节点管理
|
||||
if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
```
|
||||
|
||||
在下面的界面要显示时,**必须先把它上面的那个状态关掉** ——
|
||||
否则上面的先 return,下面的永远轮不到渲染。
|
||||
表现是"点了没反应",其实状态全对了,只是没机会画(这个 bug 真出现过)。
|
||||
|
||||
## 内核 / AI 功能约定(v3.16 起)
|
||||
|
||||
- **★★ 每加一个用户可感知的新功能 / 新工具,必须同步更新内置 Skill 手册**
|
||||
(`android/kernel/defaults.py` 的 `BUILTIN_SKILL`)。
|
||||
用户原话:「模型还不会用新功能,你每加新功能都要写skill」——
|
||||
界面上有、AI 不知道的功能等于不存在。
|
||||
写的时候讲**什么时候用 / 用完之后不许干什么**,不要重复工具 description。
|
||||
跑 `python scripts/probe-context.py`(§9 会检查关键词)和
|
||||
`python scripts/probe-agent-system.py` 确认没漏。
|
||||
- **★★ 功能变了 → 同步「全功能总体说明」和宣传资料包**(用户需求:拿它到别的对话里
|
||||
做介绍网页和商店)。产品功能的**唯一宣传口径**是
|
||||
[`docs/总体说明-所有功能.md`](docs/总体说明-所有功能.md)(功能清单/版本里程碑/
|
||||
卖点/截图清单/商店建议都在这)。新增或修改用户可感知功能后:
|
||||
1. 更新 `docs/总体说明-所有功能.md` 对应小节 + 里程碑 + 第 11 节截图清单;
|
||||
2. 新截图放 `docs/screenshots/`(功能细节可以放 `docs/assets/v3.20/`);
|
||||
要当**宣传图**的截图同时加进 `scripts/build-docs-pack.py` 的 `PROMO_ITEMS`
|
||||
(zip 里生成 `宣传图/01~NN-中文名.png` + `宣传图/00-素材说明.md`)。
|
||||
★ 用户明确要求「**宣传图只要截图就行**」——不要另做设计稿/海报,直接用真实截图;
|
||||
3. 跑 `python scripts/build-docs-pack.py` 生成
|
||||
`dist-docs/小人间-资料包-v<内核文档版本>.zip`(`dist-docs/` 不进 git),
|
||||
并用“zip 内 markdown 图片引用全部命中”自查(打包脚本会打印缺文件)。
|
||||
写介绍网页/商店文案时**只写总体说明里有的功能**,不要编。
|
||||
- **上下文组装只有一份**:`android/kernel/chat_context.py` 的 `assemble()`。
|
||||
真发消息(`_perform_chat`)和上下文查看器(`/api/conversations/<id>/context`)
|
||||
都调它 —— 查看器的全部价值就是"所见即所发",别在别处再拼一遍。
|
||||
- **地点可见性用 `place_visits.first_seq`(第一次进入),不要用 `place_states.entered_seq`
|
||||
(最近一次)**:后者会在"离开再回来"时把角色自己经历过的话藏掉
|
||||
(v3.16 用户反馈「同容器不同对话的上下文会丢」的根因)。
|
||||
- **记忆默认私有**(`agent_context.memory_scope`);共享板子要显式
|
||||
`memory_add(shared=true)`(`agent_context.shared_memory_scope`)。
|
||||
一次性迁移用 `agent.db` 的 `meta` 表记标记 —— **别写"每次启动都跑"的迁移**,
|
||||
它会把手写的新数据也搬走。
|
||||
- **独自一人的地点禁言**:内核 `place_engine.chat_guard()` 是权威,
|
||||
界面 `AppViewModel.alonePlaceName()` 只是提前拦截(数据可能旧)。
|
||||
- **函数里不要在"已经用过"之后才写局部 `import store`**:Python 会把该名字当成
|
||||
整个函数的局部变量,前面的用法直接 `UnboundLocalError`。真机报过
|
||||
「give_item 调用失败:cannot access local variable 'store'」——
|
||||
模块顶部已经 import 的,函数里就别再写;确有循环依赖要局部 import 的,
|
||||
放到函数**第一行**。改完内核跑 `probe-items` §12(有 give_item → 用户角色回归)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `android/nodekit/`**(独立模块)。
|
||||
节点类型、引脚、算子、配色、几何、形状**只有那一份** ——
|
||||
`MeetingsScreen.kt` 里**不要再写 `when (node.type)` 的长表**(默认标题、颜色、
|
||||
引脚、配置面板标题都从库查)。
|
||||
加一种节点看 [docs/节点库.md](docs/节点库.md) 的清单,改完跑
|
||||
`python scripts/verify-nodekit.py`(它会拿库和 Python 引擎逐项对拍)。
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`Ops.ALL` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
只改一半,用户会说"你不会举一反三的吗"。
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」),
|
||||
事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走
|
||||
`applyMeetingEvent`。
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
- **代码框不能软换行**。` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
就是语法。这个 Compose 版本(BOM 2024.09.03)的 `BasicTextField`
|
||||
经典重载选不中,所以用"把输入框塞进足够宽的横向滚动容器"来达到同样效果。
|
||||
- **代码框要有高度上限**。只写 `heightIn(min=...)` 的话,文件一长框就长到
|
||||
屏幕外,把底下的补全条顶出去,用户够不着。
|
||||
- **改了没生效就先怀疑工具**。PowerShell 的 `String.Replace` **匹配失败不报错**;
|
||||
按行号剪贴会算错下标(甚至把整个文件追加一遍);
|
||||
`git checkout -- <文件>` 会还原**这一轮所有未提交的改动**。
|
||||
改完立刻 grep 确认,动手前先断言下标有效。
|
||||
- **莫名其妙的"未解析引用"先数括号**。漏一个 `}` 会让后面所有顶层声明
|
||||
全部报未解析,错误信息看着完全不像是括号问题(报的是 `PrimaryButton`
|
||||
找不到这种)。
|
||||
|
||||
|
||||
## 品牌名(v3.17 起:小人间)
|
||||
|
||||
App 的对外显示名从「豆包」改成了「小人间」——这是**显示名**,不是包名/仓库名。
|
||||
|
||||
- **Android 显示名的唯一来源**:`android/app/src/main/res/values/strings.xml`
|
||||
的 `app_name`(桌面图标、最近任务、通知使用权列表都读它)。
|
||||
另有几处写死的自我介绍(抽屉标题、关于页、通知兜底标题、空态问候语),
|
||||
改名时一起 `grep -rn "小人间" android/app/src/main`。
|
||||
- **网页端**:`web/index.html`(title / boot-logo / favicon)、`web/js/app.js`
|
||||
(侧栏 logo、`setTitle`、关于入口)、`web/js/pages/about.js`(关于页标题/图标)。
|
||||
- **启动图标**:`python scripts/make-launcher-icon.py` 生成 legacy PNG;
|
||||
`res/mipmap-anydpi-v26/ic_launcher*.xml` 是自适应图标,前景/单色层在
|
||||
`res/drawable/ic_launcher_foreground.xml` / `ic_launcher_monochrome.xml`。
|
||||
几何数字是同一套 108 单位画布(安全区 21..87),改图标要两边一起改。
|
||||
- **通知小图标必须是单色剪影**(`res/drawable/ic_notify.xml`):
|
||||
自适应图标是 108dp 图层组合,直接 `setSmallIcon(applicationInfo.icon)`
|
||||
在部分机型上会渲成空白/黑块。
|
||||
- **没跟着改的**(仍用旧名,要换得单独迁移):包名 `com.doubao.lynxclone`、
|
||||
内核数据目录、仓库名「豆鲍」、桌面端 productName、内置角色「豆包」
|
||||
(那是角色名)、模型/语音服务商名(豆包 Pro / 豆包语音)。
|
||||
|
||||
## 决斗 / 状态 / 数值约定(v3.17 起;v3.18 武器;v3.19 换武器/无回合上限/四种结果;v3.29 数值也间接)
|
||||
|
||||
- **状态不能直接赋值**:AI 工具里**没有** `grant_status`(已删除)。
|
||||
状态只能由 ① 物品脚本 ② 世界脚本 ③ 用户手动 产生。
|
||||
加新的"能给状态"的通道时先想清楚:**它算不算开挂**(用户原话:
|
||||
「状态赋值只能是物品间接,不然先开挂一样」)。别把它加回 AI 工具表。
|
||||
- **数值也一样只能间接改(v3.29)**:用户原话「**数值也是间接改**」——
|
||||
AI 工具里**没有** `change_stat`(已删除)。数值只能由 ① 物品脚本
|
||||
(`api['change_stat']`)② 世界脚本 ③ 用户手动 改。加"能改数值"的 AI 工具
|
||||
等于开挂,别加;底层 `rule_engine.change` 保留(脚本/界面走它)。
|
||||
- **`give_item` 所有 AI 都能用,但只能"转移"、不能造物(v3.29)**:用户拍板
|
||||
「所有 AI 都可用 give_item」「不能 AI 自己创建物品」。
|
||||
- `give_item` 在默认工具表里(不按角色开关)——它把**自己背包里现有的**东西
|
||||
转给别人(`_find_bag_item` 先查自己身上有没有;没有/不够直接报错);
|
||||
- **AI 不能被授予"造物"能力**:物品产出只走 ① 物品脚本(`api['give_item']`,
|
||||
例如工作台带材料加工)② 世界/常驻角色规则 ③ 用户手动。别给 AI 加"凭空生成物品"
|
||||
的工具;`item_engine.grant` 只能由脚本/用户接口调用,别接到 AI 工具上;
|
||||
- 回归:`probe-items` §8(赠与)/§15(工具表 + **合计数量不变 = 只转移不造物**、
|
||||
背包没有的物品不能凭空给)、`probe-group-chat` §7(give_item 在表里)、
|
||||
`probe-context` §9(Skill 关键词)、`probe-rule-engine` §14–15(没有 change_stat)。
|
||||
- **决斗是多回合、绑对话、中断要双方同意,而且必须有武器**(v3.18):
|
||||
- 引擎在 `android/kernel/duel_engine.py`,表 `agent.db/duels`;
|
||||
- 一场决斗绑 `conversationId`(**不开新会话**,和私聊一样),聊天页有决斗条;
|
||||
- **武器 = 背包里的 `target` 类物品**(用户原话:「决斗必须要武器。没有target类物品
|
||||
的一方宣告失败」)。开局只有一方没有 → 那一方**当场判负**(`finished`、`round:0`,
|
||||
不调 `on_duel`);双方都没有 → 报错打不起来;武器用光/丢了 → 判负。
|
||||
判定只在 `duel_engine.weapons_of/_weapon_check` 里做,**别下放到脚本/界面**,
|
||||
也别给 AI 开"免武器决斗"的口子。武器列表进快照(`weapons` / `hasWeapon`),界面要显示;
|
||||
- **每回合双方各用自己的当前武器出手一次**(v3.19):内核替双方对"对方"调用
|
||||
`item_engine.use()` → 跑**这件物品自己的脚本**(`on_receive`),再按物品规则扣数量;
|
||||
`unlimited: true`(∞)的武器**不消耗**(用户原话:「有些武器不应该消耗比如拳头,木棍等」)。
|
||||
顺序固定:先双方武器出手 → 再调世界脚本;
|
||||
- **状态剩余轮数每回合 -1(v3.27)**:决斗每回合双方出完手后给两边
|
||||
`rule_engine.tick_statuses`(和聊天里"参与一轮 -1"同语义;persistent 不减)。
|
||||
以前整场不 tick:中毒(剩 3 轮)打到第 10 回合还写 3
|
||||
(用户反馈「状态不会随轮数减少 还有决斗也是」)。
|
||||
**状态脚本 `on_turn` 仍不在决斗里跑**(决斗的掉血/挂状态由世界+物品脚本裁决),
|
||||
这里只负责"剩余轮数过期"。
|
||||
- **每回合都能换武器**(用户原话「如何选择武器?」):`duel_engine.choose_weapon` /
|
||||
`POST /api/duels/<id>/weapon`;界面 `DuelScreen` 里点 chips 换。不选/用完了自动挑
|
||||
(优先 ∞ 不消耗的,其次背包第一件);
|
||||
- **没有回合上限**(用户原话「没有回合限制」):世界包 `info.duelMaxRounds` 作废,
|
||||
`api['max_rounds']` 恒为 0;决斗只在 ① `end_duel` ② 一方没武器 ③ 双方同意停手 时结束;
|
||||
- 世界脚本 `on_duel(initiator, target, api)` **每回合调用一次**,上下文有
|
||||
`api['round']` / `api['duel_id']` / `api['weapons']`;收尾调
|
||||
`api['end_duel']('结果文本', '赢家名字')` —— **只给结果不给赢家 = 平局**;
|
||||
- **四种结果状态**(用户原话「有输,赢,平局,停手,4种状态」):快照每方一个
|
||||
`outcome` = `win` / `lose` / `draw` / `stop`,界面显示成 **赢 / 输 / 平局 / 停手**。
|
||||
`interrupted`(双方同意罢手)→ 双方都是 `stop`;没武器判负 → 赢/输;双方同一回合
|
||||
都没武器 / 脚本没给赢家 → 平局;
|
||||
- 罢手必须对方同意:对方是 AI 时内核发一次单独的模型调用问它(失败按"同意"
|
||||
兜底,避免卡死);对方是用户角色时界面出「同意罢手 / 继续打」;
|
||||
- 客户端只在**界面层**推进回合/发起罢手,判定权在脚本和对方。
|
||||
- **界面入口**:聊天页**长按 @成员** →「私聊 / 决斗」二选一;
|
||||
决斗全屏页 `DuelScreen`(已在 `docs/界面总览.md` 登记,审计会检查),
|
||||
里面有「我的武器(每回合可换)」chips、四种结果状态的大字、无回合上限的回合文案。
|
||||
- **用户手动操作和 AI 同一条引擎**:`item_engine.use(...)`(使用/带材料 `with`/抛弃/赠与);
|
||||
v3.21 起用户手动使用也支持带材料(`POST /api/containers/<id>/items/action` 的 `with`),
|
||||
工作台这类物品脚本 `return False` 时**不能假装成功**(400 + 脚本旁白原因)。
|
||||
- **每回合只能用一件物品(v3.22)**:默认用当前武器攻击;也可选一件**被动物品**
|
||||
(`kind:'passive'`,如血瓶)→ 这回合跑它的 `on_use`、**不攻击**、武器不消耗;
|
||||
选择一次性(`duels.initiator_item/target_item`,推进后清空)。
|
||||
接口 `POST /api/duels/<id>/item`;快照 `passiveItems/item/action`;世界脚本 `api['items']`。
|
||||
- **AI 每回合调用工具出招(v3.26)**:用户参与时,`advance()` 每次会单独调一次 AI 那方
|
||||
(`_ask_ai_duel_action`,带人设/气血/武器/被动,要求它调用 **`duel_attack`**);
|
||||
工具 → `duel_engine.ai_take_action()` 真正跑 `item_engine.use()`,每回合一次;
|
||||
没调用/失败时**退回归自动出招**(日志写明),不能卡死决斗。
|
||||
这些内部问话必须传 `skip_round_scripts=True`(`agent_loop.run_agent` 新参数),
|
||||
否则问一句就触发每轮状态脚本/主动物品,出现额外扣血/加血。
|
||||
- **决斗对话(v3.24)**:`DuelScreen` 有对话框,用户说话 → `duel_engine.say()` 真的调一次
|
||||
**对手 AI**(`_duel_ai_reply`,带人设/气血/最近回合/原话;`emit` 必须给,否则
|
||||
`run_agent` 直接 TypeError 会被兜底吞掉);双方的话写进 `log` 的 `kind:'talk'` 条目 +
|
||||
追加到会话消息;**不推进回合、不改变胜负**。没配模型时 `replied:false` + 兜底文案。
|
||||
- **总裁脚本要写明失败者惩罚 / 胜利者奖励**(v3.21):`on_duel` 收尾时
|
||||
`api['die']`(或扣声望/掉物品/逐出等)+ `api['give_item']`/`change_stat`,
|
||||
再 `end_duel(结果文本, 赢家)`。死亡判负是内核底线;脚本赢家与死亡判定一致时,
|
||||
最终结果文案用脚本写的(含惩罚/奖励),`outcome` 仍按死亡算赢/输。
|
||||
- **别在双方还有气血/有武器时强行判负**(v3.27):用户反馈「明明有武器却判负」——
|
||||
旧测试世界脚本"第 3 回合按气血高下判负"已删掉;现在 `on_duel` 只在
|
||||
**真的有人气血 <= 0** 时才 `die` + 写惩罚/奖励,否则什么都不结束(没有回合上限)。
|
||||
测试世界的 `world.py` 是完整示范(气血归零 → 败者死亡 + 胜者铁剑/声望)。
|
||||
## 语音 / 朗读情绪指令约定(v3.27 起)
|
||||
|
||||
- 豆包语音合成 2.0(`volcv3` 引擎,`seed-tts-2.0`)的**语音指令** =
|
||||
`req_params.additions.context_texts`(控制台体验页写作 `[#指令]`,不朗读、不计费)。
|
||||
官方文档:《[语音指令与标签](https://docs.volcengine.com/docs/DoubaoVoice/DoubaoTextToSpeech20CapabilityIntroduction)》、
|
||||
《[单向流式 TTS 接口](https://www.volcengine.com/docs/6561/2534913)》(`additions.context_texts`)。
|
||||
★★ **`additions` 必须是 JSON 字符串**(不是对象):真机报过
|
||||
`code=55000000 ... req_params.additions of type string`;用 `_volc_v3_req_params()`
|
||||
统一组包,探针会用本地假服务抓真实请求体钉死格式。请求头带 `X-Api-Request-Id`。
|
||||
- **括号规则只有一套逻辑,但三处实现必须一致**(最多 60 字、不跨行、成对括号):
|
||||
- 内核 `speech.py` 的 `_STAGE_RE` / `prepare_speech`:朗读时不念括号、`volcv3` 变成
|
||||
`context_texts` 指令(`_volc_v3_additions`);
|
||||
- Android `MarkdownText.findStageEnd` + 设置 `stageTags`:界面灰色小字;
|
||||
- Web `chat.js` 的 `STAGE_RE` / `.markdown .stage-dir`:界面灰色小字。
|
||||
改规则时三处一起改,否则会出现"界面灰了、语音还念"的错位。
|
||||
- `/api/tts` 和 `/api/tts/stream` 的响应都带 `speakText`(已剥 Markdown、去掉括号旁白);
|
||||
客户端退回系统 TTS 时**念 speakText**,别念原始 `msg.content`。
|
||||
- 设置项 `speech.emotionTags`(默认 **true**,老配置没这一项也按开):
|
||||
关掉 = 老行为(括号照念、界面正常字号)。
|
||||
- Skill 同步:`defaults.py` 的 `BUILTIN_SKILL` 有「语音·情绪指令」段(模型靠它学会写
|
||||
括号);跑 `probe-context` §9 和 `probe-agent-system` §16 验证。
|
||||
|
||||
- **用户角色死亡 = 这一局游戏结束(v3.27)**:用户反馈「用户角色死亡为啥还能说话,
|
||||
直接宣布这个容器游戏结束」。
|
||||
- `store.containers_with_names()` 给容器加**派生字段** `gameOver` / `gameOverText`
|
||||
(= `agentdb.is_dead('user', cid)`,不落库;复活后自动 false,不误伤单聊容器);
|
||||
- 内核 `_perform_chat` **两处**拦:发起前 + 世界脚本 `on_turn` 跑完后(不写用户消息、
|
||||
不花 token、不生成回复,`error.code = "game_over"`);`/api/session-message` 也拦;
|
||||
`context_preview` 的 `chat.blocked` 同步 `game_over`;
|
||||
- 界面:聊天页输入框换成「🏁 游戏结束」横幅 +「复活 ›」(`GameOverBar`),
|
||||
容器列表给这局打「已结束」标签;复活走 `AppViewModel.reviveUserIn(cid)`;
|
||||
- 探针:`probe-context` §8.5(_perform_chat 拦截/不调模型/不落库/查看器/复活恢复)、
|
||||
`probe-test-world` §10.5(`GET /api/containers` 的 gameOver 派生字段)。
|
||||
- **用户角色状态也按轮递减(v3.27)**:`_perform_chat` 生成后除了发言的 AI,还给
|
||||
`'user'` tick 一次(仅 `not auto_continue`,群聊自动续轮不算用户参与)——
|
||||
以前用户身上的「中毒(剩 3 轮)」永远停在 3(用户反馈「状态不会随轮数减少」)。
|
||||
|
||||
## 死亡 / 每轮脚本约定(v3.20 起)
|
||||
|
||||
- **不新造"每角色脚本"系统**:用户问「角色/用户角色每轮开始前都可以执行一个脚本」
|
||||
—— 现成机制就是**世界脚本 `on_turn`**(每轮开始前跑、能读数值),循环
|
||||
`api['agents']()` + `api['user']()` 即可覆盖每个角色;状态脚本 `on_turn`
|
||||
是"每个角色各跑"的另一条既有通道。用户明确说「有类似机制可以不用写免得造轮子」,
|
||||
别为这个再加一套 agent/container 脚本字段。
|
||||
- **死亡 = 情绪档位「死亡」**(`agentdb.emotion_set/is_dead`),和界面禁言、立绘、
|
||||
复活是同一套数据。世界脚本新增 `api['die'](谁, 遗言='')` / `revive` / `is_dead`
|
||||
三个动作(`world_engine._api`),AI 侧**没有**新工具(AI 仍不能自己复活)。
|
||||
- **数值支持 `initial`**(`rule_engine` / `agentdb.stat_defs.initial_value`):
|
||||
气血这种不能从 0 起步的数值写 `initial`;不写仍按 min(老世界行为不变)。
|
||||
测试世界「气血 0-100 initial 100」+ `on_turn` 判 `气血 <= 0 → die`。
|
||||
- **决斗中死亡 = 判负(底线)**:`duel_engine` 每回合结算后查双方 `agentdb.is_dead`:
|
||||
死的那一方立刻 `finished` + 判负(赢/输 outcome),双方同回合都死 → 平局;
|
||||
已死亡不能发起/接受决斗(400);快照每方 `dead` 布尔,界面显示。
|
||||
别把"判死"写进界面或模型(判定只在内核/世界脚本)。
|
||||
- **用户角色也会死**:档案 `GET /api/containers/<id>/user-profile` 带
|
||||
`emotion`/`dead`;复活走 `POST /api/containers/<id>/user-emotion {preset}`;
|
||||
界面「我的角色」页有死亡卡 + 「复活」按钮。AI 复活仍走「记忆 → 情绪」。
|
||||
- **情绪/立绘显示必须按当前容器(v3.22 假死修复)**:`/api/state` 的
|
||||
`containerEmotions` / `containerPortraits` 按 `containerId` 分;
|
||||
App 用 `AppViewModel.emotionOf()/portraitOf()`(内部按 activeConversation 的容器选),
|
||||
**不要读** `state.emotions`(那是智能体默认容器,会把 A 局的死亡带到 B 局)。
|
||||
保存情绪 `PUT /api/agents/<id>/emotion` 必须带 `containerId`
|
||||
(`MemoryScreen` 用 `memoryContainerId`),否则写到默认容器 = 假死/复活无效。
|
||||
|
||||
## 客户端 HTTP / 地图移动约定(v3.28 起)
|
||||
|
||||
- **Android `KernelClient.call()`:HTTP >= 400 必须抛 `KernelException`**
|
||||
(和 Web `web/js/api.js` 的 `request()` 保持一致)。
|
||||
内核的**失败响应用 4xx**(`{"ok":false,"error":"人话"}`);
|
||||
`HTTP 200 + ok:false` 只留给"软失败"(TTS 退回系统引擎、模型测试 fallback 等),
|
||||
由调用方自己看 `ok` —— **不要**用 200+ok:false 表示"操作失败"。
|
||||
真机踩过(用户原话「移动地点后全乱了:无法移动,无法移人」):
|
||||
旧 `call()` 不看状态码,地图「移人」被内核 400 拒绝后,错误 JSON 被解析成
|
||||
**一张空地图**(页面显示「这一局还没有地图」)还弹「移过去了」;
|
||||
「去这里」则吞掉异常继续切地点对话,位置却没动 —— 位置和对话对不上。
|
||||
验收:`probe-map` §7 钉住"移动失败必须回 400"。
|
||||
- **地图页的移动/切地点以 `mapContainerId` 为准**,不要用"当前会话的容器"——
|
||||
两者可以不是一局(容器列表里点「地图」看 A 局时,聊天还停在 B 局;
|
||||
以前"去这里"会把用户移到 B 局,A 局地图纹丝不动)。
|
||||
统一入口 `AppViewModel.switchPlace(placeId, containerId, alreadyMoved)`:
|
||||
移动失败(不相邻)→ 提示原因并**留在原地**,绝不能继续切对话;
|
||||
从容器列表切进对话要 `showContainers = false`、从「我的角色」页移动要
|
||||
`userItemsOpen = false`,否则对话在浮层下面、看着像没反应。
|
||||
- **移动失败要保持原地图数据**:别把失败响应当新地图覆盖 `mapData`
|
||||
(`MapData` 解析失败会得到空 places,界面直接变成"这一局还没有地图")。
|
||||
|
||||
|
||||
## 常驻角色 / 全定义 id 化约定(v3.30 起)
|
||||
|
||||
- **常驻角色和世界包耦合,不做单独的「角色包」**(用户原话「合在一个世界包里,不要搞别的包
|
||||
因为常驻角色和世界是耦合在一起的」)。类定义进 `worldInfo.json` 的
|
||||
`residentClasses[]`,预召唤实例进 `residents[]`,功能点写在这个类的脚本的
|
||||
`FUNCTIONS` 清单里;脚本文件存在世界包 `scripts/` 里。
|
||||
- **功能清单必须是字面量**(内核 AST 解析、不执行脚本)。一个功能 = 清单一条 + 同名函数
|
||||
`def <id>(api, caller, ...)`;参数类型只支持 `string/int/number/bool/enum/array`
|
||||
(同一份 schema 同时给 AI 工具、界面表单、文档用)。改这里必须同步:
|
||||
`resident_engine.parse_functions`、编辑器 `doubao_project` 校验、文档附录 J。
|
||||
- **三个调用通道共用 `resident_engine.call()`**:AI 工具
|
||||
`resident_<类id>_<功能id>`、界面 `POST /api/containers/<cid>/residents/<iid>/call`、
|
||||
脚本 `api['summon']` / `api['dismiss']`。**caller 由通道决定,AI 不能冒充用户**;
|
||||
AI 花自己的背包/数值,用户操作必须用户自己在界面点。
|
||||
- **AI 工具按"这一局"静态生成、地点/权限在调用时校验**(不是按地点过滤工具表)——
|
||||
工具表一局内不变才不会破坏模型上下文缓存。同类多实例自动加 `instance` 枚举参数。
|
||||
- **常驻角色工具是动态的**,不在固定工具表里(v3.32 起固定工具 20 个:18 + 地点两个);
|
||||
`audience`(ai/user/both)和
|
||||
`hidden` 决定可见性。AI **没有召唤**工具;只有类上标了 `dismissible: true` 才生成
|
||||
`resident_<类id>_dismiss`(默认没有,见下面「常驻角色会离开」)。
|
||||
- **输出统一信封**:`{ok, message, data, note}`,`message` 必须是"AI 能照说的人话结果";
|
||||
业务失败 `raise ValueError("原因")`,内核转 `ok:false`。**先校验、后副作用**——
|
||||
脚本中途报错不会回滚,钱/物品可能已经动了。
|
||||
- **界面入口是聊天输入框打 `>`**(或输入条右侧 `>`)→ 角色菜单 → 功能菜单 →
|
||||
全屏 HTML(内核生成、同源页面、调同一个 call 接口)。AI 用 `show_ui` 写的任意 HTML
|
||||
**拿不到**常驻角色的功能接口(只有 pick/close)——防止 AI 自己写页面绕过工具限制。
|
||||
- 用户界面操作结果进「待回传队列」(复用 `store.add_pending_ui`),AI 下一轮能看到;
|
||||
改这条链路时同步 `probe-residents` §6。
|
||||
- **新界面要登记 `docs/界面总览.md` 并跑 `audit-ui-tree`**:
|
||||
`[常驻角色菜单]` / `[常驻角色功能]` / `[常驻角色功能页]` 三节,
|
||||
`ResidentPageScreen` 已在 `SCREENS` 对照表里。
|
||||
|
||||
- **数值/状态/物品/地点/世界/常驻角色全部 id 化(v3.30)**:用户原话
|
||||
「数值物品状态世界全部id化(脚本可读名字也可读id)」。
|
||||
- `stats[].id` / `statuses[].id` 可选,**不写 = 用 name**(老包零改动);
|
||||
物品/地点本来就有 id;世界包有资源 id;常驻角色类/实例有 id;
|
||||
- 脚本/工具/AI 里的"谁、数值名、状态名、物品名、地点名"**先按 id 找、再按名字找**
|
||||
(`rule_engine.resolve_stat / resolve_status`、`item_engine.resolve_def`、
|
||||
`place_engine.resolve_place`、`resident_engine.find_instances`);
|
||||
- 存库的键用 **id**:`statDefs/statusDefs` 有 `def_id` 列,`stat_values` /
|
||||
`status_instances` 的 name 列存 id;老数据 id=name 不用迁移。
|
||||
定义里新加 id 时 `sync_defs` 会把同名老值搬过去,**之后改 id 不会再搬**;
|
||||
- 世界脚本 api 新增 `world_id` / `world_name`(`pack_id` 保留);物品脚本新增
|
||||
`item`(正在用的物品定义)、`place_of()`、`summon/dismiss/residents`、
|
||||
`world_id` / `world_name`;
|
||||
- 回归:`probe-residents` §11(id/名字双解析、HTTP 按 id 设值/挂状态)、
|
||||
`probe-rule-engine`、`probe-test-world`。
|
||||
- **旧都市世界包是常驻角色的验收样板**:`scripts/worlds/old-city/`(源)+
|
||||
`scripts/worlds/旧都市.zip` + App 内置 `assets/worlds/old-city.zip`;
|
||||
改完跑 `python scripts/build-old-city-world.py`(会同步 App 内置包)并跑
|
||||
`probe-residents.py` §10。**v3.32 起它也是世界 Skill + 角色槽位的展示样板**
|
||||
(`skills` 1 条 + `slots` 3 个:主角位=老街 / 商店店员位=商店 / 住户位=用户角色@家·客厅);
|
||||
改槽位后同样要重建 zip + 内置包。
|
||||
- **旧都市的地图相邻关系(用户要求)**:老街 `street` / 小卖铺 `kiosk` / 商店 `store` /
|
||||
学校·校门 `school` **四个地点两两相邻**(地图上这四点之间六条线全连;任意两个直接走),
|
||||
其余(家两间、学校↔教室/操场、森林路口↔森林深处)不变。
|
||||
改完要重新生成 zip + App 内置包;**已导入的旧包不会自动更新**,要在
|
||||
「世界包 → 示例包 → 旧都市」重新导入并新建一局才看得到。
|
||||
回归:`probe-residents` §10(城镇四地点两两相邻)+ `probe-map` §9(连线去重)。
|
||||
- **界面 `>` 菜单按用户当前地点过滤(v3.30 体验修复)**:只列同地点 + 不绑地点
|
||||
(`place=''` = 全图可找)的常驻角色,避免"在家看到商店/森林的常驻角色、点进去只会
|
||||
先过去才能办事"。`GET /api/containers/<cid>/residents` 返回 `placeId/placeName/
|
||||
elsewhere/hint`;空菜单时 UI 显示 `hint`("这里没有、别的地点还有 N 个,先移动过去")。
|
||||
AI 工具表**不按地点过滤**(按局静态、调用时校验),两条规则别搞混。
|
||||
回归:`probe-residents` §6(同地点只列售货员 / 回家菜单空+提示)、§10(旧都市)。
|
||||
- **常驻角色会离开(v3.30)**:脚本 `api['dismiss_me']()` 让自己走(外卖员送完、
|
||||
解谜后消失);类上 `dismissible: true` 才生成 AI 工具 `resident_<类id>_dismiss`
|
||||
(同一地点才能请走,默认关闭)。功能信封带 `dismissed: true` + `note` 告诉 AI
|
||||
"别再找它";走后菜单/工具里都不会再出现,要它回来按世界规则重新召唤。
|
||||
回归:`probe-residents` §6b(自己走 / AI 工具 / 隔空拒绝)+ §10 旧都市
|
||||
(外卖送完 `dismiss_me`、`resident_delivery_dismiss`)。
|
||||
- **独自一人的地点:不能聊天 ≠ 不能交互(v3.30)**:`place_engine.chat_guard` 只拦
|
||||
聊天;`>` 常驻角色接口不受影响。聊天页禁言条里必须有「找常驻角色 ›」入口,
|
||||
否则用户在有常驻角色、没 AI 角色的地点会以为整个界面废了。
|
||||
回归:`probe-residents` §10(森林深处 chat_guard=false 但守林人可调)。
|
||||
- **世界容器(一局)只认成员(v3.30)**:用户反馈「这容器都没选豆包,豆包咋会出现在
|
||||
这里」。三条必须同时守住:
|
||||
1. 内核 `/api/conversations` POST:世界容器里给非成员开对话 / 群拉非成员 → 400;
|
||||
2. `app.py` rebase(换智能体另起会话):**本局成员才继承容器**,非成员回它自己的
|
||||
默认容器,并用 `rebased.message` 告诉界面原因;
|
||||
3. 客户端:`useAgent` 切到非成员时立即开它的默认容器会话;地点对话的主人必须从
|
||||
容器成员里选(不能拿 activeAgent 硬塞)。
|
||||
回归:`probe-containers` §12(成员/非成员开对话、群拉人、加群成员、rebase 事件)。
|
||||
- **图形地图(v3.31)**:地图 = **内核生成的 HTML 页**(`GET /api/containers/<cid>/map/page`,
|
||||
安卓 `MapScreen` 全屏 WebView 打开),不是 Compose 画的列表。世界包定义:
|
||||
`places[].x/y`(0-100 百分比)+ `places[].region`;`info.map` 里 `background/width/
|
||||
height/marker/css/regions[]`。**连线自动由 `places[].exits` 生成**(双向去重),
|
||||
不要另写一份。交互:双指缩放/拖动、点区域框放大、点地点「去这里/移人」、
|
||||
**长按地点或区域弹信息**(`bindLongPress` + `showPlaceInfo`)。
|
||||
背景图随包 `assets/` 导入(`_save_map_background` 落盘成绝对路径)并在导出时
|
||||
打回 zip(`_pack_one_asset`)。回归:`probe-map` §9(坐标/区域/连线去重/HTML 关键
|
||||
元素/长按/缩放/CSS 注入/节点几何/面板高度)+ `probe-residents` §10(旧都市地图背景随包导入/导出)。
|
||||
- **地图页的两条几何铁律(v3.31 修复,别再回归)**:
|
||||
1. **连线端点 = 圆点圆心**:`.map-node` 盒子**只有圆点那么大**(圆心 = `places[].x/y`),
|
||||
名字用绝对定位挂在下面;`#edges` 必须是 `#stage` 的第一个子元素(线在圆点下层)。
|
||||
曾经把节点做成"圆点+文字整列居中"、把连线 append 到节点之后 —— 用户看到
|
||||
"连线端点掉到圆点底下 / 线盖在圆点上";
|
||||
2. **信息面板竖直居中、高度随内容**,高度**用 JS `innerHeight` 算像素**,别用 `vh`(见下条)。
|
||||
- **★★ 安卓 WebView 的 `vh` / 视口百分比高度可能是 0**(真机实测:Chrome/146 WebView
|
||||
里 `10vh` → **0px**,`max-height:74vh` 也是 0px —— 地图信息面板因此被压成一条
|
||||
44px 横条,用户反复反馈"面板太矮/太低"的根因)。内核生成的 HTML 页面里
|
||||
**不要用 `vh` / 百分比高度**控制高度;要限高就用 JS
|
||||
`Math.round(window.innerHeight * 比例) + 'px'` 设行内样式(地图页 `sheetMaxHeight()`、
|
||||
常驻角色功能页 `max-height:260px` 都是这么处理的)。`MapScreen` / `ResidentPageScreen`
|
||||
另外开了 `settings.useWideViewPort = true`(别再关 overview 缩放那一半:地图舞台
|
||||
不能整体缩放),但页面里的 JS 兜底必须保留。回归:`probe-map` §9(断言页面里有
|
||||
`sheet.style.maxHeight = sheetMaxHeight()`)、`probe-residents` §5(断言功能页没有 `40vh`)。
|
||||
- **改地图不要动移动/邻接规则**:`place_engine.move` 的 exits 校验、用户/AI 位置、
|
||||
地点对话频道都保持原样;地图页只是"看 + 点"的壳,移动仍走
|
||||
`POST /api/containers/<cid>/move`(页面里 fetch 同一接口,成功后 JS 桥
|
||||
`Doubao.moved` 让 App 切到该地点对话,`alreadyMoved=true` 不能再移一次)。
|
||||
|
||||
## 世界 Skill / 角色槽位 / 地点工具(v3.32 起)
|
||||
|
||||
- **世界包角色 Skill 分两层**(用户原话「世界包角色 skill 包括:总体世界 skill,
|
||||
槽位独立 skill」):
|
||||
- **总体世界 skill**:`worldInfo.json` 的 `info.skills[]`(`{id?,name,content}`)——
|
||||
**自动加载**:容器绑了这个世界包,这一局**每个 AI** 的 `<skills>` 段都会带上
|
||||
(`【世界·名字】`),**不用**用户手动绑定到智能体;
|
||||
- **槽位独立 skill**:`info.slots[].skills[]`——只有坐在那个槽位的人有
|
||||
(`【槽位·槽位名·skill名】`)。
|
||||
- 拼装只有一份:`agent_context.build_skills(agent, container)` → `slot_engine.skills_of`。
|
||||
- **角色槽位**(`info.slots[]`):`{id,name,place,user,prompt,skills[],items[]}`,
|
||||
一套"出生配置":出生地点 / 追加初始物品 / 独立 skill / 注入提示词。
|
||||
- 分配**落库**在容器的 `slotAssignments`(`{槽位id: "user"/智能体id}`),
|
||||
`slot_engine.ensure_assignments` 负责补/清:先给 `user:true` 的槽位分配用户角色,
|
||||
其余按世界包顺序分给成员;**已有分配不改**(身份/提示词不能悄悄变);
|
||||
**槽位满了以后加入的人按世界包默认配置**(默认出生点 / 只有全世界 `initial` 物品 /
|
||||
没有槽位 prompt 和 skill)——不是"加不进来"。
|
||||
- 生效点:出生点走 `slot_engine.ensure_position_for`(`place_engine.ensure_container_positions`
|
||||
内部也用它);槽位物品走 `ensure_slot_items`(新表 `slot_item_init` 幂等,和
|
||||
`item_init` 分开:一个人可能先后坐过不同槽位);提示词是新段 `<slot>`
|
||||
(用户槽位的 prompt 进 `<user>` 段)。
|
||||
- **★ 槽位物品发放顺序**:必须先 `item_engine.ensure_initial`(全世界 initial)
|
||||
再 grant 槽位追加物品。顺序反了 `_write(初始数量)` 会把槽位物品**覆盖掉**
|
||||
(用户角色 initial 本来就要等第一次读背包才发)——症状是"槽位物品消失"。
|
||||
- 显式改分配:容器 `PATCH` 带 `slotAssignments`(整表替换,内核校验槽位存在 /
|
||||
本局成员 / 最多一个 `"user"`);查当前分配:`GET /api/containers/<cid>/slots`。
|
||||
- 世界脚本读槽位:`api['slots']()`(全部槽位 + occupant)/ `api['slot_of'](谁)`
|
||||
(id / 名字 / 「用户」都能查,没坐槽位返回 None)。结构见 `slot_engine.script_slots`。
|
||||
- **AI 查地点 / 相邻关系**(用户要求「ai可以调用工具获取所有地点和相邻关系」):
|
||||
新工具 `list_places`(全部地点 + 各自 exits + 当前位置)和 `list_place_links`
|
||||
(双向去重的两两相邻 + `exits` 为空的自由移动地点)。和 `move_to` 同一条路:
|
||||
没绑世界包 / 没地点时**报错**,不返回空表。**加/改地点工具要同步
|
||||
`defaults.BUILTIN_SKILL` 的【地点】段**(否则模型不知道有这个工具)。
|
||||
- **编辑器 schema 是唯一真源**:`android/kernel/doubao_project.py` 的
|
||||
`info.skills` / `info.slots` 两段 + `normalize_world_skill` / `normalize_slot` +
|
||||
`validate_project` 的 4 类 warning。改字段要同时改内核 `slot_engine` 解析和
|
||||
`docs/world-script-api/world.md`。
|
||||
- 回归:`scripts/probe-slots.py`(自动分配 / 槽位出生点 / 物品叠加 / prompt/skill
|
||||
注入 / 世界脚本 api / 两个地点工具 / PATCH 校验 / 导出导入 / 槽位满加人)。
|
||||
839
豆鲍/README.md
Normal file
839
豆鲍/README.md
Normal file
@@ -0,0 +1,839 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(Web / Windows 版=豆包网页版风格)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
|
||||
**Web / Windows 端**(v2)换成了**豆包网页版风格**的桌面界面,并且和安卓 App
|
||||
**共用同一份 Python 内核**(exe 内嵌 Python 运行时)—— 功能天然同步。详见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||
> 「豆包」是字节跳动的商标。
|
||||
|
||||
> **📖 完整教程(当前版本,只讲怎么用)**:[`docs/小人间-完整教程.md`](docs/小人间-完整教程.md)
|
||||
> —— 安装/配模型、世界包与容器、数值/状态/物品/地图、决斗、语音情绪指令、
|
||||
> AI 的 18 个工具与权限边界、脚本写法、FAQ;
|
||||
> **附录 C–J 是数据字典 + HTTP API 全表(每个接口每个参数)+ AI 工具全参数 +
|
||||
> 脚本 API 全表 + 错误码 + 提示词结构 + 参数速查**。
|
||||
>
|
||||
> **🧩 世界包脚本 API 参考(按模块拆分)**:[`docs/world-script-api/index.md`](docs/world-script-api/index.md)
|
||||
> —— `world`(世界脚本)/ `stats`(数值裁决)/ `status`(状态)/ `item`(物品)/
|
||||
> `guard`(驻守)/ `resident`(**常驻角色**:类/实例、FUNCTIONS 功能清单、AI 工具与界面 `>` 入口)/
|
||||
> `defs`(worldInfo.json 字段)/ `types`(数据结构)/
|
||||
> `sandbox`(沙箱与异常)/ `examples`(完整示例),Qt 文档风格逐方法写清签名·参数·返回。
|
||||
>
|
||||
> **🏙️ 示例世界包**:`scripts/worlds/旧都市.zip`(旧都市:家/学校/商店/小卖铺/森林 +
|
||||
> 4 个常驻角色 + 全部常驻角色功能;App「世界包 → 示例包」里也能一键导入)。
|
||||
>
|
||||
> **📦 宣传/开店资料包**:`python scripts/build-docs-pack.py` →
|
||||
> `dist-docs/小人间-资料包-v3.31.zip`(约 6.6 MB)—— 总体说明(全功能)+ 完整教程 +
|
||||
> 世界脚本 API + 示例世界包 + 精选截图;把 zip 丢给另一个对话就能让它写**产品介绍网页**和
|
||||
> **商店/商品页**。全功能总览见 [`docs/总体说明-所有功能.md`](docs/总体说明-所有功能.md)。
|
||||
|
||||
| 平台 | 产物 | 界面 | 内核 |
|
||||
|---|---|---|---|
|
||||
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | **豆包网页版风格 Web UI**(`web/`) | **exe 内嵌 Python + `android/kernel/`(与 App 同一份)** |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | **豆包网页版风格 Web UI**(`web/`) | **`android/kernel/`(本机 Python)** |
|
||||
|
||||
> 旧的 **Lynx 版**(`app/` + Node 内核 `server/`)没有删,作为历史留档,菜单命令见 §9。
|
||||
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||
|
||||
| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
**网页版 / Windows 桌面版(v2,豆包网页版风格):**
|
||||
|
||||
| 空对话(桌面网页) | 群聊(成员条 + 交接) | Windows exe |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 智能体 | 设置(10 家提供商 / 22 项超时) | 会议模式(运行日志) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
**AI 界面能力(电脑端也能用了:AI 自己写 HTML 弹界面 / 弹选择框 / 结束对话):**
|
||||
|
||||
| AI 写的界面(show_ui,iframe 渲染) | AI 提问(ask_user,等用户选) | 结束对话(end_conversation) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| exe 里同样可用(真窗口实拍) | | |
|
||||
|---|---|---|
|
||||
|  | | |
|
||||
|
||||
> 前两组是安卓原生 Compose 版(手机);这两组是电脑上的**网页版**(浏览器 / exe 同一个界面)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 快速开始
|
||||
|
||||
### 浏览器 / 桌面版(v2:豆包网页版风格,和 App 同一份 Python 内核)
|
||||
|
||||
需要本机有 **Python 3.10+**(内核是纯标准库;Android 端是内嵌 CPython)。
|
||||
|
||||
```bash
|
||||
npm start # 起 Python 内核并托管 web/,打开 http://127.0.0.1:5199/
|
||||
PORT=5300 npm start # 换端口
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**自带 Python,不用装**;**exe 必须放纯英文路径**,见 §7.1)。
|
||||
重新打包:`npm run exe`。
|
||||
|
||||
> 旧的 Lynx 版还留着:`npm run install:all` + `npm run start:legacy-lynx`。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
```bash
|
||||
npm run apk # 产出 dist-android/doubao-debug.apk(约 88 MB)
|
||||
adb install -r dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
装完打开 App → 抽屉 →「设置」→ 选提供商、填 API Key → 保存。
|
||||
第一次启动会解压内置 Termux(约 95 MB、3226 个文件),**约 10~30 秒**,界面上有进度。
|
||||
|
||||
---
|
||||
|
||||
## 2. 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Android App(原生 Kotlin + Compose,主力) │
|
||||
│ │
|
||||
│ ui/ ChatScreen Drawer Settings Skills Agents Profile │
|
||||
│ ModelPickerSheet TerminalScreen ← 7 个页面 │
|
||||
│ │ │
|
||||
│ │ KernelClient(OkHttp + 轮询流式) │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ Python 内核(Chaquopy 内嵌 CPython 3.13) │ │
|
||||
│ │ android/kernel/ —— 监听 127.0.0.1:5199 │ │
|
||||
│ │ · providers 10 家兼容厂商 + 思考强度映射 │ │
|
||||
│ │ · agent_loop 多轮工具循环 │ │
|
||||
│ │ · tools import 加载 tools/*.py │ │
|
||||
│ │ · mcp_client 手写 JSON-RPC(http/stdio/inproc)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ 进程内直调(Chaquopy 桥) │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 内置 Termux($PREFIX = /data/user/0/<pkg>/files/usr) │
|
||||
│ │ · bash 5.x / apt / pkg / 388 个命令 │ │
|
||||
│ │ · libtermux.so → forkpty(真 tty) │ │
|
||||
│ │ · TerminalView → ANSI 渲染(Termux 源码 vendored)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 设备能力 NativeBridge:定位 / 陀螺仪 / 加速度计 │ │
|
||||
│ │ 磁性 / 光线 / 气压 / 电量 / 剪贴板 / 选文件 │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**v2 起,电脑上的 Web/exe 版不再用 Node 内核 + Lynx**,而是:
|
||||
- 界面换成 `web/` 里**豆包网页版风格**的纯静态前端(无构建步骤,内核直接托管);
|
||||
- 后端直接跑**和安卓 App 同一份** `android/kernel/`(纯标准库 Python),
|
||||
桌面版由 Electron 起一个 Python 子进程、并带一个"原生能力桥"(选文件/剪贴板);
|
||||
- 所以「引擎改了另一端必须跟上」这条欠账**没了**:一份内核,两个客户端。
|
||||
旧的 Node 内核(`server/`)和 Lynx 界面(`app/`)留作历史存档。
|
||||
|
||||
细节见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能
|
||||
|
||||
### 3.1 智能体
|
||||
抽屉 →「智能体」。每个智能体有独立头像(9 种)和系统提示词,聊天时覆盖全局提示词,顶部显示当前智能体。
|
||||
内置 4 个(豆包 / 代码搭子 / 文案师 / 数据分析),可自建。存 `<数据目录>/agents.json`。
|
||||
|
||||
### 3.2 模型、提供商与思考强度(抽屉里的「模型」那一栏)
|
||||
|
||||
**支持 10 家,而且它们全都是同一个协议**(`POST {baseUrl}/chat/completions`),
|
||||
所以内核里只有一份实现,差别只在三件事:地址、模型名、**思考强度用哪个字段传**。
|
||||
|
||||
| key | 提供商 | Base URL | 思考强度怎么传 |
|
||||
|---|---|---|---|
|
||||
| `ark` | 火山方舟(豆包) | `https://ark.cn-beijing.volces.com/api/v3` | 顶层 `thinking: {type}` |
|
||||
| `openai` | OpenAI 官方 | `https://api.openai.com/v1` | `reasoning_effort` |
|
||||
| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | 不发(模型自己决定) |
|
||||
| `kimi` | Kimi(月之暗面) | `https://api.moonshot.cn/v1` | 不发 |
|
||||
| `zhipu` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | 顶层 `thinking: {type}` |
|
||||
| `dashscope` | 通义千问(阿里云) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | 不发 |
|
||||
| `siliconflow` | 硅基流动 | `https://api.siliconflow.cn/v1` | 不发 |
|
||||
| `openrouter` | OpenRouter(聚合) | `https://openrouter.ai/api/v1` | `reasoning_effort` |
|
||||
| `ollama` | 本地 Ollama | `http://127.0.0.1:11434/v1` | 不发 |
|
||||
| `custom` | 自定义兼容网关 | 自己填 | 不发 |
|
||||
|
||||
**为什么不是"非 ark 即 openai"**:这个判断以前写死成两家名字。
|
||||
现在厂商多了,各自认的字段不一样,而**给不认 `reasoning_effort` 的服务发这个字段,有些会直接 400**。
|
||||
所以改成每个预设自己声明 `thinkingMode`(`ark` / `effort` / `none`),**认不出来的一律 `none`**(什么都不发,最安全)。
|
||||
|
||||
| 强度 | `thinkingMode: ark` | `thinkingMode: effort` | `thinkingMode: none` |
|
||||
|---|---|---|---|
|
||||
| 快速 | `thinking={type:"disabled"}` | 推理模型 `reasoning_effort=minimal` | 不发 |
|
||||
| 自动 | 不传,交给模型 | 不传 | 不传 |
|
||||
| 低 / 中 / 高 | `thinking={type:"enabled"}` | `reasoning_effort=low/medium/high` | 不传 |
|
||||
|
||||
另外:`thinkingMode: effort` 且模型名匹配 `o1|o3|o4|gpt-5|gpt-6` 时,
|
||||
会自动剥掉 `temperature`/`top_p` 等采样参数,并把 `max_tokens` 换成 `max_completion_tokens`
|
||||
(这些模型"传默认值"也算传,会 400)。
|
||||
|
||||
两份内核(Node / Python)在这件事上**逐字段对拍 50/50 一致**(10 家 × 5 档),
|
||||
脚本:`node scripts/parity-thinking.mjs`。
|
||||
|
||||
### 3.3 思考过程怎么显示
|
||||
1. **正文里**:回答上方一个 `✨ 深度思考 ›` 入口,思考中显示跳动小点
|
||||
(这里不再拼思考强度 —— 强度本身就叫"深度思考",拼出来会变成"深度思考 · 深度思考")
|
||||
2. **点开**:底部升起「**思考过程**」弹层(左上角 X),先列这轮调了哪些工具,再是完整思维链
|
||||
3. 思维链**已落库**,刷新/切会话都不丢
|
||||
|
||||
### 3.4 界面:照着豆包抠的,带完整动效
|
||||
|
||||
安卓端是原生 Compose 重写的,视觉对着豆包真机截图一项项抠:
|
||||
|
||||
- **纯白底**(不是浅灰)——豆包的层级靠"白底 + 浅灰卡片"表达,用灰底会一股系统设置味
|
||||
- 顶部三段式:左边 ☰ / ✎,中间「头像 + 智能体名 + ›」(点开就是模型面板),右边 📞 / 🔊
|
||||
- 空会话时:168dp 蓝色圆环大头像 + 灰色问候气泡 + 白底描边快捷胶囊(对话 / AI创作 / 出行用豆包 / 豆包)
|
||||
- 用户气泡:`#2B7BFF` 蓝底、右下角收窄成 4dp(气泡"尾巴")
|
||||
- 助手气泡:`#F2F3F5` 灰底、左下角收窄;下面一排 5 个圆形小按钮(复制/朗读/赞/踩/分享)+ 右侧重新生成
|
||||
- 输入框:52dp 高的大圆角描边胶囊,左边相机、右边麦克风;**有内容时右侧才变成蓝色圆形发送键**
|
||||
- 出错的回复是浅红底 + 红字,不是普通气泡
|
||||
- 设置 / 我的 / 技能 / 智能体各页共用同一套小部件(`ScreenHeader` / `SettingsCard` / `FormField` …),
|
||||
所以在主题层改一次颜色,7 个页面一起变
|
||||
|
||||
动效(都是 Compose 原生动画,没引第三方库):
|
||||
|
||||
| 位置 | 动效 |
|
||||
|---|---|
|
||||
| 抽屉 | 从左滑入 + 遮罩淡入,关闭反向 |
|
||||
| 页面切换 | 淡入 + 轻微横向位移(`AnimatedContent`) |
|
||||
| 消息气泡 | 出现时淡入 + 上移 10dp(`AppearOnce`) |
|
||||
| 思考 / 模型面板 | 从底部升起,收起时降下去 |
|
||||
| "正在输入" | 三个小点依次跳动(`TypingDots`,错开 130ms) |
|
||||
| 按钮 | 按下缩到 0.86~0.94 回弹(`collectIsPressedAsState` + spring) |
|
||||
| 抽屉列表项 | 按下时背景色渐变 |
|
||||
|
||||
> 顺带一个坑:底部面板的**滚动区会吃掉点击**。如果面板顶到状态栏,
|
||||
> "点遮罩关闭"就只剩状态栏那条能点,等于失效。所以面板限高 85%、并且都带明确的 X 按钮。
|
||||
|
||||
### 3.5 设置不会被保存清空(三道防线)
|
||||
|
||||
之前有个真 bug:**一保存设置,整份配置被清空**。根因是首屏 `state` 还在路上时,
|
||||
设置页草稿还是"全空"的,而保存按钮把草稿**全量**下发;`/api/settings` 是浅合并,
|
||||
空字符串就等于把它清掉。现在三道防线:
|
||||
|
||||
1. **界面只发改动过的字段**(`SettingsDraft.changesAgainst`)——没动过的键根本不出现
|
||||
2. **草稿只在服务端设置真的变了时重建**(存一份 `snapshot` 对比),
|
||||
不会再被无关的 state 刷新冲掉正在输入的内容
|
||||
3. **内核拒收空的关键字段**(`provider` / `baseUrl` / `model` / `apiKey` / `nickname` / `thinkingLevel`)——
|
||||
前端再出 bug 也清不掉配置。`systemPrompt` / `toolsDir` 故意不在此列:它们"留空"是合理需求
|
||||
|
||||
验证脚本(都会先正常保存一次验证不掉字段,再按"旧版 bug 的形状"下发一堆空值验证被忽略):
|
||||
|
||||
- `node scripts/probe-settings-wipe.mjs http://127.0.0.1:5199`(电脑 / Node 内核)
|
||||
- `node scripts/device-settings-attack.mjs emulator-5556 5199`(设备 / Python 内核)
|
||||
|
||||
### 3.6 工具
|
||||
|
||||
| 工具 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `shell` | 终端执行命令,带超时与黑名单 | ✅ 优先走内置 Termux |
|
||||
| `python_run` | 执行 Python 代码 / .py 文件,`action=libs` 列可用库 | ✅ 进程内 exec(CPython 3.13.9) |
|
||||
| `device` | **手机能力**:设备信息、定位、传感器、剪贴板 | ✅ 安卓专属 |
|
||||
| `calc` `now` `get_weather` `notes` `web_fetch` | `tools/*.py`,自己写的 | ✅ 同一份代码 |
|
||||
| `mcp__*` | MCP 服务暴露的工具 | ✅ 见 3.8 |
|
||||
|
||||
**`device` 工具**(安卓)实测能力:
|
||||
- `info`:型号/厂商/系统/SDK/ABI/存储/屏幕/电量
|
||||
- `location`:GPS 经纬度(真机实测 `纬度, 经度 ±35m`)
|
||||
- `sensors` / `sensor`:列出并采样(真机 46 个传感器,加速度计 z≈9.7 m/s² 就是重力)
|
||||
- `clipboard_get` / `clipboard_set`
|
||||
- `termux_available` / `termux_run`:走内置 Termux
|
||||
|
||||
### 3.7 自己写工具
|
||||
往工具目录丢一个 `.py`(`_` 开头跳过):
|
||||
|
||||
```python
|
||||
TOOL = {
|
||||
"name": "word_count",
|
||||
"description": "统计一段文字的字数",
|
||||
"parameters": {"type": "object", "properties": {"text": {"type": "string"}},
|
||||
"required": ["text"]},
|
||||
}
|
||||
def run(args): # 同步或 async 都行
|
||||
return {"count": len(args["text"])}
|
||||
```
|
||||
|
||||
工具目录:安卓在 `files/tools/`(可通过设置里的 `toolsDir` 改),电脑在 `tools/`。
|
||||
内置工具在首次启动时会**播种**到可写目录,改坏了删掉重启就恢复。
|
||||
|
||||
> 为什么安卓上要播种、还要把源码 base64 打进 APK:Chaquopy 打的是 `.pyc`,
|
||||
> 运行时 `loader.get_source()` 拿不到源码,所以构建脚本额外生成了 `bundled_tool_sources.py`。
|
||||
|
||||
### 3.8 MCP:三种传输,安卓也能跑
|
||||
抽屉 →「技能·连接器」→「MCP 服务」,图形化和原始 JSON 两个 Tab,保存时校验并自动重连。
|
||||
|
||||
| 传输 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `http` | 标准 Streamable HTTP / SSE | ✅ |
|
||||
| `stdio` | 起一个子进程用管道通信 | ✅ 用内置 Termux 的 python/node |
|
||||
| `inproc` | 同进程内直接调用(自己写的 Python 服务) | ✅ 安卓推荐,最省事 |
|
||||
|
||||
实测:filesystem 服务 14 个工具、memory 9 个工具、自己写的 Python 服务 3 个工具,全部连接并调用成功。
|
||||
|
||||
> 为什么手写 JSON-RPC 而不用官方 `mcp` SDK:它依赖 pydantic v2,Chaquopy 装不进来。
|
||||
|
||||
### 3.9 文件上传 / 权限模式
|
||||
- **上传**:输入框左侧相机/加号 → 选文件 → 上传到内核 → 挂到输入框 → 随消息发送 → 气泡里显示
|
||||
- **权限模式**:`open` 全放行 / `restricted` 只放 `allow` 白名单。限制模式下未授权工具
|
||||
**列都不列出来**,执行时再拦一道
|
||||
|
||||
### 3.10 语音:朗读 + 语音输入
|
||||
|
||||
**引擎放在内核里,音频采集/播放在端上。** 这么分的好处:API Key 只存一份,
|
||||
浏览器 / 安卓 / exe 三端白捡同一个能力,厂商鉴权差异全在一个文件里。
|
||||
|
||||
| | 引擎 | 说明 |
|
||||
|---|---|---|
|
||||
| **朗读** | `system` | 设备自带 TTS(安卓 `TextToSpeech`)。**不联网、不要 Key**,默认就是它 |
|
||||
| | `volc` | **火山语音合成 —— 豆包同款音色** |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/speech`(`tts-1` + alloy/nova/…) |
|
||||
| **语音输入** | `system` | 设备自带识别(安卓 `SpeechRecognizer`) |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/transcriptions`(`whisper-1` 等) |
|
||||
|
||||
**火山那个接口有两个坑**(对着[官方文档](https://docs.volcengine.com/docs/DoubaoVoice/HTTPone-timecompositenon-streaminginterface-V1notrecommended?lang=zh)
|
||||
和两个第三方实现核对过,并且用 mock 抓了实际发出的请求):
|
||||
|
||||
1. 鉴权头是 `Authorization: Bearer;{token}` —— **分号,不是空格**。写成空格会判鉴权失败。
|
||||
实测抓到的请求:`Authorization="Bearer;tok-abc"`
|
||||
2. 成功判定看 body 里的 `code === 3000`,**HTTP 200 也可能带错误码**;
|
||||
返回的 `data` 是**纯 base64**(不是 data URL),解出来就是音频字节
|
||||
|
||||
接口:
|
||||
|
||||
```
|
||||
POST /api/tts {"text": "..."}
|
||||
→ {"ok":true, "engine":"system"} 用设备自带,界面自己念
|
||||
→ {"ok":true, "engine":"volc", "mime":"audio/mpeg", "audio":"<base64>"}
|
||||
→ {"ok":false, "error":"..."} 失败原因给人话
|
||||
|
||||
POST /api/stt <body 就是音频原始字节,不套 JSON/base64>
|
||||
头: X-Audio-Filename / X-Audio-Type
|
||||
→ {"ok":true, "engine":"openai", "text":"..."}
|
||||
|
||||
GET /api/speech → 当前配置 + 可选音色
|
||||
```
|
||||
|
||||
> 两个接口**失败也返回 HTTP 200 + `ok:false`**:缺 Key、厂商报错都是预期内的失败,
|
||||
> 界面要的是把原因显示出来,而不是让 fetch 抛网络异常(那样错误信息就丢了)。
|
||||
|
||||
安卓端(`speech/AudioIo.kt` + `speech/SpeechController.kt`):
|
||||
|
||||
- **录音**用 `AudioRecord` 直接拿 PCM,套 44 字节 WAV 头(16kHz 单声道 16bit ——
|
||||
Whisper 最常见的输入格式,30 秒才 1 MB)。不用 `MediaRecorder` 是因为它只吐 m4a/aac,还得再解码
|
||||
- **播放**云端音频走 `MediaPlayer`(`setDataSource` 只认路径/FD,所以 base64 落盘成临时文件再播)
|
||||
- **系统 TTS** 会**按句切分**再排队 —— `speak()` 单次上限约 4000 字符,整段塞进去会被截断
|
||||
- 念之前**剥掉 markdown**(`**加粗**`、代码块、链接),否则会念出一堆星号
|
||||
- **云端失败自动退回系统 TTS**:用户点了朗读却一点动静都没有是最差的体验
|
||||
- 录音时**先停朗读**,否则会把自己的声音录进去(自我循环)
|
||||
- 录音权限**第一次点麦克风才申请**,不在启动时要
|
||||
- 录音时输入框整条换成「正在听…」+ 实时音量画的小波形
|
||||
|
||||
验证:`node scripts/verify-speech.mjs py|node` —— **21 项断言,两份内核都跑**
|
||||
(语音在 Node 和 Python 里是分别实现的,只验一份不算数)。
|
||||
mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权头。
|
||||
|
||||
### 3.11 通话模式(设计好了,还没做)
|
||||
|
||||
顶部那个 📞 现在是提示。真要做的话按这个来(**不要一上来就上全双工**):
|
||||
|
||||
| 阶段 | 做法 | 为什么 |
|
||||
|---|---|---|
|
||||
| A(推荐先做) | **半双工**:按一次开始录 → 静音自动断句 → STT → 内核 → TTS 播 → 循环 | 复用现有的 STT/TTS,1 天能出可用版本 |
|
||||
| B | 全双工实时(OpenAI Realtime / 火山实时对话,WebSocket) | 延迟 300ms 级、能自然打断,但强依赖网络,改造量 3~5 天 |
|
||||
|
||||
阶段 A 要处理的四件事(都会真实咬人):
|
||||
|
||||
1. **自我循环**:TTS 在播时开麦会把 AI 自己的声音录进去 → 播之前必须先停麦,
|
||||
或者做回声消除(`AudioSource.VOICE_COMMUNICATION` + AEC)
|
||||
2. **音频焦点**:`TextToSpeech` 和 `AudioRecord` 不能同时持有 → 用 `AudioManager` 协调
|
||||
3. **VAD 断句**:靠静音时长判断"说完了"。阈值调不好要么打断用户、要么一直不响应;
|
||||
建议"连续 800ms 低于阈值算说完",并且**开口就打断 TTS**(barge-in)——这是"像通话"的关键手感
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
### 3.13 超时(全部可调)
|
||||
|
||||
设置页最下面那张卡片 →「超时」,**18 项全都能调**:
|
||||
|
||||

|
||||
|
||||
每一项都带一句说明(写在界面上,不用翻文档),`-` / `+` 按钮加输入框,
|
||||
右上角「恢复默认」。
|
||||
|
||||
| 分组 | 有哪些 |
|
||||
|---|---|
|
||||
| 对话 | 等模型回复、连接空闲上限、心跳间隔、本地接口请求 |
|
||||
| 工具 | 工具执行、shell 命令、跑 Python 代码、Termux 命令、会议节点、自定义节点 |
|
||||
| 界面 | AI 提问等多久、AI 界面等多久、选文件等多久 |
|
||||
| 语音 | 语音合成、语音识别 |
|
||||
| MCP | 单次请求、连接、调用工具 |
|
||||
|
||||
以前这 15 个超时**散在 10 个文件里当模块级常量**,谁也不知道一共有几个 ——
|
||||
"哪些能调、哪些不能调"这个问题根本回答不了。现在收在
|
||||
[`android/kernel/timeouts.py`](android/kernel/timeouts.py) 一份里:
|
||||
|
||||
- 界面上有哪几项、叫什么、默认多少、能填多大、说明写什么 —— **全是内核给的**
|
||||
(`GET /api/timeouts`),加一项只改那个文件,界面自动多出一行
|
||||
- 改完**立刻生效**,不用重启(各处都是现读)
|
||||
- 取值一律夹在每项的 `[min, max]` 里,填 "60秒"、空串、负数、999999 都不会出问题
|
||||
- 「改回默认」= 从配置里**删掉**这一项(不是存一个相同的值),
|
||||
这样以后调默认值时没动过的用户会跟着新默认走
|
||||
- Node 端(Web / exe)有一份对称的 [`server/src/timeouts.mjs`](server/src/timeouts.mjs),
|
||||
`python scripts/verify-timeouts.py` 会把两边**逐项对拍**
|
||||
|
||||
三个"等用户"的项(AI 提问 / AI 界面 / 工具执行)默认是 **0 = 不限时** ——
|
||||
它们的时长取决于你什么时候点,给上限等于"你想久了 AI 就自己编"。
|
||||
|
||||
> 想让 AI 别等太久?把「AI 提问等多久」填个有限值就行。但**不建议**:
|
||||
> 你去忙一会儿回来,AI 已经按自己猜的答案往下跑了,而它并不知道自己在猜。
|
||||
|
||||
---
|
||||
|
||||
### 3.14 智能体系统(记忆 / 情绪 / Token / 世界观 / 技能 / 多模型)
|
||||
|
||||
按《智能体系统需求文档 v1.1》实现。**详细文档在
|
||||
[`docs/智能体系统.md`](docs/智能体系统.md)**(需求项 → 文件对照、数据分界、踩过的坑、
|
||||
接口一览),这里只说结论。
|
||||
|
||||
> **角色扮演系统的整体介绍**(世界包 → 容器 → 智能体 → 用户角色 怎么拼起来、
|
||||
> 一轮对话怎么跑、AI 能做哪些事):[`docs/角色扮演系统-详细介绍.md`](docs/角色扮演系统-详细介绍.md)。
|
||||
|
||||

|
||||
|
||||
**选择界面**:左列表 + 右侧四层叠加(背景图 / 主体边框 / 角色图 / 介绍边框),
|
||||
切换按 0.3s 出 → 0.5s 间隔 → 0.4s 换框 → 0.3s 入的四阶段走(连点立即打断、
|
||||
从眼前画面接着走)。圆形「更多」按钮进用量页。缺哪张图就走内置默认,
|
||||
**最差也是「默认人物 + 默认背景 + 方框边框」**,不会有空白展示区。
|
||||
|
||||

|
||||
|
||||
**六个能力**(都能在界面上单独关掉或不管它):
|
||||
|
||||
| | 一句话 |
|
||||
|---|---|
|
||||
| Token | 按智能体独立统计、**按模型分桶**、输入输出分开;能设上限,用满时发起前拦住并附一句告别 |
|
||||
| 记忆 | 无上限、AI 自己记,**用户能改能删**(兜底);「必须保留」的 AI 改不动 |
|
||||
| 情绪 | 每个智能体一个当前情绪,写进提示词;**绑同一世界观也不共享**(需求明确要求) |
|
||||
| 世界观 | 独立资源。绑了它的智能体**共用一份记忆**,但**只能改自己写的**那几条 |
|
||||
| 技能 | 纯文本手册,按绑定顺序注入;内置那份默认就生效 |
|
||||
| 多模型 | 全局模型列表 + UUID 引用。引用了就**整组覆盖**(地址/Key/模型一起换) |
|
||||
|
||||
**两处需要解释的设计**:
|
||||
|
||||
1. **数据分界**:记忆/情绪/Token/Skill 绑定进 SQLite(条目无上限、每轮全量读、
|
||||
要检索、要按行改删),其余仍是 JSON(量级小、要人肉可读)。
|
||||
判据写在 `android/kernel/agentdb.py` 文件头,加新数据时先按那张表判一次。
|
||||
|
||||
2. **幻觉调用检测**:模型很容易在"该记东西"的时候只在正文里说一句"我记住了"
|
||||
—— 用户当场看不出来,下次发现它完全不记得,信任就没了。所以由程序比对
|
||||
「说了什么」和「做了什么」,对不上就在那条回复下面挂一条警示。
|
||||
判宽比判窄更糟(误伤几次之后用户就不看那个警示了),所以只收明确句式。
|
||||
|
||||
**验证**(都不需要装机、不需要网络):
|
||||
|
||||
```bash
|
||||
python scripts/probe-agent-system.py # 12 节 70+ 项:UUID、记忆、限权、注入顺序、
|
||||
# 20 多个接口、包的边界、多模型解析
|
||||
python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calling 的降级
|
||||
```
|
||||
|
||||
> ⚠️ **改完内核记得跑一次 `py_compile`**:Gradle 不编译 Python
|
||||
> (Chaquopy 只是把 `.py` 打进 APK),语法错误要等手机上启动内核才炸,
|
||||
> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸,
|
||||
> 但它拦的是"打包",不是"你刚改的那一行"。
|
||||
|
||||
**全部界面和入口在哪**:[`docs/界面总览.md`](docs/界面总览.md) ——
|
||||
把 App 里所有界面画成树(含"每个界面从哪进"),而且
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**Python 脚本在哪跑、各有什么权限**:[`docs/Python脚本.md`](docs/Python脚本.md) ——
|
||||
这个 App 里**六类地方**会跑 Python(AI 的 `python_run` / `shell`、规则脚本、
|
||||
会议 Python 节点、自定义节点、内置 Termux),它们的权限和沙箱**完全不同**。
|
||||
一句话结论:
|
||||
|
||||
> **只有「规则脚本」有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
|
||||
> 其余几处本质就是"在你手机上跑代码",靠超时兜底,不是权限隔离。
|
||||
|
||||
**Web / exe 端(v2)**:不再维护第二套实现。界面在 `web/`(豆包网页版风格),
|
||||
后端就是上面这份 `android/kernel/`(桌面 exe 内嵌 Python 运行时)。
|
||||
功能对照、架构、验收方式和已知差距全部写在 [`docs/网页版.md`](docs/网页版.md);
|
||||
接口契约在 `docs/kernel-api-chat.md` / `kernel-api-agents.md` / `kernel-api-misc.md`。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 4. 安卓端:内置 Termux 是怎么塞进去的
|
||||
|
||||
### 4.1 一条硬限制决定了整个方案
|
||||
|
||||
**Android 10(API 29)起有 W^X 限制:`targetSdk ≥ 29` 的应用不允许执行自己数据目录里的二进制。**
|
||||
而 Termux 把 bash/python/node 全解压在自己的私有目录再 exec —— 它能这么干,**唯一原因是它 `targetSdk = 28`**
|
||||
(实测核对:`dumpsys package com.termux` → `targetSdk=28`)。
|
||||
|
||||
所以这个 APK 也锁 **`targetSdk = 28`**。代价是上不了应用商店(个人工具无所谓);
|
||||
换来的是完整 Linux 用户态:`bash`、`apt`、`pkg`、以及 `pkg install python nodejs-lts`。
|
||||
|
||||
### 4.2 APK 里到底装了什么
|
||||
|
||||
```
|
||||
APK 88.4 MB
|
||||
├─ lib/arm64-v8a/libtermux-bootstrap.so 28.0 MB ← Termux 根文件系统(其实是 zip)
|
||||
├─ lib/x86_64/libtermux-bootstrap.so 28.1 MB ← 同上,模拟器用
|
||||
├─ lib/<abi>/libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号)
|
||||
├─ lib/<abi>/libpython3.13.so ← Chaquopy 的 CPython
|
||||
├─ assets/chaquopy/** ← 内核 + 9 个 Python 工具
|
||||
└─ java/com/termux/{terminal,view}/** ← Termux 的终端模拟器源码(vendored)
|
||||
```
|
||||
|
||||
Termux 的终端库**没有发布到任何 Maven 仓库**(Maven Central 没有,JitPack 也不通),
|
||||
所以是 vendored 源码 + 改了两处 `import com.termux.view.R` 指向我们自己的 R 类。
|
||||
Apache-2.0 声明见 `android/app/src/main/assets/TERMUX_LICENSE.txt`。
|
||||
|
||||
### 4.3 安装流程(移植自 Termux 的 `TermuxInstaller.java`)
|
||||
|
||||
1. 从 APK 里取出 `libtermux-bootstrap.so`
|
||||
2. **切掉 ELF 头**得到纯 zip(见 4.4 ①)
|
||||
3. 解压到 `files/usr`(3226 个文件),给 `bin/ lib/ libexec/` 下的文件补可执行位
|
||||
4. 读 `SYMLINKS.txt`(1146 行,格式 `目标←链接路径`),**用 `/system/bin/sh` 批量 `ln -sf`**
|
||||
—— Java 的 File API 建不了符号链接
|
||||
5. **改写脚本 shebang**(见 4.4 ④)
|
||||
6. 写一份自己的 `etc/doubao.bashrc`
|
||||
|
||||
进度会写进 `files/termux-install.log`(见 §7.6,为什么不用 Logcat)。
|
||||
|
||||
### 4.4 踩过的四个坑(都和你想象的不一样)
|
||||
|
||||
**① `libtermux-bootstrap.so` 不是纯 zip,是「ELF 头 + zip」**
|
||||
文件前 1328 字节是 ELF 头(Android 要求 `lib/` 下的东西得像 ELF,Termux 就把 zip 接在后面)。
|
||||
- `ZipInputStream` 按本地文件头顺序扫,**实测一个条目都读不出来**;
|
||||
- `ZipFile` 走中央目录,但它**不会**像桌面 JVM 那样自动跳过前缀 ——
|
||||
真机 Android 16 上直接报 `Entry at offset zero has invalid LFH signature 464c457f`
|
||||
(`464c457f` 就是 `\x7FELF` 的小端十六进制)。模拟器上碰巧宽松能过,真机不行。
|
||||
|
||||
所以现在的做法:**自己扫第一个 `PK\x03\x04`、把前缀切掉**,再交给 `ZipFile`。
|
||||
|
||||
**② `bin/su` 写不进去(ENOENT)**
|
||||
父目录存在、权限也对,就是 `open` 失败。安卓对这个文件名有额外限制。
|
||||
处理方式:**单个文件失败就跳过并记日志**,不让一个怪文件毁掉整次安装(其余 3226 个照常)。
|
||||
|
||||
**③ 必须设 `LD_PRELOAD` + `TERMUX__PREFIX`(双下划线)**
|
||||
Termux 的二进制里写死了 `/data/data/com.termux/files/usr`。`libtermux-exec.so` 负责把这些路径
|
||||
重写到真实 prefix,但它认的环境变量是:
|
||||
`TERMUX__PREFIX`(**不是** `TERMUX_PREFIX`)、`TERMUX_APP__DATA_DIR`。
|
||||
少一个,bash 就会去读**别的包**的 `/etc/profile`,报 `Permission denied`。
|
||||
|
||||
**④ 脚本的 shebang 也得改**
|
||||
`bin/getprop`、`bin/pkg` 这些是 shell 脚本,第一行写死 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
内核解析 shebang 时不会经过 termux-exec,照样 EACCES("bad interpreter")。
|
||||
安装时统一把 `bin/ libexec/` 下 79 个脚本的 shebang 前缀改成我们的 prefix 就好了。
|
||||
|
||||
### 4.5 终端界面(真终端 + 控制台退路)
|
||||
|
||||
用 Termux 自己的 `TerminalView` + `libtermux.so` 的 `forkpty` —— 真 pty、真 ANSI,
|
||||
所以 `vim`/`top` 这类全屏程序都能跑。Compose 里用 `AndroidView` 包一层,底下加了手机必备的功能键排:
|
||||
`ESC / TAB / CTRL+C / CTRL+D / ↑↓←→ / HOME / END / | / / / - / ENTER`(没这排连 vim 都退不出来)。
|
||||
|
||||
**但 pty 不是每台机器都给用**。实测 realme(Android 16)上:
|
||||
|
||||
```
|
||||
/dev/pts → Permission denied
|
||||
mount → devpts on /dev/pts type devpts (mode=600,ptmxmode=000)
|
||||
python openpty → OSError: out of pty devices
|
||||
```
|
||||
|
||||
`/dev/pts` 被挂成 `mode=600` 且 `ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||
于是 TerminalSession 一起来就退出(界面上只留一句 `[Process completed]`)。
|
||||
这不是 SELinux 拒绝(logcat 里没有任何 avc),是挂载参数定的,应用侧绕不过去。
|
||||
|
||||
所以做成两条路,**自动切换**:
|
||||
|
||||
| 情况 | 走哪条 |
|
||||
|---|---|
|
||||
| pty 可用(多数设备 / 模拟器) | Termux 的 TerminalView,真终端 |
|
||||
| 会话建起来 2 秒内就退出(判定 pty 不可用) | 自动切「控制台模式」:命令框 + 输出区,跑的是**同一条 Termux bash**,只是没有 tty |
|
||||
|
||||
代价只是没有全屏 TUI 和交互式提示符,跑命令、装包(`pkg install python`)都正常。
|
||||
|
||||
### 4.6 和内核怎么接
|
||||
|
||||
内核里的 `shell` 工具优先走内置 Termux(返回里带 `via: "termux"`),
|
||||
`device` 工具的 `termux_run` / `termux_available` 也走同一条路。
|
||||
因为 Termux 现在就在本进程里,不需要跨进程 intent、也不需要用户去开 `allow-external-apps`。
|
||||
|
||||
### 4.7 安卓端其余细节(Chaquopy / 界面)
|
||||
|
||||
- **Chaquopy 17.0.0** 内嵌 CPython 3.13.9:没有 `python` 可执行文件(所以 `python_run` 是**进程内 exec**,
|
||||
不能起子进程);运行时 pip 只能装纯 Python 轮子;`mcp` 官方 SDK 用不了(要 pydantic v2)
|
||||
- **刻意不装任何第三方包**:Chaquopy 每次构建都要连云 pip,网络一抖整个 APK 就构建不出来
|
||||
(实测 `Could not find a version that satisfies the requirement requests`)。
|
||||
内核只用标准库(`urllib`/`http.server`/`json`),所以留零依赖换来"离线也能构建"。
|
||||
要 requests/numpy 就走内置 Termux:`pkg install python && pip install requests`
|
||||
- **界面**:状态栏不遮挡顶栏(`windowInsetsPadding(WindowInsets.safeDrawing)`)、
|
||||
输入框跟随输入法(`imePadding`)、深色模式自动适配
|
||||
- **流式**:Lynx 那边用 SSE;安卓原生 Compose 走的是**轮询通道**
|
||||
(`transport: "poll"` + `GET /api/chat/poll?runId=&cursor=`),
|
||||
两条件事件类型完全一致,客户端 200ms 取一次增量
|
||||
|
||||
---
|
||||
|
||||
## 5. 我实际验证了什么
|
||||
|
||||
### 5.1 安卓端(原生 Compose + 内置 Termux)
|
||||
|
||||
真机(RMX5090 / Android 16 / arm64-v8a):`node scripts/verify-phone.mjs <serial>` → **17/18**。
|
||||
模拟器(Android 14 / x86_64):17/18(唯一失败的是"定位",模拟器没有 GPS)。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 构建 | ✅ `assembleDebug` 成功,APK 88.4 MB |
|
||||
| 内核启动 | ✅ `GET /api/health` → `{"ok":true,…}` |
|
||||
| 智能体 / 工具 | ✅ 4 个智能体;8 个内置工具 + MCP 工具 |
|
||||
| 内置 Termux | ✅ 首次解压 3226 个文件 / 388 个命令 / 1146 个符号链接 |
|
||||
| shell | ✅ 真机 `Linux localhost 6.6.118-android15 … aarch64 Android`,`via: termux`,stderr 干净 |
|
||||
| pkg / apt | ✅ 可执行(79 个脚本的 shebang 已修正) |
|
||||
| python_run | ✅ CPython 3.13.9 aarch64(进程内) |
|
||||
| 联网 | ✅ urllib 与 requests 都 200 |
|
||||
| device 信息 | ✅ 型号 / 厂商 / 系统 / SDK / 存储 / 电量 |
|
||||
| 传感器 | ✅ 真机 46 个;加速度计 z≈9.7 m/s²、陀螺仪有数据 |
|
||||
| 定位 | ✅ 真机 `纬度, 经度 ±35m` |
|
||||
| MCP(Python 写的服务) | ✅ 连接 + 列工具 + 调用成功 |
|
||||
| 设置保存 | ✅ 保存前后逐字段一致(含 API Key / 系统提示词),空值攻击被忽略 |
|
||||
| 思考强度映射 | ✅ 两份内核对拍 50/50 一致 |
|
||||
| 界面 | ✅ 对话 / 抽屉 / 终端 / 设置 / 模型面板 截图见文首 |
|
||||
|
||||
### 5.2 其他平台
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 浏览器渲染 | ✅ 无头 Edge + CDP,5 个页面全部渲染,控制台无异常 |
|
||||
| 端到端工具调用 | ✅ mock 模型 → 请求 `calc` → Python 返回 → 第二轮流式回答 → 落库 |
|
||||
| Python 工具 | ✅ `calc` `now` `get_weather`(实时数据) `notes` `web_fetch` 全部通过 |
|
||||
| MCP | ✅ filesystem 14 工具、memory 9 工具连接成功;6 类校验错误全部拦截 |
|
||||
| Windows exe | ✅ 冷启动、界面渲染、内置内核、MCP 自动连接 |
|
||||
|
||||
### 5.3 没有 API Key 也能把链路跑通
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假的 OpenAI 兼容服务,监听 5299
|
||||
node scripts/verify-phone.mjs emulator-5556 # 或对真机跑
|
||||
```
|
||||
|
||||
mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式回答"来演,
|
||||
所以能验证完整的 界面 → 内核 → 工具调用 → 流式返回 链路,**不消耗任何额度**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 给 Lynx 界面(Web / exe)的注意事项
|
||||
|
||||
安卓端已经不用 Lynx 了,这一节只对 Web/exe 有效:
|
||||
|
||||
- **Fresco 必须先初始化**,否则图片不显示;**Fresco 不能解码 SVG**,图标要预先栅格化成 PNG
|
||||
- Lynx 的 `fetch` 没有 `response.body`,所以流式走轮询通道
|
||||
- 状态栏/布局用 `safe-area` 相关变量,别写死 px
|
||||
- 动画(`breathe` 那种)在某些模拟器上会破坏图片绘制,已改成不影响绘制的写法
|
||||
|
||||
---
|
||||
|
||||
## 7. 打包踩坑记录
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 389 MB)
|
||||
- **v2 架构**:exe 里带一份 **python.org 的嵌入式 Python**(`runtime/python`,约 25 MB 解压后)+
|
||||
**同安卓 App 的 Python 内核**(`runtime/kernel`)+ 网页前端(`runtime/web`)。
|
||||
构建脚本会自动下载 `python-3.13.9-embed-amd64.zip` 缓存到 `desktop/build-cache/`(已 gitignore)
|
||||
- **启动时不要再设 `ELECTRON_RUN_AS_NODE=1`**(本机环境可能全局设了它):那样 Electron 会当 Node 跑,
|
||||
报 `Cannot read properties of undefined (reading 'commandLine')`。开发调试前先清掉这个环境变量
|
||||
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||
- 数据目录默认 `%APPDATA%\Doubao\data`;自动化测试可用 `DOUBAO_USER_DATA` / `DOUBAO_DATA` 覆盖
|
||||
|
||||
### 7.2 Android APK
|
||||
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||
否则 `nativeLibraryDir` 是空的,`.so` 全在 APK 里,取 bootstrap 时得从 `applicationInfo.sourceDir` 读
|
||||
- **`targetSdk = 28`**(见 4.1),`abiFilters = ["arm64-v8a", "x86_64"]`
|
||||
- 构建脚本会把 `tools/*.py` 拷进 `app/src/main/python/` 并生成 `bundled_tool_sources.py`
|
||||
- 构建暂存目录用 ASCII 路径(`C:\DoubaoAndroid`),中文路径会让 Gradle/Chaquopy 出问题
|
||||
- **别并发跑两次 Gradle**:会互相踩坏 Chaquopy 的 venv(`Scripts/python.exe does not exist`)
|
||||
|
||||
### 7.3 Chaquopy / 内嵌 Python
|
||||
- `.pyc`-only 打包导致 `loader.get_source()` 失败 → 工具源码用 base64 内嵌
|
||||
- 每次构建都会连云 pip → 已改为零第三方依赖(见 4.7)
|
||||
|
||||
### 7.4 Android 15+ 的 edge-to-edge
|
||||
强制 edge-to-edge 后,状态栏会压住顶栏、输入法会盖住输入框。
|
||||
Compose 里统一在根布局吃 `WindowInsets.safeDrawing`,滚动页再叠 `imePadding()`。
|
||||
|
||||
### 7.5 工具链(Windows)
|
||||
- **Node 20+ 不能直接 `spawn` `.bat`/`.cmd`**(`status=null`),必须 `shell: true`
|
||||
- **PowerShell 会把命令行里的 JSON 引号搅坏**:所有内联 node/python 脚本都写成文件再跑
|
||||
- **PowerShell 的 `Get-Content` / `Set-Content` 会按 GBK 读写 UTF-8 文件**,
|
||||
一读一写就把中文文档转成乱码(本文档就被这么毁过一次)。
|
||||
改文本一律用编辑器工具,别用这两个 cmdlet 做"读进来再写回去"
|
||||
- **Kotlin 的块注释会嵌套**:在 KDoc 里写 `lib/*.so` 里的 `/*` 会开一个嵌套注释,
|
||||
把后面的代码全吞掉,报错却指向文件末尾之外的行
|
||||
|
||||
### 7.6 安卓 `org.json` 不会把 `Map` 转成 JSON 对象(踩过一次大的)
|
||||
|
||||
`json.put("speech", mapOf("autoRead" to true))` **不会**产生 `{"speech":{"autoRead":true}}`,
|
||||
而是把 Map 原样存进去,序列化出来是 `{"speech":"{autoRead=true}"}` —— **值是字符串**。
|
||||
|
||||
这一个坑连锁出四件事:
|
||||
|
||||
1. 内核把字符串写进了 `settings.json`(`speech` 本来是对象,被字符串顶掉了)
|
||||
2. 之后**每一次**读配置(`{**默认, **字符串}`)都抛 `TypeError`
|
||||
3. `/api/state` 从此永远返回 `{"error":"'str' object is not a mapping"}`
|
||||
4. App 把这个错误 JSON 解析成了「全默认状态」,而且**不抛异常**,所以还弹了"已保存"
|
||||
|
||||
用户看到的就是:**点一下语音按钮,模型变「未设置」、昵称变回「我」、会话列表全空**。
|
||||
|
||||
修了三处(缺一不可):
|
||||
- **安卓**:`patchToJson()` 显式递归把 Map/List 转成 `JSONObject`/`JSONArray`(见 `AppViewModel.kt`)
|
||||
- **内核写**:`tools`/`security`/`speech` 这几个子对象,补丁里不是字典就**直接忽略**,
|
||||
宁可这次改动不生效,也不写出读不回来的配置
|
||||
- **内核读**:发现子对象不是字典就**回落默认值**(自愈)——
|
||||
一个坏字段不该让 `/api/state` 永久 500,更不该把用户其它数据一起拖没
|
||||
|
||||
> 为什么之前没暴露:只有**嵌套对象**才触发,而在此之前 App 从没发过嵌套补丁
|
||||
> (`tools` 那两个开关从来没在设置页点过)。教训是——
|
||||
> **跨语言边界传结构化数据时,别信任何一侧的隐式转换**,两端都要有"形状不对就拒绝"的防线。
|
||||
|
||||
### 7.7 部分 ROM 会吞掉应用日志
|
||||
realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一条都看不到**。
|
||||
所以安装进度、终端会话退出原因等关键信息都**落盘**到 `files/termux-install.log`,
|
||||
用 `adb shell run-as com.doubao.lynxclone cat files/termux-install.log` 读。
|
||||
|
||||
---
|
||||
|
||||
## 8. 已知限制
|
||||
|
||||
- **`targetSdk = 28` 上不了应用商店**(个人侧载没问题)。要上架就得回到"外装 Termux + 桥接"那条路
|
||||
- **pty 在部分 ROM 上不可用**(4.5),自动降级成控制台模式,没有全屏 TUI
|
||||
- **内嵌 CPython 没有 `python` 可执行文件**,`python_run` 是进程内 exec,不能起子进程
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
- **网页版(Web/exe)**:`show_ui` / `ask_user` / `end_conversation` 已经能用(走内核的
|
||||
`/api/device/*` HTTP 队列,`wait` 语义和安卓一致);会议画布、立绘背景是二期。
|
||||
详见 `docs/网页版.md` §5.1 / §6
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发(v2:网页版 + Python 内核)
|
||||
npm start # 起内核 + 托管 web/ → http://127.0.0.1:5199/
|
||||
npm run exe # 打包 Windows exe(内嵌 Python)
|
||||
npm run apk # 构建 Android APK(--clean 可彻底重建)
|
||||
node scripts/verify-web-ui.mjs # 网页版验收:逐页截图 + 收集 JS 报错
|
||||
node scripts/verify-ui-bridge.mjs # AI 界面能力:show_ui / ask_user / end_conversation
|
||||
node scripts/scrape-doubao-web.mjs # 扒豆包网页版做视觉参考(reference/,不入库)
|
||||
|
||||
# 旧的 Lynx 版(历史留档)
|
||||
npm run install:all # 装 app(Lynx 客户端)+ server(Node 内核)依赖
|
||||
npm run start:legacy-lynx
|
||||
|
||||
# 验证
|
||||
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍(历史)
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍(历史)
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
python scripts/verify-ui-tools.py # interface 工具的参数与提示词
|
||||
python scripts/verify-extract-urls.py # 「打开网页」的链接抽取
|
||||
python scripts/verify-ai-webview.py # AI 界面里的 JS 桥
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
node scripts/mock-llm.mjs # 监听 5299
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 参考
|
||||
|
||||
- 火山方舟:<https://www.volcengine.com/docs/82379/1298454>
|
||||
- OpenAI Chat Completions:<https://platform.openai.com/docs/api-reference/chat>
|
||||
- Termux(Apache-2.0):<https://github.com/termux/termux-app>
|
||||
- Chaquopy:<https://chaquo.com/chaquopy/doc/current/>
|
||||
- 调研笔记(`docs/`):
|
||||
- `ai-chat-backend-api-research.md`(Ark/OpenAI/MCP 接口细节与证据强度)
|
||||
- `lynx-ui-research.md`(豆包界面还原的调研)
|
||||
|
||||
---
|
||||
|
||||
## 11. 许可
|
||||
|
||||
本项目采用 **MIT License**,见 [LICENSE](LICENSE)。
|
||||
|
||||
它**包含或依赖**第三方作品,各自的授权独立于 MIT,使用时请一并遵守:
|
||||
|
||||
| 组件 | 授权 | 用在哪 |
|
||||
|---|---|---|
|
||||
| [Termux](https://github.com/termux/termux-app) | **Apache-2.0** | 终端模拟器源码(vendored)+ pty 的 JNI 库 |
|
||||
| [Chaquopy](https://chaquo.com/chaquopy/) | MIT | APK 内嵌 CPython |
|
||||
| [Jetpack Compose / AndroidX](https://developer.android.com/jetpack) | Apache-2.0 | 安卓界面 |
|
||||
| [LynxJS](https://github.com/lynx-family/lynx) | Apache-2.0 | Web / 桌面版界面 |
|
||||
| [Electron](https://github.com/electron/electron) | MIT | Windows 桌面版打包 |
|
||||
|
||||
Termux 的完整许可在 `android/app/src/main/assets/TERMUX_LICENSE.txt` 与 `APACHE-2.0.txt`。
|
||||
|
||||
> **商标声明**:「豆包」是字节跳动的商标。本项目是出于学习目的的界面复刻,
|
||||
> 与字节跳动无任何关联,不含任何来自豆包 App 的代码或素材。
|
||||
> 界面配色与布局照着公开截图量出,图标使用 Material Icons。
|
||||
|
||||
> **注意**:本仓库**不包含** Termux 的 bootstrap(`libtermux-bootstrap.so`,两个 ABI 共 56 MB),
|
||||
> 因此直接 clone 下来构建 APK 会缺这个文件。补法见 §4.2 与 §4.3。
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
plugins {
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 203
|
||||
versionName = "2.0.3"
|
||||
versionCode = 352
|
||||
versionName = "2.0.152"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -39,32 +39,58 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lint 不挡 release 构建。
|
||||
*
|
||||
* ★ 唯一让它报错的是 `targetSdk = 28` 那条:
|
||||
*
|
||||
* Error: Google Play requires that apps target API level 33 or higher.
|
||||
* [ExpiredTargetSdkVersion]
|
||||
*
|
||||
* 而 **28 是必须的**,不能改 —— Android 10 起 targetSdk>=29 的应用
|
||||
* 不允许执行自己数据目录里的二进制(W^X 限制),而 bash / python /
|
||||
* dpkg 全在 /data/data/<包名>/files/usr 里。Termux 自己也是锁 28
|
||||
* 才活下来的。这条 lint 检查针对的是"上架 Google Play",而我们
|
||||
* 这个 App 本来就上不了架(自签证书 + 这个 targetSdk)。
|
||||
*
|
||||
* ★ 设 `abortOnError = false` 而不是 `checkReleaseBuilds = false`:
|
||||
* lint **照常跑**、报告照常生成,只是不因为这一条把构建打断。
|
||||
* 别的真问题仍然看得到。
|
||||
*/
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名。
|
||||
*
|
||||
* ★ 为什么要自己配一个 keystore,而不是用 debug 默认的:
|
||||
* ★ 用的是**原来那个 debug 证书**(fingerprint 83:28:15:D6…),
|
||||
* 只是把它**拷进了仓库**,并且**显式开了 v1/v2/v3**。
|
||||
*
|
||||
* 1. **debug 证书换机器就变**。用 debug 包发出去,换台电脑构建出来的
|
||||
* 签名指纹不一样,用户装的时候必须**先卸载**(Android 不允许
|
||||
* 同包名不同签名覆盖安装)。发出去的包就成了"只能装一次"的。
|
||||
* 为什么这么做(踩过两次,记下来):
|
||||
*
|
||||
* 2. **默认只签 v2/v3,缺 v1(JAR)签名**。Android 7+ 自己装没问题,
|
||||
* 但很多安装器(比如从远程传过去的)和严格的 ROM 会按 v1 检查,
|
||||
* 报"解析失败:安装包没有签名文件" —— 这个真踩到了。
|
||||
* 下面显式把 v1/v2/v3 全开。
|
||||
* 1. **不能随便换证书**。Android 不允许同包名不同签名覆盖安装 ——
|
||||
* 换了之后用户必须**先卸载**(数据全丢)。
|
||||
* 我第一次"修签名问题"时顺手换了一把新证书,结果老用户装不上,
|
||||
* 报"已安装了签名冲突的应用"。**修 A 问题不能引入 B 问题。**
|
||||
*
|
||||
* ★ 密码就写在这里,**它不是秘密**:keystore 也提交进仓库了。
|
||||
* 这是个**自签**证书,目的是"指纹稳定、能覆盖安装",不是"证明是谁发的"。
|
||||
* 谁拿到这个仓库谁就能签出一样的包 —— 对这个本地工具来说够了。
|
||||
* (真要防伪得保护 keystore + 用 CI 的密钥管理,那是另一件事。)
|
||||
* 2. **缺 v1(JAR)签名会让很多安装器拒绝**。Android 7+ 自己装没问题,
|
||||
* 但从远程传过去再装(MT 管理器 / UU远程 之类)会报
|
||||
* "解析失败:安装包没有签名文件"。所以 v1/v2/v3 全开。
|
||||
*
|
||||
* 3. **debug 证书默认在 ~/.android/ 里,换台机器就变**。
|
||||
* 拷进仓库(连密码一起)之后,**哪台机器构建出来的指纹都一样**,
|
||||
* 能互相覆盖安装。
|
||||
*
|
||||
* ★ 密码是 debug 证书的标准密码,**它不是秘密**。
|
||||
* 自签证书只保证"指纹稳定、能覆盖安装",不证明"是谁发的"。
|
||||
*/
|
||||
signingConfigs {
|
||||
create("doubao") {
|
||||
storeFile = file("../doubao-release.jks")
|
||||
storePassword = "doubao-clone"
|
||||
keyAlias = "doubao"
|
||||
keyPassword = "doubao-clone"
|
||||
// ★ 三个方案全开:v1 给老安装器,v2/v3 给新系统
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
enableV1Signing = true
|
||||
enableV2Signing = true
|
||||
enableV3Signing = true
|
||||
@@ -81,8 +107,7 @@ android {
|
||||
)
|
||||
}
|
||||
debug {
|
||||
// debug 包也用它 —— 这样"我本地调试的包"和"发出去的包"
|
||||
// 签名一致,能互相覆盖安装,不用来回卸载
|
||||
// debug 包也用同一把 —— 本地调试的包和发出去的包能互相覆盖安装
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
}
|
||||
}
|
||||
@@ -156,6 +181,10 @@ chaquopy {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// 会议节点定义库:节点类型 / 引脚 / 算子 / 几何 / 形状的唯一一份定义
|
||||
// (以前散在 MeetingsScreen.kt 里,同一样东西写 6 遍 —— 见 docs/节点库.md)
|
||||
implementation(project(":nodekit"))
|
||||
|
||||
// 原生 UI 用 Compose
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
@@ -17,7 +17,17 @@
|
||||
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||
<!-- ★★ 发通知(用户要求"还可以发送通知")。
|
||||
Android 13(API 33) 起这是**运行时权限**,新装的 App **默认是拒绝的** ——
|
||||
不申请的话 `NotificationManager.notify()` 不报错但通知**不显示**。
|
||||
实测踩到:渠道建出来了(importance=3),但 App 级 `importance=NONE`,
|
||||
通知栏里什么都没有,而调用方还以为成功了。
|
||||
声明了不算完,还得在运行时 requestPermissions —— 见 MainActivity。 -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- 通知带声音/震动需要它(Android 13+ 才有这个权限名) -->
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
|
||||
<!-- Android 11+ 包可见性:不声明的话查不到别的 App,也就「打开手机 app」不了 -->
|
||||
<queries>
|
||||
<package android:name="com.termux" />
|
||||
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||
@@ -28,6 +38,13 @@
|
||||
<intent>
|
||||
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||
</intent>
|
||||
<!-- ★「打开手机 app」需要的:列出所有能启动的 App。
|
||||
Android 11 起不声明这条 queries,queryIntentActivities 只会返回空列表,
|
||||
表现是"已安装的 App 一个都找不到"。 -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
|
||||
@@ -40,7 +57,7 @@
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="false"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@style/AppTheme">
|
||||
@@ -55,5 +72,19 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- ★★ 读手机通知(用户要求的工具)。
|
||||
Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户
|
||||
手动去「设置 → 通知 → 通知使用权」勾上本 App,系统才会把通知流过来。
|
||||
不声明这个 Service,权限开了也收不到任何东西。 -->
|
||||
<service
|
||||
android:name=".DoubaoNotificationListener"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
BIN
豆鲍/android/app/src/main/assets/worlds/all-test.zip
Normal file
BIN
豆鲍/android/app/src/main/assets/worlds/all-test.zip
Normal file
Binary file not shown.
BIN
豆鲍/android/app/src/main/assets/worlds/old-city.zip
Normal file
BIN
豆鲍/android/app/src/main/assets/worlds/old-city.zip
Normal file
Binary file not shown.
@@ -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<String>,
|
||||
val shots: List<Shot>,
|
||||
)
|
||||
|
||||
private fun p(id: String, label: String, kw: List<String>, vararg shots: Shot) =
|
||||
Preset(id, label, kw, shots.toList())
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// 预设表
|
||||
//
|
||||
// ★ 加新预设只要往这个列表里塞一条 —— 工具说明、列表接口都是从这里生成的,
|
||||
// 不存在"两边不一致"的问题(这个仓库里抄两份的坑踩过好几次)。
|
||||
// ------------------------------------------------------------------ //
|
||||
|
||||
private val PRESETS: List<Preset> = 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<Map<String, Any>> = 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<String> = 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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
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
|
||||
instance = this
|
||||
// ★ 连上的瞬间就把当前挂着的通知同步进来 —— 不然用户装完 App 立刻问
|
||||
// "我最近收到什么通知了",答案是空的(那些通知在他装 App 之前就收到了)
|
||||
syncActive()
|
||||
Log.i(TAG, "通知使用权已连接,当前挂着 ${items.size} 条")
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
super.onListenerDisconnected()
|
||||
connected = false
|
||||
if (instance === this) instance = null
|
||||
Log.i(TAG, "通知使用权已断开")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
if (instance === this) instance = null
|
||||
}
|
||||
|
||||
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) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一条通知。
|
||||
*
|
||||
* ★ 可见性要 **internal**(不能 private):`companion object` 里的
|
||||
* `syncActive()` 要调它,而 Kotlin 的 private 成员**只对同一个类体可见**,
|
||||
* 伴生对象不算 —— 写成 private 会报"cannot access"。
|
||||
*/
|
||||
internal 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,
|
||||
)
|
||||
// ★ 标题和正文都空的就**不进列表**。
|
||||
//
|
||||
// 这类通知真实存在:媒体控制、正在进行的下载、某些 App 的纯图标通知 ——
|
||||
// 它们的文字要么在 RemoteViews 里(`extras` 取不到),要么压根没有。
|
||||
// 留着的话用户/模型会看到一条"什么都没有"的条目,纯噪音。
|
||||
// (实测:`cmd notification post` 发的测试通知就有一条是这样的。)
|
||||
if (item.title.isBlank() && item.text.isBlank()) return
|
||||
|
||||
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>()
|
||||
|
||||
/**
|
||||
* 当前活着的 service 实例。
|
||||
*
|
||||
* ★ 必须有它:`getActiveNotifications()` 是 **service 自己**的方法,
|
||||
* 不是静态的。没有实例就调不到,也就拿不到"系统里现在挂着哪些通知"。
|
||||
*/
|
||||
@Volatile
|
||||
private var instance: DoubaoNotificationListener? = null
|
||||
|
||||
/** 通知使用权连上了没有 */
|
||||
@Volatile
|
||||
var connected: Boolean = false
|
||||
|
||||
/**
|
||||
* ★★★ 把系统里**当前还挂着的**通知同步进来。
|
||||
*
|
||||
* ## 为什么必须有这个(用户报"还是没有读到"的根因)
|
||||
*
|
||||
* 第一版只在 `onNotificationPosted` 里记 —— 也就是说**只有本进程活着的
|
||||
* 那段时间收到的通知才算数**。而进程一重启(用户升级 App、或者系统杀后台)
|
||||
* 内存就清空了,那之前收到的通知**全都看不到**。
|
||||
*
|
||||
* 用户的期望是"读我手机上现在的通知" —— 那本来就该包含
|
||||
* **在他打开 App 之前就收到的那些**。
|
||||
*
|
||||
* `NotificationListenerService.getActiveNotifications()` 正好干这个:
|
||||
* 系统把当前通知栏上挂着的全给它。所以每次读之前先同步一遍。
|
||||
*
|
||||
* ★ 拿不到实例(service 没起来)时不报错,就用手上已有的 ——
|
||||
* 至少比什么都不给强。
|
||||
*/
|
||||
fun syncActive() {
|
||||
val svc = instance ?: return
|
||||
try {
|
||||
for (sbn in svc.activeNotifications ?: emptyArray()) {
|
||||
if (sbn.packageName == svc.packageName) continue
|
||||
svc.record(sbn, removed = false)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "同步当前通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取最近的通知。
|
||||
*
|
||||
* @param limit 最多几条
|
||||
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
|
||||
* @param query 关键词过滤(标题/正文/App 名里含它)
|
||||
*/
|
||||
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
|
||||
// ★ 先跟系统对一次账,把"我们没见过的、但此刻挂着的"补进来
|
||||
syncActive()
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
|
||||
/**
|
||||
* 内核监听的端口。
|
||||
*
|
||||
* ## 为什么要有这个单例
|
||||
*
|
||||
* 端口原来是 `MainActivity` 里一个局部变量(`client.baseUrl` 也在那儿设)。
|
||||
* 但 `NativeBridge` 也需要打内核的接口 —— `end_conversation` 要
|
||||
* `PATCH /api/conversations/<id>` 把"这次对话已结束"落盘,而
|
||||
* `NativeBridge` 在**内核的工作线程**上被调,拿不到 Activity 的局部变量,
|
||||
* 也不该去依赖 UI 层的 `KernelClient`。
|
||||
*
|
||||
* 所以放一个进程级的单例:`MainActivity` 启动内核后写一次,别处只读。
|
||||
*/
|
||||
object KernelHost {
|
||||
|
||||
/** 内核端口;0 表示还没起来 */
|
||||
@Volatile
|
||||
var port: Int = 0
|
||||
|
||||
/** 内核起来之后由 MainActivity 调 */
|
||||
fun set(p: Int) {
|
||||
port = p
|
||||
}
|
||||
|
||||
fun baseUrl(): String = if (port > 0) "http://127.0.0.1:$port" else ""
|
||||
}
|
||||
|
||||
/** 全项目统一的 JSON 请求体类型(别在各处手写字符串,写错一个字符就是 415) */
|
||||
val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType()
|
||||
@@ -35,10 +35,32 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private val client = KernelClient()
|
||||
|
||||
companion object {
|
||||
/** 发通知权限的请求码(只要不和别的撞就行) */
|
||||
private const val REQ_NOTIF = 0x4D32
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// ★★ 申请「发通知」权限(用户要求"还可以发送通知")。
|
||||
//
|
||||
// Android 13(API 33) 起这是**运行时权限**,新装的 App **默认拒绝** ——
|
||||
// 不申请的话 `NotificationManager.notify()` 不报错、但通知**根本不显示**。
|
||||
// 实测踩到:渠道建出来了(importance=3),App 级却是 `importance=NONE`,
|
||||
// 通知栏里什么都没有,而工具还返回"发送成功"。
|
||||
//
|
||||
// ★ 只在 33+ 申请:低版本没这个权限,申请了系统会直接忽略(但会打日志)。
|
||||
// ★ 用户拒绝也不影响别的功能 —— 只是发通知会失败,而且工具会如实报错。
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
val need = checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
if (need) {
|
||||
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIF)
|
||||
}
|
||||
}
|
||||
|
||||
var kernelUrl by mutableStateOf("")
|
||||
var status by mutableStateOf("正在启动本地内核…")
|
||||
var termuxReady by mutableStateOf(false)
|
||||
@@ -70,6 +92,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (port != null && port > 0) {
|
||||
client.baseUrl = "http://127.0.0.1:$port"
|
||||
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||
KernelHost.set(port)
|
||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||
withContext(Dispatchers.IO) {
|
||||
@@ -0,0 +1,912 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.net.Uri
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.data.AppTimeouts
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 暴露给 Python 内核的原生能力。
|
||||
*
|
||||
* Chaquopy 允许 Python 直接调这个类的方法(`from java import jclass` 那套),
|
||||
* 所以内核里的 `device` 工具、剪贴板钩子、选文件钩子都落到这里。
|
||||
*
|
||||
* 线程约定:device() 可能阻塞几秒(采传感器、等定位),
|
||||
* 它只会在内核的 HTTP 工作线程上被调用,**不会**卡住 UI 线程。
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
/**
|
||||
* 一次最多列多少个 App。
|
||||
*
|
||||
* ★ 必须有上限:手机上有 100~300 个 App,全塞给模型光这一条就几千 token,
|
||||
* 而且它多半只需要"找那一个"。要全量就用 query 过滤。
|
||||
*/
|
||||
private val APP_LIST_MAX = 120
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一的入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
JSONObject(payloadJson)
|
||||
} catch (e: Exception) {
|
||||
JSONObject()
|
||||
}
|
||||
val action = req.optString("action", "info")
|
||||
return try {
|
||||
when (action) {
|
||||
"info" -> deviceInfo()
|
||||
"battery" -> batteryInfo()
|
||||
"location" -> locationInfo()
|
||||
"sensors" -> sensorList()
|
||||
"sensor" -> sensorSample(req.optString("sensor"), req.optDouble("duration", 1.5))
|
||||
"clipboard_get" -> JSONObject().put("text", readClipboard())
|
||||
"clipboard_set" -> {
|
||||
setClipboard(req.optString("text"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// 内置 Termux:完整 Linux 用户态(真 bash / 真 pkg / 真子进程)
|
||||
"termux_available" -> JSONObject().put("installed", TermuxShell.isReady(activity))
|
||||
"termux_run" -> TermuxShell.run(
|
||||
activity,
|
||||
req.optString("command"),
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
|
||||
//
|
||||
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
|
||||
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
|
||||
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
|
||||
"ui_screen" -> uiScreen(req)
|
||||
// 再打开一个存下来的界面(用户要求"AI 写的界面可以再点开")
|
||||
"ui_screen_reopen" -> uiScreenReopen(req)
|
||||
"ui_screen_list" -> uiScreenList(req)
|
||||
"ui_screen_delete" -> uiScreenDelete(req)
|
||||
"ui_dialog" -> uiDialog(req)
|
||||
"end_conversation" -> endConversation(req)
|
||||
// AI 主动往会话里发一条消息(tools/send_message.py)
|
||||
"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)
|
||||
}
|
||||
// ★ AI 主动发一条通知(用户要求"还可以发送通知")
|
||||
"notification_post" -> {
|
||||
val title = req.optString("title")
|
||||
val text = req.optString("text")
|
||||
if (title.isBlank() && text.isBlank()) {
|
||||
JSONObject().put("error", "title 和 text 至少要给一个")
|
||||
} else {
|
||||
PhoneOps.postNotification(
|
||||
activity, title, text, req.optBoolean("autoCancel", true),
|
||||
)
|
||||
}
|
||||
}
|
||||
"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,
|
||||
req.optString("stream", "music"),
|
||||
req.optString("mode", "set"),
|
||||
req.optInt("value", 0),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 主动往**当前会话**里发一条消息(`tools/send_message.py`)。
|
||||
*
|
||||
* 走内核的 `/api/session-message` —— 那边负责落进会话历史、
|
||||
* 以及**两道防死循环的闸**(嵌套深度、每会话条数)。
|
||||
*
|
||||
* ★ 为什么闸不在 Kotlin 这层做:内核才有会话上下文和那两处的计数。
|
||||
* 这层只转发,判断留给一处,避免两个地方规则不一致。
|
||||
*/
|
||||
private fun sessionMessage(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId").trim()
|
||||
val text = req.optString("text").trim()
|
||||
if (conv.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
if (text.isEmpty()) return JSONObject().put("error", "text 是空的")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("conversationId", conv)
|
||||
.put("text", text)
|
||||
.put("role", req.optString("role", "user"))
|
||||
.put("reply", req.optBoolean("reply", false))
|
||||
.put("depth", req.optInt("depth", 1))
|
||||
val resp = kernelPost("/api/session-message", body) ?: return JSONObject()
|
||||
.put("error", "内核没响应,消息没发出去")
|
||||
// 内核把"闸门拒绝"也放在 error 字段里(HTTP 200 + error)——
|
||||
// 所以这里原样透传,别把它当成成功。
|
||||
resp
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。**
|
||||
*
|
||||
* AI 在 `show_ui` 的 HTML 里写 `Doubao.sendToAi('值')`,那个值会打到这里,
|
||||
* 然后 POST 到内核的 `/api/ui-result` 排队。
|
||||
* 下一轮对话开始时,`agent_loop` 会把队里的东西作为上下文交给模型 ——
|
||||
* 于是模型**真的知道**用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 为什么经内核排队、而不是让 Kotlin 直接起一轮对话:
|
||||
* 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型既慢又费 token,
|
||||
* 而且用户还没说完。排队 → 下一次说话时一起带上,语义上也更对:
|
||||
* **界面上的选择是提问的一部分,不是提问本身**。
|
||||
*
|
||||
* ★ 失败不抛异常,只回 ok:false:这是"用户点了一下按钮",
|
||||
* 内核没起来不该让 App 崩(用户会看到提示,也能再点一次)。
|
||||
*/
|
||||
private fun pushUiResult(req: JSONObject): JSONObject {
|
||||
val value = req.optString("value").trim()
|
||||
val convId = req.optString("conversationId").trim()
|
||||
if (value.isEmpty()) return JSONObject().put("error", "value 是空的")
|
||||
if (convId.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
return try {
|
||||
val body = JSONObject().put("conversationId", convId).put("value", value)
|
||||
val resp = kernelPost("/api/ui-result", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,这次选择没能送出去")
|
||||
} else {
|
||||
JSONObject().put("ok", true).put("queued", resp.optInt("queued"))
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||
*
|
||||
* [wait] 由工具参数决定:
|
||||
* · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关
|
||||
* · true ——**等用户操作**:点了回传按钮或关掉界面才返回,
|
||||
* 用户点的值原样带回给模型
|
||||
*
|
||||
* ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话,
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**(用户要求"AI 询问界面不要限时")。
|
||||
* 想限时得模型显式传 timeout。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
val wait = req.optBoolean("wait", false)
|
||||
val title = req.optString("title")
|
||||
val fullHtml = req.optBoolean("full_html", false)
|
||||
val convId = req.optString("conversationId")
|
||||
|
||||
// ★★ 先存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
// 用户的原话:"AI 写的界面可以再点开"。
|
||||
// 以前界面只活在内存里,一关(或退出 App)就没了;想再看只能让 AI
|
||||
// 重新生成,而重新生成的内容不一定一样(模型有随机性)——
|
||||
// 用户会觉得"我明明看过的东西怎么变了"。
|
||||
//
|
||||
// 存失败不影响弹出(用户至少还能看这一眼),所以不抛异常。
|
||||
val saved = runCatching {
|
||||
AiSurface.saveScreen(activity, html, title, fullHtml, convId)
|
||||
}.getOrNull()
|
||||
val screenId = saved?.optString("id").orEmpty()
|
||||
|
||||
if (wait) AiSurface.armScreenLatch()
|
||||
return AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = convId,
|
||||
wait = wait,
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
screenId = screenId,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 再打开一个存下来的界面。
|
||||
*
|
||||
* ★ 和 [uiScreen] 的区别:那个是"AI 刚写了一个新界面",
|
||||
* 这个是"用户想再看一遍**以前那个**"。后者不需要模型参与 ——
|
||||
* 内容就在磁盘上,读出来直接显示。
|
||||
*/
|
||||
private fun uiScreenReopen(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
val html = AiSurface.readScreen(activity, id)
|
||||
?: return JSONObject().put("error", "这个界面已经不在了(可能被清理或删除)")
|
||||
|
||||
// 从索引里把标题 / fullHtml 取回来,不然重开之后标题会变成"AI 界面"
|
||||
var title = ""
|
||||
var fullHtml = false
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") == id) {
|
||||
title = it.optString("title")
|
||||
fullHtml = it.optBoolean("fullHtml")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = req.optString("conversationId"),
|
||||
wait = false,
|
||||
screenId = id,
|
||||
)
|
||||
return JSONObject().put("ok", true).put("screenId", id)
|
||||
}
|
||||
|
||||
/** 列出存下来的界面(消息操作栏的「界面」按钮用它) */
|
||||
private fun uiScreenList(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId")
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
val out = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (conv.isNotBlank() && it.optString("conversationId") != conv) continue
|
||||
out.put(it)
|
||||
}
|
||||
return JSONObject().put("screens", out)
|
||||
}
|
||||
|
||||
private fun uiScreenDelete(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
AiSurface.deleteScreen(activity, id)
|
||||
return JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**。用户的原话是"AI 询问界面不要限时":
|
||||
* 他在思考的时候弹窗到点自己消失、模型还收到 timeout 当成"用户不理我",
|
||||
* 这一轮就答非所问了。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
if (question.isBlank()) return JSONObject().put("error", "question 是空的")
|
||||
|
||||
val options = mutableListOf<AiSurface.Option>()
|
||||
val arr = req.optJSONArray("options") ?: JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val label = o.optString("label").ifBlank { o.optString("value") }
|
||||
if (label.isBlank()) continue
|
||||
options.add(
|
||||
AiSurface.Option(
|
||||
label = label,
|
||||
value = o.optString("value").ifBlank { label },
|
||||
description = o.optString("description"),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (options.isEmpty()) return JSONObject().put("error", "至少要有一个选项")
|
||||
|
||||
return AiSurface.ask(
|
||||
question = question,
|
||||
options = options,
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 永久结束当前对话(tools/end_conversation.py)。
|
||||
*
|
||||
* ★ 必须**落盘**(PATCH /api/conversations/<id>),不能只改界面状态 ——
|
||||
* 界面状态一刷新就没了,用户重进会看到一个能继续输入的框,
|
||||
* 而模型以为自己已经结束了。两边状态不一致是这类功能最容易出的问题。
|
||||
*/
|
||||
private fun endConversation(req: JSONObject): JSONObject {
|
||||
val convId = req.optString("conversationId").ifBlank {
|
||||
return JSONObject().put("error", "没有 conversationId,无法结束对话")
|
||||
}
|
||||
val reason = req.optString("reason")
|
||||
val summary = req.optString("summary")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("ended", true)
|
||||
.put("endedAt", System.currentTimeMillis())
|
||||
.put("endedReason", reason)
|
||||
if (summary.isNotBlank()) body.put("endedSummary", summary)
|
||||
// 走内核自己的 HTTP 接口 —— 这是唯一一条"由 Kotlin 写内核数据"的既有通道
|
||||
val resp = kernelPatch("/api/conversations/$convId", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,对话状态没写进去")
|
||||
} else {
|
||||
AiSurface.markEnded(convId)
|
||||
JSONObject().put("ok", true).put("conversationId", convId)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH 一下内核的接口。
|
||||
*
|
||||
* ★ 这里**不能用 KernelClient** —— 那是 ViewModel 层的东西,NativeBridge
|
||||
* 拿不到(而且它跑在内核工作线程上,不该依赖 UI 层的对象)。
|
||||
* 直接用 OkHttp 打本机端口,和内核在同一个进程里,开销可以忽略。
|
||||
*
|
||||
* 端口从 [KernelHost.port] 取(内核起来之后写进去的)。
|
||||
*/
|
||||
private fun kernelPatch(path: String, body: JSONObject): String? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.patch(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
client.newCall(req).execute().use { resp ->
|
||||
return if (resp.isSuccessful) resp.body?.string() else null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 一下内核的接口,返回解析好的 JSON;失败返回 null。
|
||||
*
|
||||
* ★ 和 [kernelPatch] 共用同一套"直接打本机端口"的做法 ——
|
||||
* 不用 `KernelClient`(那是 ViewModel 层的东西,NativeBridge 拿不到,
|
||||
* 而且这里是内核工作线程,不该依赖 UI 层对象)。
|
||||
*/
|
||||
private fun kernelPost(path: String, body: JSONObject): JSONObject? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.post(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
return client.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val text = resp.body?.string() ?: return null
|
||||
runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 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()) {
|
||||
// ★ 只给包名不给 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 失败(系统拒绝了,可能被停用)")
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
val totalGb = stat.totalBytes / 1024.0 / 1024.0 / 1024.0
|
||||
return JSONObject()
|
||||
.put("platform", "Android")
|
||||
.put("model", Build.MODEL)
|
||||
.put("manufacturer", Build.MANUFACTURER)
|
||||
.put("brand", Build.BRAND)
|
||||
.put("device", Build.DEVICE)
|
||||
.put("android", Build.VERSION.RELEASE)
|
||||
.put("sdk", Build.VERSION.SDK_INT)
|
||||
.put("abis", JSONArray(Build.SUPPORTED_ABIS.toList()))
|
||||
.put("storage_free_gb", String.format("%.1f", freeGb))
|
||||
.put("storage_total_gb", String.format("%.1f", totalGb))
|
||||
.put("screen", screenInfo())
|
||||
.put("battery", batteryInfo())
|
||||
}
|
||||
|
||||
private fun screenInfo(): String {
|
||||
val metrics = activity.resources.displayMetrics
|
||||
return "${metrics.widthPixels}x${metrics.heightPixels} @${metrics.density}x"
|
||||
}
|
||||
|
||||
private fun batteryInfo(): JSONObject {
|
||||
val bm = activity.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
|
||||
return JSONObject()
|
||||
.put("level_percent", bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1)
|
||||
.put("charging", bm?.isCharging ?: false)
|
||||
}
|
||||
|
||||
/** 定位:先拿最后已知位置,拿不到就等一次单次更新(最多 8 秒) */
|
||||
private fun locationInfo(): JSONObject {
|
||||
val lm = activity.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
?: return JSONObject().put("error", "没有 LocationManager")
|
||||
val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
|
||||
var best: Location? = null
|
||||
for (p in providers) {
|
||||
try {
|
||||
if (!lm.isProviderEnabled(p)) continue
|
||||
val loc = lm.getLastKnownLocation(p) ?: continue
|
||||
if (best == null || loc.time > best!!.time) best = loc
|
||||
} catch (t: SecurityException) {
|
||||
return JSONObject().put("error", "缺少定位权限(ACCESS_FINE_LOCATION)")
|
||||
} catch (_: Throwable) {
|
||||
// 某些机型会抛 IllegalArgumentException,忽略继续
|
||||
}
|
||||
}
|
||||
if (best == null) {
|
||||
val latch = CountDownLatch(1)
|
||||
var fresh: Location? = null
|
||||
val listener = object : android.location.LocationListener {
|
||||
override fun onLocationChanged(location: Location) {
|
||||
fresh = location
|
||||
latch.countDown()
|
||||
}
|
||||
// 老 API 要求实现,留着空实现
|
||||
override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
|
||||
override fun onProviderEnabled(provider: String) {}
|
||||
override fun onProviderDisabled(provider: String) {}
|
||||
}
|
||||
try {
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, listener)
|
||||
} catch (_: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(8, TimeUnit.SECONDS)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
} finally {
|
||||
try {
|
||||
lm.removeUpdates(listener)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
best = fresh
|
||||
}
|
||||
if (best == null) {
|
||||
return JSONObject()
|
||||
.put("available", false)
|
||||
.put("hint", "没拿到定位:确认已开定位开关、已授予权限、或在室内 GPS 信号差时稍后再试")
|
||||
}
|
||||
return JSONObject()
|
||||
.put("available", true)
|
||||
.put("latitude", best!!.latitude)
|
||||
.put("longitude", best!!.longitude)
|
||||
.put("accuracy_m", best!!.accuracy.toDouble())
|
||||
.put("provider", best!!.provider)
|
||||
.put("age_seconds", (System.currentTimeMillis() - best!!.time) / 1000.0)
|
||||
}
|
||||
|
||||
private val keywordToType = mapOf(
|
||||
"accelerometer" to Sensor.TYPE_ACCELEROMETER,
|
||||
"gyroscope" to Sensor.TYPE_GYROSCOPE,
|
||||
"magnetic" to Sensor.TYPE_MAGNETIC_FIELD,
|
||||
"light" to Sensor.TYPE_LIGHT,
|
||||
"pressure" to Sensor.TYPE_PRESSURE,
|
||||
"proximity" to Sensor.TYPE_PROXIMITY,
|
||||
"gravity" to Sensor.TYPE_GRAVITY,
|
||||
"linear_acceleration" to Sensor.TYPE_LINEAR_ACCELERATION,
|
||||
"rotation_vector" to Sensor.TYPE_ROTATION_VECTOR,
|
||||
"step_counter" to Sensor.TYPE_STEP_COUNTER,
|
||||
"humidity" to Sensor.TYPE_RELATIVE_HUMIDITY,
|
||||
"temperature" to Sensor.TYPE_AMBIENT_TEMPERATURE,
|
||||
"game_rotation_vector" to Sensor.TYPE_GAME_ROTATION_VECTOR,
|
||||
)
|
||||
|
||||
private fun sensorManager(): SensorManager? =
|
||||
activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
|
||||
|
||||
private fun sensorList(): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val arr = JSONArray()
|
||||
for (s in sm.getSensorList(Sensor.TYPE_ALL)) {
|
||||
val key = keywordToType.entries.firstOrNull { it.value == s.type }?.key
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("key", key ?: "type_${s.type}")
|
||||
.put("name", s.name)
|
||||
.put("vendor", s.vendor)
|
||||
.put("type", s.type)
|
||||
.put("power_ma", s.power.toDouble()),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("count", arr.length()).put("sensors", arr)
|
||||
}
|
||||
|
||||
/** 采样:注册监听 duration 秒,返回样本序列与统计 */
|
||||
private fun sensorSample(key: String, duration: Double): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val name = key.ifBlank { "accelerometer" }
|
||||
val type = keywordToType[name] ?: return JSONObject()
|
||||
.put("error", "不认识的传感器:$name(可用:${keywordToType.keys.joinToString(", ")})")
|
||||
val sensor = sm.getDefaultSensor(type)
|
||||
?: return JSONObject().put("error", "这台设备没有 $name 传感器")
|
||||
|
||||
val seconds = duration.coerceIn(0.2, 10.0)
|
||||
val samples = mutableListOf<FloatArray>()
|
||||
val latch = CountDownLatch(1)
|
||||
val listener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
if (samples.size < 500) samples.add(event.values.copyOf())
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
|
||||
}
|
||||
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME)
|
||||
try {
|
||||
// 用 latch 等不到就超时,靠 await 的返回值判断即可
|
||||
latch.await((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
|
||||
} finally {
|
||||
sm.unregisterListener(listener)
|
||||
}
|
||||
if (samples.isEmpty()) return JSONObject().put("error", "$name 在采样期内没出数据")
|
||||
|
||||
val dims = samples.first().size
|
||||
val stats = JSONArray()
|
||||
for (d in 0 until dims) {
|
||||
val values = samples.map { it[d].toDouble() }
|
||||
stats.put(
|
||||
JSONObject()
|
||||
.put("avg", values.average())
|
||||
.put("min", values.min())
|
||||
.put("max", values.max())
|
||||
.put("last", values.last()),
|
||||
)
|
||||
}
|
||||
val last = JSONArray()
|
||||
samples.last().forEach { last.put(it.toDouble()) }
|
||||
return JSONObject()
|
||||
.put("sensor", name)
|
||||
.put("unit", unitOf(name))
|
||||
.put("sample_count", samples.size)
|
||||
.put("seconds", seconds)
|
||||
.put("axes", axisNames(dims))
|
||||
.put("last", last)
|
||||
.put("stats", stats)
|
||||
}
|
||||
|
||||
private fun axisNames(dims: Int): JSONArray {
|
||||
val names = listOf("x", "y", "z", "w")
|
||||
val arr = JSONArray()
|
||||
for (i in 0 until dims) arr.put(names.getOrElse(i) { "v$i" })
|
||||
return arr
|
||||
}
|
||||
|
||||
private fun unitOf(name: String): String = when (name) {
|
||||
"accelerometer", "gravity", "linear_acceleration" -> "m/s^2"
|
||||
"gyroscope" -> "rad/s"
|
||||
"magnetic" -> "uT"
|
||||
"light" -> "lx"
|
||||
"pressure" -> "hPa"
|
||||
"proximity" -> "cm"
|
||||
"humidity" -> "%"
|
||||
"temperature" -> "°C"
|
||||
else -> ""
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 剪贴板 / 选文件
|
||||
|
||||
@Suppress("unused")
|
||||
fun setClipboard(text: String) {
|
||||
activity.runOnUiThread {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("doubao", text))
|
||||
}
|
||||
}
|
||||
|
||||
private fun readClipboard(): String {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = cm.primaryClip ?: return ""
|
||||
if (clip.itemCount == 0) return ""
|
||||
return clip.getItemAt(0).coerceToText(activity).toString()
|
||||
}
|
||||
|
||||
/** 内核请求"用户选个文件"时调用;把选中的文件复制到 App 私有目录再返回路径 */
|
||||
@Volatile
|
||||
private var pickLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var pickedUris: List<Uri> = emptyList()
|
||||
|
||||
@Suppress("unused")
|
||||
fun pickFile(): Array<String> {
|
||||
val latch = CountDownLatch(1)
|
||||
pickLatch = latch
|
||||
pickedUris = emptyList()
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = "*/*"
|
||||
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||
}
|
||||
activity.startActivityForResult(intent, REQ_PICK)
|
||||
} catch (t: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(
|
||||
AppTimeouts.seconds("filePicker", PICK_TIMEOUT_S.toDouble()).toLong(),
|
||||
TimeUnit.SECONDS,
|
||||
)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
|
||||
/** MainActivity 的 onActivityResult 转进来 */
|
||||
fun onPicked(data: Intent?) {
|
||||
val uris = mutableListOf<Uri>()
|
||||
data?.clipData?.let { clip ->
|
||||
for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri)
|
||||
}
|
||||
data?.data?.let { uris.add(it) }
|
||||
pickedUris = uris
|
||||
pickLatch?.countDown()
|
||||
}
|
||||
|
||||
private fun copyIntoCache(uri: Uri): String? = try {
|
||||
val name = displayName(uri) ?: "upload_${System.currentTimeMillis()}"
|
||||
val dir = File(activity.cacheDir, "picked").apply { mkdirs() }
|
||||
val dest = File(dir, name)
|
||||
activity.contentResolver.openInputStream(uri)?.use { input ->
|
||||
dest.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
dest.absolutePath
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun displayName(uri: Uri): String? = try {
|
||||
activity.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
/** 安卓上没有"打开文件夹",直接返回提示(设置页会显示不可用) */
|
||||
@Suppress("unused")
|
||||
fun reveal(path: String): String? = null
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
|
||||
/**
|
||||
* AI 让你挑文件时等多久的**兜底值**。
|
||||
*
|
||||
* ★ 真实值从设置读(设置 → 超时 → 选文件等多久)——
|
||||
* 去相册里翻一张老照片可能不止两分钟。这里是拿不到设置时的兜底。
|
||||
*/
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/**
|
||||
* 打本机内核端口([kernelPost] / [kernelPatch])的读超时。
|
||||
*
|
||||
* ★ 也做成可调的(设置 → 超时 → 本地接口请求):这些请求里有几个
|
||||
* 体积不小(读一条很长的会话、传附件),老设备上 10 秒不一定够。
|
||||
* 每次现读而不是建 client 时读一次 —— 改完立刻生效。
|
||||
*/
|
||||
private val LOCAL_READ_S: Long
|
||||
get() = AppTimeouts.seconds("kernelLocal", 10.0).toLong().coerceAtLeast(3L)
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
entry.callAttr("set_android_bridge", bridge)
|
||||
}
|
||||
}
|
||||
}
|
||||
374
豆鲍/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
374
豆鲍/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -0,0 +1,374 @@
|
||||
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)
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 四、发通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 通知渠道 id。
|
||||
*
|
||||
* ★ Android 8+ 必须挂在渠道上,否则通知**直接被丢掉**(连报错都没有)。
|
||||
* 渠道的重要性用 DEFAULT:太低会被折叠成静音,用户根本注意不到;
|
||||
* 太高(HIGH)会弹横幅 —— 对"AI 提醒你一件事"这种场景
|
||||
* 弹横幅太打扰了,DEFAULT 正合适(有声音 + 进通知栏,不弹横幅)。
|
||||
*/
|
||||
private const val CHANNEL_ID = "doubao_ai"
|
||||
private const val CHANNEL_NAME = "AI 提醒"
|
||||
|
||||
private fun ensureChannel(ctx: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
// ★ 不要"渠道已存在就 return":v3.17 换了 App 名之后,老用户的渠道里
|
||||
// 还留着旧描述(系统设置 → 通知里能看到)。`createNotificationChannel`
|
||||
// 用同一个 id 再调一次只会更新 name/description,不动用户改过的
|
||||
// importance,所以每次发通知前顺手刷一遍是安全的。
|
||||
// ★ CHANNEL_ID 保持 `doubao_ai`:改 id 会新建一个渠道、老渠道的设置/通知记录全丢。
|
||||
val ch = android.app.NotificationChannel(
|
||||
CHANNEL_ID, CHANNEL_NAME, android.app.NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "小人间主动发出来的提醒"
|
||||
enableVibration(true)
|
||||
}
|
||||
nm.createNotificationChannel(ch)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 发一条通知 —— 用户要求"还可以发送通知"。
|
||||
*
|
||||
* 用途:AI 说到点提醒你什么、长任务跑完了通知一声。
|
||||
*
|
||||
* ★ 点通知要能回到 App:用 `PendingIntent` 打开 MainActivity。
|
||||
* 不给 PendingIntent 的话点了没反应 —— 用户会觉得"这通知是死的"。
|
||||
*
|
||||
* ★ 用 `System.currentTimeMillis()` 当通知 id:每条独立存在,不会互相覆盖。
|
||||
* 固定 id 的话后一条会把前一条顶掉("我刚收到的提醒怎么没了")。
|
||||
*/
|
||||
fun postNotification(ctx: Context, title: String, text: String, autoCancel: Boolean): JSONObject {
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
ensureChannel(ctx)
|
||||
|
||||
val t = title.trim().ifBlank { "小人间" }
|
||||
val body = text.trim()
|
||||
|
||||
// 点通知打开 App
|
||||
val open = Intent(ctx, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
var flags = android.app.PendingIntent.FLAG_UPDATE_CURRENT
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags = flags or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
}
|
||||
val pi = android.app.PendingIntent.getActivity(ctx, 0, open, flags)
|
||||
|
||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
android.app.Notification.Builder(ctx, CHANNEL_ID)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
android.app.Notification.Builder(ctx)
|
||||
}
|
||||
builder
|
||||
// ★ v3.17 起不能再用 applicationInfo.icon:自适应图标是 108dp 的
|
||||
// 图层组合,setSmallIcon 拿到它有些机型会渲成空白。小图标要单色剪影,
|
||||
// 所以单独做了个 ic_notify(纯白房子,系统自己染色)。
|
||||
.setSmallIcon(R.drawable.ic_notify) // ★ 不给 smallIcon 通知**不会显示**
|
||||
.setContentTitle(t)
|
||||
.setContentText(body)
|
||||
.setAutoCancel(autoCancel)
|
||||
.setContentIntent(pi)
|
||||
// 正文长的话展开显示(否则通知栏只显示一行,被截断)
|
||||
if (body.length > 40) {
|
||||
builder.setStyle(android.app.Notification.BigTextStyle().bigText(body))
|
||||
}
|
||||
|
||||
val id = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
|
||||
return try {
|
||||
nm.notify(id, builder.build())
|
||||
JSONObject().put("ok", true).put("id", id)
|
||||
.put("title", t)
|
||||
.put("chars", body.length)
|
||||
} catch (t2: Throwable) {
|
||||
Log.w(TAG, "发通知失败:${t2.message}")
|
||||
JSONObject().put("error", "发通知失败:${t2.javaClass.simpleName}: ${t2.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、打开 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
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接拉起某个 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
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、音量 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 音量流。
|
||||
*
|
||||
* ★ 用**字符串名**而不是整数常量:模型要写 `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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.doubao.lynxclone.data
|
||||
|
||||
/**
|
||||
* 客户端这边的超时缓存。
|
||||
*
|
||||
* ## 为什么客户端也要有一份
|
||||
*
|
||||
* 权威在**内核**(`android/kernel/timeouts.py`,界面通过 `GET /api/timeouts` 拿)。
|
||||
* 但客户端有几处**没法在用的那一刻去问内核**:
|
||||
*
|
||||
* · OkHttp 的连接池 —— 建连接时就要 readTimeout,而"去问内核"本身要用这个连接
|
||||
* · 文件选择(SAF)—— 那是系统界面的等待,内核根本不知情
|
||||
*
|
||||
* 所以这里缓存一份,App 启动时拉一次、用户改完设置再刷新一次。
|
||||
*
|
||||
* ★ 拿不到时一律回落**和内核一样的默认值** —— 不回落的话,"内核还没起来"
|
||||
* 会让连接超时变成 0(每次都断)。两边的默认值要保持一致,
|
||||
* `scripts/verify-timeouts.py` 会检查内核对不对得上。
|
||||
*/
|
||||
object AppTimeouts {
|
||||
|
||||
@Volatile
|
||||
private var values: Map<String, Double> = emptyMap()
|
||||
|
||||
/** 内核给的清单(界面上那份),缓存着免得每次进设置页都请求 */
|
||||
@Volatile
|
||||
var state: TimeoutsState = TimeoutsState()
|
||||
private set
|
||||
|
||||
fun update(next: TimeoutsState) {
|
||||
state = next
|
||||
values = next.values
|
||||
}
|
||||
|
||||
fun seconds(key: String, fallback: Double): Double {
|
||||
val v = values[key] ?: return fallback
|
||||
return if (v <= 0.0) fallback else v
|
||||
}
|
||||
|
||||
fun millis(key: String, fallbackMs: Long): Long =
|
||||
(seconds(key, fallbackMs / 1000.0) * 1000).toLong()
|
||||
|
||||
/**
|
||||
* 等用户的那两项:**0 是有意义的值**(不限时),所以不能按上面的写法回落。
|
||||
*/
|
||||
fun userWaitMillis(key: String): Long {
|
||||
val v = values[key] ?: return 0L
|
||||
return if (v <= 0.0) 0L else (v * 1000).toLong()
|
||||
}
|
||||
|
||||
/** 读 SSE 的间隔上限 —— 必须大于心跳间隔,否则等用户时连接会被自己掐掉 */
|
||||
fun sseReadSeconds(): Long = seconds("sseRead", 120.0).toLong().coerceAtLeast(20L)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
2974
豆鲍/android/app/src/main/java/com/doubao/lynxclone/data/Models.kt
Normal file
2974
豆鲍/android/app/src/main/java/com/doubao/lynxclone/data/Models.kt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,16 @@ class SpeechController(
|
||||
private val context: Context,
|
||||
private val client: KernelClient,
|
||||
private val scope: CoroutineScope,
|
||||
/**
|
||||
* 当前说话的是哪个智能体 —— 朗读时把它带给内核,用**它自己的音色**。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前 `client.speak(text)` 只传正文,
|
||||
* 内核拿不到 agentId 就一律用全局音色,于是**智能体编辑页里选的声音
|
||||
* 配了也没用**(用户报的"智能体语音咋没生效")。
|
||||
* 做成 lambda 而不是字符串,是因为它会随用户切换智能体而变,
|
||||
* 而这个 controller 是在进聊天页时 remember 一次的。
|
||||
*/
|
||||
private val agentId: () -> String = { "" },
|
||||
) {
|
||||
private val speaker = Speaker(context)
|
||||
private val recorder = Recorder(context)
|
||||
@@ -61,8 +71,18 @@ class SpeechController(
|
||||
|
||||
/* ------------------------------ 朗读 ------------------------------ */
|
||||
|
||||
/** 念第 index 条消息 */
|
||||
fun speak(text: String, index: Int) {
|
||||
/**
|
||||
* 念第 [index] 条消息。
|
||||
*
|
||||
* [who] = **说这句话的智能体**(群聊里每条消息的发言者都不一样)。
|
||||
* 传空串就退回 [agentId] 那个"当前智能体"。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前只会拿"当前对话的主人"去要音色,
|
||||
* 于是群聊里小黑和寐眠各配了不同音色,读出来却始终是同一个声音
|
||||
* (用户报的"群聊的时候不同智能体的语音不会切换")。
|
||||
* 内核其实**一直在消息里存 agentId**,只是客户端没读。
|
||||
*/
|
||||
fun speak(text: String, index: Int, who: String = "") {
|
||||
if (text.isBlank()) return
|
||||
// 正在念同一条 → 再点一次就是停
|
||||
if (speakingIndex == index && speaker.isPlaying) {
|
||||
@@ -76,6 +96,7 @@ class SpeechController(
|
||||
cancelRecording()
|
||||
|
||||
speakingIndex = index
|
||||
val voice = who.ifBlank { agentId() }
|
||||
scope.launch {
|
||||
// ★ 首选流式:内核边合成边下发 PCM,这边边收边喂 AudioTrack,
|
||||
// 首句大约 1 秒就能出声(整段合成再播要等 3 秒以上)。
|
||||
@@ -89,7 +110,7 @@ class SpeechController(
|
||||
// 用户看到的就是"一读语音就闪退"。
|
||||
val played = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
client.streamTts(text).use { r ->
|
||||
client.streamTts(text, voice).use { r ->
|
||||
val mime = r.body?.contentType().toString()
|
||||
val source = r.body?.source()
|
||||
source != null && speaker.playStream(mime, source)
|
||||
@@ -107,18 +128,22 @@ class SpeechController(
|
||||
}
|
||||
|
||||
try {
|
||||
val result = client.speak(text)
|
||||
val result = client.speak(text, voice)
|
||||
// ★ v3.27:内核会带回"可朗读文本"(剥 Markdown + 去掉括号旁白,
|
||||
// 云端引擎还会把括号变成语音指令)。退回系统 TTS 时念这份,
|
||||
// 否则括号里的旁白会被念出来("括号压低声音")。
|
||||
val speakText = result.optString("speakText").ifBlank { text }
|
||||
if (!result.optBoolean("ok")) {
|
||||
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
|
||||
val reason = result.optString("error").ifBlank { "云端合成失败" }
|
||||
Log.w(TAG, "云端朗读失败,改用系统引擎:$reason")
|
||||
notice = "云端失败,改用系统朗读:$reason"
|
||||
speaker.speakSystem(text)
|
||||
speaker.speakSystem(speakText)
|
||||
return@launch
|
||||
}
|
||||
val engine = result.optString("engine")
|
||||
if (engine == "system" || result.isNull("audio")) {
|
||||
speaker.speakSystem(text)
|
||||
speaker.speakSystem(speakText)
|
||||
} else {
|
||||
speaker.playBase64(result.optString("audio"), result.optString("mime", "audio/mpeg"))
|
||||
}
|
||||
@@ -157,8 +182,8 @@ class SpeechController(
|
||||
*/
|
||||
private var lastAutoReadKey: String? = null
|
||||
|
||||
/** 自动朗读:新回复刚落地时调它 */
|
||||
fun maybeAutoRead(text: String, index: Int) {
|
||||
/** 自动朗读:新回复刚落地时调它。[who] 同 [speak] —— 群聊里要按发言者挑音色 */
|
||||
fun maybeAutoRead(text: String, index: Int, who: String = "") {
|
||||
if (!autoRead || text.isBlank()) return
|
||||
if (recording) return
|
||||
|
||||
@@ -168,7 +193,7 @@ class SpeechController(
|
||||
if (speakingIndex == index && speaker.isPlaying) return
|
||||
|
||||
lastAutoReadKey = key
|
||||
speak(text, index)
|
||||
speak(text, index, who)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
@@ -0,0 +1,443 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
/**
|
||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||
*
|
||||
* ## 为什么要一个单例控制器
|
||||
*
|
||||
* 内核(Python,跑在 HTTP 工作线程上)通过 `NativeBridge.device()` 说
|
||||
* "给我弹个界面",而界面是 Compose 画的、归 `AppViewModel` 管。
|
||||
* 这两边**没有互相引用**:
|
||||
*
|
||||
* · `NativeBridge` 在 `MainActivity` 里 new 出来(见 MainActivity:76)
|
||||
* · `AppViewModel` 在 Compose 树里由 `rememberAppViewModel` 造
|
||||
*
|
||||
* 所以中间放一个单例:NativeBridge 往里写,ViewModel 订阅。
|
||||
* 这也让"内核线程"和"UI 状态"的边界很清楚 —— 内核永远不直接碰 Compose。
|
||||
*
|
||||
* ## 线程模型(这是最容易出错的地方)
|
||||
*
|
||||
* `device()` 是在**内核的 HTTP 工作线程**上被调的,而:
|
||||
* · 写状态:用 `@Volatile` + 监听器回调,ViewModel 在自己的协程里切主线程更新 Compose
|
||||
* · 等用户选择:用 [CountDownLatch] 阻塞**那个工作线程**(不能阻塞 UI 线程)
|
||||
*
|
||||
* 跟 `NativeBridge.pickFile()` 是同一套路子(它已经验证过可行)。
|
||||
*/
|
||||
object AiSurface {
|
||||
|
||||
private const val TAG = "DoubaoAiSurface"
|
||||
|
||||
/** 一次 AI 界面的标识。每次弹出都换一个,用来让 Compose 重建 WebView。 */
|
||||
private val seq = AtomicLong(0)
|
||||
|
||||
/** 正在显示的 HTML 界面;null 表示没有 */
|
||||
@Volatile
|
||||
var screen: Screen? = null
|
||||
private set
|
||||
|
||||
/** 正在等的选择弹窗;null 表示没有 */
|
||||
@Volatile
|
||||
var dialog: Dialog? = null
|
||||
private set
|
||||
|
||||
/** 当前对话被 AI 结束过 —— 界面据此禁用输入框 */
|
||||
@Volatile
|
||||
var endedConversationId: String = ""
|
||||
private set
|
||||
|
||||
data class Screen(
|
||||
val id: Long,
|
||||
val html: String,
|
||||
val title: String,
|
||||
val fullHtml: Boolean,
|
||||
val conversationId: String,
|
||||
/** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */
|
||||
val waiting: Boolean = false,
|
||||
/** 磁盘上那一份的 id(空 = 没存)。再打开时靠它去读。 */
|
||||
val screenId: String = "",
|
||||
)
|
||||
|
||||
data class Option(val label: String, val value: String, val description: String)
|
||||
|
||||
data class Dialog(
|
||||
val id: Long,
|
||||
val question: String,
|
||||
val options: List<Option>,
|
||||
val multiple: Boolean,
|
||||
val allowCancel: Boolean,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** ViewModel 订阅这个来把状态同步进 Compose。参数是"发生了什么"。 */
|
||||
@Volatile
|
||||
private var listener: ((String) -> Unit)? = null
|
||||
|
||||
fun subscribe(fn: ((String) -> Unit)?) {
|
||||
listener = fn
|
||||
}
|
||||
|
||||
private fun notify(kind: String) {
|
||||
try {
|
||||
listener?.invoke(kind)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "通知界面失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 把界面存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
*
|
||||
* ## 为什么需要(用户的原话:"AI 写的界面可以再点开")
|
||||
*
|
||||
* 界面以前只活在内存里:用户一关(或者退出 App),那份 HTML 就没了。
|
||||
* 过一会儿想"刚才那个图表再看一眼"就再也找不回来,只能让 AI 重新生成 ——
|
||||
* 而重新生成的内容**和上次不一定一样**(模型有随机性),
|
||||
* 用户看到的是"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* ## 为什么不放内核(Python)那边
|
||||
*
|
||||
* 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
|
||||
* `device()` 参数。要走内核就得 Kotlin 再 POST 一次上去,多一次往返、
|
||||
* 还多一个失败点。而 App 私有目录本来就是 Kotlin 最顺手的地方。
|
||||
*
|
||||
* 存法:
|
||||
* `<app files>/ai-screens/<id>.html` 正文
|
||||
* `<app files>/ai-screens/index.json` 索引(列表只读这个)
|
||||
*/
|
||||
private val screensLock = Any()
|
||||
|
||||
fun screenDir(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(ctx.filesDir, "ai-screens").apply { mkdirs() }
|
||||
|
||||
fun screenIndexFile(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(screenDir(ctx), "index.json")
|
||||
|
||||
fun loadScreenIndex(ctx: android.content.Context): JSONArray = synchronized(screensLock) {
|
||||
try {
|
||||
val text = screenIndexFile(ctx).readText()
|
||||
JSONArray(text)
|
||||
} catch (_: Throwable) {
|
||||
JSONArray()
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveScreenIndex(ctx: android.content.Context, arr: JSONArray) {
|
||||
try {
|
||||
screenIndexFile(ctx).writeText(arr.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "写界面索引失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 存下一个界面,返回它的索引项(含 id)。
|
||||
*
|
||||
* ★ 每个会话只留最近 [KEEP_PER_CONV] 个:用户跟 AI 聊久了会弹出几十个界面,
|
||||
* 列表没法看、磁盘也白占。超出时把**最旧的正文删掉**(索引项也去掉),
|
||||
* 保留最近这些。
|
||||
*/
|
||||
fun saveScreen(
|
||||
ctx: android.content.Context,
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
): JSONObject? {
|
||||
val id = "s_" + java.util.UUID.randomUUID().toString().replace("-", "").take(12)
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").writeText(html)
|
||||
val item = JSONObject()
|
||||
.put("id", id)
|
||||
.put("title", title.ifBlank { "AI 界面" })
|
||||
.put("fullHtml", fullHtml)
|
||||
.put("bytes", html.length)
|
||||
.put("conversationId", conversationId)
|
||||
.put("preview", previewOf(html))
|
||||
.put("at", System.currentTimeMillis())
|
||||
synchronized(screensLock) {
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray().put(item)
|
||||
var kept = 0
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("conversationId") != conversationId) {
|
||||
next.put(it); continue
|
||||
}
|
||||
if (kept < KEEP_PER_CONV) {
|
||||
next.put(it); kept++
|
||||
} else {
|
||||
runCatching { java.io.File(screenDir(ctx), "${it.optString("id")}.html").delete() }
|
||||
}
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
item
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "存界面失败:${t.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 读一个界面的正文 */
|
||||
fun readScreen(ctx: android.content.Context, id: String): String? {
|
||||
if (id.isBlank() || id.contains('/') || id.contains("..")) return null
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").readText()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteScreen(ctx: android.content.Context, id: String) {
|
||||
synchronized(screensLock) {
|
||||
runCatching { java.io.File(screenDir(ctx), "$id.html").delete() }
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") != id) next.put(it)
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 HTML 里抠一小段纯文字做预览(列表里靠它认出是哪个界面) */
|
||||
private fun previewOf(html: String): String =
|
||||
html.replace(Regex("(?is)<(script|style)[^>]*>.*?</\\1>"), " ")
|
||||
.replace(Regex("<[^>]+>"), " ")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
.take(120)
|
||||
|
||||
private const val KEEP_PER_CONV = 30
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。
|
||||
*
|
||||
* [wait] = false(默认):**不阻塞** —— 弹出来就返回。
|
||||
* [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。
|
||||
*
|
||||
* ★ 为什么要两种:
|
||||
* 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。
|
||||
* 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。
|
||||
* 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。
|
||||
*
|
||||
* ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile`
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★★ [timeoutMs] <= 0 表示**不限时**(等用户到天荒地老),这是默认。
|
||||
* 以前默认 120 秒,用户明确要求"AI 询问界面不要限时"——
|
||||
* 他可能看着界面想很久,120 秒到点界面自己收掉,体验很差。
|
||||
* 现在想限时得由模型显式传 timeout。
|
||||
*/
|
||||
fun showScreen(
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 0L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(
|
||||
seq.incrementAndGet(), html, title, fullHtml, conversationId,
|
||||
waiting = wait, screenId = screenId,
|
||||
)
|
||||
screen = s
|
||||
screenClosed = false
|
||||
screenAnswer = null
|
||||
notify("screen")
|
||||
Log.i(
|
||||
TAG,
|
||||
"AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," +
|
||||
if (wait) "等用户操作(${waitLabel(timeoutMs)})" else "不等待",
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
// ★ 带上 id —— 它一路回到模型的工具返回值、再进 ToolTrace,
|
||||
// 消息操作栏据此显示「界面」按钮(用户要求"可以再点开")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
// ---- 等待模式 ----
|
||||
val latch = screenLatch
|
||||
val answered = latch?.let { awaitUser(it, timeoutMs) } ?: false
|
||||
val answer = screenAnswer
|
||||
val closed = screenClosed
|
||||
screenLatch = null
|
||||
|
||||
// 等到答案(或超时)之后把界面收掉 —— 否则用户看到一个已经"用完了"
|
||||
// 的界面还开着,会以为还能再点。
|
||||
if (answered) {
|
||||
screen = null
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
.put("waited", true)
|
||||
.put("timeout", !answered)
|
||||
.put("closed", closed)
|
||||
// 用户点的值。超时/直接关掉时是空串。
|
||||
.put("value", answer ?: "")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
/** 等用户交互用的闩。非等待模式下是 null。 */
|
||||
@Volatile
|
||||
private var screenLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var screenAnswer: String? = null
|
||||
|
||||
@Volatile
|
||||
private var screenClosed: Boolean = false
|
||||
|
||||
/**
|
||||
* 用户在界面上点了回传按钮(`Doubao.sendToAi` / `data-doubao-result`)。
|
||||
*
|
||||
* ★ 等待模式下这一下就是"用户答完了"的信号:记下值、放行。
|
||||
* 界面侧收到后会把自己收掉。
|
||||
*/
|
||||
fun screenResult(value: String) {
|
||||
Log.i(TAG, "界面里点了:$value")
|
||||
lastScreenResult = value
|
||||
screenAnswer = value
|
||||
screenClosed = false
|
||||
screenLatch?.countDown()
|
||||
notify("screenResult")
|
||||
}
|
||||
|
||||
@Volatile
|
||||
var lastScreenResult: String = ""
|
||||
private set
|
||||
|
||||
/** 用户把界面关掉了 */
|
||||
fun closeScreen() {
|
||||
screen = null
|
||||
// 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串
|
||||
screenClosed = true
|
||||
screenLatch?.countDown()
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
/** 进等待模式前由 NativeBridge 调一次,准备闩 */
|
||||
fun armScreenLatch() {
|
||||
screenLatch = CountDownLatch(1)
|
||||
screenAnswer = null
|
||||
screenClosed = false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完。
|
||||
*
|
||||
* ★★ [timeoutMs] <= 0 = **不限时**(默认)。这是用户明确要求的:
|
||||
* "AI 询问界面不要限时" —— 他可能对着选项想很久,或者在忙别的事,
|
||||
* 120 秒到点弹窗自己消失、模型收到 `timeout=true` 以为他不想理,
|
||||
* 然后自说自话往下走 —— 整轮就废了。
|
||||
*
|
||||
* ★ 放行的方式(用户总得有一个出口,不然内核线程永远挂着):
|
||||
* · 点任意一个选项 → [answerDialog] → countDown
|
||||
* · 点「取消」(`allowCancel` 默认 true)→ 同上,`cancelled=true`
|
||||
* · 关掉 App → 进程结束,线程一起没了
|
||||
* 所以只要界面上留着取消按钮,无限等就不会变成死锁。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
*/
|
||||
fun ask(
|
||||
question: String,
|
||||
options: List<Option>,
|
||||
multiple: Boolean,
|
||||
allowCancel: Boolean,
|
||||
conversationId: String,
|
||||
timeoutMs: Long,
|
||||
): JSONObject {
|
||||
val d = Dialog(seq.incrementAndGet(), question, options, multiple, allowCancel, conversationId)
|
||||
val latch = CountDownLatch(1)
|
||||
answerLatch = latch
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,${waitLabel(timeoutMs)})")
|
||||
|
||||
val answered = awaitUser(latch, timeoutMs)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
dialog = null
|
||||
notify("dialog")
|
||||
|
||||
if (!answered || a == null) {
|
||||
Log.i(TAG, "用户没在时限内回答")
|
||||
return JSONObject()
|
||||
.put("timeout", true)
|
||||
.put("multiple", multiple)
|
||||
.put("choice", "")
|
||||
.put("values", JSONArray())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
/**
|
||||
* 等用户动作。
|
||||
*
|
||||
* [timeoutMs] <= 0 → **无限等**(`await()` 不带超时);否则最多等那么久。
|
||||
* 返回 true 表示等到了。
|
||||
*
|
||||
* ★ 只有这一个地方做等待,[ask] 和 [showScreen] 都走它 ——
|
||||
* 两处各写一遍的话,"不限时"这种改动迟早只改到一处。
|
||||
*/
|
||||
private fun awaitUser(latch: CountDownLatch, timeoutMs: Long): Boolean =
|
||||
if (timeoutMs <= 0L) {
|
||||
latch.await()
|
||||
true
|
||||
} else {
|
||||
latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
/** 日志里怎么描述等待时长 */
|
||||
private fun waitLabel(timeoutMs: Long): String =
|
||||
if (timeoutMs <= 0L) "不限时,等用户回答" else "最多等 ${timeoutMs / 1000}s"
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var answer: JSONObject? = null
|
||||
|
||||
/** 用户选了。界面调这个。 */
|
||||
fun answerDialog(values: List<String>, cancelled: Boolean) {
|
||||
val arr = JSONArray()
|
||||
values.forEach { arr.put(it) }
|
||||
answer = JSONObject()
|
||||
.put("timeout", false)
|
||||
.put("cancelled", cancelled)
|
||||
.put("multiple", dialog?.multiple ?: false)
|
||||
.put("choice", values.firstOrNull() ?: "")
|
||||
.put("values", arr)
|
||||
answerLatch?.countDown()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 结束对话
|
||||
|
||||
fun markEnded(conversationId: String) {
|
||||
endedConversationId = conversationId
|
||||
notify("ended")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,295 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Termux 的软件源(apt 源)管理。
|
||||
*
|
||||
* ★ 为什么要单独做这个:Termux 官方源(packages.termux.dev)在国内**基本连不上**,
|
||||
* 表现是 `pkg install` 卡在 "Reading package lists..." 或者直接超时 ——
|
||||
* 用户会以为"内置的 Termux 坏了",其实是源的问题。
|
||||
*
|
||||
* 国内几个镜像都是完整同步的,换一下就好。做成界面而不是让用户手敲 sed:
|
||||
* 换源这件事**每次重装都要做**,而且 apt 的源格式写错一点就整个不能用。
|
||||
*/
|
||||
object TermuxMirror {
|
||||
|
||||
/**
|
||||
* 一个源。
|
||||
*
|
||||
* @param id 稳定标识(存进偏好,别用下标 —— 以后插入新源会串位)
|
||||
* @param name 显示名
|
||||
* @param host 给 termux-main 用的仓库根地址(不带 /apt/ 之后的部分)
|
||||
* @param note 副标题:速度/稳定性之类的实话
|
||||
*/
|
||||
data class Mirror(val id: String, val name: String, val host: String, val note: String)
|
||||
|
||||
/**
|
||||
* 源列表。
|
||||
*
|
||||
* ★ 顺序是有讲究的:**默认放第一个**。
|
||||
* 镜像偶尔会挂(同步中断、证书过期),所以官方源要留着能切回去。
|
||||
*/
|
||||
val MIRRORS = listOf(
|
||||
Mirror(
|
||||
"tuna", "清华 TUNA", "http://mirrors.tuna.tsinghua.edu.cn/termux",
|
||||
"国内最快最稳的一个,推荐",
|
||||
),
|
||||
Mirror(
|
||||
"ustc", "中科大 USTC", "http://mirrors.ustc.edu.cn/termux",
|
||||
"同样完整同步,教育网更快",
|
||||
),
|
||||
Mirror(
|
||||
"aliyun", "阿里云", "http://mirrors.aliyun.com/termux",
|
||||
"公网覆盖好,偶尔缺 science 仓库",
|
||||
),
|
||||
Mirror(
|
||||
"bfsu", "北外 BFSU", "http://mirrors.bfsu.edu.cn/termux",
|
||||
"清华的备份站",
|
||||
),
|
||||
Mirror(
|
||||
"official", "官方源", "http://packages.termux.dev/apt",
|
||||
"国内经常连不上,镜像挂了才用它",
|
||||
),
|
||||
)
|
||||
|
||||
/** Termux 的仓库分几个「频道」,各自一条 sources.list 行 */
|
||||
private data class Channel(val name: String, val path: String, val components: String)
|
||||
|
||||
private val CHANNELS = listOf(
|
||||
Channel("termux-main", "apt/termux-main", "stable main"),
|
||||
Channel("termux-root", "apt/termux-root", "root stable"),
|
||||
Channel("termux-x11", "apt/termux-x11", "x11 main"),
|
||||
)
|
||||
|
||||
private fun aptDir(context: Context) = File(TermuxInstaller.prefix(context), "etc/apt")
|
||||
fun sourcesFile(context: Context) = File(aptDir(context), "sources.list")
|
||||
|
||||
/** 当前用的是哪个源(认不出来就返回 null) */
|
||||
fun current(context: Context): Mirror? {
|
||||
val file = sourcesFile(context)
|
||||
if (!file.exists()) return null
|
||||
val text = try {
|
||||
file.readText()
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
return MIRRORS.firstOrNull { text.contains(it.host) }
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 让 **`pkg`** 也认这个源。
|
||||
*
|
||||
* 踩过的坑:一开始只写了 `etc/apt/sources.list`,结果 `pkg update` 说
|
||||
* "No mirror or mirror group selected",然后**把全世界几十个镜像测了一遍**,
|
||||
* 最后挑了中国连不上的俄罗斯源 —— 用户看到一屏 `bad` 加一句
|
||||
* `E: Unable to determine a suitable packaging system type`。
|
||||
*
|
||||
* 原因:**`pkg` 不看 `sources.list`**,它自己有一套(见 `bin/pkg`):
|
||||
*
|
||||
* if [ -d .../etc/termux/chosen_mirrors ] → 镜像组(取目录下所有文件)
|
||||
* elif [ -f .../etc/termux/chosen_mirrors ] → 单个镜像(**文件本身**就是路径)
|
||||
* elif [ -L ... ] → 断链,退回测全部
|
||||
* else → 没选,测全部
|
||||
*
|
||||
* bootstrap 已经带了 `etc/termux/mirrors/<地区>/<主机名>` 这些源文件,
|
||||
* 内容是 `WEIGHT= / MAIN= / ROOT= / X11=` 的 shell 片段。
|
||||
* `termux-change-repo` 的做法就是**建个符号链接**指过去。这里照做。
|
||||
*/
|
||||
private fun selectForPkg(context: Context, mirror: Mirror): String {
|
||||
val termuxDir = File(TermuxInstaller.prefix(context), "etc/termux")
|
||||
val mirrorsDir = File(termuxDir, "mirrors")
|
||||
val chosen = File(termuxDir, "chosen_mirrors")
|
||||
if (!mirrorsDir.isDirectory) return "没有 mirrors 目录,跳过"
|
||||
|
||||
val hostOnly = mirror.host
|
||||
.removePrefix("https://").removePrefix("http://")
|
||||
.substringBefore('/')
|
||||
|
||||
val target = mirrorsDir.walkTopDown()
|
||||
.filter { it.isFile && it.name == hostOnly }
|
||||
.firstOrNull()
|
||||
?: return "mirrors/ 里没有 $hostOnly"
|
||||
|
||||
try {
|
||||
chosen.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
return try {
|
||||
java.nio.file.Files.createSymbolicLink(chosen.toPath(), target.toPath())
|
||||
"链接到 ${target.name}"
|
||||
} catch (t: Throwable) {
|
||||
// 有些文件系统不给建链接 → 退回复制(pkg 读的是文件内容,效果一样)
|
||||
try {
|
||||
target.copyTo(chosen, overwrite = true)
|
||||
"复制 ${target.name}(建链接失败:${t.javaClass.simpleName})"
|
||||
} catch (t2: Throwable) {
|
||||
"失败:${t2.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 换源。
|
||||
*
|
||||
* ★ 有个坑:Termux 官方的 sources.list **里面是带注释和 deb-src 的**,
|
||||
* 直接整份覆盖会丢掉用户自己加的东西。所以这里只**替换行**:
|
||||
* 凡是以 `deb ` 开头、且指向 termux 仓库的行,按频道重写;
|
||||
* 其余(注释、第三方源)原样留着。
|
||||
*
|
||||
* @return 写进去的行数
|
||||
*/
|
||||
fun set(context: Context, mirror: Mirror): Int {
|
||||
val dir = aptDir(context)
|
||||
dir.mkdirs()
|
||||
val file = sourcesFile(context)
|
||||
|
||||
val existing = if (file.exists()) {
|
||||
try {
|
||||
file.readLines()
|
||||
} catch (_: Throwable) {
|
||||
emptyList()
|
||||
}
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
// 保留非 termux 的行(注释、用户自己加的源)
|
||||
val kept = existing.filter { line ->
|
||||
val t = line.trim()
|
||||
!t.startsWith("deb ") || !t.contains("termux")
|
||||
}
|
||||
|
||||
// ★ 只写**原本就有**的频道:termux-root / termux-x11 这两个仓库
|
||||
// 国内镜像不一定同步了,凭空写进去会让 apt update 整条报错
|
||||
// (一个源 404,apt 就整个失败,用户看到的是"换源之后更坏了")。
|
||||
// main 永远要(没有它 pkg 什么都装不了)。
|
||||
val original = existing.joinToString("\n")
|
||||
val wanted = CHANNELS.filter {
|
||||
it.name == "termux-main" || original.contains(it.name)
|
||||
}
|
||||
|
||||
val header = listOf(
|
||||
"# 由小人间 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 换源:内置终端右上角「源」按钮;也可以手动改这个文件",
|
||||
)
|
||||
val lines = wanted.map { "deb ${mirror.host}/${it.path} ${it.components}" }
|
||||
|
||||
file.writeText(
|
||||
(header + kept.filter { it.isNotBlank() } + lines).joinToString("\n") + "\n",
|
||||
)
|
||||
|
||||
// ★★ 光写 sources.list **不够** —— `pkg` 不看这个文件!
|
||||
// 它有自己的 chosen_mirrors(见 selectForPkg 的注释)。
|
||||
// 不写的话 `pkg update` 会把全世界几十个镜像挨个测一遍,
|
||||
// 最后挑中一个国内连不上的(实测挑中了俄罗斯的 mephi),
|
||||
// 用户看到一屏 `bad` 和 `E: Unable to determine a suitable packaging system type`。
|
||||
val pkgNote = try {
|
||||
selectForPkg(context, mirror)
|
||||
} catch (t: Throwable) {
|
||||
"失败:${t.message}"
|
||||
}
|
||||
android.util.Log.i(
|
||||
"DoubaoTermux",
|
||||
"换源 ${mirror.name}:sources.list ${lines.size} 条;pkg $pkgNote",
|
||||
)
|
||||
return lines.size
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 当前源要是**用不了**,自动换一个能用的。
|
||||
*
|
||||
* ## 为什么需要
|
||||
*
|
||||
* 用户实测撞到的(原话):
|
||||
*
|
||||
* E: Failed to fetch .../binary-x86_64/Packages.bz2
|
||||
* File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
* E: Some index files failed to download. They have been ignored,
|
||||
* or old ones used instead.
|
||||
*
|
||||
* 这是**镜像正在同步**时的典型症状:`InRelease` 已经是新的了,
|
||||
* 但 `Packages.bz2` 还是旧的,apt 一对哈希就拒绝。用户侧完全没辙 ——
|
||||
* 「源」按钮他按了也没用(换到的还是同一个坏源,或者他根本不知道该换)。
|
||||
*
|
||||
* 而我们**默认给的就是清华**([MIRRORS] 第一个)。镜像偶尔同步是常态,
|
||||
* 所以这不是"清华不好",是"任何单一默认值都会偶尔把用户卡死"。
|
||||
*
|
||||
* ## 做法
|
||||
*
|
||||
* 真跑一次 `apt-get update` 当探测 —— **不自己写校验逻辑**:
|
||||
*
|
||||
* · apt 的校验比我们严(哈希、时间戳、架构都对),复用它最准
|
||||
* · 反正换源之后本来就要 update,探测这一步不白花
|
||||
* · 自己写"拉 InRelease 看看"那种轻量探针**测不出这个 bug** ——
|
||||
* InRelease 恰恰是好的那一半
|
||||
*
|
||||
* 当前源能用就**什么都不做**(不打扰用户的选择)。
|
||||
* 用不了才按 [MIRRORS] 顺序往下试,换成功就记住(写 sources.list + pkg 那套)。
|
||||
*
|
||||
* @param onSwitched 换成功时回调(给界面提示用),参数是新的源
|
||||
* @return 最终可用的源;全都不可用时返回 null
|
||||
*/
|
||||
fun autoPickIfBroken(context: Context, onSwitched: ((Mirror) -> Unit)? = null): Mirror? {
|
||||
val current = current(context) ?: MIRRORS.first()
|
||||
|
||||
if (probe(context, current)) return current
|
||||
|
||||
android.util.Log.i("DoubaoTermux", "源 ${current.name} 探测失败,开始找能用的")
|
||||
for (candidate in MIRRORS) {
|
||||
if (candidate.id == current.id) continue
|
||||
if (!probe(context, candidate)) continue
|
||||
val n = set(context, candidate)
|
||||
android.util.Log.i("DoubaoTermux", "已自动切到 ${candidate.name}($n 条)")
|
||||
onSwitched?.invoke(candidate)
|
||||
return candidate
|
||||
}
|
||||
android.util.Log.w("DoubaoTermux", "所有源都探测失败,保持 ${current.name}")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测一个源能不能用:**临时**写进 sources.list 跑一次 `apt-get update`,
|
||||
* 不管成败都把原来的 sources.list 还原回去。
|
||||
*
|
||||
* ★ 必须还原:探测失败时若留着半个写入状态,用户会看到"源莫名其妙变了"。
|
||||
*/
|
||||
private fun probe(context: Context, mirror: Mirror): Boolean {
|
||||
val file = sourcesFile(context)
|
||||
val backup = try {
|
||||
if (file.exists()) file.readText() else null
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
return try {
|
||||
set(context, mirror)
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val pb = ProcessBuilder("$prefix/bin/apt-get", "update")
|
||||
.directory(TermuxInstaller.home(context))
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
// 输出必须读掉,否则管道写满会把子进程卡死(apt 输出很多)
|
||||
val sink = Thread { proc.inputStream.readBytes(); proc.errorStream.readBytes() }
|
||||
sink.isDaemon = true
|
||||
sink.start()
|
||||
val ok = proc.waitFor(PROBE_TIMEOUT_S, java.util.concurrent.TimeUnit.SECONDS) &&
|
||||
proc.exitValue() == 0
|
||||
if (!ok) proc.destroyForcibly()
|
||||
ok
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.i("DoubaoTermux", "探测 ${mirror.name} 抛异常:${t.message}")
|
||||
false
|
||||
} finally {
|
||||
try {
|
||||
if (backup != null) file.writeText(backup) else file.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测超时。apt 卡住时不能把用户等死 */
|
||||
private const val PROBE_TIMEOUT_S = 45L
|
||||
}
|
||||
@@ -39,10 +39,21 @@ object TermuxShell {
|
||||
return try {
|
||||
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
|
||||
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
|
||||
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
//
|
||||
// ★★★ 用 `childEnvMap()` 而不是 `environment()`:ProcessBuilder 起的是
|
||||
// 子进程,**默认继承整个 App 进程的环境**,而里面带着 Chaquopy 注入的
|
||||
// `PYTHONPATH`(指向 3.13 编的 .imy)。不清掉的话 Termux 的 python 3.14
|
||||
// 一起来就读到 3.13 的 encodings/__init__.pyc,魔数不符直接核心崩溃:
|
||||
// Fatal Python error: Failed to import encodings module
|
||||
// 详见 TermuxInstaller.childEnv 的注释。
|
||||
//
|
||||
// ★ `environment().putAll(...)` 这种写法是**追加**,删不掉已有的键 ——
|
||||
// 所以必须显式摘掉那几个变量(childEnvMap 做了这件事)。
|
||||
val pb = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
.directory(workdir)
|
||||
.apply { environment().putAll(TermuxInstaller.environment(context)) }
|
||||
.start()
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
|
||||
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
|
||||
val outBuf = StringBuilder()
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||
*
|
||||
* 为什么不用 `Runtime.exec` 拼一个假终端:那样跑不了 vim/top、没有颜色、没有方向键,
|
||||
* 也不是 tty,很多命令行为会不一样。Termux 这套是完整 pty + ANSI 渲染。
|
||||
*/
|
||||
class TermuxTerminal(private val context: Context) {
|
||||
|
||||
@Volatile
|
||||
var session: TerminalSession? = null
|
||||
private set
|
||||
|
||||
/** 这次是用哪种起法建起来的(写进日志,排查时一眼能看到是哪一步坏的) */
|
||||
@Volatile
|
||||
var startedWith: String = ""
|
||||
private set
|
||||
|
||||
/**
|
||||
* ★★★ 必须把 `TerminalView` 接进来,否则**屏幕永远不刷新**。
|
||||
*
|
||||
* Termux 的分工是:会话把输出解析进 emulator 的屏幕缓冲,
|
||||
* 然后通过 `TerminalSessionClient.onTextChanged()` 通知"该重画了",
|
||||
* 由 `TerminalView.onScreenUpdated()` 真正去 invalidate。
|
||||
*
|
||||
* 我这里的 `onTextChanged` 之前是**空的** —— 于是:pty 通了、bash 活着、
|
||||
* 输出也解析进缓冲了,**但屏幕一动不动**,看起来像"什么都没发生"。
|
||||
* (这个坑和 pty 那个是两回事,修好 argv 之后才暴露出来。)
|
||||
*/
|
||||
@Volatile
|
||||
var view: TerminalView? = null
|
||||
|
||||
|
||||
/** 用完了没有(决定要不要切成命令控制台) */
|
||||
val candidatesExhausted: Boolean get() = candidateIndex >= candidateCount
|
||||
|
||||
private var candidateIndex = 0
|
||||
private var candidateCount = 0
|
||||
|
||||
/**
|
||||
* ★ 诊断用:`cat` 无参数时**一直读 stdin**,不会自己退出。
|
||||
*
|
||||
* 三种环境各试一次,就能定位到底哪一段环境变量把子进程搞坏了:
|
||||
* A. 干净环境(只留 PATH=/system/bin)—— 系统二进制,测 pty 本身
|
||||
* B. 干净环境 + 我们自己的 bash —— 测 bash 在干净环境下活不活
|
||||
* C. 完整环境(现在的默认)
|
||||
*
|
||||
* 怀疑点:`LD_LIBRARY_PATH=$prefix/lib` 会**屏蔽系统库**,
|
||||
* 系统二进制(toybox 之类)因此加载失败 → exec 返回 127。
|
||||
* 定位完这几条诊断候选都删掉。
|
||||
*/
|
||||
private fun cleanEnv(): List<String> = listOf(
|
||||
"PATH=/system/bin:/system/xbin",
|
||||
"HOME=/data",
|
||||
"TERM=xterm-256color",
|
||||
"LANG=en_US.UTF-8",
|
||||
)
|
||||
|
||||
private fun candidateList(): List<Triple<String, Array<String>, Boolean>> {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val rc = TermuxInstaller.interactiveShellArgs(context)
|
||||
return listOf(
|
||||
// ⓪-A 干净环境跑 cat:能挂住 → pty 没问题
|
||||
// ⓪-B 干净环境跑我们的 bash
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ★★ 决定性实验(定位完删):让**子进程自己**把关键信息
|
||||
// **重定向到文件**(这样绕开 pty,不依赖输出通道通不通)。
|
||||
//
|
||||
// 要看的是 fd 0/1/2 到底指向什么:
|
||||
// · 指向 /dev/pts/N → 从端接上了,EIO 另有原因
|
||||
// · 指向别的东西/没有 → 从端根本没接上(那就是根因)
|
||||
// `tty` 和 `stty` 顺带验证"是不是一个真正的终端"。
|
||||
// ★ 用 **/system/bin/sh**(toybox 的 sh)而不是我们 prefix 里的:
|
||||
// 它不依赖 Termux 的库,变量最少,能干净地回答"子进程的 fd 是什么"。
|
||||
// 输出写**绝对路径**,别用 $PREFIX(那种环境里不一定会展开)。
|
||||
Triple(
|
||||
"/system/bin/sh",
|
||||
arrayOf(
|
||||
"-c",
|
||||
"{ echo '=== fds ==='; ls -l /proc/self/fd; " +
|
||||
"echo '=== tty ==='; tty; echo tty_exit=$?; " +
|
||||
"echo '=== stty ==='; stty -a 2>&1 | head -2; " +
|
||||
"echo '=== tty_nr ==='; awk '{print $7}' /proc/self/stat; " +
|
||||
"} > /data/user/0/com.doubao.lynxclone/files/childinfo.txt 2>&1; sleep 20",
|
||||
),
|
||||
true,
|
||||
),
|
||||
// ① 直接 bash + 我们自己的 rc(正常路径)
|
||||
Triple("$prefix/bin/bash", rc, true),
|
||||
// ② ★ **不带 LD_PRELOAD** 起。
|
||||
//
|
||||
// `libtermux-exec.so` 是拦 execve/open 的 .so,让二进制里写死的
|
||||
// `/data/data/com.termux/...` 在运行时被改写到我们的 prefix。
|
||||
// 但它**在 pty 里可能把 stdin 搞坏** —— 实测现象是:
|
||||
// bash 的 rc 正常跑完(那行 echo 打出来了),然后读 stdin 直接 EOF
|
||||
// 就退出(退出码 0),终端上只剩 [Process completed]。
|
||||
// 去掉它 bash 只认编译期路径(读不到 /etc/profile),
|
||||
// 但**至少能交互** —— 哪个能用用哪个。
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ③ Termux 的登录入口(有些机型上它才行;实测退出码 126)
|
||||
Triple("$prefix/bin/login", arrayOf("$prefix/bin/login", "-shell", "$prefix/bin/bash"), true),
|
||||
// ④ 最朴素的兜底:不带 preload。★ 第一个元素仍是程序名(见 interactiveShellArgs)
|
||||
Triple("$prefix/bin/bash", arrayOf("$prefix/bin/bash", "-i"), false),
|
||||
)
|
||||
}
|
||||
|
||||
private fun tryCreate(
|
||||
onTitle: (String) -> Unit,
|
||||
onExit: () -> Unit,
|
||||
): TerminalSession? {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val baseEnv = TermuxInstaller.childEnv(context)
|
||||
|
||||
val list = candidateList()
|
||||
candidateCount = list.size
|
||||
if (candidateIndex >= list.size) {
|
||||
TermuxInstaller.trace(context, "所有起法都试过了")
|
||||
return null
|
||||
}
|
||||
val (shell, args, usePreload) = list[candidateIndex]
|
||||
if (!File(shell).exists()) {
|
||||
TermuxInstaller.trace(context, "$shell 不在,跳过")
|
||||
return tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
// 前两条候选(诊断用)走**干净环境**:只留 PATH/HOME/TERM/LANG。
|
||||
// 目的就是把"环境变量把子进程搞坏"这个可能性单独拎出来验。
|
||||
val env = when {
|
||||
candidateIndex < 0 -> cleanEnv()
|
||||
usePreload -> baseEnv
|
||||
else -> baseEnv.filterNot { s: String -> s.startsWith("LD_PRELOAD=") }
|
||||
}
|
||||
startedWith = "$shell ${args.joinToString(" ")}" + if (usePreload) "" else "(不带 preload)"
|
||||
return try {
|
||||
val created = TerminalSession(shell, home, args, env.toTypedArray(), 2000, client(onTitle, onExit))
|
||||
TermuxInstaller.trace(context, "终端会话已建:$startedWith")
|
||||
session = created
|
||||
created
|
||||
} catch (t: Throwable) {
|
||||
TermuxInstaller.trace(context, "起 $shell 抛异常:${t.javaClass.simpleName}: ${t.message}")
|
||||
tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 秒退之后换下一种起法。
|
||||
*
|
||||
* 关键点:**"起法失败"不是靠异常发现的** ——
|
||||
* bash 起得来(构造函数不抛)、rc 也跑了,然后读 stdin 拿到 EOF 就退出。
|
||||
* 从代码角度看一切正常,只有"退出得太快"这个**事件**能说明它坏了。
|
||||
* 所以回退必须由秒退来驱动(TerminalScreen 在秒退回调里调这个)。
|
||||
*
|
||||
* @return 还有下一种就返回新会话;都用完了返回 null
|
||||
*/
|
||||
fun tryNextCandidate(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession? {
|
||||
candidateIndex += 1
|
||||
TermuxInstaller.trace(context, "换下一种起法(第 ${candidateIndex + 1} 种)")
|
||||
return tryCreate(onTitle, onExit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 开一个登录 shell。
|
||||
*
|
||||
* ★ 会**依次试几种起法**,哪个活下来用哪个。
|
||||
* 为什么要试:pty 的从端没接上时 shell 的 stdin 立刻 EOF,
|
||||
* bash 读不到东西**直接退出(退出码 0)** —— 现象是"终端一闪就没了",
|
||||
* 而且**看不出是哪一步坏的**。分步试 + 每步落盘就能定位。
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
candidateIndex = 0
|
||||
return tryCreate(onTitle, onExit)
|
||||
?: throw IllegalStateException("$prefixPath 下没有能用的 shell")
|
||||
}
|
||||
|
||||
private val prefixPath: String get() = TermuxInstaller.prefix(context).absolutePath
|
||||
|
||||
private fun client(onTitle: (String) -> Unit, onExit: () -> Unit) = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
// ★ 这一行就是"屏幕刷新"的开关,别删(见 view 字段的注释)
|
||||
val v = view ?: return
|
||||
v.post { v.onScreenUpdated() }
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(
|
||||
context,
|
||||
"终端会话结束,退出码=${finishedSession.exitStatus} 用的=$startedWith",
|
||||
)
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||
fun viewClient(): TerminalViewClient = object : TerminalViewClient {
|
||||
override fun onScale(scale: Float): Float = scale
|
||||
override fun onSingleTapUp(e: MotionEvent) {
|
||||
// 点一下就把软键盘叫出来,手机上最常用
|
||||
(e.source)
|
||||
}
|
||||
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = false
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = true
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) {}
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = false
|
||||
override fun readAltKey(): Boolean = false
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {}
|
||||
// TerminalViewClient 也继承了 Logger,这 7 个必须实现
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
try {
|
||||
session?.finishIfRunning()
|
||||
} catch (t: Throwable) {
|
||||
Log.w("DoubaoTermux", "关闭会话失败", t)
|
||||
}
|
||||
session = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 给 Compose 的 AndroidView 用:把 view 绑上会话 */
|
||||
fun bindSession(view: TerminalView, terminal: TermuxTerminal, onTitle: (String) -> Unit, onExit: () -> Unit) {
|
||||
val s = terminal.session ?: terminal.createSession(onTitle, onExit)
|
||||
if (view.currentSession !== s) {
|
||||
view.attachSession(s)
|
||||
}
|
||||
view.requestFocus()
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.foundation.Image
|
||||
|
||||
/*
|
||||
* 智能体的完整编辑界面(需求 2.5 / 3.1 / 3.3 / 3.5 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## ★ 为什么是全屏,而不是沿用那个弹窗
|
||||
*
|
||||
* 字段从 8 个涨到了二十多个(外观四件套、模型引用、世界观、限额、技能……)。
|
||||
* AGENTS.md 里那张表写得很清楚:「**列表 / 多组配置 / 任何要滚动的 → 独立全屏界面**」,
|
||||
* 而"节点配置 NodeConfigDialog → 全屏(字段很多)"到现在还挂在待办清单上 ——
|
||||
* 这次不再欠新账。
|
||||
*
|
||||
* ## 三处会让人困惑的地方,界面上直接说清
|
||||
*
|
||||
* ① **介绍(description)和一句话介绍(tagline)不是一回事**:
|
||||
* 前者只在选择界面的介绍框里显示,后者是列表里的摘要。
|
||||
* ② **绑了世界观 = 记忆变成共享的**(需求 3.6)—— 不写清楚,
|
||||
* 用户会以为"我给 A 记的东西怎么 B 也知道"。
|
||||
* ③ **限额 0 就是无限制**,不是"限额为 0"。
|
||||
*/
|
||||
|
||||
/** 除立绘以外的三件套(立绘是**五档**的,单独处理) */
|
||||
private val ASSET_SLOTS = listOf(
|
||||
Triple("back", "背景图", "铺在展示区最底层;缺了用内置默认背景"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区;缺了用简单方框"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本;缺了跟主体边框一个样式"),
|
||||
)
|
||||
|
||||
/** 立绘五档各档的说明 —— 每档都要写清"缺了会退回哪张",不然用户不知道该传几张 */
|
||||
private fun portraitHint(preset: String): String = when (preset) {
|
||||
"喜" -> "高兴时用这张;缺了用「平常」那张"
|
||||
"怒" -> "发怒时用这张;缺了用「平常」那张"
|
||||
"哀" -> "悲伤时用这张;缺了用「平常」那张"
|
||||
"死亡" -> "死亡时用这张(那时不能对话);缺了用「平常」那张"
|
||||
else -> "其他档都缺时兜底用这张;连它也没有就用内置默认人物"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AgentEditScreen(
|
||||
vm: AppViewModel,
|
||||
initial: Agent?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
val isNew = initial == null
|
||||
var draft by remember { mutableStateOf(initial ?: Agent(avatar = "custom")) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var promptDraft by remember { mutableStateOf(draft.systemPrompt) }
|
||||
var limitDraft by remember { mutableStateOf(
|
||||
if (draft.tokenLimit > 0) draft.tokenLimit.toInt().toString() else ""
|
||||
) }
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// 选一张外观图 → 读字节 → base64 → 立刻上传
|
||||
// ★ 不等"保存":图片可能好几 MB,混在保存里用户会以为卡死了
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
|
||||
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
|
||||
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
|
||||
}
|
||||
|
||||
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
|
||||
// ★ 包里**只有**名字/介绍/提示词/外观四件套 —— 模型引用、世界观绑定、限额
|
||||
// 一律不进包(需求 2.5 的"包的边界约定"),更不会有 API Key。
|
||||
var pendingZip by remember { mutableStateOf<String?>(null) }
|
||||
val saveZip = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.CreateDocument("application/zip"),
|
||||
) { uri ->
|
||||
val data = pendingZip
|
||||
pendingZip = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)
|
||||
?.use { it.write(Base64.decode(data, Base64.DEFAULT)) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (isNew) "新建智能体" else "编辑智能体",
|
||||
subtitle = if (isNew) "保存后可以加外观图片" else draft.name,
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
vm.saveAgentFull(
|
||||
draft.copy(systemPrompt = promptDraft, tokenLimit = limitDraft.toDoubleOrNull() ?: 0.0),
|
||||
isNew,
|
||||
) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
// 编辑中的智能体可能是**别处刚改过**的(比如刚上传完图片)——
|
||||
// vm.agents 里的那份才是最新的,这里同步一下,否则预览是旧的
|
||||
val fresh = vm.agents.firstOrNull { it.id == draft.id }
|
||||
if (!isNew && fresh != null && fresh.image != draft.image) {
|
||||
draft = draft.copy(image = fresh.image)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
|
||||
/* ---------------- 基本信息 ---------------- */
|
||||
SectionLabel("基本信息")
|
||||
Card {
|
||||
LabeledField("名字", draft.name, "比如:玄辰") { draft = draft.copy(name = it) }
|
||||
Spacer(Modifier.height(10.dp))
|
||||
LabeledField("一句话介绍", draft.greeting, "列表里的摘要,比如:仙门大师兄") {
|
||||
draft = draft.copy(greeting = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("显示在智能体列表里。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
LabeledField("介绍文案", draft.description, "选择界面右边那个介绍框里显示的话") {
|
||||
draft = draft.copy(description = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("★ 和上面那条不一样:这条只在选择智能体时的介绍框里显示。留空就只显示名字。")
|
||||
}
|
||||
|
||||
/* ---------------- 外观 ---------------- */
|
||||
SectionLabel("外观")
|
||||
Card {
|
||||
if (isNew) {
|
||||
// ★ 图片要落到"这个智能体的资源目录"里,所以必须先在库里有一条记录
|
||||
Text(
|
||||
"先点右上角「保存」把智能体建出来,再回来加外观图片。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// ---- 立绘:五档(v1.2 需求 2.5 / 2.6)----
|
||||
//
|
||||
// ★ 槽位名带档位(`front:喜`),内核按这个落到不同文件 ——
|
||||
// 五档存成一张的话会互相覆盖。
|
||||
Text("角色立绘(按情绪换)", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Hint(
|
||||
"情绪的五档各自一张图,缺哪档就退回「平常」那张。" +
|
||||
"现在显示的是「${draft.image.portrait.ifBlank { "内置默认人物" }}」那张。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (preset in PRESETS) {
|
||||
AssetRow(
|
||||
title = preset,
|
||||
desc = portraitHint(preset),
|
||||
path = draft.image.slot(preset),
|
||||
onPick = {
|
||||
pendingSlot = "front:$preset"
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// ---- 其余三件套 ----
|
||||
Text("其他三件套", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for ((key, title, desc) in ASSET_SLOTS) {
|
||||
AssetRow(
|
||||
title = title,
|
||||
desc = desc,
|
||||
path = draft.image.pathOf(key),
|
||||
onPick = { pendingSlot = key; pickImage.launch(arrayOf("image/*")) },
|
||||
onClear = { vm.uploadAgentAsset(draft.id, key, "", "") },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("支持 PNG / JPG / GIF(动图会动)。SVG 也能显示。缺哪张就用内置默认。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 人设 ---------------- */
|
||||
SectionLabel("人设(系统提示词)")
|
||||
Card {
|
||||
OutlinedTextField(
|
||||
value = promptDraft,
|
||||
onValueChange = { promptDraft = it },
|
||||
placeholder = { Text("你是一个……", fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("留空就用全局系统提示词。记忆、情绪、世界观、技能会自动拼在这后面,不用你自己写。")
|
||||
}
|
||||
|
||||
/* ---------------- 模型 ---------------- */
|
||||
SectionLabel("模型")
|
||||
Card {
|
||||
val entries = vm.state.modelEntries
|
||||
if (entries.isEmpty()) {
|
||||
Hint("还没有全局模型。去「设置 → 超时」上面的「全局模型」里加一个,就能在这里引用它。")
|
||||
} else {
|
||||
ChipRow(
|
||||
options = listOf("" to "跟随全局") + entries.map { it.id to it.name },
|
||||
active = draft.modelId,
|
||||
onPick = { draft = draft.copy(modelId = it) },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("选了它就固定用那个模型;「跟随全局」= 用设置里当前选的那个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 世界观 ---------------- */
|
||||
SectionLabel("世界观")
|
||||
Card {
|
||||
val worlds = vm.state.worldviews
|
||||
ChipRow(
|
||||
options = listOf("" to "不绑定") + worlds.map { it.id to it.name },
|
||||
active = draft.worldviewId,
|
||||
onPick = { draft = draft.copy(worldviewId = it) },
|
||||
)
|
||||
if (draft.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// ★ 选世界观的时候就要看到"已经有谁在"(用户问的"哪些智能体绑了它")。
|
||||
// 这是**决策依据**:如果里面已经有三个角色,加进去意味着
|
||||
// 四份记忆混在一个空间里;如果只有它一个,那基本等于私有。
|
||||
val wv = vm.state.worldviews.firstOrNull { it.id == draft.worldviewId }
|
||||
val others = (wv?.agents ?: emptyList()).filter { it.id != draft.id }
|
||||
Text(
|
||||
if (others.isEmpty()) "目前只有它用这个世界观(记忆实际上还是自己一份)"
|
||||
else "已经有 ${others.size} 个智能体在用:${others.joinToString("、") { it.name }}",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (others.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定," +
|
||||
"而且记忆会和上面这些智能体共享(它们也能看到并写入同一个空间," +
|
||||
"但只能改自己写的那几条)。\n" +
|
||||
"情绪仍然是私有的(不会共享)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
if (worlds.isEmpty()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("还没有世界观。在「更多功能 → 世界观」里新建或导入一个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 能力 ---------------- */
|
||||
SectionLabel("能力")
|
||||
Card {
|
||||
ToggleRow(
|
||||
title = "情绪感知",
|
||||
sub = "能看到同世界观其他智能体当前的情绪(只读,单向)",
|
||||
checked = draft.emotionEnabled,
|
||||
onChange = { draft = draft.copy(emotionEnabled = it) },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("Token 限额", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = limitDraft,
|
||||
onValueChange = { s -> limitDraft = s.filter { it.isDigit() }.take(9) },
|
||||
placeholder = { Text("留空 = 无限制", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
// ★ v1.2 §6.1:拉起其他智能体的方式。
|
||||
// 内核(`agent_tools.invite_agent`)早就按这个字段分流了,
|
||||
// 但界面上一直**没有入口** —— 于是 `confirm` 那一档
|
||||
// 用户永远打不开,等于需求里这个选项不存在。
|
||||
ToggleRow(
|
||||
title = "拉人要先问我",
|
||||
sub = "打开后,AI 想邀请别的智能体进群时会先问一句;" +
|
||||
"关闭则直接拉进来(都会在正文里说一声)。",
|
||||
checked = draft.inviteMode == "confirm",
|
||||
onChange = { draft = draft.copy(inviteMode = if (it) "confirm" else "silent") },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
SectionLabel("技能(Skill)")
|
||||
Card {
|
||||
val all = vm.state.skills
|
||||
if (all.isEmpty()) {
|
||||
Hint("还没有自定义 Skill。内置的记忆/情绪/用量手册默认就生效,不用在这里选。")
|
||||
} else {
|
||||
for (s in all) {
|
||||
val on = s.id in draft.skillIds
|
||||
ToggleRow(
|
||||
title = s.name.ifBlank { "未命名 Skill" },
|
||||
sub = s.content.lineSequence().firstOrNull()?.take(60) ?: "",
|
||||
checked = on,
|
||||
onChange = { v ->
|
||||
draft = draft.copy(
|
||||
// ★ 按**勾选顺序**排:需求 3.7 说"按绑定顺序拼接注入",
|
||||
// 顺序会影响模型读到的先后,所以不能是 Set
|
||||
skillIds = if (v) draft.skillIds + s.id
|
||||
else draft.skillIds.filter { it != s.id },
|
||||
)
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("勾选顺序就是注入顺序(先勾的在前)。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 语音 ---------------- */
|
||||
SectionLabel("语音")
|
||||
Card {
|
||||
// ★ 这里**只选音色**,不选引擎 —— 引擎是"用哪套语音服务",
|
||||
// 属于全局设置(换引擎时音色名整套都不一样,混在一个界面里
|
||||
// 必然出现"选了引擎、音色还是上一家的"这种状态)。
|
||||
Hint("引擎跟随全局(在「设置 → 语音」里换)。想给这个智能体一个不同的嗓音,就在下面选音色。")
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val engine = vm.state.speech.ttsEngine
|
||||
VoicePickerInline(
|
||||
engine = engine,
|
||||
voices = vm.state.speechVoices[engine] ?: emptyList(),
|
||||
voicesAll = vm.state.speechVoicesAll[engine] ?: emptyList(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 状态数值 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
BigAction("看它记住了什么") { vm.openMemories(draft.id) }
|
||||
BigAction("看它用了多少") { vm.openTokenUsage(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★★ 「它的状态」这个标题下面**原来只有记忆和用量两个按钮** ——
|
||||
// 状态数值页自己写着"三个入口:聊天页状态栏 / 智能体编辑的
|
||||
// 它的状态 / 群成员的状态",而中间那个**从来没做出来**。
|
||||
// 结果是:用户在群里能点到「状态」,在智能体编辑页却点不到。
|
||||
BigAction("看它的数值和状态") { vm.openStats(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp)) {
|
||||
Hint(
|
||||
"记忆是 AI 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。数值和状态由它绑定的世界观上的" +
|
||||
"「数值状态包」定义。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 删除 ---------------- */
|
||||
if (!isNew) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
RowAction("导出这个智能体(.zip)") {
|
||||
vm.exportPackage("agents", draft.id) { content, _ -> pendingZip = content }
|
||||
}
|
||||
Text(
|
||||
"包里只有名字、介绍、提示词和外观图片;模型、世界观、限额不进包,更没有 API Key。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
if (pendingZip != null) {
|
||||
LaunchedEffect(pendingZip) {
|
||||
saveZip.launch("${draft.name.ifBlank { "agent" }}.zip")
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isNew && !draft.builtin) {
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) {
|
||||
RowAction("删除这个智能体", danger = true) {
|
||||
vm.deleteAgentFull(draft.id) { onDone() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun AgentImage.pathOf(key: String): String = when (key) {
|
||||
// v1.2:立绘是五档表,编辑界面的**预览**用内核算好的那张
|
||||
// (其他三件套还是单张)
|
||||
"front" -> portrait
|
||||
"back" -> back
|
||||
"border-main" -> borderMain
|
||||
else -> borderInfo
|
||||
}
|
||||
|
||||
// ★ `Card` / `Hint` 已经挪到 DoubaoUi.kt 变成公共组件了 ——
|
||||
// 原来它们是这个文件私有的,于是别的界面想用只能复制一份
|
||||
// ([群成员] 就要用),而"同一段逻辑抄两份"是这个仓库的老毛病。
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
private fun BigAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LabeledField(
|
||||
label: String,
|
||||
value: String,
|
||||
placeholder: String,
|
||||
onChange: (String) -> Unit,
|
||||
) {
|
||||
Text(label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onChange,
|
||||
placeholder = { Text(placeholder, fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChipRow(
|
||||
options: List<Pair<String, String>>,
|
||||
active: String,
|
||||
onPick: (String) -> Unit,
|
||||
) {
|
||||
Column {
|
||||
for (row in options.chunked(3)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 3.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
for ((key, label) in row) {
|
||||
val on = key == active
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { onPick(key) }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToggleRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
checked: Boolean,
|
||||
onChange: (Boolean) -> Unit,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
if (sub.isNotBlank()) {
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 15.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (checked) Doubao.Blue else Doubao.Border)
|
||||
.clickable { onChange(!checked) },
|
||||
contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 一个外观槽位:小预览 + 标题说明 + 选图 / 清除 */
|
||||
@Composable
|
||||
private fun AssetRow(
|
||||
title: String,
|
||||
desc: String,
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(52.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (path.isBlank()) {
|
||||
if (showDefaultPerson) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
} else {
|
||||
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
} else {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, lineHeight = 14.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
RowAction("选择") { onPick() }
|
||||
if (path.isNotBlank()) RowAction("清除", danger = true) { onClear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
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.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/*
|
||||
* 智能体选择界面(需求第二章)。
|
||||
*
|
||||
* ## 布局(需求 2.1)
|
||||
*
|
||||
* 左侧:智能体列表(纵向、当前项高亮)
|
||||
* 右侧:角色展示区,**四层叠加**:
|
||||
* ① 背景图(铺满)② 主体边框(框住展示区)③ 角色图(居中)④ 介绍边框(围住介绍文本)
|
||||
*
|
||||
* ## 切换动画(需求 2.3,定稿参数)
|
||||
*
|
||||
* ① 旧角色图渐出 + 侧移 0.3s ease-in
|
||||
* ② 间隔 0.5s
|
||||
* ③ 边框/背景/介绍 滑出滑入 0.4s ease-in-out
|
||||
* ④ 新角色图渐入 + 侧移到位 0.3s ease-out
|
||||
* 合计约 1.5s。
|
||||
*
|
||||
* **方向**:目标在当前**之下**(列表靠后)→ 向左切换;**之上** → 向右。
|
||||
*
|
||||
* **连续快速切换立即打断**:靠 `LaunchedEffect(选中的 id)` —— 换目标时
|
||||
* 上一个协程直接被取消,而 `Animatable` 会**停在当前值**,所以新动画
|
||||
* 是从眼前的画面接着走的,不会闪回。这正是需求要的"从当前视觉状态
|
||||
* 直接过渡到最新目标,不做排队"。
|
||||
*
|
||||
* ## ★ 默认资源回退(需求 2.6)
|
||||
*
|
||||
* 角色图缺 → 内置默认人物;背景缺 → 内置默认背景;边框缺 → **简单方框**。
|
||||
* 回退优先级:`smartInfo.json 指定 → 包内同名 → 内置默认`。
|
||||
* 前两级在内核导入时就落定了(存的是绝对路径),所以这里只做最后一级。
|
||||
*
|
||||
* ★ "任何智能体至少能以「默认人物 + 默认背景 + 方框边框」正常展示" ——
|
||||
* 所以**每个槽位都必须有兜底**,不能出现空白展示区。
|
||||
*/
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 动画参数(需求 2.3:所有时长收进全局配置) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* ★ 下面这四个是**兜底默认值**,真正生效的值从全局配置里读
|
||||
* (设置 →「超时」→「动画」那一组,内核 `timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 为什么不在这里写死:需求 2.3 明确要求"所有时长与缓动数值收进全局配置"。
|
||||
* 用户嫌 1.5 秒的切换太慢时,改「中间留白」就能缩到 1.0 秒。
|
||||
*
|
||||
* 复用"超时"那套数值体系(而不是在 settings 里再开一个 agentAnim 对象)
|
||||
* 的理由写在 timeouts.py 那一段注释里:再造一套就是第二份要同步的东西。
|
||||
*/
|
||||
private fun animMs(key: String, fallback: Int): Int {
|
||||
val sec = com.doubao.lynxclone.data.AppTimeouts.seconds(key, fallback / 1000.0)
|
||||
// 0 是合法的(「中间留白」调成 0 = 不停顿),所以不能拿 0 当"没配"
|
||||
return if (sec.isNaN() || sec < 0) fallback else (sec * 1000).toInt()
|
||||
}
|
||||
|
||||
private const val DEF_FRONT_OUT = 300 // ① 旧角色图出
|
||||
private const val DEF_GAP = 500 // ② 间隔
|
||||
private const val DEF_FRAME = 400 // ③ 边框/背景/介绍(滑出 + 滑入各一半)
|
||||
private const val DEF_FRONT_IN = 300 // ④ 新角色图进
|
||||
|
||||
/** 侧移幅度占展示区宽度的比例。需求只说"侧移",幅度大了像翻页、小了看不出来 */
|
||||
private const val SHIFT = 0.10f
|
||||
|
||||
@Composable
|
||||
fun AgentSelectScreen(
|
||||
vm: AppViewModel,
|
||||
agents: List<Agent>,
|
||||
activeId: String,
|
||||
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
|
||||
onEnter: (Agent) -> Unit,
|
||||
/** 「更多」→ Token 用量详情(需求 2.4) */
|
||||
onMore: (Agent) -> Unit,
|
||||
/** 「记忆」→ 看它记住了什么(记忆管理界面的主入口) */
|
||||
onMemories: (Agent) -> Unit,
|
||||
/** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */
|
||||
onManage: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
if (agents.isEmpty()) {
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg()), verticalArrangement = Arrangement.Center) {
|
||||
Text("还没有智能体", Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = doubaoText())
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("点右上角「管理」新建或导入一个", Modifier.fillMaxWidth(),
|
||||
textAlign = TextAlign.Center, fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TopAction("去管理", onClick = onManage)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val startIndex = agents.indexOfFirst { it.id == activeId }.coerceAtLeast(0)
|
||||
var picked by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
// `shown` 是**画面上正在显示**的那个;picked 变了之后要等动画走到第③阶段才换它
|
||||
var shown by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
val shownAgent = agents.getOrNull(shown) ?: agents.first()
|
||||
val pickedAgent = agents.getOrNull(picked) ?: agents.first()
|
||||
|
||||
// ★ 进这一页就拉一遍所有智能体的数值/状态(卡片上要显示)。
|
||||
// 失败就保持上一份 —— 卡片上少几个数字不该报错打扰用户。
|
||||
LaunchedEffect(Unit) { vm.refreshAllStats() }
|
||||
|
||||
val frontAlpha = remember { Animatable(1f) }
|
||||
val frontShift = remember { Animatable(0f) }
|
||||
val frameAlpha = remember { Animatable(1f) }
|
||||
val frameShift = remember { Animatable(0f) }
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
// 每次重组都读一遍全局配置(用户在设置里改完回来,下一次切换就是新时长)
|
||||
val tFrontOut = animMs("agentAnim.frontOut", DEF_FRONT_OUT)
|
||||
val tGap = animMs("agentAnim.gap", DEF_GAP)
|
||||
val tFrame = animMs("agentAnim.frame", DEF_FRAME)
|
||||
val tFrontIn = animMs("agentAnim.frontIn", DEF_FRONT_IN)
|
||||
|
||||
LaunchedEffect(picked, agents.size) {
|
||||
if (picked == shown) return@LaunchedEffect
|
||||
// 目标在列表靠后 = 向左切换(新内容从右边进来)
|
||||
val dir = if (picked > shown) 1f else -1f
|
||||
|
||||
// ① 旧角色图渐出 + 侧移
|
||||
launch { frontAlpha.animateTo(0f, tween(tFrontOut, easing = FastOutSlowInEasing)) }
|
||||
frontShift.animateTo(-dir * SHIFT, tween(tFrontOut, easing = FastOutSlowInEasing))
|
||||
|
||||
// ② 间隔(需求明确定义了这一段留白;调成 0 就跳过)
|
||||
if (tGap > 0) delay(tGap.toLong())
|
||||
|
||||
// ③ 边框 / 背景 / 介绍:滑出 → 换数据 → 滑入
|
||||
val half = (tFrame / 2).coerceAtLeast(1)
|
||||
launch { frameAlpha.animateTo(0f, tween(half, easing = FastOutSlowInEasing)) }
|
||||
frameShift.animateTo(-dir * SHIFT, tween(half, easing = FastOutSlowInEasing))
|
||||
shown = picked
|
||||
launch { frameAlpha.animateTo(1f, tween(half, easing = LinearOutSlowInEasing)) }
|
||||
frameShift.animateTo(0f, tween(half, easing = LinearOutSlowInEasing))
|
||||
|
||||
// ④ 新角色图渐入 + 侧移到位
|
||||
frontShift.snapTo(dir * SHIFT)
|
||||
launch { frontAlpha.animateTo(1f, tween(tFrontIn, easing = LinearOutSlowInEasing)) }
|
||||
frontShift.animateTo(0f, tween(tFrontIn, easing = LinearOutSlowInEasing))
|
||||
}
|
||||
|
||||
// 选中的那项滚进视野(列表长了之后不滚的话用户看不到自己选了谁)
|
||||
LaunchedEffect(picked) {
|
||||
runCatching { listState.animateScrollToItem(picked) }
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
// ---------------- 顶栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"← 返回",
|
||||
fontSize = 14.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onBack() }.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
"选择智能体",
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
TopTextAction("管理", onClick = onManage)
|
||||
}
|
||||
|
||||
// ---------------- 展示区 ----------------
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(horizontal = 8.dp)
|
||||
.clip(RoundedCornerShape(18.dp)),
|
||||
) {
|
||||
// ① 背景图(最底层,铺满)—— 缺就用内置默认背景
|
||||
ArtworkFill(shownAgent.image.back, R.drawable.agent_default_background)
|
||||
|
||||
// ② 左侧列表(浮在背景上)
|
||||
AgentList(
|
||||
agents = agents,
|
||||
picked = picked,
|
||||
onPick = { picked = it },
|
||||
state = listState,
|
||||
// ★★ 用户要求「数字界面在智能体卡片里展示」——
|
||||
// 卡片上直接显示这个角色的数值和状态,不用点进去才看得到。
|
||||
stats = vm.allStats,
|
||||
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
|
||||
)
|
||||
|
||||
// ③ 角色图(居中)。★ 它和右侧的边框/介绍一起跟着 frameShift 动
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = 96.dp, end = 10.dp, top = 10.dp, bottom = 10.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.offset(x = (frameShift.value * 180).dp)
|
||||
.alpha(frameAlpha.value),
|
||||
) {
|
||||
// ③-1 角色图
|
||||
Box(
|
||||
Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp),
|
||||
) {
|
||||
ArtworkFill(
|
||||
shownAgent.image.portrait,
|
||||
R.drawable.agent_default_character,
|
||||
alpha = frontAlpha.value,
|
||||
scale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
|
||||
// ③-2 介绍边框 + 介绍文本(需求 2.1 的第 4 层)
|
||||
IntroCard(
|
||||
agent = shownAgent,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(end = 6.dp, bottom = 10.dp)
|
||||
.width(200.dp),
|
||||
)
|
||||
|
||||
// ③-3 主体边框(画在最上层,纯装饰)
|
||||
MainBorder(shownAgent.image.borderMain)
|
||||
}
|
||||
}
|
||||
|
||||
// ④ 「更多」按钮(需求 2.4:圆形、竖排三点、在角色图附近)→ Token 用量
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 10.dp, end = 12.dp)
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color(0xCC1B2430))
|
||||
.clickable { onMore(shownAgent) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.MoreVert,
|
||||
contentDescription = "用量详情",
|
||||
tint = Color(0xFFE8EAED),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 底部:进对话 / 看记忆 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★「记忆」和「开始对话」并排:进对话之前顺手看一眼它记住了什么。
|
||||
// 记忆是这个功能里最需要"用户能看见"的东西 —— AI 会记错
|
||||
// (把"喜欢猫"记成"讨厌猫"很常见),看见了才能改。
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { onMemories(pickedAgent) }
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("记忆", fontSize = 15.sp, color = doubaoText())
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(
|
||||
Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))),
|
||||
)
|
||||
.clickable { onEnter(pickedAgent) }
|
||||
.padding(vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"开始对话",
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color.White,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 四层的具体画法 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** 铺满一层图;没有就用内置默认(需求 2.6 的最后一级回退) */
|
||||
@Composable
|
||||
private fun ArtworkFill(
|
||||
path: String,
|
||||
fallbackRes: Int,
|
||||
alpha: Float = 1f,
|
||||
scale: ContentScale = ContentScale.Crop,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().alpha(alpha)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
fallback = {
|
||||
// ★ 内置默认图:**必须画出来**,不能是空白 ——
|
||||
// 需求原话"任何智能体至少能以默认人物+默认背景+方框边框正常展示"
|
||||
Image(
|
||||
painter = painterResource(fallbackRes),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 主体边框。缺的时候用**简单方框**(纯色细线矩形)兜底 */
|
||||
@Composable
|
||||
private fun MainBorder(path: String) {
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
if (canShowImage(path)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.FillBounds,
|
||||
fallback = { SimpleFrame(shape) },
|
||||
)
|
||||
} else {
|
||||
SimpleFrame(shape)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SimpleFrame(shape: RoundedCornerShape) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.border(1.dp, Doubao.Blue.copy(alpha = 0.45f), shape),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 介绍卡片(需求 2.1 的"介绍边框 + 介绍文本")。
|
||||
*
|
||||
* 文本来自 `description`;缺失时**只显示智能体名**(需求原文)。
|
||||
*/
|
||||
@Composable
|
||||
private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Color(0xE6FFFDF5))
|
||||
.border(1.dp, Color(0x66B9A46A), RoundedCornerShape(14.dp))
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
agent.name,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color(0xFF2A2419),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val desc = agent.description.trim().ifBlank { agent.greeting.trim() }
|
||||
if (desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
desc,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF4A4232),
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字 + **数值/状态**;当前项高亮 */
|
||||
@Composable
|
||||
private fun AgentList(
|
||||
agents: List<Agent>,
|
||||
picked: Int,
|
||||
onPick: (Int) -> Unit,
|
||||
state: androidx.compose.foundation.lazy.LazyListState,
|
||||
/** agentId → 它的数值/状态(只有挂了规则包的智能体在里面) */
|
||||
stats: Map<String, com.doubao.lynxclone.data.AgentStats>,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
itemsIndexed(agents) { index, agent ->
|
||||
val on = index == picked
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (on) Color(0xCC2B7BFF) else Color(0x99101820))
|
||||
.border(
|
||||
width = if (on) 1.5.dp else 0.5.dp,
|
||||
color = if (on) Color(0xFFFFE08A) else Color(0x33FFFFFF),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.clickable { onPick(index) }
|
||||
.padding(4.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
// 缩略图:也用角色图(缺就默认人物)—— 和右侧是同一套回退。
|
||||
// ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会
|
||||
// 裁出"腰到大腿",一排缩略图全是裤子
|
||||
AssetImage(
|
||||
path = agent.image.portrait,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
fallback = {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
agent.name.ifBlank { "未命名" },
|
||||
fontSize = 11.sp,
|
||||
color = Color.White,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
|
||||
// ★★ 数值和状态(用户要求「数字界面在智能体卡片里展示」)。
|
||||
//
|
||||
// 卡片只有 96dp 宽,所以这里**极简**:
|
||||
// · 第一条数值 + 迷你进度条(一眼看出高低)
|
||||
// · 有状态就再压一行名字(圆点 + 名字,多了就 N 个点)
|
||||
//
|
||||
// ★ 只显示**第一条**数值是有意的:卡片上放大而全的数值表
|
||||
// 等于把 [状态数值] 页塞进 96dp,谁也看不清;
|
||||
// 想细看就点进去。这里要回答的只是"这个角色现在什么情况"。
|
||||
val st = stats[agent.id]
|
||||
if (st != null && st.stats.isNotEmpty()) {
|
||||
val main = st.stats.first()
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"${main.name} ${fmtNum(main.value)}",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFFFFE08A),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
// 迷你进度条:3dp 高,一眼看出比例,不占地方
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(3.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(main.ratio())
|
||||
.height(3.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Color(0xFFFFE08A)),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (st != null && st.statuses.isNotEmpty()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
st.statuses.joinToString(" · ") { it.name },
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8FE0A0),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.StatValue
|
||||
import com.doubao.lynxclone.data.StatusInstance
|
||||
|
||||
/**
|
||||
* [状态数值](v1.2 §3.10 数值 / §3.11 状态)。
|
||||
*
|
||||
* ## 三个入口共用这一个界面
|
||||
*
|
||||
* 需求 §6.1 指定的三个入口:**聊天页状态栏** / **智能体编辑的"它的状态"** /
|
||||
* **群成员的「状态」按钮**。三处都调 `vm.openStats(agentId)`。
|
||||
*
|
||||
* ★ 只写一个界面是有意的:三个入口各写一份的话,"数值怎么显示、
|
||||
* 能不能改、状态剩几轮怎么标"这三件事会各有一套说法 ——
|
||||
* 而这个仓库里"同一逻辑抄两份"已经反复出现过。
|
||||
*
|
||||
* ## 用户能直接改数值,AI 不能
|
||||
*
|
||||
* AI 的 `change_stat` 只能申请**增量**,还要过脚本裁决(§3.10)。
|
||||
* 用户是规则的主人 —— 点一下就能直接设成任何值。
|
||||
* 但内核照样会 clamp 到 `[min,max]`:超出范围的值会让进度条和区间注入
|
||||
* 全都错位。所以**回来之后要以返回值刷新**,不能乐观地先用自己填的。
|
||||
*/
|
||||
@Composable
|
||||
fun AgentStatsScreen(
|
||||
vm: AppViewModel,
|
||||
agentId: String,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val stats = vm.agentStats
|
||||
var editing by remember { mutableStateOf("") }
|
||||
var input by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "状态数值",
|
||||
subtitle = stats?.name?.takeIf { it.isNotBlank() } ?: "读不出来",
|
||||
onBack = onBack,
|
||||
) {
|
||||
if (stats == null) {
|
||||
Hint("正在读……")
|
||||
return@FullScreen
|
||||
}
|
||||
if (stats.rulePackId.isBlank()) {
|
||||
// 没挂规则包就没有数值系统 —— 如实说清楚,别让用户以为是加载失败
|
||||
Hint(
|
||||
"这个智能体还没有数值系统。\n\n" +
|
||||
"数值和状态由「数值状态包」定义 —— 去 资源 → 规则包 " +
|
||||
"建一个(或导入一个),再把它挂到智能体所在的世界观上。",
|
||||
)
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("数值")
|
||||
Card {
|
||||
if (stats.stats.isEmpty()) {
|
||||
Hint("这个规则包里没有数值。")
|
||||
}
|
||||
for (s in stats.stats) {
|
||||
StatRow(
|
||||
stat = s,
|
||||
editing = editing == s.name,
|
||||
input = input,
|
||||
onInput = { input = it },
|
||||
onStartEdit = { editing = s.name; input = fmtNum(s.value) },
|
||||
onCancel = { editing = "" },
|
||||
onCommit = {
|
||||
vm.setStatDirect(s.name, input.toDoubleOrNull() ?: s.value)
|
||||
editing = ""
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (stats.rulePackName.isNotBlank()) {
|
||||
Hint("来自规则包「${stats.rulePackName}」。")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态")
|
||||
Card {
|
||||
if (stats.statuses.isEmpty()) {
|
||||
Hint("身上没有状态。")
|
||||
}
|
||||
for (st in stats.statuses) {
|
||||
// ★ 每条状态都能**清掉**。AI 手里只有 `grant_status`(只能加),
|
||||
// 没有任何工具能移除状态 —— 所以这个按钮是唯一的出口:
|
||||
// `persistent` 状态不会自己过期,没有它就永远下不来。
|
||||
StatusRow(st, onDrop = { vm.dropStatusDirect(st.name) })
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"定时状态每参与一轮减 1,归零就消失;持久状态不会自己过期。" +
|
||||
"状态提示词会被注入到它的系统提示里。",
|
||||
)
|
||||
|
||||
// ---- 手动挂一个状态 ----
|
||||
//
|
||||
// 只在包里有**还没挂上**的状态定义时才显示 —— 全都挂上了就没东西可加了,
|
||||
// 摆一排点不动的按钮反而让人以为坏了。
|
||||
val notOn = stats.statusDefs.filter { d -> stats.statuses.none { it.name == d.name } }
|
||||
if (notOn.isNotEmpty()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("加一个")
|
||||
Card {
|
||||
Hint("AI 只能给自己加状态,你也可以直接挂 —— 用来测效果或者补剧情。")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for (d in notOn) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth()
|
||||
.clickable { vm.addStatusDirect(d.name, d.turns) }
|
||||
.padding(vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(d.name, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
if (d.isPersistent) "持久 · 不会自己过期"
|
||||
else "定时 · ${d.turns} 轮后消失",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("挂上") { vm.addStatusDirect(d.name, d.turns) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatRow(
|
||||
stat: StatValue,
|
||||
editing: Boolean,
|
||||
input: String,
|
||||
onInput: (String) -> Unit,
|
||||
onStartEdit: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
onCommit: () -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stat.name, fontSize = 13.sp, color = doubaoText(), modifier = Modifier.weight(1f))
|
||||
if (stat.shared) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag("全世界观共用")
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
if (editing) {
|
||||
// 直接设值 —— 用户主权。★ 就地在行内变成输入框,不再压一层
|
||||
// 对话框(AGENTS.md:一次输入用弹窗也行,但这里已经有上下文,
|
||||
// 就地改更省事,而且弹窗会盖住进度条)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = onInput,
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.width(84.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("好") { onCommit() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
RowAction("取消") { onCancel() }
|
||||
} else {
|
||||
Text(
|
||||
"${fmtNum(stat.value)} / ${fmtNum(stat.max)}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("改") { onStartEdit() }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// 进度条:`ratio()` 在模型里(三个入口共用一份换算,圆角和取整才不会各说各话)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
if (stat.text.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(stat.text, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(st: StatusInstance, onDrop: () -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(st.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag(if (st.isPersistent) "持久" else "剩 ${st.remaining} 轮")
|
||||
if (st.stacks > 1) {
|
||||
Spacer(Modifier.width(4.dp))
|
||||
TinyTag("×${st.stacks}")
|
||||
}
|
||||
}
|
||||
if (st.hint.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(st.hint, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
// ★ 清掉。这是用户手动移除状态的**唯一出口**(AI 没这个能力)。
|
||||
// 不做二次确认:状态本来就可以再加回来,而多一层确认会让
|
||||
// "连清五个"变成五次弹窗 —— 手机上很烦。
|
||||
RowAction("清掉") { onDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TinyTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭。
|
||||
*
|
||||
* ★ 现在**两处**在用(状态数值页 + 智能体卡片),所以是 `internal` 不是 private ——
|
||||
* 卡片那边要显示同样的数字,抄一份就是第二份实现("同一逻辑只能有一份")。
|
||||
*/
|
||||
internal fun fmtNum(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
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.Agent
|
||||
@@ -72,15 +73,33 @@ import com.doubao.lynxclone.data.VoiceOption
|
||||
*/
|
||||
@Composable
|
||||
fun AgentsScreen(vm: AppViewModel) {
|
||||
var editing by remember { mutableStateOf<Agent?>(null) }
|
||||
var creating by remember { mutableStateOf(false) }
|
||||
var confirmDelete by remember { mutableStateOf<Agent?>(null) }
|
||||
|
||||
// ★ 导入智能体包(需求 2.5):zip → base64 → 内核解包。
|
||||
// 不走 Kotlin 解压是因为安卓的 `ZipInputStream` **读不出**这类 zip
|
||||
// (Termux bootstrap 那个坑,见 TermuxInstaller 的注释),
|
||||
// 而内核的 Python `zipfile` 没这个问题 —— 少踩一次已知的坑。
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
val importPackage = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
vm.importPackage("agents", android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP), "")
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
val activeId = vm.state.activeAgent?.id.orEmpty()
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) {
|
||||
TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) }
|
||||
TextButton(onClick = {
|
||||
importPackage.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
}) { Text("导入", fontSize = 13.sp) }
|
||||
TextButton(onClick = { vm.openAgentEdit(null) }) { Text("新建", fontSize = 13.sp) }
|
||||
}
|
||||
|
||||
Column(
|
||||
@@ -103,8 +122,11 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
agent = agent,
|
||||
active = agent.id == activeId,
|
||||
onUse = { vm.useAgent(agent.id) },
|
||||
onEdit = { editing = agent },
|
||||
onEdit = { vm.openAgentEdit(agent) },
|
||||
onMemories = { vm.openMemories(agent.id) },
|
||||
onDelete = { confirmDelete = agent },
|
||||
worldName = vm.state.worldviews
|
||||
.firstOrNull { it.id == agent.worldviewId }?.name.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -113,7 +135,7 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { creating = true },
|
||||
onClick = { vm.openAgentEdit(null) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
contentPadding = PaddingValues(vertical = 12.dp),
|
||||
@@ -129,41 +151,29 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
/* ---------------- 新建 / 编辑 ---------------- */
|
||||
if (creating || editing != null) {
|
||||
val target = editing
|
||||
AgentEditDialog(
|
||||
agent = target,
|
||||
providers = vm.state.providers.values.toList(),
|
||||
voices = vm.state.speechVoices,
|
||||
voicesAll = vm.state.speechVoicesAll,
|
||||
globalTtsEngine = vm.state.speech.ttsEngine,
|
||||
onDismiss = { creating = false; editing = null },
|
||||
onSave = { draft ->
|
||||
vm.saveAgent(target?.id, draft) {
|
||||
creating = false
|
||||
editing = null
|
||||
}
|
||||
},
|
||||
onDelete = if (target != null && !target.builtin) {
|
||||
{ confirmDelete = target }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
//
|
||||
// ★ 编辑走的是 **AgentEditScreen(全屏)**,不是这里原来那个弹窗。
|
||||
// 字段从 8 个涨到二十多个(外观四件套 / 模型引用 / 世界观 / 限额 / 技能……),
|
||||
// 弹窗装不下 —— AGENTS.md 那张表写得很清楚。
|
||||
// 删除确认**仍然是弹窗**:它就是"一次确认",正好是弹窗该用的地方。
|
||||
|
||||
/* ---------------- 删除确认 ---------------- */
|
||||
confirmDelete?.let { agent ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = null },
|
||||
title = { Text("删除智能体", fontSize = 16.sp) },
|
||||
text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"确定删除「${agent.name}」吗?\n\n" +
|
||||
"它的系统提示词和外观会一起删掉,不能撤销。\n" +
|
||||
"**记忆会保留**(那是你攒下来的东西,删之前建议先导出)。",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.deleteAgent(agent.id)
|
||||
confirmDelete = null
|
||||
// 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404
|
||||
if (editing?.id == agent.id) editing = null
|
||||
}) { Text("删除") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } },
|
||||
@@ -179,7 +189,11 @@ private fun AgentRow(
|
||||
active: Boolean,
|
||||
onUse: () -> Unit,
|
||||
onEdit: () -> Unit,
|
||||
/** 看这个智能体记住了什么(记忆管理界面的入口之一) */
|
||||
onMemories: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
/** 它绑的世界观叫什么(空 = 没绑)。交互是双向的,这边也要看得见 */
|
||||
worldName: String = "",
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||
@@ -215,7 +229,23 @@ private fun AgentRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
// ★ 绑了哪个世界观(用户要求"互通")——
|
||||
// 重点不是"它有个世界观",而是**它和谁共用记忆**。
|
||||
// 所以文案直接写"共用记忆",而不是干巴巴一个名字。
|
||||
if (agent.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"世界观「${worldName.ifBlank { "已失效" }}」· 记忆与同世界的智能体共用",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★「记忆」放在「编辑」**左边**:它是"看它记住了什么",
|
||||
// 属于日常动作;编辑是配置动作,用得少。
|
||||
TextButton(onClick = onMemories) { Text("记忆", fontSize = 12.sp) }
|
||||
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
|
||||
if (!agent.builtin) {
|
||||
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
|
||||
@@ -255,185 +285,6 @@ private fun ActiveBadge() {
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun AgentEditDialog(
|
||||
agent: Agent?,
|
||||
providers: List<ProviderPreset>,
|
||||
voices: Map<String, List<VoiceOption>>,
|
||||
voicesAll: Map<String, List<VoiceOption>>,
|
||||
/** 全局当前的朗读引擎:智能体没选引擎时,音色列表要按它来给 */
|
||||
globalTtsEngine: String,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (Agent) -> Unit,
|
||||
onDelete: (() -> Unit)?,
|
||||
) {
|
||||
// 整份草稿:加字段时只要往 Agent 里加,不用再改一遍这里的所有 var
|
||||
var draft by remember {
|
||||
mutableStateOf(
|
||||
agent ?: Agent(avatar = "doubao"),
|
||||
)
|
||||
}
|
||||
var error by remember { mutableStateOf("") }
|
||||
val name = draft.name
|
||||
val avatar = draft.avatar
|
||||
val prompt = draft.systemPrompt
|
||||
val greeting = draft.greeting
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
FormLabel("头像")
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
AvatarKeys.forEach { key ->
|
||||
Box(Modifier.clickable { draft = draft.copy(avatar = key) }) {
|
||||
// 选中态画在 AvatarCircle 的外圈上,不改变尺寸
|
||||
AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("名称")
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { draft = draft.copy(name = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("例如:翻译官", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("问候语 / 一句话介绍")
|
||||
OutlinedTextField(
|
||||
value = greeting,
|
||||
onValueChange = { draft = draft.copy(greeting = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Text(
|
||||
"列表摘要会显示这句;新会话首屏也用它打招呼。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("系统提示词")
|
||||
OutlinedTextField(
|
||||
value = prompt,
|
||||
onValueChange = { draft = draft.copy(systemPrompt = it) },
|
||||
modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp),
|
||||
placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) },
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
)
|
||||
Text(
|
||||
"和它聊天时,这段提示词会覆盖全局系统提示词。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
/* ---------------- 模型(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("模型")
|
||||
Text(
|
||||
"不选就跟随「设置 → 连接与模型」里的全局配置。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") +
|
||||
providers.map { it.key to it.label },
|
||||
active = draft.provider,
|
||||
) { draft = draft.copy(provider = it) }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
// ★ 别把 `ifBlank{…} == "x" ? a : b` 写成一整行:Kotlin 会把那个 `?`
|
||||
// 当成安全调用开始解析,报一堆看不懂的语法错。拆成变量最稳。
|
||||
val followGlobalModel = draft.provider.isBlank()
|
||||
OutlinedTextField(
|
||||
value = draft.model,
|
||||
onValueChange = { draft = draft.copy(model = it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
placeholder = {
|
||||
Text(
|
||||
if (followGlobalModel) "留空 = 用全局模型" else "留空 = 用这家的默认模型",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
/* ---------------- 语音(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("语音")
|
||||
Text(
|
||||
"多人会议里靠它区分谁在说话 —— 几个智能体一个嗓子的话根本听不出谁在讲。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") + TtsEngineChoices,
|
||||
active = draft.ttsEngine,
|
||||
) { engine ->
|
||||
// 换引擎顺手清掉音色:音色是按引擎命名的(BVxxx / zh_xxx_bigtts),
|
||||
// 留着上一家的值一定会被判非法
|
||||
draft = draft.copy(ttsEngine = engine, ttsVoice = "")
|
||||
}
|
||||
val voiceEngine = draft.ttsEngine.ifBlank { globalTtsEngine }
|
||||
if (voiceEngine != "" && voiceEngine != "system") {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
VoicePickerInline(
|
||||
engine = voiceEngine,
|
||||
voices = voices[voiceEngine].orEmpty(),
|
||||
voicesAll = voicesAll[voiceEngine].orEmpty(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
if (error.isNotBlank()) {
|
||||
Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
if (draft.name.isBlank()) {
|
||||
error = "名称不能为空"
|
||||
} else {
|
||||
onSave(draft.copy(name = draft.name.trim(), greeting = draft.greeting.trim()))
|
||||
}
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = {
|
||||
Row {
|
||||
if (onDelete != null) {
|
||||
TextButton(onClick = onDelete) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
TextButton(onClick = onDismiss) { Text("取消") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 列表里那一行摘要文案 */
|
||||
private fun agentSummary(agent: Agent): String = when {
|
||||
agent.greeting.isNotBlank() -> agent.greeting
|
||||
agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手"
|
||||
@@ -495,7 +346,7 @@ internal fun WrapChips(
|
||||
* 拽进智能体页 —— 真要统一的话应该把它提成公共组件,那是另一件事。
|
||||
*/
|
||||
@Composable
|
||||
private fun VoicePickerInline(
|
||||
internal fun VoicePickerInline(
|
||||
engine: String,
|
||||
voices: List<VoiceOption>,
|
||||
voicesAll: List<VoiceOption>,
|
||||
@@ -0,0 +1,207 @@
|
||||
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.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
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.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* ★★ 「AI 界面」列表 —— 用户要求"AI 写的界面可以再点开"。
|
||||
*
|
||||
* ## 为什么要有它
|
||||
*
|
||||
* 界面以前只活在内存里,一关就没了。用户过一会儿想"刚才那个图表再看一眼"
|
||||
* 就找不回来,只能让 AI 重新生成 —— 而**重新生成的内容不一定一样**
|
||||
* (模型有随机性),用户会觉得"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* 所以每次 `show_ui` 都存一份到磁盘,这里列出它们。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面,不是弹窗
|
||||
*
|
||||
* 列表要滚动(一个会话可能攒十几个界面),弹窗装不下。
|
||||
* 顶栏用统一的 `← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun AiScreenListScreen(
|
||||
screens: List<AiScreenItem>,
|
||||
onOpen: (String) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("AI 界面", onBack = onClose) {
|
||||
Text(
|
||||
if (screens.isEmpty()) "还没有" else "${screens.size} 个",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
if (screens.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"AI 还没给你弹过界面。\n让它「弹个界面」试试。",
|
||||
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(screens.size) { index ->
|
||||
val s = screens[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onOpen(s.id) }
|
||||
.padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
s.title,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (s.preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
s.preview,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"${formatTime(s.at)} · ${formatBytes(s.bytes)}",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// 删除:单独一个小按钮,别让"点卡片"和"删除"挤在一起误触
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.clickable { onDelete(s.id) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
"删除",
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 列表里的一条(从 AiSurface 的索引 JSON 转过来) */
|
||||
data class AiScreenItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val preview: String,
|
||||
val bytes: Int,
|
||||
val at: Long,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** 时间戳 → 「今天 14:03」/「10-15 14:03」。手机上不显示年份,太占地方 */
|
||||
private fun formatTime(ms: Long): String {
|
||||
if (ms <= 0) return ""
|
||||
val now = java.util.Calendar.getInstance()
|
||||
val then = java.util.Calendar.getInstance().apply { timeInMillis = ms }
|
||||
val sameDay = now.get(java.util.Calendar.YEAR) == then.get(java.util.Calendar.YEAR) &&
|
||||
now.get(java.util.Calendar.DAY_OF_YEAR) == then.get(java.util.Calendar.DAY_OF_YEAR)
|
||||
val fmt = SimpleDateFormat(if (sameDay) "'今天' HH:mm" else "MM-dd HH:mm", Locale.getDefault())
|
||||
return fmt.format(Date(ms))
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节数 → 人能看的字符串。
|
||||
*
|
||||
* ★ 不足 1KB 的要显示字节数:第一版写的是 `bytes / 1024` + "KB",
|
||||
* 于是 524 字节的界面显示成 **"0KB"**(看起来像"这个界面是空的")。
|
||||
* 整数除法把小于 1024 的一律变成 0 了。
|
||||
*/
|
||||
private fun formatBytes(n: Int): String = when {
|
||||
n <= 0 -> "—"
|
||||
n < 1024 -> "${n}B"
|
||||
n < 1024 * 1024 -> "${n / 1024}KB"
|
||||
else -> String.format(Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0)
|
||||
}
|
||||
@@ -0,0 +1,785 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.net.Uri
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
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.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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
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.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
|
||||
/**
|
||||
* AI 主动弹出来的三个界面(都带进出动画)。
|
||||
*
|
||||
* 放在**导航之上**(见 AppRoot):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话在会议/设置页就看不到。
|
||||
*
|
||||
* 三个东西的动画各有讲究:
|
||||
* · HTML 界面 —— 从中心"长大"+ 淡入(像开一扇门),退出反向
|
||||
* · 选择弹窗 —— 从下方滑上来 + 淡入(手机上的惯例手势方向)
|
||||
* · 结束横幅 —— 从下方滑到**屏幕中间**停住,并且**留在那儿**(不自动消失)
|
||||
*/
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、AI 的 HTML 界面(show_ui) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiHtmlScreenOverlay(
|
||||
screen: AiSurface.Screen?,
|
||||
onClose: () -> Unit,
|
||||
onResult: (String) -> Unit,
|
||||
/** 等待模式:用户点了回传按钮之后自动把界面收掉(这是"用户答完了"的信号) */
|
||||
autoCloseOnResult: Boolean = false,
|
||||
) {
|
||||
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||
val shown = screen ?: last
|
||||
|
||||
// WebView 实例 + "能不能回退"。
|
||||
// ★ 拿到了 WebView 才能调 goBack();canGoBack 要轮询(WebView 没有变更回调)。
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var canGoBack by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(web, screen) {
|
||||
while (web != null && screen != null) {
|
||||
canGoBack = web?.canGoBack() == true
|
||||
kotlinx.coroutines.delay(400)
|
||||
}
|
||||
canGoBack = false
|
||||
}
|
||||
|
||||
// 系统返回键:能回退就先回退(用户点进去了一页,返回键该带他回来),
|
||||
// 不能回退才关掉整个界面 —— 比直接关掉符合直觉。
|
||||
BackHandler(enabled = screen != null) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = screen != null,
|
||||
enter = fadeIn(tween(180)) +
|
||||
scaleIn(tween(240, easing = androidx.compose.animation.core.FastOutSlowInEasing), initialScale = 0.86f),
|
||||
exit = fadeOut(tween(150)) + scaleOut(tween(180), targetScale = 0.92f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
shown.title.ifBlank { "AI 界面" },
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// 「返回上一页」只在真能回退时出现 —— 一直显示一个点了没反应的
|
||||
// 箭头比不显示更让人困惑
|
||||
AnimatedVisibility(
|
||||
visible = canGoBack,
|
||||
enter = fadeIn(tween(150)),
|
||||
exit = fadeOut(tween(120)),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { web?.goBack() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
"返回上一页",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
AiWebView(
|
||||
screen = shown,
|
||||
onResult = { value ->
|
||||
onResult(value)
|
||||
// ★ 等待模式下这一下就是"用户答完了" —— 把界面收掉,
|
||||
// 否则用户看到一个已经用完的界面还开着,会以为还能再点。
|
||||
if (autoCloseOnResult) onClose()
|
||||
},
|
||||
onClose = onClose,
|
||||
onWebView = { web = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 AI 写的 HTML。
|
||||
*
|
||||
* ## JS 开着,但 `@JavascriptInterface` 只在"我们自己那一页"暴露
|
||||
*
|
||||
* 用户要求"支持 js"。开了 JS 之后最大的风险不是 JS 本身,而是
|
||||
* **`addJavascriptInterface` 注入的那个桥**:它对**之后加载的每一个页面**
|
||||
* 都可见。AI 的页面里如果有个链接,用户点进去落到一个外部站点,
|
||||
* 那个站点的 JS 也能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
*
|
||||
* 所以这里**按 origin 收口**:
|
||||
*
|
||||
* · 初始文档用 `loadDataWithBaseURL(null, …)` 加载 —— 它的 document origin
|
||||
* 是**不透明(opaque)**的,WebView 会把它当作"没有来源"
|
||||
* · 导航到任何 **http/https** 之前,先把桥撤掉(`removeJavascriptInterface`)
|
||||
* · 外部页面在 WebView 里正常打开(用户要的"点进去"就是它),
|
||||
* 但它没有桥;而且 `onPageStarted` 里会再兜一次
|
||||
*
|
||||
* ## 依然保持关闭的那些
|
||||
*
|
||||
* · `allowFileAccess` / `allowContentAccess` —— 不让页面读本地文件
|
||||
* · `setAllowFileAccessFromFileURLs` / `setAllowUniversalAccessFromFileURLs`
|
||||
* · `mixedContentMode = NEVER` —— 不让 https 页面加载 http 资源
|
||||
*
|
||||
* ## 可点按钮的两条路都留着
|
||||
*
|
||||
* 1. `<button data-doubao-result="值">` —— App 侧字符串替换成
|
||||
* `doubao://pick?...`,由 `shouldOverrideUrlLoading` 拦。
|
||||
* **不依赖 JS**,所以页面即使 JS 出错也能用
|
||||
* 2. `Doubao.pick("值")` / `Doubao.close()` —— 给会写 JS 的模型用
|
||||
* (图表上点一个点回传、定时刷新之类)
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
private fun AiWebView(
|
||||
screen: AiSurface.Screen,
|
||||
onResult: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onWebView: (WebView) -> Unit = {},
|
||||
) {
|
||||
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||
// 记一下"桥还在不在",避免同一页里反复 remove/add
|
||||
val host = remember(screen.id) { AiWebHost() }
|
||||
host.onResult = onResult
|
||||
host.onClose = onClose
|
||||
|
||||
DisposableEffect(screen.id) {
|
||||
onDispose { host.detach() }
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
isVerticalScrollBarEnabled = true
|
||||
|
||||
/**
|
||||
* ★★ 桥的挂/摘时机 —— 这里改了两版才对,把结论记下来。
|
||||
*
|
||||
* **第一版**(错的):`loadDataWithBaseURL` 之前就 add,导航到
|
||||
* http(s) 时 remove。问题:外部页面在 `onPageStarted` 摘桥**之前**
|
||||
* 有个"已经开始加载、桥还在"的窗口期。
|
||||
*
|
||||
* **第二版**(也是错的):只在 `onPageFinished` 里判 url 是不是
|
||||
* `about:blank` 才 add。实测页面报
|
||||
* `Uncaught ReferenceError: Doubao is not defined`
|
||||
* —— `onPageFinished` 的**回调时机比页面内联 <script> 执行还晚**,
|
||||
* 脚本跑的时候桥还没挂上。
|
||||
*
|
||||
* **第三版**(现在这个):初始 load **之前就挂**(保证脚本能用到),
|
||||
* 然后靠 [AiWebHost.payloadLoaded] 这个标志挡住窗口期 ——
|
||||
* loadUrl 到别的地址时,`payloadLoaded` 已经是 true,
|
||||
* 所以立刻摘桥,外部页面**从头到尾**都碰不到它。
|
||||
*/
|
||||
addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
// 开始加载"非初始页"了 —— 说明初始页已经加载过(标志为 true),
|
||||
// 而这次是一个**导航**:立刻摘桥。
|
||||
//
|
||||
// ★ 纯锚点跳转(#xxx)不算导航,不能摘 —— 否则页面内
|
||||
// "跳到某一段"之后 JS 就废了。
|
||||
val anchorOnly = url != null && url.startsWith("about:blank#")
|
||||
if (host.payloadLoaded && !anchorOnly) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
if (!host.payloadLoaded) {
|
||||
// 初始那页加载完成。**马上补挂一次** —— 实测
|
||||
// loadDataWithBaseURL 的页面在脚本执行时桥可能还没生效,
|
||||
// 补挂之后重新 load 才稳。
|
||||
host.payloadLoaded = true
|
||||
view?.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS, null)
|
||||
return
|
||||
}
|
||||
// 之后每次加载完都探一次:**页面里有我们的标记**才重挂桥。
|
||||
//
|
||||
// ★ 为什么用"页面里有没有标记变量"而不是看 url:
|
||||
// 实测从外部页返回(goBack)时,onPageFinished 收到的 url
|
||||
// 并不是 `about:blank`,用 url 判会漏 —— 表现是
|
||||
// "点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
// 标记变量是**页面自己的属性**,页面被换掉它就没了,
|
||||
// 比 url 可靠。
|
||||
//
|
||||
// ★ 如果标记在**但桥不在**,说明这一页是我们的,
|
||||
// 而桥在上一次导航时被摘了 → 重挂。
|
||||
// 如果标记在**桥也在**,什么都不用做。
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS) { result ->
|
||||
// ★ evaluateJavascript 的回调参数是**字符串**,
|
||||
// 而且返回值经 JSON 编码("1" 带着引号)。
|
||||
// 我第一版按 Boolean 处理,条件永远不成立。
|
||||
val ok = (result ?: "").trim('"', ' ')
|
||||
if (ok == "1" && !host.bridgeAttached) {
|
||||
view.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
): Boolean {
|
||||
val u = url ?: return false
|
||||
|
||||
// ① 我们自己约定的回传协议
|
||||
if (u.startsWith("doubao://pick")) {
|
||||
val v = Uri.decode(Uri.parse(u).getQueryParameter("value") ?: "")
|
||||
if (v.isNotEmpty()) onResult(v)
|
||||
return true
|
||||
}
|
||||
if (u.startsWith("doubao://close")) {
|
||||
onClose()
|
||||
return true
|
||||
}
|
||||
|
||||
// ② http(s):**在 WebView 里打开**(用户要的"点进去")。
|
||||
// 桥会在 onPageStarted 里被摘掉(那时 payloadLoaded 已 true),
|
||||
// 所以外部站点碰不到 App。
|
||||
if (u.startsWith("http://") || u.startsWith("https://")) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
return false
|
||||
}
|
||||
|
||||
// ③ 页内锚点(#xxx)交给 WebView 自己处理
|
||||
if (u.startsWith("#")) return false
|
||||
|
||||
// ④ 别的协议(tel: / mailto: / intent: …)交给系统
|
||||
return try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(u))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||
onWebView(this)
|
||||
}
|
||||
},
|
||||
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 给 AI 页面用的 JS 桥。
|
||||
*
|
||||
* 暴露两个方法(页面上写 `Doubao.pick("值")` / `Doubao.close()`):
|
||||
*
|
||||
* · `pick(value)` —— 回传一个值,和点 `data-doubao-result` 按钮等价。
|
||||
* 适合"图表上点一个点"、"定时刷新后回传结果"这类需要脚本的场景。
|
||||
* · `close()` —— 关掉这个界面。
|
||||
*
|
||||
* ★ 方法名和 [NAME] 都刻意短且通用,因为模型要在 HTML 里手写它们;
|
||||
* 但**只暴露这两个** —— 桥能调到的越少,万一被滥用时的损失越小。
|
||||
*
|
||||
* ★ 注意:这个对象**只挂在初始那一页**上(见 [AiWebView] 的注释)。
|
||||
* 导航到外部站点时会被 `removeJavascriptInterface` 摘掉。
|
||||
*/
|
||||
class AiWebHost {
|
||||
@Volatile
|
||||
var onResult: ((String) -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onClose: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 初始那一页(AI 写的那份 HTML)加载完成了没有。
|
||||
*
|
||||
* 用来区分"初始加载"和"用户点链接导航" —— 两者都会走 `onPageStarted`,
|
||||
* 但只有后者该摘桥。见 [AiWebView] 里那段注释。
|
||||
*/
|
||||
@Volatile
|
||||
var payloadLoaded: Boolean = false
|
||||
|
||||
/** 桥现在挂着没有。重挂前要先看它,不然会重复 add。 */
|
||||
@Volatile
|
||||
var bridgeAttached: Boolean = false
|
||||
|
||||
@JavascriptInterface
|
||||
fun pick(value: String?) {
|
||||
val v = (value ?: "").trim()
|
||||
if (v.isEmpty()) return
|
||||
onResult?.invoke(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* `pick` 的别名 —— **这是"AI 自己能写进网页里的接口"**。
|
||||
*
|
||||
* AI 在它生成的 HTML 里写:
|
||||
* ```html
|
||||
* <button onclick="Doubao.sendToAi('用户选了方案 B')">方案 B</button>
|
||||
* ```
|
||||
* 那个值就会经安卓桥 POST 到内核排队,**下一轮对话时作为上下文交给模型**。
|
||||
* 也就是模型真的能知道用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 两个名字都留着(`pick` / `sendToAi`):模型有时写这个有时写那个,
|
||||
* 收两个比让它猜、猜错了整段交互失效要省事得多。
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun sendToAi(value: String?) = pick(value)
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
|
||||
/** 页面销毁时断开引用,别把 Compose 的东西一直攥着 */
|
||||
fun detach() {
|
||||
onResult = null
|
||||
onClose = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "Doubao"
|
||||
|
||||
/**
|
||||
* 往页面里写一个标记并回读 —— 用来判断"当前这一页是不是我们自己注入的"。
|
||||
*
|
||||
* ★ 走 `evaluateJavascript` 而不是看 url:实测从外部页返回时
|
||||
* `onPageFinished` 收到的 url 不是 `about:blank`,用 url 判会漏。
|
||||
* 标记是页面自己的属性,页面被换掉它就没了,可靠得多。
|
||||
*
|
||||
* 返回 "1" 表示是我们的页。
|
||||
*/
|
||||
const val PROBE_JS =
|
||||
"(function(){try{" +
|
||||
"if(!window.__doubaoAiPage){window.__doubaoAiPage=1;}" +
|
||||
"return '1';" +
|
||||
"}catch(e){return '0';}})()"
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 `data-doubao-result="x"` 变成可点的链接,再套一层骨架 */
|
||||
private fun buildAiHtml(screen: AiSurface.Screen): String {
|
||||
val body = if (screen.fullHtml) screen.html else wrapSkeleton(screen.html)
|
||||
return rewriteResultLinks(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `<button data-doubao-result="值">文字</button>` 重写成
|
||||
* `<a class="db-btn" href="doubao://pick?value=值">文字</a>`。
|
||||
*
|
||||
* ★ 用正则做单遍替换,**不引 HTML 解析器** —— 这点转换不值得多一个依赖,
|
||||
* 而且 AI 的输出是受控的(我们自己提示词里教的写法)。
|
||||
* `button` 和 `a` 两种都收,模型有时会写成链接。
|
||||
*/
|
||||
private fun rewriteResultLinks(html: String): String {
|
||||
val pattern = Regex(
|
||||
"""<(button|a)\b([^>]*?)data-doubao-result\s*=\s*["']([^"']*)["']([^>]*?)>(.*?)</\1>""",
|
||||
setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),
|
||||
)
|
||||
return pattern.replace(html) { m ->
|
||||
val value = android.net.Uri.encode(m.groupValues[3])
|
||||
val inner = m.groupValues[5]
|
||||
"""<a class="db-btn" href="doubao://pick?value=$value">$inner</a>"""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给"片段式" HTML 套一层骨架。
|
||||
*
|
||||
* 为什么要套:模型每次都要重复写 `<meta viewport>`、暗色主题背景、字体、
|
||||
* 边距 —— 既啰嗦又容易和 App 的主题打架。套一层之后它只管写内容。
|
||||
*/
|
||||
private fun wrapSkeleton(fragment: String): String = """
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 16px 16px 40px;
|
||||
background: #121317; color: #e8eaed;
|
||||
font: 15px/1.7 -apple-system, "PingFang SC", "Noto Sans CJK SC", sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
h1 { font-size: 21px; margin: 4px 0 12px; }
|
||||
h2 { font-size: 18px; margin: 20px 0 8px; }
|
||||
h3 { font-size: 16px; margin: 16px 0 6px; }
|
||||
p { margin: 8px 0; }
|
||||
a { color: #7cb0ff; }
|
||||
code, pre {
|
||||
background: #1d1f25; border-radius: 8px;
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px;
|
||||
}
|
||||
code { padding: 2px 5px; }
|
||||
pre { padding: 12px; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||
th, td { border: 1px solid #2c2f36; padding: 8px 10px; text-align: left; }
|
||||
th { background: #1b1d22; font-weight: 600; }
|
||||
blockquote {
|
||||
margin: 12px 0; padding: 8px 14px;
|
||||
border-left: 3px solid #3d4450; color: #b9bdc4;
|
||||
}
|
||||
img, svg, canvas { max-width: 100%; height: auto; }
|
||||
hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; }
|
||||
|
||||
/* ★★ 按钮 —— 这里刻意做得**非常显眼**。
|
||||
*
|
||||
* 起因:用户连着两次反馈"哪有按键,网页里的按键也点不了"、"没有一个按键能用"。
|
||||
* 实测下来**功能是好的**(点了值确实回到模型手里),问题出在**视觉**:
|
||||
*
|
||||
* · `data-doubao-result` 的按钮会被 App 改写成 `<a class="db-btn">`,
|
||||
* 拿到亮蓝整行的样式 → 看得出来能点
|
||||
* · 而 `onclick="Doubao.sendToAi(...)"` 的按钮**保持原样**,
|
||||
* 落进下面那条"普通按钮"规则 → 小灰块,在深色主题里跟正文几乎一样
|
||||
*
|
||||
* 同一屏里一半亮蓝一半灰暗,用户当然会以为"只有蓝的能点"甚至"都不能点"。
|
||||
*
|
||||
* 所以现在**所有 button / .db-btn 一律是同样显眼的实心蓝**,
|
||||
* 普通按钮那条规则删掉了。`!important` 是为了压掉模型内联的
|
||||
* `style="background:..."`(模型很爱写这个,一写就把我们的样式盖掉)。 */
|
||||
.db-btn, button, [data-doubao-result], [role=button] {
|
||||
display: block !important;
|
||||
width: 100% !important;
|
||||
margin: 10px 0 !important;
|
||||
padding: 15px 18px !important;
|
||||
background: #2b7bff !important;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none !important;
|
||||
text-align: center !important;
|
||||
border: 0 !important;
|
||||
border-radius: 12px !important;
|
||||
font-size: 16px !important;
|
||||
font-weight: 500 !important;
|
||||
line-height: 1.4 !important;
|
||||
cursor: pointer !important;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
.db-btn:active, button:active, [data-doubao-result]:active, [role=button]:active {
|
||||
background: #1e63d6 !important;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
/* 次要按钮(模型想要不那么抢眼的):加个 class 就能变灰 */
|
||||
.db-plain, button.db-plain {
|
||||
background: #262a31 !important;
|
||||
color: #e8eaed !important;
|
||||
border: 1px solid #3d4450 !important;
|
||||
}
|
||||
/* 两个按钮并排时用这个包一层 */
|
||||
.db-row { display: flex; gap: 10px; }
|
||||
.db-row > * { flex: 1; }
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、AI 的选择弹窗(ask_user) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiDialogOverlay(dialog: AiSurface.Dialog?, onAnswer: (List<String>, Boolean) -> Unit) {
|
||||
var last by remember { mutableStateOf<AiSurface.Dialog?>(null) }
|
||||
LaunchedEffect(dialog) { if (dialog != null) last = dialog }
|
||||
val shown = dialog ?: last
|
||||
|
||||
// 多选时先把已勾的攒起来,点「确定」才回传
|
||||
val picked = remember(dialog?.id) { mutableStateListOf<String>() }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
enter = fadeIn(tween(180)),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color(0xB3000000))
|
||||
.clickable(enabled = shown?.allowCancel == true) { onAnswer(emptyList(), true) },
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
enter = slideInVertically(tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) { it / 3 } +
|
||||
fadeIn(tween(200)) + scaleIn(tween(280), initialScale = 0.94f),
|
||||
exit = slideOutVertically(tween(200)) { it / 4 } + fadeOut(tween(150)) +
|
||||
scaleOut(tween(200), targetScale = 0.96f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 24.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(20.dp),
|
||||
) {
|
||||
Text("AI 想问你", fontSize = 12.sp, color = doubaoTextDim())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
shown.question,
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
lineHeight = 24.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("可多选", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
// 选项多时中间区域自己滚,按钮不跟着滚出去
|
||||
Column(
|
||||
Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
shown.options.forEach { opt ->
|
||||
val on = opt.value in picked
|
||||
OptionRow(
|
||||
label = opt.label,
|
||||
description = opt.description,
|
||||
selected = on,
|
||||
multiple = shown.multiple,
|
||||
onClick = {
|
||||
if (shown.multiple) {
|
||||
if (on) picked.remove(opt.value) else picked.add(opt.value)
|
||||
} else {
|
||||
onAnswer(listOf(opt.value), false)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (shown.allowCancel) {
|
||||
OutlinedButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
}
|
||||
Button(
|
||||
onClick = { onAnswer(picked.toList(), false) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("确定") }
|
||||
}
|
||||
} else if (shown.allowCancel) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
TextButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) { Text("取消") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OptionRow(
|
||||
label: String,
|
||||
description: String,
|
||||
selected: Boolean,
|
||||
multiple: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
// 选中时轻微放大 —— 比单纯变色更能让人感到"点到了"
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (selected) 1.02f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "optScale",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (selected) doubaoAccentSoft() else doubaoSurfaceAlt())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 15.sp,
|
||||
color = if (selected) doubaoAccent() else doubaoText(),
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
if (description.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(description, fontSize = 12.sp, color = doubaoTextDim(), lineHeight = 17.sp)
|
||||
}
|
||||
}
|
||||
if (multiple && selected) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("✓", fontSize = 16.sp, color = doubaoAccent())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、对话被 AI 结束 —— 屏幕中间的横幅 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* ★ 用户明确要求的样子:**屏幕中间一个横幅,写着 AI 关闭的原因**。
|
||||
*
|
||||
* 几个细节:
|
||||
* · **停在屏幕正中间**(不是顶部也不是底部)—— 这是"这次对话到此为止"
|
||||
* 这种终局状态,摆在视线中心最合适
|
||||
* · **不自动消失**。它不是提示条,是状态;消失了用户就不知道
|
||||
* 为什么发不出消息了
|
||||
* · 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
* · 只显示在与它相关的那次对话里(调用方按 conversationId 判断)
|
||||
*/
|
||||
@Composable
|
||||
fun EndedBanner(reason: String, onNewConversation: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
AnimatedVisibility(
|
||||
visible = true,
|
||||
enter = slideInVertically(
|
||||
tween(420, easing = androidx.compose.animation.core.FastOutSlowInEasing),
|
||||
) { it } + fadeIn(tween(280)) + scaleIn(tween(420), initialScale = 0.9f),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 28.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 20.dp, vertical = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.PowerSettingsNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("这次对话已结束", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
reason.ifBlank { "AI 结束了这次对话" },
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Button(
|
||||
onClick = onNewConversation,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = doubaoAccent()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("开始新对话", color = Color.White) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
880
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt
Normal file
880
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt
Normal file
@@ -0,0 +1,880 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
// ★ 扩展函数(`Modifier.verticalScroll`)**不能用全限定名调用** ——
|
||||
// 必须 import 进来。这个坑花了两轮构建才撞明白。
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
import com.doubao.lynxclone.data.KernelClient
|
||||
|
||||
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
|
||||
@Composable
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel {
|
||||
// ★ 必须写 `viewModel<AppViewModel>(…)`:不写的话类型推断会挂
|
||||
// (报 "Not enough information to infer type argument for 'VM'"),
|
||||
// 下面那句 `vm.appContext` 就跟着报未解析引用 ——
|
||||
// 错误信息看着完全不像"泛型没写",很容易往错的方向查。
|
||||
val vm = viewModel<AppViewModel>(factory = object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T = AppViewModel(client) as T
|
||||
})
|
||||
// ★ 把 ApplicationContext 交给 ViewModel —— 它要读写"AI 界面"那些落盘的文件
|
||||
// (用户要求"AI 写的界面可以再点开")。
|
||||
// ViewModel 自己拿不到 Context(没有 DI 框架),所以在 Compose 这一层塞进去。
|
||||
// 用 **applicationContext** 而不是 Activity:ViewModel 活得比 Activity 久,
|
||||
// 攥着 Activity 会泄漏。
|
||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
// ★ 显式写参数名 `ctx`:LaunchedEffect 的 lambda 里 `it` 是它的 key(不是我们想要的),
|
||||
// 写成 `it` 会报 "Unresolved reference 'it'" —— 因为 LaunchedEffect 的
|
||||
// block 是无参的 `suspend () -> Unit`,没有 it。
|
||||
androidx.compose.runtime.LaunchedEffect(appContext) { vm.appContext = appContext }
|
||||
return vm
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AppRoot(
|
||||
client: KernelClient,
|
||||
termuxReady: Boolean,
|
||||
termuxStatus: String,
|
||||
onInstallTermux: () -> Unit,
|
||||
) {
|
||||
val vm = rememberAppViewModel(client)
|
||||
LaunchedEffect(Unit) { vm.refresh() }
|
||||
|
||||
/* ---------------- 记忆的导入 / 导出(SAF)----------------
|
||||
*
|
||||
* ★ 为什么用系统的文件选择器而不是自己写路径:安卓 11+ 已经不给
|
||||
* App 随便写公共目录了,SAF 是唯一"用户想存哪就存哪"的正路
|
||||
* (会议导出、节点导出都是这条路,见 MeetingsScreen)。
|
||||
* ★ 编码固定 UTF-8:记忆里有中文,用默认编码在别的机器上会变乱码。
|
||||
*/
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<String?>(null) }
|
||||
// 导入记忆:文件读出来了,等用户选合并还是覆盖
|
||||
var pendingImportJson by remember { mutableStateOf<String?>(null) }
|
||||
val createMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json"),
|
||||
) { uri ->
|
||||
val text = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && text != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(text.toByteArray(Charsets.UTF_8)) }
|
||||
}.onFailure { vm.showHint("导出失败:${it.message ?: "写不进去"}") }
|
||||
.onSuccess { vm.showHint("记忆已导出") }
|
||||
}
|
||||
}
|
||||
val importMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { input ->
|
||||
input.readBytes().toString(Charsets.UTF_8)
|
||||
} ?: ""
|
||||
}.onSuccess { text ->
|
||||
// ★ 读出来先**不导**,让用户选合并还是覆盖(复查报告 4.2.4)。
|
||||
// 原来这里是"直接按合并导" —— 于是 replace 这个能力
|
||||
// 内核支持、界面上却没有入口,等于只有一半。
|
||||
if (text.isNotBlank()) pendingImportJson = text
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
// 提示条 2.5 秒后自动消失
|
||||
LaunchedEffect(vm.hint) {
|
||||
if (vm.hint.isNotBlank()) {
|
||||
kotlinx.coroutines.delay(2500)
|
||||
vm.hint = ""
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg())
|
||||
// edge-to-edge 下得自己吃系统栏/输入法内边距
|
||||
.windowInsetsPadding(WindowInsets.safeDrawing),
|
||||
) {
|
||||
// 页面切换带淡入 + 轻微位移,不然是"啪"一下就换了
|
||||
AnimatedContent(
|
||||
targetState = vm.screen,
|
||||
transitionSpec = {
|
||||
val forward = targetState != Screen.Chat
|
||||
val dir = if (forward) 1 else -1
|
||||
(slideInHorizontally(tween(240)) { it / 14 * dir } + fadeIn(tween(200))) togetherWith
|
||||
(slideOutHorizontally(tween(200)) { -it / 14 * dir } + fadeOut(tween(150)))
|
||||
},
|
||||
label = "screen",
|
||||
) { screen ->
|
||||
when (screen) {
|
||||
Screen.Chat -> ChatScreen(vm)
|
||||
Screen.Profile -> ProfileScreen(vm)
|
||||
Screen.Settings -> SettingsScreen(vm)
|
||||
Screen.Skills -> SkillsScreen(vm)
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
// 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画
|
||||
Screen.AgentSelect -> AgentSelectScreen(
|
||||
vm = vm,
|
||||
agents = vm.agents,
|
||||
activeId = vm.state.settings.activeAgentId,
|
||||
onEnter = { vm.enterAgent(it.id) },
|
||||
onMore = { vm.openTokenUsage(it.id) },
|
||||
onMemories = { vm.openMemories(it.id) },
|
||||
onManage = { vm.screen = Screen.Agents },
|
||||
onBack = { vm.screen = Screen.Chat },
|
||||
)
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)
|
||||
Screen.Resources -> ResourcesScreen(vm) { vm.screen = Screen.Chat }
|
||||
Screen.Meetings -> MeetingsScreen(vm)
|
||||
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||
}
|
||||
}
|
||||
|
||||
// 抽屉:左边滑进来 + 遮罩淡入
|
||||
AnimatedVisibility(
|
||||
visible = vm.drawerOpen,
|
||||
enter = slideInHorizontally(tween(260)) { -it } + fadeIn(tween(180)),
|
||||
exit = slideOutHorizontally(tween(220)) { -it } + fadeOut(tween(150)),
|
||||
) {
|
||||
DrawerOverlay(vm)
|
||||
}
|
||||
|
||||
/* ---------------- AI 主动弹出来的东西 ----------------
|
||||
*
|
||||
* ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 ——
|
||||
* 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。
|
||||
*
|
||||
* 顺序(后写的盖在上面):全屏网页 > 选择弹窗 > HTML 界面。
|
||||
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
// 「更多功能」—— 抽屉里放不下的入口收在这儿
|
||||
AnimatedVisibility(
|
||||
visible = vm.moreSheetOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MoreSheetScreen(
|
||||
onOpenAiScreens = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openAiScreenList()
|
||||
},
|
||||
onOpenSkills = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Skills
|
||||
},
|
||||
onOpenResources = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Resources
|
||||
},
|
||||
onOpenMeetings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Meetings
|
||||
},
|
||||
onOpenTerminal = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Terminal
|
||||
},
|
||||
onOpenSettings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
// 从抽屉挪进来的
|
||||
onOpenNotes = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openNotes()
|
||||
},
|
||||
// ★ v3.0 P2:容器(一局 = 世界包 + 成员)
|
||||
onOpenContainers = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openContainers()
|
||||
},
|
||||
onOpenModels = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.modelPickerOpen = true
|
||||
},
|
||||
onClose = { vm.moreSheetOpen = false },
|
||||
)
|
||||
}
|
||||
|
||||
// 「容器」—— v3.0 的一局 = 世界包 + 成员;数值/状态/记忆按局隔离
|
||||
AnimatedVisibility(
|
||||
visible = vm.showContainers,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
ContainerListScreen(vm = vm, onBack = { vm.closeContainers() })
|
||||
}
|
||||
|
||||
// 「容器编辑」—— 盖在容器列表上面(全屏)
|
||||
// ★ 判 `showContainerEdit` 而不是 `editingContainer != null`:
|
||||
// 新建时 editingContainer 是 null(还没有这个对象),用后者会永远打不开。
|
||||
AnimatedVisibility(
|
||||
visible = vm.showContainerEdit,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
ContainerEditScreen(vm = vm, onBack = { vm.closeContainerEdit() })
|
||||
}
|
||||
|
||||
// 「背包」—— v3.0 P3:按容器隔离的物品(用户手动使用/抛弃/赠与)
|
||||
AnimatedVisibility(
|
||||
visible = vm.bagContainerId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
BagScreen(vm = vm, onBack = { vm.closeBag() })
|
||||
}
|
||||
|
||||
// 「物品管理」—— v3.4:用户角色(用户也是角色)的背包 / 状态
|
||||
AnimatedVisibility(
|
||||
visible = vm.userItemsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
UserItemsScreen(vm = vm, onBack = { vm.closeUserItems() })
|
||||
}
|
||||
|
||||
// 「地图」—— v3.0 P4:地点 / 场景 / 在场(点地点 = 切到该地点频道)
|
||||
AnimatedVisibility(
|
||||
visible = vm.mapContainerId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MapScreen(vm = vm, onBack = { vm.closeMap() })
|
||||
}
|
||||
|
||||
// 「上下文查看器」(v3.16 用户需求):**真正送进模型的东西**
|
||||
// —— system prompt 每段 + 历史每条消息的来源与去留。
|
||||
// 入口在聊天页顶栏(「看上下文」),这个浮层盖在上面。
|
||||
AnimatedVisibility(
|
||||
visible = vm.contextViewerConvId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
ContextViewerScreen(vm = vm, onBack = { vm.closeContextViewer() })
|
||||
}
|
||||
|
||||
// 「决斗界面」(v3.17 用户需求:多回合 + 双方同意的中断 + 不开新对话)。
|
||||
// 决斗留在当前对话里,这里只是它的全屏面板;入口 = 长按 @成员 选「决斗」、
|
||||
// 聊天页的决斗条、或「我的角色」页的决斗按钮。
|
||||
AnimatedVisibility(
|
||||
visible = vm.duelScreenOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
DuelScreen(vm = vm, onBack = { vm.closeDuelScreen() })
|
||||
}
|
||||
|
||||
// 「笔记」—— 用户要能查看 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() },
|
||||
)
|
||||
}
|
||||
|
||||
// 世界观的**共享记忆**(从「资源 → 世界观 → 记忆」进来)。
|
||||
//
|
||||
// ★ 它和上面那个是同一个空间(world:<uuid>)的**另一个视角**:
|
||||
// 那边问"玄辰记住了什么",这边问"这个世界里大家共同记得什么"。
|
||||
// 纯只读 —— 写入限权是按 author 判的,而这个视角没有"我"。
|
||||
AnimatedVisibility(
|
||||
visible = vm.worldMemoryId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.worldMemorySpace,
|
||||
agentName = vm.state.worldviews.firstOrNull { it.id == vm.worldMemoryId }?.name
|
||||
?: "世界观",
|
||||
agentId = "",
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
worldMode = true,
|
||||
loading = false,
|
||||
hint = "",
|
||||
onSetEmotion = { _, _ -> },
|
||||
onAdd = { _, _ -> },
|
||||
onUpdate = { _, _, _ -> },
|
||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||
onDelete = { vm.deleteWorldMemory(it) },
|
||||
onTogglePin = { _, _ -> },
|
||||
onSummarize = {},
|
||||
onExport = {},
|
||||
onSetWindow = {},
|
||||
onImportClick = {},
|
||||
onOpenOwn = {},
|
||||
onBackToActive = {},
|
||||
onOpenShared = {},
|
||||
onBackToPrivate = {},
|
||||
onBack = { vm.closeWorldMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「智能体编辑」—— 全屏界面(字段二十多个,弹窗装不下,见 AGENTS.md 那张表)
|
||||
AnimatedVisibility(
|
||||
visible = vm.agentEditOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentEditScreen(
|
||||
vm = vm,
|
||||
initial = vm.agentEditing,
|
||||
onDone = { vm.closeAgentEdit() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「用量」详情 —— 选择界面上的「更多」按钮(需求 2.4 / 3.1)
|
||||
AnimatedVisibility(
|
||||
visible = vm.tokenUsageOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TokenUsageScreen(
|
||||
usage = vm.tokenUsage,
|
||||
onReset = { vm.tokenUsage?.agentId?.takeIf { it.isNotBlank() }?.let { vm.resetTokenUsage(it) } },
|
||||
onBack = { vm.closeTokenUsage() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「记忆」管理(需求 3.2 的"用户手动编辑兜底")
|
||||
AnimatedVisibility(
|
||||
visible = vm.memoryAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.memorySpace,
|
||||
agentName = vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "",
|
||||
agentId = vm.memoryAgentId,
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
loading = vm.memoryLoading,
|
||||
hint = vm.memoryHint,
|
||||
onSetEmotion = { preset, text -> vm.setEmotion(preset, text) },
|
||||
onAdd = { t, c -> vm.addMemory(t, c) },
|
||||
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
|
||||
onDelete = { vm.deleteMemory(it) },
|
||||
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
||||
onSummarize = { vm.summarizeMemories() },
|
||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||
onSetWindow = { vm.setMemoryWindow(it) },
|
||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, shared = false) },
|
||||
onBackToActive = { vm.openMemories(vm.memoryAgentId, shared = false) },
|
||||
onOpenShared = { vm.openMemories(vm.memoryAgentId, shared = true) },
|
||||
onBackToPrivate = { vm.openMemories(vm.memoryAgentId, shared = false) },
|
||||
onBack = { vm.closeMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「新建群聊」:挑一个搭子(当前智能体当主角 = 主智能体)
|
||||
// [世界包编辑](v3.0:世界观 + 规则包合并)—— 全屏
|
||||
AnimatedVisibility(
|
||||
visible = vm.editingWorldPack != null,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
WorldPackEditScreen(vm = vm, onBack = { vm.closeWorldPackEdit() })
|
||||
}
|
||||
|
||||
// 「群成员」(v1.2 §3.9)—— 用户手动增删成员无条件
|
||||
AnimatedVisibility(
|
||||
visible = vm.membersConvId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
GroupMembersScreen(
|
||||
vm = vm,
|
||||
conversationId = vm.membersConvId,
|
||||
onBack = { vm.closeMembers() },
|
||||
// 成员行上的「状态」→ 开 [状态数值](三个入口之一)
|
||||
onOpenStats = { vm.openStats(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// [状态数值](v1.2 §3.10 / §3.11)—— 三个入口共用这一个界面:
|
||||
// 聊天页的状态栏、智能体编辑的"它的状态"、群成员的「状态」按钮
|
||||
AnimatedVisibility(
|
||||
visible = vm.statsAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentStatsScreen(
|
||||
vm = vm,
|
||||
agentId = vm.statsAgentId,
|
||||
onBack = { vm.closeStats() },
|
||||
)
|
||||
}
|
||||
|
||||
// 导入记忆:先读文件,再让用户选**合并还是覆盖**(复查报告 4.2.4)。
|
||||
//
|
||||
// ★ 默认是合并:覆盖是破坏性的,用户点错一次就全没了。
|
||||
// 所以「覆盖」那个按钮上直接写清后果 —— 不给"确定/取消"这种看不出区别的选项。
|
||||
pendingImportJson?.let { text ->
|
||||
val count = runCatching {
|
||||
org.json.JSONObject(text).optJSONArray("smartMemory")?.length() ?: 0
|
||||
}.getOrDefault(0)
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { pendingImportJson = null },
|
||||
title = { Text("怎么导入", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"这个文件里有 $count 条记忆。\n\n" +
|
||||
"合并:只加没有的(按标题判重),现有的全留着,情绪也不动。\n" +
|
||||
"覆盖:先把现在这 ${vm.memorySpace?.memories?.size ?: 0} 条全删掉," +
|
||||
"再换成文件里的,情绪也一起换掉。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { pendingImportJson = null; vm.importMemories(text, "merge") },
|
||||
) { Text("合并(推荐)") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { pendingImportJson = null; vm.importMemories(text, "replace") },
|
||||
) { Text("覆盖", color = androidx.compose.ui.graphics.Color(0xFFD93025)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 拿到 JSON 之后再弹存盘对话框(先有内容才能给文件名,顺序不能反)
|
||||
LaunchedEffect(pendingExport) {
|
||||
val text = pendingExport ?: return@LaunchedEffect
|
||||
if (text.isNotBlank()) {
|
||||
runCatching {
|
||||
createMemoryDoc.launch(
|
||||
"${vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "agent"}-记忆.json",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 「超时」—— 所有超时都能调(入口在设置页)
|
||||
AnimatedVisibility(
|
||||
visible = vm.timeoutsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TimeoutsScreen(
|
||||
state = vm.timeouts,
|
||||
saving = vm.timeoutsSaving,
|
||||
onSave = { vm.saveTimeouts(it) },
|
||||
onReset = { vm.resetTimeouts() },
|
||||
onBack = { vm.closeTimeouts() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。
|
||||
// 排在 HTML 界面之下:点一个就从列表进到界面。
|
||||
AnimatedVisibility(
|
||||
visible = vm.aiScreenListOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AiScreenListScreen(
|
||||
screens = vm.aiScreenList,
|
||||
onOpen = { vm.reopenAiScreen(it) },
|
||||
onDelete = { vm.deleteAiScreen(it) },
|
||||
onClose = { vm.dismissAiScreenList() },
|
||||
)
|
||||
}
|
||||
|
||||
AiHtmlScreenOverlay(
|
||||
screen = vm.aiScreen,
|
||||
onClose = { vm.closeAiScreen() },
|
||||
onResult = { vm.onAiScreenResult(it, vm.aiScreen?.waiting == true) },
|
||||
autoCloseOnResult = vm.aiScreen?.waiting == true,
|
||||
)
|
||||
AiDialogOverlay(
|
||||
dialog = vm.aiDialog,
|
||||
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||
)
|
||||
|
||||
// ★ v3.30:常驻角色 —— 输入框打 `>` → 角色菜单 → 功能菜单 → 全屏 HTML 页。
|
||||
// 页面里的表单调的是**和 AI 工具同一个内核接口**(见 ResidentScreens.kt)。
|
||||
if (vm.residentMenuOpen) {
|
||||
ResidentMenuDialog(
|
||||
loading = vm.residentMenuLoading,
|
||||
residents = vm.residentMenu,
|
||||
hint = vm.residentMenuHint,
|
||||
onPick = { vm.pickResident(it) },
|
||||
onDismiss = { vm.dismissResidentMenu() },
|
||||
)
|
||||
}
|
||||
vm.residentPicked?.let { resident ->
|
||||
ResidentFunctionsDialog(
|
||||
resident = resident,
|
||||
onPick = { fn -> vm.openResidentPage(resident, fn.id, fn.name) },
|
||||
onDismiss = { vm.dismissResidentFunctions() },
|
||||
)
|
||||
}
|
||||
vm.residentPage?.let { page ->
|
||||
ResidentPageScreen(
|
||||
page = page,
|
||||
pageUrl = vm.client.residentPageUrl(
|
||||
containerId = page.containerId,
|
||||
instanceId = page.instanceId,
|
||||
function = page.functionId,
|
||||
conversationId = vm.activeConversationId,
|
||||
),
|
||||
onClose = { vm.closeResidentPage() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「网页」界面(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页显示之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
AnimatedVisibility(
|
||||
visible = vm.pickUrlFrom.isNotEmpty() || vm.urlPickerOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
UrlListScreen(
|
||||
owner = "这条回复",
|
||||
urls = vm.pickUrlFrom,
|
||||
onPick = { vm.openTypedUrl(it) },
|
||||
onClose = { vm.dismissUrlPicker() },
|
||||
)
|
||||
}
|
||||
|
||||
// 全屏看网页(点消息下方「打开网页」按钮进来)
|
||||
AnimatedVisibility(
|
||||
visible = vm.webPage != null,
|
||||
enter = slideInVertically(tween(240)) { it / 5 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 6 } + fadeOut(tween(150)),
|
||||
) {
|
||||
vm.webPage?.let { url ->
|
||||
WebPageScreen(
|
||||
url = url,
|
||||
onClose = { vm.closeWebPage() },
|
||||
// 用户在网页上点选 → 发回给 AI。走的是**普通发消息**那条路
|
||||
// (所以会正常显示在对话里、正常存历史),而不是什么隐藏通道 ——
|
||||
// 用户能看见自己"发了什么",也能反悔(重新生成)。
|
||||
onSendToAi = { text ->
|
||||
vm.closeWebPage()
|
||||
vm.sendExternal(text)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 提示条(吐司)----------------
|
||||
*
|
||||
* ★★ v3.28:**必须放在这个 Box 的最后**(所有全屏浮层之上)。
|
||||
* 以前它在抽屉后面、地图/容器/决斗这些 AnimatedVisibility **之前** ——
|
||||
* 于是地图页里「移不了:两个地点不相邻」这类提示被地图整个盖住,
|
||||
* 用户只看到"点了没反应"(原话「无法移动,无法移人」)。
|
||||
* 提示条是全局反馈,任何页面(尤其全屏浮层)出错都得看得见。
|
||||
*/
|
||||
if (vm.hint.isNotBlank()) {
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(24.dp)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(Color(0xE61F2329))
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 抽屉 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DrawerOverlay(vm: AppViewModel) {
|
||||
Row(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxHeight()
|
||||
.width(300.dp)
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 20.dp, end = 16.dp, top = 18.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("小人间", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Icon(
|
||||
Icons.Filled.Search, "搜索", tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable { vm.showHint("搜索还没做") },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 抽屉分两层(改过一次,用户反馈"太挤了对话都没了")。
|
||||
*
|
||||
* 原来 9 个入口平铺,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能(用户 90% 打开抽屉是为了切对话)。
|
||||
*
|
||||
* 现在:
|
||||
* · 第一层只放**天天用的**三个:新话题 / 智能体 / 笔记
|
||||
* · 其余的收进「更多功能」一个入口,点开是独立全屏页(按项目约定,
|
||||
* 列表这种要滚动的东西不用弹窗或折叠面板)
|
||||
*/
|
||||
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
|
||||
// ★ 分组标题的留白也一起放松 —— 只加项间距的话,
|
||||
// 标题会和第一项粘在一起,看着像"标题属于上一组"
|
||||
SectionLabel("功能", Modifier.padding(start = 22.dp, top = 14.dp, bottom = 6.dp))
|
||||
// ★★ 抽屉第一层**只留四件天天用的**(用户明确说"太挤了"、
|
||||
// "把别的放更多里"):
|
||||
//
|
||||
// 开启新话题 · 智能体 · 记忆 · 更多功能
|
||||
//
|
||||
// 笔记 / 模型 / 新建群聊都挪进「更多功能」了。
|
||||
// 「模型」虽然也常用,但它是个**配置**(配好基本不动),
|
||||
// 腾出来的位置留给底下的对话列表更值 ——
|
||||
// 而对话列表才是用户 90% 打开抽屉的目的。
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
|
||||
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
|
||||
vm.screen = Screen.AgentSelect; vm.drawerOpen = false
|
||||
}
|
||||
// ★「记忆」:当前这个智能体记住了什么。
|
||||
// 给它一个抽屉直达入口,因为这是**日常要看**的东西 ——
|
||||
// 你得知道它记对没记错(AI 记反了"喜欢猫/讨厌猫"这种事很常见)。
|
||||
DrawerItem(Icons.Filled.Psychology, "记忆") {
|
||||
vm.drawerOpen = false
|
||||
vm.activeAgent?.id?.let { vm.openMemories(it) }
|
||||
}
|
||||
DrawerItem(Icons.Filled.Apps, "更多功能") {
|
||||
vm.drawerOpen = false
|
||||
vm.moreSheetOpen = true
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
|
||||
// ★ v3.0 P2/P5:会话**按容器分组** —— 一局就是一个分组。
|
||||
//
|
||||
// 容器是 v3.0 的"这一局":数值/状态/物品/位置都按它隔离,所以
|
||||
// 抽屉里按容器分组,用户一眼就知道"哪几个对话是同一局的"。
|
||||
// 组标题 = 容器名(· 世界包名);单聊容器的名字就是那个角色。
|
||||
// 私聊记录(两个 AI 幕后聊的)和没归属的老会话归到「其他」。
|
||||
val containers = vm.state.containers
|
||||
val byContainer = vm.state.conversations
|
||||
.filter { it.type != "private" }
|
||||
.groupBy { it.containerId }
|
||||
val privates = vm.state.conversations.filter { it.type == "private" }
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
for (c in containers) {
|
||||
val convs = byContainer[c.id] ?: emptyList()
|
||||
if (convs.isEmpty()) continue
|
||||
item(key = "sec-${c.id}") {
|
||||
val title = c.name.ifBlank { "容器" } +
|
||||
(if (c.worldPackName.isNotBlank()) " · ${c.worldPackName}" else "")
|
||||
SectionLabel(title, Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
|
||||
}
|
||||
items(convs.size, key = { i -> convs[i].id }) { i ->
|
||||
ConversationRow(vm, convs[i])
|
||||
}
|
||||
}
|
||||
val orphans = (byContainer[""] ?: emptyList()) + privates
|
||||
if (orphans.isNotEmpty()) {
|
||||
item {
|
||||
SectionLabel(
|
||||
if (containers.isEmpty()) "对话" else "其他",
|
||||
Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
items(orphans.size, key = { i -> orphans[i].id }) { i ->
|
||||
ConversationRow(vm, orphans[i])
|
||||
}
|
||||
}
|
||||
if (vm.state.conversations.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"还没有任何会话。点上面的「开启新话题」挑一个智能体。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.screen = Screen.Profile; vm.drawerOpen = false }
|
||||
.padding(horizontal = 20.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).background(Doubao.Blue),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(vm.settings.nickname.take(1), color = Color.White, fontSize = 14.sp)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(vm.settings.nickname, fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.background(Doubao.Scrim)
|
||||
.clickable { vm.drawerOpen = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerItem(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
trailing: String = "",
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val bg by animateColorAsState(
|
||||
targetValue = if (pressed) doubaoCard() else Color.Transparent,
|
||||
animationSpec = tween(120),
|
||||
label = "itemBg",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
// ★ 项之间的留白从 2dp 提到 6dp、项内从 13dp 提到 16dp。
|
||||
// 原来每项视觉高度只有 ~48dp,七项叠在一起糊成一片 ——
|
||||
// 用户反馈"太挤了"。现在每项 ~60dp,手指点起来也稳。
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Text(label, fontSize = 16.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (trailing.isNotBlank()) {
|
||||
Text(trailing, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConversationRow(vm: AppViewModel, conv: Conversation) {
|
||||
val active = conv.id == vm.activeConversationId
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (active) doubaoCard() else Color.Transparent)
|
||||
.clickable { vm.openConversation(conv.id) }
|
||||
.padding(horizontal = 10.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(RoundedCornerShape(19.dp)).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(conv.title.take(1), color = Doubao.Blue, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(conv.title, fontSize = 15.sp, color = doubaoText(), maxLines = 1)
|
||||
Text(
|
||||
conv.preview.ifBlank { "还没有消息" },
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp).clickable { vm.deleteConversation(conv) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 文案小工具 ------------------------------ */
|
||||
|
||||
fun shortModel(model: String): String = when {
|
||||
model.isBlank() -> "未设置"
|
||||
model.startsWith("ep-") -> "接入点 ${model.take(8)}"
|
||||
model.startsWith("doubao-seed-2-1-pro") -> "豆包 Pro"
|
||||
model.startsWith("doubao-seed-1-8") -> "豆包 1.8"
|
||||
model.startsWith("doubao-seed-1-6") -> "豆包 1.6"
|
||||
model.startsWith("doubao") -> "豆包"
|
||||
model.startsWith("deepseek-r1") -> "DeepSeek R1"
|
||||
model.startsWith("deepseek") -> "DeepSeek"
|
||||
model.startsWith("gpt-5") -> if (model.contains("mini")) "GPT-5 mini" else "GPT-5"
|
||||
model.startsWith("gpt-4o") -> if (model.contains("mini")) "GPT-4o mini" else "GPT-4o"
|
||||
else -> if (model.length > 16) model.take(14) + "…" else model
|
||||
}
|
||||
|
||||
fun thinkingLabel(level: String): String = when (level) {
|
||||
"off" -> "快速"
|
||||
"low" -> "低"
|
||||
"medium" -> "中"
|
||||
"high" -> "深度思考"
|
||||
else -> "自动"
|
||||
}
|
||||
3999
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt
Normal file
3999
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,226 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.ImageView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import java.io.File
|
||||
|
||||
/*
|
||||
* 显示智能体/世界观包里的图片资源。
|
||||
*
|
||||
* ## ★ 为什么不用 Coil / Glide
|
||||
*
|
||||
* 项目一直坚持**零第三方依赖**(安卓端构建要能离线完成、APK 也不要多几百 KB)。
|
||||
* 而这里要的东西其实很窄:显示一个已知路径的本地图片。
|
||||
* Android 原生的三套 API 正好够:
|
||||
*
|
||||
* · PNG / JPG → `BitmapFactory.decodeFile`(所有版本)
|
||||
* · GIF 动图 → `ImageDecoder.decodeDrawable`(API 28+,低版本退化成静态第一帧)
|
||||
* · SVG → 原生**解不了**,走 WebView(项目里已经大量在用 WebView)
|
||||
*
|
||||
* ## 为什么静态图不统一走 ImageView
|
||||
*
|
||||
* 因为 Compose 的 `Image(bitmap)` 在裁剪/圆角/缩放上比 `AndroidView` 包一层
|
||||
* 可控得多(`Modifier.clip` / `ContentScale` 直接生效),而 GIF 又必须用
|
||||
* `Drawable`(Compose 没有原生的动图 Painter,accompanist 是第三方)。
|
||||
* 所以按扩展名分流:常见的静态图走低成本那条,动图才付出 AndroidView 的代价。
|
||||
*
|
||||
* ## 缺失资源的回退(需求 2.6)
|
||||
*
|
||||
* 回退是**调用方**的事(`AgentArtwork` 里判的),这里只负责"路径给了就画"。
|
||||
* 给空路径、文件不存在,这里返回 false 让调用方决定显示什么。
|
||||
*/
|
||||
|
||||
private const val TAG = "DoubaoImage"
|
||||
|
||||
/** 这个文件是哪种图(按扩展名,和内核 uploads.py 一个思路) */
|
||||
private enum class ImageKind { Static, Gif, Svg, Unknown }
|
||||
|
||||
private fun kindOf(path: String): ImageKind = when (File(path).extension.lowercase()) {
|
||||
"gif" -> ImageKind.Gif
|
||||
"svg" -> ImageKind.Svg
|
||||
"png", "jpg", "jpeg", "webp", "bmp" -> ImageKind.Static
|
||||
else -> ImageKind.Unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* 画一张本地图片。
|
||||
*
|
||||
* @param path 绝对路径(内核给的就是绝对路径)
|
||||
* @param fallback 画不出来时显示什么(通常是默认图或一个占位框)
|
||||
*/
|
||||
@Composable
|
||||
fun AssetImage(
|
||||
path: String,
|
||||
modifier: Modifier = Modifier,
|
||||
contentScale: ContentScale = ContentScale.Fit,
|
||||
/**
|
||||
* 裁剪时对齐哪儿。
|
||||
*
|
||||
* ★ 缩略图必须给 `TopCenter`:角色图是**竖长**的(头在上半部分),
|
||||
* 居中对齐裁出来的是"腰到大腿"——列表里一排裤子,谁也认不出是谁。
|
||||
*/
|
||||
alignment: Alignment = Alignment.Center,
|
||||
fallback: @Composable () -> Unit = {},
|
||||
) {
|
||||
val file = remember(path) { if (path.isBlank()) null else File(path) }
|
||||
if (file == null || !file.isFile) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
|
||||
when (kindOf(path)) {
|
||||
ImageKind.Svg -> SvgImage(file, modifier)
|
||||
ImageKind.Gif -> DrawableImage(file, modifier, contentScale, alignment, fallback)
|
||||
else -> StaticImage(file, modifier, contentScale, alignment, fallback)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StaticImage(
|
||||
file: File,
|
||||
modifier: Modifier,
|
||||
contentScale: ContentScale,
|
||||
alignment: Alignment,
|
||||
fallback: @Composable () -> Unit,
|
||||
) {
|
||||
// ★ remember(file.path):同一张图不重复解码。列表里滚动时这一下省很多。
|
||||
val bitmap = remember(file.path) {
|
||||
runCatching { BitmapFactory.decodeFile(file.path) }.getOrNull()
|
||||
}
|
||||
if (bitmap == null) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = modifier,
|
||||
contentScale = contentScale,
|
||||
alignment = alignment,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 动图(GIF)。
|
||||
*
|
||||
* ★ API 28 以下 `ImageDecoder` 不存在 —— 退回 `BitmapFactory` 拿第一帧,
|
||||
* 至少不是空白。项目 minSdk 是 24,所以这条分支真的会走到。
|
||||
*/
|
||||
@Composable
|
||||
private fun DrawableImage(
|
||||
file: File,
|
||||
modifier: Modifier,
|
||||
contentScale: ContentScale,
|
||||
alignment: Alignment,
|
||||
fallback: @Composable () -> Unit,
|
||||
) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
|
||||
StaticImage(file, modifier, contentScale, alignment, fallback)
|
||||
return
|
||||
}
|
||||
val drawable: Drawable? = remember(file.path) {
|
||||
runCatching {
|
||||
// ★ 宽度在 `info` 上(`ImageDecoder` 自己只有 setTargetSampleSize)——
|
||||
// 写成 `decoder.width` 是编译不过的
|
||||
ImageDecoder.decodeDrawable(ImageDecoder.createSource(file)) { decoder, info, _ ->
|
||||
// 缩到 1024 以内:包里的图可能很大,全尺寸解码在低端机上会 OOM
|
||||
val w = info.size.width
|
||||
if (w > 1024) decoder.setTargetSampleSize(kotlin.math.round(w / 1024f).coerceAtLeast(1f).toInt())
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
if (drawable == null) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
ImageView(ctx).apply {
|
||||
setImageDrawable(drawable)
|
||||
scaleType = when (contentScale) {
|
||||
ContentScale.Crop -> ImageView.ScaleType.CENTER_CROP
|
||||
ContentScale.FillBounds -> ImageView.ScaleType.FIT_XY
|
||||
else -> ImageView.ScaleType.FIT_CENTER
|
||||
}
|
||||
}
|
||||
},
|
||||
// 动图由 Drawable 自己驱动,不需要在 update 里做任何事;
|
||||
// 但路径变了要换图 —— 这个 composable 的 key 已经是路径,重建即可。
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG。
|
||||
*
|
||||
* ★ 原生解不了 SVG(`BitmapFactory` 直接返回 null),而引一个 SVG 库
|
||||
* 就破了"零第三方依赖"。项目里已经有成熟的 WebView 通道
|
||||
* (AI 界面就全靠它),所以这里用 WebView 单图显示。
|
||||
*
|
||||
* ★ 关掉一切交互:它是**背景/装饰**,不能抢走列表的滑动和点击。
|
||||
*/
|
||||
@Composable
|
||||
private fun SvgImage(file: File, modifier: Modifier) {
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
android.webkit.WebView(ctx).apply {
|
||||
setBackgroundColor(android.graphics.Color.TRANSPARENT)
|
||||
settings.javaScriptEnabled = false
|
||||
settings.allowFileAccess = true
|
||||
isClickable = false
|
||||
isFocusable = false
|
||||
// 让触摸穿透到下面的列表(不然在列表里滑动会被 WebView 吃掉)
|
||||
setOnTouchListener { _, _ -> false }
|
||||
loadDataWithBaseURL(
|
||||
"file://" + file.parent + "/",
|
||||
"""<html><head><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<style>html,body{margin:0;padding:0;background:transparent;height:100%}
|
||||
img{width:100%;height:100%;object-fit:contain}</style></head>
|
||||
<body><img src="${file.name}"></body></html>""",
|
||||
"text/html", "UTF-8", null,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 占位:没有图时显示一个淡淡的灰框 + 可选文字(需求 2.6 的"简单方框") */
|
||||
@Composable
|
||||
fun ImagePlaceholder(modifier: Modifier = Modifier, text: String = "") {
|
||||
Box(
|
||||
modifier.then(Modifier.fillMaxSize()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (text.isNotBlank()) {
|
||||
Text(text, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 图片能不能画出来(调用方据此决定要不要回退到默认资源) */
|
||||
fun canShowImage(path: String): Boolean {
|
||||
if (path.isBlank()) return false
|
||||
val f = File(path)
|
||||
if (!f.isFile) {
|
||||
Log.w(TAG, "图片不存在:$path")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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.BagItem
|
||||
|
||||
/**
|
||||
* [背包](v3.0 P3):一行物品按分类分组 + 用户手动操作。
|
||||
*
|
||||
* 物品是**容器隔离**的:同一个角色在世界 A 的丹药不会带到世界 B。
|
||||
* 所以这个页面必须知道"哪一局、看谁的背包"—— 进来就带好这两个参数。
|
||||
*
|
||||
* ★ 用户手动操作和 AI 走**同一个** item_engine(使用/抛弃/赠与),
|
||||
* 这里不写第二套数量逻辑 —— 两套逻辑迟早会有一份算错。
|
||||
*
|
||||
* ★ 全屏而不是弹窗(AGENTS.md):物品可能很多、要按分类滚、点开有详情。
|
||||
*/
|
||||
@Composable
|
||||
fun BagScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val container = vm.bagContainer()
|
||||
val members = container?.members ?: emptyList()
|
||||
val agents = vm.state.agents
|
||||
val agentName = agents.firstOrNull { it.id == vm.bagAgentId }?.name ?: "成员"
|
||||
|
||||
var selectedId by remember { mutableStateOf("") }
|
||||
var giveTarget by remember { mutableStateOf<String?>(null) }
|
||||
// target 类物品"对谁使用"的临时选择
|
||||
var useTarget by remember { mutableStateOf("") }
|
||||
// ★ v3.21:带材料使用(工作台这类物品要材料)
|
||||
var useWithId by remember { mutableStateOf("") }
|
||||
var useWithPicked by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
|
||||
FullScreen(
|
||||
title = "背包",
|
||||
subtitle = "${container?.name?.ifBlank { "容器" } ?: "容器"} · $agentName",
|
||||
onBack = onBack,
|
||||
) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
// ---- 成员切换(同一容器里换一个人看) ----
|
||||
if (members.size > 1) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for (aid in members) {
|
||||
val name = agents.firstOrNull { it.id == aid }?.name ?: "成员"
|
||||
val on = aid == vm.bagAgentId
|
||||
Text(
|
||||
name,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { selectedId = ""; vm.bagSwitchAgent(aid) }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vm.bagItems.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text(
|
||||
if (vm.bagLoading) "正在读背包……"
|
||||
else "这个成员还没有物品。\n世界包定义 items[].initial 之后,成员第一次进这一局就会自动发。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 20.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
// ---- 按分类分组的物品列表 ----
|
||||
val groups = vm.bagItems.groupBy { it.category.ifBlank { "其他" } }
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for ((category, items) in groups) {
|
||||
item(key = "cat-$category") { SectionLabel(category) }
|
||||
items(items, key = { it.id }) { it ->
|
||||
BagRow(
|
||||
vm = vm,
|
||||
item = it,
|
||||
expanded = selectedId == it.id,
|
||||
members = members,
|
||||
agents = agents,
|
||||
useTarget = useTarget,
|
||||
onUseTarget = { useTarget = it },
|
||||
onToggle = {
|
||||
selectedId = if (selectedId == it.id) "" else it.id
|
||||
},
|
||||
onGive = { giveTarget = it.id },
|
||||
onUseWith = { useWithId = it.id; useWithPicked = emptySet() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 赠与:选目标
|
||||
val giveItem = vm.bagItems.firstOrNull { it.id == giveTarget }
|
||||
if (giveTarget != null && giveItem != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { giveTarget = null },
|
||||
title = { Text("把「${giveItem.name}」送给谁?") },
|
||||
text = {
|
||||
Column {
|
||||
for (aid in members) {
|
||||
if (aid == vm.bagAgentId) continue
|
||||
val name = agents.firstOrNull { it.id == aid }?.name ?: "成员"
|
||||
Text(
|
||||
name,
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.bagAction(giveItem.id, "give", 1, target = name)
|
||||
giveTarget = null
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { giveTarget = null }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 带材料使用:选要一起用掉的物品(工作台这类脚本要 api.attached)
|
||||
val useWithBag = vm.bagItems.firstOrNull { it.id == useWithId }
|
||||
if (useWithBag != null) {
|
||||
val others = vm.bagItems.filter { it.id != useWithBag.id && it.count != 0 }
|
||||
AlertDialog(
|
||||
onDismissRequest = { useWithId = "" },
|
||||
title = { Text("带上材料使用「${useWithBag.name}」") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"选要一起用掉的物品(脚本通过 api.attached 读到)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
if (others.isEmpty()) {
|
||||
Text("背包里没有别的物品可带。", fontSize = 13.sp,
|
||||
color = doubaoTextSecondary())
|
||||
}
|
||||
for (o in others) {
|
||||
val on = o.id in useWithPicked
|
||||
val cnt = if (o.count < 0) "∞" else "×${o.count}"
|
||||
Text(
|
||||
(if (on) "✓ " else "") + "${o.name}$cnt",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
useWithPicked = if (on) useWithPicked - o.id
|
||||
else useWithPicked + o.id
|
||||
}
|
||||
.padding(vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.bagAction(useWithBag.id, "use", with = useWithPicked.toList())
|
||||
useWithId = ""
|
||||
}) { Text("使用") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { useWithId = "" }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BagRow(
|
||||
vm: AppViewModel,
|
||||
item: BagItem,
|
||||
expanded: Boolean,
|
||||
members: List<String>,
|
||||
agents: List<com.doubao.lynxclone.data.Agent>,
|
||||
useTarget: String,
|
||||
onUseTarget: (String) -> Unit,
|
||||
onToggle: () -> Unit,
|
||||
onGive: () -> Unit,
|
||||
onUseWith: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { onToggle() }
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
item.name,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
item.countLabel,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
KindTag(item.kindLabel)
|
||||
if (item.desc.isNotBlank()) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
item.desc,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!expanded) return@Column
|
||||
|
||||
// ---- 详情:脚本 + 用户手动操作(用户主权)----
|
||||
if (item.script.isNotBlank()) {
|
||||
Text("脚本:${item.script}", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
if (item.used > 0) {
|
||||
Text("累计用过 ${item.used} 次", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (item.usable) {
|
||||
if (item.kind == "target") {
|
||||
// 目标类:先选一个同容器成员(默认第一个别人)
|
||||
val others = members.filter { it != vm.bagAgentId }
|
||||
val chosen = useTarget.ifBlank { others.firstOrNull() ?: "" }
|
||||
val chosenName = agents.firstOrNull { it.id == chosen }?.name ?: "无目标"
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable {
|
||||
if (others.isEmpty()) return@clickable
|
||||
val idx = others.indexOf(chosen)
|
||||
onUseTarget(others[(idx + 1) % others.size])
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text("目标:$chosenName ⇄", fontSize = 12.sp, color = doubaoText())
|
||||
}
|
||||
Text(
|
||||
"使用",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable(enabled = chosen.isNotBlank()) {
|
||||
val target = agents.firstOrNull { it.id == chosen }?.name ?: ""
|
||||
vm.bagAction(item.id, "use", targets = listOf(target))
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
"使用",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable { vm.bagAction(item.id, "use") }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
// ★ v3.21:带材料使用(工作台这类物品要材料)
|
||||
Text(
|
||||
"带材料用",
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onUseWith() }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"抛弃 1 个",
|
||||
fontSize = 13.sp,
|
||||
color = Color(0xFFD93025),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.clickable { vm.bagAction(item.id, "drop", 1) }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
Text(
|
||||
"赠与",
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.clickable(enabled = members.any { it != vm.bagAgentId }) { onGive() }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 类型标签(主动 / 被动 / 目标 / 无脚本) */
|
||||
@Composable
|
||||
private fun KindTag(label: String) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(5.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.padding(horizontal = 5.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
144
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/ChatDuel.kt
Normal file
144
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/ChatDuel.kt
Normal file
@@ -0,0 +1,144 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* ★ v3.17:聊天页的**决斗条**(用户要求「决斗加个ui但不开新对话,和私密一样」)。
|
||||
*
|
||||
* 决斗绑**当前对话**、不另开会话 —— 这条就是它的状态条:
|
||||
* · 进行中:`阿玄 vs 豆包 · 决斗中 · 第 2/6 回合` + 「出招」(推进一回合)
|
||||
* · 有罢手请求在等用户回应:`「豆包」请求罢手` + 「回应」
|
||||
* · 刚结束/中断:结果一行 + 「关闭」(关掉就不再占地方)
|
||||
* 点条子本身进**决斗界面**(双方数值/状态/回合日志都在那里)。
|
||||
*
|
||||
* ★ 只放"最常用的一步"在条上:出招。请求罢手 / 同意 / 拒绝
|
||||
* 都放决斗界面里 —— 条上塞三个按钮会把标题挤成省略号。
|
||||
*/
|
||||
@Composable
|
||||
fun DuelBar(vm: AppViewModel) {
|
||||
val d = vm.duel ?: return
|
||||
val running = d.running
|
||||
val accent = when {
|
||||
d.interrupted -> Color(0xFF8A6100)
|
||||
running -> Color(0xFFB3261E)
|
||||
else -> doubaoTextSecondary()
|
||||
}
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(accent.copy(alpha = 0.10f))
|
||||
.clickable { vm.openDuelScreen() }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
when {
|
||||
running -> "${d.title()} · ${d.statusText()}"
|
||||
d.interrupted -> "双方停手:${d.result.ifBlank { d.title() }}"
|
||||
else -> "决斗结果(${d.outcomeText().ifBlank { "平局" }}):" +
|
||||
d.result.ifBlank { d.title() }
|
||||
},
|
||||
fontSize = 12.sp,
|
||||
color = accent,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 2,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
when {
|
||||
vm.duelBusy -> Text("…", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
running && d.needsMyAnswer -> DuelChip("回应", accent) { vm.openDuelScreen() }
|
||||
running && d.status == "active" -> DuelChip("出招", accent) { vm.advanceDuel() }
|
||||
running -> Text("等对方回应…", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
else -> DuelChip("关闭", doubaoTextSecondary()) { vm.dismissDuel() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 决斗条上的小按钮 */
|
||||
@Composable
|
||||
private fun DuelChip(text: String, color: Color, onClick: () -> Unit) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 12.sp,
|
||||
color = color,
|
||||
fontWeight = FontWeight.Medium,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(color.copy(alpha = 0.12f))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 3.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.17:**长按 @某人** 弹出的动作菜单(用户要求「长按@XX可选私聊和决斗」)。
|
||||
*
|
||||
* 就两个入口,点完就走 —— 按项目约定这种纯菜单用 AlertDialog 是合适的
|
||||
* (列表/配置那种才必须开全屏)。
|
||||
*/
|
||||
@Composable
|
||||
fun MemberActionDialog(vm: AppViewModel) {
|
||||
if (vm.memberMenuAgentId.isBlank()) return
|
||||
val name = vm.memberMenuAgentName
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.closeMemberMenu() },
|
||||
title = { Text("对「$name」") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"🔒 私聊:接下来你发的消息只有 TA 能看到(不另开会话)",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"决斗:在当前对话里开一场一对一决斗,回合由世界脚本裁决;" +
|
||||
"想中断得双方都同意。必须有武器 —— 武器是 target 类物品" +
|
||||
"(能对别人用的东西),没有的一方会被直接判失败。",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"每回合双方各用自己的武器出手一次(跑物品脚本,∞ 武器不消耗)," +
|
||||
"决斗界面里可以每回合换武器;没有回合上限。" +
|
||||
"结果只有四种:赢 / 输 / 平局 / 停手。",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { vm.memberMenuPrivate() }) {
|
||||
Text("私聊")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { vm.memberMenuDuel() }) {
|
||||
Text("决斗")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
1944
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt
Normal file
1944
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,467 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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 org.json.JSONObject
|
||||
|
||||
/**
|
||||
* [容器编辑](v3.0 P2):名字 / 世界包 / 成员。
|
||||
*
|
||||
* 容器 = 一局:世界包 + 成员。数值 / 状态 / 情绪 / 记忆都攒在这一局里,
|
||||
* 所以这里选什么,直接决定"进去之后看到哪套规则、读写哪份记忆"。
|
||||
*
|
||||
* ★ 全屏而不是弹窗(AGENTS.md):字段有三组,弹窗里要滚,还会盖住列表。
|
||||
*
|
||||
* ★ 删除的级联写清楚:**这局里的会话一起删、数值状态记忆一起消失**,
|
||||
* 但智能体本身不会删。用户点删除前必须知道这些 —— 否则删完才发现
|
||||
* "运营了一个月的数值没了",那是一次不可逆的信任损失。
|
||||
*/
|
||||
@Composable
|
||||
fun ContainerEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val editing = vm.editingContainer
|
||||
var name by remember(editing?.id) { mutableStateOf(editing?.name ?: "") }
|
||||
var worldPackId by remember(editing?.id) { mutableStateOf(editing?.worldPackId ?: "") }
|
||||
var members by remember(editing?.id) {
|
||||
mutableStateOf((editing?.members ?: emptyList()).toSet())
|
||||
}
|
||||
// ★ v3.4:用户角色(这一局里"用户"是谁 —— 注入给每个成员)
|
||||
var userName by remember(editing?.id) { mutableStateOf(editing?.userName ?: "") }
|
||||
var userDesc by remember(editing?.id) { mutableStateOf(editing?.userDesc ?: "") }
|
||||
var confirmDelete by remember { mutableStateOf(false) }
|
||||
val packs = vm.state.worldviews
|
||||
val agents = vm.state.agents
|
||||
|
||||
// ★★ v3.32:**角色槽位手动分配**(用户要求「小人间用户手动分配」)。
|
||||
//
|
||||
// 槽位定义来自世界包(`info.slots`):每个槽位配了出生地点 / 初始物品 /
|
||||
// 提示词 / 独立 Skill。自动分配 = 内核按"用户槽位 → 成员顺序"填;
|
||||
// 这里让用户自己指定谁坐哪儿(含用户角色),保存时发 `slotAssignments`。
|
||||
//
|
||||
// ★ 槽位定义从世界包 info 里取(新容器还没建,没有服务端分配);
|
||||
// 编辑已有容器且世界包没换时,用服务端返回的 `editing.slots`(带占用者)。
|
||||
val slotDefs: List<com.doubao.lynxclone.data.ContainerSlot> = remember(editing?.id, worldPackId) {
|
||||
if (editing != null && editing.worldPackId == worldPackId) {
|
||||
editing.slots
|
||||
} else {
|
||||
packSlots(packs.firstOrNull { it.id == worldPackId })
|
||||
}
|
||||
}
|
||||
var slotPicks by remember(editing?.id, worldPackId) {
|
||||
mutableStateOf<Map<String, String>>(
|
||||
if (editing != null && editing.worldPackId == worldPackId) {
|
||||
editing.slots.mapNotNull { s ->
|
||||
s.occupantId.takeIf { it.isNotBlank() }?.let { s.id to it }
|
||||
}.toMap()
|
||||
} else {
|
||||
emptyMap<String, String>()
|
||||
},
|
||||
)
|
||||
}
|
||||
var slotMenu by remember { mutableStateOf("") }
|
||||
|
||||
/** 选一个角色坐槽位;如果这个人已经坐在别的槽位,两个槽位**互换**。 */
|
||||
fun chooseSlot(slotId: String, who: String) {
|
||||
val old = slotPicks[slotId] ?: ""
|
||||
val other = slotPicks.entries.firstOrNull { it.key != slotId && it.value == who }?.key
|
||||
val next = slotPicks.toMutableMap()
|
||||
if (other != null) {
|
||||
if (old.isBlank()) next.remove(other) else next[other] = old
|
||||
}
|
||||
next[slotId] = who
|
||||
slotPicks = next
|
||||
}
|
||||
|
||||
/** 保存时提交的分配:null = 让内核自动分配(新容器没手动选时)。 */
|
||||
fun assignmentsToSave(): Map<String, String>? {
|
||||
if (slotDefs.isEmpty()) return null
|
||||
val clean = slotPicks.filter { (sid, who) ->
|
||||
slotDefs.any { it.id == sid } && (who == "user" || who in members)
|
||||
}
|
||||
if (editing == null && clean.isEmpty()) return null
|
||||
// 已有容器:整表提交(空串 = 这个槽位仍走自动分配)
|
||||
return slotDefs.associate { it.id to (clean[it.id] ?: "") }
|
||||
}
|
||||
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
|
||||
FullScreen(
|
||||
title = if (editing == null) "新建容器" else "编辑容器",
|
||||
subtitle = "数值 / 状态 / 情绪 / 记忆都攒在这一局里",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (editing != null) {
|
||||
TopTextAction("删除", danger = true) { confirmDelete = true }
|
||||
}
|
||||
TopAction("保存", enabled = name.isNotBlank()) {
|
||||
vm.saveContainer(
|
||||
name = name.trim(),
|
||||
worldPackId = worldPackId,
|
||||
members = members.toList(),
|
||||
existingId = editing?.id,
|
||||
userName = userName.trim(),
|
||||
userDesc = userDesc.trim(),
|
||||
slotAssignments = assignmentsToSave(),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
SectionLabel("名称")
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it.take(40) },
|
||||
singleLine = true,
|
||||
placeholder = { Text("比如:九州 · 第一局") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
SectionLabel("世界包")
|
||||
Text(
|
||||
"选了世界包,这一局才有数值 / 状态 / 脚本;不选就是普通单聊容器。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
PackChip(
|
||||
label = "无(单聊容器)",
|
||||
selected = worldPackId.isBlank(),
|
||||
) { worldPackId = "" }
|
||||
packs.forEach { w ->
|
||||
PackChip(
|
||||
label = w.name.ifBlank { "未命名世界包" },
|
||||
selected = worldPackId == w.id,
|
||||
) { worldPackId = w.id }
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("你的角色(用户)")
|
||||
Text(
|
||||
"这一局里「你」是谁 —— 名字和介绍会注入给每个成员," +
|
||||
"让它们知道面前站着的是谁(不同容器可以不同)。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = userName,
|
||||
onValueChange = { userName = it.take(20) },
|
||||
singleLine = true,
|
||||
placeholder = { Text("名字,比如:阿玄(留空就是「用户」)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = userDesc,
|
||||
onValueChange = { userDesc = it.take(300) },
|
||||
placeholder = { Text("介绍(可空):身份 / 性格 / 和它们的关系") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
SectionLabel("成员")
|
||||
Text(
|
||||
"同一批智能体可以在多局里,但每局的数值 / 状态 / 记忆各自独立互不干扰。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
if (agents.isEmpty()) {
|
||||
Text("还没有智能体", fontSize = 13.sp, color = doubaoTextDim())
|
||||
}
|
||||
agents.forEach { a ->
|
||||
val on = a.id in members
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (on) doubaoAccentSoft() else doubaoCard())
|
||||
.clickable {
|
||||
members = if (on) members - a.id else members + a.id
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (on) "✓ " else "○ ",
|
||||
fontSize = 14.sp,
|
||||
color = if (on) Doubao.Blue else doubaoTextDim(),
|
||||
)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
a.name.ifBlank { "未命名" },
|
||||
fontSize = 14.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (a.greeting.isNotBlank()) {
|
||||
Text(
|
||||
a.greeting,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ v3.32:**角色槽位手动分配**(用户要求「小人间用户手动分配」)。
|
||||
if (slotDefs.isNotEmpty()) {
|
||||
SectionLabel("角色槽位")
|
||||
Text(
|
||||
"每个槽位决定出场地点、初始物品、提示词和独立 Skill。" +
|
||||
"可以自己指定谁坐哪个槽位(含用户角色);点「自动分配」=" +
|
||||
"保存时按「用户槽位 → 成员顺序」自动坐。槽位满了以后加入的成员" +
|
||||
"按世界包默认配置。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
// ★★ 网格排版(用户要求「槽位ui网格排版」):一行两张卡片,
|
||||
// 每张卡片放 槽位名 / 坐着的角色 / 出生地点 + 「更换」。
|
||||
// 槽位多时一眼能看全,不用一行行往下滚。
|
||||
val memberChoices = agents.filter { it.id in members }
|
||||
.map { it.id to it.name.ifBlank { "未命名" } }
|
||||
slotDefs.chunked(2).forEach { rowSlots ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
rowSlots.forEach { slot ->
|
||||
SlotCard(
|
||||
modifier = Modifier.weight(1f),
|
||||
slot = slot,
|
||||
picked = slotPicks[slot.id] ?: "",
|
||||
members = memberChoices,
|
||||
expanded = slotMenu == slot.id,
|
||||
onToggle = {
|
||||
slotMenu = if (slotMenu == slot.id) "" else slot.id
|
||||
},
|
||||
onChoose = { who ->
|
||||
chooseSlot(slot.id, who)
|
||||
slotMenu = ""
|
||||
},
|
||||
onAuto = {
|
||||
slotPicks = slotPicks - slot.id
|
||||
slotMenu = ""
|
||||
},
|
||||
)
|
||||
}
|
||||
if (rowSlots.size == 1) {
|
||||
Box(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmDelete) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = false },
|
||||
title = { Text("删除这个容器?") },
|
||||
text = {
|
||||
Text(
|
||||
"这一局里的**所有会话**会一起删掉,数值 / 状态 / 记忆也跟着消失。" +
|
||||
"智能体本身不会被删。",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmDelete = false
|
||||
editing?.id?.let { vm.deleteContainer(it) }
|
||||
},
|
||||
) {
|
||||
Text("删除", color = Color(0xFFD93025))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmDelete = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 一张角色槽位卡片(v3.32,**网格排版**:两列,一行两张)。
|
||||
*
|
||||
* 显示:槽位名(用户位打标)/ 坐着谁 / 出生地点 / 「更换 ▾」菜单。
|
||||
* 菜单里可以选用户角色、任一成员、或交回自动分配。
|
||||
*/
|
||||
@Composable
|
||||
private fun SlotCard(
|
||||
modifier: Modifier = Modifier,
|
||||
slot: com.doubao.lynxclone.data.ContainerSlot,
|
||||
picked: String,
|
||||
members: List<Pair<String, String>>,
|
||||
expanded: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
onChoose: (String) -> Unit,
|
||||
onAuto: () -> Unit,
|
||||
) {
|
||||
val occupant = when {
|
||||
picked.isBlank() -> "自动分配"
|
||||
picked == "user" -> "用户角色"
|
||||
else -> members.firstOrNull { it.first == picked }?.second ?: "已移除"
|
||||
}
|
||||
val place = slot.placeName.ifBlank { slot.place }
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
slot.name.ifBlank { slot.id },
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (slot.user) {
|
||||
Text(
|
||||
"用户位",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"坐:$occupant",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
if (place.isNotBlank()) "出生:$place" else "出生:默认地点",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Box {
|
||||
Text(
|
||||
"更换 ▾",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
)
|
||||
DropdownMenu(expanded = expanded, onDismissRequest = onToggle) {
|
||||
DropdownMenuItem(text = { Text("自动分配(按顺序)") }, onClick = onAuto)
|
||||
DropdownMenuItem(text = { Text("用户角色") }, onClick = { onChoose("user") })
|
||||
members.forEach { (id, name) ->
|
||||
DropdownMenuItem(text = { Text(name) }, onClick = { onChoose(id) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 世界包选择胶囊 */
|
||||
@Composable
|
||||
private fun PackChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (selected) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (selected) Doubao.Blue else doubaoCard())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从世界包 `info` 里解析**槽位定义**(v3.32)。
|
||||
*
|
||||
* 新容器还没保存时服务端没有分配结果,所以直接读世界包 `rawInfo` 的 `slots[]`;
|
||||
* 已有容器优先用服务端返回的 `slots`(带占用者,见 `ContainerItem.slots`)。
|
||||
* 只取定义字段(id/name/place/user),占用者在容器那一侧。
|
||||
*/
|
||||
private fun packSlots(
|
||||
w: com.doubao.lynxclone.data.WorldviewItem?,
|
||||
): List<com.doubao.lynxclone.data.ContainerSlot> {
|
||||
val raw = w?.rawInfo ?: return emptyList()
|
||||
return runCatching {
|
||||
val info = JSONObject(raw)
|
||||
val placeNames = HashMap<String, String>()
|
||||
info.optJSONArray("places")?.let { places ->
|
||||
for (i in 0 until places.length()) {
|
||||
val p = places.optJSONObject(i) ?: continue
|
||||
val pid = p.optString("id")
|
||||
if (pid.isNotBlank()) placeNames[pid] = p.optString("name").ifBlank { pid }
|
||||
}
|
||||
}
|
||||
val arr = info.optJSONArray("slots") ?: return@runCatching emptyList()
|
||||
(0 until arr.length()).mapNotNull { i ->
|
||||
val o = arr.optJSONObject(i) ?: return@mapNotNull null
|
||||
val id = o.optString("id").ifBlank { "slot${i + 1}" }
|
||||
val place = o.optString("place")
|
||||
com.doubao.lynxclone.data.ContainerSlot(
|
||||
id = id,
|
||||
name = o.optString("name").ifBlank { "槽位 ${i + 1}" },
|
||||
place = place,
|
||||
placeName = placeNames[place] ?: place,
|
||||
user = o.optBoolean("user"),
|
||||
)
|
||||
}
|
||||
}.getOrElse { emptyList() }
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
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.graphics.Color
|
||||
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.ContainerItem
|
||||
|
||||
/**
|
||||
* [容器] 列表页(v3.0 P2)。
|
||||
*
|
||||
* 容器 = **一局**:世界包 + 成员。数值 / 状态 / 情绪 / 记忆都按它隔离 ——
|
||||
* 同一批智能体可以在不同容器里互不干扰(这是 v3.0 的核心)。
|
||||
*
|
||||
* 这个页面回答两个问题:
|
||||
* 1. 现在有哪几局?每局在哪个世界、里面有谁?
|
||||
* 2. 怎么进某一局聊天 / 改它 / 删它?
|
||||
*
|
||||
* ★ 为什么是**全屏界面**而不是弹窗:见 AGENTS.md「少用弹窗,能开界面就开界面」。
|
||||
* 列表 + 每行带操作 + 随时可能变长,弹窗装不下。
|
||||
*
|
||||
* ★ 点一行 = 进这一局(找该局已有的会话,没有就建一个)—— 这是用户
|
||||
* 用这个页面最高频的动作,所以做成整行可点,而不是藏在菜单里。
|
||||
*/
|
||||
@Composable
|
||||
fun ContainerListScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
FullScreen(
|
||||
title = "容器",
|
||||
subtitle = "一局 = 世界包 + 成员;数值 / 状态 / 记忆按局隔离",
|
||||
onBack = onBack,
|
||||
actions = { TopAction("新建") { vm.openContainerEdit(null) } },
|
||||
) {
|
||||
val containers = vm.state.containers
|
||||
if (containers.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) {
|
||||
Text(
|
||||
"还没有容器。\n点右上角「新建」开一局:选一个世界包、拉几个智能体进来。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 20.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(containers, key = { it.id }) { c -> ContainerRow(vm, c) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ContainerRow(vm: AppViewModel, c: ContainerItem) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { vm.openContainerChat(c) }
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
c.name.ifBlank { "未命名容器" },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// ★ v3.1:在**这一局里再开一个对话**(同一容器的对话共享上下文,
|
||||
// 用户要求"同一容器支持多个对话且上下文不会断")
|
||||
RowAction("新对话") { vm.newConversationInContainer(c) }
|
||||
// ★ v3.0 P4:地图入口(地点/场景在这里看和切)
|
||||
RowAction("地图") { vm.openMap(c.id) }
|
||||
// ★ v3.0 P3:背包也按局看 —— 先选这局里第一个成员,进去还能切人
|
||||
RowAction("背包") {
|
||||
val first = c.members.firstOrNull()
|
||||
if (first == null) vm.showHint("这一局还没有成员,先编辑它加点人")
|
||||
else vm.openBag(c.id, first)
|
||||
}
|
||||
// ★ 编辑入口放在行尾,不抢"点一行进这一局"的主操作
|
||||
RowAction("编辑") { vm.openContainerEdit(c) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
ContainerTag(if (c.isSolo) "单聊容器" else (c.worldPackName.ifBlank { "世界包已删除" }))
|
||||
if (c.gameOver) {
|
||||
// ★ v3.27:用户角色死亡 = 这一局游戏结束(进去还能看历史/复活)
|
||||
Text(
|
||||
"已结束",
|
||||
fontSize = 11.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.padding(start = 6.dp)
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.padding(horizontal = 7.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
" · ${c.memberCount} 人",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
c.memberNames.filter { it.isNotBlank() }.joinToString("、")
|
||||
.ifBlank { "(还没有成员)" },
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text("点一下进入这一局", fontSize = 11.sp, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
|
||||
/** 世界包 / 单聊 的小标签 */
|
||||
@Composable
|
||||
private fun ContainerTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.padding(horizontal = 7.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
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.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
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.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.ContextEntry
|
||||
import com.doubao.lynxclone.data.ContextPreview
|
||||
import com.doubao.lynxclone.data.ContextSection
|
||||
|
||||
/**
|
||||
* **上下文查看器**(v3.16,用户需求)。
|
||||
*
|
||||
* 用户原话:「你做个上下文查看器」—— 起因是「同容器不同对话的上下文会丢」。
|
||||
* 聊天界面只能看到"界面上有哪些消息",看不到模型**实际收到了什么**:
|
||||
* · 同容器其他对话的消息会被并进来(一局 = 一个上下文边界);
|
||||
* · 别的地点 / 第一次到该地点之前 / 超出窗口 / 别人的私聊会被筛掉;
|
||||
* · system prompt 里还有记忆 / 数值 / 地点 / 技能手册一大段。
|
||||
*
|
||||
* 这一页把内核真正组装的那份**摊开**(数据来自
|
||||
* `/api/conversations/<id>/context`,和发消息共用同一个组装函数),
|
||||
* 每条消息都标清楚"从哪来、进没进模型、为什么没进"。
|
||||
*
|
||||
* ★ 为什么必须全屏:内容量远超弹窗能装的(AGENTS.md 的界面约定)。
|
||||
*/
|
||||
@Composable
|
||||
fun ContextViewerScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val data = vm.contextViewerData
|
||||
// 副标题只放"哪一局 · 谁":会话标题往往很长(会被 AI 自动改),
|
||||
// 塞进来会折成两行;它更适合放在下面的概览卡片里。
|
||||
val subtitle = listOfNotNull(
|
||||
data?.containerName?.takeIf { it.isNotBlank() },
|
||||
data?.agentName?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · ")
|
||||
FullScreen(
|
||||
title = "上下文查看器",
|
||||
subtitle = subtitle,
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("刷新") { vm.reloadContextViewer() }
|
||||
},
|
||||
) {
|
||||
when {
|
||||
data == null && vm.contextViewerLoading ->
|
||||
CenterNote("正在组装上下文……")
|
||||
data == null && vm.contextViewerError.isNotBlank() ->
|
||||
CenterNote(vm.contextViewerError)
|
||||
data == null ->
|
||||
CenterNote("没有数据(内核可能还没启动)")
|
||||
else -> ContextViewerBody(vm, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenterNote(text: String) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text(text, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun ContextViewerBody(vm: AppViewModel, data: ContextPreview) {
|
||||
val sections = data.sections
|
||||
val entries = data.history.entries
|
||||
val included = entries.filter { it.included }
|
||||
val excluded = entries.filter { !it.included }
|
||||
val expandedSections = remember { mutableStateMapOf<String, Boolean>() }
|
||||
val expandedEntries = remember { mutableStateMapOf<Int, Boolean>() }
|
||||
val summary = data.history.summary
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// ---- ① 现在能不能发(独自一人的地点会被拦) ----
|
||||
if (data.chat.blocked) {
|
||||
item(key = "guard") {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(androidx.compose.ui.graphics.Color(0x1AD93025))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"现在发不出去:${data.chat.message.ifBlank { "这里只有你一个人" }}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = androidx.compose.ui.graphics.Color(0xFFB3261E),
|
||||
)
|
||||
if (data.chat.hint.isNotBlank()) {
|
||||
Text(
|
||||
data.chat.hint,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ② 说明(为什么看起来"少了/多了"消息) ----
|
||||
if (data.notices.isNotEmpty()) {
|
||||
item(key = "notices") {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Text("说明", fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
for (n in data.notices) {
|
||||
Text(
|
||||
"· $n",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ③ 概览 + 统计 ----
|
||||
item(key = "overview") {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text("这一轮 AI 看到什么", fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
InfoLine("会话", data.convTitle.ifBlank { "(未命名)" })
|
||||
InfoLine("容器 / 地点",
|
||||
listOfNotNull(data.containerName.ifBlank { null }, data.placeName.ifBlank { null })
|
||||
.joinToString(" · ").ifBlank { "(没有)" })
|
||||
InfoLine("模型", data.modelName.ifBlank { "(未配置)" })
|
||||
InfoLine("system prompt", "${data.promptChars} 字")
|
||||
InfoLine("历史消息", "${included.size} 条进模型(共取到 ${summary["total"] ?: entries.size} 条)")
|
||||
if ((summary["fromOtherConvs"] ?: 0) > 0) {
|
||||
InfoLine("其中别的对话", "同容器其他对话并进来 ${summary["fromOtherConvs"]} 条")
|
||||
}
|
||||
val drops = listOfNotNull(
|
||||
(summary["droppedPlace"] ?: 0).takeIf { it > 0 }?.let { "别的地点 $it 条" },
|
||||
(summary["droppedEnter"] ?: 0).takeIf { it > 0 }?.let { "第一次到该地点之前 $it 条" },
|
||||
(summary["droppedWindow"] ?: 0).takeIf { it > 0 }?.let { "超出窗口 $it 条" },
|
||||
(summary["droppedPrivate"] ?: 0).takeIf { it > 0 }?.let { "别人的私聊 $it 条" },
|
||||
)
|
||||
if (drops.isNotEmpty()) {
|
||||
InfoLine("没带进来", drops.joinToString(";"))
|
||||
}
|
||||
val rounds = summary["totalRounds"] ?: 0
|
||||
if (rounds > 1) {
|
||||
InfoLine(
|
||||
"上下文窗口",
|
||||
"保留最近 ${summary["keptRounds"] ?: rounds} 轮 / 共 $rounds 轮" +
|
||||
if ((summary["droppedWindow"] ?: 0) > 0) "" else "(没触发裁剪)",
|
||||
)
|
||||
}
|
||||
if (data.tools.isNotEmpty()) {
|
||||
InfoLine("可用工具", "${data.tools.size} 个:${data.tools.take(8).joinToString("、")}" +
|
||||
if (data.tools.size > 8) "…" else "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ④ 视角切换(群聊里每个人看到的不一样:私聊/记忆/前缀) ----
|
||||
if (data.isGroup && data.agentChoices.size > 1) {
|
||||
item(key = "agents") {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text("从谁的视角看", fontSize = 12.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 6.dp))
|
||||
// ★ v3.26:人数多的时候 Row 会横向溢出(最后一个人名被挤成竖排)——
|
||||
// 改成 FlowRow,按实际宽度自动换行;人再多也不会溢出。
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for ((aid, name) in data.agentChoices) {
|
||||
val on = aid == data.agentId
|
||||
Text(
|
||||
name,
|
||||
fontSize = 12.sp,
|
||||
color = if (on) androidx.compose.ui.graphics.Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { vm.switchContextViewerAgent(aid) }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ⑤ system prompt(逐段) ----
|
||||
item(key = "prompt-label") {
|
||||
SectionLabel("实际送进模型的 system prompt(${sections.size} 段)")
|
||||
}
|
||||
itemsIndexed(sections, key = { _, s -> "sec-${s.name}" }) { _, sec ->
|
||||
SectionCard(
|
||||
sec = sec,
|
||||
expanded = expandedSections[sec.name] ?: (sec.chars <= 300),
|
||||
onToggle = { expandedSections[sec.name] = !(expandedSections[sec.name] ?: (sec.chars <= 300)) },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- ⑥ 历史消息(每条标明来源) ----
|
||||
item(key = "history-label") {
|
||||
SectionLabel("送进模型的历史消息(${included.size} 条,按时间序)")
|
||||
}
|
||||
if (included.isEmpty()) {
|
||||
item(key = "history-empty") {
|
||||
Text(
|
||||
"一条都没有 —— 这是新对话,或者这个角色什么都看不到(检查上面的说明)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
itemsIndexed(included, key = { i, e -> "in-$i-${e.at}-${e.content.take(8)}" }) { index, e ->
|
||||
EntryCard(
|
||||
e = e,
|
||||
expanded = expandedEntries[index] ?: false,
|
||||
onToggle = { expandedEntries[index] = !(expandedEntries[index] ?: false) },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- ⑦ 没带进来的消息(给"上下文怎么丢了"一个明确答案) ----
|
||||
if (excluded.isNotEmpty()) {
|
||||
item(key = "excluded-label") {
|
||||
SectionLabel("没带进来的消息(${excluded.size} 条 —— 原因写在每条上)")
|
||||
}
|
||||
itemsIndexed(excluded, key = { i, e -> "out-$i-${e.at}-${e.content.take(8)}" }) { index, e ->
|
||||
ExcludedCard(
|
||||
e = e,
|
||||
expanded = expandedEntries[10000 + index] ?: false,
|
||||
onToggle = { expandedEntries[10000 + index] = !(expandedEntries[10000 + index] ?: false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
item(key = "footer") {
|
||||
Text(
|
||||
"说明:这里展示的就是内核组装好、正要交给模型的那一份(和真正发消息走同一个函数)。" +
|
||||
"「同容器其他对话」会并进来,是因为同一局 = 一个上下文边界;" +
|
||||
"地点 / 第一次进入之前 / 上下文窗口 / 别人的私聊按规则看不到。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextDim(),
|
||||
modifier = Modifier.padding(top = 6.dp, bottom = 24.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InfoLine(label: String, value: String) {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(label, fontSize = 11.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.width(96.dp))
|
||||
Text(value, fontSize = 11.sp, lineHeight = 17.sp, color = doubaoText(),
|
||||
modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionCard(
|
||||
sec: ContextSection,
|
||||
expanded: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
sec.label.ifBlank { sec.name },
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (sec.empty) "空段(整段没注入)" else "${sec.chars} 字",
|
||||
fontSize = 10.sp,
|
||||
color = if (sec.empty) doubaoTextDim() else doubaoTextSecondary(),
|
||||
)
|
||||
if (!sec.empty) {
|
||||
Text(
|
||||
if (expanded) " 收起" else " 展开",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!sec.empty && expanded) {
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
thickness = 0.5.dp,
|
||||
)
|
||||
Text(
|
||||
sec.text,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 17.sp,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryCard(e: ContextEntry, expanded: Boolean, onToggle: () -> Unit) {
|
||||
val isUser = e.role == "user"
|
||||
val sourceText = if (e.source == "other") {
|
||||
"同容器对话「${e.convTitle.ifBlank { "另一个" }}」"
|
||||
} else {
|
||||
"本对话"
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
if (isUser) "用户" else "AI",
|
||||
fontSize = 10.sp,
|
||||
color = androidx.compose.ui.graphics.Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(if (isUser) Doubao.Blue else doubaoTextDim())
|
||||
.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(sourceText, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
if (e.important) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("★重要", fontSize = 10.sp, color = Doubao.Blue)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
if (expanded) "收起" else "展开",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
e.modelContent.ifBlank { e.content },
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = if (expanded) Int.MAX_VALUE else 5,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
if (!expanded && (e.modelContent.ifBlank { e.content }).length > 160) {
|
||||
Text(
|
||||
"(点「展开」看全文)",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ExcludedCard(e: ContextEntry, expanded: Boolean, onToggle: () -> Unit) {
|
||||
val reason = when (e.reason) {
|
||||
"place" -> "别的地点"
|
||||
"enter" -> "第一次到这个地点之前"
|
||||
"window" -> "超出上下文窗口"
|
||||
"private" -> "别人的私聊"
|
||||
else -> "被筛掉"
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard().copy(alpha = 0.6f))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
reason,
|
||||
fontSize = 10.sp,
|
||||
color = androidx.compose.ui.graphics.Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(androidx.compose.ui.graphics.Color(0xFFB3261E))
|
||||
.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
if (e.source == "other") "对话「${e.convTitle.ifBlank { "另一个" }}」" else "本对话",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
if (expanded) "收起" else "展开",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
if (e.detail.isNotBlank()) {
|
||||
Text(e.detail, fontSize = 10.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 2.dp))
|
||||
}
|
||||
Text(
|
||||
e.content,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = if (expanded) Int.MAX_VALUE else 3,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
@@ -70,6 +72,24 @@ fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
|
||||
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
|
||||
@Composable
|
||||
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
|
||||
|
||||
/**
|
||||
* 聊天气泡的底色(**半透明**)。
|
||||
*
|
||||
* ★ 聊天页现在有一层**实心**的立绘(`ChatScreen.ChatBackdrop`)垫在下面,
|
||||
* 气泡要是也不透明,那张立绘就白铺了 —— 用户要的正是
|
||||
* 「立绘看得见、字也读得清」这一对。
|
||||
*
|
||||
* ★ 0.78 是这两条的交点:再透字就开始糊在图上,再实立绘就等于没有。
|
||||
* 别的页面(卡片、弹窗)继续用不透明的 [doubaoBubble],
|
||||
* 它们底下没有图,半透明只会显脏。
|
||||
*/
|
||||
@Composable
|
||||
fun doubaoBubbleVeil() = doubaoBubble().copy(alpha = 0.78f)
|
||||
|
||||
/** 用户自己那侧的气泡(蓝色),同样要半透明 —— 理由同 [doubaoBubbleVeil] */
|
||||
@Composable
|
||||
fun doubaoBubbleMine() = Doubao.Blue.copy(alpha = 0.82f)
|
||||
@Composable
|
||||
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
|
||||
@Composable
|
||||
@@ -77,6 +97,71 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
|
||||
@Composable
|
||||
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
|
||||
|
||||
/** 主色(AI 界面/弹窗里强调"选中"用) */
|
||||
@Composable
|
||||
fun doubaoAccent() = if (isDark()) Color(0xFF6EA8FF) else Doubao.Blue
|
||||
|
||||
/** 主色的浅底(选中项的背景) */
|
||||
@Composable
|
||||
fun doubaoAccentSoft() = if (isDark()) Color(0xFF1B2A44) else Color(0xFFEAF1FF)
|
||||
|
||||
/** 比 surface 稍亮/稍暗一档的容器底色(弹窗里的选项行) */
|
||||
@Composable
|
||||
fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg
|
||||
|
||||
/** 三级文字色(比 secondary 更淡,用于说明小字) */
|
||||
@Composable
|
||||
fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary
|
||||
|
||||
/* ------------------------------ 打开链接 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 在系统浏览器里打开一个链接。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接**以前渲染成蓝色下划线但没有绑点击** ——
|
||||
* 看着像能点,点了完全没反应。用户会以为是"链接坏了"。
|
||||
* (这个坑是用户问"网页在哪点开"时才查出来的:我一直在讲 AI 弹的界面,
|
||||
* 而最容易想到的"点链接"其实一直是坏的。)
|
||||
*
|
||||
* ## 为什么用系统浏览器而不是应用内 WebView
|
||||
*
|
||||
* AI 弹出的那个界面里点链接是**应用内**打开的(用户明确要的"可再点进去")。
|
||||
* 但聊天正文里的链接不一样:那里没有"返回 AI 界面"这个上下文,
|
||||
* 在应用内开一个 WebView 会让用户迷失(返回键行为说不清)。
|
||||
* 交给系统浏览器,行为标准、有历史、有关闭 —— 对正文链接更合适。
|
||||
*
|
||||
* ★ 必须 try/catch:设备上可能没有浏览器(精简 ROM),
|
||||
* 或者链接协议没人能处理,那会抛 ActivityNotFoundException。
|
||||
* 不接的话点一下链接 App 就崩。
|
||||
*/
|
||||
fun openInBrowser(context: android.content.Context, url: String): Boolean {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return false
|
||||
val uri = try {
|
||||
android.net.Uri.parse(u)
|
||||
} catch (_: Throwable) {
|
||||
return false
|
||||
}
|
||||
// 只放行有 scheme 的绝对地址;相对地址点了没意义,还会让 Intent 解析失败
|
||||
if (uri.scheme.isNullOrBlank()) return false
|
||||
|
||||
return try {
|
||||
context.startActivity(
|
||||
android.content.Intent(android.content.Intent.ACTION_VIEW, uri)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.w("DoubaoLink", "打不开 $u:${t.javaClass.simpleName}: ${t.message}")
|
||||
android.widget.Toast
|
||||
.makeText(context, "打不开这个链接", android.widget.Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 动画 ------------------------------ */
|
||||
|
||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||
@@ -145,6 +230,7 @@ fun TypingDots(color: Color = Doubao.TextTertiary, dot: Dp = 6.dp) {
|
||||
/* ------------------------------ 小部件 ------------------------------ */
|
||||
|
||||
/** 顶部/输入框上方的白底描边胶囊按钮(快捷入口、功能键) */
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun DoubaoPill(
|
||||
text: String? = null,
|
||||
@@ -152,15 +238,20 @@ fun DoubaoPill(
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
height: Dp = 40.dp,
|
||||
/** ★ v3.15:长按(不传 = 没有长按行为)—— 成员条用它「长按 @某人 私聊」 */
|
||||
onLongClick: (() -> Unit)? = null,
|
||||
) {
|
||||
val base = modifier
|
||||
.height(height)
|
||||
.clip(RoundedCornerShape(height / 2))
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), RoundedCornerShape(height / 2))
|
||||
Box(
|
||||
modifier
|
||||
.height(height)
|
||||
.clip(RoundedCornerShape(height / 2))
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), RoundedCornerShape(height / 2))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp),
|
||||
(if (onLongClick != null) {
|
||||
base.combinedClickable(onClick = onClick, onLongClick = onLongClick)
|
||||
} else {
|
||||
base.clickable(onClick = onClick)
|
||||
}).padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -212,3 +303,33 @@ fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
fontWeight = FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------- //
|
||||
// 通用小件(v1.2)
|
||||
// --------------------------------------------------------------------------- //
|
||||
//
|
||||
// ★ 这两个原来是 AgentEditScreen 的**私有**函数,于是别的界面想用就只能
|
||||
// 复制一份 —— 而"同一段逻辑抄两份"是这个仓库反复出现的毛病。
|
||||
// 挪到这里之后全局一份。
|
||||
|
||||
/** 一张卡片:横向留白 + 圆角 + 表面色 + 内边距 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Card(content: @androidx.compose.runtime.Composable () -> Unit) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
androidx.compose.ui.Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(androidx.compose.foundation.shape.RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
/** 一行灰字说明 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Hint(text: String) {
|
||||
androidx.compose.material3.Text(
|
||||
text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
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.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.DuelInfo
|
||||
import com.doubao.lynxclone.data.DuelRound
|
||||
import com.doubao.lynxclone.data.DuelSide
|
||||
import com.doubao.lynxclone.data.DuelStat
|
||||
import com.doubao.lynxclone.data.DuelStatus
|
||||
|
||||
/**
|
||||
* **决斗界面**(v3.17,用户需求)。
|
||||
*
|
||||
* 用户原话:「决斗加个ui但不开新对话,和私密一样」「要有决斗可以中断但需要双方同意」
|
||||
* 「如何选择武器?没有回合限制」「有输,赢,平局,停手,4种状态」。
|
||||
*
|
||||
* 所以这一页是**当前对话的一个面板**(不新建会话、不新开话题):
|
||||
* · 上半:双方名字 / 数值条 / 状态 / **当前武器**(数据来自内核每回合返回的快照)
|
||||
* · 中间:**我的武器**(每回合可换,点击切换)、回合记录、结果(赢/输/平局/停手)
|
||||
* · 底部:出招(推进一回合)、请求罢手(对方同意才停手)、
|
||||
* 等用户回应时的「同意罢手 / 继续打」
|
||||
*
|
||||
* ★ 为什么全屏:双方状态 + 多回合日志,弹窗根本装不下(AGENTS.md 界面约定)。
|
||||
* ★ 谁赢、掉多少血、中什么状态由世界脚本 + 物品脚本决定,界面**只展示 + 推进**。
|
||||
* ★ **没有回合上限**(v3.19):回合只写「第 N 回合」。
|
||||
*/
|
||||
@Composable
|
||||
fun DuelScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val d = vm.duel
|
||||
FullScreen(
|
||||
title = "决斗",
|
||||
subtitle = d?.let { "${it.title()} · ${it.statusText()}" }.orEmpty(),
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (d != null) TopTextAction("刷新") { vm.loadDuel() }
|
||||
},
|
||||
) {
|
||||
if (d == null) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text("这个对话现在没有决斗。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxWidth().weight(1f),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item(key = "status") { DuelStatusCard(d) }
|
||||
// ★ v3.19:每回合可以换武器(用户原话「如何选择武器?」→ 界面上直接选)
|
||||
item(key = "weapons") { DuelWeaponPicker(vm, d) }
|
||||
// ★ v3.22:本回合物品(被动物品/血瓶;每回合只能用一件)
|
||||
item(key = "items") { DuelItemPicker(vm, d) }
|
||||
// ★ v3.24:决斗对话(用户说话,对手 AI 真的以角色身份回应)
|
||||
item(key = "talk") { DuelTalkBox(vm, d) }
|
||||
item(key = "sides") {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
DuelSideCard(d.initiator, userLabel = "你", modifier = Modifier.weight(1f))
|
||||
DuelSideCard(d.target, userLabel = "你", modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
item(key = "logTitle") {
|
||||
Text("回合记录", fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
if (d.log.isEmpty()) {
|
||||
item(key = "emptyLog") {
|
||||
Text("还没开打。", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
items(d.log) { round -> DuelRoundCard(round) }
|
||||
item(key = "bottomSpace") { Spacer(Modifier.height(4.dp)) }
|
||||
}
|
||||
DuelActions(vm, d)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 顶部状态卡 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelStatusCard(d: DuelInfo) {
|
||||
val accent = when {
|
||||
d.interrupted -> Color(0xFF8A6100)
|
||||
d.running -> Color(0xFFB3261E)
|
||||
d.outcomeText() == "赢" -> Color(0xFFB3261E)
|
||||
d.outcomeText() == "输" -> Color(0xFF6B6B6B)
|
||||
d.outcomeText().isNotBlank() -> Color(0xFF8A6100)
|
||||
else -> Doubao.Blue
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(accent.copy(alpha = 0.10f))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
d.statusText(),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = accent,
|
||||
)
|
||||
// ★ v3.19:四种结果状态 —— 赢 / 输 / 平局 / 停手,放在最显眼的位置
|
||||
if (!d.running && d.outcomeText().isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
d.outcomeText(),
|
||||
fontSize = 24.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = accent,
|
||||
)
|
||||
}
|
||||
when {
|
||||
d.running && d.needsMyAnswer -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"「${d.pendingStopByName}」想罢手、停手 —— 要你同意才能停。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
d.running && d.status == "stop_pending" -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"你已经请求罢手,正在等「${d.foeSide.name}」回应;对方同意之前决斗还在继续。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
d.result.isNotBlank() -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(d.result, fontSize = 12.sp, color = doubaoText())
|
||||
if (d.missingWeapon) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"决斗要求双方都有 target 类物品(武器),没有的一方判负。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"每点一次「出招」推进一回合(没有回合上限):双方先用当前武器出手" +
|
||||
"(跑物品脚本),再由世界脚本(on_duel)裁决。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 双方卡片 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelSideCard(side: DuelSide, userLabel: String, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
if (side.isUser) "$userLabel(${side.name})" else side.name.ifBlank { "对手" },
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (side.isUser) Doubao.Blue else doubaoText(),
|
||||
maxLines = 1,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// ★ v3.19:四种结果状态(赢/输/平局/停手)直接标在名字右边
|
||||
if (side.outcomeText().isNotBlank()) {
|
||||
Text(
|
||||
side.outcomeText(),
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = when (side.outcome) {
|
||||
"win" -> Color(0xFFB3261E)
|
||||
"lose" -> Color(0xFF6B6B6B)
|
||||
else -> Color(0xFF8A6100)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (side.isGuard) {
|
||||
Text("驻守角色", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
// ★ v3.20:决斗中死亡 = 判负
|
||||
if (side.dead) {
|
||||
Text("已死亡(决斗判负)", fontSize = 11.sp, color = Color(0xFFB3261E))
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (side.stats.isEmpty()) {
|
||||
Text("没有数值", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (s in side.stats) {
|
||||
DuelStatBar(s)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
if (side.statuses.isNotEmpty()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
for (st in side.statuses) {
|
||||
Text(
|
||||
"· ${st.name}" + if (st.kind != "persistent" && st.remaining > 0) "(剩 ${st.remaining} 轮)" else "",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★ v3.18:武器(target 类物品)—— 没有武器的一方会被直接判失败
|
||||
// ★ v3.19:显示"这回合用的是哪件",并提示可换
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text("武器", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
if (side.weapons.isEmpty()) {
|
||||
Text(
|
||||
"没有 target 类物品 —— 会被判失败",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
} else {
|
||||
val cur = side.weapon
|
||||
Text(
|
||||
if (cur != null) "本回合:${cur.name}${cur.countText()}" else "本回合:自动选择",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 2,
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Text(
|
||||
side.weapons.joinToString("、") { "${it.name}${it.countText()}" },
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 3,
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
}
|
||||
// ★ v3.22:本回合用被动物品 = 不攻击(每回合只能用一件物品)
|
||||
val usedItem = side.item
|
||||
if (usedItem != null) {
|
||||
Text(
|
||||
"本回合动作:使用「${usedItem.name}」(不攻击)",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.19:**我的武器**选择器(用户原话「如何选择武器?」→ 每回合都能换)。
|
||||
*
|
||||
* 从自己的 target 类物品里点一件当"下一回合的武器";点一下就走接口(不弹窗,
|
||||
* 这本来就是一行 chips)。没有武器时整块不显示(上面卡片会红字说明)。
|
||||
*/
|
||||
@Composable
|
||||
private fun DuelWeaponPicker(vm: AppViewModel, d: DuelInfo) {
|
||||
val side = d.meSide
|
||||
if (side.weapons.isEmpty()) return
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text("我的武器(每回合可换)", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for (w in side.weapons) {
|
||||
val selected = w.id == side.weapon?.id
|
||||
Text(
|
||||
"${w.name}${w.countText()}",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (selected) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (selected) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(enabled = d.status == "active" && !vm.duelBusy) {
|
||||
vm.chooseDuelWeapon(w.id)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (d.status != "active") {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("决斗中才能换武器。", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.22:**本回合物品**(用户原话「被动在决斗中也可使用 比如用血瓶 但每回合只能用一个物品」)。
|
||||
*
|
||||
* 选被动物品 = 这回合用它、**不用武器攻击**;不选 = 正常武器攻击。
|
||||
* 选择是一次性的:推进一回合后自动清空(快照里 item 变 null)。
|
||||
*/
|
||||
@Composable
|
||||
private fun DuelItemPicker(vm: AppViewModel, d: DuelInfo) {
|
||||
val side = d.meSide
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text("本回合物品(每回合只能用一件)", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"选被动物品(比如血瓶)= 这回合用它、不攻击;不选就用武器攻击。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// "改用武器"= 取消物品选择(默认动作)
|
||||
val noItem = side.item == null
|
||||
Text(
|
||||
"用武器攻击",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (noItem) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (noItem) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (noItem) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(enabled = d.status == "active" && !vm.duelBusy) {
|
||||
vm.chooseDuelItem("")
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
for (it in side.passiveItems) {
|
||||
val selected = it.id == side.item?.id
|
||||
Text(
|
||||
"${it.name}${it.countText()}",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (selected) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (selected) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(enabled = d.status == "active" && !vm.duelBusy) {
|
||||
vm.chooseDuelItem(it.id)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (side.passiveItems.isEmpty()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("背包里没有被动物品(血瓶/回春丹这类)。",
|
||||
fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
if (d.status != "active") {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("决斗中才能选物品。", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.24:**决斗对话**(用户原话:「决斗要ai真的参与,弄个对话框」)。
|
||||
*
|
||||
* 用户在这里说话 → 内核真的问一次**对手 AI**(按它的人设/气血/最近交锋),
|
||||
* AI 以角色身份回一句,双方的话都写进回合记录和会话消息。
|
||||
* 不影响出招/回合推进 —— 想说话就说话,想出招就出招。
|
||||
*/
|
||||
@Composable
|
||||
private fun DuelTalkBox(vm: AppViewModel, d: DuelInfo) {
|
||||
var line by remember(d.id) { mutableStateOf("") }
|
||||
val foe = d.foeSide.name.ifBlank { "对手" }
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text("决斗对话(AI 会真的回你)", fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"对「$foe」说句话(挑衅/谈判/认输都行)—— 对手 AI 会按人设回应;" +
|
||||
"不影响出招和回合。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
OutlinedTextField(
|
||||
value = line,
|
||||
onValueChange = { line = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
placeholder = { Text("对 $foe 说…", fontSize = 13.sp) },
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
maxLines = 2,
|
||||
singleLine = false,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TextButton(
|
||||
enabled = d.status == "active" && !vm.duelSaying
|
||||
&& line.isNotBlank(),
|
||||
onClick = {
|
||||
vm.sayInDuel(line)
|
||||
line = ""
|
||||
},
|
||||
) { Text(if (vm.duelSaying) "回应中…" else "发送") }
|
||||
}
|
||||
if (d.status != "active") {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("决斗中才能对话。", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DuelStatBar(stat: DuelStat) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(stat.name, fontSize = 11.sp, color = doubaoTextSecondary(), modifier = Modifier.weight(1f))
|
||||
Text(
|
||||
"${fmt(stat.value)} / ${fmt(stat.max)}",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(5.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoTextSecondary().copy(alpha = 0.18f)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(5.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (kotlin.math.abs(v - v.toLong()) < 0.001) v.toLong().toString() else "%.1f".format(v)
|
||||
|
||||
/* ------------------------------ 回合记录 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelRoundCard(round: DuelRound) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"第 ${round.round} 回合",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
if (round.lines.isEmpty()) {
|
||||
Text("这一回合没有旁白。", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (line in round.lines) {
|
||||
Text(
|
||||
line,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 底部按钮 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelActions(vm: AppViewModel, d: DuelInfo) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (vm.duelBusy) {
|
||||
Text("处理中……", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
return@Row
|
||||
}
|
||||
when {
|
||||
d.running && d.needsMyAnswer -> {
|
||||
DuelButton("同意罢手", primary = true) { vm.answerDuelStop(true) }
|
||||
DuelButton("继续打", primary = false) { vm.answerDuelStop(false) }
|
||||
}
|
||||
d.running && d.status == "active" -> {
|
||||
DuelButton("出招", primary = true) { vm.advanceDuel() }
|
||||
if (d.userInvolved) {
|
||||
DuelButton("请求罢手", primary = false) { vm.requestDuelStop() }
|
||||
}
|
||||
}
|
||||
d.running -> {
|
||||
Text("等「${d.foeSide.name}」回应罢手请求……", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
else -> {
|
||||
DuelButton("关闭", primary = true) {
|
||||
vm.dismissDuel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun androidx.compose.foundation.layout.RowScope.DuelButton(
|
||||
label: String,
|
||||
primary: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (primary) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(if (primary) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 10.dp),
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
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.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
|
||||
/**
|
||||
* 群成员(v1.2 §3.9)。
|
||||
*
|
||||
* ## 为什么是全屏而不是弹窗
|
||||
*
|
||||
* 需求里写的是"浮层",但按仓库的界面约定(AGENTS.md):**列表用全屏**。
|
||||
* 一屏弹窗大概只够三四行,成员一多就得在弹窗里滚 —— 那还不如直接开一屏,
|
||||
* 而且这里还要放"加人/移出"两组动作。
|
||||
*
|
||||
* ## 谁不能移出
|
||||
*
|
||||
* ★ **主智能体不能移出**(成员列表第一个):它是"没人被点名时兜底发言"的
|
||||
* 那个人,移掉这个群就会冷场。
|
||||
* 界面上把它的按钮藏起来 —— 但那只是给用户看的,**服务端也拦**
|
||||
* (绕过界面直接调接口的路径也得挡住)。
|
||||
*/
|
||||
@Composable
|
||||
fun GroupMembersScreen(
|
||||
vm: AppViewModel,
|
||||
conversationId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenStats: (String) -> Unit = {},
|
||||
) {
|
||||
val conv: Conversation? = vm.state.conversations.firstOrNull { it.id == conversationId }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "会话成员",
|
||||
subtitle = conv?.let { "${it.participants.size} 个人在群里" } ?: "会话不见了",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (!adding) TopTextAction("加人") { adding = true } else TopTextAction("取消") { adding = false }
|
||||
},
|
||||
) {
|
||||
// ---- 加人(就地展开,不再弹一层 —— 弹窗压弹窗是手机上的灾难)----
|
||||
if (adding) {
|
||||
val inGroup = conv?.participants?.toSet() ?: emptySet()
|
||||
// ★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
//
|
||||
// 群聊上下文里有 <worldview> 段、共享记忆也按世界观分空间 ——
|
||||
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
|
||||
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
|
||||
// 让人点了才被告知"加不进去"是最差的体验。
|
||||
//
|
||||
// ★ **未绑世界观的放行**:它没有设定会串,和谁都合得来
|
||||
// (用户报的「还是加不了人」,其中"黑化豆包"就是未绑的)。
|
||||
val hostWorldview = vm.state.agents
|
||||
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
|
||||
val sameWorldview = vm.state.agents.filter {
|
||||
it.worldviewId.orEmpty().isBlank() || it.worldviewId.orEmpty() == hostWorldview
|
||||
}
|
||||
val candidates = sameWorldview.filter { it.id !in inGroup }
|
||||
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
|
||||
SectionLabel("拉谁进来")
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint(
|
||||
if (blocked > 0) "没有可以拉的人了。"
|
||||
else "所有能拉的人都在群里了。",
|
||||
)
|
||||
} else {
|
||||
for (a in candidates) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
// ★ 注意签名:`makeGroup` 是**这个会话还没有群成员**时
|
||||
// 用的(会新建群聊);已经有成员了就走 `addMember`,
|
||||
// 不能混 —— 混了会把当前会话换掉,用户会一头雾水。
|
||||
if (inGroup.isEmpty()) vm.makeGroup(a.id) else vm.addMember(a.id)
|
||||
// ★★ 加完**不收起**(原来这里 `adding = false`)。
|
||||
// 收起的话,用户加了一个就得再点一次「加人」才能加下一个,
|
||||
// 体感就是"群聊只能拉两个"(真机反馈)。
|
||||
// 刷新后 `candidates` 会少一个,接着点就行。
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(vm, a, 36)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
|
||||
}
|
||||
// ★★ 被世界观挡下的**也列出来**,并说清原因。
|
||||
//
|
||||
// 不列的话用户只看到"某些智能体不见了",以为功能坏了 ——
|
||||
// 他报的「还是加不了人」有一半是这种感觉。
|
||||
val blockedAgents = vm.state.agents.filter { it.id !in inGroup && it !in sameWorldview }
|
||||
if (blockedAgents.isNotEmpty()) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"这些绑的是别的世界观,拉进来会串设定(两套背景、共享记忆也会混):",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
for (a in blockedAgents) {
|
||||
Text(
|
||||
"· ${a.name}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(start = 6.dp, top = 2.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("想拉它们:先去它们的编辑页绑成这个世界观(或者另开一个群)。")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
}
|
||||
|
||||
if (conv == null) {
|
||||
Hint("这个会话已经不在了。")
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("成员")
|
||||
Card {
|
||||
for ((i, id) in conv.participants.withIndex()) {
|
||||
val a: Agent? = vm.state.agents.firstOrNull { it.id == id }
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(vm, a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
// ★ 这里原来标了「主」徽章 + "没人被 @ 的时候由它接话"。
|
||||
// 用户要求「群聊去掉主人设定」—— 群里没有老大,
|
||||
// 没人被 @ 时**按顺序轮**(见 kernel/group_chat.rotate_next)。
|
||||
Text(
|
||||
"第 ${i + 1} 个进群的",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
// ★ v3.15:私聊入口改成**聊天页长按 @成员**(用户要求
|
||||
// 「长按@xxx私聊」)。这里不再放按钮 —— 那会另开一个
|
||||
// 私聊会话,和"私聊在当前对话里"的预期不符。
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
|
||||
// 就没有"动不了"的那一个。内核那边会拦住"最后一个"
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
|
||||
)
|
||||
// ★ v3.17:决斗入口从这一页挪走了 —— 用户要求「长按@XX可选私聊和决斗」。
|
||||
// 私聊和决斗**都不另开会话**(都在当前对话里),所以入口统一放在
|
||||
// 聊天页的成员条上:点 = @,长按 = 私聊/决斗二选一。
|
||||
Hint("长按聊天页的 @成员 还能选「私聊」或「决斗」(都不会另开对话)。")
|
||||
|
||||
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
|
||||
//
|
||||
// 放这儿而不是抽屉里:抽屉已经有七项了(用户刚说过"太挤了"),
|
||||
// 而**群成员页本来就有成员** —— 从这儿点两个人比在抽屉里
|
||||
// 再开一个挑人对话框顺得多。
|
||||
//
|
||||
// 内核早就完整实现了(10 轮安全网、一方触顶另一方单方面收尾、
|
||||
// 摘要进共享记忆),但界面上一直没有入口 —— 这个需求项碰不到。
|
||||
Spacer(Modifier.height(12.dp))
|
||||
SectionLabel("私下聊聊")
|
||||
Card {
|
||||
Hint(
|
||||
"点两个名字,让他们在后台自主对聊 —— 你不在场。" +
|
||||
"聊完的摘要会写进共享记忆,完整记录在会话列表里能翻。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (id in conv.participants) {
|
||||
val a = vm.state.agents.firstOrNull { it.id == id }
|
||||
val picked = id in vm.privatePair
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { vm.togglePrivatePick(id) }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (picked) "✓" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (picked) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a?.name ?: "(已删除)", fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("开始私聊") { vm.startPickedPrivateChat() }
|
||||
if (vm.privatePair.isNotEmpty()) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
RowAction("清空选择") { vm.cancelPrivatePick() }
|
||||
}
|
||||
}
|
||||
if (vm.privateChatRunning.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("${vm.privateChatRunning} 正在聊……(要跑一会儿,别退出去)")
|
||||
}
|
||||
if (vm.privateChatResult.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(vm.privateChatResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@Composable
|
||||
private fun AgentFace(vm: AppViewModel, agent: Agent?, size: Int) {
|
||||
val art = vm.portraitOf(agent)
|
||||
Box(
|
||||
Modifier
|
||||
.size(size.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoCard()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(art, Modifier.size(size.dp), contentScale = ContentScale.Crop)
|
||||
} else {
|
||||
Text(
|
||||
(agent?.name ?: "?").take(1),
|
||||
fontSize = (size * 0.42).sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.util.Base64
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* 选图 → 读成能上传的 base64。
|
||||
*
|
||||
* ## 为什么必须在这里压缩(这是真机上报回来的 bug)
|
||||
*
|
||||
* 用户选的是**手机相册里的照片**,现在动辄 30~55MB(一亿像素)。
|
||||
* 原样读进来会连撞三堵墙:
|
||||
*
|
||||
* ① `readBytes()` 把 55MB 全读进内存,`Base64` 再翻 4/3 倍 → 低端机直接 OOM;
|
||||
* ② 内核 `read_json_body()` 每条接口有自己的上限,图片这条路走的是小上限,
|
||||
* 38MB 的请求体一进去就被判「请求体过大」;
|
||||
* ③ 更糟的是那个异常被上层吞掉,最后报出来的是
|
||||
* **「不认识的外观槽位」** —— 一个和真实原因毫无关系的错误,
|
||||
* 用户只看到"设置不了",查代码的人也会往槽位名上去找。
|
||||
*
|
||||
* 所以压缩不是优化,是**这条链路能不能用**的前提:
|
||||
* 一张 4000×3000 的照片按最长边 1600 采样后大约是 200~400KB,
|
||||
* 比原来小两个数量级,上面三堵墙一次全绕过。
|
||||
*
|
||||
* ## 两种图**不能**压
|
||||
*
|
||||
* - **GIF**:缩放会丢动画(这个 App 明确支持动图,"动图会动"是写在界面上的);
|
||||
* - **SVG**:本来就是矢量,栅格化等于自毁。
|
||||
*
|
||||
* 这两种原样传,只在超过内核 20MB 上限时明确报错 —— 让用户换个文件,
|
||||
* 而不是静默失败。
|
||||
*/
|
||||
|
||||
/** 压缩后最长边不超过它。1600 在手机上看立绘/背景已经够清楚 */
|
||||
private const val MAX_EDGE = 1600
|
||||
|
||||
/** 压到这么大就收手。经验值:1600 边长的 JPEG 通常在 200~400KB */
|
||||
private const val TARGET_BYTES = 3 * 1024 * 1024
|
||||
|
||||
/** 内核 `_set_asset` 的硬上限,超过它一定传不上去,这里提前拦下来把话说清楚 */
|
||||
private const val MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
/** 一张选好的图。[note] 是给用户看的一句话,说明这张图被怎么处理了 */
|
||||
data class PickedImage(val name: String, val base64: String, val note: String)
|
||||
|
||||
private fun mb(n: Int): String = String.format("%.1f", n / 1048576.0)
|
||||
|
||||
/**
|
||||
* 读一张图并压到能传的大小。
|
||||
*
|
||||
* 失败时抛 [IllegalStateException],**消息是可以直接显示给用户的中文** ——
|
||||
* 调用方 `catch` 之后原样 `showHint(e.message)` 就行,
|
||||
* 不要再包一层"上传失败",那样又把原因盖掉了。
|
||||
*/
|
||||
fun readImageForUpload(ctx: Context, uri: Uri): PickedImage {
|
||||
val resolver = ctx.contentResolver
|
||||
val rawName = (uri.lastPathSegment ?: "image").substringAfterLast('/').ifBlank { "image" }
|
||||
// ★ 名字靠不住:SAF 给的常常是 `image_1000018030` 这种没有扩展名的。
|
||||
// MIME 才是可信的(getType 对 content:// 会去查 provider)。
|
||||
val mime = (resolver.getType(uri) ?: "").lowercase()
|
||||
val isGif = mime.contains("gif")
|
||||
val isSvg = mime.contains("svg")
|
||||
|
||||
if (isGif || isSvg) {
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw IllegalStateException("读不出这个文件")
|
||||
if (bytes.isEmpty()) throw IllegalStateException("这个文件是空的")
|
||||
if (bytes.size > MAX_BYTES) {
|
||||
throw IllegalStateException("这张图 ${mb(bytes.size)}MB,超过 20MB 上限了,换一张吧")
|
||||
}
|
||||
return PickedImage(
|
||||
name = rawName,
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = if (isGif) "动图原样上传(压缩会丢动画)" else "SVG 原样上传",
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 位图:先只问尺寸,不解码像素 ----
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
|
||||
throw IllegalStateException("这不是一张能识别的图片")
|
||||
}
|
||||
|
||||
// 压不下来就一轮轮降:边长 ×3/4、质量 ×4/5。四轮足够把任何照片压进 3MB
|
||||
var edge = MAX_EDGE
|
||||
var quality = 88
|
||||
var last = 0
|
||||
repeat(4) {
|
||||
val opts = BitmapFactory.Options().apply { inSampleSize = sampleFor(bounds, edge) }
|
||||
val bmp = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) }
|
||||
?: throw IllegalStateException("读不出这张图")
|
||||
val hasAlpha = bmp.hasAlpha()
|
||||
val out = ByteArrayOutputStream()
|
||||
bmp.compress(if (hasAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, quality, out)
|
||||
val w = bmp.width
|
||||
val h = bmp.height
|
||||
bmp.recycle()
|
||||
val bytes = out.toByteArray()
|
||||
last = bytes.size
|
||||
|
||||
if (bytes.size <= TARGET_BYTES) {
|
||||
return PickedImage(
|
||||
// ★ 扩展名要跟着真实格式走:压成 JPEG 却叫 .png,虽然解码器看魔数也能认,
|
||||
// 但导出的包里会留下一个名不副实的文件
|
||||
name = "${rawName.substringBeforeLast('.')}.${if (hasAlpha) "png" else "jpg"}",
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = "已压到 ${w}×${h}、${bytes.size / 1024}KB 再上传",
|
||||
)
|
||||
}
|
||||
edge = edge * 3 / 4
|
||||
quality = (quality * 4) / 5
|
||||
}
|
||||
throw IllegalStateException("这张图压到 ${mb(last)}MB 还是太大,换一张吧")
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样率(2 的幂,`BitmapFactory` 只认这个)。
|
||||
*
|
||||
* ★ 判据是**最长边**(写成 `||`),不是"宽高都超"。
|
||||
* 写成 `&&` 的话 4000×3000 一张只缩到 4000(短边 3000 没到阈值就停了),
|
||||
* JPEG 出来还有 2.2MB;按长边缩一档到 2000×1500 就只有它的三分之一。
|
||||
*
|
||||
* 取**解码后仍然 ≥ maxEdge** 的那一档 —— 宁可多留一点,
|
||||
* 后面还有缩小/降质的循环兜着;反过来取小了就再也补不回清晰度。
|
||||
*/
|
||||
private fun sampleFor(bounds: BitmapFactory.Options, maxEdge: Int): Int {
|
||||
var sample = 1
|
||||
while (bounds.outWidth / (sample * 2) >= maxEdge ||
|
||||
bounds.outHeight / (sample * 2) >= maxEdge
|
||||
) {
|
||||
sample *= 2
|
||||
}
|
||||
return sample
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
|
||||
/**
|
||||
* [地图](v3.31):**内核生成的图形地图页**(全屏 WebView)。
|
||||
*
|
||||
* 页面由 `/api/containers/<cid>/map/page` 生成,画的是:
|
||||
* · 背景图(世界包 `info.map.background`,可上传图片)
|
||||
* · 区域框(`info.map.regions[]`:家 / 老街 / 森林 / 学校…)
|
||||
* · 地点圆点(世界包 `places[].x/y` 是背景图里的 **0-100 百分比位置**)
|
||||
* · 邻接连线(由 `places[].exits` 自动推出来,一个地点可连多个)
|
||||
* · 用户位置五角星(`info.map.marker` 可换成自定义字符或图片)
|
||||
*
|
||||
* 交互都在页面里(同一份 HTML/CSS/JS,样式可由 `info.map.css` 追加):
|
||||
* · 双指缩放 / 滚轮 / 拖动;点区域框放大到该区域;
|
||||
* · 点地点圆点 → 「去这里 / 移人」;**长按地点或区域 → 弹出信息**;
|
||||
* · 页面里 `fetch` 直接调内核移动接口,「去这里」成功后通过 JS 桥回调
|
||||
* [MapBridge.moved] 让 App 切到该地点的对话。
|
||||
*
|
||||
* 以前这里是 Compose 画的地点头像列表;换成 HTML 页是为了让世界作者能用
|
||||
* CSS 改边框/连线/节点样式(用户要求)。
|
||||
*/
|
||||
@Composable
|
||||
fun MapScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val url = vm.mapPageUrl
|
||||
val container = vm.state.containers.firstOrNull { it.id == vm.mapContainerId }
|
||||
FullScreen(
|
||||
title = "地图",
|
||||
subtitle = container?.name?.ifBlank { "容器" } ?: "容器",
|
||||
onBack = onBack,
|
||||
) {
|
||||
val bridge = remember(url) {
|
||||
MapBridge(
|
||||
onClose = { vm.closeMap() },
|
||||
onMoved = { placeId, placeName -> vm.onMapMoved(placeId, placeName) },
|
||||
)
|
||||
}
|
||||
DisposableEffect(bridge) {
|
||||
onDispose {
|
||||
bridge.onClose = null
|
||||
bridge.onMoved = null
|
||||
}
|
||||
}
|
||||
if (url.isBlank()) {
|
||||
Hint("这一局还没有地图。")
|
||||
return@FullScreen
|
||||
}
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(android.graphics.Color.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
settings.cacheMode = WebSettings.LOAD_NO_CACHE
|
||||
// 缩放由页面里的 pointer 事件实现(双指/滚轮),别让 WebView 再插一手
|
||||
settings.builtInZoomControls = false
|
||||
settings.displayZoomControls = false
|
||||
// ★ v3.31 修复:`useWideViewPort = true` 让 WebView 按页面的
|
||||
// `<meta viewport width=device-width>` 建立布局视口(360 CSS px),
|
||||
// 这样 CSS 的 `vh / %` 高度才是对的。
|
||||
// 默认 false 时这个 WebView 里 `10vh` 会算成 0px ——
|
||||
// 地图信息面板曾经因此被压成一条 44px 的横条(用户反馈
|
||||
// 「面板太矮 / 太低」的根因)。页面里已经用 innerHeight 兜底,
|
||||
// 这里再把它从根上修好,世界包自定义 CSS 用 vh 也不会踩坑。
|
||||
// `loadWithOverviewMode` 保持 false:不要把 1080px 宽的地图舞台
|
||||
// 再整体缩放一遍(那样坐标和内边距全乱)。
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = false
|
||||
addJavascriptInterface(bridge, "Doubao")
|
||||
webViewClient = WebViewClient()
|
||||
loadUrl(url)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 地图页的极小 JS 桥:关掉全屏 / 告诉 App「已经移动到某地点」。 */
|
||||
private class MapBridge(
|
||||
@Volatile var onClose: (() -> Unit)?,
|
||||
@Volatile var onMoved: ((String, String) -> Unit)?,
|
||||
) {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
main.post { onClose?.invoke() }
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun moved(placeId: String, placeName: String) {
|
||||
main.post { onMoved?.invoke(placeId ?: "", placeName ?: "") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,912 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.ExperimentalTextApi
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* 极简 Markdown 渲染。
|
||||
*
|
||||
* 为什么自己写而不引库:
|
||||
* 项目一直坚持"零第三方依赖"(安卓端构建要能离线完成),而 Markdown 渲染
|
||||
* 在这个规模下不需要一个几百 KB 的库 —— 聊天里真正会出现的就那几种:标题、
|
||||
* 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。
|
||||
*
|
||||
* 支持:
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、- [ ] 任务列表、> 引用、--- 分隔线、
|
||||
* **| 表格 |**、普通段落
|
||||
* 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接)
|
||||
*
|
||||
* 不支持(有意为之):嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 而且做全了就得处理各种边界,性价比很低。
|
||||
*
|
||||
* ## ★★ 表格是补上的,起因是用户截图:"表格没做"
|
||||
*
|
||||
* 之前这里明确写着"不支持表格",理由是"聊天里几乎不出现"—— **判断错了**。
|
||||
* 复盘为什么错得这么离谱:
|
||||
*
|
||||
* · 内核的 `speech.py` **早就**在按"表格会被渲染"处理朗读文本了
|
||||
* (`_MD_TABLE_SEP` / `_MD_PIPE` 把竖线和分隔行剥掉)。也就是说
|
||||
* **朗读那条路认为表格存在,渲染这条路不存在** —— 两端不一致,
|
||||
* 而我一直没发现,因为语音和界面是分开测的。
|
||||
* · 这个模型(用户的"病娇女友"智能体)非常爱用表格算账,
|
||||
* 截图里那张"一个月开销"表就是。宽表塞进聊天流的后果不是"少个表格",
|
||||
* 而是**满屏竖线 + 换行错位,整段没法读**。
|
||||
*
|
||||
* 所以现在按 GFM 表格实现。教训:**别用"几乎不出现"当不做某个 Markdown
|
||||
* 元素的理由** —— 去内核里看看朗读/复制那些旁路是不是已经假设它存在了。
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
markdown: String,
|
||||
// ★ color 不能给默认值:默认参数里不能调用 @Composable 函数
|
||||
// (doubaoText() 是 @Composable,写成 `color: Color = doubaoText()` 直接编译不过)
|
||||
color: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
linkColor: Color = Doubao.Blue,
|
||||
fontSize: Int = 16,
|
||||
lineHeight: Int = 26,
|
||||
/**
|
||||
* 把(括号)/【方括号】里的旁白显示成灰色小字(v3.27「朗读情绪指令」)。
|
||||
*
|
||||
* ★ 只影响**显示**:真正的朗读文本由内核 speech.prepare_speech 处理
|
||||
* (括号内容不念、改成豆包语音的 context_texts 指令)。两边的括号规则
|
||||
* 必须一致 —— 否则会出现"界面灰了、语音还念"或反过来的错位。
|
||||
*/
|
||||
stageTags: Boolean = false,
|
||||
) {
|
||||
val blocks = remember(markdown) { parseMarkdown(markdown) }
|
||||
val codeBg = if (isDark()) Color(0xFF1B1F27) else Color(0xFFF3F4F6)
|
||||
val quoteBar = Doubao.Blue.copy(alpha = 0.55f)
|
||||
// 旁白样式:更灰、更小。放在 inline() 里按括号匹配,不参与 Markdown 解析。
|
||||
val stageStyle = if (stageTags) {
|
||||
SpanStyle(color = color.copy(alpha = 0.42f), fontSize = (fontSize - 2).sp)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (block in blocks) {
|
||||
when (block) {
|
||||
is MdBlock.Code -> {
|
||||
// 代码块单独一块:等宽字体 + 底色 + 可横向滚动(长行不折行更好读)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(codeBg)
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
block.text.trimEnd(),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = (fontSize - 3).sp,
|
||||
lineHeight = (fontSize + 5).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Quote -> {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
// 左边一条竖线,跟正文区分开
|
||||
Box(
|
||||
Modifier
|
||||
.width(3.dp)
|
||||
.heightIn(min = 20.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(quoteBar),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color.copy(alpha = 0.85f),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> {
|
||||
Text(
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Numbered -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"${block.number}.",
|
||||
fontSize = fontSize.sp,
|
||||
color = color.copy(alpha = 0.7f),
|
||||
modifier = Modifier.width(22.dp),
|
||||
)
|
||||
Text(
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
// 任务列表:方框 + 文字。勾上的加删除线(进度一眼能看出来)
|
||||
is MdBlock.Task -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (block.checked) "☑" else "☐",
|
||||
fontSize = fontSize.sp,
|
||||
color = if (block.checked) Doubao.Blue else color.copy(alpha = 0.55f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = if (block.checked) color.copy(alpha = 0.6f) else color,
|
||||
textDecoration = if (block.checked) TextDecoration.LineThrough else null,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Table -> MarkdownTable(
|
||||
block = block,
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 2.dp)
|
||||
.height(1.dp)
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> {
|
||||
Text(
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 表格渲染 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 一张表。
|
||||
*
|
||||
* ## 为什么是"横向滚动 + 按内容算列宽",而不是等分
|
||||
*
|
||||
* 手机屏宽就 360dp 左右,而这类表格(模型最爱拿它算账)常见的形态是
|
||||
* **第一列很长、后面几列很短**:
|
||||
*
|
||||
* 吃(早150+午363+晚510+零食150) | 1173 | 大头还是晚饭
|
||||
*
|
||||
* 等分的话第一列必然折成三行、而"1173"那一列白白空着一大片。
|
||||
* 按内容量宽 + 整张表横向滚动,窄表看起来就是正常表格,
|
||||
* 宽表右滑能看全 —— 比挤成一坨强。
|
||||
*
|
||||
* ## 列宽怎么算
|
||||
*
|
||||
* 用 [rememberTextMeasurer] 把每一列的所有单元格量一遍取最大值,
|
||||
* 夹在 [MIN_COL_W] 和 [MAX_COL_W] 之间:
|
||||
* · 下限防止"一个月"这种短列被压成一条缝
|
||||
* · 上限防止某一格特别长(模型爱写长句)把整列撑到几屏宽
|
||||
*
|
||||
* ★ 量宽是 `remember(block)` 的:流式输出时每个字都在变,
|
||||
* 每帧重量一遍 20 多个单元格也还好(表格行数一般不超过 15)。
|
||||
*/
|
||||
@Composable
|
||||
private fun MarkdownTable(
|
||||
block: MdBlock.Table,
|
||||
color: Color,
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
stageStyle: SpanStyle? = null,
|
||||
) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
val cols = block.header.size
|
||||
val cellStyle = remember(fontSize) { TextStyle(fontSize = (fontSize - 2).sp) }
|
||||
|
||||
val headBg = if (isDark()) Color(0xFF232A36) else Color(0xFFEDF1F7)
|
||||
val lineColor = color.copy(alpha = 0.14f)
|
||||
|
||||
// 量出来的是 px,除上 density 换成 dp(Compose 里布局一律用 dp)
|
||||
// ★ density / measurer 也进 key:系统字号一变(或旋转)就得重量,
|
||||
// 不然列宽还是照着旧字号的
|
||||
val widths: List<Dp> = remember(block, fontSize, density, measurer) {
|
||||
val pad = with(density) { (CELL_PAD_H * 2).toPx() }
|
||||
// 每列额外留一点余量:测量和真实排版总有一点差(字体 hinting、
|
||||
// 中英文混排的字距),差一点点就会让表头折成两行 —— 很难看
|
||||
val slack = with(density) { 2.dp.toPx() }
|
||||
val minW = with(density) { MIN_COL_W.toPx() }
|
||||
val maxW = with(density) { MAX_COL_W.toPx() }
|
||||
// ★★ 表头是 SemiBold,量它必须用**粗体**的 style。
|
||||
// 用常规字重量的话算出来的列宽偏窄,表头就会被挤到折行 ——
|
||||
// 实测"一个月"三个字被折成"一个"/"月",就是这么来的。
|
||||
val headStyle = cellStyle.copy(fontWeight = FontWeight.SemiBold)
|
||||
(0 until cols).map { c ->
|
||||
var w = 0
|
||||
for (r in -1 until block.rows.size) {
|
||||
val raw = if (r < 0) block.header[c] else block.rows[r][c]
|
||||
val plain = stripInlineMarks(raw)
|
||||
if (plain.isEmpty()) continue
|
||||
val style = if (r < 0) headStyle else cellStyle
|
||||
val measured = measurer.measure(AnnotatedString(plain), style).size.width
|
||||
if (measured > w) w = measured
|
||||
}
|
||||
(((w + pad + slack).coerceIn(minW, maxW)) / density.density).dp
|
||||
}
|
||||
}
|
||||
val totalWidth = widths.fold(0.dp) { acc, w -> acc + w }
|
||||
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
|
||||
Column(Modifier.clip(RoundedCornerShape(10.dp))) {
|
||||
// 表头:整行底色 + 加粗
|
||||
Row(Modifier.width(totalWidth).background(headBg)) {
|
||||
for (c in 0 until cols) {
|
||||
TableCell(
|
||||
text = block.header[c],
|
||||
width = widths[c],
|
||||
align = block.aligns[c],
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
bold = true,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(Modifier.width(totalWidth).height(1.dp).background(lineColor))
|
||||
for ((r, row) in block.rows.withIndex()) {
|
||||
if (r > 0) Box(Modifier.width(totalWidth).height(1.dp).background(lineColor))
|
||||
Row(Modifier.width(totalWidth)) {
|
||||
for (c in 0 until cols) {
|
||||
TableCell(
|
||||
text = row[c],
|
||||
width = widths[c],
|
||||
align = block.aligns[c],
|
||||
color = color,
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TableCell(
|
||||
text: String,
|
||||
width: Dp,
|
||||
align: TextAlign,
|
||||
color: Color,
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
bold: Boolean = false,
|
||||
stageStyle: SpanStyle? = null,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.width(width)
|
||||
.padding(horizontal = CELL_PAD_H, vertical = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
// 单元格里也走行内解析 —— `**合计**`、`` `code` ``、链接都要生效
|
||||
inline(text, linkColor, stageStyle),
|
||||
fontSize = (fontSize - 2).sp,
|
||||
lineHeight = (lineHeight - 4).coerceAtLeast(fontSize).sp,
|
||||
fontWeight = if (bold) FontWeight.SemiBold else null,
|
||||
textAlign = align,
|
||||
color = color,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 单元格左右内边距 */
|
||||
private val CELL_PAD_H = 10.dp
|
||||
|
||||
/** 列宽下限:短列别被压成一条缝 */
|
||||
private val MIN_COL_W = 56.dp
|
||||
|
||||
/** 列宽上限:一格特别长时让它折行,别把整列撑出几屏 */
|
||||
private val MAX_COL_W = 240.dp
|
||||
|
||||
/* ------------------------------ 块级解析 ------------------------------ */
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
data class Paragraph(val text: String) : MdBlock
|
||||
data class Heading(val level: Int, val text: String) : MdBlock
|
||||
data class Bullet(val text: String) : MdBlock
|
||||
data class Numbered(val number: String, val text: String) : MdBlock
|
||||
data class Quote(val text: String) : MdBlock
|
||||
data class Code(val text: String, val lang: String = "") : MdBlock
|
||||
data object Divider : MdBlock
|
||||
|
||||
/** `- [ ] 待办` / `- [x] 做完了` */
|
||||
data class Task(val checked: Boolean, val text: String) : MdBlock
|
||||
|
||||
/**
|
||||
* 表格。
|
||||
*
|
||||
* [rows] 里每行的列数**已经补齐到 [header] 的长度**(缺的填空串)——
|
||||
* 模型偶尔会漏写某一行的某一列,渲染时按列取下标会越界。
|
||||
* 补在这里而不是渲染时,是因为对齐信息 [aligns] 也是按列来的,
|
||||
* 两处各补一次迟早会不一致。
|
||||
*/
|
||||
data class Table(
|
||||
val header: List<String>,
|
||||
val rows: List<List<String>>,
|
||||
val aligns: List<TextAlign>,
|
||||
) : MdBlock
|
||||
}
|
||||
|
||||
private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$")
|
||||
private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$")
|
||||
/** `- [ ] 待办` / `- [x] 已经做了`。**必须排在 [RE_BULLET] 前面判**,否则被当成普通项目符号 */
|
||||
private val RE_TASK = Regex("^\\s*[-*+]\\s+\\[([ xX])]\\s*(.*)$")
|
||||
private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$")
|
||||
private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$")
|
||||
private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$")
|
||||
private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$")
|
||||
|
||||
/** 表格分隔行里的一格:`---`、`:--`、`--:`、`:--:` 都算 */
|
||||
private val RE_TABLE_SEP_CELL = Regex("^:?-{1,}:?$")
|
||||
|
||||
/* ------------------------------ 表格 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 这一行像不像表格行。
|
||||
*
|
||||
* 判据是**至少两个竖线**(`|` 的数量,转义的 `\|` 不算)。
|
||||
* 两端有没有竖线都收 —— 合法 GFM 两种写法都允许:
|
||||
*
|
||||
* | 项目 | 钱 | 项目 | 钱
|
||||
* |---|---| ---|---
|
||||
*
|
||||
* ★ 为什么门槛定在 2 而不是 1:正文里"或者 a | b"这种带一个竖线的句子
|
||||
* 不算少,定 1 会把它们吃掉。
|
||||
*/
|
||||
private fun looksLikeTableRow(line: String): Boolean =
|
||||
line.replace("\\|", "").count { it == '|' } >= 2
|
||||
|
||||
/**
|
||||
* 拆一行表格。
|
||||
*
|
||||
* ★ 转义的竖线(`\|`)要**先换成占位符再切**,否则 `a \| b | c` 会被切成三格。
|
||||
* 占位符用 `\u0001`(正文里不可能出现的控制字符),切完换回来。
|
||||
*/
|
||||
internal fun splitTableRow(line: String): List<String> {
|
||||
var s = line.trim()
|
||||
if (s.startsWith("|")) s = s.substring(1)
|
||||
// 末尾的竖线要去掉,但如果它是转义的(`… \|`)就不是分隔符
|
||||
if (s.endsWith("|") && !s.endsWith("\\|")) s = s.dropLast(1)
|
||||
s = s.replace("\\|", "\u0001")
|
||||
return s.split('|').map { it.replace("\u0001", "|").trim() }
|
||||
}
|
||||
|
||||
/** `|---|:--:|---:|` 这种分隔行 */
|
||||
internal fun isTableSeparator(line: String): Boolean {
|
||||
if (!line.contains('-')) return false
|
||||
val cells = splitTableRow(line)
|
||||
if (cells.isEmpty()) return false
|
||||
return cells.all { it.isNotEmpty() && RE_TABLE_SEP_CELL.matches(it) }
|
||||
}
|
||||
|
||||
/** 分隔行里的冒号决定这一列的对齐方式 */
|
||||
private fun alignOf(cell: String): TextAlign = when {
|
||||
cell.startsWith(":") && cell.endsWith(":") -> TextAlign.Center
|
||||
cell.endsWith(":") -> TextAlign.End
|
||||
else -> TextAlign.Start
|
||||
}
|
||||
|
||||
private class TableRead(val block: MdBlock.Table, val next: Int)
|
||||
|
||||
/**
|
||||
* 从 [start] 行开始读一张表,读不出来返回 null(那就按普通段落处理)。
|
||||
*
|
||||
* 两种情况都认:
|
||||
* ① 标准 GFM —— 表头行 + `|---|---|` 分隔行 + 数据行
|
||||
* ② 模型忘了写分隔行,但**连着两行列数一致**(兜底)
|
||||
*
|
||||
* ★ 数据行读到"不像表格行"就停。不设这个终点的话,表格后面紧跟的正文
|
||||
* 会被一路吃进来(模型写表格后面常常直接接一段总结)。
|
||||
*/
|
||||
private fun readTable(lines: List<String>, start: Int): TableRead? {
|
||||
val headLine = lines.getOrNull(start) ?: return null
|
||||
if (!looksLikeTableRow(headLine)) return null
|
||||
val head = splitTableRow(headLine)
|
||||
if (head.size < 2) return null
|
||||
|
||||
val second = lines.getOrNull(start + 1)
|
||||
val aligns: List<TextAlign>
|
||||
val bodyStart: Int
|
||||
if (second != null && isTableSeparator(second)) {
|
||||
val sep = splitTableRow(second)
|
||||
// 分隔行少写几格(模型手抖)时按表头列数补成左对齐,别让下标越界
|
||||
aligns = (0 until head.size).map { c -> alignOf(sep.getOrElse(c) { "---" }) }
|
||||
bodyStart = start + 2
|
||||
} else if (second != null && looksLikeTableRow(second) && splitTableRow(second).size == head.size) {
|
||||
aligns = List(head.size) { TextAlign.Start }
|
||||
bodyStart = start + 1
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
val rows = ArrayList<List<String>>()
|
||||
var i = bodyStart
|
||||
while (i < lines.size && looksLikeTableRow(lines[i])) {
|
||||
val cells = splitTableRow(lines[i])
|
||||
if (cells.size < 2) break
|
||||
// ★ 按表头列数补齐 / 截断:模型偶尔多写一列或少写一列,
|
||||
// 不补的话渲染时按下标取会越界,截断是为了不让一行的多余列把整表撑歪
|
||||
rows.add((0 until head.size).map { c -> cells.getOrElse(c) { "" } })
|
||||
i += 1
|
||||
}
|
||||
if (rows.isEmpty()) return null
|
||||
return TableRead(MdBlock.Table(head, rows, aligns), i)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把行内标记去掉,只留纯文字 —— 给"量列宽"用。
|
||||
*
|
||||
* ★ 量宽必须用剥过的文本:`| **合计** |` 里的 `**` 不显示,
|
||||
* 按原文量出来的列会白白宽出一截。
|
||||
*/
|
||||
internal fun stripInlineMarks(s: String): String =
|
||||
RE_STRIP_LINK.replace(s) { it.groupValues[1] }
|
||||
.replace("~~", "")
|
||||
.replace("**", "")
|
||||
.replace("`", "")
|
||||
.replace("*", "")
|
||||
|
||||
private val RE_STRIP_LINK = Regex("\\[([^\\]]*)]\\([^)]*\\)")
|
||||
|
||||
internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
val out = ArrayList<MdBlock>()
|
||||
val lines = src.replace("\r\n", "\n").split("\n")
|
||||
val para = StringBuilder()
|
||||
var i = 0
|
||||
|
||||
fun flushPara() {
|
||||
if (para.isNotBlank()) out.add(MdBlock.Paragraph(para.toString().trim()))
|
||||
para.setLength(0)
|
||||
}
|
||||
|
||||
while (i < lines.size) {
|
||||
val line = lines[i]
|
||||
|
||||
// 代码块:``` 开头到下一个 ```(或文件结束)
|
||||
val fence = RE_FENCE.find(line)
|
||||
if (fence != null) {
|
||||
flushPara()
|
||||
val lang = fence.groupValues[1]
|
||||
val body = StringBuilder()
|
||||
i += 1
|
||||
while (i < lines.size && RE_FENCE.find(lines[i]) == null) {
|
||||
body.append(lines[i]).append('\n')
|
||||
i += 1
|
||||
}
|
||||
i += 1 // 跳过收尾的 ```
|
||||
out.add(MdBlock.Code(body.toString(), lang))
|
||||
continue
|
||||
}
|
||||
|
||||
// 表格:多行结构,得像代码块那样整块吃掉(不能按行在 when 里判)
|
||||
if (looksLikeTableRow(line)) {
|
||||
val table = readTable(lines, i)
|
||||
if (table != null) {
|
||||
flushPara()
|
||||
out.add(table.block)
|
||||
i = table.next
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
when {
|
||||
line.isBlank() -> flushPara()
|
||||
|
||||
RE_DIVIDER.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Divider)
|
||||
}
|
||||
|
||||
RE_HEADING.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_HEADING.find(line)!!
|
||||
out.add(MdBlock.Heading(m.groupValues[1].length, m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_QUOTE.matches(line) -> {
|
||||
flushPara()
|
||||
// 连续的引用行合成一段
|
||||
val q = StringBuilder()
|
||||
while (i < lines.size && RE_QUOTE.matches(lines[i])) {
|
||||
if (q.isNotEmpty()) q.append(' ')
|
||||
q.append(RE_QUOTE.find(lines[i])!!.groupValues[1])
|
||||
i += 1
|
||||
}
|
||||
out.add(MdBlock.Quote(q.toString().trim()))
|
||||
continue
|
||||
}
|
||||
|
||||
// ★ 任务列表必须排在普通项目符号前面 —— `- [x] 干完了` 也满足 RE_BULLET
|
||||
RE_TASK.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_TASK.find(line)!!
|
||||
out.add(MdBlock.Task(m.groupValues[1].isNotBlank(), m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_BULLET.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim()))
|
||||
}
|
||||
|
||||
RE_NUMBERED.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_NUMBERED.find(line)!!
|
||||
out.add(MdBlock.Numbered(m.groupValues[1], m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
else -> {
|
||||
if (para.isNotEmpty()) para.append('\n')
|
||||
para.append(line)
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
flushPara()
|
||||
return out
|
||||
}
|
||||
|
||||
/** 一条回复里提到的一个网页 */
|
||||
data class FoundUrl(
|
||||
/** 完整地址 */
|
||||
val url: String,
|
||||
/** 模型给链接写的文字(`[文字](url)` 里的那个),没有就是空串 */
|
||||
val label: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* 从 markdown 里抽出所有网页地址(去重、保序,带上链接文字)。
|
||||
*
|
||||
* ## ★★ 重写过一版:原来漏了 7/11 种写法
|
||||
*
|
||||
* 上一版是手写扫描器,**只认 `](` 紧挨着的 markdown 链接**。
|
||||
* 实测(`scripts/probe-extract-urls.py`)漏掉这些:
|
||||
*
|
||||
* · **裸 URL** —— `见 https://example.com`(**模型最常这么写**)
|
||||
* · `[文字] (地址)` —— 中英混排时中间常有空格
|
||||
* · `<https://example.com>` —— 尖括号包裹
|
||||
* · 中文标点紧跟着的 URL —— `见(https://…)。`
|
||||
* · 换行里的裸 URL
|
||||
* · `www.example.com`
|
||||
*
|
||||
* 后果不是"少显示一个链接",而是 **`extractUrls` 返回空 → 整个
|
||||
* 「打开网页」按钮都不显示**(用户报的"还是没有"就是这个)。
|
||||
*
|
||||
* 现在改成**正则扫全文**,两类都收:markdown 链接 + 裸 URL。
|
||||
*
|
||||
* ★ 只认 http/https。`[文档](docs/x.md)` 这种相对路径在手机上点了没意义,
|
||||
* 不算"网页"(剪掉尾巴上的中文标点和右括号,别把 `)。` 吞进地址里)。
|
||||
*/
|
||||
fun extractUrls(markdown: String): List<FoundUrl> {
|
||||
if (!markdown.contains("http://") && !markdown.contains("https://")) return emptyList()
|
||||
val out = LinkedHashSet<String>()
|
||||
val labels = HashMap<String, String>()
|
||||
|
||||
// ① markdown 链接:[文字](地址),允许中间有空格、文字里有方括号
|
||||
RE_MD_LINK.findAll(markdown).forEach { m ->
|
||||
val label = m.groupValues[1].trim().trim('[', ']')
|
||||
val url = cleanUrl(m.groupValues[2])
|
||||
if (url.isNotEmpty()) {
|
||||
if (label.isNotEmpty()) labels.putIfAbsent(url, label)
|
||||
out.add(url)
|
||||
}
|
||||
}
|
||||
|
||||
// ② 裸 URL / 尖括号包裹的 URL
|
||||
RE_BARE_URL.findAll(markdown).forEach { m ->
|
||||
val url = cleanUrl(m.value)
|
||||
if (url.isNotEmpty()) out.add(url)
|
||||
}
|
||||
|
||||
return out.map { FoundUrl(it, labels[it] ?: "") }
|
||||
}
|
||||
|
||||
/**
|
||||
* 剪掉 URL 尾巴上不属于地址的字符。
|
||||
*
|
||||
* ★ 必须做:中文回复里 URL 后面常紧跟 `)。`、`,`、`】`,
|
||||
* 不剪的话地址里会带上这些,打开必然 404。
|
||||
* 左右括号要配对判断(`.../a_(b)` 这种地址本身带括号,不能一刀切)。
|
||||
*/
|
||||
private fun cleanUrl(raw: String): String {
|
||||
var s = raw.trim().trim('<', '>', '"', '\'', '`')
|
||||
// 尾部的中文标点/空白一律剪掉
|
||||
s = s.trimEnd('。', ',', '、', ';', ':', '!', '?', ')', '】', '》', '」', '』', '…', '.', ',', ';', ':', '!', '?')
|
||||
// 去掉不配对的右括号
|
||||
while (s.endsWith(")") && s.count { it == ')' } > s.count { it == '(' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
while (s.endsWith("]") && s.count { it == ']' } > s.count { it == '[' }) {
|
||||
s = s.dropLast(1)
|
||||
}
|
||||
if (!s.startsWith("http://") && !s.startsWith("https://")) return ""
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* markdown 链接 `[文字](地址)`。
|
||||
*
|
||||
* ★★ 地址部分用 **`(?:[^\s()]|\([^\s()]*\))+`** 而不是 `[^\s)]+`。
|
||||
*
|
||||
* 起因是一条维基百科地址:`https://en.wikipedia.org/wiki/A_(b)`
|
||||
*
|
||||
* · 用 `[^\s)]+` 的话,它在 `A_(b` 处被第一个 `)` 截断 ——
|
||||
* 然后外层那个 `\)` 匹配的是**地址里那个右括号**,
|
||||
* 于是算出来的地址是 `https://en.wikipedia.org/wiki/A_(b`(缺一个括号、点开 404)
|
||||
* · 而且裸 URL 规则会再匹配一次,得到另一个截断版本 →
|
||||
* **同一个链接在列表里出现两次,两个都不对**
|
||||
*
|
||||
* "平衡括号"这个写法让右括号只能以完整 `(…)` 的形式出现在地址里,
|
||||
* 所以维基那种地址能整个吃到,而 markdown 的收尾括号仍然能正确识别。
|
||||
*
|
||||
* ★ 文字部分用 `[^\]\n]*` 而不是 `.*?` —— 后者在长回复里可能跨行吞掉一大段。
|
||||
*/
|
||||
private val RE_MD_LINK =
|
||||
Regex("""\[([^\]\n]{1,200})]\s*\(\s*(https?://(?:[^\s()]|\([^\s()]*\))+)\s*\)""")
|
||||
|
||||
/**
|
||||
* 裸 URL(含尖括号包裹)。
|
||||
*
|
||||
* ★★ 同样用"平衡括号"写法。两种错法都踩过:
|
||||
*
|
||||
* · 允许右括号(`[^\s]+`)→ `[x](https://a.com)` 会被**再匹配一次**,
|
||||
* 同一条链接算出两个不同地址(一个还带多余的右括号)
|
||||
* · 完全禁止括号(`[^\s()]+`)→ `.../wiki/A_(b)` 被截断成 `.../wiki/A_`
|
||||
*
|
||||
* 到空白或中文标点为止(中文回复里 URL 后面常紧跟 `)。`、`,`)。
|
||||
*/
|
||||
private val RE_BARE_URL =
|
||||
Regex("""<?https?://(?:[^\s<>()\[\]{}()【】「」『』,。;:!?、]|\([^\s()]*\))+>?""")
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 行内标记 → AnnotatedString。
|
||||
*
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*
|
||||
* ★ 这是个 `@Composable`:链接要用 `withLink(...)` 挂点击,
|
||||
* 而那个 API 是 composable 的(它内部要拿 `LocalTextLinkScope`)。
|
||||
*
|
||||
* ★ 还要 `@OptIn(ExperimentalTextApi::class)` —— `withLink` 标了实验 API。
|
||||
* 不 opt-in 的话报的是 `Unresolved reference 'withLink'`(不是"需要 opt-in"),
|
||||
* 很容易误判成"这个版本没有这个 API"。我是把 aar 拆开 javap 看了注解才确认的。
|
||||
*/
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
@Composable
|
||||
internal fun inline(
|
||||
text: String,
|
||||
linkColor: Color,
|
||||
/** 旁白(括号)样式;null = 不特殊显示(设置里的「朗读情绪指令」关掉时) */
|
||||
stageStyle: SpanStyle? = null,
|
||||
): AnnotatedString {
|
||||
val ctx = LocalContext.current
|
||||
return buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
// ★ v3.27:括号旁白先整段套样式,再按普通字符走后面的 Markdown 解析。
|
||||
// 规则只认成对括号、单段 ≤60 字、不跨行 —— 和内核 speech.py 的
|
||||
// `_STAGE_RE` 对齐(那边负责不念出来 + 变成语音指令)。
|
||||
val stageEnd = if (stageStyle != null) findStageEnd(text, i) else -1
|
||||
if (stageEnd > i) {
|
||||
withStyle(stageStyle!!) { append(text.substring(i, stageEnd + 1)) }
|
||||
i = stageEnd + 1
|
||||
continue
|
||||
}
|
||||
when {
|
||||
// 行内代码:`code`
|
||||
text[i] == '`' -> {
|
||||
val end = text.indexOf('`', i + 1)
|
||||
if (end > i) {
|
||||
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp)) {
|
||||
append(text.substring(i + 1, end))
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 粗斜体 / 粗体 / 斜体:***x***、**x**、*x*
|
||||
text.startsWith("***", i) || text.startsWith("**", i) || text[i] == '*' -> {
|
||||
val marker = when {
|
||||
text.startsWith("***", i) -> "***"
|
||||
text.startsWith("**", i) -> "**"
|
||||
else -> "*"
|
||||
}
|
||||
val end = text.indexOf(marker, i + marker.length)
|
||||
// 找不到收尾、或者里面是空的,就当普通字符
|
||||
if (end > i + marker.length) {
|
||||
val inner = text.substring(i + marker.length, end)
|
||||
val style = when (marker) {
|
||||
"***" -> SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic)
|
||||
"**" -> SpanStyle(fontWeight = FontWeight.Bold)
|
||||
else -> SpanStyle(fontStyle = FontStyle.Italic)
|
||||
}
|
||||
withStyle(style) { append(inner) }
|
||||
i = end + marker.length
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 删除线:~~x~~
|
||||
text.startsWith("~~", i) -> {
|
||||
val end = text.indexOf("~~", i + 2)
|
||||
if (end > i + 2) {
|
||||
withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) {
|
||||
append(text.substring(i + 2, end))
|
||||
}
|
||||
i = end + 2
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 链接:[文字](地址)
|
||||
text[i] == '[' -> {
|
||||
val close = text.indexOf(']', i)
|
||||
val open = if (close > 0 && close + 1 < text.length && text[close + 1] == '(') close + 1 else -1
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
val url = text.substring(open + 1, end).trim()
|
||||
/**
|
||||
* ★★ 给链接**真正绑上点击**。
|
||||
*
|
||||
* 以前这里只有颜色和下划线,**没有 clickable** ——
|
||||
* 看着像能点、点了完全没反应。用户会以为"链接坏了"。
|
||||
* (这是用户问"网页在哪点开"时才查出来的:我一直在讲
|
||||
* AI 弹的那个界面,而最容易想到的"点链接"一直是坏的。)
|
||||
*
|
||||
* ★ 用 `withLink(LinkAnnotation.Url(...))`:这是 Compose 1.7
|
||||
* 起的方式,和 `Text()` 直接配合(不需要 ClickableText),
|
||||
* 而且**不需要在外部套 pointerInput 去算点击落在哪个字符上**。
|
||||
* 那个老办法要自己遍历 annotation 范围,容易算错。
|
||||
*/
|
||||
if (url.isNotEmpty()) {
|
||||
withLink(
|
||||
LinkAnnotation.Url(
|
||||
url = url,
|
||||
styles = TextLinkStyles(
|
||||
style = SpanStyle(
|
||||
color = linkColor,
|
||||
textDecoration = TextDecoration.Underline,
|
||||
),
|
||||
),
|
||||
linkInteractionListener = { link ->
|
||||
val target = (link as? LinkAnnotation.Url)?.url ?: url
|
||||
openInBrowser(ctx, target)
|
||||
},
|
||||
),
|
||||
) { append(label) }
|
||||
} else {
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 找一处「旁白」的收尾下标:(……)(……)【……】[……]。
|
||||
*
|
||||
* 返回 -1 = 当前位置不是旁白开头。规则(和内核 speech.py 的 `_STAGE_RE` 对齐):
|
||||
* · 成对括号、内容 1~60 字、不跨行;
|
||||
* · `[` 后面紧跟 `(` 的是 Markdown 链接(`[文字](url)`),不算旁白 —— 交给链接分支。
|
||||
*/
|
||||
private fun findStageEnd(text: String, start: Int): Int {
|
||||
val close = when (text[start]) {
|
||||
'(' -> ')'
|
||||
'(' -> ')'
|
||||
'【' -> '】'
|
||||
'[' -> ']'
|
||||
else -> return -1
|
||||
}
|
||||
var j = start + 1
|
||||
while (j < text.length && j - start <= 61) {
|
||||
val c = text[j]
|
||||
if (c == '\n' || c == close) break
|
||||
j++
|
||||
}
|
||||
if (j >= text.length || text[j] != close || j == start + 1) return -1
|
||||
// Markdown 链接 [文字](url):别当旁白吞掉(链接分支要拿它渲染成可点)
|
||||
if (text[start] == '[' && j + 1 < text.length && text[j + 1] == '(') return -1
|
||||
return j
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import com.doubao.lynxclone.data.CustomNodeDef
|
||||
import com.doubao.lynxclone.data.MeetingNode
|
||||
import com.doubao.nodekit.CastKinds
|
||||
import com.doubao.nodekit.CustomNodePins
|
||||
import com.doubao.nodekit.JudgeKinds
|
||||
import com.doubao.nodekit.NodeCatalog
|
||||
import com.doubao.nodekit.NodeGeometry
|
||||
import com.doubao.nodekit.NodeSpecs
|
||||
import com.doubao.nodekit.NodeStyles
|
||||
import com.doubao.nodekit.NodeView
|
||||
import com.doubao.nodekit.Ops
|
||||
import com.doubao.nodekit.PinDecl
|
||||
import com.doubao.nodekit.PinKind
|
||||
import com.doubao.nodekit.PinSpec
|
||||
|
||||
/*
|
||||
* 会议节点库(`:nodekit`)和 App 之间的**唯一一层胶水**。
|
||||
*
|
||||
* ## 这层为什么必须存在,而且必须**薄**
|
||||
*
|
||||
* 库不认 App 的 `MeetingNode` / `CustomNodeDef`(那是刻意的,见 nodekit/Pins.kt 的
|
||||
* NodeView 注释)。所以中间要有人做转换。
|
||||
*
|
||||
* 危险的地方在于:这层一旦开始"顺手做点事"(补个默认值、改个判断、加个特例),
|
||||
* 它就变成了**第二份定义** —— 而这次的整个目的就是把散在 6 个地方的节点定义
|
||||
* 收成一份。所以这里只有三件事:
|
||||
*
|
||||
* 1. `MeetingNode` → [NodeView](纯字段搬运,**一个判断都不许有**)
|
||||
* 2. 库的 `Int` 颜色 → Compose 的 `Color`
|
||||
* 3. 库的扁平 API → App 原来的函数名(这样 `MeetingsScreen.kt` 里几百个
|
||||
* 调用点一行都不用改 —— 迁移的风险全压在这一层,而它能一眼看完全文)
|
||||
*
|
||||
* ★ 反过来也成立:**这里的每个 `fun` 都必须能在库里找到对应物**。
|
||||
* `scripts/verify-nodekit.py` 会检查这一点(数一遍适配层的函数是不是都只是转发)。
|
||||
*/
|
||||
|
||||
/* ------------------------------ 1. 类型转换 ------------------------------ */
|
||||
|
||||
/** App 的自定义节点定义 → 库只要的"引脚部分" */
|
||||
fun CustomNodeDef.toPins(): CustomNodePins = CustomNodePins(
|
||||
inputs = inputs.map { PinDecl(it.name, it.type) },
|
||||
outputs = outputs.map { PinDecl(it.name, it.type) },
|
||||
)
|
||||
|
||||
/**
|
||||
* App 的节点 → 库认识的节点视图。
|
||||
*
|
||||
* ★ [varTypes] 是必须的:写变量的入口类型、读变量的出口类型都按变量登记表查,
|
||||
* 写死 `str` 的话 num 变量的线接不到运算节点上(这个 bug 真出现过)。
|
||||
*/
|
||||
fun MeetingNode.nodeView(
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): NodeView = NodeView(
|
||||
type = type,
|
||||
op = op,
|
||||
varName = varName,
|
||||
valueType = valueType,
|
||||
castTo = castTo,
|
||||
customKey = customKey,
|
||||
custom = custom.firstOrNull { it.key == customKey }?.toPins(),
|
||||
varTypes = varTypes,
|
||||
)
|
||||
|
||||
/* ------------------------------ 2. 引脚 ------------------------------ */
|
||||
|
||||
/** 输入引脚。实现只有一句:转成 NodeView 交给库 */
|
||||
fun inputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): List<PinSpec> = NodeSpecs.inputPins(node.nodeView(custom, varTypes))
|
||||
|
||||
/** 输出引脚。同上 */
|
||||
fun outputPins(
|
||||
node: MeetingNode,
|
||||
custom: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): List<PinSpec> = NodeSpecs.outputPins(node.nodeView(custom, varTypes))
|
||||
|
||||
/* ------------------------------ 3. 几何 ------------------------------ */
|
||||
|
||||
/** 卡片宽度(画布上所有布局都按它算) */
|
||||
internal const val NODE_W = NodeGeometry.WIDTH
|
||||
|
||||
/** 顶部彩色标题栏的高度 */
|
||||
internal const val HEADER_H = NodeGeometry.HEADER_H
|
||||
|
||||
/** 一行引脚占的高度 */
|
||||
internal const val PIN_ROW_H = NodeGeometry.PIN_ROW_H
|
||||
|
||||
/** 引脚下面的内容区 */
|
||||
internal const val BODY_H = NodeGeometry.BODY_H
|
||||
|
||||
/** 引脚画多大 / 命中范围多大 */
|
||||
internal const val PORT_R = NodeGeometry.PORT_R
|
||||
internal const val PORT_HIT = NodeGeometry.PORT_HIT
|
||||
|
||||
/** 画布右下留的空白 */
|
||||
internal const val CANVAS_MARGIN = NodeGeometry.MARGIN
|
||||
|
||||
/** 节点高矮跟着引脚数走 */
|
||||
fun nodeHeight(
|
||||
node: MeetingNode,
|
||||
customDefs: List<CustomNodeDef> = emptyList(),
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
): Float = NodeGeometry.height(node.nodeView(customDefs, varTypes))
|
||||
|
||||
/** 第 index 个引脚的坐标 */
|
||||
fun pinPos(node: MeetingNode, index: Int, isOutput: Boolean): Offset =
|
||||
NodeGeometry.pinPos(node.x, node.y, index, isOutput)
|
||||
|
||||
/** 按 (种类, 分支) 找输出引脚的序号 */
|
||||
fun outPinIndex(node: MeetingNode, kind: String, branch: String): Int =
|
||||
NodeGeometry.outPinIndex(node.nodeView(), kind, branch)
|
||||
|
||||
/** 输入端口的位置 */
|
||||
fun portIn(
|
||||
node: MeetingNode,
|
||||
kind: String,
|
||||
varTypes: Map<String, String> = emptyMap(),
|
||||
pinKey: String = "",
|
||||
): Offset = NodeGeometry.portIn(node.nodeView(varTypes = varTypes), node.x, node.y, kind, pinKey)
|
||||
|
||||
/** 输出端口的位置 */
|
||||
fun portOut(
|
||||
node: MeetingNode,
|
||||
kind: String,
|
||||
branch: String,
|
||||
pinKey: String = "",
|
||||
): Offset = NodeGeometry.portOut(node.nodeView(), node.x, node.y, kind, branch, pinKey)
|
||||
|
||||
/** 画布要多大 */
|
||||
fun canvasSize(nodes: List<MeetingNode>): Pair<Float, Float> =
|
||||
NodeGeometry.canvasSize(nodes.map { Triple(it.x, it.y, nodeHeight(it)) })
|
||||
|
||||
/** 平移量的夹取 */
|
||||
fun clampPan(
|
||||
x: Float, y: Float,
|
||||
viewW: Float, viewH: Float,
|
||||
contentW: Float, contentH: Float,
|
||||
): Pair<Float, Float> = NodeGeometry.clampPan(x, y, viewW, viewH, contentW, contentH)
|
||||
|
||||
/* ------------------------------ 4. 配色 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 节点标题栏颜色。
|
||||
*
|
||||
* ★ 这里没有 `when` —— 颜色在库里跟着节点类型走(`NodeCatalog`)。
|
||||
* 以前这个函数是 31 行的 when,加一种节点忘改它就少一个颜色,
|
||||
* 而且**不报错**(默默落到"智能体蓝")。
|
||||
*/
|
||||
fun nodeColor(type: String): Color = Color(NodeCatalog.color(type))
|
||||
|
||||
/** 数据引脚按类型上色 */
|
||||
fun pinColor(kind: String): Color = Color(NodeStyles.pinColor(kind))
|
||||
|
||||
/** 按**引脚**算颜色:收全部类型的引脚是紫的 */
|
||||
fun pinColorOf(pin: PinSpec): Color = Color(NodeStyles.pinColorOf(pin))
|
||||
|
||||
/**
|
||||
* 引脚的边框色。
|
||||
*
|
||||
* ★ 库给的是不透明色,这里统一加 0.85 的透明度 —— 描边比填充淡一点才好看。
|
||||
* 这个"淡一点"是**渲染方的事**,所以留在这一层(库不该知道我们要多淡)。
|
||||
*/
|
||||
fun pinBorder(kind: String): Color = pinColor(kind).copy(alpha = 0.85f)
|
||||
|
||||
/** 执行引脚的描边色(白引脚描在浅色背景上,不描边看不见) */
|
||||
val EXEC_BORDER: Color = Color(NodeStyles.EXEC_BORDER)
|
||||
|
||||
/** 连线的颜色(数据线按类型、exec 线按分支真假) */
|
||||
fun wireColor(pin: PinSpec): Color = Color(NodeStyles.wireColor(pin))
|
||||
|
||||
/**
|
||||
* 一条线的类型说明(鼠标/长按提示里用)。
|
||||
*
|
||||
* ★ 这**不是** `PinKind.label`:那是"文本/数字/真假"(说数据类型),
|
||||
* 这是"str 数据线/执行线"(说线的种类)。用户看到的是后者。
|
||||
*/
|
||||
fun kindLabel(kind: String): String = when (kind) {
|
||||
PinKind.EXEC -> "执行线"
|
||||
PinKind.BOOL -> "bool 数据线"
|
||||
PinKind.NUM -> "num 数据线"
|
||||
PinKind.LEGACY_DATA -> "str 数据线"
|
||||
else -> "str 数据线"
|
||||
}
|
||||
|
||||
/** 变量类型的中文名 */
|
||||
fun typeLabel(type: String): String = PinKind.label(type)
|
||||
|
||||
/**
|
||||
* 变量 / 值节点的类型选项。
|
||||
*
|
||||
* ★ 这四项以前在界面里**逐字重复了三处**(变量管理、值节点、转换节点),
|
||||
* 加一种类型必然漏改一处 —— 而漏改的表现是"某个界面选不到新类型",
|
||||
* 不报错、也没人会发现。现在只有这一份。
|
||||
*/
|
||||
val VARIABLE_TYPE_OPTIONS: List<Pair<String, String>> =
|
||||
PinKind.DATA.map { it to PinKind.labelWithKey(it) }
|
||||
|
||||
/**
|
||||
* 转换节点的目标类型选项。
|
||||
*
|
||||
* ★ 单独一份而不是复用 [VARIABLE_TYPE_OPTIONS]:这两个列表**现在**内容一样,
|
||||
* 但意思不同("变量能是什么类型" vs "能转成什么类型")——
|
||||
* 将来变量加了新类型,不代表转换也支持。混用一次就分不开了。
|
||||
*/
|
||||
val CAST_TYPE_OPTIONS: List<Pair<String, String>> =
|
||||
CastKinds.ALL.map { it to PinKind.labelWithKey(it) }
|
||||
|
||||
/**
|
||||
* 判断条件的可选项。
|
||||
*
|
||||
* ★ 正常情况下用内核给的(`meetingMeta.judgeKinds`,那是权威);这里只是
|
||||
* **meta 还没加载到时的兜底** —— 以前 meta 为空时那个选择器是空的,
|
||||
* 用户点开一片空白,会以为界面坏了。
|
||||
*/
|
||||
val JUDGE_KIND_OPTIONS: List<Pair<String, String>> = JudgeKinds.ALL
|
||||
|
||||
/* ------------------------------ 5. 算子 ------------------------------ */
|
||||
|
||||
/** `(键, 显示名)` 列表 —— 配置面板里的下拉项 */
|
||||
val OPS_UI: List<Pair<String, String>> = Ops.ALL.map { it.key to it.label }
|
||||
|
||||
/** 算子的显示名 */
|
||||
fun opLabel(key: String): String = Ops.label(key)
|
||||
|
||||
/**
|
||||
* 算子的 `(入口类型, 出口类型, 要几个输入)`。
|
||||
*
|
||||
* ★ 保留这个三元组而不是直接换成 `Ops.of()`:调用点有 4 处(引脚表 + 配置面板),
|
||||
* 换签名要动它们全部,而它们本来就是按三元组用的。
|
||||
* `opSpec` 自己只有三行,且**不含任何规则**(规则在 `Ops.ALL` 那张表里)。
|
||||
*/
|
||||
fun opSpec(key: String): Triple<String, String, Int> {
|
||||
val op = Ops.of(key)
|
||||
return Triple(op.inType, op.outType, op.arity)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,662 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.MemoryItem
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import com.doubao.lynxclone.data.PRESET_DEAD
|
||||
import com.doubao.lynxclone.data.MemorySpace
|
||||
|
||||
/*
|
||||
* 记忆管理(需求 3.2 / 3.5)。
|
||||
*
|
||||
* ## 这个界面存在的理由
|
||||
*
|
||||
* 需求里记忆是"**混合制**":AI 通过工具自主读写,**用户手动编辑兜底**。
|
||||
* 没有这个界面,"兜底"就是空话 —— AI 记错了东西,用户只能干看着
|
||||
* (而他会记错:模型把"他喜欢猫"记成"他讨厌猫"这种事很常见)。
|
||||
*
|
||||
* 顺带把三样东西一起放进来,因为它们都是"这个智能体的内在状态":
|
||||
* · 情绪(需求 3.5:用户可手动编辑)
|
||||
* · AI 提的"该整理记忆了"建议(需求 3.2:仅提示,用户确认才执行)
|
||||
* · 导入 / 导出(需求 3.4)
|
||||
*
|
||||
* ## 记忆空间:默认私有 + 共享板子(v3.16)
|
||||
*
|
||||
* 用户反馈「怎么串味了豆包怎么读的了小黑的记忆」之后,默认空间从
|
||||
* "一局共享"改成了"**每个智能体一份私有**":
|
||||
* · 私有记忆:只有这个智能体自己读写 / 注入(这一页的默认视角);
|
||||
* · 共享板子:显式共享的条目(`memory_add(shared=true)`),全一局可见。
|
||||
* 两条都还在 —— 但界面必须写清楚"你在看哪一份",不然用户会以为记忆丢了。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun MemoryScreen(
|
||||
space: MemorySpace?,
|
||||
agentName: String,
|
||||
/** 正在看谁的记忆 —— 用来判断"这条是不是别人写的" */
|
||||
agentId: String,
|
||||
/** 所有智能体的 id → 名字(共享记忆里显示"由某某写入") */
|
||||
agentNames: Map<String, String>,
|
||||
/**
|
||||
* **世界观视角**("这个世界里大家共同记得什么")。
|
||||
*
|
||||
* ★ 只读:增删改仍从智能体那边做。世界观视角没有"我",
|
||||
* 而共享空间的写入限权是按 author 判的(需求 3.6)——
|
||||
* 硬做一个权限含义不明的界面,只会让人误操作。
|
||||
* 情绪也藏起来:情绪是**智能体私有**的,不属于这个空间。
|
||||
*/
|
||||
worldMode: Boolean = false,
|
||||
loading: Boolean,
|
||||
hint: String,
|
||||
/** 保存情绪:preset(五档)+ text(自由一句) */
|
||||
onSetEmotion: (String, String) -> Unit,
|
||||
onAdd: (String, String) -> Unit,
|
||||
onUpdate: (String, String?, String?) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onTogglePin: (String, Boolean) -> Unit,
|
||||
onSummarize: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
/** 调注入窗口(条数,0 = 不限) */
|
||||
onSetWindow: (Int) -> Unit,
|
||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||
onImportClick: () -> Unit,
|
||||
/** (兼容旧调用)看私有记忆 —— 现在默认就是私有,等同于 no-op */
|
||||
onOpenOwn: () -> Unit = {},
|
||||
/** (兼容旧调用)从旧空间回到当前空间 */
|
||||
onBackToActive: () -> Unit = {},
|
||||
/** 去看**这一局的共享记忆**(所有角色都能看到的那份) */
|
||||
onOpenShared: () -> Unit = {},
|
||||
/** 从共享记忆回到自己的私有记忆 */
|
||||
onBackToPrivate: () -> Unit = {},
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
/** 情绪的双字段草稿(v1.2)。preset 是五档之一、text 是自由文本 */
|
||||
var emotionPreset by remember(space?.emotion) { mutableStateOf(space?.emotion?.preset ?: "平常") }
|
||||
var emotionText by remember(space?.emotion) { mutableStateOf(space?.emotion?.text ?: "") }
|
||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||
var confirmSummarize by remember { mutableStateOf(false) }
|
||||
/** 调注入窗口(输入条数,0 = 不限) */
|
||||
var editWindow by remember { mutableStateOf(false) }
|
||||
var windowDraft by remember(space?.window) { mutableStateOf((space?.window ?: 0).toString()) }
|
||||
/** ★ v3.16:正在看**这一局的共享记忆**(不是自己的私有记忆) */
|
||||
val readingShared = space?.sharedView == true
|
||||
|
||||
FullScreen(
|
||||
title = "记忆",
|
||||
subtitle = buildString {
|
||||
append(agentName.ifBlank { "智能体" })
|
||||
append(" · ")
|
||||
when {
|
||||
worldMode -> append("世界观共享记忆")
|
||||
readingShared -> append("本局共享记忆")
|
||||
space == null -> append("读取中")
|
||||
else -> append("私有记忆")
|
||||
}
|
||||
space?.let { append(" ${it.memories.size} 条") }
|
||||
if (loading) append(" · 处理中…")
|
||||
},
|
||||
onBack = { if (readingShared) onBackToPrivate() else onBack() },
|
||||
actions = {
|
||||
// 世界观视角是纯只读(导入/导出都以"某个智能体的记忆"为单位,
|
||||
// 而这里没有"我")—— 不给按钮,而不是给一个点了没反应的按钮
|
||||
if (!worldMode && !readingShared) TopTextAction("导入", onClick = onImportClick)
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
/* ---- 空间标识(复查报告 4.1 / v3.16)----
|
||||
*
|
||||
* ★ 这是这个界面最重要的一段字。
|
||||
* 默认空间变了、或者有另一块共享板子时,不说明的话用户
|
||||
* 必然判定"我的记忆丢了 / 记忆串味了"。
|
||||
*/
|
||||
if (readingShared) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.clickable { onBackToPrivate() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是这一局的共享记忆:所有角色都能看到(每条标了是谁写的)。" +
|
||||
"AI 只能改自己写的条目,别人的你可以在这里手动删。" +
|
||||
"私密的事别放共享 —— 点这里回到自己的私有记忆。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if (!worldMode && (space?.sharedCount ?: 0) > 0) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onOpenShared() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这一局还有 ${space?.sharedCount ?: 0} 条共享记忆(所有角色共用、显式共享的),还留着。" +
|
||||
"下面这些才是你自己的私有记忆 —— 点这里去看共享板子 ›",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口(一遍看不出来"哪些真的进去了",所以直接写清)----
|
||||
if (!readingShared && !worldMode && space != null) {
|
||||
val total = space.memories.size
|
||||
val win = space.window
|
||||
val injected = space.injected
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { windowDraft = win.toString(); editWindow = true }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
// ★ "列表里有 300 条"和"带进去 50 条"是完全不同的两件事。
|
||||
// 不写清楚的话,用户会以为记忆全都在提示词里。
|
||||
"这一轮会带进去 $injected / $total 条",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
buildString {
|
||||
append("窗口:")
|
||||
append(if (win <= 0) "不限(全部都带)" else "最近 $win 条")
|
||||
append("。")
|
||||
// ★ "能置顶几条"必须在界面上说清:不说的话用户会默认
|
||||
// "只能有一条"(很自然的假设),而实际上标几条都行,
|
||||
// 而且它们**永远**带进去、不受窗口限制。
|
||||
append(
|
||||
if (space.pinnedCount > 0) "已置顶 ${space.pinnedCount} 条"
|
||||
else "可以置顶任意多条"
|
||||
)
|
||||
append(",置顶的永远带、不受窗口限制")
|
||||
if (injected < total) {
|
||||
append(";没带进去的没丢,AI 用 memory_search 还能搜到")
|
||||
}
|
||||
append("。 点这里调 ›")
|
||||
},
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
|
||||
if (worldMode) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是这个世界观里所有人共同记得的 —— 绑定了它的智能体共用这一份。\n" +
|
||||
"这里只供查看(改和删请从各自的智能体进去,那边才知道「我」是谁);" +
|
||||
"每条都标了是谁写的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- AI 的建议(需求 3.2:仅提示,用户确认才执行)----
|
||||
if (!readingShared && !space?.suggestion.isNullOrBlank()) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.08f))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("AI 觉得记忆该整理一下了", fontSize = 12.sp, color = Doubao.Blue)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(space?.suggestion ?: "", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Text(
|
||||
"整理",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable(enabled = !loading) { onSummarize() }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (hint.isNotBlank()) {
|
||||
Text(
|
||||
hint,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 情绪(世界观/共享视角没有"自己的情绪",隐藏)----
|
||||
if (!worldMode && !readingShared) {
|
||||
SectionLabel("情绪")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"preset 决定系统行为(立绘换哪张、能不能对话、同伴看到什么脸色);" +
|
||||
"下面那句话只是扮演质感。AI 自己能改,你也可以在这里改。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★ 五档选择器,顺序就是需求里的顺序(喜 怒 哀 平常 死亡)。
|
||||
// 「死亡」单独标红 —— 它是**唯一有系统后果**的档位。
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
for (p in PRESETS) {
|
||||
val on = p == emotionPreset
|
||||
val danger = p == PRESET_DEAD
|
||||
Text(
|
||||
p,
|
||||
fontSize = 13.sp,
|
||||
color = when {
|
||||
on -> Color.White
|
||||
danger -> Color(0xFFB3261E)
|
||||
else -> doubaoText()
|
||||
},
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(
|
||||
when {
|
||||
on && danger -> Color(0xFFB3261E)
|
||||
on -> Doubao.Blue
|
||||
else -> doubaoCard()
|
||||
},
|
||||
)
|
||||
.clickable { emotionPreset = p }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
// 死亡是唯一需要额外解释的档位:它会让这个智能体**不能对话**。
|
||||
// 不说清楚的话,用户点了「死亡」然后发现消息发不出去,会以为坏了。
|
||||
if (emotionPreset == PRESET_DEAD) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"「死亡」状态下这个智能体不能对话(输入条会禁用)。" +
|
||||
"把它改回其他档就是复活 —— 这是你的权力,AI 自己不能从死亡改活。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = emotionText,
|
||||
onValueChange = { emotionText = it },
|
||||
placeholder = { Text("他此刻在想什么(自由一句,比如:强作镇定,手心全是汗)", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||
TextButton(
|
||||
onClick = { onSetEmotion(emotionPreset, emotionText.trim()) },
|
||||
enabled = emotionPreset != (space?.emotion?.preset ?: "平常") ||
|
||||
emotionText.trim() != (space?.emotion?.text ?: ""),
|
||||
) { Text("保存情绪", fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 操作条 ----
|
||||
SectionLabel("记忆(按时间排,最新的在下面)")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!readingShared && !worldMode) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingShared && !worldMode) {
|
||||
SmallAction(if (loading) "整理中…" else "AI 整理") {
|
||||
// ★ 先确认再调(复查报告 4.2.1):整理是**一次真的 LLM 调用**、
|
||||
// 会改掉现有记忆,而且用户可能刚标好了「必须保留」——
|
||||
// 让他有机会在动手前把那几条标上
|
||||
if (!loading) confirmSummarize = true
|
||||
}
|
||||
}
|
||||
// 导出的是**自己的私有记忆**(共享板子是另一份,别混着导)
|
||||
if (!readingShared && !worldMode) {
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
} else if (worldMode) {
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
// ---- 列表 ----
|
||||
val items = space?.memories ?: emptyList()
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
if (loading) "读取中…" else "还没有记忆。AI 觉得有值得记住的事时会自己记下来。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
for (m in items) {
|
||||
// ★ 共享空间里「别人写的」条目要标出来、并且**禁掉编辑和删除**
|
||||
// (复查报告 4.2.2)。不给禁用态的话,用户点了删除被后端拒绝,
|
||||
// 他会当成 bug —— 而后端拦得对(需求 3.6:只能改自己写的)。
|
||||
val author = m.authorAgent.trim()
|
||||
val mine = author.isEmpty() || author == agentId
|
||||
val authorName = if (author.isEmpty()) "" else (agentNames[author] ?: "另一个智能体")
|
||||
MemoryRow(
|
||||
item = m,
|
||||
// ★ v3.16:共享板子上条目按"是不是自己写的"判改删(不是整页只读)
|
||||
readOnly = false,
|
||||
// 别人写的 = 界面上不给改删的入口(不是"点了才报错")
|
||||
foreign = !mine,
|
||||
authorName = if (mine) "" else authorName,
|
||||
onEdit = { editing = m },
|
||||
onDelete = { onDelete(m.id) },
|
||||
onTogglePin = { onTogglePin(m.id, !m.pinned) },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(28.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口的调整(A 方案)----
|
||||
if (editWindow) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { editWindow = false },
|
||||
title = { Text("注入窗口", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"每轮最多把多少条记忆放进提示词。\n\n" +
|
||||
"置顶的永远带,不受这个数限制 —— 而且可以置顶任意多条" +
|
||||
"(标几条都行,它们一定都在)。\n" +
|
||||
"其余按时间取最近的。没带进去的不会丢," +
|
||||
"AI 用 memory_search 还能搜到。\n\n" +
|
||||
"填 0 = 不限(全量注入)。记忆攒到几百条时提示词会很贵," +
|
||||
"而且早期的会挤掉最近的对话上下文。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = windowDraft,
|
||||
onValueChange = { s -> windowDraft = s.filter { it.isDigit() }.take(5) },
|
||||
label = { Text("条数(0 = 不限)", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
editWindow = false
|
||||
onSetWindow(windowDraft.toIntOrNull() ?: 0)
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editWindow = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- AI 整理的确认(复查报告 4.2.1)----
|
||||
if (confirmSummarize) {
|
||||
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmSummarize = false },
|
||||
title = { Text("让 AI 整理一次记忆", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
buildString {
|
||||
append("这会把现在这 ${space?.memories?.size ?: 0} 条零散、重复的记忆")
|
||||
append("压缩成更少、更完整的几条。\n\n")
|
||||
append("· 标了「置顶」的(现在有 $pinnedCount 条)原样不动,不参与合并\n")
|
||||
append("· 它只做合并改写,不许编造新的事实\n")
|
||||
append("· 这是一次真实的模型调用,会花 Token(但不受额度限制)\n\n")
|
||||
append("想保住哪几条,先取消对话框去标上「置顶」。")
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { confirmSummarize = false; onSummarize() }) { Text("开始整理") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmSummarize = false }) { Text("先去标几条") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 导入模式选择放在调用方(它管文件选择器)----
|
||||
|
||||
// ---- 编辑 / 新增 ----
|
||||
val target = editing
|
||||
if (target != null || adding) {
|
||||
MemoryEditDialog(
|
||||
initial = target,
|
||||
onDismiss = { editing = null; adding = false },
|
||||
onSave = { title, content ->
|
||||
if (target == null) onAdd(title, content) else onUpdate(target.id, title, content)
|
||||
editing = null
|
||||
adding = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SmallAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryRow(
|
||||
item: MemoryItem,
|
||||
/** 在看旧空间 → 一切都只读(那里已经不属于当前对话了,改了会让人困惑) */
|
||||
readOnly: Boolean,
|
||||
/** 这条是**别人写的**(共享空间里)→ 不给改删入口,并且标出来源 */
|
||||
foreign: Boolean,
|
||||
authorName: String,
|
||||
onEdit: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onTogglePin: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.border(
|
||||
width = if (item.pinned) 1.dp else 0.dp,
|
||||
color = if (item.pinned) Color(0x66F29900) else Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (item.pinned) {
|
||||
Text(
|
||||
"置顶",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Color(0x22F29900))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
// ★ 来源标注(复查报告 4.2.2):共享空间里必须看得出这条是谁写的。
|
||||
// 不标的话用户点删除会被后端拒绝,他会当成 bug —— 而后端拦得对。
|
||||
if (foreign && authorName.isNotBlank()) {
|
||||
Text(
|
||||
"由 $authorName 写入",
|
||||
fontSize = 9.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
Text(
|
||||
item.title.ifBlank { "(无标题)" },
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (item.content.isNotBlank()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(item.content, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
if (readOnly) {
|
||||
Text(
|
||||
"绑定世界观之前的记忆,只供查看",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else if (foreign) {
|
||||
// 别人写的:不是"按钮点了才报错",而是**根本不给按钮**
|
||||
Text(
|
||||
"别人写的,AI 和你都改不了这一条(要删只能在这里删)",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
} else {
|
||||
// ★「必须保留」是**用户**的权利(需求 3.2):标上之后 AI 总结时
|
||||
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
||||
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
||||
// 但文案要写成"取消保留",不能只显示当前状态)
|
||||
RowAction(if (item.pinned) "取消置顶" else "置顶", onClick = onTogglePin)
|
||||
RowAction("编辑", onClick = onEdit)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryEditDialog(
|
||||
initial: MemoryItem?,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (String, String) -> Unit,
|
||||
) {
|
||||
var title by remember { mutableStateOf(initial?.title ?: "") }
|
||||
var content by remember { mutableStateOf(initial?.content ?: "") }
|
||||
// ★ 单条记忆的编辑用弹窗是合适的(内容量小、就是两个输入框);
|
||||
// 而"列表 / 多组配置"一律全屏 —— 见 AGENTS.md 那张表
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (initial == null) "加一条记忆" else "编辑记忆", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = title,
|
||||
onValueChange = { title = it },
|
||||
label = { Text("标题", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = content,
|
||||
onValueChange = { content = it },
|
||||
label = { Text("内容", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 90.dp, max = 220.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = { onSave(title.trim(), content.trim()) },
|
||||
enabled = title.isNotBlank() || content.isNotBlank(),
|
||||
) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.termux.TermuxMirror
|
||||
|
||||
/**
|
||||
* 换源界面(全屏,不是弹窗)。
|
||||
*
|
||||
* ★ 为什么做成界面:源列表有五个,每个还要显示说明和当前选中状态 ——
|
||||
* 弹窗装不下(见 AGENTS.md 的界面约定)。
|
||||
*
|
||||
* ★ 为什么需要这个功能:Termux 官方源在国内基本连不上,
|
||||
* `pkg install` 会卡住或超时,用户会以为"内置的 Termux 坏了"。
|
||||
* 换源这件事**每次重装都要做**,手敲 sed 又容易把 apt 配置写坏。
|
||||
*/
|
||||
@Composable
|
||||
fun MirrorScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
// 每次进界面重读一次:用户可能手改过 sources.list
|
||||
var current by remember { mutableStateOf(TermuxMirror.current(context)) }
|
||||
var toast by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "软件源",
|
||||
subtitle = "换完记得跑一次 pkg update",
|
||||
onBack = onBack,
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"Termux 官方源(packages.termux.dev)在国内基本连不上,表现是 " +
|
||||
"pkg install 卡在 Reading package lists 或者直接超时。" +
|
||||
"换一个国内镜像就好。",
|
||||
color = doubaoTextSecondary(),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
|
||||
if (toast.isNotBlank()) {
|
||||
Surface(
|
||||
color = Color(0xFF16301F),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
) {
|
||||
Text(
|
||||
toast,
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("选一个源")
|
||||
|
||||
TermuxMirror.MIRRORS.forEach { m ->
|
||||
val selected = current?.id == m.id
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (selected) Doubao.Blue.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.clickable {
|
||||
val n = try {
|
||||
TermuxMirror.set(context, m)
|
||||
} catch (t: Throwable) {
|
||||
toast = "换源失败:${t.message}"
|
||||
return@clickable
|
||||
}
|
||||
current = m
|
||||
toast = "已切到 ${m.name}(写入 $n 条),去终端跑一次 pkg update"
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
m.name,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
|
||||
color = if (selected) Doubao.Blue else Color(0xFF1F2328),
|
||||
)
|
||||
Text(
|
||||
m.note,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Text(
|
||||
m.host,
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary().copy(alpha = 0.7f),
|
||||
)
|
||||
}
|
||||
if (selected) {
|
||||
Text("✓ 当前", fontSize = 11.sp, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("换完之后")
|
||||
Text(
|
||||
"去终端敲:\n" +
|
||||
" pkg update\n" +
|
||||
"\n" +
|
||||
"update 会重新拉索引,第一次可能要等十几秒。" +
|
||||
"如果报错,换另一个源再试 —— 镜像偶尔会同步中断。",
|
||||
color = doubaoTextSecondary(),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 19.sp,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
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.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.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Group
|
||||
import androidx.compose.material.icons.filled.Memory
|
||||
import androidx.compose.material.icons.filled.Layers
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
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.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* ★★ 「更多功能」—— 抽屉里放不下的那些入口收在这儿。
|
||||
*
|
||||
* ## 为什么要这么改(用户反馈:"太挤了对话都没了")
|
||||
*
|
||||
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
|
||||
*
|
||||
* ★★ 后来又收了一次(用户第二次说"太挤了"、"把别的放更多里"):
|
||||
* 抽屉第一层现在只剩**四件天天用的**:新话题 / 智能体 / 记忆 / 更多功能。
|
||||
* 笔记、模型、新建群聊都挪进来了 ——
|
||||
* 「模型」虽然也常用,但它是个**配置**,配好基本不动;
|
||||
* 抽屉里腾出来的位置留给对话列表更值。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
* `← 返回 | 标题`,和别的全屏界面一套顶栏。
|
||||
* 不用折叠面板:折叠起来每次都要展开一次,反而更麻烦。
|
||||
*/
|
||||
@Composable
|
||||
fun MoreSheetScreen(
|
||||
onOpenAiScreens: () -> Unit,
|
||||
onOpenSkills: () -> Unit,
|
||||
onOpenResources: () -> Unit,
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenNotes: () -> Unit,
|
||||
onOpenModels: () -> Unit,
|
||||
/** v3.0 P2:容器(一局 = 世界包 + 成员) */
|
||||
onOpenContainers: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("更多功能", onBack = onClose)
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.EditNote,
|
||||
title = "笔记",
|
||||
subtitle = "AI 替你记下来的东西",
|
||||
) { onOpenNotes() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Memory,
|
||||
title = "模型",
|
||||
subtitle = "换模型 / 思考强度(配好基本不用动)",
|
||||
) { onOpenModels() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Dashboard,
|
||||
title = "AI 界面",
|
||||
subtitle = "AI 弹过的界面都存着,点一下就能再打开",
|
||||
) { onOpenAiScreens() }
|
||||
}
|
||||
item {
|
||||
// ★ v3.0 P2:容器(一局 = 世界包 + 成员)。
|
||||
// 用户核心诉求:"不同容器同一批智能体可以在不同的世界互不干扰"——
|
||||
// 所以"开一局"必须是个能点到的入口。
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
title = "容器",
|
||||
subtitle = "一局 = 世界包 + 成员;数值 / 状态 / 记忆按局隔离",
|
||||
) { onOpenContainers() }
|
||||
}
|
||||
item {
|
||||
// 世界包 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)——
|
||||
// 它们是"全局资源"那一层:都被智能体引用,都是列表 + 增删改 + 导入导出
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Public,
|
||||
title = "世界包 · 技能 · 模型",
|
||||
subtitle = "世界包(设定 / 数值 / 物品 / 地图)、AI 的工具手册、可选模型列表",
|
||||
) { onOpenResources() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
title = "技能 · 连接器",
|
||||
subtitle = "Python 工具、MCP 服务、界面能力开关",
|
||||
) { onOpenSkills() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.AccountTree,
|
||||
title = "会议模式",
|
||||
subtitle = "多个智能体一起讨论,可以搭流程图",
|
||||
) { onOpenMeetings() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Terminal,
|
||||
title = "终端",
|
||||
subtitle = "内置 Termux,真 Linux 环境",
|
||||
) { onOpenTerminal() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Settings,
|
||||
title = "设置",
|
||||
subtitle = "模型、语音、外观、数据",
|
||||
) { onOpenSettings() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoreRow(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(subtitle, fontSize = 12.sp, lineHeight = 17.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.doubao.nodekit.NodeCatalog
|
||||
import com.doubao.nodekit.NodeShape
|
||||
import com.doubao.nodekit.NodeShapes
|
||||
|
||||
/*
|
||||
* 节点形状的小图标。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 节点的"形状"在库里是一个字段([NodeShape]),但字段本身用户看不见 ——
|
||||
* 得有人把它画出来。这里就是那个"画"的地方,两处用它:
|
||||
*
|
||||
* · 「加节点」面板里每个类型前面的缩略图 —— **选之前**就看出这是起点、
|
||||
* 判断、循环还是纯数据节点
|
||||
* · 节点卡片标题栏左边的小白形状 —— 图大了以后靠它认节点
|
||||
*
|
||||
* ## 为什么不直接在库里写 @Composable
|
||||
*
|
||||
* 库刻意不依赖 Compose **运行时**(只依赖 `Path` 那几个值类型),
|
||||
* 这样它才能被单元测试直接跑、也不用拖着 compose runtime 走。
|
||||
* 画的那一步(`Canvas` / `drawPath`)留在 App 这边。
|
||||
*
|
||||
* 形状的**路径**仍然只有一份 —— 库里的 `NodeShapes.path()`。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 按节点类型画形状徽标(自动取该类型的颜色)。
|
||||
*
|
||||
* 用在「加节点」面板那种"还没创建、只知道类型"的地方。
|
||||
*/
|
||||
@Composable
|
||||
fun NodeShapeBadge(
|
||||
type: String,
|
||||
size: Dp = 22.dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
NodeShapeBadge(
|
||||
shape = NodeCatalog.shape(type),
|
||||
color = Color(NodeCatalog.color(type)),
|
||||
size = size,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按形状 + 颜色画徽标。
|
||||
*
|
||||
* [filled] = true 时填色(面板里用,颜色淡一点做底 + 描边),
|
||||
* false 时只描边(标题栏里用白色描边太重,所以那边直接填白)。
|
||||
*/
|
||||
@Composable
|
||||
fun NodeShapeBadge(
|
||||
shape: NodeShape,
|
||||
color: Color,
|
||||
size: Dp = 22.dp,
|
||||
strokeWidth: Dp = 1.6.dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Canvas(modifier.size(size)) {
|
||||
val p = NodeShapes.thumbPath(shape, this.size.width)
|
||||
// 淡底 + 实描边:小尺寸下只有描边会看不清,只有实心又显得太重
|
||||
drawPath(p, color = color.copy(alpha = 0.16f))
|
||||
drawPath(p, color = color, style = Stroke(width = strokeWidth.toPx()))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -152,7 +152,7 @@ fun ProfileScreen(vm: AppViewModel) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
SettingsCard("关于") {
|
||||
FormHint("豆包客户端复刻版:原生 Compose 界面 + 跑在同一进程里的本地 Python 内核,请求不经过任何中转服务器。")
|
||||
FormHint("小人间:一个小世界,里面住着 AI 角色。原生 Compose 界面 + 跑在同一进程里的本地 Python 内核,请求不经过任何中转服务器。")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(onClick = { vm.refresh() }) { Text("重新连接内核", fontSize = 13.sp) }
|
||||
@@ -0,0 +1,295 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
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.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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.doubao.lynxclone.data.ResidentFunction
|
||||
import com.doubao.lynxclone.data.ResidentItem
|
||||
import com.doubao.lynxclone.data.ResidentPage
|
||||
|
||||
/*
|
||||
* 常驻角色界面(v3.30)。
|
||||
*
|
||||
* 用户需求原文:
|
||||
* 「在界面入口:>XXX。功能选择弹出弹窗。进入功能后弹个html来交互
|
||||
* (调用的api和ai调的一样)」
|
||||
*
|
||||
* 所以这里有两层:
|
||||
* 1. 输入框输入 `>` → 角色菜单 → 选角色 → 功能菜单(两个都是小弹层,
|
||||
* 符合 AGENTS.md「纯菜单可以用弹层」);
|
||||
* 2. 选完功能 → **全屏 WebView** 打开内核生成的 HTML 页,页面里的表单
|
||||
* 直接调 `POST /api/containers/<cid>/residents/<iid>/call` —— 和 AI
|
||||
* 工具是同一个内核函数,所以结果一定一致。
|
||||
*/
|
||||
|
||||
/** 常驻角色菜单(输入框输入 `>` 后弹出;只列**当前地点**能办事的) */
|
||||
@Composable
|
||||
fun ResidentMenuDialog(
|
||||
loading: Boolean,
|
||||
residents: List<ResidentItem>,
|
||||
hint: String = "",
|
||||
onPick: (ResidentItem) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onDismiss() }
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
SheetScaffold(title = "找谁办事", subtitle = "这里能办事的常驻角色(别的地点要先移动过去)", onDismiss = onDismiss) {
|
||||
if (loading) {
|
||||
Text("正在找…", fontSize = 14.sp, color = doubaoTextSecondary(), modifier = Modifier.padding(20.dp))
|
||||
return@SheetScaffold
|
||||
}
|
||||
if (residents.isEmpty()) {
|
||||
Text(
|
||||
hint.ifBlank { "这里没有能用界面办事的常驻角色。" },
|
||||
fontSize = 14.sp, lineHeight = 22.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(20.dp),
|
||||
)
|
||||
return@SheetScaffold
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
residents.forEach { item ->
|
||||
ResidentRow(item = item, onClick = { onPick(item) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 功能菜单(选完常驻角色后弹出) */
|
||||
@Composable
|
||||
fun ResidentFunctionsDialog(
|
||||
resident: ResidentItem,
|
||||
onPick: (ResidentFunction) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onDismiss() }
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
SheetScaffold(
|
||||
title = resident.name,
|
||||
subtitle = listOfNotNull(
|
||||
resident.className.ifBlank { null },
|
||||
resident.placeName.ifBlank { null }?.let { "在$it" } ?: "随处可找",
|
||||
).joinToString(" · "),
|
||||
onDismiss = onDismiss,
|
||||
) {
|
||||
if (resident.desc.isNotBlank()) {
|
||||
Text(
|
||||
resident.desc, fontSize = 13.sp, lineHeight = 20.sp,
|
||||
color = doubaoTextSecondary(), modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
resident.functions.forEach { fn ->
|
||||
FunctionRow(fn = fn, onClick = { onPick(fn) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SheetScaffold(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onDismiss: () -> Unit,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.38f)).clickable(onClick = onDismiss)) {
|
||||
Column(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 560.dp)
|
||||
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable(enabled = false) {}
|
||||
.padding(top = 14.dp, bottom = 18.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
|
||||
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
if (subtitle.isNotBlank()) {
|
||||
Text(subtitle, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"关闭", fontSize = 13.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { onDismiss() }
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResidentRow(item: ResidentItem, onClick: () -> Unit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(item.name.take(1), color = Doubao.Blue, fontSize = 16.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.name, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
if (item.ai) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"AI", fontSize = 10.sp, color = Doubao.Blue,
|
||||
modifier = Modifier.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f)).padding(horizontal = 5.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
listOfNotNull(
|
||||
item.className.ifBlank { null },
|
||||
item.placeName.ifBlank { null }?.let { "在$it" } ?: "随处可找",
|
||||
"${item.functions.size} 个功能",
|
||||
).joinToString(" · "),
|
||||
fontSize = 12.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
Text("›", fontSize = 20.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FunctionRow(fn: ResidentFunction, onClick: () -> Unit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
fn.kindLabel,
|
||||
fontSize = 10.sp,
|
||||
color = if (fn.kind == "query") Color(0xFF3B82F6) else Color(0xFFE0821B),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(
|
||||
if (fn.kind == "query") Color(0x1A3B82F6) else Color(0x1AE0821B),
|
||||
)
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fn.name, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
if (fn.desc.isNotBlank()) {
|
||||
Text(fn.desc, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Text("›", fontSize = 20.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 功能页(全屏 WebView) ------------------------------ */
|
||||
|
||||
/**
|
||||
* 全屏打开常驻角色功能页。
|
||||
*
|
||||
* ★ 页面由**内核生成**(`/api/containers/.../page`),是 http://127.0.0.1:5199
|
||||
* 的同源页面 —— 所以页面里的 `fetch('/api/.../call')` 能直接调内核,
|
||||
* 不需要 JS 桥传业务数据。这里只注入一个 `Doubao.close()` 让页面的
|
||||
* 「返回」按钮能关掉全屏。
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
fun ResidentPageScreen(page: ResidentPage, pageUrl: String, onClose: () -> Unit) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
FullScreen(
|
||||
title = page.functionName.ifBlank { "常驻角色" },
|
||||
subtitle = page.residentName,
|
||||
onBack = onClose,
|
||||
) {
|
||||
val bridge = remember(page.instanceId, page.functionId) { ResidentCloseBridge(onClose) }
|
||||
DisposableEffect(bridge) {
|
||||
onDispose { bridge.onClose = null }
|
||||
}
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
settings.cacheMode = WebSettings.LOAD_NO_CACHE
|
||||
// ★ 和地图页同一个原因:默认 useWideViewPort=false 时这个 WebView
|
||||
// 里 `vh` 会算成 0(功能页的结果框 max-height 曾因此变 0)。
|
||||
// 页面自带 `<meta viewport width=device-width>`,开它不会缩放错;
|
||||
// 但**不要**开 overviewMode(那会整体缩放页面)。
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = false
|
||||
addJavascriptInterface(bridge, "Doubao")
|
||||
webViewClient = WebViewClient()
|
||||
loadUrl(pageUrl)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 只给功能页用的极小桥:关掉全屏(业务数据走同源 fetch,不经过桥)。 */
|
||||
private class ResidentCloseBridge(@Volatile var onClose: (() -> Unit)?) {
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,768 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.ModelEntry
|
||||
import com.doubao.lynxclone.data.SkillItem
|
||||
import com.doubao.lynxclone.data.WorldviewItem
|
||||
|
||||
/*
|
||||
* 世界观 / Skill / 模型列表的管理界面(需求 3.3 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## 为什么三种东西挤在一个界面里
|
||||
*
|
||||
* 它们是**同一层的东西**:都是"全局资源",都被智能体引用,都是"列表 + 增删改 +
|
||||
* 导入导出"。分开成三个入口的话,用户要记住"世界观在哪、技能在哪、模型在哪"——
|
||||
* 而它们其实是一件事("这个 App 里有哪些可复用的东西")。
|
||||
*
|
||||
* ## 表单是**字段驱动**的,不是写三份
|
||||
*
|
||||
* 三种资源的表单字段完全不同(世界观有设定文本 + 四件套;Skill 就两行;
|
||||
* 模型有地址/标识/Key/单价),但**长得一模一样** —— 都是一个 label + 一个输入框。
|
||||
* 所以用 `List<Field>` 描述,渲染只有一份。
|
||||
*
|
||||
* 写三份的话,加一个字段就要改三处,而这个仓库里"加了 list 类型但某张表没跟上"
|
||||
* 已经反复出现过(AGENTS.md 第一条就是它)。
|
||||
*/
|
||||
|
||||
/** 表单里的一个字段 */
|
||||
private data class Field(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val placeholder: String = "",
|
||||
val multiline: Boolean = false,
|
||||
val password: Boolean = false,
|
||||
val number: Boolean = false,
|
||||
/** 开关:值的约定是 `"1"` = 开、`""` = 关(不弹键盘,点一下切换) */
|
||||
val toggle: Boolean = false,
|
||||
)
|
||||
|
||||
private val WORLD_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:九霄"),
|
||||
Field(
|
||||
"setting", "世界观设定",
|
||||
"这个世界的规则、背景、称呼……(绑定了它的智能体,提示词里会整段带上)",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val SKILL_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:写代码的规矩"),
|
||||
Field(
|
||||
"content", "内容",
|
||||
"告诉 AI 有哪些工具、什么时候用、用完之后不许干什么",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val MODEL_FIELDS = listOf(
|
||||
Field("name", "显示名", "比如:豆包 Pro"),
|
||||
Field("apiBase", "API 地址", "https://ark.cn-beijing.volces.com/api/v3"),
|
||||
Field("model", "模型标识", "doubao-seed-2-1-pro-260628"),
|
||||
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
|
||||
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
|
||||
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
|
||||
// ★ v1.2:命中缓存的单价单独填。各家命中都比未命中便宜得多(常见 1/10),
|
||||
// 不填的话费用按未命中的价格算 —— **越用越高估**,而用户会以为
|
||||
// 自己真花了那些钱。留空 = 按未命中单价算(保守估计,不会低估)。
|
||||
Field("cachePricePerK", "命中单价(元/千 Token)", "留空 = 按上面的单价算(偏保守)", number = true),
|
||||
Field(
|
||||
"noTools", "不支持工具调用",
|
||||
"这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," +
|
||||
"改成让它在正文里写调用,内核执行完再剥掉 —— 记忆和情绪照常能用。",
|
||||
toggle = true,
|
||||
),
|
||||
)
|
||||
|
||||
/** 三张表:kind → (标题、字段、说明、是不是包) */
|
||||
private class Kind(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val tabLabel: String,
|
||||
val fields: List<Field>,
|
||||
val hint: String,
|
||||
/** 导入导出是 zip 包(世界观)还是单个 JSON(Skill) */
|
||||
val isZip: Boolean,
|
||||
)
|
||||
|
||||
private val KINDS = listOf(
|
||||
Kind(
|
||||
// ★ v3.0:世界观 = 世界包(设定 + 数值/状态/物品/地图定义 + 脚本)。
|
||||
// v2 里「世界观」和「规则包」是两个资源、两页编辑 —— 现在合成一个,
|
||||
// 点开就是 [世界包编辑] 的四个分区。
|
||||
"worldviews", "世界包", "世界包", WORLD_FIELDS, isZip = true,
|
||||
hint = "一个世界包 = 设定 + 数值/状态/物品/地图的定义 + 脚本,导出的 zip 连脚本一起带走。" +
|
||||
"绑定同一个世界包的智能体**共用一份记忆**。",
|
||||
),
|
||||
Kind(
|
||||
"skills", "Skill", "Skill", SKILL_FIELDS, isZip = false,
|
||||
hint = "纯文本的「工具使用手册」。内置的记忆/情绪/用量手册**默认就生效**;这里写的是你自己加的规矩。",
|
||||
),
|
||||
Kind(
|
||||
"models", "模型", "模型", MODEL_FIELDS, isZip = false,
|
||||
hint = "全局模型列表。智能体按 id 引用这里的某一项 —— 所以换 Key 只改一处," +
|
||||
"而且**导出智能体包时不会把 Key 带出去**。",
|
||||
),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
var tab by remember { mutableStateOf(0) }
|
||||
// 正在编辑的那一项(null 且 editing 为 true = 新建)
|
||||
var editing by remember { mutableStateOf<Boolean>(false) }
|
||||
var editId by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val kind = KINDS[tab]
|
||||
val items: List<Pair<String, Triple<String, String, AgentImage>>> = when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.map {
|
||||
// ★ v3:副标题列出这个世界包含多少定义 —— 那才是用户判断
|
||||
// 这个包"能不能用"的信息,光看名字看不出来
|
||||
val bits = mutableListOf("${it.stats.size} 数值", "${it.statuses.size} 状态")
|
||||
if (it.hasScripts) bits += "${it.scriptCount} 脚本"
|
||||
it.id to Triple(it.name, bits.joinToString(" · "), it.image)
|
||||
}
|
||||
"skills" -> vm.state.skills.map { it.id to Triple(it.name, it.content, AgentImage()) }
|
||||
else -> vm.state.modelEntries.map {
|
||||
// ★ 兼容模式在列表上就要看得出来(复查 3.3):进了编辑页才知道
|
||||
// 这个模型不传 tools,等于用户永远想不起自己开过它
|
||||
it.id to Triple(
|
||||
if (it.noTools) "${it.name}(兼容模式)" else it.name,
|
||||
listOf(it.model, it.apiBase).filter { s -> s.isNotBlank() }.joinToString(" · "),
|
||||
AgentImage(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导入导出(SAF)----------------
|
||||
* zip 走 base64(二进制没法塞进 JSON 文本),Skill 是纯 JSON 文本。
|
||||
*/
|
||||
val ctx = LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<Triple<String, String, String>?>(null) }
|
||||
// ★ v3.30:内置示例世界包选择框(现在有两个:全能测试世界 / 旧都市)
|
||||
var sampleOpen by remember { mutableStateOf(false) }
|
||||
val saveDoc = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
|
||||
val data = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
val bytes = if (data.second == "zip") Base64.decode(data.first, Base64.DEFAULT)
|
||||
else data.first.toByteArray(Charsets.UTF_8)
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
// ---- 带脚本包的警告 ----
|
||||
//
|
||||
// ★ 这里是全仓库**唯一**该用弹窗的导入场景:内容就是一段警告 + 两个按钮,
|
||||
// 属于"一次确认"(AGENTS.md 的界面约定:一次确认用弹窗,列表/多组配置
|
||||
// 才开全屏)。真正拦得住的是**服务端**那道 `confirmScripts` 关口,
|
||||
// 这个框只是把风险如实告诉用户。
|
||||
if (vm.pendingScriptPack.isNotBlank()) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.dismissScriptImport() },
|
||||
title = { Text("这个包里带了 Python 脚本") },
|
||||
text = {
|
||||
Text(
|
||||
vm.scriptImportWarning.ifBlank {
|
||||
"包里有可执行脚本。导入后它会在你的设备上运行 —— " +
|
||||
"只导入你信得过的来源。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { vm.importWorldPackage(vm.pendingScriptPack, confirmed = true) }) {
|
||||
Text("我知道风险,继续", color = Doubao.Blue)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { vm.dismissScriptImport() }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ★ v3.30:内置示例世界包选择(纯菜单 → 弹窗合适)
|
||||
if (sampleOpen) {
|
||||
fun importSample(asset: String, label: String) {
|
||||
sampleOpen = false
|
||||
runCatching {
|
||||
val bytes = ctx.assets.open(asset).use { it.readBytes() }
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
vm.importWorldPackage(b64)
|
||||
vm.showHint("正在导入「$label」…")
|
||||
}.onFailure { vm.showHint("读不出内置示例包:${it.message}") }
|
||||
}
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { sampleOpen = false },
|
||||
title = { Text("内置示例世界包") },
|
||||
text = {
|
||||
androidx.compose.foundation.layout.Column {
|
||||
Text(
|
||||
"两个包都能直接点「导入」试玩;带脚本,导入时会再确认一次。",
|
||||
fontSize = 13.sp, lineHeight = 19.sp,
|
||||
)
|
||||
TextButton(
|
||||
onClick = { importSample("worlds/all-test.zip", "全能测试世界") },
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("全能测试世界(系统功能样板)", color = Doubao.Blue, fontSize = 14.sp)
|
||||
Text(
|
||||
"数值/状态/物品四类、决斗、驻守角色 —— 逐项试系统功能",
|
||||
fontSize = 11.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = { importSample("worlds/old-city.zip", "旧都市") },
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("旧都市(常驻角色样板)", color = Doubao.Blue, fontSize = 14.sp)
|
||||
Text(
|
||||
"家/学校/商店/小卖铺/森林;三家店与门卫都能在输入框打 > 办事",
|
||||
fontSize = 11.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { sampleOpen = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val openDoc = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
if (kind.isZip) {
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
// ★ 世界包是**唯一允许夹带可执行 Python 的包类型**:
|
||||
// 内核要求带 `confirmScripts` 才落库,第一次返回
|
||||
// needConfirm + 警告,界面弹框、用户确认后再传一次
|
||||
// (这个往返收在 `importWorldPackage` 里)。
|
||||
vm.importWorldPackage(b64)
|
||||
} else {
|
||||
vm.importPackage(kind.id, "", bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
// ★ v3.12:内置示例世界包 —— 一键导入,不用先找文件/传文件。
|
||||
// ★ v3.30:从两个示例里选(全能测试世界 / 旧都市)。
|
||||
if (kind.isZip) {
|
||||
TopTextAction("示例包") { sampleOpen = true }
|
||||
}
|
||||
TopTextAction("导入") {
|
||||
if (kind.isZip) openDoc.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
else openDoc.launch(arrayOf("application/json", "text/plain", "*/*"))
|
||||
}
|
||||
},
|
||||
) {
|
||||
// ---- Tab ----
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
for ((i, k) in KINDS.withIndex()) {
|
||||
val on = i == tab
|
||||
Text(
|
||||
k.tabLabel,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { tab = i }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") {
|
||||
// ★ 世界包不是"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。所以「新建」直接
|
||||
// 建一个**带模板**的包并进去,而不是先弹"名称+设定"的表单、
|
||||
// 再让用户自己去找编辑器。
|
||||
if (kind.id == "worldviews") { vm.createWorldPackFromTemplate(); return@RowAction }
|
||||
editId = null; editing = true
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.07f))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(kind.hint.replace("**", ""), fontSize = 11.sp, lineHeight = 16.sp, color = Doubao.Blue)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
"还没有。点右上角「新建」,或者用「导入」拿一个现成的包。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 20.dp),
|
||||
)
|
||||
}
|
||||
|
||||
for ((id, info) in items) {
|
||||
val (name, preview, image) = info
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable {
|
||||
// ★ 世界包走**独立的全屏编辑页**(设定/数值/状态/脚本
|
||||
// 四个分区)—— 它的内容不是"label + 输入框"那套
|
||||
// 表单能表达的;Skill / 模型还是下面那套字段表单。
|
||||
if (kind.id == "worldviews") { vm.openWorldPackEdit(id); return@clickable }
|
||||
editId = id; editing = true
|
||||
}
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (kind.id == "worldviews") {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = image.slot("平常"),
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name.ifBlank { "未命名" }, fontSize = 14.sp, color = doubaoText())
|
||||
if (preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
preview.replace("\n", " ").take(70),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
// ★ 谁绑了它(用户要求)—— 反过来也得看得见:
|
||||
// 绑之前你要知道"这个世界观已经有谁在用了",
|
||||
// 空的则说明没人用它、共享记忆也没人在读写。
|
||||
if (kind.id == "worldviews") {
|
||||
val users = vm.state.worldviews.firstOrNull { it.id == id }?.agents ?: emptyList()
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
if (users.isEmpty()) "还没有智能体用它"
|
||||
else "${users.size} 个智能体在用:${users.joinToString("、") { it.name }}",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = if (users.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
RowAction("记忆") {
|
||||
// ★ 世界观的**共享记忆**("大家共同记得什么")——
|
||||
// 和从智能体进去看的是同一个空间、不同的视角
|
||||
vm.openWorldMemories(id)
|
||||
}
|
||||
RowAction("导出") {
|
||||
vm.exportPackage(kind.id, id) { content, ext ->
|
||||
pendingExport = Triple(content, ext, "x")
|
||||
saveDoc.launch("${name.ifBlank { "resource" }}.${if (kind.isZip) "zip" else "json"}")
|
||||
}
|
||||
}
|
||||
RowAction("删除", danger = true) { vm.deleteResource(kind.id, id) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// 世界包走独立的全屏编辑页(由 vm.editingWorldPack 驱动),
|
||||
// 不经过下面这套字段表单
|
||||
if (editing && kind.id != "worldviews") {
|
||||
ResourceEditScreen(
|
||||
vm = vm,
|
||||
kind = kind,
|
||||
id = editId,
|
||||
onDone = { editing = false; editId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 字段驱动的编辑表单 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun ResourceEditScreen(
|
||||
vm: AppViewModel,
|
||||
kind: Kind,
|
||||
id: String?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
// 三种资源的初始值从内存里那份拿(列表就是它渲染的,不会对不上)
|
||||
val initial: Map<String, String> = remember(id, kind.id) {
|
||||
when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
mapOf(
|
||||
"name" to it.name,
|
||||
"setting" to it.setting,
|
||||
// ★ 世界观挂的数值状态包 —— 不读出来的话,一进编辑页
|
||||
// 选择器就显示"没挂",用户一保存就把原来的关联抹了
|
||||
"rulePackId" to it.rulePackId,
|
||||
)
|
||||
} ?: emptyMap()
|
||||
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "content" to it.content)
|
||||
} ?: emptyMap()
|
||||
else -> vm.state.modelEntries.firstOrNull { it.id == id }?.let {
|
||||
mapOf(
|
||||
"name" to it.name, "apiBase" to it.apiBase, "model" to it.model,
|
||||
"apiKey" to "", "provider" to it.provider,
|
||||
"pricePerK" to if (it.pricePerK > 0) it.pricePerK.toString() else "",
|
||||
"noTools" to if (it.noTools) "1" else "",
|
||||
)
|
||||
} ?: emptyMap()
|
||||
}
|
||||
}
|
||||
var values by remember(id, kind.id) { mutableStateOf(initial) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var worldImage by remember(id, kind.id) {
|
||||
mutableStateOf(vm.state.worldviews.firstOrNull { it.id == id }?.image ?: AgentImage())
|
||||
}
|
||||
val ctx = LocalContext.current
|
||||
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
|
||||
// 和智能体编辑页**同一份实现** —— 这条链路的坑(大图、GIF、SAF 没扩展名)
|
||||
// 两边一模一样,抄两份迟早只修一份
|
||||
vm.uploadWorldviewAssetFrom(ctx.applicationContext, id, slot, uri)
|
||||
}
|
||||
// 上传完 image 会变,跟着刷新预览
|
||||
vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
if (it.image != worldImage) worldImage = it.image
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (id == null) "新建${kind.title}" else "编辑${kind.title}",
|
||||
subtitle = values["name"].orEmpty().ifBlank { kind.title },
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
val name = values["name"].orEmpty().trim()
|
||||
val text = values[
|
||||
if (kind.id == "models") "apiBase" else if (kind.id == "skills") "content" else "setting"
|
||||
].orEmpty()
|
||||
val extra = mutableMapOf<String, Any?>()
|
||||
if (kind.id == "models") {
|
||||
extra["model"] = values["model"].orEmpty()
|
||||
extra["apiKey"] = values["apiKey"].orEmpty()
|
||||
extra["provider"] = values["provider"].orEmpty()
|
||||
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
|
||||
extra["noTools"] = values["noTools"] == "1"
|
||||
}
|
||||
if (kind.id == "worldviews") {
|
||||
extra["image"] = worldImage
|
||||
// ★ 世界观挂的数值状态包(空 = 不挂)
|
||||
extra["rulePackId"] = values["rulePackId"].orEmpty()
|
||||
}
|
||||
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
SectionLabel("基本信息")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
for (f in kind.fields) {
|
||||
// ---- 开关型字段:点一下切换,不弹键盘 ----
|
||||
if (f.toggle) {
|
||||
val on = values[f.key] == "1"
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
if (f.placeholder.isNotBlank()) {
|
||||
Text(
|
||||
f.placeholder,
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (on) Doubao.Blue else Doubao.Border)
|
||||
.clickable { values = values + (f.key to if (on) "" else "1") },
|
||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
continue
|
||||
}
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = values[f.key].orEmpty(),
|
||||
onValueChange = { v ->
|
||||
// 单价只收数字和小数点;别的字段原样收
|
||||
values = values + (f.key to if (f.number) v.filter { c -> c.isDigit() || c == '.' } else v)
|
||||
},
|
||||
placeholder = { Text(f.placeholder, fontSize = 12.sp) },
|
||||
singleLine = !f.multiline,
|
||||
visualTransformation = if (f.password) PasswordVisualTransformation()
|
||||
else androidx.compose.ui.text.input.VisualTransformation.None,
|
||||
keyboardOptions = if (f.number) KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
else KeyboardOptions.Default,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.then(if (f.multiline) Modifier.heightIn(min = 120.dp, max = 300.dp) else Modifier),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 数值状态包:**世界观是它的挂载点**(需求 §3.6)。
|
||||
//
|
||||
// 以前这里**没有这个入口** —— 内核那条链路是通的
|
||||
// (`agent_context.pack_of` 读 `世界观.rulePackId`),
|
||||
// 但界面上根本挂不上,于是整个数值/状态系统在 App 里是死的:
|
||||
// 用户在「资源 → 规则包」里辛苦写完,回来发现没有任何地方能启用它。
|
||||
//
|
||||
// 只在世界观这一种资源上出现(规则包/Skill/模型没有这个概念)。
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("数值状态包")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
Text(
|
||||
"挂上之后,绑这个世界观的智能体就有**数值**(好感度、声望……)" +
|
||||
"和**状态**(中毒、庇佑……)。不挂就没有 —— 提示词里那两段是空的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val pickedPack = values["rulePackId"].orEmpty()
|
||||
val packs = vm.state.rulePacks
|
||||
if (packs.isEmpty()) {
|
||||
Text(
|
||||
"还没有数值状态包。去「资源 → 规则包」新建一个(有模板)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// 一行一个:手机上横向排不下(包名可能很长),
|
||||
// 而且"选中哪个"要一眼看得出来
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { values = values + ("rulePackId" to "") }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (pickedPack.isBlank()) "◉" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (pickedPack.isBlank()) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text("不挂(没有数值和状态)", fontSize = 13.sp, color = doubaoText())
|
||||
}
|
||||
for (p in packs) {
|
||||
val on = p.id == pickedPack
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
values = values + ("rulePackId" to p.id)
|
||||
}.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (on) "◉" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(p.name.ifBlank { "(未命名)" }, fontSize = 13.sp, color = doubaoText())
|
||||
val bits = mutableListOf<String>()
|
||||
bits.add("${p.stats.size} 条数值")
|
||||
bits.add("${p.statuses.size} 条状态")
|
||||
if (p.hasScripts) bits.add("带脚本")
|
||||
Text(bits.joinToString(" · "), fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("外观(四件套)")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
if (id == null) {
|
||||
Text(
|
||||
"先保存,再回来加外观图片(图片要落到这个世界观自己的目录里)。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
val slots = listOf(
|
||||
Triple("front", "封面 / 代表图", "智能体选择界面上用的那张"),
|
||||
Triple("back", "背景图", "铺在展示区最底层"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本"),
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> worldImage.slot("平常")
|
||||
"back" -> worldImage.back
|
||||
"border-main" -> worldImage.borderMain
|
||||
else -> worldImage.borderInfo
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
RowAction("选择") {
|
||||
pendingSlot = key
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
}
|
||||
if (path.isNotBlank()) {
|
||||
RowAction("清除", danger = true) {
|
||||
vm.uploadWorldviewAsset(id, key, "", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
if (id != null && kind.id == "skills") {
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TextButton(onClick = { vm.deleteResource(kind.id, id); onDone() }) {
|
||||
Text("删除这个 Skill", color = Color(0xFFD93025), fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -328,6 +328,17 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
checked = draft.speech.autoRead,
|
||||
onChange = { draft = draft.copy(speech = draft.speech.copy(autoRead = it)) },
|
||||
)
|
||||
FormSwitch(
|
||||
title = "朗读情绪指令(括号变语音指令)",
|
||||
sub = "回复里(括号)/【方括号】写的旁白变成豆包语音的情绪指令,不念出来;" +
|
||||
"界面里显示成灰色小字",
|
||||
checked = draft.speech.emotionTags,
|
||||
onChange = { draft = draft.copy(speech = draft.speech.copy(emotionTags = it)) },
|
||||
)
|
||||
FormHint(
|
||||
"只有「豆包语音 V3」(2.0 音色)支持语音指令;其他引擎开启后只会把括号旁白" +
|
||||
"从朗读里去掉。豆包控制台里这个写法叫「语音指令 / [#指令]」,不额外计费。",
|
||||
)
|
||||
|
||||
FormLabel("语音输入(STT)")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
@@ -495,7 +506,76 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
FormHint("当前发现 Python 工具 ${vm.state.tools.size} 个 · MCP 工具 ${vm.state.mcp.sumOf { it.toolCount }} 个(在「技能·连接器」里看明细)")
|
||||
}
|
||||
|
||||
/* ---------------- 超时 ---------------- */
|
||||
// ★ 这一页**不在这个「保存设置」里** —— 超时有自己的接口
|
||||
// (/api/timeouts)和自己的全屏界面,改一项立刻生效。
|
||||
// 混进"本地草稿 + 一次性保存"反而会让用户以为要按保存。
|
||||
SettingsCard("超时") {
|
||||
NavRow(
|
||||
label = "超时设置",
|
||||
value = if (vm.timeouts.items.isEmpty()) "" else "${vm.timeouts.items.size} 项",
|
||||
onClick = { vm.openTimeouts() },
|
||||
)
|
||||
FormHint(
|
||||
"模型回复、工具执行、命令、MCP、语音、等用户回答……所有超时都能在这里调。" +
|
||||
"「等用户回答」默认是不限时。",
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 个人资料 ---------------- */
|
||||
// 外观(v1.2 §6.1)
|
||||
SettingsCard("外观") {
|
||||
FormSwitch(
|
||||
title = "背景跟随说话者",
|
||||
sub = "多人会话时,展示区的立绘和背景跟着当前发言的人换 —— " +
|
||||
"一眼就能看出这句话是谁说的。关掉的话固定用主智能体的。",
|
||||
checked = vm.state.settings.followSpeaker,
|
||||
onChange = { vm.setFollowSpeaker(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// 对话(v1.2 §3.9 / §4.3)
|
||||
//
|
||||
// ★★ 这几个数字内核早就有、界面一直缺着 —— 用户只能手改 settings.json。
|
||||
// 而它们**都要和内核的默认值一致**,不然界面显示"20"而内核按别的跑。
|
||||
SettingsCard("对话") {
|
||||
NumberRow(
|
||||
title = "对话上下文窗口",
|
||||
sub = "每轮最多带最近多少轮对话进模型。超出的直接丢掉(不摘要)—— " +
|
||||
"该记住的走记忆系统。攒够几轮才裁一次,见下一项。",
|
||||
value = vm.state.settings.contextWindow,
|
||||
onChange = { vm.setContextWindow(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "攒够几轮裁一次",
|
||||
sub = "不是「超一点就裁」,而是攒够这个数才裁一批 —— " +
|
||||
"每轮都裁的话前缀缓存每轮都失效,比多带几轮贵得多。",
|
||||
value = vm.state.settings.contextBatch,
|
||||
onChange = { vm.setContextBatch(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "私聊最多几轮",
|
||||
sub = "两个智能体后台对聊时的上限(一轮 = 双方各说一次)。" +
|
||||
"这是安全网 —— 它们没有「该结束了」的内在信号。",
|
||||
value = vm.state.settings.privateChatRounds,
|
||||
onChange = { vm.setPrivateChatRounds(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★★ 用户要求:「talk_to 是用户可以选择传递和停止,有自动模式
|
||||
// (不用用户确认)」—— 所以默认是**手动**(关),
|
||||
// 群聊里 AI 交了话就停下来等你点;开了这个才是自动接着跑。
|
||||
FormSwitch(
|
||||
title = "AI 对聊自动模式",
|
||||
sub = "关(默认):群里 AI 把话交给别人时,底下会出现" +
|
||||
"「让他说 / 停在这」两个按钮,由你决定要不要接着聊。" +
|
||||
"开:不用确认,自动一轮轮接着跑(最多几轮)。",
|
||||
checked = vm.state.settings.aiTalkAuto,
|
||||
onChange = { vm.setAiTalkAuto(it) },
|
||||
)
|
||||
}
|
||||
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
FormField(
|
||||
@@ -1191,6 +1271,7 @@ internal data class SettingsDraft(
|
||||
if (speech.ttsVoice != base.ttsVoice) sp["ttsVoice"] = speech.ttsVoice
|
||||
if (speech.ttsSpeed != base.ttsSpeed) sp["ttsSpeed"] = speech.ttsSpeed
|
||||
if (speech.autoRead != base.autoRead) sp["autoRead"] = speech.autoRead
|
||||
if (speech.emotionTags != base.emotionTags) sp["emotionTags"] = speech.emotionTags
|
||||
if (speech.sttEngine != base.sttEngine) sp["sttEngine"] = speech.sttEngine
|
||||
if (speech.sttModel != base.sttModel) sp["sttModel"] = speech.sttModel
|
||||
if (speech.sttLanguage != base.sttLanguage) sp["sttLanguage"] = speech.sttLanguage
|
||||
@@ -1254,3 +1335,41 @@ private fun secretOrNull(raw: String): String? {
|
||||
if (v.all { it == '•' }) return null
|
||||
return v
|
||||
}
|
||||
|
||||
/**
|
||||
* 一行数字设置(v1.2 的上下文窗口 / 裁剪批量 / 私聊轮数)。
|
||||
*
|
||||
* ★ 独立一个组件而不是塞三个 `OutlinedTextField`:它们长得一样、
|
||||
* 行为也一样(只收数字、失焦/改完就存),抄三遍迟早有一处不一样。
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
value: Int,
|
||||
onChange: (Int) -> Unit,
|
||||
) {
|
||||
var draft by remember(value) { mutableStateOf(value.toString()) }
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { s ->
|
||||
val digits = s.filter { it.isDigit() }.take(4)
|
||||
draft = digits
|
||||
digits.toIntOrNull()?.takeIf { it > 0 }?.let(onChange)
|
||||
},
|
||||
singleLine = true,
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
|
||||
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
|
||||
),
|
||||
modifier = Modifier.width(100.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -72,6 +73,12 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
|
||||
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
|
||||
|
||||
// AI 界面能力的开关。改一下立刻存 —— 这个开关不需要"应用"按钮,
|
||||
// 用户拨完就想生效(跟下面的权限白名单不一样,那个要挑一堆再一起提交)。
|
||||
var uiToolsOn by remember(vm.settings.uiToolsEnabled) {
|
||||
mutableStateOf(vm.settings.uiToolsEnabled)
|
||||
}
|
||||
|
||||
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
|
||||
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
@@ -105,6 +112,50 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
|
||||
/* ============ ⓪ AI 界面能力(show_ui / ask_user / end_conversation)============
|
||||
*
|
||||
* 为什么单独一个卡片、而且默认关:这三个工具会让 AI **主动往用户脸上
|
||||
* 弹东西**(HTML 界面、选择弹窗),甚至**把对话封掉** ——
|
||||
* 属于"打扰性"能力,不该装好就默认打开。
|
||||
*/
|
||||
SettingsCard("AI 界面能力") {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("允许 AI 弹出界面和弹窗", fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"打开后 AI 才能用这三个工具。关掉时它们对模型完全隐藏。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 17.sp,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = uiToolsOn,
|
||||
onCheckedChange = {
|
||||
uiToolsOn = it
|
||||
vm.saveUiTools(it)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormHint(
|
||||
"· show_ui —— AI 自己写 HTML 弹一个全屏界面(图表、卡片、对比表)\n" +
|
||||
"· ask_user —— 弹一个选择框,等用户选完再继续(最多 120 秒)\n" +
|
||||
"· end_conversation —— AI 永久结束这次对话。屏幕中间会出现一条" +
|
||||
"写着原因的横幅,之后要开新对话才能继续",
|
||||
)
|
||||
if (!uiToolsOn) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"当前:关闭(模型看不到这三个工具)",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== ① 工具权限 ==================== */
|
||||
SettingsCard("工具权限") {
|
||||
SegmentedOptions(
|
||||
@@ -0,0 +1,452 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.view.doOnLayout
|
||||
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||
import com.termux.view.TerminalView
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* 内置 Termux 终端。
|
||||
*
|
||||
* 这里是**真的终端**,不是"命令框":
|
||||
* - 进程侧用 Termux 的 pty(libtermux.so 的 JNI 直接调 forkpty),所以是 tty,能跑 vim/top
|
||||
* - 渲染侧用 Termux 的 TerminalView,ANSI 颜色、光标、选区都是现成的
|
||||
*
|
||||
* 手机上没有 Esc/Tab/方向键,所以额外加了一排功能键 —— 没有它连 vim 都退不出来。
|
||||
*/
|
||||
@Composable
|
||||
fun TerminalScreen(
|
||||
vm: AppViewModel,
|
||||
termuxReady: Boolean,
|
||||
termuxStatus: String,
|
||||
onInstallTermux: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val terminal = remember { TermuxTerminal(context) }
|
||||
var title by remember { mutableStateOf("termux") }
|
||||
/**
|
||||
* pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台。
|
||||
*
|
||||
* ★ 这里**不再静默切换**:以前一旦判定失败就直接换成"命令框",
|
||||
* 用户只看到"怎么不是终端",完全不知道发生了什么(真踩过)。
|
||||
* 现在会**明说原因**并给"重试",终端仍然是主界面。
|
||||
*/
|
||||
var ptyFailed by remember { mutableStateOf(false) }
|
||||
var failReason by remember { mutableStateOf("") }
|
||||
var startedAt by remember { mutableStateOf(0L) }
|
||||
var showMirror by remember { mutableStateOf(false) }
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { terminal.destroy() }
|
||||
}
|
||||
|
||||
// 换源是独立全屏界面(源列表 + 说明装不进弹窗)
|
||||
if (showMirror) {
|
||||
MirrorScreen(onBack = { showMirror = false })
|
||||
return
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后很快就结束,说明 shell 拿不到 tty(stdin 直接 EOF)。
|
||||
//
|
||||
// ★ 要**连续两次**都秒退才认输。一次秒退可能是别的原因
|
||||
// (比如用户手滑按了 Ctrl+D 把 shell 退了),
|
||||
// 直接切到命令框会让"终端一闪就变成命令框",比不切还懵。
|
||||
var fastExits by remember { mutableStateOf(0) }
|
||||
/** 换起法之后要 +1,让 AndroidView 的 update 重新跑一遍去 attach 新会话 */
|
||||
var sessionTick by remember { mutableStateOf(0) }
|
||||
|
||||
// ★ 必须**在这里读一下** sessionTick。
|
||||
// Compose 只跟踪「组合期间读过」的状态:只在 update 那个 lambda 里读不算
|
||||
// (lambda 是布局阶段才跑的),于是 sessionTick 变了也不重组、update 不重跑、
|
||||
// 换了起法之后新会话**永远接不上** —— 表现是"屏幕停在旧会话的
|
||||
// [Process completed],打字没反应"。(真踩到了:修语法时把 key() 去掉,订阅也丢了。)
|
||||
val tickNow = sessionTick
|
||||
|
||||
/**
|
||||
* 重置 Termux 环境。
|
||||
*
|
||||
* ★ 为什么需要:装坏了自己救不回来。dpkg 的数据库和真实文件一旦不一致
|
||||
* (比如在修好 apt 路径之前试着装过包),后面 `pkg install` 会一直报
|
||||
* `E: Internal Error, No file name for ...` 或 `1 not fully installed or removed`,
|
||||
* **用户在界面上没有任何办法恢复**,只能清 App 数据 —— 那会把会议、设置、
|
||||
* 自定义节点全丢掉。有了这个,重置的代价只是"重下一次运行环境"。
|
||||
*
|
||||
* 删的是 `files/usr` + `files/home`;**不碰** kernel-data 和 nodes。
|
||||
*/
|
||||
var showResetConfirm by remember { mutableStateOf(false) }
|
||||
var resetting by remember { mutableStateOf(false) }
|
||||
var resetMsg by remember { mutableStateOf("") }
|
||||
|
||||
/**
|
||||
* 真 Termux 冲突(见下面横幅的注释)。
|
||||
*
|
||||
* ★ 为什么放在 `LaunchedEffect` 里而不是直接在组合里算:
|
||||
* 这个判断要**起一个进程跑 `dpkg --version`**,直接在组合里做会
|
||||
* 每帧跑一次。它是 IO,必须挪到副作用里,而且只查一次。
|
||||
*/
|
||||
var realTermuxConflict by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(termuxReady) {
|
||||
if (termuxReady) {
|
||||
realTermuxConflict = withContext(Dispatchers.IO) {
|
||||
runCatching { TermuxInstaller.hasRealTermuxConflict(context) }
|
||||
.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
val onSessionExit = {
|
||||
val quick = startedAt > 0 && System.currentTimeMillis() - startedAt < 900
|
||||
if (quick) {
|
||||
fastExits += 1
|
||||
TermuxInstaller.trace(context, "会话秒退(第 $fastExits 次)")
|
||||
// ★ 秒退 → **换下一种起法**。
|
||||
//
|
||||
// 关键:bash 起不来这件事**不会抛异常**(构造函数成功、rc 也跑了,
|
||||
// 然后 stdin EOF 就退出)。所以回退只能靠"退出得太快"这个事件驱动,
|
||||
// 不能靠 try/catch。试完所有起法才认输切命令控制台。
|
||||
val next = try {
|
||||
terminal.tryNextCandidate(onTitle = { title = it }, onExit = { })
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
if (next != null) {
|
||||
startedAt = System.currentTimeMillis()
|
||||
sessionTick += 1 // 触发 AndroidView update 去 attach 新会话
|
||||
TermuxInstaller.trace(context, "已切到:${terminal.startedWith}")
|
||||
// ★ 起法全试完 → **立刻**切命令控制台。之前要求"连续两次秒退",
|
||||
// 但候选有四种,全试完要好几秒,这期间屏幕是**全黑的**(上一种会话的画面
|
||||
// 刚被清掉、新的又没起来)—— 用户看到的就是"卡住了"。宁可切早点。
|
||||
} else {
|
||||
ptyFailed = true
|
||||
failReason = "几种起法都试过了,shell 一起来就退出(拿不到 tty)。"
|
||||
TermuxInstaller.trace(context, "pty 不可用,切成命令控制台:$failReason")
|
||||
}
|
||||
} else {
|
||||
fastExits = 0
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(Color(0xFF14161A))) {
|
||||
// ---------------- 顶部栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(Color(0xFF1C1F24)).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
IconButton(onClick = { vm.screen = Screen.Chat }) {
|
||||
Icon(Icons.Filled.ArrowBack, "返回", tint = Color.White)
|
||||
}
|
||||
Text(title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 换源:国内用官方源基本装不了东西,这是最常用的一个入口
|
||||
TextButton(onClick = { showMirror = true }) {
|
||||
Text("源", color = Color(0xFF9BE7B4), fontSize = 13.sp)
|
||||
}
|
||||
// 重置环境:装坏了(dpkg 数据库和文件不一致)时的唯一自救入口。
|
||||
// 放在换源旁边 —— 出问题时这两个是最先要点的。
|
||||
TextButton(onClick = { showResetConfirm = true }) {
|
||||
Text("重置", color = Color(0xFFFFB4A9), fontSize = 13.sp)
|
||||
}
|
||||
|
||||
// ---------------- 重置确认 + 进度 ----------------
|
||||
if (showResetConfirm) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showResetConfirm = false },
|
||||
title = { Text("重置 Termux 环境?") },
|
||||
text = {
|
||||
Text(
|
||||
"会把内置运行环境(约 95MB)删掉重新解压。\n\n" +
|
||||
"什么时候需要:pkg install 报 Internal Error、\n" +
|
||||
"not fully installed,或者终端起不来又查不出原因。\n\n" +
|
||||
"**会议、设置、智能体、自定义节点都不会动**," +
|
||||
"只有装在 Termux 里的包(python 之类)会没。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showResetConfirm = false
|
||||
resetting = true
|
||||
resetMsg = "正在准备…"
|
||||
Thread {
|
||||
val ok = TermuxInstaller.reset(context) { msg ->
|
||||
resetMsg = msg
|
||||
}
|
||||
resetting = false
|
||||
resetMsg = if (ok) "重置完成,重新打开终端即可" else "重置失败,看看 termux-install.log"
|
||||
}.start()
|
||||
}) { Text("重置", color = Color(0xFFD93025)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showResetConfirm = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
IconButton(onClick = {
|
||||
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
|
||||
terminal.session?.write("\u0003".toByteArray(), 0, 1)
|
||||
}) { Icon(Icons.Filled.Stop, "Ctrl+C", tint = Color.White) }
|
||||
IconButton(onClick = {
|
||||
terminal.session?.write("clear\n".toByteArray(), 0, 6)
|
||||
}) { Icon(Icons.Filled.DeleteSweep, "清屏", tint = Color.White) }
|
||||
}
|
||||
|
||||
// ---------------- 环境状态 / 安装入口 ----------------
|
||||
if (!termuxReady) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
if (termuxStatus.isBlank()) "正在准备内置 Termux 环境…" else termuxStatus,
|
||||
color = Color(0xFFFFD08A),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
if (termuxStatus.contains("失败")) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
TextButton(onClick = onInstallTermux) { Text("重试安装") }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Surface(color = Color(0xFF16301F), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Termux 已内置 · ${TermuxInstaller.prefix(context).absolutePath}\n" +
|
||||
"装东西前先换源(右上角「源」),官方源国内连不上",
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 真 Termux 的检测结果 —— v2.0.33 起**不再提示卸载**。
|
||||
*
|
||||
* 以前这里是一条红色横幅,让用户去卸载真 Termux,因为
|
||||
* Termux 仓库里的 dpkg 有个**编译死的配置目录**:
|
||||
*
|
||||
* dpkg: error: error opening configuration directory
|
||||
* "/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
|
||||
*
|
||||
* 那个目录"不存在"dpkg 会跳过、"存在但打不开"就直接死,
|
||||
* 而两个 App 同时装着就必然是后者 —— 从应用这侧无解。
|
||||
*
|
||||
* **现在从根上修掉了**:装的是我们自编的 dpkg,配置目录改成
|
||||
* 运行时从 `/proc/self/exe` 反推,指向自己所在的前缀。
|
||||
* 所以真 Termux 在不在场都无所谓,横幅也就没必要了。
|
||||
*
|
||||
* 配方见 `android/termux-dpkg/README.md`。
|
||||
* 安装逻辑在 `TermuxInstaller.installOwnDpkg`。
|
||||
*
|
||||
* ★ 这里不再渲染任何界面 —— 只在日志里记一笔,方便排查。
|
||||
* 保留这个变量和检测(`hasRealTermuxConflict`)是因为
|
||||
* 万一自编 dpkg 没装成功(比如 jniLibs 里那份坏了),
|
||||
* 日志里能看到"真 Termux 在场",好定位。
|
||||
*/
|
||||
LaunchedEffect(termuxReady, realTermuxConflict) {
|
||||
if (termuxReady && realTermuxConflict) {
|
||||
Log.i("DoubaoTerminal", "检测到真 Termux 在场 —— v2.0.33 起不影响使用(自编 dpkg)")
|
||||
}
|
||||
}
|
||||
|
||||
// ★ pty 失败要**明说**,别让用户以为"这软件就只有命令框"
|
||||
if (termuxReady && ptyFailed) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
"真终端起不来:$failReason\n" +
|
||||
"下面先用命令控制台顶着(同一条 Termux bash,只是没有 tty," +
|
||||
"所以 vim/top 这类全屏程序不能用)。",
|
||||
color = Color(0xFFFFD08A),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
TextButton(onClick = {
|
||||
ptyFailed = false
|
||||
failReason = ""
|
||||
startedAt = 0
|
||||
terminal.destroy()
|
||||
}) { Text("重试真终端") }
|
||||
TextButton(onClick = { showMirror = true }) { Text("换软件源") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 终端本体 ----------------
|
||||
if (termuxReady && ptyFailed) {
|
||||
// pty 用不了 → 命令控制台(跑的是同一条 Termux bash,只是没有 tty)
|
||||
//
|
||||
// ★ 上面那条橙色横幅会说明原因 + 给"重试真终端",
|
||||
// 不能让用户莫名其妙地从终端变成命令框。
|
||||
Box(Modifier.weight(1f).fillMaxWidth().background(Color(0xFF14161A))) {
|
||||
CommandConsole(
|
||||
onRun = { command, done ->
|
||||
vm.runTool("shell", org.json.JSONObject().put("command", command)) { ok, text ->
|
||||
done(ok, text)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
} else if (termuxReady) {
|
||||
AndroidView(
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
factory = { ctx ->
|
||||
TerminalView(ctx, null).apply {
|
||||
setTerminalViewClient(terminal.viewClient())
|
||||
setTextSize(28)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
// ★ 把 view 交给会话:`onTextChanged` 要靠它调 `onScreenUpdated()`
|
||||
// 去重画。不接的话屏幕永远不动 —— pty 通了、bash 活着、
|
||||
// 输出也解析了,**但一个像素都不刷新**(这个坑刚踩到)。
|
||||
terminal.view = this
|
||||
// ★ 点一下就弹软键盘。
|
||||
//
|
||||
// 之前 `onSingleTapUp` 里是一句空代码(`(e.source)`),
|
||||
// 点了什么都不会发生 —— 用户的原话是"输入不了"。
|
||||
// TerminalView 是普通 View,直接请求焦点 + 叫输入法就行。
|
||||
setOnClickListener {
|
||||
requestFocus()
|
||||
val imm = ctx.getSystemService(Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager
|
||||
imm?.showSoftInput(this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
// 读一下 tickNow:它变了说明换过起法,这次 update 要把新会话接上
|
||||
@Suppress("UNUSED_EXPRESSION") tickNow
|
||||
try {
|
||||
val session = terminal.session ?: run {
|
||||
startedAt = System.currentTimeMillis()
|
||||
terminal.createSession(onTitle = { title = it }, onExit = onSessionExit)
|
||||
}
|
||||
if (view.currentSession !== session) {
|
||||
// ★★ attach **必须等布局完成**。
|
||||
//
|
||||
// Termux 的 `TerminalSession` 构造函数**只存字段、不启动子进程**:
|
||||
// 子进程是在 `initializeEmulator(columns, rows, ...)` 里调
|
||||
// `JNI.createSubprocess(...)` 建的,而它由 `TerminalView.attachSession()`
|
||||
// 触发(内部拿 view 的宽高算行列数)。
|
||||
//
|
||||
// 在 `AndroidView.update` 里直接 attach 时 view 往往还没量过尺寸,
|
||||
// 于是 rows/columns = 0 → pty 建成 **0 列** →
|
||||
// shell 一起来就结束(退出码 0、几十毫秒),屏幕只剩 [Process completed]。
|
||||
// **这就是那个找了很久的"pty 拿不到 tty"。**
|
||||
//
|
||||
// doOnLayout 保证"量过了再 attach"。
|
||||
val doAttach = Runnable {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
}
|
||||
if (view.width > 0 && view.height > 0) {
|
||||
doAttach.run()
|
||||
} else {
|
||||
view.doOnLayout { doAttach.run() }
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
title = "会话启动失败:${t.message}"
|
||||
ptyFailed = true
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
// 没就绪时给一块占位区,别留空白让人以为卡死了
|
||||
Box(
|
||||
Modifier.weight(1f).fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"内置 Termux 环境还没装好,装好后这里就是真终端。",
|
||||
color = Color(0xFF8A93A0),
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 功能键(手机没键盘,必须有这一排) ----------------
|
||||
if (termuxReady) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(Color(0xFF1C1F24))
|
||||
.horizontalScroll(rememberScrollState()).padding(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
data class Key(val label: String, val bytes: String)
|
||||
val keys = listOf(
|
||||
// ★★ ENTER 放**第一个**,而且必须发 `\r`(CR)不是 `\n`(LF)。
|
||||
//
|
||||
// 终端里的"回车"是 **CR**:行规程(line discipline)靠 `\r`
|
||||
// 判定"这一行输入完了"。发 `\n` 的话光标会往下走一格,
|
||||
// 但**命令不会执行** —— 用户的原话就是"回车不了"。
|
||||
//
|
||||
// (Termux 自己的 TerminalView 也把输入法的回车转成 `\r`,
|
||||
// 见 TerminalView.java:401。)
|
||||
//
|
||||
// 另外它原来排在最后,被横向滚动**顶出屏幕**了,等于没有。
|
||||
// 回车是终端里按得最多的键,必须第一眼就能看到。
|
||||
Key("ENTER", "\r"),
|
||||
Key("ESC", "\u001b"),
|
||||
Key("TAB", "\t"),
|
||||
Key("CTRL+C", "\u0003"),
|
||||
Key("CTRL+D", "\u0004"),
|
||||
Key("↑", "\u001b[A"),
|
||||
Key("↓", "\u001b[B"),
|
||||
Key("←", "\u001b[D"),
|
||||
Key("→", "\u001b[C"),
|
||||
Key("HOME", "\u001b[H"),
|
||||
Key("END", "\u001b[F"),
|
||||
Key("|", "|"),
|
||||
Key("/", "/"),
|
||||
Key("-", "-"),
|
||||
)
|
||||
keys.forEach { key ->
|
||||
Surface(
|
||||
shape = RoundedCornerShape(6.dp),
|
||||
color = Color(0xFF2A2F37),
|
||||
modifier = Modifier.padding(end = 6.dp).clickable {
|
||||
val s = terminal.session ?: return@clickable
|
||||
val bytes = key.bytes.toByteArray()
|
||||
s.write(bytes, 0, bytes.size)
|
||||
},
|
||||
) {
|
||||
Text(
|
||||
key.label,
|
||||
color = Color(0xFFD7DAE0),
|
||||
fontSize = 12.sp,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TimeoutItem
|
||||
import com.doubao.lynxclone.data.TimeoutsState
|
||||
|
||||
/*
|
||||
* 「设置 → 超时」:所有超时都能在这儿调。
|
||||
*
|
||||
* ## 为什么做成全屏界面而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗,能开界面就开界面」—— 这里有 17 项、每项还带两三行说明,
|
||||
* 弹窗装不下(用户得在一个半屏高的框里滚十几屏)。
|
||||
*
|
||||
* ## ★★ 这一页**没有硬编码任何一项**
|
||||
*
|
||||
* 有哪些超时、叫什么、默认多少、能填多大、说明写什么 —— 全部来自内核
|
||||
* (`GET /api/timeouts` ← `android/kernel/timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 这么做的理由不是"架构好看",而是这个东西以前正是**反面教材**:
|
||||
* 15 个超时散在 10 个文件里当模块级常量,加一个超时要改好几处,
|
||||
* 而"到底有几个超时"这个问题谁都答不上来。现在加一项只改内核那一个文件,
|
||||
* 这一页自动多出一行。
|
||||
*
|
||||
* ## 怎么算保存
|
||||
*
|
||||
* 不做"保存按钮":点 +/- 立刻存,输入框失焦时存。
|
||||
* 每个改动都只发**改的那一项**(内核会并到当前值上),所以两项之间不会互相覆盖。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TimeoutsScreen(
|
||||
state: TimeoutsState,
|
||||
saving: Boolean,
|
||||
/** 只传改过的那一项 */
|
||||
onSave: (Map<String, Double>) -> Unit,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
FullScreen(
|
||||
title = "超时",
|
||||
subtitle = if (saving) "保存中…" else "改完立刻生效,不用重启",
|
||||
onBack = onBack,
|
||||
actions = { TopTextAction("恢复默认", onClick = onReset) },
|
||||
) {
|
||||
if (state.items.isEmpty()) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
if (state.error.isBlank()) "正在从内核读取…" else state.error,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
for ((group, items) in state.groups) {
|
||||
SectionLabel(group)
|
||||
for (item in items) {
|
||||
TimeoutRow(item = item, onSave = onSave)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"说明:这些值的边界由内核把关(填超了会自动夹回去)。" +
|
||||
"「不限时」表示会一直等,不会自己放弃。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimeoutRow(item: TimeoutItem, onSave: (Map<String, Double>) -> Unit) {
|
||||
// 输入框里的**草稿**(用户可能正在打字,这时候不能立刻拿它去保存,
|
||||
// 否则打到一半的 "18" 会被当成 18 存进去)
|
||||
var draft by remember(item.key) { mutableStateOf(fmt(item.value)) }
|
||||
var editing by remember(item.key) { mutableStateOf(false) }
|
||||
|
||||
// 值被外部改掉时(保存回来 / 恢复默认)同步草稿,但**别打断正在输入的人**
|
||||
if (!editing && draft != fmt(item.value)) draft = fmt(item.value)
|
||||
|
||||
val step = stepOf(item)
|
||||
|
||||
fun commit(raw: String) {
|
||||
val v = raw.trim().toDoubleOrNull() ?: item.value
|
||||
val clamped = v.coerceIn(item.min, item.max)
|
||||
draft = fmt(clamped)
|
||||
if (kotlin.math.abs(clamped - item.value) > 0.001) {
|
||||
onSave(mapOf(item.key to clamped))
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.label, fontSize = 14.sp, color = doubaoText())
|
||||
if (item.isDefault) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("默认", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StepButton("−") {
|
||||
val next = (item.value - step).coerceAtLeast(item.min)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { draft = it.filter { c -> c.isDigit() || c == '.' } },
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier
|
||||
.width(78.dp)
|
||||
.height(48.dp)
|
||||
.onFocusChanged { st ->
|
||||
if (st.isFocused) {
|
||||
editing = true
|
||||
} else if (editing) {
|
||||
editing = false
|
||||
commit(draft)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
StepButton("+") {
|
||||
val next = (item.value + step).coerceAtMost(item.max)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
// 0 且允许 0 时显示"不限时",比"0 秒"清楚得多
|
||||
if (item.unlimited) "${item.zero} (${item.unit})"
|
||||
else "单位:${item.unit} 范围 ${fmt(item.min)}–${fmt(item.max)}",
|
||||
fontSize = 10.sp,
|
||||
color = if (item.unlimited) Doubao.Blue else doubaoTextSecondary(),
|
||||
fontWeight = if (item.unlimited) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
if (item.desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(item.desc, fontSize = 11.sp, lineHeight = 17.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepButton(label: String, onClick: () -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 4.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, fontSize = 16.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
|
||||
/** 整秒显示,别出现 "180.0" */
|
||||
private fun fmt(v: Double): String =
|
||||
if (kotlin.math.abs(v - v.toInt()) < 0.001) v.toInt().toString() else v.toString()
|
||||
|
||||
/** 步长跟着量级走:5 秒的东西一次加 60 太难用,1800 秒的东西一次加 5 是折磨 */
|
||||
private fun stepOf(item: TimeoutItem): Double = when {
|
||||
item.max <= 60 -> 5.0
|
||||
item.max <= 300 -> 10.0
|
||||
item.max <= 900 -> 30.0
|
||||
else -> 60.0
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TokenUsage
|
||||
|
||||
/*
|
||||
* Token 用量详情(需求 3.1 的展示入口:选择界面「更多」按钮)。
|
||||
*
|
||||
* ## 展示什么
|
||||
*
|
||||
* · 累计用量(**输入 / 输出分列**,需求明确要求不合并)
|
||||
* · 限额进度(没限额就显示"无限制")
|
||||
* · **按模型分行**(需求 3.1 的"按模型分桶",可看总数也可展开)
|
||||
* · 配了单价才显示估算费用 —— 没配就只显示 Token 数,不瞎估
|
||||
*
|
||||
* ## 不做历史曲线
|
||||
*
|
||||
* 需求原话"当前不做曲线"(时间戳只是为将来预留)。
|
||||
*
|
||||
* ## 做全屏而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗」。这里要放三四行数字 + 一张可能十几行的模型表,
|
||||
* 弹窗装不下。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TokenUsageScreen(
|
||||
usage: TokenUsage?,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// ★ 清零是不可逆的(历史消耗数就没了),给它一次确认(复查报告 3.4)——
|
||||
// 这是"一次确认"的典型场景,弹窗正合适(AGENTS.md 那张表)
|
||||
var confirmReset by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "用量",
|
||||
subtitle = usage?.name?.takeIf { it.isNotBlank() }?.let { "$it · 累计" } ?: "正在读取…",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (usage != null && usage.total > 0) {
|
||||
TopTextAction("清零", danger = true) { confirmReset = true }
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (usage == null) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text("正在读取…", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
// ---- 总览 ----
|
||||
Card {
|
||||
Text("累计消耗", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
fmtTokens(usage.total),
|
||||
fontSize = 30.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("输入", usage.input)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("输出", usage.output)
|
||||
}
|
||||
// ★ 缓存统计(v1.2):**这家没给就不显示**。
|
||||
// 不是每家都返回缓存字段,显示两个恒为 0 的数会让用户
|
||||
// 以为"缓存完全没生效" —— 那是假警报,比不显示更糟。
|
||||
if (usage.hasCacheInfo) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("缓存命中", usage.cacheHit)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("缓存未命中", usage.cacheMiss)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"命中率 ${(usage.hitRate * 100).toInt()}% —— " +
|
||||
"命中缓存的输入便宜得多,这一段没白存",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
if (usage.pricePerK > 0 && usage.cost != null) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"估算费用 ¥${"%.2f".format(usage.cost)}(按 ¥${usage.pricePerK}/千 Token)",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 限额 ----
|
||||
Card {
|
||||
if (usage.unlimited) {
|
||||
Text("额度:无限制", fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"想限制他?在「管理 → 编辑」里填一个 Token 上限就行。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
Text("额度", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(
|
||||
fmtTokens(usage.remaining ?: 0),
|
||||
fontSize = 22.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoText(),
|
||||
)
|
||||
Text(
|
||||
" / ${fmtTokens(usage.limit)} 剩余",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// 进度条自己画(项目没有 material 的 LinearProgressIndicator 用法先例,
|
||||
// 一条圆角 Box 更可控)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Border),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(usage.percent.toFloat().coerceIn(0f, 1f))
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (usage.percent >= 1f) Color(0xFFD93025) else Doubao.Blue),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
if (usage.percent >= 1f)
|
||||
"已经用完了 —— 下一轮会被拦住,并附一句告别。可以清零、调大限额或改成无限制。"
|
||||
else "用满之后会拦住发送(记忆整理这类操作不受影响)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 按模型分桶 ----
|
||||
Card {
|
||||
Text("按模型", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (usage.byModel.isEmpty()) {
|
||||
Text("还没用过", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
} else {
|
||||
for ((i, m) in usage.byModel.withIndex()) {
|
||||
if (i > 0) Spacer(Modifier.height(8.dp))
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
m.model,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"入 ${fmtTokens(m.input)} · 出 ${fmtTokens(m.output)}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
// ★ 缓存命中/未命中(v1.2)。**这家没给就不显示这一行** ——
|
||||
// 不是每家都返回缓存字段,显示一个恒为 0 的"命中率"
|
||||
// 会让用户以为"缓存完全没生效"(那是个假警报)
|
||||
if (m.hasCacheInfo) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"命中 ${fmtTokens(m.cacheHit)} · 未命中 ${fmtTokens(m.cacheMiss)}" +
|
||||
" · 命中率 ${(m.hitRate * 100).toInt()}%",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmReset) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { confirmReset = false },
|
||||
title = { Text("清零用量", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"把「${usage?.name ?: ""}」的累计用量归零(当前 ${fmtTokens(usage?.total ?: 0)})。\n\n" +
|
||||
"这个数字回不来 —— 它是历史统计,不是「当前会话进度」。\n" +
|
||||
"清零之后额度也重新算,但它记得的东西、你们的对话都不受影响。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { confirmReset = false; onReset() },
|
||||
) { Text("清零") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { confirmReset = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 这里的私有 `Card` 删了 —— 它和 AgentEditScreen 的那个是**同一段代码**
|
||||
// 抄了两份(只有 vertical 内边距差 2dp)。现在统一用 DoubaoUi.kt 里的公共版。
|
||||
// 留着的话两个同签名函数都可见,编译器直接报"重载歧义"。
|
||||
|
||||
@Composable
|
||||
private fun Metric(label: String, value: Long) {
|
||||
Column {
|
||||
Text(label, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
Text(fmtTokens(value), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
}
|
||||
|
||||
/** 大数字加千分位:`12345` → `12,345`。Token 数动辄五六位,不加看不清量级 */
|
||||
fun fmtTokens(n: Long): String {
|
||||
val s = n.toString()
|
||||
if (s.length <= 3) return s
|
||||
val sb = StringBuilder()
|
||||
for ((i, c) in s.withIndex()) {
|
||||
if (i > 0 && (s.length - i) % 3 == 0) sb.append(',')
|
||||
sb.append(c)
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.BagItem
|
||||
|
||||
/**
|
||||
* 「我的角色」—— **用户角色**的属性与功能(v3.7)。
|
||||
*
|
||||
* 用户需求原话:「这个加个人属性(状态,数值,物品管理等)和功能(对决移动等)」
|
||||
*
|
||||
* 页面结构:
|
||||
* · 角色卡:这一局里"你"是谁(容器设置的名字 + 介绍)
|
||||
* · 数值:气血之类(进度条 + 当前/上限)
|
||||
* · 状态:常驻/限时 + 摘掉 / 给自己加
|
||||
* · 物品:获得 / 使用 / 对谁使用 / 给予 / 抛弃(和智能体同一套引擎)
|
||||
* · 功能:**一对一对决**(选同局成员)+ **移动**(走到某个地点)
|
||||
*
|
||||
* ★ 和 [BagScreen] 的区别:那个看的是某个 AI 的背包;这里是「你」自己的。
|
||||
*/
|
||||
@Composable
|
||||
fun UserItemsScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val container = vm.userRoleContainer()
|
||||
var addOpen by remember { mutableStateOf(false) }
|
||||
var statusOpen by remember { mutableStateOf(false) }
|
||||
var useOnFor by remember { mutableStateOf<BagItem?>(null) }
|
||||
var giveFor by remember { mutableStateOf<BagItem?>(null) }
|
||||
var useWithFor by remember { mutableStateOf<BagItem?>(null) }
|
||||
var useWithPicked by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
var duelOpen by remember { mutableStateOf(false) }
|
||||
var moveOpen by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "我的角色",
|
||||
subtitle = listOfNotNull(
|
||||
container?.name?.ifBlank { null },
|
||||
"你是:${vm.userRoleName()}",
|
||||
).joinToString(" · "),
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("获得物品") { addOpen = true }
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// ---- 角色卡 ----
|
||||
val desc = vm.userRoleDesc()
|
||||
SectionLabel("角色")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
vm.userRoleName(),
|
||||
fontSize = 16.sp,
|
||||
color = doubaoText(),
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
if (desc.isNotBlank()) {
|
||||
Text(
|
||||
desc,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
val place = vm.userPlaceName.ifBlank { "未分配地点" }
|
||||
Text(
|
||||
"当前位置:$place",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 死亡 / 复活(v3.20:气血为 0 判死,决斗中死亡算输)----
|
||||
if (vm.userDead) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E).copy(alpha = 0.10f))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"已死亡",
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
Text(
|
||||
"世界规则判了死亡(比如气血为 0);决斗中死亡算输。" +
|
||||
"改回「平常」就是复活 —— 用户是规则的主人。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
Text(
|
||||
"复活",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.padding(top = 8.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { vm.reviveUser() }
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 数值 ----
|
||||
SectionLabel("数值")
|
||||
if (vm.userStats.isEmpty()) {
|
||||
Hint("这一局没有定义数值(世界包 info.stats 为空)。")
|
||||
}
|
||||
for ((name, value, max) in vm.userStats) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(name, fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
if (max > 0) "${value.toInt()} / ${max.toInt()}" else "${value.toInt()}",
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoTextSecondary().copy(alpha = 0.18f)),
|
||||
) {
|
||||
val frac = if (max > 0) (value / max).coerceIn(0f, 1f) else 0f
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(frac)
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 功能 ----
|
||||
SectionLabel("功能")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
RowAction("决斗") { duelOpen = true }
|
||||
RowAction("🚶 移动") { moveOpen = true }
|
||||
}
|
||||
|
||||
// ---- 状态 ----
|
||||
SectionLabel("状态")
|
||||
if (vm.userStatuses.isEmpty()) {
|
||||
Hint("当前没有状态。别人能给你挂状态(比如中毒),你自己也能加。")
|
||||
}
|
||||
for ((name, remain) in vm.userStatuses) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(name, fontSize = 14.sp, color = doubaoText(), fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
if (remain < 0) "常驻" else "剩 $remain 轮",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("摘掉") { vm.userStatusAction(name, "drop") }
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(vertical = 4.dp)) {
|
||||
RowAction("+ 给自己加个状态") { statusOpen = true }
|
||||
}
|
||||
|
||||
// ---- 物品 ----
|
||||
SectionLabel("物品")
|
||||
if (vm.userItems.isEmpty()) {
|
||||
Hint("还没有物品。点右上「获得物品」拿一个,或让同局的智能体送你。")
|
||||
}
|
||||
for (it in vm.userItems) {
|
||||
UserItemCard(
|
||||
item = it,
|
||||
onUse = { vm.userItemAction(it, "use") },
|
||||
onUseWith = { useWithFor = it; useWithPicked = emptySet() },
|
||||
onUseOn = { useOnFor = it },
|
||||
onGive = { giveFor = it },
|
||||
onDrop = { vm.userItemAction(it, "drop") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================= 弹窗 =================
|
||||
if (addOpen) {
|
||||
val defs = vm.userItemsDefinitions()
|
||||
AlertDialog(
|
||||
onDismissRequest = { addOpen = false },
|
||||
title = { Text("获得物品") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (defs.isEmpty()) {
|
||||
Text("这个世界包没有定义物品。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (d in defs) {
|
||||
Text(
|
||||
"${d.name}(${d.kindLabel})",
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.grantUserItem(d.id, 1)
|
||||
addOpen = false
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { addOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
if (statusOpen) {
|
||||
val defs = vm.userStatusDefinitions()
|
||||
AlertDialog(
|
||||
onDismissRequest = { statusOpen = false },
|
||||
title = { Text("给自己加状态") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (defs.isEmpty()) {
|
||||
Text("这个世界包没有定义状态。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (d in defs) {
|
||||
Text(
|
||||
"${d.name}(${if (d.kind == "persistent") "常驻" else "限时"})",
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.userStatusAction(d.name, "grant")
|
||||
statusOpen = false
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { statusOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
useOnFor?.let { item ->
|
||||
val members = vm.userRoleMembers()
|
||||
AlertDialog(
|
||||
onDismissRequest = { useOnFor = null },
|
||||
title = { Text("把「${item.name}」对谁使用?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for ((id, name) in members) {
|
||||
Text(
|
||||
name.ifBlank { id },
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.userItemAction(item, "use", targets = listOf(id))
|
||||
useOnFor = null
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { useOnFor = null }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
giveFor?.let { item ->
|
||||
val members = vm.userRoleMembers()
|
||||
AlertDialog(
|
||||
onDismissRequest = { giveFor = null },
|
||||
title = { Text("把「${item.name}」送给谁?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for ((id, name) in members) {
|
||||
Text(
|
||||
name.ifBlank { id },
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.userItemAction(item, "give", target = id)
|
||||
giveFor = null
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { giveFor = null }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// 带材料使用:选要一起用掉的物品(工作台这类脚本要 api.attached)
|
||||
useWithFor?.let { item ->
|
||||
val others = vm.userItems.filter { it.id != item.id && it.count != 0 }
|
||||
AlertDialog(
|
||||
onDismissRequest = { useWithFor = null },
|
||||
title = { Text("带上材料使用「${item.name}」") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"选要一起用掉的物品(脚本通过 api.attached 读到)。" +
|
||||
"比如工作台要带 2 根木头,做出一把木椅。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
if (others.isEmpty()) {
|
||||
Text("背包里没有别的物品可带。", fontSize = 13.sp,
|
||||
color = doubaoTextSecondary())
|
||||
}
|
||||
for (o in others) {
|
||||
val on = o.id in useWithPicked
|
||||
val cnt = if (o.count < 0) "∞" else "×${o.count}"
|
||||
Text(
|
||||
(if (on) "✓ " else "") + "${o.name}$cnt",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoText(),
|
||||
fontWeight = if (on) FontWeight.Medium else FontWeight.Normal,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
useWithPicked = if (on) useWithPicked - o.id
|
||||
else useWithPicked + o.id
|
||||
}
|
||||
.padding(vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.userItemAction(item, "use", with = useWithPicked.toList())
|
||||
useWithFor = null
|
||||
}) { Text("使用") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { useWithFor = null }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 决斗:选一个同局成员(v3.17:多回合,决斗留在当前对话里)
|
||||
if (duelOpen) {
|
||||
val members = vm.userRoleMembers()
|
||||
AlertDialog(
|
||||
onDismissRequest = { duelOpen = false },
|
||||
title = { Text("向谁发起决斗?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"决斗留在当前对话里(不另开对话),一回合一点「出招」推进;" +
|
||||
"过程和结果由世界脚本裁决,中断要双方同意。" +
|
||||
"没有武器(target 类物品)的一方会被直接判失败 —— " +
|
||||
"先确认自己背包里有能对别人用的东西。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
Text(
|
||||
"每回合双方各用自己的武器出手(跑物品脚本,∞ 武器不消耗)," +
|
||||
"决斗界面里可以每回合换武器;没有回合上限。" +
|
||||
"结果只有四种:赢 / 输 / 平局 / 停手。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
if (members.isEmpty()) {
|
||||
Text("这一局还没有成员。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for ((id, name) in members) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
name.ifBlank { id },
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("选他") {
|
||||
vm.startDuelWith(id)
|
||||
duelOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { duelOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// 移动:选一个地点
|
||||
if (moveOpen) {
|
||||
val places = vm.placesOfCurrentContainer()
|
||||
AlertDialog(
|
||||
onDismissRequest = { moveOpen = false },
|
||||
title = { Text("走到哪里?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (places.isEmpty()) {
|
||||
Text("这一局没有地点(世界包 info.places 为空)。",
|
||||
fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (p in places) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
(if (p.id == vm.userPlaceId) "✓ " else "") + p.name,
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction(if (p.id == vm.userPlaceId) "就在这儿" else "去") {
|
||||
vm.userMove(p.id)
|
||||
moveOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { moveOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户背包里的一件物品(数量 / 类型 / 四个操作) */
|
||||
@Composable
|
||||
private fun UserItemCard(
|
||||
item: BagItem,
|
||||
onUse: () -> Unit,
|
||||
onUseWith: () -> Unit,
|
||||
onUseOn: () -> Unit,
|
||||
onGive: () -> Unit,
|
||||
onDrop: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.name, fontSize = 15.sp, color = doubaoText(), fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(item.countLabel, fontSize = 12.sp, color = Doubao.Blue, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(item.kindLabel, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
if (item.desc.isNotBlank()) {
|
||||
Text(
|
||||
item.desc,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (item.usable) RowAction("使用") { onUse() }
|
||||
// ★ v3.21:带材料使用(工作台这类被动物品要材料)
|
||||
if (item.usable && item.kind != "target") RowAction("带材料用") { onUseWith() }
|
||||
if (item.kind == "target") RowAction("对谁使用") { onUseOn() }
|
||||
RowAction("给予") { onGive() }
|
||||
RowAction("抛弃") { onDrop() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.core.tween
|
||||
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.heightIn
|
||||
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.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.TouchApp
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
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 androidx.compose.ui.viewinterop.AndroidView
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/**
|
||||
* ★★ 全屏看网页 —— 由一个**明确的按钮**打开,不靠去点正文里的小字。
|
||||
*
|
||||
* ## 为什么单独做这个界面
|
||||
*
|
||||
* 聊天气泡里的 markdown 链接做成蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会发生什么(是开浏览器?还是在应用里开?)。
|
||||
* 用户的原话是"你要单独开个按钮" —— 对,产品上正确的就是给个按钮。
|
||||
*
|
||||
* 所以:消息操作栏里出现一个「打开网页」按钮(只有回复里真有链接才出现),
|
||||
* 点开就是这里 —— 一个像样的浏览器界面,而不是把用户丢给系统浏览器
|
||||
* (那样他就离开 App 了,回来还得重新找对话)。
|
||||
*
|
||||
* ## 和 AI 那个 `show_ui` 界面的区别
|
||||
*
|
||||
* `show_ui` 是 **AI 写的 HTML**,我们注入内容、页面里只有它写的东西
|
||||
* 这里 是**真的在浏览互联网**,用户能点链接、能返回、能前进
|
||||
*
|
||||
* 两者都需要 JS,但**桥只有 `show_ui` 那边有** —— 这里浏览的是外部网站,
|
||||
* 绝不能让它碰到 App 的接口(所以这个 WebView 里没有任何
|
||||
* `addJavascriptInterface`)。
|
||||
*
|
||||
* ## 安全
|
||||
*
|
||||
* 文件访问 / 跨域访问 / 混合内容全部关闭。没有注入任何 JS 桥。
|
||||
* 这是"浏览器",就该按浏览器的方式隔离。
|
||||
*
|
||||
* ## 点选模式(把网页上的东西回传给 AI)
|
||||
*
|
||||
* 顶部有个「点选」按钮。打开之后页面上的可点元素会被描上虚线边框,
|
||||
* 用户点哪个就把哪个的**文字/链接/位置**记下来,出现在底部确认条上,
|
||||
* 用户点「发给 AI」才真的发出去(点错了不至于白跑一轮模型)。
|
||||
*
|
||||
* ★ 实现上**没有挂 JS 桥** —— 用的是"注入脚本写进数组 + Kotlin 主动轮询取走",
|
||||
* 数据只从页面流向 App。理由见 [WebPick] 的注释:这里浏览的是外部网站,
|
||||
* 挂桥等于把 App 的内部接口交给互联网上任意一个站点。
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
fun WebPageScreen(
|
||||
url: String,
|
||||
onClose: () -> Unit,
|
||||
onSendToAi: (String) -> Unit = {},
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var title by remember(url) { mutableStateOf("") }
|
||||
var canBack by remember { mutableStateOf(false) }
|
||||
var canFwd by remember { mutableStateOf(false) }
|
||||
var progress by remember { mutableStateOf(0) }
|
||||
|
||||
/** 点选模式开着没有 */
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
|
||||
/**
|
||||
* 用户选中/填写的条目(**累积**)。
|
||||
*
|
||||
* ★ 累积而不是点一条发一条:用户可能在页面上选好几处、填几个框,
|
||||
* 然后一起问"这些对不对"。分开发会触发好几轮模型调用,又慢又费 token。
|
||||
*/
|
||||
val picked = remember { mutableStateListOf<PickedElement>() }
|
||||
|
||||
// WebView 没有"导航状态变了"的回调,只能轮询。
|
||||
// 400ms 在真机上完全够用(页面前进后退是用户动作,不是动画)。
|
||||
LaunchedEffect(web) {
|
||||
while (web != null) {
|
||||
canBack = web?.canGoBack() == true
|
||||
canFwd = web?.canGoForward() == true
|
||||
delay(400)
|
||||
}
|
||||
}
|
||||
|
||||
// 点选模式下:每次加载完注入一次;然后每 500ms 取一次队列。
|
||||
//
|
||||
// ★ 为什么要"每次加载完注入":用户点链接跳到新页面(或页面自己跳),
|
||||
// 新文档里没有我们注入的脚本,不重注就没法点了。
|
||||
LaunchedEffect(web, picking) {
|
||||
if (!picking || web == null) {
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
while (true) {
|
||||
delay(500)
|
||||
val w = web ?: break
|
||||
// evaluateJavascript 的返回值经 JSON 编码:脚本返回字符串 'xxx',
|
||||
// 这里拿到的是 "\"xxx\"" —— 所以要解两层
|
||||
w.evaluateJavascript(WebPick.DRAIN_JS) { raw ->
|
||||
val parsed = decodeJsonString(raw)
|
||||
if (parsed.isBlank() || parsed == "[]") return@evaluateJavascript
|
||||
runCatching {
|
||||
val arr = org.json.JSONArray(parsed)
|
||||
for (i in 0 until arr.length()) {
|
||||
val obj = arr.optJSONObject(i) ?: continue
|
||||
picked.add(
|
||||
PickedElement(
|
||||
summary = WebPick.describe(obj),
|
||||
kind = obj.optString("kind", "click"),
|
||||
url = obj.optString("url"),
|
||||
pageTitle = obj.optString("title").ifBlank { title },
|
||||
raw = obj.toString(),
|
||||
),
|
||||
)
|
||||
}
|
||||
// 只留最近 30 条,别让用户在页面上乱点把内存堆满
|
||||
while (picked.size > 30) picked.removeAt(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 系统返回键:先回退网页,退不了了才关界面
|
||||
BackHandler(enabled = true) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 6.dp, end = 6.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowBack, "后退", canBack) { web?.goBack() }
|
||||
NavIcon(Icons.AutoMirrored.Filled.ArrowForward, "前进", canFwd) { web?.goForward() }
|
||||
NavIcon(Icons.Filled.Refresh, "刷新", true) { web?.reload() }
|
||||
|
||||
// 标题:能拿到网页 title 就用它,拿不到退回落 host ——
|
||||
// 只显示一长串 URL 在手机窄屏上没法看
|
||||
Column(Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||
Text(
|
||||
title.ifBlank { hostOf(url) },
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (title.isNotBlank()) {
|
||||
Text(
|
||||
hostOf(url),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
NavIcon(Icons.Filled.OpenInNew, "用系统浏览器打开", true) {
|
||||
openInBrowser(ctx, web?.url ?: url)
|
||||
}
|
||||
NavIcon(Icons.Filled.Close, "关闭", true) { onClose() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 「点选」开关 —— 打开后能在网页上点东西回传给 AI。
|
||||
*
|
||||
* ★ 做成一条**常驻的横条**而不是顶部一个图标:
|
||||
* 这个能力不看说明根本发现不了(用户得先知道"能点选"才会去找按钮)。
|
||||
* 横条上写清楚现在是什么状态、点了会发生什么。
|
||||
*/
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(if (picking) doubaoAccentSoft() else doubaoCard())
|
||||
.clickable {
|
||||
if (picking) {
|
||||
web?.evaluateJavascript(WebPick.UNINSTALL_JS, null)
|
||||
picking = false
|
||||
picked.clear()
|
||||
} else {
|
||||
picking = true
|
||||
}
|
||||
}
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.TouchApp,
|
||||
null,
|
||||
tint = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
if (picking) "点选已开启 —— 点网页上任意元素,内容会带回给 AI" else "点选:把网页上的内容带回给 AI",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (picking) "关闭" else "开启",
|
||||
fontSize = 13.sp,
|
||||
color = if (picking) doubaoAccent() else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
// 加载进度:细一条,不占地方但能让人知道"在动"
|
||||
AnimatedVisibility(
|
||||
visible = progress in 1..99,
|
||||
enter = fadeIn(tween(120)),
|
||||
exit = fadeOut(tween(300)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(progress / 100f)
|
||||
.height(2.dp)
|
||||
.background(doubaoAccent()),
|
||||
)
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { c ->
|
||||
WebView(c).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true // 正常浏览器行为
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = true
|
||||
settings.builtInZoomControls = true
|
||||
settings.displayZoomControls = false
|
||||
settings.userAgentString = settings.userAgentString + " DoubaoClone"
|
||||
|
||||
// ★ 这个 WebView 里**不挂任何 JS 桥** ——
|
||||
// 浏览的是外部网站,绝不能让它碰到 App 的接口。
|
||||
// (点选回传走的是"页面写队列 + 我们主动 evaluateJavascript 取",
|
||||
// 数据单向,页面没有办法主动调 App。见 WebPick 的注释。)
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, u: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, u, favicon)
|
||||
progress = 5
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, u: String?) {
|
||||
super.onPageFinished(view, u)
|
||||
progress = 100
|
||||
title = view?.title.orEmpty()
|
||||
// ★ 用户点链接跳到新页面(或页面自己跳)之后,
|
||||
// 新文档里没有我们注入的脚本 —— 点选模式就失效了。
|
||||
// 所以每次加载完补注一次(脚本自己防重)。
|
||||
if (picking) view?.evaluateJavascript(WebPick.INSTALL_JS, null)
|
||||
}
|
||||
}
|
||||
webChromeClient = object : android.webkit.WebChromeClient() {
|
||||
override fun onProgressChanged(view: WebView?, newProgress: Int) {
|
||||
progress = newProgress
|
||||
}
|
||||
|
||||
override fun onReceivedTitle(view: WebView?, t: String?) {
|
||||
if (!t.isNullOrBlank()) title = t
|
||||
}
|
||||
}
|
||||
loadUrl(url)
|
||||
web = this
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* 底部确认条:用户点中了什么,以及「发给 AI / 取消」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*/
|
||||
/**
|
||||
* 底部确认条:用户攒了哪些"选了/写了"的内容,以及
|
||||
* 「发给 AI」「清空」。
|
||||
*
|
||||
* ★ 为什么要有这一步而不是点了就发:
|
||||
* 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token,
|
||||
* 而模型会基于一个错误的前提回答。
|
||||
* 让用户确认一下,成本极低、收益很大。
|
||||
*
|
||||
* ★ 支持**累积多条**再一起发 —— 用户在页面上选几处、填几个框,
|
||||
* 最后一起问"这些对不对"。分开发会跑好几轮模型。
|
||||
*/
|
||||
AnimatedVisibility(
|
||||
visible = picked.isNotEmpty(),
|
||||
enter = slideInVertically(tween(220)) { it } + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(tween(180)) { it } + fadeOut(tween(120)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"已选 ${picked.size} 条,会一起发给 AI:",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"清空",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoAccent(),
|
||||
modifier = Modifier.clickable { picked.clear() },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// 条目多了要能滚 —— 但只占一段固定高度,别把网页挤没了
|
||||
Column(
|
||||
Modifier
|
||||
.heightIn(max = 120.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
picked.forEach { p ->
|
||||
Text(
|
||||
"· " + p.summary,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(11.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
androidx.compose.material3.OutlinedButton(
|
||||
onClick = { picked.clear() },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
androidx.compose.material3.Button(
|
||||
onClick = {
|
||||
onSendToAi(WebPick.buildReport(picked.toList()))
|
||||
picked.clear()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("发给 AI") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `evaluateJavascript` 的返回值是**经 JSON 编码的字符串**(脚本返回 `'abc'`
|
||||
* 时 Kotlin 拿到的是 `"\"abc\""`)。
|
||||
*
|
||||
* ★ 这个坑踩过两次([AiWebView] 的探针、这里),所以抽成一个函数,
|
||||
* 并在名字上把"要解两层"这件事写出来。
|
||||
*/
|
||||
private fun decodeJsonString(raw: String?): String {
|
||||
val s = (raw ?: "").trim()
|
||||
if (s.isEmpty() || s == "null") return ""
|
||||
return try {
|
||||
if (s.startsWith("\"")) org.json.JSONTokener(s).nextValue() as? String ?: "" else s
|
||||
} catch (_: Throwable) {
|
||||
s.trim('"')
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavIcon(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
desc: String,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
// 不能点的时候**也要占位**(否则顶部栏的图标会左右跳),
|
||||
// 但变淡 + 不响应点击
|
||||
.clickable(enabled = enabled) { onClick() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
icon,
|
||||
desc,
|
||||
tint = if (enabled) doubaoText() else doubaoTextDim().copy(alpha = 0.35f),
|
||||
modifier = Modifier.size(19.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 URL 里取主机名(显示用)。解析不了就原样返回。 */
|
||||
private fun hostOf(url: String): String = try {
|
||||
android.net.Uri.parse(url).host ?: url
|
||||
} catch (_: Throwable) {
|
||||
url
|
||||
}
|
||||
|
||||
/**
|
||||
* 「网页」—— **独立全屏界面**,不是弹窗。
|
||||
*
|
||||
* ## 为什么不用 AlertDialog
|
||||
*
|
||||
* 项目约定:**列表这种要滚动的东西不用弹窗**。一条回复里挂五六个链接是常事,
|
||||
* 弹窗一屏只装得下三四个,用户得在弹窗里滚动 —— 那还不如直接开一屏。
|
||||
* 而且弹窗盖住对话,用户没法一边看着回复一边挑链接。
|
||||
*
|
||||
* ## ★★ 自己输网址(v2.0.39 加)
|
||||
*
|
||||
* 用户的原话是"**你要单独开个按钮**"。既然它是个按钮,那它就不该只在
|
||||
* "这条回复恰好有链接"时才有用 —— 现在里面能直接输网址,
|
||||
* 它就是一个**浏览器入口**,任何时候按都有意义。
|
||||
* (另一个原因:`extractUrls` 曾经漏认写法,导致按钮整个不显示,
|
||||
* 用户根本不知道这功能存在。)
|
||||
*
|
||||
* 顶栏按项目约定:`← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun UrlListScreen(
|
||||
owner: String,
|
||||
urls: List<FoundUrl>,
|
||||
onPick: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
var typed by remember { mutableStateOf("") }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("网页", onBack = onClose) {
|
||||
if (urls.isNotEmpty()) {
|
||||
Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
/* ---------- 自己输网址(永远在最上面,入口要显眼)---------- */
|
||||
item {
|
||||
Column {
|
||||
Text("输入网址", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
singleLine = true,
|
||||
placeholder = { Text("example.com", fontSize = 14.sp) },
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 15.sp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
androidx.compose.material3.Button(
|
||||
onClick = { onPick(typed) },
|
||||
enabled = typed.isNotBlank(),
|
||||
) { Text("打开") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 这条回复里找到的链接 ---------- */
|
||||
if (urls.isNotEmpty()) {
|
||||
item {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// ★ 一定要写 ${owner} 而不是 $owner:紧跟中文时 Kotlin 会把
|
||||
// 后面那几个汉字当成变量名的一部分(`$owner里提到的网页` 会
|
||||
// 被解析成一个叫「owner里提到的网页」的标识符,报未解析引用)。
|
||||
Text("${owner}里提到的网页:", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
items(urls.size) { index ->
|
||||
val u = urls[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onPick(u.url) }
|
||||
.padding(horizontal = 14.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
/**
|
||||
* ★ 主标题优先用**模型给链接写的文字**。
|
||||
*
|
||||
* 以前只显示 host,于是同一域名的两条链接
|
||||
* (`https://example.com` 和
|
||||
* `https://example.com/index-zh`)
|
||||
* 看起来**一模一样**,用户根本分不出该点哪个。
|
||||
* 模型的链接文字就是为了区分它们而写的。
|
||||
*/
|
||||
Text(
|
||||
u.label.ifBlank { hostOf(u.url) },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
u.url,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user