Compare commits
69 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
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/
|
||||
|
||||
182
AGENTS.md
182
AGENTS.md
@@ -1,161 +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 真出现过)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `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`
|
||||
找不到这种)。
|
||||
坑和完整操作(装 APK、截图、点按、抓内核日志、连设备内核 API)都在
|
||||
[`豆鲍/docs/安卓模拟器-操作手册.md`](豆鲍/docs/安卓模拟器-操作手册.md)。
|
||||
|
||||
详细约定见 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)。
|
||||
|
||||
677
README.md
677
README.md
@@ -1,666 +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`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.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,整包 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 内核对拍
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
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。
|
||||
|
||||
约定见 [`AGENTS.md`](AGENTS.md)(入口)和 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)(详细)。
|
||||
|
||||
@@ -1,452 +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.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
|
||||
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() }
|
||||
|
||||
// 提示条 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)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 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
|
||||
},
|
||||
onOpenMeetings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Meetings
|
||||
},
|
||||
onOpenTerminal = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Terminal
|
||||
},
|
||||
onOpenSettings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
onClose = { vm.moreSheetOpen = false },
|
||||
)
|
||||
}
|
||||
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
AnimatedVisibility(
|
||||
visible = vm.notesOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
NotesScreen(
|
||||
notes = vm.notes,
|
||||
opening = vm.openingNote,
|
||||
onOpen = { vm.openNote(it) },
|
||||
onCloseNote = { vm.closeNote() },
|
||||
onDelete = { vm.deleteNote(it) },
|
||||
onBack = { vm.closeNotes() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。
|
||||
// 排在 HTML 界面之下:点一个就从列表进到界面。
|
||||
AnimatedVisibility(
|
||||
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) },
|
||||
)
|
||||
|
||||
// 「网页」界面(**独立全屏界面**,不是弹窗)。
|
||||
// 排在网页显示之下:用户选完就直接进网页,中间那一层要能被盖住。
|
||||
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)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 抽屉 ------------------------------ */
|
||||
|
||||
@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(horizontal = 20.dp, vertical = 6.dp))
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
vm.openNotes()
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Apps, "更多功能") {
|
||||
vm.drawerOpen = false
|
||||
vm.moreSheetOpen = true
|
||||
}
|
||||
|
||||
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,934 +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 com.doubao.lynxclone.termux.AiSurface
|
||||
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)
|
||||
|
||||
/* -------------------- AI 主动弹出来的东西 -------------------- */
|
||||
|
||||
/**
|
||||
* AI 弹的全屏 HTML 界面(`show_ui` 工具);null 表示没有。
|
||||
*
|
||||
* 数据源是 [AiSurface](内核线程往里写),这里通过监听器同步过来 ——
|
||||
* 内核永远不直接碰 Compose。
|
||||
*/
|
||||
var aiScreen by mutableStateOf<AiSurface.Screen?>(null)
|
||||
private set
|
||||
|
||||
/** AI 弹的选择弹窗(`ask_user` 工具);null 表示没有 */
|
||||
var aiDialog by mutableStateOf<AiSurface.Dialog?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* ApplicationContext。
|
||||
*
|
||||
* ★ ViewModel 自己拿不到 Context(这个项目没上 DI 框架),
|
||||
* 而"AI 界面"那些文件要读写磁盘 —— 所以在 Compose 那一层塞进来。
|
||||
* 用 **applicationContext**:ViewModel 活得比 Activity 久,攥着会泄漏。
|
||||
*/
|
||||
var appContext: android.content.Context? = null
|
||||
|
||||
/**
|
||||
* ★★ 存下来的 AI 界面列表(用户要求"AI 写的界面可以再点开")。
|
||||
*
|
||||
* 每次 `show_ui` 都会把 HTML 存一份到 App 私有目录,这里列出它们,
|
||||
* 用户随时能再打开 —— 不用让 AI 重新生成(重新生成的内容不一定一样)。
|
||||
*/
|
||||
var aiScreenList by mutableStateOf<List<AiScreenItem>>(emptyList())
|
||||
private set
|
||||
|
||||
/** 「AI 界面」列表界面开着没有 */
|
||||
var aiScreenListOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 「更多功能」页开着没有。
|
||||
*
|
||||
* ★ 抽屉原来平铺 9 个入口,把对话列表挤没了(用户反馈"太挤了对话都没了")。
|
||||
* 现在只留天天用的,其余收进这一页。
|
||||
*/
|
||||
var moreSheetOpen by mutableStateOf(false)
|
||||
|
||||
/* -------------------- 笔记(用户要能查看)-------------------- */
|
||||
|
||||
/**
|
||||
* 笔记列表。
|
||||
*
|
||||
* ★ 用户的原话:"notes 用户要能查看" —— 以前笔记**只有 AI 能读写**,
|
||||
* 用户在界面上完全看不到:AI 说"我记下来了",他没法确认记了什么、
|
||||
* 记错没有。这类"AI 替你做事但你无法查看"的功能,用户不会信任。
|
||||
*/
|
||||
var notes by mutableStateOf<List<com.doubao.lynxclone.data.NoteItem>>(emptyList())
|
||||
private set
|
||||
|
||||
var notesOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** 正在阅读的那条笔记(null = 在列表页) */
|
||||
var openingNote by mutableStateOf<com.doubao.lynxclone.data.NoteItem?>(null)
|
||||
private set
|
||||
|
||||
fun openNotes() {
|
||||
notesOpen = true
|
||||
openingNote = null
|
||||
refreshNotes()
|
||||
}
|
||||
|
||||
fun closeNotes() {
|
||||
notesOpen = false
|
||||
openingNote = null
|
||||
}
|
||||
|
||||
fun refreshNotes() {
|
||||
viewModelScope.launch {
|
||||
val list = runCatching {
|
||||
withContext(Dispatchers.IO) { client.notes() }
|
||||
}.getOrDefault(emptyList())
|
||||
notes = list
|
||||
}
|
||||
}
|
||||
|
||||
/** 点开一条:列表接口不带正文,这里再去读全文 */
|
||||
fun openNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
val full = runCatching {
|
||||
withContext(Dispatchers.IO) { client.note(item.file) }
|
||||
}.getOrNull()
|
||||
openingNote = full ?: item
|
||||
}
|
||||
}
|
||||
|
||||
fun closeNote() {
|
||||
openingNote = null
|
||||
}
|
||||
|
||||
fun deleteNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching { client.deleteNote(item.file) }.isSuccess
|
||||
}
|
||||
openingNote = null
|
||||
refreshNotes()
|
||||
showHint(if (ok) "已删除「${item.title.ifBlank { item.file }}」" else "删除失败")
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开 AI 界面列表 / 直接重开某一个 */
|
||||
fun openAiScreenList() {
|
||||
aiScreenListOpen = true
|
||||
refreshAiScreens()
|
||||
}
|
||||
|
||||
fun dismissAiScreenList() {
|
||||
aiScreenListOpen = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 从磁盘重新读一遍界面索引。
|
||||
*
|
||||
* ★ 为什么不用 KernelClient:界面是 **Kotlin 自己存的**(App 私有目录),
|
||||
* 不经过内核。用 `AiSurface` 直接读,少一次 HTTP 往返、也少一个失败点。
|
||||
*/
|
||||
fun refreshAiScreens() {
|
||||
val app = appContext ?: return
|
||||
val arr = AiSurface.loadScreenIndex(app)
|
||||
val out = ArrayList<AiScreenItem>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
val id = it.optString("id")
|
||||
if (id.isBlank()) continue
|
||||
out.add(
|
||||
AiScreenItem(
|
||||
id = id,
|
||||
title = it.optString("title").ifBlank { "AI 界面" },
|
||||
preview = it.optString("preview"),
|
||||
bytes = it.optInt("bytes"),
|
||||
at = it.optLong("at"),
|
||||
conversationId = it.optString("conversationId"),
|
||||
),
|
||||
)
|
||||
}
|
||||
aiScreenList = out
|
||||
}
|
||||
|
||||
/** 再打开一个存下来的界面(不需要模型参与,内容就在磁盘上) */
|
||||
fun reopenAiScreen(screenId: String) {
|
||||
val app = appContext ?: return
|
||||
val html = AiSurface.readScreen(app, screenId)
|
||||
if (html.isNullOrBlank()) {
|
||||
showHint("这个界面已经不在了(可能被清理或删除)")
|
||||
refreshAiScreens()
|
||||
return
|
||||
}
|
||||
var title = ""
|
||||
var fullHtml = false
|
||||
val arr = AiSurface.loadScreenIndex(app)
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") == screenId) {
|
||||
title = it.optString("title")
|
||||
fullHtml = it.optBoolean("fullHtml")
|
||||
break
|
||||
}
|
||||
}
|
||||
// ★ 不要在这里关列表界面:用户可能从**列表**里点进来的,
|
||||
// 也可能从**消息操作栏**直接点进来(那时列表本来就没开)。
|
||||
// 关掉的话会顺手把列表状态清掉,退出界面后回不到列表 ——
|
||||
// 而"逐条收藏翻看"正是用户会做的事。
|
||||
// 列表在下面一层,HTML 界面盖在它上面(见 AppRoot 的层级顺序)。
|
||||
AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = activeConversationId,
|
||||
wait = false,
|
||||
screenId = screenId,
|
||||
)
|
||||
aiScreen = AiSurface.screen
|
||||
}
|
||||
|
||||
fun deleteAiScreen(screenId: String) {
|
||||
val app = appContext ?: return
|
||||
AiSurface.deleteScreen(app, screenId)
|
||||
refreshAiScreens()
|
||||
showHint("已删除")
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前对话被 AI 永久结束了 —— 界面据此把输入框换成结束横幅。
|
||||
*
|
||||
* ★ 这是从内核读回来的**落盘状态**(Conversation.ended),不是本地开关。
|
||||
*/
|
||||
var conversationEnded by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** AI 给出的结束原因(屏幕中间那个横幅上写的就是它) */
|
||||
var endedReason by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/**
|
||||
* 正在全屏看的网页(点消息下方的「打开网页」按钮进来的);null 表示没开。
|
||||
*
|
||||
* ★ 为什么要有这个独立界面,而不是让用户去点正文里那行小字:
|
||||
* 链接做成蓝色下划线**没有可发现性** —— 用户不知道能点、也不知道点了
|
||||
* 会发生什么。产品上正确的是给一个**明确的按钮**。
|
||||
*/
|
||||
var webPage by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 一条回复里提到、或用户自己输的网页;空表示不展示那个界面。
|
||||
*
|
||||
* ★ 按项目约定:**列表这种要滚动的东西不用弹窗**,用独立全屏界面。
|
||||
* 一条回复里挂五六个链接是常事,弹窗装不下、用户还得在里面滚动 ——
|
||||
* 那还不如直接开一屏。
|
||||
*/
|
||||
var pickUrlFrom by mutableStateOf<List<FoundUrl>>(emptyList())
|
||||
private set
|
||||
|
||||
/**
|
||||
* 「网页」界面开着没有。
|
||||
*
|
||||
* ★ 为什么它和 [pickUrlFrom] 要分开:**没找到链接时也要能打开这个界面**
|
||||
* (用户可能想自己输网址)。只看 `pickUrlFrom.isNotEmpty()` 的话,
|
||||
* 一条链接都没有的回复点按钮就毫无反应。
|
||||
*/
|
||||
var urlPickerOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 打开「网页」界面。
|
||||
*
|
||||
* ★★ v2.0.39 改:**只有一个链接时也走这个界面**,不再直接跳转。
|
||||
* 上一版是"1 个就直接开",于是用户没有任何确认的机会;
|
||||
* 而且他看不到自己到底要打开哪个地址。
|
||||
* 现在统一先看一眼再决定。(用户拍板:"你要单独开个按钮")
|
||||
*/
|
||||
fun openUrlPicker(urls: List<FoundUrl>) {
|
||||
pickUrlFrom = urls
|
||||
urlPickerOpen = true
|
||||
}
|
||||
|
||||
/** 用户自己输了一个网址(或从列表里挑了一个) */
|
||||
fun openTypedUrl(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty()) return
|
||||
// 没写协议就补 https —— 用户不会每次都打 https://
|
||||
val url = if (t.startsWith("http://") || t.startsWith("https://")) t else "https://$t"
|
||||
urlPickerOpen = false
|
||||
pickUrlFrom = emptyList()
|
||||
webPage = url
|
||||
}
|
||||
|
||||
fun dismissUrlPicker() {
|
||||
pickUrlFrom = emptyList()
|
||||
urlPickerOpen = false
|
||||
}
|
||||
|
||||
/** 打开一个网页(全屏界面) */
|
||||
fun openWebPage(url: String) {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return
|
||||
pickUrlFrom = emptyList() // 进网页界面时把"选哪个"收掉
|
||||
webPage = u
|
||||
}
|
||||
|
||||
fun closeWebPage() {
|
||||
webPage = null
|
||||
}
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
init {
|
||||
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
|
||||
AiSurface.subscribe { kind ->
|
||||
viewModelScope.launch {
|
||||
when (kind) {
|
||||
"screen" -> aiScreen = AiSurface.screen
|
||||
"dialog" -> aiDialog = AiSurface.dialog
|
||||
"ended" -> {
|
||||
conversationEnded = true
|
||||
refreshEndedReason()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户关掉 AI 的界面 */
|
||||
fun closeAiScreen() {
|
||||
AiSurface.closeScreen()
|
||||
aiScreen = null
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。
|
||||
*
|
||||
* 两条路,按界面是不是"等待模式"分流:
|
||||
*
|
||||
* · **等待模式**(`show_ui` 传了 `wait=true`):
|
||||
* 这个值直接作为工具的返回值交给模型 —— 模型**在同一个回合里**就拿到了,
|
||||
* 可以接着干活。所以这里不用再排队(排了反而会让模型看到重复信息)。
|
||||
*
|
||||
* · **不等待模式**(默认):
|
||||
* 模型这一轮已经答完了,所以值先排队(`/api/ui-result`),
|
||||
* 等用户下次说话时和那句话一起交给模型。
|
||||
*
|
||||
* ★ 提示语要**如实**区分这两种情况:
|
||||
* 等待模式说"已提交"(模型确实马上会用);
|
||||
* 不等待模式说"已记下,下次对话会告诉 AI" ——
|
||||
* 写成"已发送"会让用户以为模型马上回话,然后干等。
|
||||
*/
|
||||
fun onAiScreenResult(value: String, waiting: Boolean = false) {
|
||||
AiSurface.screenResult(value)
|
||||
if (waiting) {
|
||||
showHint("已提交:$value")
|
||||
return
|
||||
}
|
||||
val conv = activeConversationId
|
||||
if (conv.isBlank()) {
|
||||
showHint("已选择:$value")
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching { client.pushUiResult(conv, value) }.getOrDefault(false)
|
||||
}
|
||||
showHint(
|
||||
if (ok) {
|
||||
"已记下你的选择,下次对话会告诉 AI"
|
||||
} else {
|
||||
"选择没能送出去(内核没响应),再点一次试试"
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户在 AI 的选择弹窗里点了 */
|
||||
fun answerAiDialog(values: List<String>, cancelled: Boolean = false) {
|
||||
AiSurface.answerDialog(values, cancelled)
|
||||
aiDialog = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 把当前对话的"已结束"状态读回来。
|
||||
*
|
||||
* ★ 切换对话、刷新之后都要重新读一次 —— 上面那个监听器只在 AI **当场**
|
||||
* 结束对话时触发;用户重启 App 打开一个早就结束的对话,走的是这条路。
|
||||
*/
|
||||
private fun refreshEndedReason() {
|
||||
val id = activeConversationId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
val meta = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversationMeta(id) }
|
||||
}.getOrNull()
|
||||
conversationEnded = meta?.ended == true
|
||||
endedReason = meta?.endedReason.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
// ★ 顺手读一下这次对话是不是被 AI 结束过 —— 只读 messages 是看不出来的
|
||||
// (ended 在会话对象上,不在消息里)。
|
||||
val meta = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversationMeta(id) }
|
||||
}.getOrNull()
|
||||
conversationEnded = meta?.ended == true
|
||||
endedReason = meta?.endedReason.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
fun newTopic() {
|
||||
viewModelScope.launch {
|
||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||
refresh()
|
||||
if (conv != null) {
|
||||
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
||||
conversationEnded = false
|
||||
endedReason = ""
|
||||
openConversation(conv.id)
|
||||
} else {
|
||||
messages.clear()
|
||||
activeConversationId = ""
|
||||
conversationEnded = false
|
||||
endedReason = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// ★ 对话被 AI 结束后就挡住 —— 界面上的输入框已经换成了横幅,
|
||||
// 但发送按钮/回车/历史入口都可能绕过界面判断,所以在**这里**再拦一道。
|
||||
if (conversationEnded) {
|
||||
showHint("这次对话已结束,请开一个新对话")
|
||||
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())
|
||||
}
|
||||
|
||||
/**
|
||||
* 从别处(现在只有"网页点选")发一条消息给 AI。
|
||||
*
|
||||
* ★ 走的是**和手打消息完全一样的那条路** —— 所以它会正常出现在对话里、
|
||||
* 正常存进历史、也能被"重新生成"。
|
||||
* 刻意不做成什么"隐藏上下文注入":用户得看得见自己发了什么,
|
||||
* 否则模型回一句"你选的这个……"而用户根本不知道自己选过什么。
|
||||
*/
|
||||
fun sendExternal(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty() || streaming) return
|
||||
if (conversationEnded) {
|
||||
showHint("这次对话已结束,请开一个新对话")
|
||||
return
|
||||
}
|
||||
screen = Screen.Chat
|
||||
runChat(t, 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,
|
||||
// ★ show_ui 的返回值里带 screenId —— 记下来,
|
||||
// 消息操作栏据此显示「界面」按钮(再打开用)。
|
||||
screenId = runCatching {
|
||||
org.json.JSONObject(event.result).optString("screenId")
|
||||
}.getOrDefault(""),
|
||||
)
|
||||
} 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))
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 界面能力(show_ui / ask_user / end_conversation)开关。
|
||||
*
|
||||
* ★ 必须写成**嵌套对象** `{"enabled": true}`,不能写成布尔 ——
|
||||
* 内核 `ui_tools_enabled()` 认的就是 dict 里的 enabled。
|
||||
* 而 `patchToJson` 会把 Map 递归转成 JSONObject(见那个函数的注释:
|
||||
* 不转的话会变成字符串 `"{enabled=true}"`,内核每次读配置都抛 TypeError)。
|
||||
* 所以这里传 Map 进去,让它走那条已经修好的转换路径。
|
||||
*/
|
||||
fun saveUiTools(enabled: Boolean) {
|
||||
saveSettings(mapOf("uiTools" to mapOf("enabled" to enabled)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把补丁 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,951 +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)
|
||||
|
||||
if (vm.conversationEnded) {
|
||||
/**
|
||||
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
* `Modifier.weight(1f)` 让它占掉原本给消息列表之外的全部剩余空间,
|
||||
* 横幅在**这块区域的中心**(也就是视觉上的屏幕中下部)。
|
||||
* 要的是"正中间",但顶部还有标题栏、下面还有输入法安全区,
|
||||
* 放在这块剩余区域的中心在观感上才是居中的。
|
||||
*
|
||||
* 输入框在此处**整个不渲染** —— 用户看到的就是"这儿没得输了",
|
||||
* 而不是一个点了没反应的框。
|
||||
*/
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
EndedBanner(
|
||||
reason = vm.endedReason,
|
||||
onNewConversation = { vm.newTopic() },
|
||||
)
|
||||
}
|
||||
} else {
|
||||
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))
|
||||
/**
|
||||
* ★★「打开网页」—— 用户明确要求"你要单独开个按钮"。
|
||||
*
|
||||
* 以前只有正文里那行蓝色下划线,**没有可发现性**:
|
||||
* 用户不知道它能点、也不知道点了会怎样。
|
||||
* 现在改成:回复里只要有 http(s) 链接,这里就出现一个按钮。
|
||||
*
|
||||
* · 只有 1 个链接 → 直接打开
|
||||
* · 多个链接 → 进「链接列表」全屏界面让用户挑
|
||||
* (按项目约定:列表这种要滚动的东西**不用弹窗**)
|
||||
*
|
||||
* ★ 链接是从 markdown 里现算的(`extractUrls`),不额外存状态 ——
|
||||
* 存了就要担心和 content 不同步(重新生成、编辑之后)。
|
||||
*
|
||||
* ★★ 按钮**无条件显示**(v2.0.39 改)。
|
||||
* 上一版是"这条回复里有链接才显示",于是:
|
||||
* · extractUrls 漏认写法时(裸 URL 就漏)按钮整个不见了
|
||||
* · 而且用户根本无从知道"这条能不能开网页"
|
||||
* 现在永远在,顺带还能自己在里面输网址 —— 它就是个浏览器入口。
|
||||
*/
|
||||
val urls = remember(msg.content) { extractUrls(msg.content) }
|
||||
RoundIconButton(
|
||||
Icons.Filled.Language,
|
||||
if (urls.isEmpty()) "打开网页" else "打开网页(${urls.size} 个链接)",
|
||||
tint = if (urls.isEmpty()) null else Doubao.Blue,
|
||||
) {
|
||||
vm.openUrlPicker(urls)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
|
||||
/**
|
||||
* ★★「界面」—— 再打开 AI 给你弹过的界面。
|
||||
*
|
||||
* 用户要求:"AI 写的界面可以再点开"。
|
||||
* 以前界面只活在内存里,一关就没了 —— 想再看只能让 AI 重做,
|
||||
* 而重做出来的内容**不一定一样**(模型有随机性)。
|
||||
*
|
||||
* 现在每次 show_ui 都存一份,这里只在这条回复**确实弹过界面**时出现。
|
||||
* 判断依据是工具痕迹里的 screenId(`show_ui` 的返回值带来的)。
|
||||
*/
|
||||
val screenIds = remember(msg.toolTrace) {
|
||||
msg.toolTrace.map { it.screenId }.filter { it.isNotBlank() }
|
||||
}
|
||||
if (screenIds.isNotEmpty()) {
|
||||
RoundIconButton(
|
||||
Icons.Filled.Dashboard,
|
||||
if (screenIds.size == 1) "再看一次这个界面" else "看这条弹过的 ${screenIds.size} 个界面",
|
||||
tint = Doubao.Blue,
|
||||
) {
|
||||
if (screenIds.size == 1) {
|
||||
vm.reopenAiScreen(screenIds.first())
|
||||
} else {
|
||||
vm.openAiScreenList()
|
||||
}
|
||||
}
|
||||
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(),
|
||||
)
|
||||
} }
|
||||
}
|
||||
}
|
||||
}
|
||||
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 |
@@ -1,278 +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))
|
||||
|
||||
|
||||
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
|
||||
#
|
||||
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
|
||||
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
|
||||
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
|
||||
# 硬塞进 markdown。
|
||||
#
|
||||
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
|
||||
# 所以措辞是"确实用文字说不清时才用"。
|
||||
UI_TOOLS_HINT = '\n'.join([
|
||||
'界面能力(用户已打开):',
|
||||
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||||
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||||
' 界面**支持 JavaScript**(canvas 画图、动态渲染都行)。',
|
||||
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
||||
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
||||
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
||||
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||||
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||||
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||||
' · wait=true = **等用户点一个回传按钮或关掉界面**(默认不限时,会一直等)。',
|
||||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。一般别传 timeout。',
|
||||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||
' 它会**一直等你选完**再继续(默认不限时),所以你不用在正文里再问一遍、',
|
||||
' 更不能自己替用户假设一个答案往下写。',
|
||||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||||
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||||
])
|
||||
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None,
|
||||
conversation_id: str = '', send_depth: int = 0) -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
settings 当前设置
|
||||
messages [{role, content}] 历史(不含 system)
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||||
send_depth `send_message` 嵌套了几层。AI 主动发消息会顺手跑一轮回复,
|
||||
那一轮就是 depth+1;超过上限时工具会被拒。
|
||||
**这是防无限套娃的关键**(见 app.py 的 /api/session-message)。
|
||||
"""
|
||||
# ★ 传 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 ''
|
||||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||||
#
|
||||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||||
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
|
||||
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
|
||||
# 按开关动态追加,两边永远一致。
|
||||
#
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
if tools_runtime.ui_tools_enabled(settings):
|
||||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||||
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})
|
||||
|
||||
# ★★★ AI 界面的**数据回流**在这里进上下文。
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 里可以调 `Doubao.sendToAi(值)`,
|
||||
# 安卓桥把它 POST 到 /api/ui-result 排队;这里取走并作为
|
||||
# **一条 system 消息**插在历史前面。
|
||||
#
|
||||
# ★ 为什么是 system 而不是 user:
|
||||
# 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,
|
||||
# 而且用户点"重新生成"时会和真正那条用户消息混在一起。
|
||||
# system 的语义就是"背景信息",正合适。
|
||||
#
|
||||
# ★ 为什么要**取走**:不取走的话这轮用、下轮还用,
|
||||
# 模型会反复提同一件事,用户会以为它卡住了。
|
||||
#
|
||||
# ★ 为什么放在 messages **之前**:它是"用户接下来这句话的前提",
|
||||
# 要让模型先看到"用户在界面上选了什么",再读用户那句话。
|
||||
ui_results = store.take_pending_ui(conversation_id) if conversation_id else []
|
||||
if ui_results:
|
||||
lines = '\n'.join(f'- {v}' for v in ui_results)
|
||||
convo.append({
|
||||
'role': 'system',
|
||||
'content': (
|
||||
'用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):\n'
|
||||
f'{lines}\n'
|
||||
'请结合这些信息回答用户接下来的话;如果用户还没说话,就针对这些选择给出回应。'
|
||||
),
|
||||
})
|
||||
# 也让界面知道模型收到了 —— 前端可以据此显示"AI 已收到你的选择"
|
||||
emit({'type': 'ui_results', 'count': len(ui_results)})
|
||||
|
||||
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')})
|
||||
# ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话",
|
||||
# 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local,
|
||||
# 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。
|
||||
tools_runtime.push_context(
|
||||
conversationId=conversation_id,
|
||||
agentId=(agent or {}).get('id') or '',
|
||||
toolName=tc.get('name') or '',
|
||||
# ★★ 防无限套娃:send_message 触发的回复里再发消息,深度 +1。
|
||||
# 这个值一路传到(Kotlin 桥 → 内核 /api/session-message),
|
||||
# 超过 SESSION_MSG_MAX_DEPTH 就被拒。
|
||||
# **不传的话**:模型发一条 → 那轮回复里再发 → 无限套娃,
|
||||
# 一个下午能把 API 额度烧光,用户看到满屏没发过的消息。
|
||||
sendDepth=send_depth,
|
||||
)
|
||||
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}'}
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
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,277 +0,0 @@
|
||||
"""
|
||||
常量表:提供商预设、默认设置、内置智能体。
|
||||
|
||||
这些值必须和 Node 版 server/src/config.mjs、server/src/agents.mjs 逐字段一致,
|
||||
否则 Lynx 前端读到的设置会出现"字段名对但默认值不同"的细微差异。
|
||||
"""
|
||||
|
||||
DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||
[
|
||||
'你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。',
|
||||
'',
|
||||
'回答要求:',
|
||||
'1. 用简体中文回答,除非用户要求其他语言。',
|
||||
'2. 先给结论,再给必要的解释,避免空话和过度铺垫。',
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
'',
|
||||
'关于用户发来的文件(附件):',
|
||||
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
|
||||
' **那个路径是文件在手机上的真实落盘位置**,可以直接用 shell 或 python 工具打开它 ——',
|
||||
' 不要猜路径,也不要说"我拿不到文件"。',
|
||||
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
|
||||
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
|
||||
]
|
||||
)
|
||||
|
||||
# 提供商预设。
|
||||
#
|
||||
# 全都是 **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},
|
||||
# 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话
|
||||
# (show_ui / ask_user / end_conversation)。
|
||||
#
|
||||
# ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、
|
||||
# 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。
|
||||
'uiTools': {'enabled': False},
|
||||
# 语音(朗读 / 语音输入)。引擎默认 '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,972 +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 shutil
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
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 = {}
|
||||
# ★★ 显式的"清除"通路:值传 None 就是"我要把它清掉"。
|
||||
#
|
||||
# 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是
|
||||
# "前端草稿没初始化好,一次保存清空整份配置"),但代价是
|
||||
# **用户永远清不掉自定义 Base URL / 模型名** ——
|
||||
# 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
|
||||
# (这是我在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认,
|
||||
# 传空串怎么也改不掉。)
|
||||
#
|
||||
# 所以给一条**显式**的路:传 null。空串仍然= "没填、别动",
|
||||
# null = "确实要清掉"。两者语义不同,前端可以按需选。
|
||||
explicit_clear = {k for k, v in patch.items() if v is None}
|
||||
for key in explicit_clear:
|
||||
patch.pop(key, None)
|
||||
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||||
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||||
# 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}
|
||||
# 显式清除的落到默认值上(不是留着旧值,也不是变成空 —— 空会让
|
||||
# "用哪个 provider 的默认 baseUrl"这套逻辑失效)
|
||||
for key in explicit_clear:
|
||||
nxt[key] = DEFAULT_SETTINGS.get(key, '')
|
||||
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||||
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 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
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 弹过的界面(HTML)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 用户要求:"AI 写的界面可以再点开" —— 关掉之后(甚至重启 App 之后)
|
||||
# 还能把它调出来。所以每次 show_ui 都存一份。
|
||||
#
|
||||
# 存法:
|
||||
# <data>/screens/<id>.html 正文
|
||||
# <data>/screens/index.json 索引(列表页只读这个,不用把 HTML 全读一遍)
|
||||
#
|
||||
# ★ 为什么落盘而不是只留内存:
|
||||
# 用户关掉界面、过一会儿想起来"刚才那个再看一眼",内存里那份早没了。
|
||||
# 重启 App 更是全没了。
|
||||
#
|
||||
# ★ 为什么单独存文件而不是塞进 conversations.json:
|
||||
# 一个界面的 HTML 可能几十 KB,塞进会话文件会让那个文件越来越大、
|
||||
# 每次读写整个会话列表都变慢。分开存,列表页只读个小索引。
|
||||
SCREEN_INDEX = 'index.json'
|
||||
# 一个会话最多留多少个界面(多了列表没法看,磁盘也白占)
|
||||
SCREEN_KEEP_PER_CONV = 30
|
||||
|
||||
|
||||
def _screens_dir() -> str:
|
||||
d = paths.get().screens_dir
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _screen_index_path() -> str:
|
||||
return os.path.join(_screens_dir(), SCREEN_INDEX)
|
||||
|
||||
|
||||
def _load_screen_index() -> list:
|
||||
try:
|
||||
with open(_screen_index_path(), encoding='utf-8') as fh:
|
||||
data = json.load(fh)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception: # noqa: BLE001 - 没有/坏了都当空
|
||||
return []
|
||||
|
||||
|
||||
def _save_screen_index(items: list) -> None:
|
||||
try:
|
||||
with open(_screen_index_path(), 'w', encoding='utf-8') as fh:
|
||||
json.dump(items, fh, ensure_ascii=False, indent=2)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[screens] 写索引失败:{exc}', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def _screen_preview(html: str) -> str:
|
||||
"""从 HTML 里抠一小段纯文字做预览(去掉标签/脚本/样式)"""
|
||||
text = re.sub(r'<(script|style)[^>]*>.*?</\1>', ' ', html, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r'<[^>]+>', ' ', text)
|
||||
text = re.sub(r'\s+', ' ', text).strip()
|
||||
return text[:120]
|
||||
|
||||
|
||||
def save_screen(conv_id: str, html: str, title: str, full_html: bool) -> dict:
|
||||
"""存一个 AI 弹出来的界面,返回它的索引项。"""
|
||||
sid = 's_' + uuid.uuid4().hex[:12]
|
||||
try:
|
||||
with open(os.path.join(_screens_dir(), f'{sid}.html'), 'w', encoding='utf-8') as fh:
|
||||
fh.write(html)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[screens] 写 {sid}.html 失败:{exc}', file=sys.stderr, flush=True)
|
||||
return {}
|
||||
|
||||
item = {
|
||||
'id': sid,
|
||||
'conversationId': conv_id or '',
|
||||
'title': (title or '').strip() or 'AI 界面',
|
||||
'fullHtml': bool(full_html),
|
||||
'bytes': len(html),
|
||||
# 列表页拿它做一行预览 —— 不用把 HTML 读出来也能看出这是哪个界面
|
||||
'preview': _screen_preview(html),
|
||||
'at': now_iso(),
|
||||
}
|
||||
with _lock:
|
||||
items = _load_screen_index()
|
||||
items.insert(0, item)
|
||||
# 每个会话只留最近 N 个
|
||||
kept, per_conv = [], {}
|
||||
for it in items:
|
||||
cid = it.get('conversationId') or ''
|
||||
per_conv[cid] = per_conv.get(cid, 0) + 1
|
||||
if per_conv[cid] <= SCREEN_KEEP_PER_CONV:
|
||||
kept.append(it)
|
||||
else:
|
||||
# 超出的把正文删掉,别让磁盘一直涨
|
||||
try:
|
||||
os.remove(os.path.join(_screens_dir(), f"{it.get('id')}.html"))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_save_screen_index(kept)
|
||||
return item
|
||||
|
||||
|
||||
def list_screens(conv_id: str = '') -> list:
|
||||
"""列出界面(按时间倒序)。传 conv_id 就只看那个会话的。"""
|
||||
items = _load_screen_index()
|
||||
if conv_id:
|
||||
items = [it for it in items if (it.get('conversationId') or '') == conv_id]
|
||||
# 正文被清掉的(超上限)就别列出来了
|
||||
out = []
|
||||
for it in items:
|
||||
if os.path.isfile(os.path.join(_screens_dir(), f"{it.get('id')}.html")):
|
||||
out.append(it)
|
||||
return out
|
||||
|
||||
|
||||
def read_screen(screen_id: str):
|
||||
"""读一个界面的正文;不存在返回 None"""
|
||||
if not screen_id or '/' in screen_id or '\\' in screen_id or '..' in screen_id:
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(_screens_dir(), f'{screen_id}.html'), encoding='utf-8') as fh:
|
||||
return fh.read()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def delete_screen(screen_id: str) -> bool:
|
||||
if not screen_id:
|
||||
return False
|
||||
with _lock:
|
||||
items = _load_screen_index()
|
||||
kept = [it for it in items if it.get('id') != screen_id]
|
||||
if len(kept) == len(items):
|
||||
return False
|
||||
_save_screen_index(kept)
|
||||
try:
|
||||
os.remove(os.path.join(_screens_dir(), f'{screen_id}.html'))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 主动往会话里发消息(send_message 工具)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★★ 这个功能最危险的地方是**死循环**:
|
||||
# 模型发一条消息 → 内核顺手跑一轮回复 → 那一轮里模型又调 send_message
|
||||
# → 再跑一轮 → 无限套娃。一个下午能把 API 额度烧光,
|
||||
# 而且用户看到满屏自己没发过的消息。
|
||||
#
|
||||
# 所以除了工具侧和桥侧的深度检查,这里再做一道**每会话条数上限**:
|
||||
# 即使深度检查因为某个环节没传到而失效,条数上限也能兜住。
|
||||
#
|
||||
# ★ 计数**从会话历史里数**,不用内存计数器(第一版就是内存计数,两个毛病):
|
||||
# 1. 重启 App 就清零 —— 上限形同虚设,"每次重启又能发 20 条"
|
||||
# 2. 写失败时可能多计 —— 拒绝信息里的数字和实际条数对不上
|
||||
# 数历史没有这两个问题:它自洽、跨重启、和用户看到的东西一致。
|
||||
#
|
||||
# 靠消息上的 `aiSent` 标记区分"AI 主动发的"和"用户打的"。
|
||||
# 这个标记界面上不显示,也不给模型看,纯粹是内部记账。
|
||||
SESSION_MSG_MAX = 20
|
||||
|
||||
|
||||
def session_message_count(conv_id: str) -> int:
|
||||
conv = get_conversation(conv_id) or {}
|
||||
return sum(1 for m in (conv.get('messages') or []) if m.get('aiSent'))
|
||||
|
||||
|
||||
def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
"""
|
||||
往会话里追加一条消息(AI 主动发的)。
|
||||
|
||||
★ 走 `update_conversation` 而不是自己写文件:会话的落盘、时间戳、
|
||||
标题自动生成那些逻辑都在那儿,这里再写一份就会不一致
|
||||
(这个仓库里"同一段逻辑两份、加功能只改一份"的坑踩过好几次)。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
raise KeyError(f'会话不存在:{conv_id}')
|
||||
msgs = list(item.get('messages') or [])
|
||||
msg = {
|
||||
'role': role if role in ('user', 'assistant') else 'user',
|
||||
'content': content,
|
||||
'at': now_iso(),
|
||||
# ★ 内部标记:这条是 AI 主动发的。
|
||||
# 用来算"这个会话还能主动发几条",界面上不显示、也不给模型看。
|
||||
'aiSent': True,
|
||||
}
|
||||
msgs.append(msg)
|
||||
update_conversation(conv_id, {'messages': msgs})
|
||||
return msg
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 笔记(notes 工具写的,用户要能查看)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 用户的原话:"notes 用户要能查看"。
|
||||
# 以前笔记只有 AI 能读写(走 notes 工具),用户在界面上看不到。
|
||||
#
|
||||
# ★ 目录是 `<数据目录>/notes`(`paths.get().notes_dir`)——
|
||||
# 以前 notes.py 自己算 `工具文件/../data/notes`,在安卓上落到
|
||||
# **App 外部私有目录**(用户翻不到、卸载还会被清掉)。
|
||||
# 那些老文件由 notes.py 里的 `_migrate_once` 自动搬过来。
|
||||
#
|
||||
# ★ 文件名格式:`20261015-151925-标题.md`。时间戳前缀让排序天然按时间倒序。
|
||||
NOTE_SUFFIX = '.md'
|
||||
|
||||
|
||||
def _notes_dir() -> str:
|
||||
d = paths.get().notes_dir
|
||||
os.makedirs(d, exist_ok=True)
|
||||
# ★ 顺手把老位置的笔记搬过来。
|
||||
#
|
||||
# 以前迁移只在 `notes` 工具被调用时才跑(notes.py 的 ensure_dir)。
|
||||
# 问题是:用户装了新版之后**先打开「笔记」页面**(而不是先让 AI 写笔记),
|
||||
# 那时迁移还没跑,他看到的是**空列表** —— 以为笔记全丢了。
|
||||
# 放在这里,任何一次读笔记都会先保证迁移过。
|
||||
_migrate_legacy_notes(d)
|
||||
return d
|
||||
|
||||
|
||||
# 老位置:工具文件旁边的 `../data/notes`。
|
||||
# 在安卓上那会落到 App 的**外部**私有目录
|
||||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)——
|
||||
# 用户用文件管理器翻不到(Android 11+ 直接隐藏),卸载还会一起删掉。
|
||||
def _legacy_notes_dirs() -> list:
|
||||
dirs = []
|
||||
try:
|
||||
# 工具目录的上一级 + /data/notes
|
||||
tools_dir = paths.get().tools_dir
|
||||
if tools_dir:
|
||||
dirs.append(os.path.join(os.path.dirname(tools_dir), 'data', 'notes'))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return [d for d in dirs if d and os.path.abspath(d) != os.path.abspath(paths.get().notes_dir)]
|
||||
|
||||
|
||||
def _migrate_legacy_notes(target: str) -> None:
|
||||
"""
|
||||
把老位置的笔记搬到新位置(只做一次)。
|
||||
|
||||
★ 为什么必须搬:用户在老版本里记的笔记是**真实数据** ——
|
||||
换了目录之后文件还在老地方躺着,但 list/read 都看不到,
|
||||
表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。
|
||||
"""
|
||||
marker = os.path.join(target, '.migrated')
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
moved = 0
|
||||
for legacy in _legacy_notes_dirs():
|
||||
if not os.path.isdir(legacy):
|
||||
continue
|
||||
try:
|
||||
names = os.listdir(legacy)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
for name in names:
|
||||
if not name.endswith(NOTE_SUFFIX):
|
||||
continue
|
||||
dst = os.path.join(target, name)
|
||||
if os.path.exists(dst):
|
||||
continue # 不覆盖同名的(新位置已有)
|
||||
src = os.path.join(legacy, name)
|
||||
try:
|
||||
shutil.move(src, dst)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
# 跨设备 move 可能失败,退回复制
|
||||
try:
|
||||
shutil.copy2(src, dst)
|
||||
os.remove(src)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
with open(marker, 'w', encoding='utf-8') as fh:
|
||||
fh.write('ok\n')
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if moved:
|
||||
print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def _note_path(name: str):
|
||||
"""把文件名解析成绝对路径;不合法(穿越/非 .md)返回 None"""
|
||||
if not name or not name.endswith(NOTE_SUFFIX):
|
||||
return None
|
||||
# ★ 防目录穿越:文件名必须是纯文件名,不能带路径分隔符
|
||||
if '/' in name or '\\' in name or '..' in name:
|
||||
return None
|
||||
return os.path.join(_notes_dir(), name)
|
||||
|
||||
|
||||
def _note_title(path: str, fallback: str) -> str:
|
||||
"""标题取正文第一行的 `# 标题`;读不到就用文件名兜底"""
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
first = fh.readline().strip().lstrip('#').strip()
|
||||
return first or fallback
|
||||
except Exception: # noqa: BLE001
|
||||
return fallback
|
||||
|
||||
|
||||
def _note_time(name: str) -> str:
|
||||
"""
|
||||
从文件名前缀 `20261015-151925` 解析出时间,转成 `2026-10-15T15:19:25`。
|
||||
|
||||
★ 解析不出来就返回空串(界面上不显示时间),**不要瞎猜** ——
|
||||
用户手改过文件名的情况是有的。
|
||||
"""
|
||||
m = re.match(r'^(\d{8})-(\d{6})-', name)
|
||||
if not m:
|
||||
return ''
|
||||
d, t = m.group(1), m.group(2)
|
||||
return f'{d[0:4]}-{d[4:6]}-{d[6:8]}T{t[0:2]}:{t[2:4]}:{t[4:6]}'
|
||||
|
||||
|
||||
def list_notes() -> list:
|
||||
"""列出所有笔记(按文件名倒序 = 按时间倒序)"""
|
||||
d = _notes_dir()
|
||||
try:
|
||||
names = sorted(os.listdir(d), reverse=True)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
out = []
|
||||
for name in names:
|
||||
if not name.endswith(NOTE_SUFFIX):
|
||||
continue
|
||||
full = os.path.join(d, name)
|
||||
try:
|
||||
size = os.path.getsize(full)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
# 预览 = 去掉标题行之后的头一段
|
||||
preview = ''
|
||||
try:
|
||||
with open(full, encoding='utf-8') as fh:
|
||||
body = fh.read()
|
||||
lines = [ln.strip() for ln in body.splitlines()]
|
||||
body_lines = [ln for ln in lines[1:] if ln]
|
||||
preview = ' '.join(body_lines)[:100]
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
out.append({
|
||||
'file': name,
|
||||
'title': _note_title(full, name),
|
||||
'bytes': size,
|
||||
'at': _note_time(name),
|
||||
'preview': preview,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def read_note(name: str):
|
||||
"""读一条笔记;不存在返回 None"""
|
||||
path = _note_path(name)
|
||||
if not path or not os.path.isfile(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
text = fh.read()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return {
|
||||
'file': name,
|
||||
'title': _note_title(path, name),
|
||||
'at': _note_time(name),
|
||||
'content': text,
|
||||
'bytes': len(text.encode('utf-8')),
|
||||
}
|
||||
|
||||
|
||||
def delete_note(name: str) -> bool:
|
||||
path = _note_path(name)
|
||||
if not path or not os.path.isfile(path):
|
||||
return False
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def get_conversation(conv_id: str):
|
||||
for conv in _load_conversations()['conversations']:
|
||||
if conv.get('id') == conv_id:
|
||||
return conv
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AI 界面的数据回流
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# AI 用 show_ui 弹的 HTML 界面里可以调 `Doubao.sendToAi(值)`,
|
||||
# 那个值先落到这里排队,下一轮对话开始时被取走、当作上下文交给模型。
|
||||
#
|
||||
# ★ 为什么单独存一份、而不是直接写进会话的消息列表:
|
||||
# 写进消息列表的话它会**变成一条 user 消息** —— 用户会看到一条
|
||||
# 自己没打过的消息,而且它会被当成"用户说的话"进历史。
|
||||
# 语义上它更像**附件/上下文**,不是用户的一句话。
|
||||
# 所以单独排队,由 agent_loop 拼进这一轮的上下文里。
|
||||
#
|
||||
# ★ 为什么不落盘:这是**一次性的上下文**,跨重启没有意义
|
||||
# (用户重启 App 之后那个界面早就关了,界面的选择也就失效了)。
|
||||
# 放内存里,进程重启自然清空,正合适。
|
||||
_pending_ui: dict = {}
|
||||
_pending_ui_lock = threading.Lock()
|
||||
|
||||
# 每个会话最多排多少条 —— 用户在界面上乱点不能把内存堆满
|
||||
PENDING_UI_MAX = 20
|
||||
# 单条最长多少字符 —— 界面可能回传一大段文本
|
||||
PENDING_UI_ITEM_MAX = 4000
|
||||
|
||||
|
||||
def add_pending_ui(conv_id: str, value: str) -> int:
|
||||
"""把界面上回传的一个值排进队。返回队里现在有几条。"""
|
||||
text = (value or '').strip()[:PENDING_UI_ITEM_MAX]
|
||||
if not conv_id or not text:
|
||||
return len(_pending_ui.get(conv_id) or [])
|
||||
with _pending_ui_lock:
|
||||
box = _pending_ui.setdefault(conv_id, [])
|
||||
box.append(text)
|
||||
# 超了就丢**最旧的**:用户最新点的那次最相关
|
||||
while len(box) > PENDING_UI_MAX:
|
||||
box.pop(0)
|
||||
return len(box)
|
||||
|
||||
|
||||
def peek_pending_ui(conv_id: str) -> list:
|
||||
"""看一眼(不取走)—— 给调试用的 GET 接口"""
|
||||
with _pending_ui_lock:
|
||||
return list(_pending_ui.get(conv_id) or [])
|
||||
|
||||
|
||||
def take_pending_ui(conv_id: str) -> list:
|
||||
"""
|
||||
取走并清空。
|
||||
|
||||
★ 必须"取走":不取走的话每轮对话都会把同一条又带上,
|
||||
用户会看到模型反复提同一件事。
|
||||
"""
|
||||
with _pending_ui_lock:
|
||||
return list(_pending_ui.pop(conv_id, []) or [])
|
||||
|
||||
|
||||
def clear_pending_ui(conv_id: str) -> None:
|
||||
with _pending_ui_lock:
|
||||
_pending_ui.pop(conv_id, 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();
|
||||
});
|
||||
}
|
||||
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/
|
||||
499
豆鲍/AGENTS.md
Normal file
499
豆鲍/AGENTS.md
Normal file
@@ -0,0 +1,499 @@
|
||||
# 项目约定
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
|
||||
---
|
||||
|
||||
# 代码托管
|
||||
|
||||
## 两个 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` 枚举参数。
|
||||
- **常驻角色工具是动态的**,不在 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。
|
||||
- **旧都市的地图相邻关系(用户要求)**:老街 `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` 不能再移一次)。
|
||||
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 = 245
|
||||
versionName = "2.0.45"
|
||||
versionCode = 351
|
||||
versionName = "2.0.151"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -57,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">
|
||||
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.
@@ -20,6 +20,7 @@ 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
|
||||
@@ -419,7 +420,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, 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")
|
||||
@@ -442,7 +443,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, 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")
|
||||
@@ -837,7 +838,10 @@ class NativeBridge(private val activity: Activity) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||
latch.await(
|
||||
AppTimeouts.seconds("filePicker", PICK_TIMEOUT_S.toDouble()).toLong(),
|
||||
TimeUnit.SECONDS,
|
||||
)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
@@ -880,8 +884,25 @@ class NativeBridge(private val activity: Activity) {
|
||||
|
||||
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")
|
||||
@@ -70,11 +70,15 @@ object PhoneOps {
|
||||
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
|
||||
if (nm.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
// ★ 不要"渠道已存在就 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 = "豆包主动发出来的提醒"
|
||||
description = "小人间主动发出来的提醒"
|
||||
enableVibration(true)
|
||||
}
|
||||
nm.createNotificationChannel(ch)
|
||||
@@ -95,7 +99,7 @@ object PhoneOps {
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
ensureChannel(ctx)
|
||||
|
||||
val t = title.trim().ifBlank { "豆包" }
|
||||
val t = title.trim().ifBlank { "小人间" }
|
||||
val body = text.trim()
|
||||
|
||||
// 点通知打开 App
|
||||
@@ -114,7 +118,10 @@ object PhoneOps {
|
||||
android.app.Notification.Builder(ctx)
|
||||
}
|
||||
builder
|
||||
.setSmallIcon(ctx.applicationInfo.icon) // ★ 不给 smallIcon 通知**不会显示**
|
||||
// ★ v3.17 起不能再用 applicationInfo.icon:自适应图标是 108dp 的
|
||||
// 图层组合,setSmallIcon 拿到它有些机型会渲成空白。小图标要单色剪影,
|
||||
// 所以单独做了个 ic_notify(纯白房子,系统自己染色)。
|
||||
.setSmallIcon(R.drawable.ic_notify) // ★ 不给 smallIcon 通知**不会显示**
|
||||
.setContentTitle(t)
|
||||
.setContentText(body)
|
||||
.setAutoCancel(autoCancel)
|
||||
@@ -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
2913
豆鲍/android/app/src/main/java/com/doubao/lynxclone/data/Models.kt
Normal file
2913
豆鲍/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)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
@@ -859,7 +859,7 @@ object TermuxInstaller {
|
||||
rc.parentFile?.mkdirs()
|
||||
rc.writeText(
|
||||
"""
|
||||
# 由豆包 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||
# 由小人间 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||
export PREFIX="$prefix"
|
||||
export HOME="$home"
|
||||
export TMPDIR="$prefix/tmp"
|
||||
@@ -871,7 +871,7 @@ object TermuxInstaller {
|
||||
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"
|
||||
echo "小人间内置 Termux —— 试试 pkg install python"
|
||||
""".trimIndent() + "\n",
|
||||
Charsets.UTF_8,
|
||||
)
|
||||
@@ -1087,7 +1087,7 @@ object TermuxInstaller {
|
||||
conf.parentFile?.mkdirs()
|
||||
conf.writeText(
|
||||
"""
|
||||
// 由豆包 App 生成 —— 把 apt 的目录全部指到我们自己的 prefix。
|
||||
// 由小人间 App 生成 —— 把 apt 的目录全部指到我们自己的 prefix。
|
||||
//
|
||||
// 不写这份文件的话,apt 会去 /data/data/com.termux/... (真 Termux 的包名)
|
||||
// 找 apt.conf.d,读不到就报 "Unable to determine a suitable packaging
|
||||
@@ -171,7 +171,7 @@ object TermuxMirror {
|
||||
}
|
||||
|
||||
val header = listOf(
|
||||
"# 由豆包 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 由小人间 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 换源:内置终端右上角「源」按钮;也可以手动改这个文件",
|
||||
)
|
||||
val lines = wanted.map { "deb ${mirror.host}/${it.path} ${it.components}" }
|
||||
@@ -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>,
|
||||
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 -> "自动"
|
||||
}
|
||||
3994
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt
Normal file
3994
豆鲍/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,236 @@
|
||||
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.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.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
|
||||
|
||||
/**
|
||||
* [容器编辑](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
|
||||
|
||||
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(),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 世界包选择胶囊 */
|
||||
@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),
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
@@ -210,6 +230,7 @@ fun TypingDots(color: Color = Doubao.TextTertiary, dot: Dp = 6.dp) {
|
||||
/* ------------------------------ 小部件 ------------------------------ */
|
||||
|
||||
/** 顶部/输入框上方的白底描边胶囊按钮(快捷入口、功能键) */
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun DoubaoPill(
|
||||
text: String? = null,
|
||||
@@ -217,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) {
|
||||
@@ -277,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 ?: "") }
|
||||
}
|
||||
}
|
||||
@@ -76,10 +76,24 @@ fun MarkdownText(
|
||||
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) {
|
||||
@@ -116,7 +130,7 @@ fun MarkdownText(
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color.copy(alpha = 0.85f),
|
||||
@@ -127,7 +141,7 @@ fun MarkdownText(
|
||||
|
||||
is MdBlock.Heading -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
@@ -143,7 +157,7 @@ fun MarkdownText(
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
@@ -159,7 +173,7 @@ fun MarkdownText(
|
||||
modifier = Modifier.width(22.dp),
|
||||
)
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
@@ -176,7 +190,7 @@ fun MarkdownText(
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = if (block.checked) color.copy(alpha = 0.6f) else color,
|
||||
@@ -191,6 +205,7 @@ fun MarkdownText(
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
@@ -203,7 +218,7 @@ fun MarkdownText(
|
||||
|
||||
is MdBlock.Paragraph -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
@@ -247,6 +262,7 @@ private fun MarkdownTable(
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
stageStyle: SpanStyle? = null,
|
||||
) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
@@ -299,6 +315,7 @@ private fun MarkdownTable(
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
bold = true,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -315,6 +332,7 @@ private fun MarkdownTable(
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -333,6 +351,7 @@ private fun TableCell(
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
bold: Boolean = false,
|
||||
stageStyle: SpanStyle? = null,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
@@ -341,7 +360,7 @@ private fun TableCell(
|
||||
) {
|
||||
Text(
|
||||
// 单元格里也走行内解析 —— `**合计**`、`` `code` ``、链接都要生效
|
||||
inline(text, linkColor),
|
||||
inline(text, linkColor, stageStyle),
|
||||
fontSize = (fontSize - 2).sp,
|
||||
lineHeight = (lineHeight - 4).coerceAtLeast(fontSize).sp,
|
||||
fontWeight = if (bold) FontWeight.SemiBold else null,
|
||||
@@ -738,11 +757,25 @@ private val RE_BARE_URL =
|
||||
*/
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
@Composable
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
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] == '`' -> {
|
||||
@@ -849,4 +882,31 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 找一处「旁白」的收尾下标:(……)(……)【……】[……]。
|
||||
*
|
||||
* 返回 -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,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("取消") } },
|
||||
)
|
||||
}
|
||||
@@ -21,7 +21,11 @@ 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
|
||||
@@ -43,8 +47,11 @@ import androidx.compose.ui.unit.sp
|
||||
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
|
||||
*
|
||||
* 现在抽屉第一层只留天天用的(新话题 / 智能体 / 笔记 / 模型),
|
||||
* 其余收进这里。
|
||||
* ★★ 后来又收了一次(用户第二次说"太挤了"、"把别的放更多里"):
|
||||
* 抽屉第一层现在只剩**四件天天用的**:新话题 / 智能体 / 记忆 / 更多功能。
|
||||
* 笔记、模型、新建群聊都挪进来了 ——
|
||||
* 「模型」虽然也常用,但它是个**配置**,配好基本不动;
|
||||
* 抽屉里腾出来的位置留给对话列表更值。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
@@ -55,9 +62,14 @@ import androidx.compose.ui.unit.sp
|
||||
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() }
|
||||
@@ -74,6 +86,20 @@ fun MoreSheetScreen(
|
||||
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,
|
||||
@@ -81,6 +107,25 @@ fun MoreSheetScreen(
|
||||
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,
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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,349 @@
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
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.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.ItemDef
|
||||
import com.doubao.lynxclone.data.PlaceDef
|
||||
import com.doubao.lynxclone.data.StatDef
|
||||
import com.doubao.lynxclone.data.StatusDef
|
||||
|
||||
/**
|
||||
* 世界包的**定义编辑区**(v3.0 补遗):
|
||||
* 手机端也能改数值 / 状态 / 物品 / 地点定义,不用再去电脑上改 JSON。
|
||||
*
|
||||
* ★ 交互取舍:手机上做不了电脑那种表格,所以用"一行 + 几个输入框"的
|
||||
* 紧凑布局;类型(kind / 主动被动目标)做成**点一下循环切换**的按钮,
|
||||
* 比下拉菜单少一次点击。
|
||||
* ★ 复杂的嵌套结构(数值的区间文案 `ranges`、物品的 hint)**不在这里编辑**,
|
||||
* 保存时原样带回(`worldPackInfoJson` 里保留),不会被静默抹掉。
|
||||
*/
|
||||
|
||||
/** 一行里的紧凑输入框 */
|
||||
@Composable
|
||||
private fun CompactField(
|
||||
value: String,
|
||||
placeholder: String,
|
||||
modifier: Modifier = Modifier,
|
||||
onValue: (String) -> Unit,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onValue,
|
||||
placeholder = { Text(placeholder, fontSize = 11.sp) },
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/** 点一下循环切换的按钮(类型 / 共享 / 无限 这类布尔或枚举字段) */
|
||||
@Composable
|
||||
private fun CycleAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.padding(vertical = 8.dp)
|
||||
.padding(horizontal = 6.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
private fun <T> List<T>.replaceAt(i: Int, item: T): List<T> = toMutableList().also { it[i] = item }
|
||||
private fun <T> List<T>.removeAt2(i: Int): List<T> = toMutableList().also { it.removeAt(i) }
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 数值 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
fun EditableStatsSection(stats: List<StatDef>, onStats: (List<StatDef>) -> Unit) {
|
||||
SectionLabel("数值定义")
|
||||
Hint("共享 = 整个世界共用一份(声望);自身 = 每个角色各算一份(好感度)。" +
|
||||
"初始值不填 = 按 min 起步(测试世界的「气血」填 100,配合「气血为 0 = 死亡」)。区间文案在电脑端改。")
|
||||
if (stats.isEmpty()) Hint("没有数值。数值是这个世界的规则,比如好感度、声望。")
|
||||
for ((i, s) in stats.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(s.name, "名称", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
// ★ v3.30:稳定 id(空 = 用名字当 id);脚本/接口按 id 或名字引用
|
||||
CompactField(s.id, "id(空=名字)", Modifier.weight(0.8f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (s.shared) "世界" else "自身") {
|
||||
onStats(stats.replaceAt(i, s.copy(shared = !s.shared)))
|
||||
}
|
||||
CycleAction("删除") { onStats(stats.removeAt2(i)) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(fmt(s.min), "min", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(min = numOr(v, s.min))))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(fmt(s.max), "max", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(max = numOr(v, s.max))))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(s.script, "脚本文件名", Modifier.weight(1.2f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(script = v.trim())))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// ★ v3.20:初始值(可选,空 = min)—— 气血这类要「100 起步」的数值靠它
|
||||
CompactField(s.initial?.let { fmt(it) } ?: "", "初始值(空 = min)", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(
|
||||
initial = if (v.isBlank()) null else numOr(v, s.initial ?: s.min))))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一条数值") {
|
||||
onStats(stats + StatDef(name = "新数值", min = 0.0, max = 100.0, shared = false))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 状态 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
fun EditableStatusesSection(statuses: List<StatusDef>, onStatuses: (List<StatusDef>) -> Unit) {
|
||||
SectionLabel("状态定义")
|
||||
Hint("限时 timed:每轮 -1、归零消失;常驻 persistent:不会自己过期。")
|
||||
if (statuses.isEmpty()) Hint("没有状态。状态是挂在这个角色身上的临时状况,比如中毒、庇佑。")
|
||||
for ((i, s) in statuses.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(s.name, "名称", Modifier.weight(1f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
// ★ v3.30:稳定 id(空 = 用名字当 id)
|
||||
CompactField(s.id, "id(空=名字)", Modifier.weight(0.8f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (s.kind == "persistent") "常驻" else "限时") {
|
||||
onStatuses(
|
||||
statuses.replaceAt(
|
||||
i, s.copy(kind = if (s.kind == "persistent") "timed" else "persistent"),
|
||||
),
|
||||
)
|
||||
}
|
||||
CycleAction("删除") { onStatuses(statuses.removeAt2(i)) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(s.turns.toString(), "轮数", Modifier.weight(1f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(turns = numOr(v, s.turns.toDouble()).toInt())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(s.maxStack.toString(), "最多几层", Modifier.weight(1f)) { v ->
|
||||
onStatuses(
|
||||
statuses.replaceAt(i, s.copy(maxStack = numOr(v, s.maxStack.toDouble()).toInt())),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(s.script, "脚本文件名", Modifier.weight(1.2f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(script = v.trim())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一条状态") {
|
||||
onStatuses(statuses + StatusDef(name = "新状态", kind = "timed", turns = 3, maxStack = 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 物品 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private val ITEM_KINDS = listOf("plain", "passive", "active", "target")
|
||||
private fun itemKindLabel(kind: String): String = when (kind) {
|
||||
"active" -> "主动"
|
||||
"passive" -> "被动"
|
||||
"target" -> "目标"
|
||||
else -> "无脚本"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ItemsSection(
|
||||
items: List<ItemDef>,
|
||||
onItems: (List<ItemDef>) -> Unit,
|
||||
scriptNames: List<String>,
|
||||
) {
|
||||
SectionLabel("物品定义")
|
||||
Hint("主动=每轮生效;被动=使用触发;目标=对别人用;无脚本=只能被查询/出旁白。成员第一次进这一局按「初始数量」发放。")
|
||||
if (items.isEmpty()) Hint("没有物品。物品四件套:主动 / 被动 / 目标 / 无脚本。")
|
||||
for ((i, it) in items.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(it.id, "id(英文)", Modifier.weight(1f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(it.name, "名字", Modifier.weight(1f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(it.category, "分类", Modifier.weight(0.8f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(category = v)))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CycleAction(itemKindLabel(it.kind)) {
|
||||
val next = ITEM_KINDS[(ITEM_KINDS.indexOf(it.kind) + 1) % ITEM_KINDS.size]
|
||||
onItems(items.replaceAt(i, it.copy(kind = next)))
|
||||
}
|
||||
CompactField(it.initial.toString(), "初始数量", Modifier.weight(0.8f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(initial = numOr(v, it.initial.toDouble()).toInt())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (it.unlimited) "无限 ∞" else "有限") {
|
||||
onItems(items.replaceAt(i, it.copy(unlimited = !it.unlimited)))
|
||||
}
|
||||
CycleAction("删除") { onItems(items.removeAt2(i)) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(it.script, "脚本文件名", Modifier.weight(1f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(script = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(it.desc, "介绍(会注入给 AI)", Modifier.weight(2f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(desc = v)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一个物品") {
|
||||
onItems(items + ItemDef(id = "item_${items.size + 1}", name = "新物品", category = "其他"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 地点 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
fun PlacesSection(
|
||||
places: List<PlaceDef>,
|
||||
onPlaces: (List<PlaceDef>) -> Unit,
|
||||
onPickBackground: (String) -> Unit,
|
||||
onClearBackground: (String) -> Unit,
|
||||
) {
|
||||
SectionLabel("地点定义")
|
||||
Hint("默认地点 = 新成员进来的地方;相邻地点限制移动(留空 = 随便走);聊天按地点分开。")
|
||||
if (places.isEmpty()) Hint("还没有地点。定义之后这一局就有地图了。")
|
||||
for ((i, p) in places.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(p.id, "id(英文)", Modifier.weight(1f)) { v ->
|
||||
onPlaces(places.replaceAt(i, p.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(p.name, "地点名", Modifier.weight(1f)) { v ->
|
||||
onPlaces(places.replaceAt(i, p.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(p.category, "分类", Modifier.weight(0.8f)) { v ->
|
||||
onPlaces(places.replaceAt(i, p.copy(category = v)))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CycleAction(if (p.isDefault) "默认地点" else "非默认") {
|
||||
onPlaces(places.replaceAt(i, p.copy(isDefault = !p.isDefault)))
|
||||
}
|
||||
CycleAction(if (p.hidden) "隐藏" else "显示") {
|
||||
onPlaces(places.replaceAt(i, p.copy(hidden = !p.hidden)))
|
||||
}
|
||||
CycleAction("删除") { onPlaces(places.removeAt2(i)) }
|
||||
}
|
||||
CompactField(
|
||||
p.desc,
|
||||
"描述(会注入给 AI,AI 才知道这地方长什么样)",
|
||||
Modifier.fillMaxWidth(),
|
||||
) { v -> onPlaces(places.replaceAt(i, p.copy(desc = v))) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(p.exits.joinToString(","), "相邻地点 id(逗号分隔)", Modifier.weight(1.4f)) { v ->
|
||||
onPlaces(
|
||||
places.replaceAt(
|
||||
i,
|
||||
p.copy(
|
||||
exits = v.split(',', ',', ' ').map { it.trim() }.filter { it.isNotEmpty() },
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (p.background.isBlank()) "背景:无" else "背景:已设置") {
|
||||
if (p.background.isBlank()) onPickBackground(p.id) else onClearBackground(p.id)
|
||||
}
|
||||
if (p.background.isBlank()) {
|
||||
CycleAction("上传背景") { onPickBackground(p.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一个地点") {
|
||||
onPlaces(places + PlaceDef(id = "place_${places.size + 1}", name = "新地点"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 小工具 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun numOr(s: String, fallback: Double): Double =
|
||||
s.trim().toDoubleOrNull() ?: fallback
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toInt().toDouble()) v.toInt().toString() else v.toString()
|
||||
|
||||
/** 这个包里的脚本文件名(物品/状态/数值引用时给个提示) */
|
||||
@Composable
|
||||
private fun ScriptHint(scriptNames: List<String>) {
|
||||
if (scriptNames.isEmpty()) return
|
||||
Text(
|
||||
"可用脚本:" + scriptNames.joinToString("、"),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** 只是防止 Kotlin 报未使用(ScriptHint 留给后续在编辑行里用) */
|
||||
@Suppress("unused")
|
||||
private fun keepScriptHint(scriptNames: List<String>) = scriptNames
|
||||
@@ -0,0 +1,495 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
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.horizontalScroll
|
||||
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.BasicTextField
|
||||
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.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
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.AgentImage
|
||||
import com.doubao.lynxclone.data.StatDef
|
||||
import com.doubao.lynxclone.data.StatusDef
|
||||
|
||||
/**
|
||||
* [世界包编辑](v3.0:世界观 + 规则包合并)—— 全屏。
|
||||
*
|
||||
* ## 为什么合并成一个界面
|
||||
*
|
||||
* v2 里"一个世界"是两样东西:世界观(设定 + 图片)在资源页里点开改,
|
||||
* 规则包(数值/状态/脚本)在另一个全屏页里改。用户要配一个世界得来回跳两页,
|
||||
* 而且**忘了挂上规则包**是最常见的坑(挂了才有数值,不挂就没有)。
|
||||
*
|
||||
* v3 起它们就是一个包:设定、定义、脚本在同一个界面里,四个分区切换。
|
||||
* 物品 / 地图分区等 P3 / P4 落地后再加。
|
||||
*
|
||||
* ## 脚本框的形状(照抄节点代码组件的做法)
|
||||
*
|
||||
* 1. **不软换行** —— `else:` 折成两行、缩进全乱,而 Python 的缩进就是语法。
|
||||
* 2. **有高度上限** —— 只写 `heightIn(min=...)` 的话脚本一长框就长到屏幕外。
|
||||
*
|
||||
* ## 定义表现在也能编辑了(v3.0 补遗)
|
||||
*
|
||||
* 数值 / 状态 / 物品 / 地点都能在手机上改(每行几个输入框,紧凑布局)。
|
||||
* 只有区间文案(ranges)这种嵌套结构仍要在电脑端改 —— 保存时原样带回。
|
||||
*/
|
||||
@Composable
|
||||
fun WorldPackEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val pack = vm.editingWorldPack
|
||||
if (pack == null) {
|
||||
FullScreen(title = "世界包编辑", onBack = onBack) { Hint("正在读……") }
|
||||
return
|
||||
}
|
||||
|
||||
var tab by remember(pack.id) { mutableStateOf(0) }
|
||||
var name by remember(pack.id) { mutableStateOf(pack.name) }
|
||||
var setting by remember(pack.id) { mutableStateOf(pack.setting) }
|
||||
var stats by remember(pack.id) { mutableStateOf(pack.stats) }
|
||||
var statuses by remember(pack.id) { mutableStateOf(pack.statuses) }
|
||||
var items by remember(pack.id) { mutableStateOf(pack.items) }
|
||||
var places by remember(pack.id) { mutableStateOf(pack.places) }
|
||||
var scripts by remember(pack.id) { mutableStateOf(pack.scripts) }
|
||||
var editing by remember(pack.id) { mutableStateOf("") }
|
||||
var newScript by remember(pack.id) { mutableStateOf("") }
|
||||
var draft by remember(pack.id) { mutableStateOf("") }
|
||||
var worldImage by remember(pack.id) { mutableStateOf(pack.image) }
|
||||
|
||||
// 外观图是**即时上传**的(选完就落到世界包目录里),上传完 state 会变 ——
|
||||
// 跟着刷新预览,不然用户选完了预览还是空的("上传失败"错觉)。
|
||||
vm.state.worldviews.firstOrNull { it.id == pack.id }?.let {
|
||||
if (it.image != worldImage) worldImage = it.image
|
||||
}
|
||||
|
||||
// ★ 上传**地点背景**后内核会把落盘路径写回 info.places[].background ——
|
||||
// 用内核版本补到草稿里(只补"本地空、内核有"的,别覆盖用户正在改的字段)。
|
||||
androidx.compose.runtime.LaunchedEffect(pack.places) {
|
||||
if (pack.places.isEmpty()) return@LaunchedEffect
|
||||
places = places.map { local ->
|
||||
val fresh = pack.places.firstOrNull { it.id == local.id } ?: return@map local
|
||||
if (local.background.isBlank() && fresh.background.isNotBlank()) {
|
||||
local.copy(background = fresh.background)
|
||||
} else {
|
||||
local
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val ctx = LocalContext.current
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
// 和智能体编辑页**同一份实现** —— 大图/压缩/GIF/SAF 没扩展名这些坑
|
||||
// 两边一模一样,抄两份迟早只修一份
|
||||
vm.uploadWorldviewAssetFrom(ctx.applicationContext, pack.id, slot, uri)
|
||||
}
|
||||
// 地点背景:选完直接上传到那个地点(不用等"保存")
|
||||
var pendingPlace by remember { mutableStateOf("") }
|
||||
val pickPlaceBg = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val pid = pendingPlace
|
||||
pendingPlace = ""
|
||||
if (uri == null || pid.isBlank()) return@rememberLauncherForActivityResult
|
||||
vm.uploadPlaceBackgroundFrom(ctx.applicationContext, pack.id, pid, uri)
|
||||
}
|
||||
|
||||
val tabs = listOf("设定", "数值", "状态", "物品", "地点", "脚本")
|
||||
|
||||
FullScreen(
|
||||
title = "世界包编辑",
|
||||
subtitle = "${name.ifBlank { "未命名" }} · ${stats.size} 数值 · ${statuses.size} 状态 · " +
|
||||
"${items.size} 物品 · ${places.size} 地点 · ${scripts.size} 脚本",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("保存") {
|
||||
vm.saveWorldPack(name, setting, stats, statuses, items, places, scripts)
|
||||
}
|
||||
},
|
||||
) {
|
||||
// ---- 分区 tab(横向滚动:6 个在小屏上一行放不下)----
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
for ((i, label) in tabs.withIndex()) {
|
||||
val on = i == tab
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) androidx.compose.ui.graphics.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),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
when (tab) {
|
||||
0 -> SettingSection(
|
||||
name = name, onName = { name = it },
|
||||
setting = setting, onSetting = { setting = it },
|
||||
image = worldImage,
|
||||
onPick = { slot -> pendingSlot = slot; pickImage.launch(arrayOf("image/*")) },
|
||||
onClear = { slot -> vm.uploadWorldviewAsset(pack.id, slot, "", "") },
|
||||
)
|
||||
1 -> EditableStatsSection(stats, onStats = { stats = it })
|
||||
2 -> EditableStatusesSection(statuses, onStatuses = { statuses = it })
|
||||
3 -> ItemsSection(
|
||||
items = items,
|
||||
onItems = { items = it },
|
||||
scriptNames = scripts.keys.toList(),
|
||||
)
|
||||
4 -> PlacesSection(
|
||||
places = places,
|
||||
onPlaces = { places = it },
|
||||
onPickBackground = { pid ->
|
||||
pendingPlace = pid
|
||||
pickPlaceBg.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClearBackground = { pid -> vm.clearPlaceBackground(pack.id, pid) },
|
||||
)
|
||||
else -> ScriptsSection(
|
||||
scripts = scripts,
|
||||
onScripts = { scripts = it },
|
||||
editing = editing, onEditing = { editing = it },
|
||||
draft = draft, onDraft = { draft = it },
|
||||
newScript = newScript, onNewScript = { newScript = it },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 设定:名称 / 正文 / 外观四件套 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun SettingSection(
|
||||
name: String,
|
||||
onName: (String) -> Unit,
|
||||
setting: String,
|
||||
onSetting: (String) -> Unit,
|
||||
image: AgentImage,
|
||||
onPick: (String) -> Unit,
|
||||
onClear: (String) -> Unit,
|
||||
) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("基本信息")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = onName,
|
||||
label = { Text("名称", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"世界观正文 —— 整段注入绑定这个世界观的智能体的 <worldview> 段。" +
|
||||
"别以「你是…」开头,那是智能体自己的系统提示词。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
value = setting,
|
||||
onValueChange = onSetting,
|
||||
placeholder = { Text("比如:九州山河破碎,灵气复苏三百年……", fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp),
|
||||
textStyle = TextStyle(fontSize = 14.sp, lineHeight = 20.sp),
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("外观(四件套)")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
val slots = listOf(
|
||||
Triple("front", "封面 / 代表图", "世界包列表上用的那张"),
|
||||
Triple("back", "背景图", "铺在展示区最底层"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本"),
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> image.slot("平常")
|
||||
"back" -> image.back
|
||||
"border-main" -> image.borderMain
|
||||
else -> image.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("选择") { onPick(key) }
|
||||
if (path.isNotBlank()) {
|
||||
RowAction("清除", danger = true) { onClear(key) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 数值 / 状态(只读) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun StatsSection(stats: List<StatDef>) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("数值定义")
|
||||
Card {
|
||||
if (stats.isEmpty()) Hint("没有数值。数值是这个世界的规则,比如好感度、声望。")
|
||||
for (s in stats) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${fmt(s.min)} ~ ${fmt(s.max)}" + if (s.shared) " · 全世界共用" else "",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.ranges.isNotEmpty()) {
|
||||
Text(
|
||||
"${s.ranges.size} 段区间:" + s.ranges.joinToString("、") {
|
||||
"${fmt(it.min)}~${fmt(it.max)}「${it.text.take(10)}」"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.script.isNotBlank()) {
|
||||
Text("裁决脚本:${s.script}", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"数值结构(增删数值、min/max、区间表)这一版还是只读的 —— " +
|
||||
"用「导出」在电脑上改 worldInfo.json 再导回来是最快的办法。" +
|
||||
"界面上能改的是脚本,那也是最常改的部分。",
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusesSection(statuses: List<StatusDef>) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态定义")
|
||||
Card {
|
||||
if (statuses.isEmpty()) Hint("没有状态。状态是挂在这个角色身上的临时状况,比如中毒、庇佑。")
|
||||
for (s in statuses) {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
(if (s.isPersistent) "持久" else "定时 ${s.turns} 轮") +
|
||||
(if (s.maxStack > 1) " · 最多叠 ${s.maxStack} 层" else ""),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 脚本(可编辑) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun ScriptsSection(
|
||||
scripts: Map<String, String>,
|
||||
onScripts: (Map<String, String>) -> Unit,
|
||||
editing: String,
|
||||
onEditing: (String) -> Unit,
|
||||
draft: String,
|
||||
onDraft: (String) -> Unit,
|
||||
newScript: String,
|
||||
onNewScript: (String) -> Unit,
|
||||
) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("脚本")
|
||||
if (scripts.isEmpty()) {
|
||||
Hint("这个世界包还没有脚本。数值的裁决、状态的每轮行为、赋予判定都靠脚本。")
|
||||
}
|
||||
Card {
|
||||
for ((fname, src) in scripts) {
|
||||
if (editing == fname) {
|
||||
Text(fname, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
CodeBox(value = draft, onValueChange = onDraft)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("保存这段") { onScripts(scripts + (fname to draft)); onEditing("") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("取消") { onEditing("") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("删掉") { onScripts(scripts - fname); onEditing("") }
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fname, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
"${src.lines().size} 行 · 点开编辑",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("编辑") { onEditing(fname); onDraft(src) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
// 新建一段
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = newScript,
|
||||
onValueChange = onNewScript,
|
||||
label = { Text("新脚本文件名", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("新建") {
|
||||
val f = newScript.trim()
|
||||
if (f.isNotBlank() && !scripts.containsKey(f)) {
|
||||
onScripts(scripts + (f to SCRIPT_TEMPLATE))
|
||||
onNewScript("")
|
||||
onEditing(f)
|
||||
onDraft(SCRIPT_TEMPLATE)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"三段脚本共用同一个沙箱(静态扫描 + 内置函数白名单 + 硬超时):" +
|
||||
"不能 import、不能读写文件。报错只影响这一次操作,不会中断对话。",
|
||||
)
|
||||
}
|
||||
|
||||
/** 新建脚本时给的骨架(三个入口都列出来,用户知道可以写什么) */
|
||||
private const val SCRIPT_TEMPLATE = """# 可用的三个入口(写哪个都行,不写的就不执行):
|
||||
|
||||
def on_stat_change(name, value, delta):
|
||||
# 数值裁决:返回生效的增量(可以放大、缩小、返回 0 否决)
|
||||
return delta
|
||||
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
# 每轮生成回复之前跑一次(状态脚本)
|
||||
# stats_api['change_stat']('好感度', -1)
|
||||
# stats_api['set_hint']('中毒', '你眼前发黑')
|
||||
# stats_api['narrate']('毒性发作了')
|
||||
return True
|
||||
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
# 别人要给你挂状态时,返回 False 就是抵抗掉
|
||||
return True
|
||||
"""
|
||||
|
||||
/**
|
||||
* 代码框:**不软换行** + **有高度上限**(见文件头的两条硬要求)。
|
||||
*/
|
||||
@Composable
|
||||
private fun CodeBox(value: String, onValueChange: (String) -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState())) {
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoText(),
|
||||
),
|
||||
modifier = Modifier.width(900.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user