Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 00b7bb78d3 | |||
| d482fc414e | |||
| 2dd3ed3dd3 | |||
| 33bade6e1a | |||
| a1373a1a96 | |||
| 214f1ddd2a | |||
| 276c949374 | |||
| c2024efd91 | |||
| 6149a96d52 | |||
| b4621d64bf | |||
| 35c67263a1 | |||
| ef2e8fed53 | |||
| bade4541fe | |||
| f9a9284cba | |||
| 2b4698c000 | |||
| 850f909ba7 | |||
| 83828c8366 | |||
| fb22490ada | |||
| de497efe8a | |||
| 4dc42e2c73 | |||
| 8e8a66daf6 | |||
| d4896a5dd1 | |||
| 1956828296 | |||
| 79a7ebcb05 | |||
| 11ce35a201 | |||
| d9dfa6442a | |||
| c3831a461b | |||
| 6ad80011dd | |||
| e0ae716e98 | |||
| ca65ec36c8 | |||
| 62a613a1e2 | |||
| dd66541446 | |||
| 3a0869eab8 | |||
| 849e2e5beb | |||
| aa5b0226f9 | |||
| 155f95c982 | |||
| 7ccdc4516a | |||
| 8acfc0ed0d | |||
| 693e75dad2 | |||
| 91675f21fb | |||
| 91a4ba2ab4 | |||
| 5a65320a5d | |||
| 946bf8bc55 | |||
| 050a3b2385 | |||
| ab8296901d | |||
| c09df1d0a2 | |||
| 31c62fafc2 | |||
| 7498810c70 | |||
| 57a9ff4ea1 | |||
| ab063d0674 | |||
| 3d5c02e7a9 | |||
| 4ed6c6a4ee | |||
| f665b83b34 | |||
| 1c07e37932 | |||
| daccc3fd10 | |||
| e62dd7b87b | |||
| 8ccf009958 | |||
| ff1c2e3400 | |||
| bea9debe15 | |||
| 8ac14bdaa2 | |||
| f84c68762b | |||
| 5878ec7a7f | |||
| 77b4f3d74f | |||
| fbfd50eb56 | |||
| 5a7ed44226 | |||
| 0b80ca4830 | |||
| c1da6486a4 | |||
| f877bd6ee8 | |||
| c9e0d689c0 | |||
| cceffd77ec | |||
| 2142e119c6 | |||
| 4ad2ea8e90 | |||
| bbc32dcb46 | |||
| 778c19b088 | |||
| 7e7aea0f48 | |||
| 4effa968ac | |||
| 76d6445ed6 | |||
| b55ce63c6e | |||
| 28a2ede206 | |||
| 1a9229aa75 | |||
| e11e178810 | |||
| 6bcb5d72f8 | |||
| b693f22f61 | |||
| 6e5ea9d3b6 | |||
| 08eecb9e0a | |||
| 182c0005a4 | |||
| 9ff60e684b | |||
| f8ab075f5e | |||
| 56b15f1d19 | |||
| d3a327da26 | |||
| 4b94e3eef3 | |||
| d557dbd2e3 | |||
| a6840f383e | |||
| 9024810558 | |||
| ef42aa70ca | |||
| a87eca329a | |||
| fd72ad06a1 | |||
| 2a25cf623f | |||
| c7fed95650 | |||
| d82c3d3176 | |||
| 4850ea12af | |||
| 2c259d4270 | |||
| 39813985b5 | |||
|
|
f330af963a | ||
|
|
74c87686ef | ||
|
|
5e95e17c3e |
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/
|
||||
|
||||
186
AGENTS.md
@@ -1,155 +1,61 @@
|
||||
# 项目约定
|
||||
# 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`),再构建;编辑器构建脚本会校验版本一致。
|
||||
桌面 exe 在 **E 盘工作区**构建(工作区目录里跑 exe 写外部目录会被限制):
|
||||
`python 豆鲍编辑器/scripts/build_exe_e.py` —— 同步源码到 `E:\豆鲍编辑器`
|
||||
→ PyInstaller + 签名 + `--selftest` → 回拷 `发布/`;
|
||||
APK:`python 豆鲍编辑器/scripts/build_apk.py --release --install --device emulator-5558`。
|
||||
编辑器 exe 打包时会带上**完整小人间内核**(`豆鲍/android/kernel/*.py`)、`tools/`
|
||||
和 `kernel_host.py`;「真实内核 · AI 联调」(Ctrl+Alt+F7)直接跑这份内核 +
|
||||
真实 OpenAI 兼容 AI API(Key 存在本机 `data_dir()/real-kernel.json`)。
|
||||
编辑器有**四种工程**:节点 / 世界包 / 角色包 / **UI 包**(v3.36–v3.38 的游戏界面
|
||||
HTML 模板包:template.json + index.html/style.css/game.js;桌面和 APK 都能编辑、
|
||||
导出 App 可导入的 zip)。
|
||||
|
||||
这个服务器上 `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 真出现过)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`opSpec` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 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)。
|
||||
|
||||
649
README.md
@@ -1,638 +1,25 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆鲍 · 豆包 App 复刻
|
||||
|
||||
[](LICENSE)
|
||||
工程在 **[`豆鲍/`](豆鲍/)**,说明看 **[`豆鲍/README.md`](豆鲍/README.md)**。
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
```
|
||||
豆鲍/ 完整工程(Android 原生 + Python 内核 + Node 服务端 + 网页 + 桌面版)
|
||||
豆鲍编辑器/ 编辑器工作区(放导出的包、手改的 JSON、批量改数据的脚本)
|
||||
```
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||
> 「豆包」是字节跳动的商标。
|
||||
|
||||
| 平台 | 产物 | 界面 | 内核 |
|
||||
|---|---|---|---|
|
||||
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | Lynx(旧版,仍在) | Node(随 Electron 启动) |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | Lynx(旧版,仍在) | Node |
|
||||
|
||||
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||
|
||||
| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
|
||||
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
|
||||
|
||||
---
|
||||
|
||||
## 1. 快速开始
|
||||
|
||||
### 浏览器 / 桌面版
|
||||
## 最快验证它能跑
|
||||
|
||||
```bash
|
||||
npm run install:all # app(Lynx 客户端)+ server(Node 内核)
|
||||
npm run build
|
||||
npm start # 打开 http://127.0.0.1:5199/
|
||||
cd 豆鲍
|
||||
|
||||
# 1) 探针:不需要设备、不需要网络,在电脑上把内核逻辑逐条断言
|
||||
python scripts/probe-agent-system.py
|
||||
python scripts/probe-group-chat.py
|
||||
# … 一共八个,见 README
|
||||
|
||||
# 2) 构建 APK
|
||||
node scripts/build-apk.mjs
|
||||
# → dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**exe 必须放纯英文路径**,见 §7.1)。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
```bash
|
||||
npm run apk # 产出 dist-android/doubao-debug.apk(约 88 MB)
|
||||
adb install -r dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
装完打开 App → 抽屉 →「设置」→ 选提供商、填 API Key → 保存。
|
||||
第一次启动会解压内置 Termux(约 95 MB、3226 个文件),**约 10~30 秒**,界面上有进度。
|
||||
|
||||
---
|
||||
|
||||
## 2. 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Android App(原生 Kotlin + Compose,主力) │
|
||||
│ │
|
||||
│ ui/ ChatScreen Drawer Settings Skills Agents Profile │
|
||||
│ ModelPickerSheet TerminalScreen ← 7 个页面 │
|
||||
│ │ │
|
||||
│ │ KernelClient(OkHttp + 轮询流式) │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ Python 内核(Chaquopy 内嵌 CPython 3.13) │ │
|
||||
│ │ android/kernel/ —— 监听 127.0.0.1:5199 │ │
|
||||
│ │ · providers 10 家兼容厂商 + 思考强度映射 │ │
|
||||
│ │ · agent_loop 多轮工具循环 │ │
|
||||
│ │ · tools import 加载 tools/*.py │ │
|
||||
│ │ · mcp_client 手写 JSON-RPC(http/stdio/inproc)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ 进程内直调(Chaquopy 桥) │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 内置 Termux($PREFIX = /data/user/0/<pkg>/files/usr) │
|
||||
│ │ · bash 5.x / apt / pkg / 388 个命令 │ │
|
||||
│ │ · libtermux.so → forkpty(真 tty) │ │
|
||||
│ │ · TerminalView → ANSI 渲染(Termux 源码 vendored)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 设备能力 NativeBridge:定位 / 陀螺仪 / 加速度计 │ │
|
||||
│ │ 磁性 / 光线 / 气压 / 电量 / 剪贴板 / 选文件 │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
电脑上的 Web/exe 版仍然用 **Node 内核 + Lynx 界面**。两个内核**接口逐字段一致**,
|
||||
所以安卓端把界面换成 Compose 之后,后端一行都不用改。
|
||||
|
||||
怎么做到一致的:`android/kernel/` 是照 `server/src/` 的契约重写的纯标准库实现
|
||||
(`http.server` + `urllib` + 手写 JSON-RPC),不依赖任何第三方包 —— 因为安卓上装不进来。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能
|
||||
|
||||
### 3.1 智能体
|
||||
抽屉 →「智能体」。每个智能体有独立头像(9 种)和系统提示词,聊天时覆盖全局提示词,顶部显示当前智能体。
|
||||
内置 4 个(豆包 / 代码搭子 / 文案师 / 数据分析),可自建。存 `<数据目录>/agents.json`。
|
||||
|
||||
### 3.2 模型、提供商与思考强度(抽屉里的「模型」那一栏)
|
||||
|
||||
**支持 10 家,而且它们全都是同一个协议**(`POST {baseUrl}/chat/completions`),
|
||||
所以内核里只有一份实现,差别只在三件事:地址、模型名、**思考强度用哪个字段传**。
|
||||
|
||||
| key | 提供商 | Base URL | 思考强度怎么传 |
|
||||
|---|---|---|---|
|
||||
| `ark` | 火山方舟(豆包) | `https://ark.cn-beijing.volces.com/api/v3` | 顶层 `thinking: {type}` |
|
||||
| `openai` | OpenAI 官方 | `https://api.openai.com/v1` | `reasoning_effort` |
|
||||
| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | 不发(模型自己决定) |
|
||||
| `kimi` | Kimi(月之暗面) | `https://api.moonshot.cn/v1` | 不发 |
|
||||
| `zhipu` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | 顶层 `thinking: {type}` |
|
||||
| `dashscope` | 通义千问(阿里云) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | 不发 |
|
||||
| `siliconflow` | 硅基流动 | `https://api.siliconflow.cn/v1` | 不发 |
|
||||
| `openrouter` | OpenRouter(聚合) | `https://openrouter.ai/api/v1` | `reasoning_effort` |
|
||||
| `ollama` | 本地 Ollama | `http://127.0.0.1:11434/v1` | 不发 |
|
||||
| `custom` | 自定义兼容网关 | 自己填 | 不发 |
|
||||
|
||||
**为什么不是"非 ark 即 openai"**:这个判断以前写死成两家名字。
|
||||
现在厂商多了,各自认的字段不一样,而**给不认 `reasoning_effort` 的服务发这个字段,有些会直接 400**。
|
||||
所以改成每个预设自己声明 `thinkingMode`(`ark` / `effort` / `none`),**认不出来的一律 `none`**(什么都不发,最安全)。
|
||||
|
||||
| 强度 | `thinkingMode: ark` | `thinkingMode: effort` | `thinkingMode: none` |
|
||||
|---|---|---|---|
|
||||
| 快速 | `thinking={type:"disabled"}` | 推理模型 `reasoning_effort=minimal` | 不发 |
|
||||
| 自动 | 不传,交给模型 | 不传 | 不传 |
|
||||
| 低 / 中 / 高 | `thinking={type:"enabled"}` | `reasoning_effort=low/medium/high` | 不传 |
|
||||
|
||||
另外:`thinkingMode: effort` 且模型名匹配 `o1|o3|o4|gpt-5|gpt-6` 时,
|
||||
会自动剥掉 `temperature`/`top_p` 等采样参数,并把 `max_tokens` 换成 `max_completion_tokens`
|
||||
(这些模型"传默认值"也算传,会 400)。
|
||||
|
||||
两份内核(Node / Python)在这件事上**逐字段对拍 50/50 一致**(10 家 × 5 档),
|
||||
脚本:`node scripts/parity-thinking.mjs`。
|
||||
|
||||
### 3.3 思考过程怎么显示
|
||||
1. **正文里**:回答上方一个 `✨ 深度思考 ›` 入口,思考中显示跳动小点
|
||||
(这里不再拼思考强度 —— 强度本身就叫"深度思考",拼出来会变成"深度思考 · 深度思考")
|
||||
2. **点开**:底部升起「**思考过程**」弹层(左上角 X),先列这轮调了哪些工具,再是完整思维链
|
||||
3. 思维链**已落库**,刷新/切会话都不丢
|
||||
|
||||
### 3.4 界面:照着豆包抠的,带完整动效
|
||||
|
||||
安卓端是原生 Compose 重写的,视觉对着豆包真机截图一项项抠:
|
||||
|
||||
- **纯白底**(不是浅灰)——豆包的层级靠"白底 + 浅灰卡片"表达,用灰底会一股系统设置味
|
||||
- 顶部三段式:左边 ☰ / ✎,中间「头像 + 智能体名 + ›」(点开就是模型面板),右边 📞 / 🔊
|
||||
- 空会话时:168dp 蓝色圆环大头像 + 灰色问候气泡 + 白底描边快捷胶囊(对话 / AI创作 / 出行用豆包 / 豆包)
|
||||
- 用户气泡:`#2B7BFF` 蓝底、右下角收窄成 4dp(气泡"尾巴")
|
||||
- 助手气泡:`#F2F3F5` 灰底、左下角收窄;下面一排 5 个圆形小按钮(复制/朗读/赞/踩/分享)+ 右侧重新生成
|
||||
- 输入框:52dp 高的大圆角描边胶囊,左边相机、右边麦克风;**有内容时右侧才变成蓝色圆形发送键**
|
||||
- 出错的回复是浅红底 + 红字,不是普通气泡
|
||||
- 设置 / 我的 / 技能 / 智能体各页共用同一套小部件(`ScreenHeader` / `SettingsCard` / `FormField` …),
|
||||
所以在主题层改一次颜色,7 个页面一起变
|
||||
|
||||
动效(都是 Compose 原生动画,没引第三方库):
|
||||
|
||||
| 位置 | 动效 |
|
||||
|---|---|
|
||||
| 抽屉 | 从左滑入 + 遮罩淡入,关闭反向 |
|
||||
| 页面切换 | 淡入 + 轻微横向位移(`AnimatedContent`) |
|
||||
| 消息气泡 | 出现时淡入 + 上移 10dp(`AppearOnce`) |
|
||||
| 思考 / 模型面板 | 从底部升起,收起时降下去 |
|
||||
| "正在输入" | 三个小点依次跳动(`TypingDots`,错开 130ms) |
|
||||
| 按钮 | 按下缩到 0.86~0.94 回弹(`collectIsPressedAsState` + spring) |
|
||||
| 抽屉列表项 | 按下时背景色渐变 |
|
||||
|
||||
> 顺带一个坑:底部面板的**滚动区会吃掉点击**。如果面板顶到状态栏,
|
||||
> "点遮罩关闭"就只剩状态栏那条能点,等于失效。所以面板限高 85%、并且都带明确的 X 按钮。
|
||||
|
||||
### 3.5 设置不会被保存清空(三道防线)
|
||||
|
||||
之前有个真 bug:**一保存设置,整份配置被清空**。根因是首屏 `state` 还在路上时,
|
||||
设置页草稿还是"全空"的,而保存按钮把草稿**全量**下发;`/api/settings` 是浅合并,
|
||||
空字符串就等于把它清掉。现在三道防线:
|
||||
|
||||
1. **界面只发改动过的字段**(`SettingsDraft.changesAgainst`)——没动过的键根本不出现
|
||||
2. **草稿只在服务端设置真的变了时重建**(存一份 `snapshot` 对比),
|
||||
不会再被无关的 state 刷新冲掉正在输入的内容
|
||||
3. **内核拒收空的关键字段**(`provider` / `baseUrl` / `model` / `apiKey` / `nickname` / `thinkingLevel`)——
|
||||
前端再出 bug 也清不掉配置。`systemPrompt` / `toolsDir` 故意不在此列:它们"留空"是合理需求
|
||||
|
||||
验证脚本(都会先正常保存一次验证不掉字段,再按"旧版 bug 的形状"下发一堆空值验证被忽略):
|
||||
|
||||
- `node scripts/probe-settings-wipe.mjs http://127.0.0.1:5199`(电脑 / Node 内核)
|
||||
- `node scripts/device-settings-attack.mjs emulator-5556 5199`(设备 / Python 内核)
|
||||
|
||||
### 3.6 工具
|
||||
|
||||
| 工具 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `shell` | 终端执行命令,带超时与黑名单 | ✅ 优先走内置 Termux |
|
||||
| `python_run` | 执行 Python 代码 / .py 文件,`action=libs` 列可用库 | ✅ 进程内 exec(CPython 3.13.9) |
|
||||
| `device` | **手机能力**:设备信息、定位、传感器、剪贴板 | ✅ 安卓专属 |
|
||||
| `calc` `now` `get_weather` `notes` `web_fetch` | `tools/*.py`,自己写的 | ✅ 同一份代码 |
|
||||
| `mcp__*` | MCP 服务暴露的工具 | ✅ 见 3.8 |
|
||||
|
||||
**`device` 工具**(安卓)实测能力:
|
||||
- `info`:型号/厂商/系统/SDK/ABI/存储/屏幕/电量
|
||||
- `location`:GPS 经纬度(真机实测 `纬度, 经度 ±35m`)
|
||||
- `sensors` / `sensor`:列出并采样(真机 46 个传感器,加速度计 z≈9.7 m/s² 就是重力)
|
||||
- `clipboard_get` / `clipboard_set`
|
||||
- `termux_available` / `termux_run`:走内置 Termux
|
||||
|
||||
### 3.7 自己写工具
|
||||
往工具目录丢一个 `.py`(`_` 开头跳过):
|
||||
|
||||
```python
|
||||
TOOL = {
|
||||
"name": "word_count",
|
||||
"description": "统计一段文字的字数",
|
||||
"parameters": {"type": "object", "properties": {"text": {"type": "string"}},
|
||||
"required": ["text"]},
|
||||
}
|
||||
def run(args): # 同步或 async 都行
|
||||
return {"count": len(args["text"])}
|
||||
```
|
||||
|
||||
工具目录:安卓在 `files/tools/`(可通过设置里的 `toolsDir` 改),电脑在 `tools/`。
|
||||
内置工具在首次启动时会**播种**到可写目录,改坏了删掉重启就恢复。
|
||||
|
||||
> 为什么安卓上要播种、还要把源码 base64 打进 APK:Chaquopy 打的是 `.pyc`,
|
||||
> 运行时 `loader.get_source()` 拿不到源码,所以构建脚本额外生成了 `bundled_tool_sources.py`。
|
||||
|
||||
### 3.8 MCP:三种传输,安卓也能跑
|
||||
抽屉 →「技能·连接器」→「MCP 服务」,图形化和原始 JSON 两个 Tab,保存时校验并自动重连。
|
||||
|
||||
| 传输 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `http` | 标准 Streamable HTTP / SSE | ✅ |
|
||||
| `stdio` | 起一个子进程用管道通信 | ✅ 用内置 Termux 的 python/node |
|
||||
| `inproc` | 同进程内直接调用(自己写的 Python 服务) | ✅ 安卓推荐,最省事 |
|
||||
|
||||
实测:filesystem 服务 14 个工具、memory 9 个工具、自己写的 Python 服务 3 个工具,全部连接并调用成功。
|
||||
|
||||
> 为什么手写 JSON-RPC 而不用官方 `mcp` SDK:它依赖 pydantic v2,Chaquopy 装不进来。
|
||||
|
||||
### 3.9 文件上传 / 权限模式
|
||||
- **上传**:输入框左侧相机/加号 → 选文件 → 上传到内核 → 挂到输入框 → 随消息发送 → 气泡里显示
|
||||
- **权限模式**:`open` 全放行 / `restricted` 只放 `allow` 白名单。限制模式下未授权工具
|
||||
**列都不列出来**,执行时再拦一道
|
||||
|
||||
### 3.10 语音:朗读 + 语音输入
|
||||
|
||||
**引擎放在内核里,音频采集/播放在端上。** 这么分的好处:API Key 只存一份,
|
||||
浏览器 / 安卓 / exe 三端白捡同一个能力,厂商鉴权差异全在一个文件里。
|
||||
|
||||
| | 引擎 | 说明 |
|
||||
|---|---|---|
|
||||
| **朗读** | `system` | 设备自带 TTS(安卓 `TextToSpeech`)。**不联网、不要 Key**,默认就是它 |
|
||||
| | `volc` | **火山语音合成 —— 豆包同款音色** |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/speech`(`tts-1` + alloy/nova/…) |
|
||||
| **语音输入** | `system` | 设备自带识别(安卓 `SpeechRecognizer`) |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/transcriptions`(`whisper-1` 等) |
|
||||
|
||||
**火山那个接口有两个坑**(对着[官方文档](https://docs.volcengine.com/docs/DoubaoVoice/HTTPone-timecompositenon-streaminginterface-V1notrecommended?lang=zh)
|
||||
和两个第三方实现核对过,并且用 mock 抓了实际发出的请求):
|
||||
|
||||
1. 鉴权头是 `Authorization: Bearer;{token}` —— **分号,不是空格**。写成空格会判鉴权失败。
|
||||
实测抓到的请求:`Authorization="Bearer;tok-abc"`
|
||||
2. 成功判定看 body 里的 `code === 3000`,**HTTP 200 也可能带错误码**;
|
||||
返回的 `data` 是**纯 base64**(不是 data URL),解出来就是音频字节
|
||||
|
||||
接口:
|
||||
|
||||
```
|
||||
POST /api/tts {"text": "..."}
|
||||
→ {"ok":true, "engine":"system"} 用设备自带,界面自己念
|
||||
→ {"ok":true, "engine":"volc", "mime":"audio/mpeg", "audio":"<base64>"}
|
||||
→ {"ok":false, "error":"..."} 失败原因给人话
|
||||
|
||||
POST /api/stt <body 就是音频原始字节,不套 JSON/base64>
|
||||
头: X-Audio-Filename / X-Audio-Type
|
||||
→ {"ok":true, "engine":"openai", "text":"..."}
|
||||
|
||||
GET /api/speech → 当前配置 + 可选音色
|
||||
```
|
||||
|
||||
> 两个接口**失败也返回 HTTP 200 + `ok:false`**:缺 Key、厂商报错都是预期内的失败,
|
||||
> 界面要的是把原因显示出来,而不是让 fetch 抛网络异常(那样错误信息就丢了)。
|
||||
|
||||
安卓端(`speech/AudioIo.kt` + `speech/SpeechController.kt`):
|
||||
|
||||
- **录音**用 `AudioRecord` 直接拿 PCM,套 44 字节 WAV 头(16kHz 单声道 16bit ——
|
||||
Whisper 最常见的输入格式,30 秒才 1 MB)。不用 `MediaRecorder` 是因为它只吐 m4a/aac,还得再解码
|
||||
- **播放**云端音频走 `MediaPlayer`(`setDataSource` 只认路径/FD,所以 base64 落盘成临时文件再播)
|
||||
- **系统 TTS** 会**按句切分**再排队 —— `speak()` 单次上限约 4000 字符,整段塞进去会被截断
|
||||
- 念之前**剥掉 markdown**(`**加粗**`、代码块、链接),否则会念出一堆星号
|
||||
- **云端失败自动退回系统 TTS**:用户点了朗读却一点动静都没有是最差的体验
|
||||
- 录音时**先停朗读**,否则会把自己的声音录进去(自我循环)
|
||||
- 录音权限**第一次点麦克风才申请**,不在启动时要
|
||||
- 录音时输入框整条换成「正在听…」+ 实时音量画的小波形
|
||||
|
||||
验证:`node scripts/verify-speech.mjs py|node` —— **21 项断言,两份内核都跑**
|
||||
(语音在 Node 和 Python 里是分别实现的,只验一份不算数)。
|
||||
mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权头。
|
||||
|
||||
### 3.11 通话模式(设计好了,还没做)
|
||||
|
||||
顶部那个 📞 现在是提示。真要做的话按这个来(**不要一上来就上全双工**):
|
||||
|
||||
| 阶段 | 做法 | 为什么 |
|
||||
|---|---|---|
|
||||
| A(推荐先做) | **半双工**:按一次开始录 → 静音自动断句 → STT → 内核 → TTS 播 → 循环 | 复用现有的 STT/TTS,1 天能出可用版本 |
|
||||
| B | 全双工实时(OpenAI Realtime / 火山实时对话,WebSocket) | 延迟 300ms 级、能自然打断,但强依赖网络,改造量 3~5 天 |
|
||||
|
||||
阶段 A 要处理的四件事(都会真实咬人):
|
||||
|
||||
1. **自我循环**:TTS 在播时开麦会把 AI 自己的声音录进去 → 播之前必须先停麦,
|
||||
或者做回声消除(`AudioSource.VOICE_COMMUNICATION` + AEC)
|
||||
2. **音频焦点**:`TextToSpeech` 和 `AudioRecord` 不能同时持有 → 用 `AudioManager` 协调
|
||||
3. **VAD 断句**:靠静音时长判断"说完了"。阈值调不好要么打断用户、要么一直不响应;
|
||||
建议"连续 800ms 低于阈值算说完",并且**开口就打断 TTS**(barge-in)——这是"像通话"的关键手感
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 4. 安卓端:内置 Termux 是怎么塞进去的
|
||||
|
||||
### 4.1 一条硬限制决定了整个方案
|
||||
|
||||
**Android 10(API 29)起有 W^X 限制:`targetSdk ≥ 29` 的应用不允许执行自己数据目录里的二进制。**
|
||||
而 Termux 把 bash/python/node 全解压在自己的私有目录再 exec —— 它能这么干,**唯一原因是它 `targetSdk = 28`**
|
||||
(实测核对:`dumpsys package com.termux` → `targetSdk=28`)。
|
||||
|
||||
所以这个 APK 也锁 **`targetSdk = 28`**。代价是上不了应用商店(个人工具无所谓);
|
||||
换来的是完整 Linux 用户态:`bash`、`apt`、`pkg`、以及 `pkg install python nodejs-lts`。
|
||||
|
||||
### 4.2 APK 里到底装了什么
|
||||
|
||||
```
|
||||
APK 88.4 MB
|
||||
├─ lib/arm64-v8a/libtermux-bootstrap.so 28.0 MB ← Termux 根文件系统(其实是 zip)
|
||||
├─ lib/x86_64/libtermux-bootstrap.so 28.1 MB ← 同上,模拟器用
|
||||
├─ lib/<abi>/libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号)
|
||||
├─ lib/<abi>/libpython3.13.so ← Chaquopy 的 CPython
|
||||
├─ assets/chaquopy/** ← 内核 + 9 个 Python 工具
|
||||
└─ java/com/termux/{terminal,view}/** ← Termux 的终端模拟器源码(vendored)
|
||||
```
|
||||
|
||||
Termux 的终端库**没有发布到任何 Maven 仓库**(Maven Central 没有,JitPack 也不通),
|
||||
所以是 vendored 源码 + 改了两处 `import com.termux.view.R` 指向我们自己的 R 类。
|
||||
Apache-2.0 声明见 `android/app/src/main/assets/TERMUX_LICENSE.txt`。
|
||||
|
||||
### 4.3 安装流程(移植自 Termux 的 `TermuxInstaller.java`)
|
||||
|
||||
1. 从 APK 里取出 `libtermux-bootstrap.so`
|
||||
2. **切掉 ELF 头**得到纯 zip(见 4.4 ①)
|
||||
3. 解压到 `files/usr`(3226 个文件),给 `bin/ lib/ libexec/` 下的文件补可执行位
|
||||
4. 读 `SYMLINKS.txt`(1146 行,格式 `目标←链接路径`),**用 `/system/bin/sh` 批量 `ln -sf`**
|
||||
—— Java 的 File API 建不了符号链接
|
||||
5. **改写脚本 shebang**(见 4.4 ④)
|
||||
6. 写一份自己的 `etc/doubao.bashrc`
|
||||
|
||||
进度会写进 `files/termux-install.log`(见 §7.6,为什么不用 Logcat)。
|
||||
|
||||
### 4.4 踩过的四个坑(都和你想象的不一样)
|
||||
|
||||
**① `libtermux-bootstrap.so` 不是纯 zip,是「ELF 头 + zip」**
|
||||
文件前 1328 字节是 ELF 头(Android 要求 `lib/` 下的东西得像 ELF,Termux 就把 zip 接在后面)。
|
||||
- `ZipInputStream` 按本地文件头顺序扫,**实测一个条目都读不出来**;
|
||||
- `ZipFile` 走中央目录,但它**不会**像桌面 JVM 那样自动跳过前缀 ——
|
||||
真机 Android 16 上直接报 `Entry at offset zero has invalid LFH signature 464c457f`
|
||||
(`464c457f` 就是 `\x7FELF` 的小端十六进制)。模拟器上碰巧宽松能过,真机不行。
|
||||
|
||||
所以现在的做法:**自己扫第一个 `PK\x03\x04`、把前缀切掉**,再交给 `ZipFile`。
|
||||
|
||||
**② `bin/su` 写不进去(ENOENT)**
|
||||
父目录存在、权限也对,就是 `open` 失败。安卓对这个文件名有额外限制。
|
||||
处理方式:**单个文件失败就跳过并记日志**,不让一个怪文件毁掉整次安装(其余 3226 个照常)。
|
||||
|
||||
**③ 必须设 `LD_PRELOAD` + `TERMUX__PREFIX`(双下划线)**
|
||||
Termux 的二进制里写死了 `/data/data/com.termux/files/usr`。`libtermux-exec.so` 负责把这些路径
|
||||
重写到真实 prefix,但它认的环境变量是:
|
||||
`TERMUX__PREFIX`(**不是** `TERMUX_PREFIX`)、`TERMUX_APP__DATA_DIR`。
|
||||
少一个,bash 就会去读**别的包**的 `/etc/profile`,报 `Permission denied`。
|
||||
|
||||
**④ 脚本的 shebang 也得改**
|
||||
`bin/getprop`、`bin/pkg` 这些是 shell 脚本,第一行写死 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
内核解析 shebang 时不会经过 termux-exec,照样 EACCES("bad interpreter")。
|
||||
安装时统一把 `bin/ libexec/` 下 79 个脚本的 shebang 前缀改成我们的 prefix 就好了。
|
||||
|
||||
### 4.5 终端界面(真终端 + 控制台退路)
|
||||
|
||||
用 Termux 自己的 `TerminalView` + `libtermux.so` 的 `forkpty` —— 真 pty、真 ANSI,
|
||||
所以 `vim`/`top` 这类全屏程序都能跑。Compose 里用 `AndroidView` 包一层,底下加了手机必备的功能键排:
|
||||
`ESC / TAB / CTRL+C / CTRL+D / ↑↓←→ / HOME / END / | / / / - / ENTER`(没这排连 vim 都退不出来)。
|
||||
|
||||
**但 pty 不是每台机器都给用**。实测 realme(Android 16)上:
|
||||
|
||||
```
|
||||
/dev/pts → Permission denied
|
||||
mount → devpts on /dev/pts type devpts (mode=600,ptmxmode=000)
|
||||
python openpty → OSError: out of pty devices
|
||||
```
|
||||
|
||||
`/dev/pts` 被挂成 `mode=600` 且 `ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||
于是 TerminalSession 一起来就退出(界面上只留一句 `[Process completed]`)。
|
||||
这不是 SELinux 拒绝(logcat 里没有任何 avc),是挂载参数定的,应用侧绕不过去。
|
||||
|
||||
所以做成两条路,**自动切换**:
|
||||
|
||||
| 情况 | 走哪条 |
|
||||
|---|---|
|
||||
| pty 可用(多数设备 / 模拟器) | Termux 的 TerminalView,真终端 |
|
||||
| 会话建起来 2 秒内就退出(判定 pty 不可用) | 自动切「控制台模式」:命令框 + 输出区,跑的是**同一条 Termux bash**,只是没有 tty |
|
||||
|
||||
代价只是没有全屏 TUI 和交互式提示符,跑命令、装包(`pkg install python`)都正常。
|
||||
|
||||
### 4.6 和内核怎么接
|
||||
|
||||
内核里的 `shell` 工具优先走内置 Termux(返回里带 `via: "termux"`),
|
||||
`device` 工具的 `termux_run` / `termux_available` 也走同一条路。
|
||||
因为 Termux 现在就在本进程里,不需要跨进程 intent、也不需要用户去开 `allow-external-apps`。
|
||||
|
||||
### 4.7 安卓端其余细节(Chaquopy / 界面)
|
||||
|
||||
- **Chaquopy 17.0.0** 内嵌 CPython 3.13.9:没有 `python` 可执行文件(所以 `python_run` 是**进程内 exec**,
|
||||
不能起子进程);运行时 pip 只能装纯 Python 轮子;`mcp` 官方 SDK 用不了(要 pydantic v2)
|
||||
- **刻意不装任何第三方包**:Chaquopy 每次构建都要连云 pip,网络一抖整个 APK 就构建不出来
|
||||
(实测 `Could not find a version that satisfies the requirement requests`)。
|
||||
内核只用标准库(`urllib`/`http.server`/`json`),所以留零依赖换来"离线也能构建"。
|
||||
要 requests/numpy 就走内置 Termux:`pkg install python && pip install requests`
|
||||
- **界面**:状态栏不遮挡顶栏(`windowInsetsPadding(WindowInsets.safeDrawing)`)、
|
||||
输入框跟随输入法(`imePadding`)、深色模式自动适配
|
||||
- **流式**:Lynx 那边用 SSE;安卓原生 Compose 走的是**轮询通道**
|
||||
(`transport: "poll"` + `GET /api/chat/poll?runId=&cursor=`),
|
||||
两条件事件类型完全一致,客户端 200ms 取一次增量
|
||||
|
||||
---
|
||||
|
||||
## 5. 我实际验证了什么
|
||||
|
||||
### 5.1 安卓端(原生 Compose + 内置 Termux)
|
||||
|
||||
真机(RMX5090 / Android 16 / arm64-v8a):`node scripts/verify-phone.mjs <serial>` → **17/18**。
|
||||
模拟器(Android 14 / x86_64):17/18(唯一失败的是"定位",模拟器没有 GPS)。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 构建 | ✅ `assembleDebug` 成功,APK 88.4 MB |
|
||||
| 内核启动 | ✅ `GET /api/health` → `{"ok":true,…}` |
|
||||
| 智能体 / 工具 | ✅ 4 个智能体;8 个内置工具 + MCP 工具 |
|
||||
| 内置 Termux | ✅ 首次解压 3226 个文件 / 388 个命令 / 1146 个符号链接 |
|
||||
| shell | ✅ 真机 `Linux localhost 6.6.118-android15 … aarch64 Android`,`via: termux`,stderr 干净 |
|
||||
| pkg / apt | ✅ 可执行(79 个脚本的 shebang 已修正) |
|
||||
| python_run | ✅ CPython 3.13.9 aarch64(进程内) |
|
||||
| 联网 | ✅ urllib 与 requests 都 200 |
|
||||
| device 信息 | ✅ 型号 / 厂商 / 系统 / SDK / 存储 / 电量 |
|
||||
| 传感器 | ✅ 真机 46 个;加速度计 z≈9.7 m/s²、陀螺仪有数据 |
|
||||
| 定位 | ✅ 真机 `纬度, 经度 ±35m` |
|
||||
| MCP(Python 写的服务) | ✅ 连接 + 列工具 + 调用成功 |
|
||||
| 设置保存 | ✅ 保存前后逐字段一致(含 API Key / 系统提示词),空值攻击被忽略 |
|
||||
| 思考强度映射 | ✅ 两份内核对拍 50/50 一致 |
|
||||
| 界面 | ✅ 对话 / 抽屉 / 终端 / 设置 / 模型面板 截图见文首 |
|
||||
|
||||
### 5.2 其他平台
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 浏览器渲染 | ✅ 无头 Edge + CDP,5 个页面全部渲染,控制台无异常 |
|
||||
| 端到端工具调用 | ✅ mock 模型 → 请求 `calc` → Python 返回 → 第二轮流式回答 → 落库 |
|
||||
| Python 工具 | ✅ `calc` `now` `get_weather`(实时数据) `notes` `web_fetch` 全部通过 |
|
||||
| MCP | ✅ filesystem 14 工具、memory 9 工具连接成功;6 类校验错误全部拦截 |
|
||||
| Windows exe | ✅ 冷启动、界面渲染、内置内核、MCP 自动连接 |
|
||||
|
||||
### 5.3 没有 API Key 也能把链路跑通
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假的 OpenAI 兼容服务,监听 5299
|
||||
node scripts/verify-phone.mjs emulator-5556 # 或对真机跑
|
||||
```
|
||||
|
||||
mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式回答"来演,
|
||||
所以能验证完整的 界面 → 内核 → 工具调用 → 流式返回 链路,**不消耗任何额度**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 给 Lynx 界面(Web / exe)的注意事项
|
||||
|
||||
安卓端已经不用 Lynx 了,这一节只对 Web/exe 有效:
|
||||
|
||||
- **Fresco 必须先初始化**,否则图片不显示;**Fresco 不能解码 SVG**,图标要预先栅格化成 PNG
|
||||
- Lynx 的 `fetch` 没有 `response.body`,所以流式走轮询通道
|
||||
- 状态栏/布局用 `safe-area` 相关变量,别写死 px
|
||||
- 动画(`breathe` 那种)在某些模拟器上会破坏图片绘制,已改成不影响绘制的写法
|
||||
|
||||
---
|
||||
|
||||
## 7. 打包踩坑记录
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 384 MB)
|
||||
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||
|
||||
### 7.2 Android APK
|
||||
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||
否则 `nativeLibraryDir` 是空的,`.so` 全在 APK 里,取 bootstrap 时得从 `applicationInfo.sourceDir` 读
|
||||
- **`targetSdk = 28`**(见 4.1),`abiFilters = ["arm64-v8a", "x86_64"]`
|
||||
- 构建脚本会把 `tools/*.py` 拷进 `app/src/main/python/` 并生成 `bundled_tool_sources.py`
|
||||
- 构建暂存目录用 ASCII 路径(`C:\DoubaoAndroid`),中文路径会让 Gradle/Chaquopy 出问题
|
||||
- **别并发跑两次 Gradle**:会互相踩坏 Chaquopy 的 venv(`Scripts/python.exe does not exist`)
|
||||
|
||||
### 7.3 Chaquopy / 内嵌 Python
|
||||
- `.pyc`-only 打包导致 `loader.get_source()` 失败 → 工具源码用 base64 内嵌
|
||||
- 每次构建都会连云 pip → 已改为零第三方依赖(见 4.7)
|
||||
|
||||
### 7.4 Android 15+ 的 edge-to-edge
|
||||
强制 edge-to-edge 后,状态栏会压住顶栏、输入法会盖住输入框。
|
||||
Compose 里统一在根布局吃 `WindowInsets.safeDrawing`,滚动页再叠 `imePadding()`。
|
||||
|
||||
### 7.5 工具链(Windows)
|
||||
- **Node 20+ 不能直接 `spawn` `.bat`/`.cmd`**(`status=null`),必须 `shell: true`
|
||||
- **PowerShell 会把命令行里的 JSON 引号搅坏**:所有内联 node/python 脚本都写成文件再跑
|
||||
- **PowerShell 的 `Get-Content` / `Set-Content` 会按 GBK 读写 UTF-8 文件**,
|
||||
一读一写就把中文文档转成乱码(本文档就被这么毁过一次)。
|
||||
改文本一律用编辑器工具,别用这两个 cmdlet 做"读进来再写回去"
|
||||
- **Kotlin 的块注释会嵌套**:在 KDoc 里写 `lib/*.so` 里的 `/*` 会开一个嵌套注释,
|
||||
把后面的代码全吞掉,报错却指向文件末尾之外的行
|
||||
|
||||
### 7.6 安卓 `org.json` 不会把 `Map` 转成 JSON 对象(踩过一次大的)
|
||||
|
||||
`json.put("speech", mapOf("autoRead" to true))` **不会**产生 `{"speech":{"autoRead":true}}`,
|
||||
而是把 Map 原样存进去,序列化出来是 `{"speech":"{autoRead=true}"}` —— **值是字符串**。
|
||||
|
||||
这一个坑连锁出四件事:
|
||||
|
||||
1. 内核把字符串写进了 `settings.json`(`speech` 本来是对象,被字符串顶掉了)
|
||||
2. 之后**每一次**读配置(`{**默认, **字符串}`)都抛 `TypeError`
|
||||
3. `/api/state` 从此永远返回 `{"error":"'str' object is not a mapping"}`
|
||||
4. App 把这个错误 JSON 解析成了「全默认状态」,而且**不抛异常**,所以还弹了"已保存"
|
||||
|
||||
用户看到的就是:**点一下语音按钮,模型变「未设置」、昵称变回「我」、会话列表全空**。
|
||||
|
||||
修了三处(缺一不可):
|
||||
- **安卓**:`patchToJson()` 显式递归把 Map/List 转成 `JSONObject`/`JSONArray`(见 `AppViewModel.kt`)
|
||||
- **内核写**:`tools`/`security`/`speech` 这几个子对象,补丁里不是字典就**直接忽略**,
|
||||
宁可这次改动不生效,也不写出读不回来的配置
|
||||
- **内核读**:发现子对象不是字典就**回落默认值**(自愈)——
|
||||
一个坏字段不该让 `/api/state` 永久 500,更不该把用户其它数据一起拖没
|
||||
|
||||
> 为什么之前没暴露:只有**嵌套对象**才触发,而在此之前 App 从没发过嵌套补丁
|
||||
> (`tools` 那两个开关从来没在设置页点过)。教训是——
|
||||
> **跨语言边界传结构化数据时,别信任何一侧的隐式转换**,两端都要有"形状不对就拒绝"的防线。
|
||||
|
||||
### 7.7 部分 ROM 会吞掉应用日志
|
||||
realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一条都看不到**。
|
||||
所以安装进度、终端会话退出原因等关键信息都**落盘**到 `files/termux-install.log`,
|
||||
用 `adb shell run-as com.doubao.lynxclone cat files/termux-install.log` 读。
|
||||
|
||||
---
|
||||
|
||||
## 8. 已知限制
|
||||
|
||||
- **`targetSdk = 28` 上不了应用商店**(个人侧载没问题)。要上架就得回到"外装 Termux + 桥接"那条路
|
||||
- **pty 在部分 ROM 上不可用**(4.5),自动降级成控制台模式,没有全屏 TUI
|
||||
- **内嵌 CPython 没有 `python` 可执行文件**,`python_run` 是进程内 exec,不能起子进程
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发
|
||||
npm run dev # 起 Node 内核 + Lynx 热更
|
||||
npm run build # 构建 Lynx bundle
|
||||
npm run apk # 构建 APK(--clean 可彻底重建)
|
||||
npm run exe # 打包 Windows exe
|
||||
|
||||
# 验证
|
||||
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
node scripts/mock-llm.mjs # 监听 5299
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 参考
|
||||
|
||||
- 火山方舟:<https://www.volcengine.com/docs/82379/1298454>
|
||||
- OpenAI Chat Completions:<https://platform.openai.com/docs/api-reference/chat>
|
||||
- Termux(Apache-2.0):<https://github.com/termux/termux-app>
|
||||
- Chaquopy:<https://chaquo.com/chaquopy/doc/current/>
|
||||
- 调研笔记(`docs/`):
|
||||
- `ai-chat-backend-api-research.md`(Ark/OpenAI/MCP 接口细节与证据强度)
|
||||
- `lynx-ui-research.md`(豆包界面还原的调研)
|
||||
|
||||
---
|
||||
|
||||
## 11. 许可
|
||||
|
||||
本项目采用 **MIT License**,见 [LICENSE](LICENSE)。
|
||||
|
||||
它**包含或依赖**第三方作品,各自的授权独立于 MIT,使用时请一并遵守:
|
||||
|
||||
| 组件 | 授权 | 用在哪 |
|
||||
|---|---|---|
|
||||
| [Termux](https://github.com/termux/termux-app) | **Apache-2.0** | 终端模拟器源码(vendored)+ pty 的 JNI 库 |
|
||||
| [Chaquopy](https://chaquo.com/chaquopy/) | MIT | APK 内嵌 CPython |
|
||||
| [Jetpack Compose / AndroidX](https://developer.android.com/jetpack) | Apache-2.0 | 安卓界面 |
|
||||
| [LynxJS](https://github.com/lynx-family/lynx) | Apache-2.0 | Web / 桌面版界面 |
|
||||
| [Electron](https://github.com/electron/electron) | MIT | Windows 桌面版打包 |
|
||||
|
||||
Termux 的完整许可在 `android/app/src/main/assets/TERMUX_LICENSE.txt` 与 `APACHE-2.0.txt`。
|
||||
|
||||
> **商标声明**:「豆包」是字节跳动的商标。本项目是出于学习目的的界面复刻,
|
||||
> 与字节跳动无任何关联,不含任何来自豆包 App 的代码或素材。
|
||||
> 界面配色与布局照着公开截图量出,图标使用 Material Icons。
|
||||
|
||||
> **注意**:本仓库**不包含** Termux 的 bootstrap(`libtermux-bootstrap.so`,两个 ABI 共 56 MB),
|
||||
> 因此直接 clone 下来构建 APK 会缺这个文件。补法见 §4.2 与 §4.3。
|
||||
|
||||
约定见 [`AGENTS.md`](AGENTS.md)(入口)和 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)(详细)。
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.Context
|
||||
import com.chaquo.python.Python
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 手机端的本地 AI 内核(Chaquopy 内嵌 CPython)。
|
||||
*
|
||||
* 为什么要它:手机上装不了 Node,而用户要的是"脱离电脑也能用"。
|
||||
* 内核用 Python 重写了一份(android/kernel),接口和电脑上的 Node 版一模一样,
|
||||
* 所以 Lynx 界面完全不用改,只是把 apiBase 指到 127.0.0.1。
|
||||
*
|
||||
* 注意 Chaquopy 的两个硬约束(都踩过):
|
||||
* 1. 它把 Python 嵌在主进程里,**没有独立 python 可执行文件** → 不能用 subprocess 起 py 脚本
|
||||
* 2. 只有 arm64-v8a / x86_64 两个 ABI
|
||||
*/
|
||||
object LocalKernel {
|
||||
|
||||
@Volatile
|
||||
private var port = 0
|
||||
|
||||
@Volatile
|
||||
private var failure: String? = null
|
||||
|
||||
/** 已启动则直接返回端口;否则同步启动(要在子线程调) */
|
||||
@Synchronized
|
||||
fun ensureStarted(context: Context, preferredPort: Int = 5199): Int {
|
||||
if (port > 0) return port
|
||||
failure = null
|
||||
try {
|
||||
val py = Python.getInstance()
|
||||
val entry = py.getModule("doubao_entry")
|
||||
|
||||
val dataDir = File(context.filesDir, "kernel-data").apply { mkdirs() }.absolutePath
|
||||
// 外部私有目录:不用申请存储权限,用户能通过文件管理器/USB 往里放自己的 py 工具
|
||||
val workDir = (context.getExternalFilesDir(null) ?: File(context.filesDir, "external"))
|
||||
.apply { mkdirs() }.absolutePath
|
||||
|
||||
val actual = entry.callAttr("start", dataDir, workDir, preferredPort).toInt()
|
||||
port = actual
|
||||
android.util.Log.i("DoubaoKernel", "本地内核已就绪 127.0.0.1:$actual data=$dataDir work=$workDir")
|
||||
return actual
|
||||
} catch (t: Throwable) {
|
||||
failure = t.message ?: t.toString()
|
||||
android.util.Log.e("DoubaoKernel", "本地内核启动失败", t)
|
||||
throw t
|
||||
}
|
||||
}
|
||||
|
||||
fun baseUrl(): String? = if (port > 0) "http://127.0.0.1:$port" else null
|
||||
|
||||
fun lastFailure(): String? = failure
|
||||
|
||||
/** 工具目录(给界面显示用) */
|
||||
fun workDir(context: Context): String =
|
||||
(context.getExternalFilesDir(null) ?: File(context.filesDir, "external")).absolutePath
|
||||
}
|
||||
@@ -1,406 +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` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
// 「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("搜索还没做") },
|
||||
)
|
||||
}
|
||||
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
}
|
||||
/**
|
||||
* ★「AI 界面」—— 用户要求"AI 写的界面可以再点开"。
|
||||
*
|
||||
* 放在抽屉里而不是只靠消息操作栏:操作栏那个按钮只有**那一条回复**
|
||||
* 弹过界面时才出现,用户想"翻翻前几次弹过什么"就没路走。
|
||||
* 这里是个总入口,能看全部、也能删。
|
||||
*/
|
||||
DrawerItem(Icons.Filled.Dashboard, "AI 界面") {
|
||||
vm.drawerOpen = false
|
||||
vm.openAiScreenList()
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.AccountTree, "会议模式") {
|
||||
vm.screen = Screen.Meetings; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Terminal, "终端") {
|
||||
vm.screen = Screen.Terminal; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Settings, "设置") {
|
||||
vm.screen = Screen.Settings; vm.drawerOpen = false
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
ConversationRow(vm, vm.state.conversations[i])
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.screen = Screen.Profile; vm.drawerOpen = false }
|
||||
.padding(horizontal = 20.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).background(Doubao.Blue),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(vm.settings.nickname.take(1), color = Color.White, fontSize = 14.sp)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(vm.settings.nickname, fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.background(Doubao.Scrim)
|
||||
.clickable { vm.drawerOpen = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerItem(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
trailing: String = "",
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val bg by animateColorAsState(
|
||||
targetValue = if (pressed) doubaoCard() else Color.Transparent,
|
||||
animationSpec = tween(120),
|
||||
label = "itemBg",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Text(label, fontSize = 16.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (trailing.isNotBlank()) {
|
||||
Text(trailing, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConversationRow(vm: AppViewModel, conv: Conversation) {
|
||||
val active = conv.id == vm.activeConversationId
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (active) doubaoCard() else Color.Transparent)
|
||||
.clickable { vm.openConversation(conv.id) }
|
||||
.padding(horizontal = 10.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(RoundedCornerShape(19.dp)).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(conv.title.take(1), color = Doubao.Blue, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(conv.title, fontSize = 15.sp, color = doubaoText(), maxLines = 1)
|
||||
Text(
|
||||
conv.preview.ifBlank { "还没有消息" },
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp).clickable { vm.deleteConversation(conv) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 文案小工具 ------------------------------ */
|
||||
|
||||
fun shortModel(model: String): String = when {
|
||||
model.isBlank() -> "未设置"
|
||||
model.startsWith("ep-") -> "接入点 ${model.take(8)}"
|
||||
model.startsWith("doubao-seed-2-1-pro") -> "豆包 Pro"
|
||||
model.startsWith("doubao-seed-1-8") -> "豆包 1.8"
|
||||
model.startsWith("doubao-seed-1-6") -> "豆包 1.6"
|
||||
model.startsWith("doubao") -> "豆包"
|
||||
model.startsWith("deepseek-r1") -> "DeepSeek R1"
|
||||
model.startsWith("deepseek") -> "DeepSeek"
|
||||
model.startsWith("gpt-5") -> if (model.contains("mini")) "GPT-5 mini" else "GPT-5"
|
||||
model.startsWith("gpt-4o") -> if (model.contains("mini")) "GPT-4o mini" else "GPT-4o"
|
||||
else -> if (model.length > 16) model.take(14) + "…" else model
|
||||
}
|
||||
|
||||
fun thinkingLabel(level: String): String = when (level) {
|
||||
"off" -> "快速"
|
||||
"low" -> "低"
|
||||
"medium" -> "中"
|
||||
"high" -> "深度思考"
|
||||
else -> "自动"
|
||||
}
|
||||
@@ -1,862 +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
|
||||
|
||||
/** 打开 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(),
|
||||
)
|
||||
} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 9.1 KiB |
|
Before Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 44 KiB |
@@ -1,277 +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 秒,默认 120)。',
|
||||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||||
' 适合"弹几个选项让用户挑,然后我继续"。',
|
||||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||||
'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,
|
||||
}
|
||||
@@ -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,780 +0,0 @@
|
||||
"""
|
||||
持久化:设置 / 会话 / 智能体。
|
||||
|
||||
对应 Node 版的 config.mjs(设置)+ store.mjs(会话)+ agents.mjs(智能体),
|
||||
文件名也保持一致(settings.json / conversations.json / agents.json),
|
||||
这样安卓内核和桌面内核可以共用同一个数据目录。
|
||||
|
||||
为什么用 JSON 文件而不是 SQLite:
|
||||
* 数据量极小(几条会话、几个智能体),前端还要能直接看到/改这些文件;
|
||||
* 安卓上 Chaquopy 自带 sqlite3,但跨端"人肉可读"更重要;
|
||||
* 写盘走"临时文件 + 原子替换",避免安卓被杀进程时留下半个 JSON。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
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
|
||||
|
||||
|
||||
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
@@ -1,168 +0,0 @@
|
||||
/**
|
||||
* 豆包 · LynxJS 复刻 —— Electron 桌面壳(CommonJS)
|
||||
*
|
||||
* 为什么用 CJS:Electron 主进程在 ESM 下解析 'electron' 会命中 npm 包
|
||||
* (那个包的 index.js 只导出二进制路径),拿不到 app/BrowserWindow。
|
||||
* 内核本身是 ESM,用动态 import() 加载即可。
|
||||
*
|
||||
* 主进程做三件事:
|
||||
* 1. 进程内直接启动 AI 内核(不额外起 node 子进程)
|
||||
* 2. 开一个手机比例窗口,加载 ?frame=0 的界面
|
||||
* 3. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去
|
||||
*/
|
||||
const { app, BrowserWindow, Menu, shell, dialog, clipboard } = require('electron');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
|
||||
/**
|
||||
* 可选:开一个 CDP 调试端口,方便用脚本截图/验证桌面窗口。
|
||||
*
|
||||
* 为什么需要:Electron 的界面只有真窗口才渲染得出来,光跑 curl 验不了;
|
||||
* 有了这个端口就能用 scripts/screenshot.mjs 附着上去截图(设 CDP_PORT 即可)。
|
||||
* 默认不开,避免平时多一个监听端口。
|
||||
*/
|
||||
if (process.env.DOUBAO_CDP_PORT) {
|
||||
app.commandLine.appendSwitch('remote-debugging-port', String(process.env.DOUBAO_CDP_PORT));
|
||||
app.commandLine.appendSwitch('remote-allow-origins', '*');
|
||||
}
|
||||
|
||||
// 打包后应用根目录是 resources/app(若打成 asar 则是 resources/app.asar);开发时是仓库根
|
||||
const appRoot = app.isPackaged
|
||||
? [
|
||||
path.join(process.resourcesPath, 'app'),
|
||||
path.join(process.resourcesPath, 'app.asar'),
|
||||
].find((p) => fs.existsSync(p)) || path.join(process.resourcesPath, 'app')
|
||||
: path.resolve(__dirname, '..');
|
||||
|
||||
// 打包后的自有资源放在 <appRoot>/runtime,开发时直接用仓库根
|
||||
const bundledRuntime = path.join(appRoot, 'runtime');
|
||||
const runtimeRoot = fs.existsSync(bundledRuntime) ? bundledRuntime : appRoot;
|
||||
|
||||
process.env.DOUBAO_RESOURCES = runtimeRoot;
|
||||
process.env.DOUBAO_TOOLS = path.join(runtimeRoot, 'tools');
|
||||
process.env.DOUBAO_DATA = path.join(app.getPath('userData'), 'data');
|
||||
|
||||
const serverEntry = path.join(appRoot, 'server', 'src', 'index.mjs');
|
||||
|
||||
// 给内核挂几个桌面能力钩子:定位配置文件、用系统浏览器打开链接、原生选文件、写剪贴板。
|
||||
// 内核自己不认识 Electron,有钩子就用,没有就降级。
|
||||
globalThis.__doubaoReveal = (target) => shell.showItemInFolder(target);
|
||||
globalThis.__doubaoOpenExternal = (url) => shell.openExternal(url);
|
||||
globalThis.__doubaoClipboard = (text) => clipboard.writeText(String(text));
|
||||
globalThis.__doubaoPickFile = async () => {
|
||||
const result = await dialog.showOpenDialog({
|
||||
title: '选择要发给豆包的文件',
|
||||
buttonLabel: '发送',
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
filters: [
|
||||
{
|
||||
name: '常用文件',
|
||||
extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'txt', 'md', 'json', 'csv',
|
||||
'log', 'yml', 'yaml', 'py', 'js', 'ts', 'tsx', 'html', 'css', 'pdf'],
|
||||
},
|
||||
{ name: '所有文件', extensions: ['*'] },
|
||||
],
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
};
|
||||
|
||||
let kernel = null;
|
||||
let win = null;
|
||||
|
||||
/** 启动内核:默认 5199,被占用就换随机端口 */
|
||||
async function startKernelWithFallback() {
|
||||
const { startKernel } = await import(pathToFileURL(serverEntry).href);
|
||||
const preferred = Number(process.env.DOUBAO_PORT || 5199);
|
||||
try {
|
||||
return await startKernel({ port: preferred, quiet: true });
|
||||
} catch (err) {
|
||||
if (err && err.code === 'EADDRINUSE') {
|
||||
console.warn(`[desktop] 端口 ${preferred} 被占用,改用随机端口`);
|
||||
return startKernel({ port: 0, quiet: true });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(url) {
|
||||
win = new BrowserWindow({
|
||||
width: 420,
|
||||
height: 900,
|
||||
minWidth: 360,
|
||||
minHeight: 620,
|
||||
title: '豆包',
|
||||
backgroundColor: '#ffffff',
|
||||
autoHideMenuBar: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
spellcheck: false,
|
||||
},
|
||||
});
|
||||
|
||||
// 界面是移动端比例,菜单栏只会碍事:去掉,改用快捷键
|
||||
Menu.setApplicationMenu(null);
|
||||
win.once('ready-to-show', () => win.show());
|
||||
|
||||
win.webContents.on('before-input-event', (event, input) => {
|
||||
const key = (input.key || '').toLowerCase();
|
||||
if (key === 'f12' || (input.control && input.shift && key === 'i')) {
|
||||
win.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
} else if (input.control && key === 'r') {
|
||||
win.webContents.reload();
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// 外链交给系统浏览器
|
||||
win.webContents.setWindowOpenHandler(({ url: target }) => {
|
||||
if (/^https?:/i.test(target)) shell.openExternal(target);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
win.webContents.on('will-navigate', (event, target) => {
|
||||
if (!target.startsWith(url)) {
|
||||
event.preventDefault();
|
||||
if (/^https?:/i.test(target)) shell.openExternal(target);
|
||||
}
|
||||
});
|
||||
|
||||
win.loadURL(`${url}?frame=0`);
|
||||
return win;
|
||||
}
|
||||
|
||||
// 只允许开一个实例,第二次启动就把已有窗口拉到前面
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', () => {
|
||||
if (win) {
|
||||
if (win.isMinimized()) win.restore();
|
||||
win.focus();
|
||||
}
|
||||
});
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
app.setAppUserModelId('com.doubao.lynxclone');
|
||||
try {
|
||||
kernel = await startKernelWithFallback();
|
||||
createWindow(kernel.url);
|
||||
console.log(`[desktop] 内核就绪:${kernel.url} 资源:${runtimeRoot}`);
|
||||
console.log(`[desktop] 数据目录:${process.env.DOUBAO_DATA}`);
|
||||
} catch (err) {
|
||||
dialog.showErrorBox('豆包启动失败', String((err && err.stack) || (err && err.message) || err));
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', async () => {
|
||||
try {
|
||||
if (kernel) await kernel.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
"""核对引擎和界面的算子表是否一致。
|
||||
|
||||
加算子时"只加一边"已经犯过好几次:
|
||||
· 引擎加了 gte/lte/and/or/xor/shl/shr,界面 OPS_UI 没加(用户"没看到大于等于")
|
||||
· 引擎有 neg/not,界面也选不到
|
||||
加完算子先跑它,别等用户发现。
|
||||
"""
|
||||
import os, re, sys
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(WS, 'android', 'kernel'))
|
||||
import meeting as M
|
||||
KT = os.path.join(WS, 'android', 'app', 'src', 'main', 'java',
|
||||
'com', 'doubao', 'lynxclone', 'ui', 'MeetingsScreen.kt')
|
||||
src = open(KT, encoding='utf-8').read()
|
||||
m = re.search(r'OPS_UI = listOf\((.*?)\n\s*\)', src, re.S)
|
||||
ui = set(re.findall(r'"(\w+)"\s+to\s+"', m.group(1))) if m else set()
|
||||
eng = {o[0] for o in M.OPS}
|
||||
sb = re.search(r'private fun opSpec\(key: String\)(.*?)private fun opLabel', src, re.S)
|
||||
ss = sb.group(1) if sb else ''
|
||||
spec = set(re.findall(r'"(\w+)"', ss))
|
||||
has_else = 'else ->' in ss
|
||||
miss_ui = sorted(eng - ui)
|
||||
miss_spec = [] if has_else else sorted(ui - spec)
|
||||
covered = sorted(ui - spec) if has_else else []
|
||||
extra = sorted(ui - eng)
|
||||
print(' 引擎 OPS %d 个' % len(eng))
|
||||
print(' 界面 OPS_UI %d 个' % len(ui))
|
||||
print(' 界面 opSpec %d 个%s' % (len(spec), '(有 else 兜底)' if has_else else ''))
|
||||
print(' %s 引擎有、界面选项里没有: %s' % ('X' if miss_ui else 'v', miss_ui or '无'))
|
||||
print(' %s 界面有选项、opSpec 没定义类型: %s' % ('X' if miss_spec else 'v', miss_spec or '无'))
|
||||
if covered:
|
||||
print(' (%s 由 else 兜底,正常)' % covered)
|
||||
print(' %s 界面有、引擎不认: %s' % ('X' if extra else 'v', extra or '无'))
|
||||
sys.exit(1 if (miss_ui or miss_spec or extra) else 0)
|
||||
@@ -1,90 +0,0 @@
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
NOTES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
|
||||
TOOL = {
|
||||
"name": "notes",
|
||||
"description": "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,action=search 关键词搜索。适合记录用户偏好、待办、结论。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["save", "list", "read", "search"], "description": "要做的操作"},
|
||||
"title": {"type": "string", "description": "save 时的标题"},
|
||||
"content": {"type": "string", "description": "save 时的正文"},
|
||||
"query": {"type": "string", "description": "search 时的关键词"},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def ensure_dir():
|
||||
os.makedirs(NOTES_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def slug(title):
|
||||
safe = re.sub(r'[\\/:*?"<>|\s]+', "-", title.strip())[:40]
|
||||
return safe or "note"
|
||||
|
||||
|
||||
def run(args):
|
||||
ensure_dir()
|
||||
action = str(args.get("action", "list")).lower()
|
||||
|
||||
if action == "save":
|
||||
title = str(args.get("title", "")).strip() or "未命名"
|
||||
content = str(args.get("content", ""))
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
path = os.path.join(NOTES_DIR, f"{stamp}-{slug(title)}.md")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(f"# {title}\n\n{content}\n")
|
||||
return {"saved": os.path.basename(path), "title": title, "chars": len(content)}
|
||||
|
||||
if action == "list":
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
items = []
|
||||
for name in files[:50]:
|
||||
full = os.path.join(NOTES_DIR, name)
|
||||
with open(full, encoding="utf-8") as fh:
|
||||
first = fh.readline().strip().lstrip("# ")
|
||||
items.append({"file": name, "title": first, "bytes": os.path.getsize(full)})
|
||||
return {"count": len(files), "notes": items}
|
||||
|
||||
if action == "read":
|
||||
name = str(args.get("title") or args.get("query") or "").strip()
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
hit = next((f for f in files if name and name in f), None)
|
||||
if not hit:
|
||||
return {"ok": False, "error": f"没找到匹配 {name} 的笔记"}
|
||||
with open(os.path.join(NOTES_DIR, hit), encoding="utf-8") as fh:
|
||||
return {"file": hit, "content": fh.read()[:4000]}
|
||||
|
||||
if action == "search":
|
||||
query = str(args.get("query", "")).strip()
|
||||
if not query:
|
||||
raise ValueError("search 需要 query")
|
||||
hits = []
|
||||
for name in sorted(os.listdir(NOTES_DIR), reverse=True):
|
||||
with open(os.path.join(NOTES_DIR, name), encoding="utf-8") as fh:
|
||||
text = fh.read()
|
||||
if query in text:
|
||||
idx = text.index(query)
|
||||
hits.append({"file": name, "excerpt": text[max(0, idx - 60): idx + 120]})
|
||||
if len(hits) >= 20:
|
||||
break
|
||||
return {"query": query, "hits": hits}
|
||||
|
||||
raise ValueError(f"不支持的 action: {action}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
227
web/index.html
@@ -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
108
豆鲍/.gitignore
vendored
Normal file
@@ -0,0 +1,108 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 依赖(几百 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/
|
||||
dist-ui/
|
||||
hs_err_pid*.log
|
||||
988
豆鲍/AGENTS.md
Normal file
@@ -0,0 +1,988 @@
|
||||
# 项目约定
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
|
||||
---
|
||||
|
||||
# 代码托管
|
||||
|
||||
## 两个 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`)
|
||||
都调它 —— 查看器的全部价值就是"所见即所发",别在别处再拼一遍。
|
||||
- **地点可见性用「在场区间」(v3.34 起),别再写成"只看当前地点"**:
|
||||
`place_engine.presence_intervals()` 给出"在哪个地点的哪几段 `[enter_seq, leave_seq)`",
|
||||
`chat_context.assemble` 按"消息 `seq` 落在区间里"判定可见 —— 换地点不会失忆,
|
||||
没去过 / 到达之前 / 离开之后的消息仍然看不到。`first_visit_seq`(第一次进入)
|
||||
是 v3.16 的旧机制,仍用于界面「回看」和当前地点的兜底(`app._conversation_for_client`),
|
||||
但 **AI 上下文只看区间**。改移动/位置逻辑要同步 `place_presence` 的开关区间
|
||||
(`place_engine.set_position` 是唯一实现处,别在 move/接口里另记)。
|
||||
- **记忆默认私有**(`agent_context.memory_scope`);共享板子要显式
|
||||
`memory_add(shared=true)`(`agent_context.shared_memory_scope`)。
|
||||
一次性迁移用 `agent.db` 的 `meta` 表记标记 —— **别写"每次启动都跑"的迁移**,
|
||||
它会把手写的新数据也搬走。
|
||||
- **记忆的"语义搜"(向量检索)已经有调研结论,动手前先看
|
||||
[`docs/记忆向量检索-调研.md`](docs/记忆向量检索-调研.md)**。三条最容易被带偏的:
|
||||
① **安卓上 sqlite-vec 用不了**(实测 Chaquopy 的 `sqlite3.Connection` 没有
|
||||
`enable_load_extension`,连 FTS5 也没编进去)——别照着网上的教程加扩展;
|
||||
② 方案是**纯 stdlib + SQLite BLOB**,向量存 `agent.db` 的派生表,零新依赖;
|
||||
③ 方舟 embedding 是 2048/2560 维,**纯暴力反而不够快**(真机 3000 条 479ms),
|
||||
条数多时用"符号位二值预筛(`int.bit_count()`)+ 精确重排",实测 ~20ms。
|
||||
- **独自一人的地点禁言**:内核 `place_engine.chat_guard()` 是权威,
|
||||
界面 `AppViewModel.alonePlaceName()` 只是提前拦截(数据可能旧)。
|
||||
- **函数里不要在"已经用过"之后才写局部 `import store`**:Python 会把该名字当成
|
||||
整个函数的局部变量,前面的用法直接 `UnboundLocalError`。真机报过
|
||||
「give_item 调用失败:cannot access local variable 'store'」——
|
||||
模块顶部已经 import 的,函数里就别再写;确有循环依赖要局部 import 的,
|
||||
放到函数**第一行**。改完内核跑 `probe-items` §12(有 give_item → 用户角色回归)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `android/nodekit/`**(独立模块)。
|
||||
节点类型、引脚、算子、配色、几何、形状**只有那一份** ——
|
||||
`MeetingsScreen.kt` 里**不要再写 `when (node.type)` 的长表**(默认标题、颜色、
|
||||
引脚、配置面板标题都从库查)。
|
||||
加一种节点看 [docs/节点库.md](docs/节点库.md) 的清单,改完跑
|
||||
`python scripts/verify-nodekit.py`(它会拿库和 Python 引擎逐项对拍)。
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`Ops.ALL` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
只改一半,用户会说"你不会举一反三的吗"。
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」),
|
||||
事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走
|
||||
`applyMeetingEvent`。
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
- **代码框不能软换行**。` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
就是语法。这个 Compose 版本(BOM 2024.09.03)的 `BasicTextField`
|
||||
经典重载选不中,所以用"把输入框塞进足够宽的横向滚动容器"来达到同样效果。
|
||||
- **代码框要有高度上限**。只写 `heightIn(min=...)` 的话,文件一长框就长到
|
||||
屏幕外,把底下的补全条顶出去,用户够不着。
|
||||
- **改了没生效就先怀疑工具**。PowerShell 的 `String.Replace` **匹配失败不报错**;
|
||||
按行号剪贴会算错下标(甚至把整个文件追加一遍);
|
||||
`git checkout -- <文件>` 会还原**这一轮所有未提交的改动**。
|
||||
改完立刻 grep 确认,动手前先断言下标有效。
|
||||
- **莫名其妙的"未解析引用"先数括号**。漏一个 `}` 会让后面所有顶层声明
|
||||
全部报未解析,错误信息看着完全不像是括号问题(报的是 `PrimaryButton`
|
||||
找不到这种)。
|
||||
|
||||
|
||||
## 品牌名(v3.17 起:小人间)
|
||||
|
||||
App 的对外显示名从「豆包」改成了「小人间」——这是**显示名**,不是包名/仓库名。
|
||||
|
||||
- **Android 显示名的唯一来源**:`android/app/src/main/res/values/strings.xml`
|
||||
的 `app_name`(桌面图标、最近任务、通知使用权列表都读它)。
|
||||
另有几处写死的自我介绍(抽屉标题、关于页、通知兜底标题、空态问候语),
|
||||
改名时一起 `grep -rn "小人间" android/app/src/main`。
|
||||
- **网页端**:`web/index.html`(title / boot-logo / favicon)、`web/js/app.js`
|
||||
(侧栏 logo、`setTitle`、关于入口)、`web/js/pages/about.js`(关于页标题/图标)。
|
||||
- **启动图标**:`python scripts/make-launcher-icon.py` 生成 legacy PNG;
|
||||
`res/mipmap-anydpi-v26/ic_launcher*.xml` 是自适应图标,前景/单色层在
|
||||
`res/drawable/ic_launcher_foreground.xml` / `ic_launcher_monochrome.xml`。
|
||||
几何数字是同一套 108 单位画布(安全区 21..87),改图标要两边一起改。
|
||||
- **通知小图标必须是单色剪影**(`res/drawable/ic_notify.xml`):
|
||||
自适应图标是 108dp 图层组合,直接 `setSmallIcon(applicationInfo.icon)`
|
||||
在部分机型上会渲成空白/黑块。
|
||||
- **没跟着改的**(仍用旧名,要换得单独迁移):包名 `com.doubao.lynxclone`、
|
||||
内核数据目录、仓库名「豆鲍」、桌面端 productName、内置角色「豆包」
|
||||
(那是角色名)、模型/语音服务商名(豆包 Pro / 豆包语音)。
|
||||
|
||||
## 决斗 / 状态 / 数值约定(v3.17 起;v3.18 武器;v3.19 换武器/无回合上限/四种结果;v3.29 数值也间接)
|
||||
|
||||
- **状态不能直接赋值**:AI 工具里**没有** `grant_status`(已删除)。
|
||||
状态只能由 ① 物品脚本 ② 世界脚本 ③ 用户手动 产生。
|
||||
加新的"能给状态"的通道时先想清楚:**它算不算开挂**(用户原话:
|
||||
「状态赋值只能是物品间接,不然先开挂一样」)。别把它加回 AI 工具表。
|
||||
- **数值也一样只能间接改(v3.29)**:用户原话「**数值也是间接改**」——
|
||||
AI 工具里**没有** `change_stat`(已删除)。数值只能由 ① 物品脚本
|
||||
(`api['change_stat']`)② 世界脚本 ③ 用户手动 改。加"能改数值"的 AI 工具
|
||||
等于开挂,别加;底层 `rule_engine.change` 保留(脚本/界面走它)。
|
||||
- **`give_item` 所有 AI 都能用,但只能"转移"、不能造物(v3.29)**:用户拍板
|
||||
「所有 AI 都可用 give_item」「不能 AI 自己创建物品」。
|
||||
- `give_item` 在默认工具表里(不按角色开关)——它把**自己背包里现有的**东西
|
||||
转给别人(`_find_bag_item` 先查自己身上有没有;没有/不够直接报错);
|
||||
- **AI 不能被授予"造物"能力**:物品产出只走 ① 物品脚本(`api['give_item']`,
|
||||
例如工作台带材料加工)② 世界/常驻角色规则 ③ 用户手动。别给 AI 加"凭空生成物品"
|
||||
的工具;`item_engine.grant` 只能由脚本/用户接口调用,别接到 AI 工具上;
|
||||
- 回归:`probe-items` §8(赠与)/§15(工具表 + **合计数量不变 = 只转移不造物**、
|
||||
背包没有的物品不能凭空给)、`probe-group-chat` §7(give_item 在表里)、
|
||||
`probe-context` §9(Skill 关键词)、`probe-rule-engine` §14–15(没有 change_stat)。
|
||||
- **决斗是多回合、绑对话、中断要双方同意,而且必须有武器**(v3.18):
|
||||
- 引擎在 `android/kernel/duel_engine.py`,表 `agent.db/duels`;
|
||||
- 一场决斗绑 `conversationId`(**不开新会话**,和私聊一样),聊天页有决斗条;
|
||||
- **武器 = 背包里的 `target` 类物品**(用户原话:「决斗必须要武器。没有target类物品
|
||||
的一方宣告失败」)。开局只有一方没有 → 那一方**当场判负**(`finished`、`round:0`,
|
||||
不调 `on_duel`);双方都没有 → 报错打不起来;武器用光/丢了 → 判负。
|
||||
判定只在 `duel_engine.weapons_of/_weapon_check` 里做,**别下放到脚本/界面**,
|
||||
也别给 AI 开"免武器决斗"的口子。武器列表进快照(`weapons` / `hasWeapon`),界面要显示;
|
||||
- **每回合双方各用自己的当前武器出手一次**(v3.19):内核替双方对"对方"调用
|
||||
`item_engine.use()` → 跑**这件物品自己的脚本**(`on_receive`),再按物品规则扣数量;
|
||||
`unlimited: true`(∞)的武器**不消耗**(用户原话:「有些武器不应该消耗比如拳头,木棍等」)。
|
||||
顺序固定:先双方武器出手 → 再调世界脚本;
|
||||
- **状态剩余轮数每回合 -1(v3.27)**:决斗每回合双方出完手后给两边
|
||||
`rule_engine.tick_statuses`(和聊天里"参与一轮 -1"同语义;persistent 不减)。
|
||||
以前整场不 tick:中毒(剩 3 轮)打到第 10 回合还写 3
|
||||
(用户反馈「状态不会随轮数减少 还有决斗也是」)。
|
||||
**状态脚本 `on_turn` 仍不在决斗里跑**(决斗的掉血/挂状态由世界+物品脚本裁决),
|
||||
这里只负责"剩余轮数过期"。
|
||||
- **每回合都能换武器**(用户原话「如何选择武器?」):`duel_engine.choose_weapon` /
|
||||
`POST /api/duels/<id>/weapon`;界面 `DuelScreen` 里点 chips 换。不选/用完了自动挑
|
||||
(优先 ∞ 不消耗的,其次背包第一件);
|
||||
- **没有回合上限**(用户原话「没有回合限制」):世界包 `info.duelMaxRounds` 作废,
|
||||
`api['max_rounds']` 恒为 0;决斗只在 ① `end_duel` ② 一方没武器 ③ 双方同意停手 时结束;
|
||||
- 世界脚本 `on_duel(initiator, target, api)` **每回合调用一次**,上下文有
|
||||
`api['round']` / `api['duel_id']` / `api['weapons']`;收尾调
|
||||
`api['end_duel']('结果文本', '赢家名字')` —— **只给结果不给赢家 = 平局**;
|
||||
- **四种结果状态**(用户原话「有输,赢,平局,停手,4种状态」):快照每方一个
|
||||
`outcome` = `win` / `lose` / `draw` / `stop`,界面显示成 **赢 / 输 / 平局 / 停手**。
|
||||
`interrupted`(双方同意罢手)→ 双方都是 `stop`;没武器判负 → 赢/输;双方同一回合
|
||||
都没武器 / 脚本没给赢家 → 平局;
|
||||
- 罢手必须对方同意:对方是 AI 时内核发一次单独的模型调用问它(失败按"同意"
|
||||
兜底,避免卡死);对方是用户角色时界面出「同意罢手 / 继续打」;
|
||||
- 客户端只在**界面层**推进回合/发起罢手,判定权在脚本和对方。
|
||||
- **界面入口**:聊天页**长按 @成员** →「私聊 / 决斗」二选一;
|
||||
决斗全屏页 `DuelScreen`(已在 `docs/界面总览.md` 登记,审计会检查),
|
||||
里面有「我的武器(每回合可换)」chips、四种结果状态的大字、无回合上限的回合文案。
|
||||
- **用户手动操作和 AI 同一条引擎**:`item_engine.use(...)`(使用/带材料 `with`/抛弃/赠与);
|
||||
v3.21 起用户手动使用也支持带材料(`POST /api/containers/<id>/items/action` 的 `with`),
|
||||
工作台这类物品脚本 `return False` 时**不能假装成功**(400 + 脚本旁白原因)。
|
||||
- **每回合只能用一件物品(v3.22)**:默认用当前武器攻击;也可选一件**被动物品**
|
||||
(`kind:'passive'`,如血瓶)→ 这回合跑它的 `on_use`、**不攻击**、武器不消耗;
|
||||
选择一次性(`duels.initiator_item/target_item`,推进后清空)。
|
||||
接口 `POST /api/duels/<id>/item`;快照 `passiveItems/item/action`;世界脚本 `api['items']`。
|
||||
- **AI 每回合调用工具出招(v3.26)**:用户参与时,`advance()` 每次会单独调一次 AI 那方
|
||||
(`_ask_ai_duel_action`,带人设/气血/武器/被动,要求它调用 **`duel_attack`**);
|
||||
工具 → `duel_engine.ai_take_action()` 真正跑 `item_engine.use()`,每回合一次;
|
||||
没调用/失败时**退回归自动出招**(日志写明),不能卡死决斗。
|
||||
这些内部问话必须传 `skip_round_scripts=True`(`agent_loop.run_agent` 新参数),
|
||||
否则问一句就触发每轮状态脚本/主动物品,出现额外扣血/加血。
|
||||
- **决斗对话(v3.24)**:`DuelScreen` 有对话框,用户说话 → `duel_engine.say()` 真的调一次
|
||||
**对手 AI**(`_duel_ai_reply`,带人设/气血/最近回合/原话;`emit` 必须给,否则
|
||||
`run_agent` 直接 TypeError 会被兜底吞掉);双方的话写进 `log` 的 `kind:'talk'` 条目 +
|
||||
追加到会话消息;**不推进回合、不改变胜负**。没配模型时 `replied:false` + 兜底文案。
|
||||
- **总裁脚本要写明失败者惩罚 / 胜利者奖励**(v3.21):`on_duel` 收尾时
|
||||
`api['die']`(或扣声望/掉物品/逐出等)+ `api['give_item']`/`change_stat`,
|
||||
再 `end_duel(结果文本, 赢家)`。死亡判负是内核底线;脚本赢家与死亡判定一致时,
|
||||
最终结果文案用脚本写的(含惩罚/奖励),`outcome` 仍按死亡算赢/输。
|
||||
- **别在双方还有气血/有武器时强行判负**(v3.27):用户反馈「明明有武器却判负」——
|
||||
旧测试世界脚本"第 3 回合按气血高下判负"已删掉;现在 `on_duel` 只在
|
||||
**真的有人气血 <= 0** 时才 `die` + 写惩罚/奖励,否则什么都不结束(没有回合上限)。
|
||||
测试世界的 `world.py` 是完整示范(气血归零 → 败者死亡 + 胜者铁剑/声望)。
|
||||
## 语音 / 朗读情绪指令约定(v3.27 起)
|
||||
|
||||
- 豆包语音合成 2.0(`volcv3` 引擎,`seed-tts-2.0`)的**语音指令** =
|
||||
`req_params.additions.context_texts`(控制台体验页写作 `[#指令]`,不朗读、不计费)。
|
||||
官方文档:《[语音指令与标签](https://docs.volcengine.com/docs/DoubaoVoice/DoubaoTextToSpeech20CapabilityIntroduction)》、
|
||||
《[单向流式 TTS 接口](https://www.volcengine.com/docs/6561/2534913)》(`additions.context_texts`)。
|
||||
★★ **`additions` 必须是 JSON 字符串**(不是对象):真机报过
|
||||
`code=55000000 ... req_params.additions of type string`;用 `_volc_v3_req_params()`
|
||||
统一组包,探针会用本地假服务抓真实请求体钉死格式。请求头带 `X-Api-Request-Id`。
|
||||
- **括号规则只有一套逻辑,但三处实现必须一致**(最多 60 字、不跨行、成对括号):
|
||||
- 内核 `speech.py` 的 `_STAGE_RE` / `prepare_speech`:朗读时不念括号、`volcv3` 变成
|
||||
`context_texts` 指令(`_volc_v3_additions`);
|
||||
- Android `MarkdownText.findStageEnd` + 设置 `stageTags`:界面灰色小字;
|
||||
- Web `chat.js` 的 `STAGE_RE` / `.markdown .stage-dir`:界面灰色小字。
|
||||
改规则时三处一起改,否则会出现"界面灰了、语音还念"的错位。
|
||||
- `/api/tts` 和 `/api/tts/stream` 的响应都带 `speakText`(已剥 Markdown、去掉括号旁白);
|
||||
客户端退回系统 TTS 时**念 speakText**,别念原始 `msg.content`。
|
||||
- 设置项 `speech.emotionTags`(默认 **true**,老配置没这一项也按开):
|
||||
关掉 = 老行为(括号照念、界面正常字号)。
|
||||
- Skill 同步:`defaults.py` 的 `BUILTIN_SKILL` 有「语音·情绪指令」段(模型靠它学会写
|
||||
括号);跑 `probe-context` §9 和 `probe-agent-system` §16 验证。
|
||||
|
||||
- **用户角色死亡 = 这一局游戏结束(v3.27)**:用户反馈「用户角色死亡为啥还能说话,
|
||||
直接宣布这个容器游戏结束」。
|
||||
- `store.containers_with_names()` 给容器加**派生字段** `gameOver` / `gameOverText`
|
||||
(= `agentdb.is_dead('user', cid)`,不落库;复活后自动 false,不误伤单聊容器);
|
||||
- 内核 `_perform_chat` **两处**拦:发起前 + 世界脚本 `on_turn` 跑完后(不写用户消息、
|
||||
不花 token、不生成回复,`error.code = "game_over"`);`/api/session-message` 也拦;
|
||||
`context_preview` 的 `chat.blocked` 同步 `game_over`;
|
||||
- 界面:聊天页输入框换成「🏁 游戏结束」横幅 +「复活 ›」(`GameOverBar`),
|
||||
容器列表给这局打「已结束」标签;复活走 `AppViewModel.reviveUserIn(cid)`;
|
||||
- 探针:`probe-context` §8.5(_perform_chat 拦截/不调模型/不落库/查看器/复活恢复)、
|
||||
`probe-test-world` §10.5(`GET /api/containers` 的 gameOver 派生字段)。
|
||||
- **用户角色状态也按轮递减(v3.27)**:`_perform_chat` 生成后除了发言的 AI,还给
|
||||
`'user'` tick 一次(仅 `not auto_continue`,群聊自动续轮不算用户参与)——
|
||||
以前用户身上的「中毒(剩 3 轮)」永远停在 3(用户反馈「状态不会随轮数减少」)。
|
||||
|
||||
## 死亡 / 每轮脚本约定(v3.20 起)
|
||||
|
||||
- **不新造"每角色脚本"系统**:用户问「角色/用户角色每轮开始前都可以执行一个脚本」
|
||||
—— 现成机制就是**世界脚本 `on_turn`**(每轮开始前跑、能读数值),循环
|
||||
`api['agents']()` + `api['user']()` 即可覆盖每个角色;状态脚本 `on_turn`
|
||||
是"每个角色各跑"的另一条既有通道。用户明确说「有类似机制可以不用写免得造轮子」,
|
||||
别为这个再加一套 agent/container 脚本字段。
|
||||
- **死亡 = 情绪档位「死亡」**(`agentdb.emotion_set/is_dead`),和界面禁言、立绘、
|
||||
复活是同一套数据。世界脚本新增 `api['die'](谁, 遗言='')` / `revive` / `is_dead`
|
||||
三个动作(`world_engine._api`),AI 侧**没有**新工具(AI 仍不能自己复活)。
|
||||
- **数值支持 `initial`**(`rule_engine` / `agentdb.stat_defs.initial_value`):
|
||||
气血这种不能从 0 起步的数值写 `initial`;不写仍按 min(老世界行为不变)。
|
||||
测试世界「气血 0-100 initial 100」+ `on_turn` 判 `气血 <= 0 → die`。
|
||||
- **决斗中死亡 = 判负(底线)**:`duel_engine` 每回合结算后查双方 `agentdb.is_dead`:
|
||||
死的那一方立刻 `finished` + 判负(赢/输 outcome),双方同回合都死 → 平局;
|
||||
已死亡不能发起/接受决斗(400);快照每方 `dead` 布尔,界面显示。
|
||||
别把"判死"写进界面或模型(判定只在内核/世界脚本)。
|
||||
- **用户角色也会死**:档案 `GET /api/containers/<id>/user-profile` 带
|
||||
`emotion`/`dead`;复活走 `POST /api/containers/<id>/user-emotion {preset}`;
|
||||
界面「我的角色」页有死亡卡 + 「复活」按钮。AI 复活仍走「记忆 → 情绪」。
|
||||
- **情绪/立绘显示必须按当前容器(v3.22 假死修复)**:`/api/state` 的
|
||||
`containerEmotions` / `containerPortraits` 按 `containerId` 分;
|
||||
App 用 `AppViewModel.emotionOf()/portraitOf()`(内部按 activeConversation 的容器选),
|
||||
**不要读** `state.emotions`(那是智能体默认容器,会把 A 局的死亡带到 B 局)。
|
||||
保存情绪 `PUT /api/agents/<id>/emotion` 必须带 `containerId`
|
||||
(`MemoryScreen` 用 `memoryContainerId`),否则写到默认容器 = 假死/复活无效。
|
||||
|
||||
## 客户端 HTTP / 地图移动约定(v3.28 起)
|
||||
|
||||
- **Android `KernelClient.call()`:HTTP >= 400 必须抛 `KernelException`**
|
||||
(和 Web `web/js/api.js` 的 `request()` 保持一致)。
|
||||
内核的**失败响应用 4xx**(`{"ok":false,"error":"人话"}`);
|
||||
`HTTP 200 + ok:false` 只留给"软失败"(TTS 退回系统引擎、模型测试 fallback 等),
|
||||
由调用方自己看 `ok` —— **不要**用 200+ok:false 表示"操作失败"。
|
||||
真机踩过(用户原话「移动地点后全乱了:无法移动,无法移人」):
|
||||
旧 `call()` 不看状态码,地图「移人」被内核 400 拒绝后,错误 JSON 被解析成
|
||||
**一张空地图**(页面显示「这一局还没有地图」)还弹「移过去了」;
|
||||
「去这里」则吞掉异常继续切地点对话,位置却没动 —— 位置和对话对不上。
|
||||
验收:`probe-map` §7 钉住"移动失败必须回 400"。
|
||||
- **地图页的移动/切地点以 `mapContainerId` 为准**,不要用"当前会话的容器"——
|
||||
两者可以不是一局(容器列表里点「地图」看 A 局时,聊天还停在 B 局;
|
||||
以前"去这里"会把用户移到 B 局,A 局地图纹丝不动)。
|
||||
统一入口 `AppViewModel.switchPlace(placeId, containerId, alreadyMoved)`:
|
||||
移动失败(不相邻)→ 提示原因并**留在原地**,绝不能继续切对话;
|
||||
从容器列表切进对话要 `showContainers = false`、从「我的角色」页移动要
|
||||
`userItemsOpen = false`,否则对话在浮层下面、看着像没反应。
|
||||
- **移动失败要保持原地图数据**:别把失败响应当新地图覆盖 `mapData`
|
||||
(`MapData` 解析失败会得到空 places,界面直接变成"这一局还没有地图")。
|
||||
|
||||
|
||||
## 常驻角色 / 全定义 id 化约定(v3.30 起)
|
||||
|
||||
- **常驻角色和世界包耦合,不做单独的「角色包」**(用户原话「合在一个世界包里,不要搞别的包
|
||||
因为常驻角色和世界是耦合在一起的」)。类定义进 `worldInfo.json` 的
|
||||
`residentClasses[]`,预召唤实例进 `residents[]`,功能点写在这个类的脚本的
|
||||
`FUNCTIONS` 清单里;脚本文件存在世界包 `scripts/` 里。
|
||||
- **功能清单必须是字面量**(内核 AST 解析、不执行脚本)。一个功能 = 清单一条 + 同名函数
|
||||
`def <id>(api, caller, ...)`;参数类型只支持 `string/int/number/bool/enum/array`
|
||||
(同一份 schema 同时给 AI 工具、界面表单、文档用)。改这里必须同步:
|
||||
`resident_engine.parse_functions`、编辑器 `doubao_project` 校验、文档附录 J。
|
||||
- **三个调用通道共用 `resident_engine.call()`**:AI 工具
|
||||
`resident_<类id>_<功能id>`、界面 `POST /api/containers/<cid>/residents/<iid>/call`、
|
||||
脚本 `api['summon']` / `api['dismiss']`。**caller 由通道决定,AI 不能冒充用户**;
|
||||
AI 花自己的背包/数值,用户操作必须用户自己在界面点。
|
||||
- **AI 工具按"这一局"静态生成、地点/权限在调用时校验**(不是按地点过滤工具表)——
|
||||
工具表一局内不变才不会破坏模型上下文缓存。同类多实例自动加 `instance` 枚举参数。
|
||||
- **常驻角色工具是动态的**,不在固定工具表里(v3.32 起固定工具 20 个:18 + 地点两个);
|
||||
`audience`(ai/user/both)和
|
||||
`hidden` 决定可见性。AI **没有召唤**工具;只有类上标了 `dismissible: true` 才生成
|
||||
`resident_<类id>_dismiss`(默认没有,见下面「常驻角色会离开」)。
|
||||
- **输出统一信封**:`{ok, message, data, note}`,`message` 必须是"AI 能照说的人话结果";
|
||||
业务失败 `raise ValueError("原因")`,内核转 `ok:false`。**先校验、后副作用**——
|
||||
脚本中途报错不会回滚,钱/物品可能已经动了。
|
||||
- **界面入口是聊天输入框打 `>`**(或输入条右侧 `>`)→ 角色菜单 → 功能菜单 →
|
||||
全屏 HTML(内核生成、同源页面、调同一个 call 接口)。AI 用 `show_ui` 写的任意 HTML
|
||||
**拿不到**常驻角色的功能接口(只有 pick/close)——防止 AI 自己写页面绕过工具限制。
|
||||
- 用户界面操作结果进「待回传队列」(复用 `store.add_pending_ui`),AI 下一轮能看到;
|
||||
改这条链路时同步 `probe-residents` §6。
|
||||
- **新界面要登记 `docs/界面总览.md` 并跑 `audit-ui-tree`**:
|
||||
`[常驻角色菜单]` / `[常驻角色功能]` / `[常驻角色功能页]` 三节,
|
||||
`ResidentPageScreen` 已在 `SCREENS` 对照表里。
|
||||
|
||||
- **数值/状态/物品/地点/世界/常驻角色全部 id 化(v3.30)**:用户原话
|
||||
「数值物品状态世界全部id化(脚本可读名字也可读id)」。
|
||||
- `stats[].id` / `statuses[].id` 可选,**不写 = 用 name**(老包零改动);
|
||||
物品/地点本来就有 id;世界包有资源 id;常驻角色类/实例有 id;
|
||||
- 脚本/工具/AI 里的"谁、数值名、状态名、物品名、地点名"**先按 id 找、再按名字找**
|
||||
(`rule_engine.resolve_stat / resolve_status`、`item_engine.resolve_def`、
|
||||
`place_engine.resolve_place`、`resident_engine.find_instances`);
|
||||
- 存库的键用 **id**:`statDefs/statusDefs` 有 `def_id` 列,`stat_values` /
|
||||
`status_instances` 的 name 列存 id;老数据 id=name 不用迁移。
|
||||
定义里新加 id 时 `sync_defs` 会把同名老值搬过去,**之后改 id 不会再搬**;
|
||||
- 世界脚本 api 新增 `world_id` / `world_name`(`pack_id` 保留);物品脚本新增
|
||||
`item`(正在用的物品定义)、`place_of()`、`summon/dismiss/residents`、
|
||||
`world_id` / `world_name`;
|
||||
- 回归:`probe-residents` §11(id/名字双解析、HTTP 按 id 设值/挂状态)、
|
||||
`probe-rule-engine`、`probe-test-world`。
|
||||
- **旧都市世界包是常驻角色的验收样板**:`scripts/worlds/old-city/`(源)+
|
||||
`scripts/worlds/旧都市.zip` + App 内置 `assets/worlds/old-city.zip`;
|
||||
改完跑 `python scripts/build-old-city-world.py`(会同步 App 内置包)并跑
|
||||
`probe-residents.py` §10。**v3.32 起它也是世界 Skill + 角色槽位的展示样板**
|
||||
(`skills` 1 条 + `slots` 3 个:主角位=老街 / 商店店员位=商店 / 住户位=用户角色@家·客厅);
|
||||
改槽位后同样要重建 zip + 内置包。
|
||||
- **旧都市的地图相邻关系(用户要求)**:老街 `street` / 小卖铺 `kiosk` / 商店 `store` /
|
||||
学校·校门 `school` **四个地点两两相邻**(地图上这四点之间六条线全连;任意两个直接走),
|
||||
其余(家两间、学校↔教室/操场、森林路口↔森林深处)不变。
|
||||
改完要重新生成 zip + App 内置包;**已导入的旧包不会自动更新**,要在
|
||||
「世界包 → 示例包 → 旧都市」重新导入并新建一局才看得到。
|
||||
回归:`probe-residents` §10(城镇四地点两两相邻)+ `probe-map` §9(连线去重)。
|
||||
- **界面 `>` 菜单按用户当前地点过滤(v3.30 体验修复)**:只列同地点 + 不绑地点
|
||||
(`place=''` = 全图可找)的常驻角色,避免"在家看到商店/森林的常驻角色、点进去只会
|
||||
先过去才能办事"。`GET /api/containers/<cid>/residents` 返回 `placeId/placeName/
|
||||
elsewhere/hint`;空菜单时 UI 显示 `hint`("这里没有、别的地点还有 N 个,先移动过去")。
|
||||
AI 工具表**不按地点过滤**(按局静态、调用时校验),两条规则别搞混。
|
||||
回归:`probe-residents` §6(同地点只列售货员 / 回家菜单空+提示)、§10(旧都市)。
|
||||
- **常驻角色会离开(v3.30)**:脚本 `api['dismiss_me']()` 让自己走(外卖员送完、
|
||||
解谜后消失);类上 `dismissible: true` 才生成 AI 工具 `resident_<类id>_dismiss`
|
||||
(同一地点才能请走,默认关闭)。功能信封带 `dismissed: true` + `note` 告诉 AI
|
||||
"别再找它";走后菜单/工具里都不会再出现,要它回来按世界规则重新召唤。
|
||||
回归:`probe-residents` §6b(自己走 / AI 工具 / 隔空拒绝)+ §10 旧都市
|
||||
(外卖送完 `dismiss_me`、`resident_delivery_dismiss`)。
|
||||
- **独自一人的地点:不能聊天 ≠ 不能交互(v3.30)**:`place_engine.chat_guard` 只拦
|
||||
聊天;`>` 常驻角色接口不受影响。聊天页禁言条里必须有「找常驻角色 ›」入口,
|
||||
否则用户在有常驻角色、没 AI 角色的地点会以为整个界面废了。
|
||||
回归:`probe-residents` §10(森林深处 chat_guard=false 但守林人可调)。
|
||||
- **世界容器(一局)只认成员(v3.30)**:用户反馈「这容器都没选豆包,豆包咋会出现在
|
||||
这里」。三条必须同时守住:
|
||||
1. 内核 `/api/conversations` POST:世界容器里给非成员开对话 / 群拉非成员 → 400;
|
||||
2. `app.py` rebase(换智能体另起会话):**本局成员才继承容器**,非成员回它自己的
|
||||
默认容器,并用 `rebased.message` 告诉界面原因;
|
||||
3. 客户端:`useAgent` 切到非成员时立即开它的默认容器会话;地点对话的主人必须从
|
||||
容器成员里选(不能拿 activeAgent 硬塞)。
|
||||
回归:`probe-containers` §12(成员/非成员开对话、群拉人、加群成员、rebase 事件)。
|
||||
- **图形地图(v3.31)**:地图 = **内核生成的 HTML 页**(`GET /api/containers/<cid>/map/page`,
|
||||
安卓 `MapScreen` 全屏 WebView 打开),不是 Compose 画的列表。世界包定义:
|
||||
`places[].x/y`(0-100 百分比)+ `places[].region`;`info.map` 里 `background/width/
|
||||
height/marker/css/regions[]`。**连线自动由 `places[].exits` 生成**(双向去重),
|
||||
不要另写一份。交互:双指缩放/拖动、点区域框放大、点地点「去这里/移人」、
|
||||
**长按地点或区域弹信息**(`bindLongPress` + `showPlaceInfo`)。
|
||||
背景图随包 `assets/` 导入(`_save_map_background` 落盘成绝对路径)并在导出时
|
||||
打回 zip(`_pack_one_asset`)。回归:`probe-map` §9(坐标/区域/连线去重/HTML 关键
|
||||
元素/长按/缩放/CSS 注入/节点几何/面板高度)+ `probe-residents` §10(旧都市地图背景随包导入/导出)。
|
||||
- **地图页的两条几何铁律(v3.31 修复,别再回归)**:
|
||||
1. **连线端点 = 圆点圆心**:`.map-node` 盒子**只有圆点那么大**(圆心 = `places[].x/y`),
|
||||
名字用绝对定位挂在下面;`#edges` 必须是 `#stage` 的第一个子元素(线在圆点下层)。
|
||||
曾经把节点做成"圆点+文字整列居中"、把连线 append 到节点之后 —— 用户看到
|
||||
"连线端点掉到圆点底下 / 线盖在圆点上";
|
||||
2. **信息面板竖直居中、高度随内容**,高度**用 JS `innerHeight` 算像素**,别用 `vh`(见下条)。
|
||||
- **★★ 安卓 WebView 的 `vh` / 视口百分比高度可能是 0**(真机实测:Chrome/146 WebView
|
||||
里 `10vh` → **0px**,`max-height:74vh` 也是 0px —— 地图信息面板因此被压成一条
|
||||
44px 横条,用户反复反馈"面板太矮/太低"的根因)。内核生成的 HTML 页面里
|
||||
**不要用 `vh` / 百分比高度**控制高度;要限高就用 JS
|
||||
`Math.round(window.innerHeight * 比例) + 'px'` 设行内样式(地图页 `sheetMaxHeight()`、
|
||||
常驻角色功能页 `max-height:260px` 都是这么处理的)。`MapScreen` / `ResidentPageScreen`
|
||||
另外开了 `settings.useWideViewPort = true`(别再关 overview 缩放那一半:地图舞台
|
||||
不能整体缩放),但页面里的 JS 兜底必须保留。回归:`probe-map` §9(断言页面里有
|
||||
`sheet.style.maxHeight = sheetMaxHeight()`)、`probe-residents` §5(断言功能页没有 `40vh`)。
|
||||
- **改地图不要动移动/邻接规则**:`place_engine.move` 的 exits 校验、用户/AI 位置、
|
||||
地点对话频道都保持原样;地图页只是"看 + 点"的壳,移动仍走
|
||||
`POST /api/containers/<cid>/move`(页面里 fetch 同一接口,成功后 JS 桥
|
||||
`Doubao.moved` 让 App 切到该地点对话,`alreadyMoved=true` 不能再移一次)。
|
||||
|
||||
## 世界 Skill / 角色槽位 / 地点工具(v3.32 起)
|
||||
|
||||
- **世界包角色 Skill 分两层**(用户原话「世界包角色 skill 包括:总体世界 skill,
|
||||
槽位独立 skill」):
|
||||
- **总体世界 skill**:`worldInfo.json` 的 `info.skills[]`(`{id?,name,content}`)——
|
||||
**自动加载**:容器绑了这个世界包,这一局**每个 AI** 的 `<skills>` 段都会带上
|
||||
(`【世界·名字】`),**不用**用户手动绑定到智能体;
|
||||
- **槽位独立 skill**:`info.slots[].skills[]`——只有坐在那个槽位的人有
|
||||
(`【槽位·槽位名·skill名】`)。
|
||||
- 拼装只有一份:`agent_context.build_skills(agent, container)` → `slot_engine.skills_of`。
|
||||
- **角色槽位**(`info.slots[]`):`{id,name,place,user,prompt,skills[],items[]}`,
|
||||
一套"出生配置":出生地点 / 追加初始物品 / 独立 skill / 注入提示词。
|
||||
- 分配**落库**在容器的 `slotAssignments`(`{槽位id: "user"/智能体id}`),
|
||||
`slot_engine.ensure_assignments` 负责补/清:先给 `user:true` 的槽位分配用户角色,
|
||||
其余按世界包顺序分给成员;**已有分配不改**(身份/提示词不能悄悄变);
|
||||
**槽位满了以后加入的人按世界包默认配置**(默认出生点 / 只有全世界 `initial` 物品 /
|
||||
没有槽位 prompt 和 skill)——不是"加不进来"。
|
||||
- 生效点:出生点走 `slot_engine.ensure_position_for`(`place_engine.ensure_container_positions`
|
||||
内部也用它);槽位物品走 `ensure_slot_items`(新表 `slot_item_init` 幂等,和
|
||||
`item_init` 分开:一个人可能先后坐过不同槽位);提示词是新段 `<slot>`
|
||||
(用户槽位的 prompt 进 `<user>` 段)。
|
||||
- **★ 槽位物品发放顺序**:必须先 `item_engine.ensure_initial`(全世界 initial)
|
||||
再 grant 槽位追加物品。顺序反了 `_write(初始数量)` 会把槽位物品**覆盖掉**
|
||||
(用户角色 initial 本来就要等第一次读背包才发)——症状是"槽位物品消失"。
|
||||
- 显式改分配:容器 `PATCH` 带 `slotAssignments`(整表替换,内核校验槽位存在 /
|
||||
本局成员 / 最多一个 `"user"`);查当前分配:`GET /api/containers/<cid>/slots`。
|
||||
- 世界脚本读槽位:`api['slots']()`(全部槽位 + occupant)/ `api['slot_of'](谁)`
|
||||
(id / 名字 / 「用户」都能查,没坐槽位返回 None)。结构见 `slot_engine.script_slots`。
|
||||
- **AI 查地点 / 相邻关系**(用户要求「ai可以调用工具获取所有地点和相邻关系」):
|
||||
新工具 `list_places`(全部地点 + 各自 exits + 当前位置)和 `list_place_links`
|
||||
(双向去重的两两相邻 + `exits` 为空的自由移动地点)。和 `move_to` 同一条路:
|
||||
没绑世界包 / 没地点时**报错**,不返回空表。**加/改地点工具要同步
|
||||
`defaults.BUILTIN_SKILL` 的【地点】段**(否则模型不知道有这个工具)。
|
||||
- **编辑器 schema 是唯一真源**:`android/kernel/doubao_project.py` 的
|
||||
`info.skills` / `info.slots` 两段 + `normalize_world_skill` / `normalize_slot` +
|
||||
`validate_project` 的 4 类 warning。改字段要同时改内核 `slot_engine` 解析和
|
||||
`docs/world-script-api/world.md`。
|
||||
- 回归:`scripts/probe-slots.py`(自动分配 / 槽位出生点 / 物品叠加 / prompt/skill
|
||||
注入 / 世界脚本 api / 两个地点工具 / PATCH 校验 / 导出导入 / 槽位满加人)。
|
||||
|
||||
## 移动 / 位置 / 地点动态 / 群发 / 空回复(v3.33 起)
|
||||
|
||||
- **`move_to` 可以带人**(用户要求「move_to 工具可以带上别的角色(包括用户角色)」):
|
||||
`move_to(place=..., others=[名字/id...])`。只能带**和你在同一地点**的人(含用户角色
|
||||
「用户」/用户名),先全部校验再一起移动;不合格整次不动。
|
||||
- 统一入口 `place_engine.move(..., others=..., moved_by=...)`;`moved_by='user'`
|
||||
表示用户在地图上移人(见 `agent_api._container_move`)。
|
||||
- 被带的人也会触发世界脚本 `on_enter`;回执里 `movedOthers` 要能说出谁跟来了。
|
||||
- **地点动态(谁进谁出)**:所有移动都必须走 `place_engine.move` —— 通知在**那里**
|
||||
统一记(`_notify_move_batch` → `agentdb.place_notes`),不要在工具/接口里各记一份:
|
||||
- 原地点的人看到「X 离开了这里(去了 Y)」;目的地的人看到「X 来了(从 Y)」;
|
||||
- 用户移人时,被移的 AI 看到「用户把你移到了 Y」;
|
||||
- 带人走时,被带的人看到「X 带你一起到了 Y」。
|
||||
提示词里是新段 `<place_events>`(`agent_context.build_place_events`)。
|
||||
**真对话读完即清**:`agent_loop` 给 build_system_prompt 的 settings 副本带
|
||||
`_consumePlaceNotes=True`;上下文查看器**不消费**(看得到同一条、不吃掉模型提示)。
|
||||
别在别处清 `place_notes`,否则"查看器一看,模型就永远看不到了"。
|
||||
- **进错地点的对话不准说话**(用户要求「用户进入其他地方地点的对话是不准对话」):
|
||||
`chat_guard` 两道判定、顺序固定 —— ① 会话 `placeId` ≠ 用户当前位置 → `wrong_place`
|
||||
("你不在这里,说不了话");② 用户所在地点没有任何 AI 成员 → `alone_place`。
|
||||
判定只在内核(`_perform_chat` / `context_preview.chat.blocked` 同一份),
|
||||
客户端别自己另算一遍。
|
||||
- **用户群发 = 一条消息 @多个人**(用户原话「用户也可以群发信息」「用户多选要对话
|
||||
的角色:例如 @aa @bb」):`AppViewModel.send()` 从用户文本里解析 `@名字`
|
||||
(只认本群成员、按**出现顺序**、按名字长度从长到短匹配并检查边界),
|
||||
`@` 了 2 个以上 → 第一个先答,其余进 `broadcastQueue`,`runChat` 的 `finally`
|
||||
用 `auto=true, forceSpeaker=next` 依次续轮(每人各回一句)。
|
||||
**内核不需要 broadcast 参数**,别在内核里再造一个循环;普通发消息/点停止会清空队列,
|
||||
私聊不继承队列。
|
||||
- **同地点看得见工具动作(v3.33)**:用户原话「角色用了工具同地点的角色也能知道」。
|
||||
在 `tools_runtime.execute_tool` 里统一做(所有 AI 工具唯一入口,新工具不会漏):
|
||||
`_ACTION_NOTES` 覆盖 `use_item` / `use_item_on` / `drop_item` / `give_item` /
|
||||
`start_duel` / `duel_attack` / `request_stop_duel`,以及所有 `resident_*`(只写"找常驻
|
||||
角色办了件事");成功后调 `place_engine.note_action`,给**同一地点**的其他 AI 成员
|
||||
记一条地点动态。记忆/情绪/查询类**不记**(内心活动,不是动作)。
|
||||
工具动作通知失败必须吞掉,不能影响工具结果。
|
||||
- **空回复不落库**(用户反馈「有时 ai 会回复...然后停止」):根因是模型只调工具/
|
||||
流被截断,`answer` 为空时仍存了一条空 assistant,界面渲染成「…」。
|
||||
现在两层:`agent_loop` 轮次用尽且正文为空 → **补问一次"只输出正文、不要工具"**;
|
||||
`app.py` 若仍为空 → **不 append 消息**,emit `error.code='empty_reply'`;
|
||||
`AppViewModel` finally 里把本地空气泡移除并提示。别再存 content 为空的
|
||||
assistant 消息(会让界面永远停在「…」)。
|
||||
- **顶栏地图重复打开会失灵(v3.33 修复)**:`MapScreen` 的 WebView 现在
|
||||
`onRelease` 里 `loadUrl("about:blank")` + `removeJavascriptInterface` + `destroy()`,
|
||||
并且 `openMap` 的 URL 带 `?t=<时间戳>`(内核路由会剥 query)。以前反复开关
|
||||
会泄漏一堆 WebView,第二次打开白屏/按钮没反应。
|
||||
- **AI 查位置**:新工具 `list_characters`(21 个固定工具了)—— 每个成员/用户/常驻角色
|
||||
的 `placeId/placeName/here`。加/改这类工具要同步 `defaults.BUILTIN_SKILL` 的
|
||||
【地点】段(写"什么时候用",别重复工具 description)。
|
||||
- 回归:`probe-slots` §11(带人/位置/wrong_place/地点动态/空回复)、`probe-context` §4
|
||||
(wrong_place + alone_place 两道)、`probe-items` §15 / `probe-group-chat` §7(工具数 21)。
|
||||
|
||||
## 换地点不失忆(v3.34 起)
|
||||
|
||||
- **问题**(用户原话):「角色之前的上下文应该保留而不是切换地点而隐藏,不然角色一换
|
||||
地点就失忆」。以前读历史只用"当前地点 + 首次进入",角色从客栈走到长街,客栈里刚
|
||||
聊过的暗号/约定立刻从上下文消失 —— 换个地方就像换了个人。
|
||||
- **正确语义 = 记得自己当时在场的事**(不是"只看当前地点"):
|
||||
- `agent.db/place_presence` 记每次进入的在场区间 `[enter_seq, leave_seq)`,
|
||||
`leave_seq=0` = 还在那里(延续到现在);同一地点可以有多段(离开又回来);
|
||||
- **唯一写入口**:`place_engine.set_position`(换地点时闭合旧区间、开新区间),
|
||||
`move` / 用户地图移人 / 槽位出生点全都走它 —— 别在别处另记一份;
|
||||
- **唯一读入口**:`place_engine.presence_intervals(cid, aid)`;
|
||||
`chat_context.assemble` 按"消息 `seq` 是否落在区间里"判定可见;
|
||||
- 当前地点 / 没去过 / 到达之前 / 离开之后 分别给 reason:
|
||||
`place`(没去过)/ `enter`(到达之前)/ `left`(离开之后)—— 上下文查看器
|
||||
和 `ContextViewerScreen` 的标签要一起改(别只改内核)。
|
||||
- 界面上的「地点 = 对话频道」**不变**(`app._conversation_for_client` 仍按
|
||||
`first_visit_seq` 过滤显示);变的只是**送进模型的上下文**。
|
||||
- **老数据回填**:`place_engine._backfill_presence_once()` —— 用 `meta` 记
|
||||
`place_presence_backfilled_v334`,**只跑一次**(升级后)。规则:当前地点
|
||||
`[first_seq, ∞)`,其他去过的地点 `[first_seq, 现在)`(升级后那里新发生的事不会
|
||||
再漏进来)。另外 `_backfill_presence_pair(cid, aid)` 给"有位置、没区间"的
|
||||
单个角色补(导入的老备份 / 漏记),幂等;别写成"每次启动都全量跑",
|
||||
否则真实移动记录会被重复追加区间。
|
||||
- **上下文查看器**(`context_preview`)新增 summary:`keptOtherPlaces`(跨地点保留条数)、
|
||||
`rememberedPlaces`(记得几个地点)、`droppedLeft`;概览显示「换地点没失忆 ·
|
||||
另一地点经历过的 N 条也带进来了」。
|
||||
- **内置 Skill**:`defaults.BUILTIN_SKILL` 的【地点】段要写明"换地点不会失忆,
|
||||
但没去过/离开之后看不到"(模型据此别说"我忘了")。
|
||||
- 回归:`scripts/probe-context.py` §3(没去过 / 离开之后隔离,reason=place/left)、
|
||||
§3.5(换地点后客栈暗号还在、`keptOtherPlaces>0`、查看器提示)、§8(查看器 label)、
|
||||
§9(Skill 关键词「不会失忆」);`probe-map` §6/§8 仍走旧的界面过滤,不该受影响。
|
||||
|
||||
## 决斗结果进地点动态(v3.35 起)
|
||||
|
||||
- **用户要求**:「决斗结束后要在地点动态中写明结果多少回合」。以前决斗结果只存在
|
||||
`duels` 表/日志里 —— 界面上能看到,但**角色(尤其 AI 对 AI 的双方)在聊天上下文里
|
||||
没有任何"这场架谁赢了、打了多久"**。现在结束时会写一条地点动态。
|
||||
- **写在哪 / 谁收到**:`duel_engine._note_duel_result()` → `place_engine.note_place_event()`
|
||||
→ `agentdb.place_notes`,只给**决斗记录 `place_id` 这个地点的 AI 成员**记
|
||||
(用户没有提示词;参战双方也收 —— AI 对 AI 时这是它们唯一的结果记忆)。
|
||||
文本:`「A」和「B」的决斗结束了:{获胜/平局/双方停手}(共 N 回合)。`
|
||||
- **什么时候写**:只在 `_write_log_and_finish()` 里、状态**真的从**
|
||||
`active` / `stop_pending` 变成 `finished` / `interrupted` 时写(防止重复/无关更新)。
|
||||
所以脚本 `end_duel`、死亡判负、没武器判负、双方同意停手**所有结束路径都覆盖**;
|
||||
开局就判负(round=0)写「0 回合(还没开打)」;脚本出错"中止"写「中止」。
|
||||
- **地点用记录里的 `place_id`**,不是参战者"现在"的位置 —— 打完被移走/死亡不影响。
|
||||
- **回归**:`scripts/probe-duel.py` §3.5(结束→动态有结果+共 2 回合、`<place_events>`
|
||||
真的带上、双方都收到)、§4(停手→「双方停手(共 1 回合)」);
|
||||
设备验收:`scripts` 之外用真机 HTTP 跑过(AI 对 AI 决斗结束 → 上下文查看器
|
||||
的「地点动态」段里看到「获胜(共 2 回合)」,截图 `docs/screenshots/v335-duel-result-place-events.png`)。
|
||||
|
||||
## 游戏界面 HTML 自定义(v3.36 起)
|
||||
|
||||
- **边界**(用户原话「除了侧边栏里的界面(会议,容器等),其他都要自定义」):
|
||||
**侧边栏 / 会议 / 容器 / 设置 / 世界包 / 技能 / 资源 / 终端仍是原生 Compose**,
|
||||
不要把它们搬进 HTML。自定义的是**游戏内界面**,P1 只做聊天页。
|
||||
- **模板包在数据目录,不在 APK assets**:
|
||||
`kernel-data/ui-packs/<id>/`(`template.json` + `index.html` + 任意 CSS/JS/图片);
|
||||
共享 SDK 在 `ui-packs/ui-sdk/sdk.js`。内核静态托管 `/ui-packs/<id>/...`
|
||||
(同源,页面里可直接 fetch `/api/...`),读写接口在 `/api/ui-packs...`。
|
||||
- 安卓:`LocalKernel` 启动前从 APK `assets/ui-packs/` 播种(只补缺、不覆盖用户包;
|
||||
`VERSION` 标记控制);桌面:`ui_packs.seed_builtin()` 从仓库 assets 播种。
|
||||
- **「恢复内置」在安卓必须走 Kotlin assets**,不能走内核 `/reset` ——
|
||||
内核在 APK 里读不到 `assets/ui-packs`(`_builtin_dir()` 指向不存在的仓库路径)。
|
||||
`LocalKernel.resetUiPack()` 负责覆盖。
|
||||
- **AAPT 会忽略 assets 里以 `_` 开头的目录**:最早用 `_sdk/`,APK 里整个消失,
|
||||
真机表现「SDK 404 → GameUI is not defined」。所以叫 `ui-sdk/`,别再改回下划线开头。
|
||||
- **页面加载的是 HTTP,不是 file://**:`http://127.0.0.1:<端口>/ui-packs/<包>/index.html`。
|
||||
`MapScreen` 那套 WebView 设置照抄(`useWideViewPort=true`、`loadWithOverviewMode=false`、
|
||||
JS/DOM storage、`onRelease` 里 `about:blank` + `removeJavascriptInterface` + `destroy`)。
|
||||
- **桥是白名单**:`window.Doubao` 只放 `openDrawer/openScreen/setConversation/toast/close`;
|
||||
页面不能直接操作 ViewModel。页面切会话时调 `setConversation(id)`,原生把
|
||||
`activeConversationId` 跟上但不回推(防来回重载)。
|
||||
- **失败兜底是硬要求**:404 / `onReceivedError` / JS 崩 → Compose 显示
|
||||
「重试 / 切回原生聊天界面」;原生 `ChatScreen` 永远保留,开关关掉立刻回原生。
|
||||
- **图片路径换算**:`assetUrl()` 必须**先找 `agent-assets/` 再判断 `/` 开头**。
|
||||
安卓角色图是 `/data/user/0/.../agent-assets/...`,先判断绝对路径会原样返回,
|
||||
WebView 去请求 `/data/user/...` → 404(真机踩过:立绘一片空白)。
|
||||
- **1×1 占位图要当没有**:只监听 `onerror` 发现不了「能加载但看不见」的图。
|
||||
背景 <64px、立绘 <120px 时回退到 CSS 房间 / 头像徽章(真机内置角色就是 70 字节占位图)。
|
||||
- **不要用 `vh`**:安卓 WebView 会算成 0。`style.css` 用 flex / `%` / `position:fixed`;
|
||||
`probe-ui-packs` 会断言没有 `数字vh`。
|
||||
- **默认开**(`gameUiEnabled=true`、`gameUiPack=galgame`,内核 `defaults.py`)。
|
||||
新增设置键要同步:`defaults.py`、`Models.kt` 的 `Settings` + `toSettings()`、
|
||||
设置页入口、`docs/总体说明-所有功能.md`。
|
||||
- **设置入口**:设置 →「游戏界面(HTML)」`GameUiSettingsScreen`;
|
||||
界面文档 `docs/界面总览.md` 的 `[游戏界面]` / `[游戏界面设置]` 和
|
||||
`scripts/audit-ui-tree.py` 的 `SCREENS` 必须同步。
|
||||
- **端到端验收**(不能只跑内核):
|
||||
1. `python scripts/probe-ui-packs.py`(播种/静态/穿越/读写/导入导出/开关/HTML 关键内容);
|
||||
2. 真机/模拟器:`GameUiScreen` 能显示 galgame 皮肤、发消息有流式、存档能标重要、
|
||||
信息/读档/记录面板能开、菜单按钮能开原生抽屉、设置里关掉能回原生聊天;
|
||||
截图 `docs/screenshots/v336-galgame-*.png`。
|
||||
- **P1 没做的**(别在宣传里写):地图/决斗/背包还没迁进 HTML;应用内编辑器/导入按钮、
|
||||
附件/语音在 P4;世界包自带皮肤已按用户要求撤掉(v3.38 UI 包独立)。
|
||||
|
||||
## 游戏界面 P2/P3:路由页 / 编辑器 / UI 包独立(v3.37/v3.38)
|
||||
|
||||
- **游戏内路由页**:`map.html` / `duel.html` / `bag.html` 与 `index.html` 同包、共用
|
||||
`ui-sdk/sdk.js` + `routes.css`。原生 `MapScreen` / `DuelScreen` / `UserItemsScreen`
|
||||
在 `vm.gameUiActive` 时改渲染 `GameUiRouteScreen`,否则保持原生 —— **原生的永远保留**。
|
||||
路由页是**浮层 WebView**,聊天页 WebView 在下面保持挂载:开地图/决斗/背包
|
||||
**不会中断聊天流式**;关闭只关浮层(`onClose`),不是关掉整个自定义 UI。
|
||||
- **地图不重画几何**:`map.html` 用 iframe 加载内核
|
||||
`/api/containers/<cid>/map/page`,只在外层做自定义顶栏和配色注入;
|
||||
世界包的 `places[].x/y` / `exits` / `info.map` 只有一份。要完全重画再用
|
||||
`GameUI.placesData` + `moveMember`,别复制一套几何解析。
|
||||
- **路由页桥的 `close` 语义不同**:聊天页 `close` = `vm.disableGameUi()`;
|
||||
路由页 `close` = 关闭浮层(`closeMap` / `closeDuelScreen` / `closeUserItems`)。
|
||||
`GameUiRouteScreen` 必须传对 `onClose`,否则会把整个自定义界面关掉。
|
||||
- **`Doubao.moved`**:内核地图页和背包页移动成功后都会调;原生桥要按路由分派:
|
||||
地图 → `vm.onMapMoved`(切地点对话并关地图);背包 → `vm.onGameUserMoved`
|
||||
(位置已由页面 move 移好,原生只 `switchPlace(alreadyMoved=true)`)。
|
||||
**页面不要再调一次原生移动**,否则会重复移动/400。
|
||||
- **打开决斗页**:聊天页快捷「决斗」走 `vm.openDuelScreenAny()`(不要求 `vm.duel`
|
||||
已加载,页面自己 `GET /api/conversations/<id>/duel`);原生入口仍走 `openDuelScreen()`。
|
||||
- **UI 包独立于世界包(v3.38,用户明确要求)**:UI 包只从「游戏界面」设置里
|
||||
**全局选一个**(`AppViewModel.gameUiPack`),聊天/地图/决斗/背包都用它;不要按容器/
|
||||
世界包再算一遍。世界包**不携带、不切换**皮肤:
|
||||
- 导入世界包时 zip 里的 `ui/` 直接忽略;不建 `world-*` 界面包、不写 `info.uiPack`、
|
||||
不返回 `uiFiles`;导出世界包也不把 `ui/` 带回。
|
||||
- 旧世界包的 `info.uiPack` / 残留 `world-*` 包不参与选包(可在设置页手动删)。
|
||||
- 分享皮肤 = 导出 UI 包 zip → 对方导入;和世界包是两条独立的包管理线。
|
||||
- ★ 别再恢复 `gameUiPackFor` 或世界包 ui/ 皮肤逻辑 —— 用户原话「是要独立的ui包」。
|
||||
- **编辑器**:`UiPackEditorScreen` 只编辑文本(HTML/CSS/JS/JSON,和内核同限制),
|
||||
保存走 `/api/ui-packs/<id>/file`;新建/导入/导出/删除在
|
||||
`GameUiSettingsScreen`;恢复内置走 Kotlin `LocalKernel.resetUiPack`(APK assets)。
|
||||
SAF 选 zip 后 base64 发给内核,不要自己解压绕过内核校验。
|
||||
- **AAPT 仍会忽略 `_` 开头的 assets 目录**(v3.36 的坑):共用 SDK 必须叫 `ui-sdk/`。
|
||||
- **老包升级只补缺**:`assets/ui-packs/VERSION` 变化时,`seedUiPacks` 对已存在的内置包
|
||||
递归 `overwrite=false` —— 只补新文件(v3.37 的 map/duel/bag),**不覆盖用户改过的文件**;
|
||||
SDK 始终覆盖。要拿完整新皮肤让用户点「恢复内置」。别回退成"目录存在就整个跳过",
|
||||
否则老用户升级后没有路由页 → 地图/决斗/背包直接 404。
|
||||
- **回归**:`probe-ui-packs.py` 新增路由页/SDK/UI 包独立断言(世界包 `ui/` 被忽略、不建包、导出不带);
|
||||
真机验收:聊天 HUD/快捷条 → 地图(iframe)→ 决斗(出招/说话/停手)→
|
||||
背包(使用/给予/移动/复活)→ 设置(新建/导入/编辑/导出/恢复)→ 关总开关回原生。
|
||||
|
||||
## 游戏界面 P3:任意页面 / 地点过滤 / 系统页(v3.39 起)
|
||||
|
||||
- **UI 包页面数量不限**:`GameUI.openPage('任意页面.html', {x:1})` 从聊天/地图/决斗/背包/
|
||||
另一个自定义页跳转;参数变成查询串,目标页 `GameUI.param('x')` 读。
|
||||
- SDK 桥:`Doubao.openPage(page, query, containerId, conversationId)`;原生
|
||||
`GameUiBridge.openPage` → `AppViewModel.openGameUiPage` → `AppRoot` 的
|
||||
`GameUiPage` 浮层(`GameUiRouteScreen` 的通用模式)。
|
||||
- **只允许包内相对路径**:`/^[A-Za-z0-9._/-]+\.html?$/`,拒绝 `http://`、`..`、`\`;
|
||||
SDK 也挡一次。页面 URL 由原生拼,不要让页面直接 `location.href` 绕开(会丢会话/容器)。
|
||||
- `GameUiRouteScreen(route=...)` 现在既接受 `map/duel/bag` 别名,也接受任意 `.html`;
|
||||
`packId/query` 参数用于编辑器预览和带参数跳转。不要在 `GameUiRouteScreen` 里写死页面枚举。
|
||||
- **背包/地图页里的 `GameUI.openPage` 会保存在原路由页之上**;关闭通用页回原页,不是直接回聊天。
|
||||
- 内置系统页:`backlog.html`(底部「记录」)、`settings.html`(底部「设置」)。
|
||||
设置页保存后 `GameUI.reloadChat()` 让聊天 WebView 重载(bridge `reloadChat` → `vm.reloadGameUi`)。
|
||||
- **成员必须按地点过滤**:HTML 的 `game.js` 用 `coLocatedIds()`,语义和原生
|
||||
`AppViewModel.coLocatedMembers` 一致:地点对话(`conversation.placeId`)按容器
|
||||
`positions` 过滤成员条和 @ 快捷条;普通对话/无位置数据不过滤。别再用
|
||||
`conv.participants` 直接渲染所有人(用户原话「咋角色不根据地点过滤了」)。
|
||||
- **编辑器更好改**:`UiPackEditorScreen` 的「新建」可以建任意 html/css/js/json/txt;
|
||||
html 文件列表右侧「预览」直接 `vm.openGameUiPage(path, ..., packId)`(**packId 要传**,
|
||||
否则预览的是全局包而不是正在编辑的包);保存后 `vm.reloadGameUi()`,聊天页自动重载。
|
||||
- **播种必须检查缺包**:`seedUiPacks` 不能只看 `.seed-version` —— 用户删了内置包但标记还在时,
|
||||
必须重新从 assets 补;每启动检查 `galgame/index.html` 与 `ui-sdk/`。`VERSION` 变化时
|
||||
仍只补缺(overwrite=false),不覆盖用户改过的文件。
|
||||
- **UI 包独立于世界包不变**:`GameUI.openPage` 只改页面,不改世界包;世界包不参与选包。
|
||||
- 回归:`probe-ui-packs` §2 检查 `backlog/settings` 页面、SDK `openPage/reloadChat`、
|
||||
`game.js` 的 `coLocatedIds`;真机:记录/设置/任意自定义页、成员条地点过滤、编辑器新建+预览。
|
||||
- **UI API 教程唯一入口**:`docs/游戏界面-UI-API教程.md`。改 SDK / 桥 / 页面 API 时同步教程和 `probe-ui-packs` 静态断言;别只写代码不写教程。
|
||||
|
||||
## 默认 UI「月影」/ 左侧 HUD rail(v3.41 起)
|
||||
|
||||
- **默认皮肤重做**:内置 `galgame` 包改名为「月影 · Galgame」,深靛蓝 + 月白 + 香槟金;
|
||||
不再用厚奶油纸、双层金边、大圆头像。改动集中在
|
||||
`assets/ui-packs/galgame/{index.html,style.css,game.js}` 和 `assets/avatars/default-body.png`。
|
||||
- **默认全身立绘**:`showFallback()` 对 `a_doubao` / `avatar=doubao` / 名字「豆包」
|
||||
优先用 `assets/avatars/default-body.png`(由 App 内置 `agent_default_character.png`
|
||||
转透明 PNG);其他角色仍回头像。不要把所有角色都套豆包身体。
|
||||
- **左侧 HUD rail**:`index.html` 的 `.side-rail` 放当前位置 / 数值 `#hud` / 在场
|
||||
`#memberBar` / 地图/背包/决斗/常驻 `[data-rail]`。成员条仍走 `coLocatedIds()` 地点过滤;
|
||||
点在场成员 = 插入 `@名字`(成员档案走底栏「信息」),不要再放一份底部快捷条。
|
||||
- **布局铁律**:rail `top:72px; bottom:57%`(用 `%` 不用 `vh`,安卓 WebView 的 `vh=0`);
|
||||
名字牌现在**放进对白窗内部**(`top:9px; left:18px`,box `padding-top:30px`),不再放外面挡 rail;
|
||||
立绘 `top:104px; bottom:244px`,比旧版更低。
|
||||
改完在 360×640 和 390×844 两档都截图确认 nav 四格不被对白窗盖住。
|
||||
- **性能**:默认 UI **不要**加回大面积 `backdrop-filter`、全屏 `filter: blur`、
|
||||
大图 `drop-shadow`、每帧 `visualViewport` 改 `paddingBottom`。这些是输入法弹出卡顿的根因。
|
||||
键盘只用 `body.keyboard-open`:以 `visualViewport.height < screen.height * 0.72` 判断,
|
||||
**不要用 innerHeight 比**(adjustResize 会把两者一起缩)。
|
||||
- **探针**:`probe-ui-packs` 检查 `.side-rail` / 四个 `data-rail` / `default-body.png` /
|
||||
`keyboard-open`,并断言 CSS 没有 `vh`、`backdrop-filter`、`filter: blur`。
|
||||
- 默认包内 `VERSION` 随资源改动递增(v3.41 为 4);已经装过旧内置包的用户需「恢复内置」
|
||||
才能看到新默认皮肤(只补缺不覆盖用户改动)。
|
||||
|
||||
- **长按 @ 决斗(v3.42)**:`bindMemberActions()` 同时绑在场成员和底部 @ 片;
|
||||
点=插 `@名字`,长按 560ms(或 contextmenu)= `openDuelPrompt` → `GameUI.startDuel`
|
||||
→ `GameUI.openScreen('duel')`。不要用 click 直接开打;没有武器要让内核报错并 toast。
|
||||
|
||||
## 游戏界面 v3.43:@ 收进 rail / 可折叠底栏 / 动态对白窗
|
||||
|
||||
- **@ 在左侧 rail**:`index.html` 的 `在场 / @` 下面是成员 chip(`@名字`)。**不要再放底部
|
||||
`#quick` 快捷条**(用户明确让删)。点=插 `@`,长按=弹「私聊 / 决斗 / 信息」;
|
||||
`bindMemberActions` 同时绑 rail 成员;长按时 `touch-action:none`,否则父级滚动会抢走
|
||||
长按(真机踩过)。
|
||||
- **私聊**:菜单里 `privateTo` → `GameUI.send(text, { privateTo })`,SDK 转成
|
||||
`/api/chat` 的 `privateTo`;输入框上方 `#privateBar` 显示「🔒 私聊 · 某人 / 退出」。
|
||||
单人会话(在场成员 < 2)直接 toast,不进私聊。
|
||||
- **底栏 8 功能 + 折叠**:存档/信息/读档/跳过/记录/设置/朗读/新话题;最左 `⌄` 收起,
|
||||
`body.actions-collapsed` 时只显示 `#actionsToggle`「功能 ⌃」。状态存
|
||||
`localStorage['galgame:actionsCollapsed']`;收起时 `.dock` 要加 42px 底部 padding,
|
||||
别让「功能」小钮压住输入框。
|
||||
- **对白窗定高**:`.box` 150px(≥760px 高时 180px),`.text` 自己 `height:100%; overflow-y:auto`。
|
||||
**不要用 `min-height + max-height:百分比`** —— Chrome 会把 `.dialogue` 按文字内容撑高,
|
||||
多出 100px 空白(用户反馈「这个咋那么高」)。名字牌放 box 外,始终可见;文字只滚 `.text`。
|
||||
- **rail 动态高度**:`fitRail()` 取 `.dialogue` top,把 rail 底边收到其上方 10px;
|
||||
可用高 <240px 自动 `rail-compact`(隐藏标签、成员竖排收窄、nav 缩高)。改布局后
|
||||
必须在 360×640 验证 4 个 nav + @ 都在,不能只信 390×844。
|
||||
- **探针**:`probe-ui-packs` 检查 `privateBar` / `actions-fold` / `actionsToggle` /
|
||||
`speak`/`newtopic` / `openMemberMenu` / `fitRail` / `rail-compact` / SDK `privateTo`,
|
||||
并断言 HTML 里没有 `id="quick"`。
|
||||
|
||||
## 导出相关 v3.44
|
||||
|
||||
- **智能体包导出**:`image.front` 是**五档 dict**,不是字符串。`_export_agent` 必须逐档
|
||||
打包成 `front-<档位><ext>`,`smartInfo.json.image.front` 写回档位字典;旧代码对 dict
|
||||
调 `os.path.isfile` 会 TypeError → 带立绘的智能体导出 500。世界观导出已有同款测试,
|
||||
智能体这条路也必须保住;回归 `probe-agent-system` §9(设置 front:平常 → 导出 → 导入)。
|
||||
- **UI 包导出入口**:设置 →「游戏界面(HTML)」每个包右侧「导出」;编辑器右上角也有。
|
||||
导出走 `KernelClient.exportUiPack`,zip base64 → SAF,别只藏在「编辑」里。
|
||||
|
||||
## 工具调用动效 v3.45
|
||||
|
||||
- 内核 `agent_loop` 发 `tool_call` / `tool_result` 事件;SDK 没有专门 switch 分支,会落到
|
||||
通用 `event`。game.js 监听 `GameUI.on('event')`,在 `#toolToast` 显示
|
||||
「AI 正在调用 · 工具名」→「✓ AI 调用了 · 工具名」;工具失败显示「工具失败」,
|
||||
1.2s 后隐藏。工具 id 用 `TOOL_LABELS` 映射中文,未知显示原 id。
|
||||
- 位置:`.dialogue` 内的绝对定位胶囊,**右对齐**在对话框上方,别放左边(会压住 rail 的
|
||||
地图/背包)。别让它进入 dock 文档流,否则会把对白窗顶下去。
|
||||
|
||||
## 工具调用铁律 v3.46(弱模型只说不做)
|
||||
|
||||
- **用户反馈最大问题**:小/弱模型移动、用物品时只在正文写「我走向商店 / 我用了药」,
|
||||
实际没调 `move_to` / `use_item`;必须让动作落成工具。
|
||||
- **三处同时改**:
|
||||
1. `defaults.BUILTIN_SKILL` 第一段「行动必须调用工具」(映射 + 不许口头完成);
|
||||
2. `agent_context.build_system_prompt` 末尾追加 `TOOL_ACTION_POLICY`(最后一段,弱模型更敏感);
|
||||
3. `agent_loop.action_turn_hint()` 检测到用户行动句时再加一轮 system 提醒。
|
||||
- **降级模式**(provider.noTools):`DEGRADED_HINT` 不能只列 memory/emotion —— 必须列
|
||||
`move_to/list_places/use_item/use_item_on/give_item/drop_item/...` 并给 `doubao-call` 示例,
|
||||
否则不能 function calling 的模型永远只会说。
|
||||
- **工具描述**也要写「必须调用本工具;只写正文位置/背包不会变」。
|
||||
- 回归:`probe-agent-system` §16(prompt 末尾/技能首段/工具描述/降级提示/行动句提醒)。
|
||||
- **别加 `tool_choice:'required'` 硬强制**:闲聊/用户描述自己动作时会被迫乱调工具,比只说不做更糟;
|
||||
先用分层提示 + 降级可写调用兜底。
|
||||
|
||||
## rail 导航可点性 v3.47
|
||||
|
||||
- `fitRail()` 的底部留白从 10px 调到 **26px**,导航不再贴着对白窗;rail 高度同步。
|
||||
- `.rail-nav button` 正常 42px 高、compact 36px 高,图标 13px,保证手机上好点。
|
||||
- 别只改 nav 不调 `fitRail` 的 26px,否则加大后的 nav 会顶到对白窗;改完 360×640
|
||||
验证四格完整、能点、不压名字牌。
|
||||
|
||||
## rail 下排按钮点不到 v3.48
|
||||
|
||||
- **症状**:左侧地图/背包(上排)能点,决斗/常驻(下排)看得到但点不动。
|
||||
- **根因**:`.side-rail` 的 `z-index` 是 12,`.dock` 是 18;下排落在 `.dock` 的透明覆盖区里,
|
||||
点击被 `.dock` 吃掉。上排刚好在 dock 外所以正常。
|
||||
- **修复**:`.side-rail` 改 `z-index:24`(高于 dock 18、低于面板 60)。验证方式不是只看截图:
|
||||
用 `document.elementFromPoint(按钮中心)` 检查四格都命中按钮/`SPAN`,不能命中 `.dock`。
|
||||
- 改 rail 层级后如果按钮盖住对白/名字牌,优先调 `fitRail` 的底部留白,不要降 z-index 回去。
|
||||
|
||||
## 对白滚动跟随 v3.49
|
||||
|
||||
- 打字机 `renderShown()` 原来每个 tick 都 `text.scrollTop = text.scrollHeight`,用户往上翻也拉回底部。
|
||||
现在用 `stickBottom`:`scroll` 时计算是否离底部 <20px;只有为真才跟随。
|
||||
- 手指滑动后 WebView 可能补一个 click,原 click 会 `finishTyping()` 再跳底部;现在
|
||||
`lastScrollAt` 420ms 内忽略 click。
|
||||
- 新消息 `startTyping` 会 `stickBottom=true`(新内容跳底部);用户手动上翻后,流式/结束
|
||||
都不再抢滚动。改这里别把 `scrollTextToBottom` 又改回无条件。
|
||||
|
||||
## 内核性能约定 v3.50("HTML 手机卡"这一层)
|
||||
|
||||
用户原话:「感觉 html 还是很卡……不是优化界面,是优化内核」。实测下来卡的不是 CSS,
|
||||
是内核里**每秒都在重复的劳动**。改慢代码之前先看 `python scripts/probe-perf.py`
|
||||
(它会把这些数字全部重测并断言),别凭感觉优化。
|
||||
|
||||
- **★ `/api/state` 一次别读同一份文件好几遍**:`store.list_resource()` 现在按
|
||||
`(mtime_ns, size)` 缓存,**返回 item 浅拷贝**。写入口必须走 `_write_resource`
|
||||
(它会 pop 缓存);如果新增"直接 `_write_json(worldviews_file)`"的写法,缓存会陈旧。
|
||||
实测一次 `/api/state` 原来是 **48 次**读盘 + json.load,现在 3 次。
|
||||
- **★ 大会话库别每条消息重写整份 `conversations.json`**:`_persist_conversations()`
|
||||
对 >128KB 的文件改成"脏标记 + 400ms 合并写"(`_flush_conversations` /
|
||||
`flush_if_dirty`)。实测 20 会话×400 条(2.3MB)**38ms/条 → 0.0ms/条**。
|
||||
- 小文件(<128KB)仍**同步写**(数据安全优先);
|
||||
- 新建/删除/标重要走 `force=True` 立刻落盘;
|
||||
- `/api/state` 每次刷新会 `flush_if_dirty()`,等于给数据加了一道保险;
|
||||
- 加新的会话写入口时:用 `_persist_conversations()`(别自己 `_write_json` 整份文件),
|
||||
而且要保证**改字典的时候持 `_lock`** —— 后台 flush 是在锁里 dump 的。
|
||||
- **★ 静态文件必须能 304**:`serve_file()` 现在发 `ETag` + `Last-Modified` 并处理
|
||||
`If-None-Match` / `If-Modified-Since`。默认立绘 454KB,没有校验器时浏览器每次重载
|
||||
都会整个重下。**新增静态路由一律走 `serve_file`**,别自己 `send_header` + 写文件。
|
||||
- **★ `/api/state` 有 `?lite=1`**(游戏界面 SDK 用):摘掉 `speechVoicesAll` /
|
||||
`providers` / `mcpConfig` / `python.tools`,72KB → 22KB。
|
||||
给 HTML 侧加新字段时**要注意 lite 里有没有**:lite 只保证
|
||||
`conversations/agents/containers/places/settings/containerEmotions/containerPortraits`
|
||||
+ 工具名/平台这些轻字段。
|
||||
- **★ 响应默认紧凑 JSON**(`_json_dumps`),别改回 `indent=2`;调试用
|
||||
`DOUBAO_JSON_PRETTY=1`。
|
||||
- **★ 聊天轮询支持长轮询**:`GET /api/chat/poll?...&wait=1` 会挂到有新事件才回
|
||||
(`CHAT_POLL_MAX_WAIT=1.2s`,拿到第一条后再攒 `CHAT_POLL_BATCH_S=30ms`)。
|
||||
**响应里必须带 `longPoll: true`**(能力通告)—— SDK 靠它判断,不要用"请求耗时短"
|
||||
去猜:模型吐字快(本地/边缘模型)时长轮询本来就几十毫秒返回,会被误判成
|
||||
"内核不支持"、整轮退回 200ms 轮询(v3.50 犯过,真机实测 55 次轮询只 5 次带 wait)。
|
||||
别把"不带 wait 立刻返回"的老行为弄丢(网页端/老客户端还在用)。
|
||||
- **★ 图片静态资源给真 max-age(v3.51)**:`serve_file()` 对 png/jpg/webp/gif/avif/ico
|
||||
发 `max-age=600, must-revalidate`,文本类仍是 `max-age=0`。
|
||||
原因:安卓 WebView 在 `max-age=0` 下**不保证留住缓存条目** —— 真机实测 465KB 的
|
||||
`default-body.png` 在页面运行中反复整份重下,每次还要重新解码(≈100ms),
|
||||
就是"发一句话卡一下"。改缓存策略前先想想"图片会不会被反复重下+重解码"。
|
||||
- **★ HTML 侧别整块重建没变的 DOM(v3.51)**:`game.js` 的 `applySpeaker` /
|
||||
`applyBackground` / `renderMembers` 用 `lastSpriteKey` / `lastBgUrl` /
|
||||
`lastMembersKey` 做"没变就跳过"。`refreshChrome()` 里那三个函数都是每次都调的,
|
||||
以前每次都 `new Image()` 探立绘 + 重建整排成员头像 ⇒ 真机每轮对话发送后 ~180ms
|
||||
一次 **116ms 长帧**。加新的"每次刷新都要画"的东西时,同样先比较再动 DOM。
|
||||
- **`disable_nagle_algorithm = True`** 保留:小响应攒包在安卓上就是凭空的几十毫秒。
|
||||
- **测量优先**:改完跑 `probe-perf.py`,并把"之前/现在"的数字写进提交信息和文档。
|
||||
用户能感知的三件事:点发送后反应更快(不再先写几百毫秒磁盘)、吐字更顺
|
||||
(200ms 一跳 → 几十毫秒)、重开界面不再先卡一下(立绘不再重下/重解码)。
|
||||
真机(模拟器)采集办法:`.tmp-perf/perf-collect.py`(CDP,帧/请求/长任务)
|
||||
+ `.tmp-perf/verify-v174.py`(真实点击发送 + 首字延迟),做 UI 相关性能改动后照它跑一遍。
|
||||
|
||||
## 记忆语义检索 / 向量 v3.52
|
||||
|
||||
用户原话:「先研究一下向量数据库,记忆想用向量搜索」,然后拍板:**用方舟**、
|
||||
**配了火山 key 的默认开**、**每轮自动回忆也默认开**。
|
||||
完整调研与真机数据见 [`docs/记忆向量检索-调研.md`](docs/记忆向量检索-调研.md)。
|
||||
|
||||
- **★ 安卓上不能用 sqlite-vec / sqlite-vss(实测)**:Chaquopy 的
|
||||
`sqlite3.Connection` 没有 `enable_load_extension`(AttributeError),
|
||||
APK 里 `_sqlite3.so` 根本没引用 `sqlite3_load_extension` —— 编译时没开
|
||||
loadable extension;连 FTS5 都没编进去。hnswlib / faiss / usearch 也没安卓轮子。
|
||||
**别照着网上教程给内核加向量库/原生依赖**,APK 会崩在 import 那一步。
|
||||
- **架构(四块,别混)**:
|
||||
- `memory_vec.py`:**纯计算**(打包/归一化/符号位/汉明/点积/topK/预筛)。
|
||||
无 DB、无网络,探针直接测它。
|
||||
- `memory_embed.py`:**客户端 + 回填**。OpenAI 兼容 `POST {baseUrl}/embeddings`
|
||||
(复用用户已有的 key,默认方舟 doubao-embedding 系列,自动探测模型/维度);
|
||||
后台线程按"缺向量即队列"补;查询嵌入有内存缓存(同一句话一轮里只算一次)。
|
||||
- `agentdb.py`:`memory_vectors` 表 + `memory_vec_*` 函数。**派生数据**:
|
||||
删了能重建,不进导出,不参与备份口径。
|
||||
- 消费方:`agent_tools.memory_search`(混合检索)、`agent_context.build_memory`
|
||||
(每轮自动回忆)。
|
||||
- **★ 级联必须走数据层钩子**:`memory_add` / `memory_update` / `memory_forget` /
|
||||
`memory_replace_all` 分别 wake / 删向量 / 清 scope —— 钩子放在 `agentdb` 的写入口
|
||||
(所有通道都经过它),别放到工具层(会漏掉界面/导入/总结写回)。
|
||||
改记忆内容却不删旧向量 = 语义检索会返回**改之前的正文**,很难查。
|
||||
- **★ 写入绝不能同步嵌入**:`memory_add` 只写库 + 叫醒后台(实测 <100ms)。
|
||||
同步嵌入会让"记住这件事"变成"卡一下"(一次网络 200~800ms)。
|
||||
后台线程失败只记日志,**绝不能死**(while True + try/except 包住整轮)。
|
||||
- **★ 降级是硬要求**:没 key / 服务商没有 `/embeddings` / 网络断 / 额度没了 →
|
||||
`memory_search` 退回纯关键词、自动回忆那段直接不出现、对话不受影响。
|
||||
失败后进入 10 分钟冷却(`disabledUntil`),否则每条记忆都打一次失败请求。
|
||||
- **★ 阈值 0.30**:语义结果低于余弦 0.30 直接丢掉。不设阈值的话"关键词 0 命中"
|
||||
会把整库倒给模型,它会把无关记忆当线索编故事 —— 比"没搜到"更糟。
|
||||
- **★ 自动回忆只"加"不改**:窗口裁剪/置顶逻辑一行别动;查询词通过
|
||||
`settings['_recallQuery']` 临时键传进来(和 `_consumePlaceNotes` 同一套路,
|
||||
不落库)。`agent_loop`(真对话)和 `context_preview`(查看器)都要传,
|
||||
否则"所见即所发"就不成立了。
|
||||
- **★ `build_memory` / `memory_embed._cfg` 收到的是"临时副本"**:`settings` 里可能只有
|
||||
一个 `_recallQuery`。所以两处都是**实时设置打底、传入的覆盖**
|
||||
(`{**live, **settings}`)—— 直接用传进来的那份会把 `memoryWindow` 读成 0
|
||||
(不裁剪)、把 apiKey 读成空(误判没配)。探针 §5 钉住这条。
|
||||
- **settings 键 `memoryEmbed`**:`{enabled, autoRecall, model, topK}`,
|
||||
两个开关是 `auto / on / off` 三态,**auto = 配了 key 就开**(用户要求默认开)。
|
||||
它在 `store.write_settings` 的**深合并**名单里(`tools/security/speech/memoryEmbed`)。
|
||||
- **换模型/换服务商**:`memory_vectors` 带 `model` + `dim`,旧行自然不参与检索
|
||||
(不同模型向量空间不可比);换完在设置页点「重建索引」
|
||||
(`POST /api/memory/embed/backfill`),状态在 `GET /api/memory/embed`。
|
||||
- **探针**:`python scripts/probe-memory-vec.py`(纯函数 / 存储级联 / 嵌入客户端 /
|
||||
后台回填 / 混合检索 / 自动回忆 / 降级 / HTTP 接口,八节全过才算数)。
|
||||
假 embedding 服务按"意思分组"给固定方向,用来构造"字面不同、意思一样"的场景。
|
||||
- **性能数据(真机实测,改算法前先看)**:方舟 2048/2560 维下纯暴力余弦
|
||||
3000 条 **479ms**(不可接受);符号位二值预筛(`int.bit_count()`)+ 精确重排
|
||||
后 **18~24ms**,召回(与精确 top10 重合)合成数据 **78~81%**。
|
||||
`memory_vec.PREFILTER_MIN_COUNT=800` / `PREFILTER_CANDIDATES=300` 是这两个旋钮。
|
||||
|
||||
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 = 240
|
||||
versionName = "2.0.40"
|
||||
versionCode = 376
|
||||
versionName = "2.0.176"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -181,6 +181,10 @@ chaquopy {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// 会议节点定义库:节点类型 / 引脚 / 算子 / 几何 / 形状的唯一一份定义
|
||||
// (以前散在 MeetingsScreen.kt 里,同一样东西写 6 遍 —— 见 docs/节点库.md)
|
||||
implementation(project(":nodekit"))
|
||||
|
||||
// 原生 UI 用 Compose
|
||||
implementation(platform("androidx.compose:compose-bom:2024.09.03"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
@@ -17,7 +17,17 @@
|
||||
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||
<!-- ★★ 发通知(用户要求"还可以发送通知")。
|
||||
Android 13(API 33) 起这是**运行时权限**,新装的 App **默认是拒绝的** ——
|
||||
不申请的话 `NotificationManager.notify()` 不报错但通知**不显示**。
|
||||
实测踩到:渠道建出来了(importance=3),但 App 级 `importance=NONE`,
|
||||
通知栏里什么都没有,而调用方还以为成功了。
|
||||
声明了不算完,还得在运行时 requestPermissions —— 见 MainActivity。 -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- 通知带声音/震动需要它(Android 13+ 才有这个权限名) -->
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
|
||||
<!-- Android 11+ 包可见性:不声明的话查不到别的 App,也就「打开手机 app」不了 -->
|
||||
<queries>
|
||||
<package android:name="com.termux" />
|
||||
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||
@@ -28,6 +38,13 @@
|
||||
<intent>
|
||||
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||
</intent>
|
||||
<!-- ★「打开手机 app」需要的:列出所有能启动的 App。
|
||||
Android 11 起不声明这条 queries,queryIntentActivities 只会返回空列表,
|
||||
表现是"已安装的 App 一个都找不到"。 -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
|
||||
@@ -40,7 +57,7 @@
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="false"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@style/AppTheme">
|
||||
@@ -55,5 +72,19 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- ★★ 读手机通知(用户要求的工具)。
|
||||
Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户
|
||||
手动去「设置 → 通知 → 通知使用权」勾上本 App,系统才会把通知流过来。
|
||||
不声明这个 Service,权限开了也收不到任何东西。 -->
|
||||
<service
|
||||
android:name=".DoubaoNotificationListener"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
1
豆鲍/android/app/src/main/assets/ui-packs/VERSION
Normal file
@@ -0,0 +1 @@
|
||||
6
|
||||
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 454 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 68 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
29
豆鲍/android/app/src/main/assets/ui-packs/galgame/backlog.html
Normal file
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>小人间 · BACKLOG</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="routes.css">
|
||||
</head>
|
||||
<body class="route-page">
|
||||
<div class="route-app">
|
||||
<header class="route-top">
|
||||
<button id="back" class="cream-btn square" title="返回">←</button>
|
||||
<div class="route-title"><b>BACKLOG</b><span>这一局的对话记录</span></div>
|
||||
<button id="refresh" class="cream-btn square" title="刷新">↻</button>
|
||||
</header>
|
||||
|
||||
<div id="list" class="route-scroll"></div>
|
||||
|
||||
<footer class="route-foot">
|
||||
<span id="count">共 0 条</span>
|
||||
<button id="close" class="route-close">收起</button>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script src="../ui-sdk/sdk.js"></script>
|
||||
<script src="backlog.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
72
豆鲍/android/app/src/main/assets/ui-packs/galgame/backlog.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/* BACKLOG:对话记录页(v3.39) */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const els = {
|
||||
list: document.getElementById('list'),
|
||||
count: document.getElementById('count'),
|
||||
back: document.getElementById('back'),
|
||||
close: document.getElementById('close'),
|
||||
refresh: document.getElementById('refresh'),
|
||||
};
|
||||
|
||||
function speakerOf(m) {
|
||||
if (!m) return '旁白';
|
||||
if (m.role === 'user') return (GameUI.settings() || {}).nickname || '你';
|
||||
const agent = GameUI.agentById(m.agentId) || GameUI.currentAgent() || {};
|
||||
return agent.name || '旁白';
|
||||
}
|
||||
|
||||
function timeOf(m) {
|
||||
const raw = m && (m.at || m.createdAt || m.time);
|
||||
if (!raw) return '';
|
||||
try {
|
||||
if (typeof GameUI.fmtTime === 'function') return GameUI.fmtTime(raw);
|
||||
const d = new Date(raw);
|
||||
return isNaN(d.getTime()) ? String(raw) : `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`;
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
const messages = (GameUI.messages() || []).filter((m) => m && String(m.content || '').trim());
|
||||
els.list.innerHTML = '';
|
||||
els.count.textContent = `共 ${messages.length} 条`;
|
||||
if (!messages.length) {
|
||||
els.list.innerHTML = '<div class="g-empty">还没有说过话。<br>回聊天页发一句,这里就会出现。</div>';
|
||||
return;
|
||||
}
|
||||
messages.forEach((m, index) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'backlog-row' + (m.role === 'user' ? ' user' : '');
|
||||
const who = speakerOf(m);
|
||||
const time = timeOf(m);
|
||||
row.innerHTML = `
|
||||
<div class="backlog-meta"><b></b><span></span></div>
|
||||
<div class="backlog-text"></div>
|
||||
`;
|
||||
row.querySelector('.backlog-meta b').textContent = who;
|
||||
row.querySelector('.backlog-meta span').textContent = time || `#${index + 1}`;
|
||||
row.querySelector('.backlog-text').textContent = String(m.content || '');
|
||||
els.list.appendChild(row);
|
||||
});
|
||||
// 打开时直接看最新一条
|
||||
requestAnimationFrame(() => {
|
||||
els.list.scrollTop = els.list.scrollHeight;
|
||||
});
|
||||
}
|
||||
|
||||
els.back.addEventListener('click', () => GameUI.close());
|
||||
els.close.addEventListener('click', () => GameUI.close());
|
||||
els.refresh.addEventListener('click', render);
|
||||
|
||||
(async function boot() {
|
||||
try {
|
||||
await GameUI.ready();
|
||||
render();
|
||||
} catch (err) {
|
||||
els.list.innerHTML = `<div class="g-empty">记录读不出来:${GameUI.escapeHtml(err.message || err)}</div>`;
|
||||
}
|
||||
})();
|
||||
})();
|
||||
35
豆鲍/android/app/src/main/assets/ui-packs/galgame/bag.html
Normal file
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>小人间 · 我的角色</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="routes.css">
|
||||
</head>
|
||||
<body class="route-page">
|
||||
<div class="route-app">
|
||||
<header class="route-top">
|
||||
<button id="backBtn" class="cream-btn square" title="返回">←</button>
|
||||
<div class="route-title">
|
||||
<b>我的角色</b>
|
||||
<span id="routeSub">这一局</span>
|
||||
</div>
|
||||
<button id="refreshBtn" class="cream-btn square" title="刷新">⟳</button>
|
||||
</header>
|
||||
|
||||
<div class="route-scroll">
|
||||
<div id="bagRoot"></div>
|
||||
</div>
|
||||
|
||||
<div class="route-foot">
|
||||
<span>用户也是这一局里的角色:数值 / 状态 / 物品和 AI 走同一套引擎。</span>
|
||||
<button id="closeBtn" class="route-close">收起</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast"></div>
|
||||
<script src="../ui-sdk/sdk.js"></script>
|
||||
<script src="bag.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
255
豆鲍/android/app/src/main/assets/ui-packs/galgame/bag.js
Normal file
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* 「我的角色 / 背包」路由(v3.37)
|
||||
* ---------------------------------------------------------------------------
|
||||
* 用户角色和 AI 走同一套引擎(/api/containers/<cid>/...):数值、状态、物品都
|
||||
* 按这一局隔离。页面只做显示 + 调接口;能不能用、用多少由内核判断。
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const els = {
|
||||
back: $('backBtn'), close: $('closeBtn'), refresh: $('refreshBtn'),
|
||||
sub: $('routeSub'), root: $('bagRoot'), toast: $('toast'),
|
||||
};
|
||||
|
||||
const state = {
|
||||
cid: '',
|
||||
profile: null,
|
||||
items: [],
|
||||
map: null,
|
||||
container: null,
|
||||
busy: false,
|
||||
};
|
||||
|
||||
let toastTimer = 0;
|
||||
function toast(text) {
|
||||
if (!text) return;
|
||||
els.toast.textContent = text;
|
||||
els.toast.classList.add('show');
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => els.toast.classList.remove('show'), 1800);
|
||||
GameUI.toast(text);
|
||||
}
|
||||
|
||||
function esc(text) { return GameUI.escapeHtml(text); }
|
||||
|
||||
function agentName(id) {
|
||||
const a = GameUI.agentById(id);
|
||||
return (a && a.name) || id || '';
|
||||
}
|
||||
|
||||
function containerMembers() {
|
||||
const members = (state.container && state.container.members) || [];
|
||||
return members.filter(Boolean);
|
||||
}
|
||||
|
||||
function itemList() {
|
||||
const list = Array.isArray(state.items) ? state.items.slice() : [];
|
||||
return list.filter((item) => item && (item.id || item.name));
|
||||
}
|
||||
|
||||
function statRatio(s) {
|
||||
const v = Number(s.value) || 0;
|
||||
const max = Number(s.max) || 0;
|
||||
const min = Number(s.min) || 0;
|
||||
if (max > min) return Math.max(0, Math.min(1, (v - min) / (max - min)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
function statusLabel(item) {
|
||||
if (!item) return '';
|
||||
if (typeof item === 'string') return item;
|
||||
let text = item.name || item.id || '';
|
||||
const left = item.remaining != null ? item.remaining : item.turns;
|
||||
if (left != null && Number(left) > 0) text += ` · ${left}`;
|
||||
return text;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const p = state.profile;
|
||||
const container = state.container || GameUI.currentContainer() || {};
|
||||
const place = (p && p.place) || {};
|
||||
els.sub.textContent = [container.name, place.name].filter(Boolean).join(' · ') || '这一局';
|
||||
|
||||
if (!p) {
|
||||
els.root.innerHTML = `<div class="g-empty">还没有读到用户角色档案。<br>可能是这一局还没有绑定世界包/用户角色。</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const stats = p.stats || [];
|
||||
const statuses = (p.statuses || []).map(statusLabel).filter(Boolean);
|
||||
const items = itemList();
|
||||
const places = (state.map && state.map.places) || [];
|
||||
const currentPlace = place.id || p.placeId || '';
|
||||
const members = containerMembers();
|
||||
|
||||
els.root.innerHTML = `
|
||||
<div class="g-card">
|
||||
<div class="profile-head">
|
||||
<img class="profile-avatar" id="profileAvatar" alt="">
|
||||
<div style="min-width:0">
|
||||
<div class="profile-name">${esc(p.name || '我')}</div>
|
||||
<div class="profile-sub">${esc(container.name || '')}${place.name ? ' · ' + esc(place.name) : ''}</div>
|
||||
<div class="profile-sub">${p.dead ? '<span class="profile-dead">已死亡 · 这一局结束</span>' : (p.emotion && p.emotion.preset ? '情绪:' + esc(p.emotion.preset) : '')}</div>
|
||||
</div>
|
||||
</div>
|
||||
${p.desc ? `<div class="g-hint" style="margin-bottom:8px">${esc(p.desc)}</div>` : ''}
|
||||
${p.dead ? `<button class="g-btn" id="reviveBtn" style="width:100%">复活(改回「平常」)</button>` : ''}
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>数值</h3>
|
||||
${stats.length ? stats.map((s) => {
|
||||
const v = Number(s.value) || 0;
|
||||
const max = Number(s.max) || 0;
|
||||
const ratio = statRatio(s);
|
||||
return `<div class="stat-line">
|
||||
<div class="head"><span>${esc(s.name || s.id || '')}</span><b>${Math.round(v)}${max ? ' / ' + Math.round(max) : ''}</b></div>
|
||||
<div class="track"><i style="width:${Math.round(ratio * 100)}%"></i></div>
|
||||
</div>`;
|
||||
}).join('') : '<div class="g-hint">这一局还没有定义数值。</div>'}
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>状态</h3>
|
||||
${statuses.length ? statuses.map((t) => `<span class="badge">${esc(t)}</span>`).join('')
|
||||
: '<div class="g-hint">当前没有状态。别人能给你挂状态,自己也能用物品获得。</div>'}
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>物品(${items.length})</h3>
|
||||
${items.length ? items.map((item) => {
|
||||
const count = item.count == null ? 1 : Number(item.count);
|
||||
return `<div class="item-row" data-item="${esc(item.id || item.name || '')}">
|
||||
<div class="item-main">
|
||||
<div class="item-name">${esc(item.name || item.id || '')}</div>
|
||||
<div class="item-desc">${esc(item.desc || item.kind || '')}</div>
|
||||
</div>
|
||||
<div class="item-count">${count < 0 ? '∞' : '×' + count}</div>
|
||||
<div class="item-actions">
|
||||
<button class="g-btn" data-act="use">使用</button>
|
||||
<button class="g-btn ghost" data-act="drop">抛弃</button>
|
||||
${members.length ? `<button class="g-btn ghost" data-act="give">给予</button>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('') : '<div class="g-empty">背包是空的。</div>'}
|
||||
${members.length ? `<div class="g-row" style="margin-top:8px">
|
||||
<span class="g-hint">给予对象:</span>
|
||||
<select id="giveTarget" class="g-select">
|
||||
${members.map((id) => `<option value="${esc(id)}">${esc(agentName(id))}</option>`).join('')}
|
||||
</select>
|
||||
</div>` : ''}
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>移动</h3>
|
||||
${places.length ? `<div class="g-row" style="flex-wrap:wrap">
|
||||
<select id="movePlace" class="g-select">
|
||||
${places.map((pl) => `<option value="${esc(pl.id)}" ${pl.id === currentPlace ? 'selected' : ''}>${esc(pl.name || pl.id)}</option>`).join('')}
|
||||
</select>
|
||||
<button class="g-btn" id="moveBtn">走过去</button>
|
||||
</div>
|
||||
<div class="g-hint" style="margin-top:6px">移动会照常触发地点动态;走到别的场景后,聊天页也会跟着切地点对话。</div>`
|
||||
: '<div class="g-hint">这一局没有地点定义。</div>'}
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>这一局</h3>
|
||||
<div class="g-hint">${esc(container.name || '未归属容器')} · ${esc(container.worldPackId || '没有世界包')}</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const avatar = $('profileAvatar');
|
||||
if (avatar) {
|
||||
avatar.src = 'assets/avatars/main.png';
|
||||
avatar.onerror = () => { avatar.src = 'assets/avatars/custom.png'; };
|
||||
}
|
||||
$('reviveBtn')?.addEventListener('click', revive);
|
||||
$('moveBtn')?.addEventListener('click', move);
|
||||
els.root.querySelectorAll('.item-row').forEach((row) => {
|
||||
const itemId = row.dataset.item;
|
||||
row.querySelectorAll('[data-act]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => itemAction(itemId, btn.dataset.act));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function load(silent) {
|
||||
try {
|
||||
if (!state.cid) {
|
||||
state.cid = GameUI.param('containerId') || (GameUI.currentContainer() || {}).id || '';
|
||||
}
|
||||
if (!state.cid) throw new Error('缺少容器 id');
|
||||
if (!GameUI.S.ready) await GameUI.ready();
|
||||
state.profile = await GameUI.userProfile(state.cid);
|
||||
state.items = await GameUI.userBag(state.cid);
|
||||
state.map = await GameUI.placesData(state.cid);
|
||||
state.container = (GameUI.containers() || []).find((c) => c.id === state.cid) || GameUI.currentContainer();
|
||||
render();
|
||||
} catch (err) {
|
||||
if (!silent) toast('读取失败:' + (err.message || err));
|
||||
els.root.innerHTML = `<div class="g-empty">读取失败:${esc(err.message || err)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function itemAction(itemId, action) {
|
||||
if (state.busy) return;
|
||||
if (action === 'drop' && !window.confirm('确定抛弃 1 个吗?')) return;
|
||||
const body = { action };
|
||||
if (action === 'give') {
|
||||
const sel = $('giveTarget');
|
||||
const target = sel ? sel.value : '';
|
||||
if (!target) { toast('没有可给予的对象'); return; }
|
||||
body.target = target;
|
||||
}
|
||||
state.busy = true;
|
||||
try {
|
||||
await GameUI.bagAction(itemId, action, body);
|
||||
toast(action === 'use' ? '用掉了' : action === 'drop' ? '已抛弃' : '已送出');
|
||||
await load(true);
|
||||
} catch (err) {
|
||||
toast('操作失败:' + (err.message || err));
|
||||
} finally {
|
||||
state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function move() {
|
||||
if (state.busy) return;
|
||||
const sel = $('movePlace');
|
||||
const placeId = sel ? sel.value : '';
|
||||
if (!placeId) return;
|
||||
state.busy = true;
|
||||
try {
|
||||
await GameUI.moveMember(placeId, 'user', state.cid);
|
||||
const place = ((state.map && state.map.places) || []).find((p) => p.id === placeId);
|
||||
toast('已移动到「' + ((place && place.name) || placeId) + '」');
|
||||
await load(true);
|
||||
} catch (err) {
|
||||
toast('移动失败:' + (err.message || err));
|
||||
} finally {
|
||||
state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function revive() {
|
||||
if (state.busy) return;
|
||||
state.busy = true;
|
||||
try {
|
||||
await GameUI.reviveUser(state.cid);
|
||||
toast('已复活');
|
||||
await load(true);
|
||||
} catch (err) {
|
||||
toast('复活失败:' + (err.message || err));
|
||||
} finally {
|
||||
state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
els.back.addEventListener('click', () => GameUI.close());
|
||||
els.close.addEventListener('click', () => GameUI.close());
|
||||
els.refresh.addEventListener('click', () => load(false));
|
||||
|
||||
load(false);
|
||||
})();
|
||||
45
豆鲍/android/app/src/main/assets/ui-packs/galgame/duel.html
Normal file
@@ -0,0 +1,45 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>小人间 · 决斗</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="routes.css">
|
||||
</head>
|
||||
<body class="route-page">
|
||||
<div class="route-app">
|
||||
<header class="route-top">
|
||||
<button id="backBtn" class="cream-btn square" title="返回">←</button>
|
||||
<div class="route-title">
|
||||
<b>决斗</b>
|
||||
<span id="routeSub">这一场对话</span>
|
||||
</div>
|
||||
<button id="refreshBtn" class="cream-btn square" title="刷新">⟳</button>
|
||||
</header>
|
||||
|
||||
<div id="duelScroll" class="route-scroll">
|
||||
<div id="duelRoot"></div>
|
||||
</div>
|
||||
|
||||
<div class="route-foot">
|
||||
<span>多回合 · 每回合可换武器 · 双方同意才能停手 · 没有回合上限</span>
|
||||
<button id="closeBtn" class="route-close">收起</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 武器/物品选择面板 -->
|
||||
<div id="pickPanel" class="panel hidden">
|
||||
<div class="panel-card">
|
||||
<div class="panel-head">
|
||||
<span id="pickTitle">选择武器</span>
|
||||
<button id="pickClose" class="cream-btn square">✕</button>
|
||||
</div>
|
||||
<div id="pickBody" class="panel-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../ui-sdk/sdk.js"></script>
|
||||
<script src="duel.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
376
豆鲍/android/app/src/main/assets/ui-packs/galgame/duel.js
Normal file
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* 决斗路由(v3.37)
|
||||
* ---------------------------------------------------------------------------
|
||||
* 视觉小说风格的决斗面板:双方气血/状态、回合数、武器/被动道具、出招、说话、
|
||||
* 请求停手 / 回应停手、结果。判定全部在内核(duel_engine + 世界脚本),页面只
|
||||
* 负责显示和发请求 —— 客户端永远不能自己决定输赢。
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const els = {
|
||||
back: $('backBtn'), close: $('closeBtn'), refresh: $('refreshBtn'),
|
||||
sub: $('routeSub'), root: $('duelRoot'), scroll: $('duelScroll'),
|
||||
pick: $('pickPanel'), pickTitle: $('pickTitle'), pickBody: $('pickBody'), pickClose: $('pickClose'),
|
||||
};
|
||||
|
||||
const state = {
|
||||
duel: null,
|
||||
convId: '',
|
||||
busy: false,
|
||||
speaking: false,
|
||||
sayText: '',
|
||||
};
|
||||
|
||||
function toast(text) { if (text) GameUI.toast(text); }
|
||||
function esc(text) { return GameUI.escapeHtml(text); }
|
||||
|
||||
function sideById(id) {
|
||||
const d = state.duel;
|
||||
if (!d) return null;
|
||||
if (d.initiator && d.initiator.id === id) return d.initiator;
|
||||
if (d.target && d.target.id === id) return d.target;
|
||||
return null;
|
||||
}
|
||||
|
||||
function meSide() {
|
||||
const d = state.duel;
|
||||
if (!d) return null;
|
||||
if (d.initiator && d.initiator.isUser) return d.initiator;
|
||||
if (d.target && d.target.isUser) return d.target;
|
||||
return d.initiator || null;
|
||||
}
|
||||
|
||||
function foeSide() {
|
||||
const d = state.duel;
|
||||
const me = meSide();
|
||||
if (!d || !me) return null;
|
||||
return me.id === (d.initiator || {}).id ? d.target : d.initiator;
|
||||
}
|
||||
|
||||
function hpOf(side) {
|
||||
const stats = (side && side.stats) || [];
|
||||
const stat = stats.find((s) => /气血|生命|HP|血量/i.test(s.name || '')) || stats[0] || null;
|
||||
if (!stat) return null;
|
||||
const v = Number(stat.value) || 0;
|
||||
const max = Number(stat.max) || 0;
|
||||
const min = Number(stat.min) || 0;
|
||||
const ratio = max > min ? Math.max(0, Math.min(1, (v - min) / (max - min))) : 1;
|
||||
return { name: stat.name || '气血', value: v, max, ratio };
|
||||
}
|
||||
|
||||
function statusText(item) {
|
||||
if (!item) return '';
|
||||
if (typeof item === 'string') return item;
|
||||
let text = item.name || '';
|
||||
const left = item.remaining != null ? item.remaining : item.turns;
|
||||
if (left != null && Number(left) > 0) text += ` · ${left}`;
|
||||
return text;
|
||||
}
|
||||
|
||||
function outcomeText(side) {
|
||||
if (!side) return '';
|
||||
return ({ win: '赢', lose: '输', draw: '平局', stop: '停手' })[side.outcome] || '';
|
||||
}
|
||||
|
||||
function renderFighter(side, mine) {
|
||||
const hp = hpOf(side);
|
||||
const stats = (side.stats || []).filter((s) => !hp || s.name !== hp.name);
|
||||
const statuses = (side.statuses || []).map(statusText).filter(Boolean);
|
||||
const outcome = outcomeText(side);
|
||||
return `
|
||||
<div class="fighter ${mine ? 'me' : ''} ${side.dead ? 'dead' : ''}">
|
||||
<div class="fighter-name">${esc(side.name || '?')}</div>
|
||||
<div class="fighter-role">${mine ? '你' : '对手'}${side.dead ? ' · 已倒下' : ''}${outcome ? ' · ' + outcome : ''}</div>
|
||||
${hp ? `
|
||||
<div class="hp-line"><span>${esc(hp.name)}</span><span>${Math.round(hp.value)} / ${Math.round(hp.max)}</span></div>
|
||||
<div class="hp-bar"><i style="width:${Math.round(hp.ratio * 100)}%"></i></div>` : `
|
||||
<div class="hp-line"><span>状态</span><span>—</span></div>`}
|
||||
${stats.map((s) => `<div class="fighter-stat"><span>${esc(s.name || '')}</span><b>${Math.round(Number(s.value) || 0)}</b></div>`).join('')}
|
||||
${statuses.length ? `<div style="margin-top:5px">${statuses.map((t) => `<span class="badge">${esc(t)}</span>`).join('')}</div>` : ''}
|
||||
${side.weapons && side.weapons.length
|
||||
? `<div class="fighter-stat"><span>武器</span><b>${esc((side.weapon || side.weapons[0]).name || '')}</b></div>`
|
||||
: `<div class="fighter-stat"><span>武器</span><b style="color:#ff9aa7">没有</b></div>`}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderLog() {
|
||||
const log = (state.duel && state.duel.log) || [];
|
||||
const rows = log.slice(-8).map((entry) => {
|
||||
const lines = (entry.lines || []).filter(Boolean);
|
||||
if (!lines.length) return '';
|
||||
return `<div class="turn ${entry.kind === 'talk' ? 'talk' : ''}">
|
||||
<b>第 ${entry.round || '?'} 回合${entry.kind === 'talk' ? ' · 对话' : ''}</b>
|
||||
<p>${lines.map(esc).join('\n')}</p>
|
||||
</div>`;
|
||||
}).filter(Boolean).join('');
|
||||
return rows || '<div class="g-empty">还没有回合记录。</div>';
|
||||
}
|
||||
|
||||
function resultBanner(d) {
|
||||
if (!d) return '';
|
||||
if (d.status === 'finished' || d.status === 'interrupted') {
|
||||
const me = meSide();
|
||||
const my = outcomeText(me);
|
||||
const title = d.winnerName ? `「${d.winnerName}」获胜` : (d.status === 'interrupted' ? '双方同意停手' : '这一场结束了');
|
||||
return `<div class="result-banner">
|
||||
${esc(title)}${my ? ` · 你:<b>${esc(my)}</b>` : ''}
|
||||
${d.result ? `<div style="margin-top:6px;font-size:12px;color:#e6cfc4">${esc(d.result)}</div>` : ''}
|
||||
<div style="margin-top:5px;font-size:12px;color:#e6cfc4">共 ${d.round || 0} 回合</div>
|
||||
</div>`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function weaponsPanel() {
|
||||
const me = meSide();
|
||||
const weapons = (me && me.weapons) || [];
|
||||
openPick('选择这一回合的武器', weapons, me && me.weapon, (w) => {
|
||||
chooseWeapon(w.id);
|
||||
}, '没有可用的 target 类武器 —— 没有武器的一方会被判负。');
|
||||
}
|
||||
|
||||
function itemsPanel() {
|
||||
const me = meSide();
|
||||
const items = (me && me.passiveItems) || [];
|
||||
openPick('选择本回合的被动物品(用物品 = 这回合不攻击)', items, me && me.item, (item) => {
|
||||
chooseItem(item.id);
|
||||
}, '身上没有被动物品。');
|
||||
}
|
||||
|
||||
function openPick(title, list, selected, onPick, emptyText) {
|
||||
els.pickTitle.textContent = title;
|
||||
els.pickBody.innerHTML = '';
|
||||
if (!list.length) {
|
||||
els.pickBody.innerHTML = `<div class="g-empty">${esc(emptyText)}</div>`;
|
||||
}
|
||||
list.forEach((item) => {
|
||||
const row = document.createElement('button');
|
||||
row.className = 'save-card' + (selected && selected.id === item.id ? ' active' : '');
|
||||
row.innerHTML = `<div class="save-main">
|
||||
<div class="save-title">${esc(item.name || item.id)}</div>
|
||||
<div class="save-sub">${esc(item.desc || item.kind || '')}</div>
|
||||
</div>`;
|
||||
row.addEventListener('click', () => {
|
||||
closePick();
|
||||
onPick(item);
|
||||
});
|
||||
els.pickBody.appendChild(row);
|
||||
});
|
||||
const cancel = document.createElement('button');
|
||||
cancel.className = 'panel-btn ghost';
|
||||
cancel.textContent = '取消(用武器攻击)';
|
||||
cancel.addEventListener('click', () => { closePick(); chooseItem(''); });
|
||||
if (title.indexOf('物品') >= 0) els.pickBody.appendChild(cancel);
|
||||
els.pick.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closePick() { els.pick.classList.add('hidden'); }
|
||||
|
||||
function render() {
|
||||
const d = state.duel;
|
||||
const container = GameUI.currentContainer() || {};
|
||||
els.sub.textContent = [container.name, d && d.round ? `第 ${d.round} 回合` : ''].filter(Boolean).join(' · ')
|
||||
|| '这一场对话';
|
||||
|
||||
if (!d) {
|
||||
els.root.innerHTML = `<div class="g-empty">
|
||||
这一场对话里没有决斗。<br>
|
||||
在聊天页成员条上长按 @某人 →「决斗」开始一场。
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const me = meSide();
|
||||
const foe = foeSide();
|
||||
const running = d.status === 'active' || d.status === 'stop_pending';
|
||||
const myWeapons = (me && me.weapons) || [];
|
||||
const myItems = (me && me.passiveItems) || [];
|
||||
const stopPendingByMe = d.pendingStopBy === 'user';
|
||||
const needsAnswer = d.status === 'stop_pending' && d.pendingStopBy && d.pendingStopBy !== 'user';
|
||||
const missing = (me && !me.hasWeapon) || (foe && !foe.hasWeapon);
|
||||
|
||||
els.root.innerHTML = `
|
||||
${resultBanner(d)}
|
||||
<div class="round-chip">第 ${d.round || 0} 回合${d.status === 'stop_pending' ? ' · 停手请求中' : ''}</div>
|
||||
<div class="arena">
|
||||
${me ? renderFighter(me, true) : ''}
|
||||
<div class="versus">VS</div>
|
||||
${foe ? renderFighter(foe, false) : ''}
|
||||
</div>
|
||||
${missing ? `<div class="g-card"><div class="g-hint" style="color:#ffc0cb">
|
||||
⚠ 有一方没有 target 类武器 —— 按规则没有武器的一方会被判负。可以在背包里准备武器。
|
||||
</div></div>` : ''}
|
||||
|
||||
<div class="g-card">
|
||||
<h3>这一回合</h3>
|
||||
<div class="chips">
|
||||
${myWeapons.length ? `<button class="chip-opt ${!me.item ? 'on' : ''}" id="weaponBtn">
|
||||
武器:${esc((me.weapon || myWeapons[0] || {}).name || '')} ▾</button>` : ''}
|
||||
${myItems.length ? `<button class="chip-opt ${me.item ? 'on' : ''}" id="itemBtn">
|
||||
物品:${esc((me.item || {}).name || '不用,直接攻击')} ▾</button>` : ''}
|
||||
</div>
|
||||
<div class="action-line">
|
||||
<button class="g-btn" id="attackBtn" ${running && !state.busy ? '' : 'disabled'}>${state.busy ? '结算中…' : '出招'}</button>
|
||||
${d.status === 'active' ? `<button class="g-btn danger" id="stopBtn" ${state.busy ? 'disabled' : ''}>请求停手</button>` : ''}
|
||||
${d.status === 'stop_pending' && stopPendingByMe ? `<button class="g-btn ghost" disabled>等待对方回应…</button>` : ''}
|
||||
${needsAnswer ? `
|
||||
<button class="g-btn" id="agreeStop" ${state.busy ? 'disabled' : ''}>同意停手</button>
|
||||
<button class="g-btn ghost" id="refuseStop" ${state.busy ? 'disabled' : ''}>继续打</button>` : ''}
|
||||
</div>
|
||||
<div class="duel-say">
|
||||
<input id="sayInput" maxlength="200" placeholder="对对手说一句……(不会推进回合)">
|
||||
<button class="g-btn" id="sayBtn" ${state.speaking ? 'disabled' : ''}>${state.speaking ? '…' : '说'}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>回合记录</h3>
|
||||
<div class="duel-log">${renderLog()}</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
$('weaponBtn')?.addEventListener('click', weaponsPanel);
|
||||
$('itemBtn')?.addEventListener('click', itemsPanel);
|
||||
$('attackBtn')?.addEventListener('click', advance);
|
||||
$('stopBtn')?.addEventListener('click', requestStop);
|
||||
$('agreeStop')?.addEventListener('click', () => answerStop(true));
|
||||
$('refuseStop')?.addEventListener('click', () => answerStop(false));
|
||||
$('sayBtn')?.addEventListener('click', say);
|
||||
const input = $('sayInput');
|
||||
if (input) {
|
||||
input.value = state.sayText || '';
|
||||
input.addEventListener('input', () => { state.sayText = input.value; });
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); say(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function applyDuel(duel) {
|
||||
state.duel = duel || null;
|
||||
render();
|
||||
}
|
||||
|
||||
function setBusy(on) {
|
||||
state.busy = on;
|
||||
render();
|
||||
}
|
||||
|
||||
async function refresh(silent) {
|
||||
try {
|
||||
const d = await GameUI.currentDuel();
|
||||
applyDuel(d);
|
||||
if (!silent && !d) toast('这一场对话里没有决斗');
|
||||
} catch (err) {
|
||||
if (!silent) toast('读取决斗失败:' + (err.message || err));
|
||||
}
|
||||
}
|
||||
|
||||
async function advance() {
|
||||
const d = state.duel;
|
||||
if (!d || state.busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const next = await GameUI.advanceDuel(d.id);
|
||||
applyDuel(next);
|
||||
toast('这一回合结算完了');
|
||||
} catch (err) {
|
||||
toast('出招失败:' + (err.message || err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseWeapon(id) {
|
||||
if (!state.duel || !id) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
applyDuel(await GameUI.chooseWeapon(state.duel.id, id));
|
||||
toast('下回合用这把武器');
|
||||
} catch (err) {
|
||||
toast('换武器失败:' + (err.message || err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseItem(id) {
|
||||
if (!state.duel) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
applyDuel(await GameUI.chooseDuelItem(state.duel.id, id || ''));
|
||||
toast(id ? '这回合用物品,不攻击' : '这回合用武器攻击');
|
||||
} catch (err) {
|
||||
toast('选物品失败:' + (err.message || err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestStop() {
|
||||
if (!state.duel || state.busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const next = await GameUI.requestDuelStop(state.duel.id);
|
||||
applyDuel(next);
|
||||
const now = state.duel;
|
||||
if (now && now.status === 'interrupted') toast('双方同意,决斗停手了');
|
||||
else if (now && now.status === 'stop_pending' && now.pendingStopBy === 'user') toast('已经请求停手,等对方回应');
|
||||
else toast('对方不同意,决斗继续');
|
||||
} catch (err) {
|
||||
toast('请求停手失败:' + (err.message || err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function answerStop(agree) {
|
||||
if (!state.duel || state.busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
applyDuel(await GameUI.answerDuelStop(state.duel.id, agree));
|
||||
toast(agree ? '双方同意,决斗停手了' : '决斗继续');
|
||||
} catch (err) {
|
||||
toast('回应失败:' + (err.message || err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function say() {
|
||||
const input = $('sayInput');
|
||||
const text = (input ? input.value : state.sayText || '').trim();
|
||||
if (!text || !state.duel || state.speaking) return;
|
||||
state.speaking = true;
|
||||
state.sayText = '';
|
||||
render();
|
||||
try {
|
||||
const duelId = state.duel.id;
|
||||
const next = await GameUI.sayInDuel(duelId, text);
|
||||
applyDuel(next);
|
||||
if (next && next.replied === false) toast('对手没有回应(可能没配模型或网络不通)');
|
||||
} catch (err) {
|
||||
toast('说不了:' + (err.message || err));
|
||||
} finally {
|
||||
state.speaking = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
els.back.addEventListener('click', () => GameUI.close());
|
||||
els.close.addEventListener('click', () => GameUI.close());
|
||||
els.refresh.addEventListener('click', () => refresh(false));
|
||||
els.pickClose.addEventListener('click', closePick);
|
||||
els.pick.addEventListener('click', (e) => { if (e.target === els.pick) closePick(); });
|
||||
|
||||
async function boot() {
|
||||
state.convId = GameUI.param('conversationId') || '';
|
||||
try { await GameUI.ready(); } catch (err) { toast('读取失败:' + (err.message || err)); }
|
||||
if (!state.convId) state.convId = GameUI.conversationId();
|
||||
await refresh(true);
|
||||
}
|
||||
|
||||
boot();
|
||||
})();
|
||||
1398
豆鲍/android/app/src/main/assets/ui-packs/galgame/game.js
Normal file
137
豆鲍/android/app/src/main/assets/ui-packs/galgame/index.html
Normal file
@@ -0,0 +1,137 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>小人间 · Galgame</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<!-- 背景 / 角色 -->
|
||||
<div id="bg" class="bg"></div>
|
||||
<div class="bg-room"></div>
|
||||
<div class="bg-bloom"></div>
|
||||
<div class="bg-vignette"></div>
|
||||
<div id="petals" class="petals"></div>
|
||||
|
||||
<div id="character" class="character">
|
||||
<img id="sprite" class="sprite" alt="">
|
||||
<div id="fallback" class="fallback">
|
||||
<div class="fallback-halo"></div>
|
||||
<img id="avatarBig" class="avatar-big" alt="">
|
||||
<div class="fallback-ring"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 顶栏 -->
|
||||
<header class="topbar">
|
||||
<div class="top-left">
|
||||
<button id="menuBtn" class="cream-btn square" title="侧边栏">☰</button>
|
||||
<button id="pauseBtn" class="cream-btn" title="暂停/继续"><b class="glyph">Ⅱ</b><span>暂停</span></button>
|
||||
<button id="speedBtn" class="cream-btn" title="文字速度"><b class="glyph">»</b><span>2×</span></button>
|
||||
</div>
|
||||
<div class="top-right">
|
||||
<div class="hp-card">
|
||||
<span class="hp-heart">♥</span>
|
||||
<div class="hp-meta"><b>HP</b><span id="hpText">—</span></div>
|
||||
<div class="hp-track"><i id="hpFill"></i></div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 左侧 HUD:当前位置 / 数值 / 在场成员 / 功能入口(v3.41) -->
|
||||
<aside class="side-rail">
|
||||
<div class="rail-block">
|
||||
<div class="rail-label">当前位置</div>
|
||||
<div id="sceneChip" class="scene-chip"><span id="sceneName">场景</span></div>
|
||||
</div>
|
||||
|
||||
<div class="rail-block">
|
||||
<div class="rail-label">数值</div>
|
||||
<div id="hud" class="hud hidden"></div>
|
||||
</div>
|
||||
|
||||
<div class="rail-block rail-grow">
|
||||
<div class="rail-label">在场 / @</div>
|
||||
<div id="memberBar" class="member-bar"></div>
|
||||
</div>
|
||||
|
||||
<nav class="rail-nav">
|
||||
<button data-rail="map"><span class="ico">⌖</span>地图</button>
|
||||
<button data-rail="items"><span class="ico">▣</span>背包</button>
|
||||
<button data-rail="duel"><span class="ico">⚔</span>决斗</button>
|
||||
<button data-rail="residents"><span class="ico">☰</span>常驻</button>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<!-- 对话区 -->
|
||||
<section class="dock">
|
||||
<div id="choiceEcho" class="choice-echo"></div>
|
||||
<div class="dialogue">
|
||||
<!-- 工具调用动效:在对话框上方浮一条,告诉用户 AI 刚调了什么工具(v3.45) -->
|
||||
<div id="toolToast" class="tool-toast hidden">
|
||||
<span id="toolSpinner" class="tool-spinner"></span>
|
||||
<span id="toolText" class="tool-text">AI 正在调用</span>
|
||||
<b id="toolName" class="tool-name"></b>
|
||||
</div>
|
||||
<div class="nameplate"><span id="speakerName">……</span></div>
|
||||
<div id="box" class="box">
|
||||
<div id="dialogueText" class="text"></div>
|
||||
<div id="cursor" class="cursor">▼</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 输入 -->
|
||||
<div id="inputBar" class="input-bar">
|
||||
<div id="privateBar" class="private-bar hidden">
|
||||
<span>🔒 私聊 · <b id="privateName"></b></span>
|
||||
<button id="privateExit">退出</button>
|
||||
</div>
|
||||
<div class="input-row">
|
||||
<textarea id="input" rows="1" placeholder="说点什么……(Enter 发送)" autocomplete="off"></textarea>
|
||||
<button id="sendBtn" class="send-btn" title="发送">➤</button>
|
||||
<button id="stopBtn" class="stop-btn hidden" title="停止">■</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部按钮(图里的 Save / Info / Load / Skip / Log) -->
|
||||
<button id="actionsToggle" class="actions-toggle" title="展开功能栏">功能 <span>⌃</span></button>
|
||||
<nav class="actions" id="actions">
|
||||
<button id="actionsCollapse" class="actions-fold" title="收起功能栏">⌄</button>
|
||||
<button class="act" data-act="save"><span class="ico">↓</span><span>存档</span></button>
|
||||
<button class="act" data-act="info"><span class="ico">i</span><span>信息</span></button>
|
||||
<button class="act" data-act="load"><span class="ico">↑</span><span>读档</span></button>
|
||||
<button class="act" data-act="skip"><span class="ico">»</span><span>跳过</span></button>
|
||||
<button class="act" data-act="log"><span class="ico">☰</span><span>记录</span></button>
|
||||
<button class="act" data-act="settings"><span class="ico">⚙</span><span>设置</span></button>
|
||||
<button class="act" data-act="speak"><span class="ico">♪</span><span>朗读</span></button>
|
||||
<button class="act" data-act="newtopic"><span class="ico">+</span><span>新话题</span></button>
|
||||
</nav>
|
||||
</section>
|
||||
|
||||
<!-- 覆盖层 -->
|
||||
<div id="panel" class="panel hidden">
|
||||
<div class="panel-card">
|
||||
<div class="panel-head">
|
||||
<span id="panelTitle">记录</span>
|
||||
<button id="panelClose" class="cream-btn square">✕</button>
|
||||
</div>
|
||||
<div id="panelBody" class="panel-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast"></div>
|
||||
|
||||
<div id="errorBar" class="error-bar hidden">
|
||||
<span id="errorText"></span>
|
||||
<button id="errorClose">知道了</button>
|
||||
</div>
|
||||
|
||||
<div id="loading" class="loading">正在进入这一局……</div>
|
||||
</div>
|
||||
|
||||
<script src="../ui-sdk/sdk.js"></script>
|
||||
<script src="game.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
34
豆鲍/android/app/src/main/assets/ui-packs/galgame/map.html
Normal file
@@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>小人间 · 地图</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="routes.css">
|
||||
</head>
|
||||
<body class="route-page">
|
||||
<div id="routeApp" class="route-app">
|
||||
<header class="route-top">
|
||||
<button id="backBtn" class="cream-btn square" title="返回">←</button>
|
||||
<div class="route-title">
|
||||
<b>地图</b>
|
||||
<span id="routeSub">这一局</span>
|
||||
</div>
|
||||
<button id="reloadBtn" class="cream-btn square" title="刷新">⟳</button>
|
||||
</header>
|
||||
|
||||
<div id="mapWrap" class="map-wrap">
|
||||
<div id="mapLoading" class="route-loading">正在展开地图……</div>
|
||||
<iframe id="mapFrame" title="世界地图"></iframe>
|
||||
</div>
|
||||
|
||||
<div class="route-foot">
|
||||
<span id="mapHint">点地点:去这里 / 移人;长按地点看信息。地图本身仍由世界包定义。</span>
|
||||
<button id="closeBtn" class="route-close">收起地图</button>
|
||||
</div>
|
||||
</div>
|
||||
<script src="../ui-sdk/sdk.js"></script>
|
||||
<script src="map.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
143
豆鲍/android/app/src/main/assets/ui-packs/galgame/map.js
Normal file
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 地图路由(v3.37)
|
||||
* ---------------------------------------------------------------------------
|
||||
* 复用内核已经生成好的图形地图页(`/api/containers/<cid>/map/page`),把它装进
|
||||
* 自定义界面的外框里:奶油/玫瑰金的边框 + 原生返回;地图内部的缩放、点地点、
|
||||
* 移人、长按信息全部保持原样(页面里的 `Doubao.moved` 由原生壳接管)。
|
||||
*
|
||||
* 为什么用 iframe 而不是重画:地图是世界包资产(背景/区域/坐标/邻接)驱动的,
|
||||
* 内核那份页面已经把几何和交互做对了;重画会多一份"两边不一致"的维护负担。
|
||||
* 要改地图节点样式,世界包作者仍可用 `info.map.css`;外层也可以再注入皮肤 CSS。
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const els = {
|
||||
back: $('backBtn'), close: $('closeBtn'), reload: $('reloadBtn'),
|
||||
sub: $('routeSub'), frame: $('mapFrame'), loading: $('mapLoading'),
|
||||
hint: $('mapHint'), wrap: $('mapWrap'),
|
||||
};
|
||||
|
||||
let cid = '';
|
||||
let loaded = false;
|
||||
|
||||
function toast(text) {
|
||||
if (text) GameUI.toast(text);
|
||||
}
|
||||
|
||||
function setLoading(on, text) {
|
||||
els.loading.classList.toggle('hidden', !on);
|
||||
if (text) els.loading.textContent = text;
|
||||
}
|
||||
|
||||
function buildUrl() {
|
||||
if (!cid) return '';
|
||||
return `/api/containers/${encodeURIComponent(cid)}/map/page?t=${Date.now()}`;
|
||||
}
|
||||
|
||||
function injectSkin() {
|
||||
try {
|
||||
const doc = els.frame.contentDocument;
|
||||
if (!doc) return;
|
||||
const style = doc.createElement('style');
|
||||
style.textContent = `
|
||||
:root {
|
||||
--map-bg: #1b0c12;
|
||||
--map-line: rgba(255, 168, 197, .78);
|
||||
--map-node: #ff8fb4;
|
||||
--map-node-ring: rgba(255, 140, 180, .38);
|
||||
--map-node-text: #ffe0ea;
|
||||
--map-region: rgba(216, 179, 148, .68);
|
||||
--map-region-fill: rgba(216, 179, 148, .07);
|
||||
--map-marker: #ff5f92;
|
||||
}
|
||||
html, body { background: #180b10 !important; }
|
||||
.map-node-dot { box-shadow: 0 0 0 2px rgba(255, 195, 220, .55), 0 0 18px rgba(255, 140, 180, .35) !important; }
|
||||
.map-marker-glyph { color: #ff5f92 !important; }
|
||||
#sheet, .sheet { background: linear-gradient(180deg, #fff8f0, #f0daca) !important;
|
||||
color: #3b1c25 !important; border: 2px solid #2d0f18 !important;
|
||||
box-shadow: 0 0 0 4px rgba(216, 179, 148, .3), 0 14px 34px rgba(0,0,0,.55) !important; }
|
||||
#sheet .sub, #sheet .desc { color: #6b4350 !important; }
|
||||
#sheet button { background: #f3dccb !important; color: #3b1c25 !important;
|
||||
border: 1px solid #b98b72 !important; }
|
||||
#sheet button.primary { background: linear-gradient(180deg, #ffd0e0, #ff8fb4) !important;
|
||||
border-color: #d94f7c !important; color: #3c1020 !important; }
|
||||
.map-region-label { color: #ffe6ef !important; text-shadow: 0 1px 2px #000; }
|
||||
`;
|
||||
doc.head.appendChild(style);
|
||||
} catch (_) {
|
||||
// 跨域/页面还没准备好就算了,地图本身仍然能用
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFrame(force) {
|
||||
if (!cid) {
|
||||
setLoading(false);
|
||||
els.loading.classList.remove('hidden');
|
||||
els.loading.textContent = '这一局没有地图(缺少容器 id)';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await GameUI.placesData(cid);
|
||||
} catch (err) {
|
||||
setLoading(false);
|
||||
els.loading.classList.remove('hidden');
|
||||
els.loading.textContent = '这一局没有地图:' + (err.message || err);
|
||||
return;
|
||||
}
|
||||
if (loaded && !force) return;
|
||||
loaded = true;
|
||||
const url = buildUrl();
|
||||
els.frame.src = url;
|
||||
setLoading(true, '正在展开地图……');
|
||||
els.frame.onload = () => {
|
||||
setLoading(false);
|
||||
injectSkin();
|
||||
};
|
||||
}
|
||||
|
||||
function close() {
|
||||
GameUI.close();
|
||||
}
|
||||
|
||||
els.back.addEventListener('click', close);
|
||||
els.close.addEventListener('click', close);
|
||||
els.reload.addEventListener('click', () => loadFrame(true));
|
||||
|
||||
async function boot() {
|
||||
setLoading(true, '正在读取这一局……');
|
||||
try {
|
||||
await GameUI.ready();
|
||||
} catch (err) {
|
||||
// 内核刚启动/断网时页面至少能显示错误,不白屏
|
||||
els.sub.textContent = '读取失败';
|
||||
toast('读取失败:' + (err.message || err));
|
||||
}
|
||||
cid = GameUI.param('containerId') || (GameUI.currentContainer() || {}).id || '';
|
||||
if (!cid) {
|
||||
// 有些入口只给 conversationId,从会话里反查容器
|
||||
const conv = GameUI.conversation() || {};
|
||||
cid = conv.containerId || '';
|
||||
}
|
||||
const container = GameUI.currentContainer() || {};
|
||||
const place = GameUI.currentPlace() || {};
|
||||
els.sub.textContent = [container.name, place.name].filter(Boolean).join(' · ') || '这一局';
|
||||
if (place.name) els.hint.textContent = `当前地点:${place.name} · 点地点去这里 / 移人,长按看信息。`;
|
||||
loadFrame(false);
|
||||
}
|
||||
|
||||
// 页面回到前台(例如从原生管理页回来)时,地图可能已经变了
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible' && loaded) {
|
||||
// 不自动重载,避免打断用户缩放;只刷新标题
|
||||
GameUI.resume().then(() => {
|
||||
const container = GameUI.currentContainer() || {};
|
||||
const place = GameUI.currentPlace() || {};
|
||||
els.sub.textContent = [container.name, place.name].filter(Boolean).join(' · ') || '这一局';
|
||||
}).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
boot();
|
||||
})();
|
||||
458
豆鲍/android/app/src/main/assets/ui-packs/galgame/routes.css
Normal file
@@ -0,0 +1,458 @@
|
||||
/* 路由页(地图 / 决斗 / 背包)共用。聊天页不加载这份。 */
|
||||
|
||||
.route-page {
|
||||
background: var(--wine-0);
|
||||
color: var(--cream);
|
||||
}
|
||||
|
||||
.route-app {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background:
|
||||
radial-gradient(circle at 50% 0%, rgba(120, 52, 74, 0.55), transparent 42%),
|
||||
linear-gradient(180deg, #1b0c12 0%, #2a1119 55%, #14080c 100%);
|
||||
}
|
||||
|
||||
.route-top {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
background: linear-gradient(180deg, rgba(22, 8, 13, .94), rgba(22, 8, 13, .55));
|
||||
border-bottom: 1px solid rgba(216, 179, 148, .25);
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.route-top .cream-btn.square {
|
||||
width: 38px;
|
||||
min-width: 38px;
|
||||
height: 38px;
|
||||
font-size: 20px;
|
||||
color: #5f1f32;
|
||||
}
|
||||
|
||||
.route-title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
padding-left: 2px;
|
||||
}
|
||||
|
||||
.route-title b {
|
||||
font-family: var(--serif);
|
||||
font-size: 20px;
|
||||
letter-spacing: .16em;
|
||||
color: var(--cream);
|
||||
text-shadow: 0 1px 2px #000;
|
||||
}
|
||||
|
||||
.route-title span {
|
||||
font-size: 10px;
|
||||
letter-spacing: .06em;
|
||||
color: rgba(240, 205, 217, .55);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.route-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 12px 12px 18px;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.route-scroll::-webkit-scrollbar { display: none; }
|
||||
|
||||
.route-foot {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 12px calc(9px + env(safe-area-inset-bottom));
|
||||
background: rgba(14, 5, 9, .78);
|
||||
border-top: 1px solid rgba(216, 179, 148, .2);
|
||||
font-size: 10px;
|
||||
line-height: 1.4;
|
||||
color: rgba(240, 205, 217, .55);
|
||||
}
|
||||
|
||||
.route-foot #mapHint { flex: 1; }
|
||||
|
||||
.route-close {
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid rgba(255, 168, 197, .42);
|
||||
background: rgba(255, 140, 180, .13);
|
||||
color: #ffd3e1;
|
||||
border-radius: 999px;
|
||||
padding: 5px 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.route-loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #1b0c12;
|
||||
color: var(--cream-2);
|
||||
font-family: var(--serif);
|
||||
font-size: 13px;
|
||||
letter-spacing: .14em;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 地图 */
|
||||
|
||||
.map-wrap {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 10px;
|
||||
border-radius: 16px;
|
||||
border: 2px solid rgba(216, 179, 148, .45);
|
||||
box-shadow: 0 0 0 4px rgba(20, 8, 12, .7), 0 14px 34px rgba(0, 0, 0, .5);
|
||||
overflow: hidden;
|
||||
background: #120a0d;
|
||||
}
|
||||
|
||||
#mapFrame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
background: #120a0d;
|
||||
}
|
||||
|
||||
/* 让内核地图页的浅色面板也带一点酒红边框(同源,注入 CSS 在 map.js) */
|
||||
.map-wrap.skin iframe { background: #180b10; }
|
||||
|
||||
/* ---------------------------------------------------------------- 通用卡片 */
|
||||
|
||||
.g-card {
|
||||
border: 1px solid rgba(216, 179, 148, .25);
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(180deg, rgba(62, 25, 37, .58), rgba(26, 10, 16, .68));
|
||||
padding: 11px 12px;
|
||||
box-shadow: inset 0 1px 0 rgba(255, 230, 240, .06), 0 6px 18px rgba(0, 0, 0, .25);
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.g-card h3 {
|
||||
margin: 0 0 8px;
|
||||
font-family: var(--serif);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .12em;
|
||||
color: #ffd9e5;
|
||||
}
|
||||
|
||||
.g-hint {
|
||||
color: rgba(240, 205, 217, .48);
|
||||
font-size: 10.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.g-btn {
|
||||
border: 1px solid rgba(255, 168, 197, .4);
|
||||
background: linear-gradient(180deg, rgba(255, 168, 197, .22), rgba(160, 52, 82, .22));
|
||||
color: #ffe0ea;
|
||||
border-radius: 10px;
|
||||
padding: 7px 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
font-family: var(--sans);
|
||||
}
|
||||
|
||||
.g-btn:active { transform: translateY(1px); }
|
||||
|
||||
.g-btn.ghost {
|
||||
border-color: rgba(216, 179, 148, .25);
|
||||
background: rgba(20, 8, 12, .35);
|
||||
color: rgba(240, 205, 217, .7);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.g-btn.danger {
|
||||
border-color: rgba(255, 120, 130, .5);
|
||||
background: rgba(120, 24, 40, .35);
|
||||
color: #ffd4dc;
|
||||
}
|
||||
|
||||
.g-btn:disabled { opacity: .4; }
|
||||
|
||||
.g-row { display: flex; align-items: center; gap: 8px; }
|
||||
|
||||
.g-empty {
|
||||
padding: 20px 12px;
|
||||
text-align: center;
|
||||
color: rgba(240, 205, 217, .5);
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 决斗 */
|
||||
|
||||
.arena {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.fighter {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: 1px solid rgba(216, 179, 148, .3);
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(180deg, rgba(72, 29, 44, .55), rgba(24, 9, 15, .72));
|
||||
padding: 9px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.fighter.me { border-color: rgba(255, 168, 197, .55); box-shadow: 0 0 0 1px rgba(255, 168, 197, .15); }
|
||||
.fighter.dead { filter: grayscale(.7); opacity: .75; }
|
||||
|
||||
.fighter-name {
|
||||
font-family: var(--serif);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: #ffe2ec;
|
||||
text-align: center;
|
||||
margin-bottom: 5px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.fighter-role {
|
||||
text-align: center;
|
||||
font-size: 9px;
|
||||
color: rgba(240, 205, 217, .5);
|
||||
letter-spacing: .1em;
|
||||
margin-bottom: 7px;
|
||||
}
|
||||
|
||||
.hp-line { display: flex; justify-content: space-between; font-size: 9.5px; color: rgba(240, 205, 217, .6); margin-bottom: 3px; }
|
||||
|
||||
.hp-bar {
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
background: #4a202d;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(20, 8, 12, .7);
|
||||
box-shadow: inset 0 2px 4px rgba(0, 0, 0, .5);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.hp-bar i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #ffa8c5, #d45c82);
|
||||
border-radius: inherit;
|
||||
box-shadow: 0 0 8px rgba(255, 140, 180, .4);
|
||||
transition: width .35s ease;
|
||||
}
|
||||
|
||||
.fighter-stat { display: flex; justify-content: space-between; font-size: 10px; color: #e6cfc4; padding: 1px 0; }
|
||||
.fighter-stat b { color: #ffd2e0; font-weight: 700; }
|
||||
|
||||
.versus {
|
||||
align-self: center;
|
||||
flex: 0 0 auto;
|
||||
width: 30px;
|
||||
text-align: center;
|
||||
font-family: var(--serif);
|
||||
font-size: 11px;
|
||||
color: var(--gold);
|
||||
letter-spacing: .08em;
|
||||
}
|
||||
|
||||
.round-chip {
|
||||
text-align: center;
|
||||
margin: 0 auto 10px;
|
||||
width: fit-content;
|
||||
padding: 3px 14px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(216, 179, 148, .4);
|
||||
background: rgba(20, 8, 12, .55);
|
||||
color: var(--cream-2);
|
||||
font-family: var(--serif);
|
||||
font-size: 11px;
|
||||
letter-spacing: .16em;
|
||||
}
|
||||
|
||||
.result-banner {
|
||||
text-align: center;
|
||||
padding: 10px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 168, 197, .45);
|
||||
background: rgba(255, 140, 180, .10);
|
||||
color: #ffd9e5;
|
||||
font-family: var(--serif);
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 4px; }
|
||||
|
||||
.chip-opt {
|
||||
border: 1px solid rgba(216, 179, 148, .32);
|
||||
background: rgba(20, 8, 12, .4);
|
||||
color: #f0cdd9;
|
||||
border-radius: 999px;
|
||||
padding: 3px 9px;
|
||||
font-size: 10.5px;
|
||||
}
|
||||
|
||||
.chip-opt.on {
|
||||
border-color: var(--rose);
|
||||
background: rgba(255, 140, 180, .18);
|
||||
color: #ffe0ea;
|
||||
}
|
||||
|
||||
.duel-log {
|
||||
max-height: 180px;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.duel-log::-webkit-scrollbar { display: none; }
|
||||
.duel-log .turn { border-top: 1px solid rgba(216, 179, 148, .1); padding: 6px 0; }
|
||||
.duel-log .turn:first-child { border-top: 0; }
|
||||
.duel-log .turn b { font-size: 9.5px; color: rgba(240, 205, 217, .45); letter-spacing: .06em; }
|
||||
.duel-log .turn p { margin: 2px 0 0; font-size: 11.5px; line-height: 1.65; color: #e8d3ca; white-space: pre-wrap; }
|
||||
.duel-log .turn.talk p { color: #ffd0df; }
|
||||
|
||||
.duel-say { display: flex; gap: 6px; margin-top: 8px; }
|
||||
.duel-say input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: 1px solid rgba(216, 179, 148, .28);
|
||||
border-radius: 9px;
|
||||
background: rgba(10, 4, 7, .5);
|
||||
color: var(--cream);
|
||||
padding: 8px 10px;
|
||||
font-size: 13px;
|
||||
outline: none;
|
||||
}
|
||||
.duel-say input::placeholder { color: rgba(240, 205, 217, .4); }
|
||||
|
||||
.action-line { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
|
||||
.action-line .g-btn { flex: 1; min-width: 88px; }
|
||||
|
||||
/* ---------------------------------------------------------------- 背包 */
|
||||
|
||||
.profile-head { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; }
|
||||
|
||||
.profile-avatar {
|
||||
width: 66px;
|
||||
height: 66px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
border: 2px solid var(--gold);
|
||||
box-shadow: 0 0 0 5px rgba(20, 8, 12, .7), 0 0 22px rgba(255, 150, 190, .15);
|
||||
background: var(--wine-2);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.profile-name { font-family: var(--serif); font-size: 22px; font-weight: 700; letter-spacing: .12em; color: #ffe2ec; }
|
||||
.profile-sub { margin-top: 3px; font-size: 10.5px; color: rgba(240, 205, 217, .55); line-height: 1.5; }
|
||||
.profile-dead { color: #ff9aa7; }
|
||||
|
||||
.stat-line { margin: 7px 0; }
|
||||
.stat-line .head { display: flex; justify-content: space-between; font-size: 11px; color: #e8d3ca; margin-bottom: 3px; }
|
||||
.stat-line .head b { color: #ffd2e0; }
|
||||
.stat-line .track { height: 8px; border-radius: 999px; background: rgba(10, 4, 7, .65); overflow: hidden; }
|
||||
.stat-line .track i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #ffa8c5, #d45c82); }
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
margin: 2px 4px 2px 0;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 168, 197, .35);
|
||||
color: #ffc7da;
|
||||
font-size: 10.5px;
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
border-top: 1px solid rgba(216, 179, 148, .1);
|
||||
}
|
||||
.item-row:first-of-type { border-top: 0; }
|
||||
.item-main { flex: 1; min-width: 0; }
|
||||
.item-name { font-size: 12.5px; color: #ffe0ea; font-weight: 700; }
|
||||
.item-desc { margin-top: 1px; font-size: 10px; color: rgba(240, 205, 217, .5); line-height: 1.45; }
|
||||
.item-count { flex: 0 0 auto; font-family: var(--serif); font-size: 12px; color: var(--gold); }
|
||||
.item-actions { display: flex; gap: 5px; flex: 0 0 auto; }
|
||||
.item-actions .g-btn { padding: 4px 8px; font-size: 10.5px; }
|
||||
|
||||
.g-select {
|
||||
border: 1px solid rgba(216, 179, 148, .3);
|
||||
border-radius: 8px;
|
||||
background: rgba(10, 4, 7, .55);
|
||||
color: var(--cream);
|
||||
padding: 5px 7px;
|
||||
font-size: 11px;
|
||||
max-width: 150px;
|
||||
}
|
||||
|
||||
/* 小屏 */
|
||||
@media (max-height: 680px) {
|
||||
.route-title b { font-size: 18px; }
|
||||
.duel-log { max-height: 130px; }
|
||||
.profile-avatar { width: 56px; height: 56px; }
|
||||
}
|
||||
|
||||
|
||||
/* ---------------------------------------------------------------- BACKLOG / SETTINGS */
|
||||
|
||||
.backlog-row {
|
||||
border: 1px solid rgba(216, 179, 148, .18);
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(180deg, rgba(62, 25, 37, .46), rgba(24, 10, 16, .62));
|
||||
padding: 9px 11px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.backlog-row.user {
|
||||
border-color: rgba(255, 168, 197, .35);
|
||||
background: linear-gradient(180deg, rgba(96, 35, 53, .5), rgba(32, 12, 19, .7));
|
||||
}
|
||||
.backlog-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.backlog-meta b { font-family: var(--serif); font-size: 12.5px; color: #ffd9e5; letter-spacing: .08em; }
|
||||
.backlog-meta span { font-size: 9.5px; color: rgba(240, 205, 217, .4); }
|
||||
.backlog-text { font-size: 12.5px; line-height: 1.7; color: #ead8cf; white-space: pre-wrap; word-break: break-word; }
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 7px 0;
|
||||
font-size: 12.5px;
|
||||
color: #efd9d2;
|
||||
}
|
||||
.setting-val { color: var(--gold); font-size: 11px; }
|
||||
.setting-check { display: flex; align-items: center; gap: 5px; color: #efd9d2; font-size: 12px; }
|
||||
.setting-check input { accent-color: var(--rose-deep); }
|
||||
.setting-range { width: 100%; accent-color: var(--rose-deep); margin: 2px 0 6px; }
|
||||
@@ -0,0 +1,59 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>小人间 · SETTINGS</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="routes.css">
|
||||
</head>
|
||||
<body class="route-page">
|
||||
<div class="route-app">
|
||||
<header class="route-top">
|
||||
<button id="back" class="cream-btn square" title="返回">←</button>
|
||||
<div class="route-title"><b>SETTINGS</b><span>只改这套 UI 的阅读体验</span></div>
|
||||
</header>
|
||||
|
||||
<div class="route-scroll">
|
||||
<div class="g-card">
|
||||
<h3>阅读</h3>
|
||||
<div class="setting-row">
|
||||
<label for="theme">配色</label>
|
||||
<select id="theme" class="g-select">
|
||||
<option value="wine">葡萄酒(默认)</option>
|
||||
<option value="night">深夜蓝</option>
|
||||
<option value="rose">玫瑰灰</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<label for="font">对白字号</label>
|
||||
<span id="fontVal" class="setting-val">17px</span>
|
||||
</div>
|
||||
<input id="font" class="setting-range" type="range" min="15" max="22" step="1" value="17">
|
||||
<div class="setting-row">
|
||||
<label for="speed">文字速度</label>
|
||||
<label class="setting-check"><input id="speed" type="checkbox"> 2× 快进</label>
|
||||
</div>
|
||||
<p class="g-hint">这些设置只属于当前 UI 包,存在本机;换 UI 包/世界包都不会被覆盖。</p>
|
||||
</div>
|
||||
|
||||
<div class="g-card">
|
||||
<h3>说明</h3>
|
||||
<p class="g-hint">这是 UI 包里的 <b>settings.html</b>,不是原生设置。<br>
|
||||
想加自己的页面,就在界面包编辑器里新建一个 HTML,再用
|
||||
<code>GameUI.openPage('你的页面.html')</code> 跳过去。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="route-foot">
|
||||
<button id="reset" class="g-btn ghost">恢复默认</button>
|
||||
<span style="flex:1"></span>
|
||||
<button id="save" class="g-btn">保存并重载</button>
|
||||
<button id="close" class="route-close">收起</button>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script src="../ui-sdk/sdk.js"></script>
|
||||
<script src="settings.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
72
豆鲍/android/app/src/main/assets/ui-packs/galgame/settings.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/* UI 包内的阅读设置页(v3.39)。只存 localStorage,不碰内核设置。 */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const KEY = 'galgame:ui';
|
||||
const DEFAULTS = { theme: 'wine', font: 17, speed2: false };
|
||||
|
||||
const els = {
|
||||
theme: document.getElementById('theme'),
|
||||
font: document.getElementById('font'),
|
||||
fontVal: document.getElementById('fontVal'),
|
||||
speed: document.getElementById('speed'),
|
||||
back: document.getElementById('back'),
|
||||
close: document.getElementById('close'),
|
||||
save: document.getElementById('save'),
|
||||
reset: document.getElementById('reset'),
|
||||
};
|
||||
|
||||
function read() {
|
||||
try {
|
||||
return Object.assign({}, DEFAULTS, JSON.parse(localStorage.getItem(KEY) || '{}'));
|
||||
} catch (_) {
|
||||
return Object.assign({}, DEFAULTS);
|
||||
}
|
||||
}
|
||||
|
||||
function fill(prefs) {
|
||||
els.theme.value = prefs.theme || 'wine';
|
||||
els.font.value = String(prefs.font || 17);
|
||||
els.fontVal.textContent = `${els.font.value}px`;
|
||||
els.speed.checked = !!prefs.speed2;
|
||||
}
|
||||
|
||||
function collect() {
|
||||
return {
|
||||
theme: els.theme.value || 'wine',
|
||||
font: Number(els.font.value) || 17,
|
||||
speed2: !!els.speed.checked,
|
||||
};
|
||||
}
|
||||
|
||||
function preview() {
|
||||
const p = collect();
|
||||
document.documentElement.dataset.theme = p.theme;
|
||||
document.documentElement.style.setProperty('--dialogue-size', `${p.font}px`);
|
||||
}
|
||||
|
||||
els.font.addEventListener('input', () => {
|
||||
els.fontVal.textContent = `${els.font.value}px`;
|
||||
preview();
|
||||
});
|
||||
els.theme.addEventListener('change', preview);
|
||||
els.speed.addEventListener('change', preview);
|
||||
|
||||
els.back.addEventListener('click', () => GameUI.close());
|
||||
els.close.addEventListener('click', () => GameUI.close());
|
||||
els.reset.addEventListener('click', () => {
|
||||
fill(DEFAULTS);
|
||||
preview();
|
||||
});
|
||||
els.save.addEventListener('click', () => {
|
||||
localStorage.setItem(KEY, JSON.stringify(collect()));
|
||||
try {
|
||||
GameUI.toast('已保存,正在重载聊天页');
|
||||
GameUI.reloadChat();
|
||||
} catch (_) {}
|
||||
setTimeout(() => GameUI.close(), 160);
|
||||
});
|
||||
|
||||
fill(read());
|
||||
preview();
|
||||
})();
|
||||
1841
豆鲍/android/app/src/main/assets/ui-packs/galgame/style.css
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"id": "galgame",
|
||||
"name": "月影 · Galgame",
|
||||
"version": "2.0.0",
|
||||
"description": "深靛蓝夜海 + 香槟金对白窗 + 全身立绘 + 左侧 HUD(位置/数值/在场/地图/背包)",
|
||||
"author": "小人间",
|
||||
"entry": "index.html",
|
||||
"builtin": true
|
||||
}
|
||||
886
豆鲍/android/app/src/main/assets/ui-packs/ui-sdk/sdk.js
Normal file
@@ -0,0 +1,886 @@
|
||||
/**
|
||||
* 小人间 · 游戏界面 SDK(v3.36 P1)
|
||||
* =================================
|
||||
*
|
||||
* 所有「自定义游戏界面」模板共用的一份胶水层。它只做三件事:
|
||||
*
|
||||
* 1. **读内核**:/api/state /api/conversations/<id> /api/chat/poll …
|
||||
* 2. **包聊天**:send() 负责 POST /api/chat 然后轮询增量事件,模板不用
|
||||
* 自己实现 200ms 轮询和事件状态机。
|
||||
* 3. **通知 App**:调原生能力(打开侧边栏 / 管理页 / 停用自定义界面)。
|
||||
* Android 里由 `GameUiScreen` 注入 `window.Doubao`;网页里没有这个对象,
|
||||
* 所有桥调用都会安全地变成 no-op。
|
||||
*
|
||||
* 模板加载方式(从 /ui-packs/<包名>/index.html 里):
|
||||
*
|
||||
* <script src="../ui-sdk/sdk.js"></script>
|
||||
* <script>
|
||||
* await GameUI.ready(); // 拉 state + 当前会话
|
||||
* GameUI.on('delta', ({ text }) => …);
|
||||
* GameUI.chat.send('你好');
|
||||
* </script>
|
||||
*
|
||||
* ★ 这是**游戏内界面**,不是管理界面:侧边栏/会议/容器/设置仍由原生负责。
|
||||
* 模板能拿到内核全部 HTTP 接口(同源),这里包的只是最常用的一层。
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const params = new URLSearchParams(location.search);
|
||||
const bridge = window.Doubao || null;
|
||||
|
||||
function bridgeCall(name, ...args) {
|
||||
try {
|
||||
if (bridge && typeof bridge[name] === 'function') {
|
||||
bridge[name](...args);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[GameUI] bridge', name, err);
|
||||
}
|
||||
}
|
||||
|
||||
async function request(method, path, body) {
|
||||
const init = { method, headers: {} };
|
||||
if (body !== undefined) {
|
||||
init.headers['Content-Type'] = 'application/json';
|
||||
init.body = JSON.stringify(body);
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(path, init);
|
||||
} catch (err) {
|
||||
throw new Error('连不上内核(它可能还没启动好)');
|
||||
}
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try { data = text ? JSON.parse(text) : null; } catch (_) { /* 非 JSON */ }
|
||||
if (!res.ok) {
|
||||
throw new Error((data && (data.error || data.message)) || `${res.status} 请求失败`);
|
||||
}
|
||||
if (data && data.ok === false && data.error) throw new Error(data.error);
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 事件 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const listeners = new Map();
|
||||
|
||||
function on(topic, fn) {
|
||||
if (!listeners.has(topic)) listeners.set(topic, new Set());
|
||||
listeners.get(topic).add(fn);
|
||||
return () => listeners.get(topic).delete(fn);
|
||||
}
|
||||
|
||||
function emit(topic, payload) {
|
||||
const set = listeners.get(topic);
|
||||
if (set) {
|
||||
for (const fn of [...set]) {
|
||||
try { fn(payload); } catch (err) { console.error('[GameUI]', topic, err); }
|
||||
}
|
||||
}
|
||||
const all = listeners.get('*');
|
||||
if (all) {
|
||||
for (const fn of [...all]) {
|
||||
try { fn(topic, payload); } catch (_) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 全局状态 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const S = {
|
||||
state: null,
|
||||
conversation: null, // 当前会话对象(含 messages)
|
||||
conversationId: params.get('conversationId') || '',
|
||||
messages: [],
|
||||
streaming: false,
|
||||
runId: '',
|
||||
cursor: 0,
|
||||
stopFlag: false,
|
||||
live: null, // 正在流式追加的 assistant 消息
|
||||
error: '',
|
||||
ready: false,
|
||||
};
|
||||
|
||||
const settings = () => (S.state && S.state.settings) || {};
|
||||
const agents = () => (S.state && S.state.agents) || [];
|
||||
const conversations = () => (S.state && S.state.conversations) || [];
|
||||
const containers = () => (S.state && S.state.containers) || [];
|
||||
const places = () => (S.state && S.state.places) || [];
|
||||
|
||||
function agentById(id) {
|
||||
return agents().find((a) => a.id === id) || null;
|
||||
}
|
||||
|
||||
function conversationById(id) {
|
||||
return conversations().find((c) => c.id === id) || null;
|
||||
}
|
||||
|
||||
function currentContainer() {
|
||||
const conv = S.conversation || conversationById(S.conversationId) || {};
|
||||
return containers().find((c) => c.id === conv.containerId) || null;
|
||||
}
|
||||
|
||||
function currentPlace() {
|
||||
const conv = S.conversation || conversationById(S.conversationId) || {};
|
||||
return places().find((p) => p.id === conv.placeId) || null;
|
||||
}
|
||||
|
||||
/** 会话的主人 / 最后发言的角色(群聊里用 lastAgentId 更准) */
|
||||
function currentAgent() {
|
||||
const conv = S.conversation || conversationById(S.conversationId) || {};
|
||||
const lastAssistant = [...S.messages].reverse().find((m) => m.role === 'assistant' && m.agentId);
|
||||
return agentById((lastAssistant && lastAssistant.agentId) || conv.agentId)
|
||||
|| agentById(settings().activeAgentId)
|
||||
|| agents()[0]
|
||||
|| null;
|
||||
}
|
||||
|
||||
/** 立绘 / 背景图的绝对路径 → 内核静态 URL */
|
||||
function assetUrl(path) {
|
||||
const raw = String(path || '').replace(/\\/g, '/');
|
||||
if (!raw) return '';
|
||||
// ★ 先找 agent-assets:安卓上角色图是 `/data/user/0/.../agent-assets/...`
|
||||
// 绝对路径。先判断"以 / 开头"会把它当 URL 原样返回 → WebView 去请求
|
||||
// `/data/user/...` → 404(真机踩过,立绘直接不显示)。
|
||||
const marker = 'agent-assets/';
|
||||
const idx = raw.indexOf(marker);
|
||||
if (idx >= 0) {
|
||||
const rel = raw.slice(idx + marker.length);
|
||||
return '/agent-assets/' + rel.split('/').map(encodeURIComponent).join('/');
|
||||
}
|
||||
if (/^(https?:|data:|\/)/.test(raw)) return raw;
|
||||
return '';
|
||||
}
|
||||
|
||||
function agentAvatar(agent) {
|
||||
if (!agent) return '';
|
||||
const custom = agent.image && agent.image.avatar;
|
||||
const url = assetUrl(custom);
|
||||
if (url) return url;
|
||||
const key = String(agent.avatar || agent.id || 'custom').replace(/^a_/, '');
|
||||
const known = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'cloud', 'robot', 'star', 'custom'];
|
||||
// 模板包自带一套小头像(见 galgame/assets/avatars),路径相对当前包
|
||||
return `assets/avatars/${known.includes(key) ? key : 'custom'}.png`;
|
||||
}
|
||||
|
||||
/** 当前应展示的立绘:情绪立绘优先,其次「平常」档,最后空 */
|
||||
function portraitOf(agent) {
|
||||
if (!agent) return '';
|
||||
const conv = S.conversation || {};
|
||||
const cid = conv.containerId || '';
|
||||
const byContainer = (S.state && S.state.containerPortraits && S.state.containerPortraits[cid]) || {};
|
||||
if (byContainer[agent.id]) return assetUrl(byContainer[agent.id]);
|
||||
const img = agent.image || {};
|
||||
if (img.portrait) return assetUrl(img.portrait);
|
||||
const front = img.front || {};
|
||||
return assetUrl(front['平常'] || front['喜'] || Object.values(front)[0]);
|
||||
}
|
||||
|
||||
function backgroundOf() {
|
||||
const place = currentPlace();
|
||||
if (place && place.background) {
|
||||
const url = assetUrl(place.background);
|
||||
if (url) return url;
|
||||
}
|
||||
const agent = currentAgent();
|
||||
const img = (agent && agent.image) || {};
|
||||
return assetUrl(img.back);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 载入 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function loadState() {
|
||||
// ★ v3.50:`?lite=1` —— 只要界面用得上的字段。
|
||||
// 完整 /api/state 有 72KB,其中 49KB 是 Python 工具 JSON Schema、
|
||||
// 全部音色目录、提供商预设、MCP 配置,HTML 界面一个都不读;
|
||||
// 而 state 每 12 秒 / 每次开面板都会重拉,手机上纯属白烧。
|
||||
// (内核老版本不认这个参数也没关系:多带的字段没人读就是了。)
|
||||
let state;
|
||||
try {
|
||||
state = await request('GET', '/api/state?lite=1');
|
||||
} catch (_) {
|
||||
state = await request('GET', '/api/state');
|
||||
}
|
||||
S.state = state;
|
||||
if (!S.conversationId) {
|
||||
// 没有指定会话:沿用内核设置里的 activeAgent 的第一条会话
|
||||
const list = state.conversations || [];
|
||||
const active = state.settings && state.settings.activeAgentId;
|
||||
const conv = list.find((c) => c.agentId === active) || list[0];
|
||||
if (conv) S.conversationId = conv.id;
|
||||
}
|
||||
emit('state', state);
|
||||
return state;
|
||||
}
|
||||
|
||||
async function loadConversation(id) {
|
||||
const cid = id || S.conversationId;
|
||||
if (!cid) {
|
||||
S.conversation = null;
|
||||
S.messages = [];
|
||||
emit('conversation', null);
|
||||
return null;
|
||||
}
|
||||
const res = await request('GET', `/api/conversations/${encodeURIComponent(cid)}`);
|
||||
const conv = (res && res.conversation) || res || {};
|
||||
S.conversationId = cid;
|
||||
S.conversation = conv;
|
||||
S.messages = Array.isArray(conv.messages) ? conv.messages.slice() : [];
|
||||
emit('conversation', conv);
|
||||
emit('messages', S.messages);
|
||||
return conv;
|
||||
}
|
||||
|
||||
async function ready(opts) {
|
||||
const options = opts || {};
|
||||
if (options.conversationId) S.conversationId = options.conversationId;
|
||||
await loadState();
|
||||
await loadConversation();
|
||||
S.ready = true;
|
||||
emit('ready', { state: S.state, conversation: S.conversation });
|
||||
return { state: S.state, conversation: S.conversation };
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await loadState();
|
||||
await loadConversation();
|
||||
}
|
||||
|
||||
/** 页面切回来时刷新(App 从设置/侧边栏回来) */
|
||||
async function resume() {
|
||||
try {
|
||||
await loadState();
|
||||
await loadConversation();
|
||||
} catch (err) {
|
||||
S.error = err.message || String(err);
|
||||
emit('error', { message: S.error });
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 会话切换 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function openConversation(id) {
|
||||
if (!id || id === S.conversationId) return S.conversation;
|
||||
if (S.streaming) stop();
|
||||
S.conversationId = id;
|
||||
try {
|
||||
await loadConversation(id);
|
||||
// 通知原生:当前会话变了(返回原生界面时不会串)
|
||||
bridgeCall('setConversation', id);
|
||||
emit('opened', { conversationId: id });
|
||||
return S.conversation;
|
||||
} catch (err) {
|
||||
S.error = err.message || String(err);
|
||||
emit('error', { message: S.error });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 发消息 + 流式 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
async function send(text, opts) {
|
||||
const options = opts || {};
|
||||
const message = String(text || '').trim();
|
||||
if (!message) return null;
|
||||
if (S.streaming) throw new Error('上一轮还在生成中');
|
||||
const cid = S.conversationId || (S.conversation && S.conversation.id) || '';
|
||||
if (!cid) throw new Error('还没有打开任何对话');
|
||||
const conv = S.conversation || conversationById(cid) || {};
|
||||
if (conv.ended) throw new Error('这次对话已结束,请在侧边栏开新话题');
|
||||
|
||||
// 本地先插一条用户消息(内核落库很快,但界面要立即有反馈)
|
||||
const userMsg = { role: 'user', content: message, at: new Date().toISOString(), pendingLocal: true };
|
||||
S.messages.push(userMsg);
|
||||
S.live = {
|
||||
role: 'assistant', content: '', agentId: '', at: new Date().toISOString(),
|
||||
pendingLocal: true, streaming: true,
|
||||
};
|
||||
S.messages.push(S.live);
|
||||
S.streaming = true;
|
||||
S.stopFlag = false;
|
||||
S.error = '';
|
||||
emit('messages', S.messages);
|
||||
emit('user', userMsg);
|
||||
emit('stream-start', { conversationId: cid });
|
||||
|
||||
const body = {
|
||||
conversationId: cid,
|
||||
message,
|
||||
transport: 'poll',
|
||||
};
|
||||
if (options.agentId) body.agentId = options.agentId;
|
||||
if (options.privateTo) body.privateTo = String(options.privateTo);
|
||||
if (options.attachments && options.attachments.length) body.attachments = options.attachments;
|
||||
|
||||
let start;
|
||||
try {
|
||||
start = await request('POST', '/api/chat', body);
|
||||
} catch (err) {
|
||||
S.streaming = false;
|
||||
S.live = null;
|
||||
S.messages.pop(); // 去掉占位的 assistant
|
||||
emit('messages', S.messages);
|
||||
emit('error', { message: err.message || String(err) });
|
||||
throw err;
|
||||
}
|
||||
const runId = start && start.runId;
|
||||
if (!runId) {
|
||||
S.streaming = false;
|
||||
S.live = null;
|
||||
S.messages.pop();
|
||||
emit('messages', S.messages);
|
||||
throw new Error('内核没有返回 runId');
|
||||
}
|
||||
S.runId = runId;
|
||||
S.cursor = 0;
|
||||
emit('run', { runId });
|
||||
|
||||
let idle = 0;
|
||||
let flushing = false;
|
||||
// ★ v3.50:内核支持**长轮询**(`wait=1`:有新事件立刻回,没有就挂到 1.2s)。
|
||||
// 第一次请求先按长轮询发;内核在响应里回 `longPoll:true` 就是认这个参数。
|
||||
// ★ 不能用"这次请求挂了多久"判断 —— 模型吐字快(本地/边缘模型)时长轮询
|
||||
// 本来就会几十毫秒返回,被误判成"不支持"会整轮退回 200ms 轮询(真机实测踩过)。
|
||||
// 老内核没有 `longPoll` 字段 → 退回 200ms 一拉,两种内核都能用。
|
||||
let longPoll = true;
|
||||
try {
|
||||
while (true) {
|
||||
if (S.stopFlag) {
|
||||
emit('stopped', { runId });
|
||||
break;
|
||||
}
|
||||
let payload;
|
||||
try {
|
||||
payload = await request(
|
||||
'GET',
|
||||
`/api/chat/poll?runId=${encodeURIComponent(runId)}&cursor=${S.cursor}`
|
||||
+ (longPoll ? '&wait=1' : ''),
|
||||
);
|
||||
} catch (err) {
|
||||
if (flushing) break;
|
||||
idle += 1;
|
||||
if (idle > 30) throw err;
|
||||
await sleep(400);
|
||||
continue;
|
||||
}
|
||||
if (longPoll && !(payload && payload.longPoll)) longPoll = false;
|
||||
const events = (payload && payload.events) || [];
|
||||
if (typeof payload.cursor === 'number') S.cursor = payload.cursor;
|
||||
let sawEnd = false;
|
||||
for (const ev of events) {
|
||||
if (!ev) continue;
|
||||
if (ev.type === 'done' || ev.type === 'error') sawEnd = true;
|
||||
handleEvent(ev);
|
||||
}
|
||||
if (payload.done || sawEnd) {
|
||||
if (flushing) break;
|
||||
flushing = true;
|
||||
await sleep(80);
|
||||
continue;
|
||||
}
|
||||
idle = events.length ? 0 : idle + 1;
|
||||
if (idle > 900) throw new Error('超过 3 分钟没有新内容,已停止等待');
|
||||
// 长轮询:请求本身已经"等"过了,几乎不用再 sleep(只让出一次事件循环)
|
||||
await sleep(longPoll ? 16 : 200);
|
||||
}
|
||||
} catch (err) {
|
||||
S.error = err.message || String(err);
|
||||
emit('error', { message: S.error });
|
||||
} finally {
|
||||
S.streaming = false;
|
||||
S.runId = '';
|
||||
if (S.live) {
|
||||
S.live.streaming = false;
|
||||
if (!S.live.content) {
|
||||
// 空回复不留在界面上(内核也不会落库)
|
||||
const idx = S.messages.indexOf(S.live);
|
||||
if (idx >= 0) S.messages.splice(idx, 1);
|
||||
}
|
||||
S.live = null;
|
||||
}
|
||||
// 以落库版本为准重新拉一次(工具消息 / 续轮 / rebase 都能跟上)
|
||||
try {
|
||||
await loadConversation(S.conversationId);
|
||||
} catch (err) {
|
||||
emit('error', { message: err.message || String(err) });
|
||||
}
|
||||
emit('messages', S.messages);
|
||||
emit('stream-end', { conversationId: S.conversationId });
|
||||
}
|
||||
return { runId };
|
||||
}
|
||||
|
||||
function handleEvent(ev) {
|
||||
switch (ev.type) {
|
||||
case 'delta': {
|
||||
if (!S.live) break;
|
||||
S.live.content += ev.text || '';
|
||||
emit('delta', { text: ev.text || '', full: S.live.content, message: S.live });
|
||||
break;
|
||||
}
|
||||
case 'speaker': {
|
||||
if (S.live) S.live.agentId = ev.agentId || '';
|
||||
emit('speaker', { agentId: ev.agentId || '', reason: ev.reason || '', note: ev.note || '' });
|
||||
break;
|
||||
}
|
||||
case 'rebased': {
|
||||
if (ev.conversationId && ev.conversationId !== S.conversationId) {
|
||||
S.conversationId = ev.conversationId;
|
||||
bridgeCall('setConversation', ev.conversationId);
|
||||
emit('rebased', { conversationId: ev.conversationId, reason: ev.reason || '', message: ev.message || '' });
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'saved': {
|
||||
if (ev.conversationId) S.conversationId = ev.conversationId;
|
||||
emit('saved', ev);
|
||||
break;
|
||||
}
|
||||
case 'handoff': {
|
||||
emit('handoff', ev);
|
||||
break;
|
||||
}
|
||||
case 'status': {
|
||||
emit('status', ev);
|
||||
break;
|
||||
}
|
||||
case 'narration': {
|
||||
emit('narration', ev);
|
||||
break;
|
||||
}
|
||||
case 'error': {
|
||||
S.error = ev.message || '生成失败';
|
||||
if (S.live) S.live.error = true;
|
||||
emit('error', { message: S.error, hint: ev.hint || '', code: ev.code || '' });
|
||||
break;
|
||||
}
|
||||
case 'done': {
|
||||
if (S.live) {
|
||||
if (ev.content) S.live.content = ev.content;
|
||||
S.live.reasoning = ev.reasoning || '';
|
||||
S.live.streaming = false;
|
||||
}
|
||||
emit('done', ev);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
emit('event', ev);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
if (!S.streaming) return;
|
||||
S.stopFlag = true;
|
||||
emit('stop-request', {});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 其他常用数据 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function markImportant(indexOrMessage) {
|
||||
const cid = S.conversationId;
|
||||
if (!cid) throw new Error('还没有打开任何对话');
|
||||
const msg = typeof indexOrMessage === 'number'
|
||||
? S.messages[indexOrMessage]
|
||||
: indexOrMessage;
|
||||
if (!msg || !msg.content) throw new Error('这条消息没有内容');
|
||||
return request('POST', `/api/conversations/${encodeURIComponent(cid)}/important`, {
|
||||
content: msg.content,
|
||||
role: msg.role === 'user' ? 'user' : 'assistant',
|
||||
});
|
||||
}
|
||||
|
||||
async function userProfile(container) {
|
||||
const cid = container || containerId();
|
||||
if (!cid) return null;
|
||||
return request('GET', `/api/containers/${encodeURIComponent(cid)}/user-profile`);
|
||||
}
|
||||
|
||||
async function agentsOfConversation() {
|
||||
const conv = S.conversation || conversationById(S.conversationId) || {};
|
||||
const ids = (conv.participants && conv.participants.length)
|
||||
? conv.participants
|
||||
: [conv.agentId].filter(Boolean);
|
||||
return ids.map(agentById).filter(Boolean);
|
||||
}
|
||||
|
||||
async function mapData() {
|
||||
const c = currentContainer();
|
||||
if (!c) return null;
|
||||
return request('GET', `/api/containers/${encodeURIComponent(c.id)}/places`);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 路由上下文(map / duel / bag 页面共用) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function param(name) {
|
||||
return params.get(String(name || '')) || '';
|
||||
}
|
||||
|
||||
function containerId() {
|
||||
const c = currentContainer();
|
||||
return (c && c.id) || param('containerId') || '';
|
||||
}
|
||||
|
||||
function conversationId() {
|
||||
return S.conversationId || param('conversationId') || '';
|
||||
}
|
||||
|
||||
/** 把地点 / 容器 / 位置数据拉全(地图页用) */
|
||||
async function placesData(container) {
|
||||
const cid = container || containerId();
|
||||
if (!cid) throw new Error('缺少容器 id');
|
||||
return request('GET', `/api/containers/${encodeURIComponent(cid)}/places`);
|
||||
}
|
||||
|
||||
/** 移动一个人;agentId 默认 user(地图页「去这里/移人」) */
|
||||
async function moveMember(placeId, agentId, container) {
|
||||
const cid = container || containerId();
|
||||
if (!cid) throw new Error('缺少容器 id');
|
||||
const target = agentId || 'user';
|
||||
await request('POST', `/api/containers/${encodeURIComponent(cid)}/move`, {
|
||||
agentId: target, placeId: String(placeId || ''),
|
||||
});
|
||||
if (target === 'user') bridgeCall('moved', String(placeId || ''), '');
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 背包 / 我的角色 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function userBag(container) {
|
||||
const cid = container || containerId();
|
||||
if (!cid) return [];
|
||||
const res = await request('GET',
|
||||
`/api/containers/${encodeURIComponent(cid)}/items?agentId=user`);
|
||||
return (res && res.items) || [];
|
||||
}
|
||||
|
||||
async function bagAction(itemId, action, opts) {
|
||||
const options = opts || {};
|
||||
const cid = containerId();
|
||||
if (!cid) throw new Error('缺少容器 id');
|
||||
const body = {
|
||||
agentId: 'user', itemId: String(itemId || ''), action: String(action || ''),
|
||||
count: options.count || 1,
|
||||
};
|
||||
if (options.target) body.target = options.target;
|
||||
if (options.targets) body.targets = options.targets;
|
||||
if (options.with) body.with = options.with;
|
||||
return request('POST', `/api/containers/${encodeURIComponent(cid)}/items/action`, body);
|
||||
}
|
||||
|
||||
async function userStatuses(container) {
|
||||
const cid = container || containerId();
|
||||
if (!cid) return [];
|
||||
const res = await request('GET',
|
||||
`/api/containers/${encodeURIComponent(cid)}/user-profile`);
|
||||
return (res && res.statuses) || [];
|
||||
}
|
||||
|
||||
async function userStatusAction(name, action) {
|
||||
const cid = containerId();
|
||||
if (!cid) throw new Error('缺少容器 id');
|
||||
return request('POST', `/api/containers/${encodeURIComponent(cid)}/user-status`, {
|
||||
name: String(name || ''), action: String(action || 'grant'),
|
||||
});
|
||||
}
|
||||
|
||||
async function reviveUser(container) {
|
||||
const cid = container || containerId();
|
||||
if (!cid) throw new Error('缺少容器 id');
|
||||
return request('POST', `/api/containers/${encodeURIComponent(cid)}/user-emotion`, {
|
||||
preset: '平常',
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 决斗 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function currentDuel(conv) {
|
||||
const cid = conv || conversationId();
|
||||
if (!cid) return null;
|
||||
const res = await request('GET',
|
||||
`/api/conversations/${encodeURIComponent(cid)}/duel`);
|
||||
return (res && res.duel) || null;
|
||||
}
|
||||
|
||||
async function startDuel(targetId, opts) {
|
||||
const options = opts || {};
|
||||
const cid = options.conversationId || conversationId();
|
||||
if (!cid) throw new Error('缺少会话 id');
|
||||
const body = { targetId: String(targetId || '') };
|
||||
if (options.weaponId) body.weaponId = options.weaponId;
|
||||
const res = await request('POST',
|
||||
`/api/conversations/${encodeURIComponent(cid)}/duel`, body);
|
||||
return (res && res.duel) || null;
|
||||
}
|
||||
|
||||
async function duelAction(duelId, action, body) {
|
||||
if (!duelId) throw new Error('缺少决斗 id');
|
||||
const res = await request('POST',
|
||||
`/api/duels/${encodeURIComponent(duelId)}/${action}`, body || {});
|
||||
return (res && res.duel) || res;
|
||||
}
|
||||
|
||||
const advanceDuel = (duelId) => duelAction(duelId, 'round');
|
||||
const chooseWeapon = (duelId, weaponId) => duelAction(duelId, 'weapon', { weaponId });
|
||||
const chooseDuelItem = (duelId, itemId) => duelAction(duelId, 'item', { itemId });
|
||||
const requestDuelStop = (duelId, reason) => duelAction(duelId, 'stop', { reason: reason || '' });
|
||||
const answerDuelStop = (duelId, agree) => duelAction(duelId, 'stop-answer', { agree: !!agree });
|
||||
|
||||
/** 决斗里说话:除了新快照,还要把 `replied` 带出来(页面据此提示"对手没回应") */
|
||||
async function sayInDuel(duelId, text) {
|
||||
if (!duelId) throw new Error('缺少决斗 id');
|
||||
const res = await request('POST',
|
||||
`/api/duels/${encodeURIComponent(duelId)}/say`, { text: String(text || '') });
|
||||
const duel = (res && res.duel) || null;
|
||||
return Object.assign({}, duel || {}, {
|
||||
replied: res && Object.prototype.hasOwnProperty.call(res, 'replied') ? !!res.replied : true,
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 朗读(浏览器 / 内核 TTS) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
let currentAudio = null;
|
||||
|
||||
function stopSpeak() {
|
||||
if (currentAudio) {
|
||||
try { currentAudio.pause(); } catch (_) { /* ignore */ }
|
||||
currentAudio = null;
|
||||
}
|
||||
if ('speechSynthesis' in window) {
|
||||
try { window.speechSynthesis.cancel(); } catch (_) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
function browserSpeak(text, agentId) {
|
||||
if (!('speechSynthesis' in window)) return;
|
||||
const utter = new SpeechSynthesisUtterance(String(text || '').slice(0, 3000));
|
||||
utter.lang = 'zh-CN';
|
||||
const a = agentById(agentId);
|
||||
if (a && a.ttsSpeed) utter.rate = Number(a.ttsSpeed) || 1;
|
||||
window.speechSynthesis.speak(utter);
|
||||
}
|
||||
|
||||
async function speak(text, agentId) {
|
||||
const clean = String(text || '').replace(/[#*_`>]/g, '').trim();
|
||||
if (!clean) return;
|
||||
stopSpeak();
|
||||
try {
|
||||
const res = await request('POST', '/api/tts', {
|
||||
text: String(text || ''), agentId: String(agentId || ''),
|
||||
});
|
||||
if (!res || res.ok === false || res.engine === 'system' || !res.audio) {
|
||||
browserSpeak((res && res.speakText) || clean, agentId);
|
||||
return;
|
||||
}
|
||||
const audio = new Audio(`data:${res.mime || 'audio/mpeg'};base64,${res.audio}`);
|
||||
currentAudio = audio;
|
||||
audio.addEventListener('ended', () => { currentAudio = null; });
|
||||
await audio.play();
|
||||
} catch (_) {
|
||||
browserSpeak(clean, agentId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 原生桥 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function openDrawer() { bridgeCall('openDrawer'); }
|
||||
function openScreen(name) { bridgeCall('openScreen', String(name || '')); }
|
||||
|
||||
/**
|
||||
* 打开**同一个 UI 包里的任意自定义页面**(v3.39)。
|
||||
*
|
||||
* 页面数量和文件名都不限:只要文件在这个包里(例如 `market.html`),
|
||||
* 就能从聊天/地图/决斗或另一个自定义页跳过去。参数会变成查询串,
|
||||
* 目标页用 `GameUI.param('x')` 读。
|
||||
*
|
||||
* GameUI.openPage('market.html', { tab: 'weapons' })
|
||||
* GameUI.openPage('detail.html?id=3') // 也可以直接写查询串
|
||||
*
|
||||
* ★ 只允许**包内相对路径**:不能 `http://`、不能 `../`。原生侧还会再挡一次。
|
||||
*/
|
||||
function openPage(page, params) {
|
||||
const raw = String(page || '').trim();
|
||||
if (!raw) throw new Error('openPage: 缺少页面文件名');
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(raw) || raw.startsWith('//') || raw.includes('..')) {
|
||||
throw new Error('openPage: 只允许 UI 包内相对路径');
|
||||
}
|
||||
let query = '';
|
||||
if (typeof params === 'string') {
|
||||
query = params.replace(/^\?/, '');
|
||||
} else if (params && typeof params === 'object') {
|
||||
query = new URLSearchParams(params).toString();
|
||||
}
|
||||
if (bridge && typeof bridge.openPage === 'function') {
|
||||
bridge.openPage(raw, query, containerId(), conversationId());
|
||||
return;
|
||||
}
|
||||
const sep = raw.includes('?') ? '&' : '?';
|
||||
location.href = raw + (query ? sep + query : '');
|
||||
}
|
||||
|
||||
function close() { bridgeCall('close'); }
|
||||
function toast(text) { bridgeCall('toast', String(text || '')); }
|
||||
function setNativeConversation(id) { bridgeCall('setConversation', String(id || '')); }
|
||||
|
||||
/** 让下面的聊天 WebView 重新加载(设置页保存后调;页面自己 close 回聊天) */
|
||||
function reloadChat() { bridgeCall('reloadChat'); }
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 小工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text == null ? '' : text)
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/** 极简 Markdown(和网页版/原生不完全等价,只覆盖聊天里最常出现的几种) */
|
||||
function markdown(text) {
|
||||
let html = escapeHtml(text);
|
||||
html = html.replace(/```([\s\S]*?)```/g, (_, code) => `<pre><code>${code.trim()}</code></pre>`);
|
||||
html = html.replace(/`([^`\n]+)`/g, '<code>$1</code>');
|
||||
html = html.replace(/^###\s+(.+)$/gm, '<strong>$1</strong>');
|
||||
html = html.replace(/^##\s+(.+)$/gm, '<strong>$1</strong>');
|
||||
html = html.replace(/^#\s+(.+)$/gm, '<strong>$1</strong>');
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
html = html.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
|
||||
html = html.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,
|
||||
'<a href="$2" target="_blank" rel="noreferrer">$1</a>');
|
||||
html = html.replace(/\n/g, '<br>');
|
||||
return html;
|
||||
}
|
||||
|
||||
/** 旁白/动作括号 → 灰色小字(和 App 的展示规则一致:成对括号、不跨行) */
|
||||
function stageify(html) {
|
||||
if (settings().speech && settings().speech.emotionTags === false) return html;
|
||||
return html.replace(/(([^()\n]{1,60})|\([^()\n]{1,60}\)|【[^【】\n]{1,60}】)/g,
|
||||
'<span class="stage">$1</span>');
|
||||
}
|
||||
|
||||
function fmtTime(iso) {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function roleName(msg) {
|
||||
if (!msg) return '';
|
||||
if (msg.role === 'user') return settings().nickname || '你';
|
||||
const a = agentById(msg.agentId);
|
||||
return (a && a.name) || (currentAgent() && currentAgent().name) || '旁白';
|
||||
}
|
||||
|
||||
const GameUI = {
|
||||
// 状态
|
||||
S,
|
||||
settings,
|
||||
agents,
|
||||
conversations,
|
||||
containers,
|
||||
places,
|
||||
messages: () => S.messages,
|
||||
conversation: () => S.conversation,
|
||||
currentAgent,
|
||||
currentContainer,
|
||||
currentPlace,
|
||||
conversationById,
|
||||
agentById,
|
||||
// 载入
|
||||
ready,
|
||||
refresh,
|
||||
resume,
|
||||
loadState,
|
||||
loadConversation,
|
||||
openConversation,
|
||||
// 聊天
|
||||
send,
|
||||
stop,
|
||||
markImportant,
|
||||
userProfile,
|
||||
agentsOfConversation,
|
||||
mapData,
|
||||
// 路由上下文 + 地图
|
||||
param,
|
||||
containerId,
|
||||
conversationId,
|
||||
placesData,
|
||||
moveMember,
|
||||
// 背包 / 我的角色
|
||||
userBag,
|
||||
bagAction,
|
||||
userStatuses,
|
||||
userStatusAction,
|
||||
reviveUser,
|
||||
// 决斗
|
||||
currentDuel,
|
||||
startDuel,
|
||||
advanceDuel,
|
||||
chooseWeapon,
|
||||
chooseDuelItem,
|
||||
sayInDuel,
|
||||
requestDuelStop,
|
||||
answerDuelStop,
|
||||
// 朗读
|
||||
speak,
|
||||
stopSpeak,
|
||||
// 事件
|
||||
on,
|
||||
emit,
|
||||
// 资源
|
||||
assetUrl,
|
||||
agentAvatar,
|
||||
portraitOf,
|
||||
backgroundOf,
|
||||
// 原生
|
||||
openDrawer,
|
||||
openScreen,
|
||||
openPage,
|
||||
close,
|
||||
toast,
|
||||
setNativeConversation,
|
||||
reloadChat,
|
||||
bridge: bridge,
|
||||
// 小工具
|
||||
escapeHtml,
|
||||
markdown,
|
||||
stageify,
|
||||
fmtTime,
|
||||
roleName,
|
||||
// 原始 HTTP(模板想调别的接口时用)
|
||||
api: {
|
||||
get: (path) => request('GET', path),
|
||||
post: (path, body) => request('POST', path, body || {}),
|
||||
put: (path, body) => request('PUT', path, body || {}),
|
||||
del: (path) => request('DELETE', path),
|
||||
},
|
||||
};
|
||||
|
||||
window.GameUI = GameUI;
|
||||
})();
|
||||
BIN
豆鲍/android/app/src/main/assets/worlds/all-test.zip
Normal file
BIN
豆鲍/android/app/src/main/assets/worlds/old-city.zip
Normal file
@@ -0,0 +1,261 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.Intent
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★★ 「预设快捷入口」—— 一句话直达某个 App 的某个页面。
|
||||
*
|
||||
* 用户要求:"打开应用工具支持打开活动,并预设几个比如微信对话,支付宝菜鸟"
|
||||
*
|
||||
* ## 为什么每个预设是一**串**候选而不是一个
|
||||
*
|
||||
* 深链 scheme 和 Activity 名字**都会随 App 版本变**。
|
||||
* 只赌一个的话,用户那边 App 一升级这个功能就静默失效了 ——
|
||||
* 而且报的还是"打不开",查起来很费劲。
|
||||
*
|
||||
* 所以每个预设给一组候选,**按顺序试,第一个成的算**:
|
||||
* 1. 深链(最稳,scheme 通常不变)
|
||||
* 2. 指定 Activity(有的页面有独立 Activity)
|
||||
* 3. 退回主界面(保证"至少把 App 打开了",不会让用户觉得功能坏了)
|
||||
*
|
||||
* ★ 每个候选都标了 `kind`,返回里如实说**是哪一个成的** ——
|
||||
* 万一以后要调,一眼看得出走到哪一层了。
|
||||
*
|
||||
* ## ★ 诚实说明:这些 scheme 没法离线验证
|
||||
*
|
||||
* 我没法在没有真机 App 的情况下确认 `weixin://` 一定进"聊天列表"、
|
||||
* `alipays://platformapi/startapp?appId=200011235` 一定开菜鸟。
|
||||
* 这些值来自公开的深链惯例,**大多数情况可用,但 App 大版本更新后可能失效**。
|
||||
*
|
||||
* 所以设计上:
|
||||
* · 全部走"多候选 + 退回主界面",失效也不会让功能变成"点了没反应"
|
||||
* · 返回里带 `how`(哪一条成的)和 `tried`(试过哪些),方便排查
|
||||
* · 用户可以在 `tools/apps.py` 的说明里看到怎么改用自己手机上的值
|
||||
*/
|
||||
object AppShortcuts {
|
||||
|
||||
private const val WECHAT = "com.tencent.mm"
|
||||
private const val ALIPAY = "com.eg.android.AlipayGphone"
|
||||
private const val TAOBAO = "com.taobao.taobao"
|
||||
private const val QQ = "com.tencent.mobileqq"
|
||||
private const val DOUYIN = "com.ss.android.ugc.aweme"
|
||||
|
||||
/**
|
||||
* 一个候选:怎么打开。
|
||||
*
|
||||
* ★ 可见性跟着用的地方走:`run()` 的参数/返回类型里出现了它,
|
||||
* 所以它至少要**一样宽**。Kotlin 不允许 public 函数暴露 private/internal 类型
|
||||
* (报 "Function 'public' exposes its 'private-in-class' return type")。
|
||||
* 这个坑连着踩了两次(先 private 后 internal),索性都用默认的 public。
|
||||
*/
|
||||
data class Shot(
|
||||
val kind: String, // uri / activity / main
|
||||
val pkg: String,
|
||||
val uri: String = "",
|
||||
val cls: String = "",
|
||||
val note: String = "",
|
||||
)
|
||||
|
||||
/** 一个预设:名字 + 关键词 + 一串候选 */
|
||||
data class Preset(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val keywords: List<String>,
|
||||
val shots: List<Shot>,
|
||||
)
|
||||
|
||||
private fun p(id: String, label: String, kw: List<String>, vararg shots: Shot) =
|
||||
Preset(id, label, kw, shots.toList())
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
// 预设表
|
||||
//
|
||||
// ★ 加新预设只要往这个列表里塞一条 —— 工具说明、列表接口都是从这里生成的,
|
||||
// 不存在"两边不一致"的问题(这个仓库里抄两份的坑踩过好几次)。
|
||||
// ------------------------------------------------------------------ //
|
||||
|
||||
private val PRESETS: List<Preset> = listOf(
|
||||
// ---------------- 微信 ----------------
|
||||
p(
|
||||
"wechat", "微信(主界面)", listOf("微信", "wechat", "weixin"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "微信主 scheme"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-chat", "微信 · 聊天列表", listOf("微信聊天", "微信对话", "聊天列表", "wechat chat"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/chat", note = "聊天列表"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-scan", "微信 · 扫一扫", listOf("微信扫一扫", "扫码", "扫一扫", "wechat scan"),
|
||||
Shot("uri", WECHAT, uri = "weixin://scanqrcode", note = "扫一扫"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-moments", "微信 · 朋友圈", listOf("朋友圈", "moments", "wechat moments"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/moments", note = "朋友圈"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
p(
|
||||
"wechat-pay", "微信 · 收付款", listOf("微信支付", "微信收付款", "付款码", "wechat pay"),
|
||||
Shot("uri", WECHAT, uri = "weixin://dl/offline", note = "收付款(付款码)"),
|
||||
Shot("uri", WECHAT, uri = "weixin://", note = "退回微信主界面"),
|
||||
Shot("main", WECHAT),
|
||||
),
|
||||
|
||||
// ---------------- 支付宝 ----------------
|
||||
p(
|
||||
"alipay", "支付宝(主界面)", listOf("支付宝", "alipay", "zhifubao"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "支付宝主 scheme"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-scan", "支付宝 · 扫一扫", listOf("支付宝扫一扫", "支付宝扫码", "alipay scan"),
|
||||
// 200011235 是支付宝"扫一扫"的公开 appId;后面那个通用端口是备选
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=200011235", note = "扫一扫"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?saId=10000007", note = "通用启动端口"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-pay", "支付宝 · 付款码", listOf("支付宝付款", "支付宝收付款", "付款码", "alipay pay"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=20000056", note = "付款码"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-cainiao", "支付宝 · 菜鸟裹裹", listOf("菜鸟", "菜鸟裹裹", "快递", "cainiao"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=200011235&url=%2Fwww%2Fcainiao.html", note = "菜鸟"),
|
||||
// 菜鸟也有独立 App,装了就直接开它
|
||||
Shot("uri", "com.cainiao.wireless", uri = "cainiao://", note = "菜鸟独立 App"),
|
||||
Shot("main", "com.cainiao.wireless", note = "菜鸟独立 App 主界面"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
p(
|
||||
"alipay-card", "支付宝 · 卡包", listOf("卡包", "支付宝卡包", "alipay card"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://platformapi/startapp?appId=20000021", note = "卡包"),
|
||||
Shot("uri", ALIPAY, uri = "alipays://", note = "退回支付宝主界面"),
|
||||
Shot("main", ALIPAY),
|
||||
),
|
||||
|
||||
// ---------------- 别的常用的 ----------------
|
||||
p(
|
||||
"taobao", "淘宝", listOf("淘宝", "taobao"),
|
||||
Shot("uri", TAOBAO, uri = "taobao://", note = "淘宝主 scheme"),
|
||||
Shot("main", TAOBAO),
|
||||
),
|
||||
p(
|
||||
"qq", "QQ", listOf("qq", "腾讯qq"),
|
||||
Shot("uri", QQ, uri = "mqq://", note = "QQ 主 scheme"),
|
||||
Shot("main", QQ),
|
||||
),
|
||||
p(
|
||||
"douyin", "抖音", listOf("抖音", "douyin", "tiktok"),
|
||||
Shot("uri", DOUYIN, uri = "snssdk1128://", note = "抖音主 scheme"),
|
||||
Shot("main", DOUYIN),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 全部预设。
|
||||
*
|
||||
* ★ Context 当**参数**传,不存一个可空的全局变量 ——
|
||||
* 第一版用 `@Volatile var appCtx`,于是编译期类型是 `Context?`,
|
||||
* 每次用都要解包,还容易忘了先赋值(那样"装了没有"永远返回 false)。
|
||||
* 传参是编译期就能保证的。
|
||||
*/
|
||||
fun all(ctx: android.content.Context): List<Map<String, Any>> = PRESETS.map { p ->
|
||||
mapOf(
|
||||
"id" to p.id,
|
||||
"label" to p.label,
|
||||
"keywords" to p.keywords,
|
||||
// 只看第一个候选那个 App 装了没有 —— 后面的候选可能包含没装的备选
|
||||
"installed" to PhoneOps.isInstalled(ctx, p.shots.first().pkg),
|
||||
"app" to p.shots.first().pkg,
|
||||
)
|
||||
}
|
||||
|
||||
fun ids(): List<String> = PRESETS.map { it.id }
|
||||
|
||||
/** 按 id 或关键词找一个预设 */
|
||||
fun find(query: String): Preset? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
PRESETS.firstOrNull { it.id.equals(q, ignoreCase = true) }?.let { return it }
|
||||
PRESETS.firstOrNull { it.label.lowercase() == q }?.let { return it }
|
||||
PRESETS.firstOrNull { it.keywords.any { k -> k.lowercase() == q } }?.let { return it }
|
||||
// 先匹配 label 里的,再匹配关键词 —— 避免"微信"先命中"微信扫一扫"那种歧义
|
||||
PRESETS.firstOrNull { it.label.lowercase().contains(q) }?.let { return it }
|
||||
return PRESETS.firstOrNull { p ->
|
||||
p.keywords.any { k -> k.lowercase().contains(q) || q.contains(k.lowercase()) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一个预设:按候选顺序试,第一个成的算。
|
||||
*
|
||||
* ★ 全失败时返回**试过哪些 + 各自为什么失败** ——
|
||||
* 只回一句"打不开"的话,用户和模型都不知道下一步该干嘛。
|
||||
*/
|
||||
fun run(ctx: android.content.Context, preset: Preset): JSONObject {
|
||||
val tried = JSONArray()
|
||||
for (shot in preset.shots) {
|
||||
if (!PhoneOps.isInstalled(ctx, shot.pkg)) {
|
||||
tried.put(JSONObject().put("kind", shot.kind).put("pkg", shot.pkg)
|
||||
.put("error", "没装这个 App"))
|
||||
continue
|
||||
}
|
||||
val err: String? = when (shot.kind) {
|
||||
"uri" -> PhoneOps.launchUri(ctx, shot.uri)
|
||||
"activity" -> PhoneOps.launchActivity(ctx, shot.pkg, shot.cls)
|
||||
else -> if (PhoneOps.launchApp(ctx, shot.pkg, mainActivityOf(ctx, shot.pkg))) {
|
||||
null
|
||||
} else {
|
||||
"启动主界面失败"
|
||||
}
|
||||
}
|
||||
if (err == null) {
|
||||
return JSONObject()
|
||||
.put("ok", true)
|
||||
.put("shortcut", preset.id)
|
||||
.put("label", preset.label)
|
||||
.put("how", shot.kind)
|
||||
.put("detail", shot.note)
|
||||
.put("tried", tried)
|
||||
}
|
||||
tried.put(JSONObject().put("kind", shot.kind)
|
||||
.put("detail", shot.note)
|
||||
.put("error", err))
|
||||
}
|
||||
return JSONObject()
|
||||
.put("error", "「${preset.label}」的所有打开方式都没成功")
|
||||
.put("tried", tried)
|
||||
.put(
|
||||
"hint",
|
||||
"多半是这个 App 没装,或者它的版本改了深链。可以先用 action=open 打开 App 主界面," +
|
||||
"或者在 tools/apps.py 里把这个预设的链接改成你手机上的实际值。",
|
||||
)
|
||||
}
|
||||
|
||||
/** 拿一个包的 launcher activity */
|
||||
fun mainActivityOf(ctx: android.content.Context, pkg: String): String {
|
||||
val i = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(android.content.Intent.CATEGORY_LAUNCHER)
|
||||
.setPackage(pkg)
|
||||
val list = if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
ctx.packageManager.queryIntentActivities(
|
||||
i, android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ctx.packageManager.queryIntentActivities(i, 0)
|
||||
}
|
||||
return list.firstOrNull()?.activityInfo?.name.orEmpty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Notification
|
||||
import android.os.Bundle
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* ★★ 读手机通知 —— 用户要求"加个读取手机通知的工具"。
|
||||
*
|
||||
* ## 为什么必须是个 Service
|
||||
*
|
||||
* Android **没有**"读取通知"的运行时权限。唯一合法的路是让用户手动去
|
||||
* 「设置 → 通知 → 通知使用权」里把这个 App 勾上,系统才会把通知流给我们。
|
||||
* 这个 Service 就是那个接收端 —— 不声明它,权限开了也收不到任何东西。
|
||||
*
|
||||
* ## 不落盘,只在内存里留最近的
|
||||
*
|
||||
* 通知是**高度隐私**的内容(验证码、私信、银行短信都在里面)。
|
||||
* 写进磁盘意味着卸载前一直躺在那儿,也可能被别的工具读到。
|
||||
* 只留内存,进程一死就没了 —— 用户要"读最近的通知"这个需求完全够用,
|
||||
* 而隐私面小得多。
|
||||
*
|
||||
* ★ 上限 [MAX_KEEP] 条:用户一天能收几百条通知,不限量会把内存吃满。
|
||||
*/
|
||||
class DoubaoNotificationListener : NotificationListenerService() {
|
||||
|
||||
override fun onListenerConnected() {
|
||||
super.onListenerConnected()
|
||||
connected = true
|
||||
instance = this
|
||||
// ★ 连上的瞬间就把当前挂着的通知同步进来 —— 不然用户装完 App 立刻问
|
||||
// "我最近收到什么通知了",答案是空的(那些通知在他装 App 之前就收到了)
|
||||
syncActive()
|
||||
Log.i(TAG, "通知使用权已连接,当前挂着 ${items.size} 条")
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
super.onListenerDisconnected()
|
||||
connected = false
|
||||
if (instance === this) instance = null
|
||||
Log.i(TAG, "通知使用权已断开")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
if (instance === this) instance = null
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
try {
|
||||
// ★ 跳过我们自己的通知(不然"AI 读通知"会把 App 自己的提示也读进去)
|
||||
if (n.packageName == packageName) return
|
||||
record(n, removed = false)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "记通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
// ★ 只标成"已消失",**不删掉** —— 用户问"刚才那条验证码呢"的时候,
|
||||
// 通知早就被划掉了,删了就直接查不到了。
|
||||
try {
|
||||
val key = n.key ?: return
|
||||
items[key]?.let { it.removed = true; it.atRemoved = System.currentTimeMillis() }
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一条通知。
|
||||
*
|
||||
* ★ 可见性要 **internal**(不能 private):`companion object` 里的
|
||||
* `syncActive()` 要调它,而 Kotlin 的 private 成员**只对同一个类体可见**,
|
||||
* 伴生对象不算 —— 写成 private 会报"cannot access"。
|
||||
*/
|
||||
internal fun record(n: StatusBarNotification, removed: Boolean) {
|
||||
val extras: Bundle = n.notification?.extras ?: Bundle()
|
||||
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = extras.getCharSequence(Notification.EXTRA_TEXT)?.toString().orEmpty()
|
||||
val big = extras.getCharSequence(Notification.EXTRA_BIG_TEXT)?.toString().orEmpty()
|
||||
val sub = extras.getCharSequence(Notification.EXTRA_SUB_TEXT)?.toString().orEmpty()
|
||||
|
||||
val item = Item(
|
||||
key = n.key ?: "${n.packageName}:${n.postTime}",
|
||||
pkg = n.packageName.orEmpty(),
|
||||
app = appLabel(n.packageName.orEmpty()),
|
||||
title = title,
|
||||
text = if (big.isNotBlank()) big else text,
|
||||
subText = sub,
|
||||
at = if (n.postTime > 0) n.postTime else System.currentTimeMillis(),
|
||||
removed = removed,
|
||||
atRemoved = 0L,
|
||||
)
|
||||
// ★ 标题和正文都空的就**不进列表**。
|
||||
//
|
||||
// 这类通知真实存在:媒体控制、正在进行的下载、某些 App 的纯图标通知 ——
|
||||
// 它们的文字要么在 RemoteViews 里(`extras` 取不到),要么压根没有。
|
||||
// 留着的话用户/模型会看到一条"什么都没有"的条目,纯噪音。
|
||||
// (实测:`cmd notification post` 发的测试通知就有一条是这样的。)
|
||||
if (item.title.isBlank() && item.text.isBlank()) return
|
||||
|
||||
items[item.key] = item
|
||||
|
||||
// 超上限就丢最旧的。用 postTime 排(key 是字符串,排不了时间序)
|
||||
if (items.size > MAX_KEEP) {
|
||||
items.values.sortedBy { it.at }.take(items.size - MAX_KEEP).forEach { items.remove(it.key) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun appLabel(pkg: String): String = try {
|
||||
val pm = packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString()
|
||||
} catch (_: Throwable) {
|
||||
pkg
|
||||
}
|
||||
|
||||
data class Item(
|
||||
val key: String,
|
||||
val pkg: String,
|
||||
val app: String,
|
||||
val title: String,
|
||||
val text: String,
|
||||
val subText: String,
|
||||
val at: Long,
|
||||
var removed: Boolean,
|
||||
var atRemoved: Long,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DoubaoNotif"
|
||||
private const val MAX_KEEP = 200
|
||||
|
||||
/** 最近的通知(内存里,进程死了就没了 —— 见类注释里的隐私考虑) */
|
||||
private val items = ConcurrentHashMap<String, Item>()
|
||||
|
||||
/**
|
||||
* 当前活着的 service 实例。
|
||||
*
|
||||
* ★ 必须有它:`getActiveNotifications()` 是 **service 自己**的方法,
|
||||
* 不是静态的。没有实例就调不到,也就拿不到"系统里现在挂着哪些通知"。
|
||||
*/
|
||||
@Volatile
|
||||
private var instance: DoubaoNotificationListener? = null
|
||||
|
||||
/** 通知使用权连上了没有 */
|
||||
@Volatile
|
||||
var connected: Boolean = false
|
||||
|
||||
/**
|
||||
* ★★★ 把系统里**当前还挂着的**通知同步进来。
|
||||
*
|
||||
* ## 为什么必须有这个(用户报"还是没有读到"的根因)
|
||||
*
|
||||
* 第一版只在 `onNotificationPosted` 里记 —— 也就是说**只有本进程活着的
|
||||
* 那段时间收到的通知才算数**。而进程一重启(用户升级 App、或者系统杀后台)
|
||||
* 内存就清空了,那之前收到的通知**全都看不到**。
|
||||
*
|
||||
* 用户的期望是"读我手机上现在的通知" —— 那本来就该包含
|
||||
* **在他打开 App 之前就收到的那些**。
|
||||
*
|
||||
* `NotificationListenerService.getActiveNotifications()` 正好干这个:
|
||||
* 系统把当前通知栏上挂着的全给它。所以每次读之前先同步一遍。
|
||||
*
|
||||
* ★ 拿不到实例(service 没起来)时不报错,就用手上已有的 ——
|
||||
* 至少比什么都不给强。
|
||||
*/
|
||||
fun syncActive() {
|
||||
val svc = instance ?: return
|
||||
try {
|
||||
for (sbn in svc.activeNotifications ?: emptyArray()) {
|
||||
if (sbn.packageName == svc.packageName) continue
|
||||
svc.record(sbn, removed = false)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "同步当前通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取最近的通知。
|
||||
*
|
||||
* @param limit 最多几条
|
||||
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
|
||||
* @param query 关键词过滤(标题/正文/App 名里含它)
|
||||
*/
|
||||
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
|
||||
// ★ 先跟系统对一次账,把"我们没见过的、但此刻挂着的"补进来
|
||||
syncActive()
|
||||
|
||||
var list = items.values.toList()
|
||||
if (onlyAlive) list = list.filter { !it.removed }
|
||||
if (query.isNotBlank()) {
|
||||
val q = query.lowercase()
|
||||
list = list.filter {
|
||||
it.title.lowercase().contains(q) ||
|
||||
it.text.lowercase().contains(q) ||
|
||||
it.app.lowercase().contains(q) ||
|
||||
it.pkg.lowercase().contains(q)
|
||||
}
|
||||
}
|
||||
val arr = JSONArray()
|
||||
list.sortedByDescending { it.at }.take(limit.coerceIn(1, MAX_KEEP)).forEach { it ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("app", it.app)
|
||||
.put("package", it.pkg)
|
||||
.put("title", it.title)
|
||||
.put("text", it.text)
|
||||
.put("subText", it.subText)
|
||||
.put("at", it.at)
|
||||
.put("removed", it.removed),
|
||||
)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
fun count(): Int = items.size
|
||||
|
||||
fun clear() = items.clear()
|
||||
}
|
||||
}
|
||||
190
豆鲍/android/app/src/main/java/com/doubao/lynxclone/LocalKernel.kt
Normal file
@@ -0,0 +1,190 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.AssetManager
|
||||
import com.chaquo.python.Python
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 手机端的本地 AI 内核(Chaquopy 内嵌 CPython)。
|
||||
*
|
||||
* 为什么要它:手机上装不了 Node,而用户要的是"脱离电脑也能用"。
|
||||
* 内核用 Python 重写了一份(android/kernel),接口和电脑上的 Node 版一模一样,
|
||||
* 所以 Lynx 界面完全不用改,只是把 apiBase 指到 127.0.0.1。
|
||||
*
|
||||
* 注意 Chaquopy 的两个硬约束(都踩过):
|
||||
* 1. 它把 Python 嵌在主进程里,**没有独立 python 可执行文件** → 不能用 subprocess 起 py 脚本
|
||||
* 2. 只有 arm64-v8a / x86_64 两个 ABI
|
||||
*/
|
||||
object LocalKernel {
|
||||
|
||||
@Volatile
|
||||
private var port = 0
|
||||
|
||||
@Volatile
|
||||
private var failure: String? = null
|
||||
|
||||
/** 已启动则直接返回端口;否则同步启动(要在子线程调) */
|
||||
@Synchronized
|
||||
fun ensureStarted(context: Context, preferredPort: Int = 5199): Int {
|
||||
if (port > 0) return port
|
||||
failure = null
|
||||
try {
|
||||
val py = Python.getInstance()
|
||||
val entry = py.getModule("doubao_entry")
|
||||
|
||||
val dataDir = File(context.filesDir, "kernel-data").apply { mkdirs() }.absolutePath
|
||||
// ★ v3.36:把 APK assets 里的「游戏界面模板包」播种到数据目录。
|
||||
// 必须在启动内核**之前**:内核只认 data_dir/ui-packs,读不到 APK assets。
|
||||
seedUiPacks(context, dataDir)
|
||||
// 外部私有目录:不用申请存储权限,用户能通过文件管理器/USB 往里放自己的 py 工具
|
||||
val workDir = (context.getExternalFilesDir(null) ?: File(context.filesDir, "external"))
|
||||
.apply { mkdirs() }.absolutePath
|
||||
|
||||
val actual = entry.callAttr("start", dataDir, workDir, preferredPort).toInt()
|
||||
port = actual
|
||||
android.util.Log.i("DoubaoKernel", "本地内核已就绪 127.0.0.1:$actual data=$dataDir work=$workDir")
|
||||
return actual
|
||||
} catch (t: Throwable) {
|
||||
failure = t.message ?: t.toString()
|
||||
android.util.Log.e("DoubaoKernel", "本地内核启动失败", t)
|
||||
throw t
|
||||
}
|
||||
}
|
||||
|
||||
fun baseUrl(): String? = if (port > 0) "http://127.0.0.1:$port" else null
|
||||
|
||||
fun lastFailure(): String? = failure
|
||||
|
||||
/** 工具目录(给界面显示用) */
|
||||
fun workDir(context: Context): String =
|
||||
(context.getExternalFilesDir(null) ?: File(context.filesDir, "external")).absolutePath
|
||||
|
||||
/**
|
||||
* 把内置界面包恢复成 APK assets 里的原样(v3.36)。
|
||||
*
|
||||
* ★ 为什么不走内核的 `/reset`:内核在安卓上读不到 APK assets
|
||||
* (`ui_packs._builtin_dir()` 指向仓库路径,APK 里不存在),
|
||||
* 而 Kotlin 这边有 AssetManager —— 所以「恢复内置」由这里做。
|
||||
*/
|
||||
fun resetUiPack(context: Context, packId: String): Boolean {
|
||||
if (!Regex("^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$").matches(packId)) return false
|
||||
val dataDir = File(context.filesDir, "kernel-data").apply { mkdirs() }.absolutePath
|
||||
val target = File(File(dataDir, "ui-packs"), packId)
|
||||
try {
|
||||
val assets = context.assets
|
||||
// 先确认 APK 里真的有这个包,别把用户包误删了
|
||||
val names = assets.list("ui-packs/$packId") ?: return false
|
||||
if (names.isEmpty()) return false
|
||||
if (!copyAssetDirChecked(assets, "ui-packs/$packId", target, overwrite = true)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.w("DoubaoKernel", "恢复内置界面包失败", t)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 和 [copyAssetDir] 相同,但任何一步失败都返回 false(调用方要知道有没有成功) */
|
||||
private fun copyAssetDirChecked(
|
||||
assets: AssetManager,
|
||||
assetPath: String,
|
||||
target: File,
|
||||
overwrite: Boolean,
|
||||
): Boolean {
|
||||
val children = try {
|
||||
assets.list(assetPath)
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
if (children.isNullOrEmpty()) {
|
||||
if (!overwrite && target.exists()) return true
|
||||
target.parentFile?.mkdirs()
|
||||
assets.open(assetPath).use { input ->
|
||||
target.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (target.exists() && target.isFile) target.delete()
|
||||
target.mkdirs()
|
||||
for (child in children) {
|
||||
if (!copyAssetDirChecked(assets, "$assetPath/$child", File(target, child), overwrite)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 APK 里的 `assets/ui-packs/` 整个目录拷到 `<data>/kernel-data/ui-packs/`。
|
||||
*
|
||||
* 规则(和内核 `ui_packs.seed_builtin()` 一致):
|
||||
* - 共享 SDK `ui-sdk/` 每次按版本覆盖 —— 它不属于用户数据;
|
||||
* - 内置界面包**只补缺、不覆盖**:用户可能已经改过 `index.html`/`style.css`,
|
||||
* 升级 App 不能把人家的皮肤冲掉。改坏了可以在「游戏界面」页点「恢复内置」;
|
||||
* - 用 `VERSION` 标记,避免每次启动都扫一遍 assets。
|
||||
*/
|
||||
private fun seedUiPacks(context: Context, dataDir: String) {
|
||||
try {
|
||||
val root = File(dataDir, "ui-packs")
|
||||
root.mkdirs()
|
||||
val assets = context.assets
|
||||
val version = runCatching {
|
||||
assets.open("ui-packs/VERSION").bufferedReader().use { it.readText() }.trim()
|
||||
}.getOrNull().orEmpty().ifBlank { "1" }
|
||||
val marker = File(root, ".seed-version")
|
||||
val names = assets.list("ui-packs") ?: emptyArray()
|
||||
// ★ 不能只看 VERSION:用户/清理工具可能删了某个内置包,标记还在。
|
||||
// 只要缺包(或包缺 index.html)就要重新补,不能因为标记相同就跳过。
|
||||
val builtinNames = names.filter { !it.startsWith("_") && it != "VERSION" }
|
||||
val missingPack = builtinNames.any { name ->
|
||||
val dir = File(root, name)
|
||||
!dir.isDirectory || !File(dir, "index.html").isFile
|
||||
}
|
||||
if (marker.isFile && marker.readText().trim() == version &&
|
||||
!missingPack && File(root, "ui-sdk").isDirectory
|
||||
) return
|
||||
|
||||
copyAssetDir(assets, "ui-packs/ui-sdk", File(root, "ui-sdk"), overwrite = true)
|
||||
for (name in builtinNames) {
|
||||
// ★ 关键:**不是** target.exists() 就跳过。
|
||||
// 老版本装过 galgame 包的用户升级到 v3.37 时,包里还缺 map/duel/bag 路由页;
|
||||
// 这里用 overwrite=false 递归补缺 —— 已存在的文件(用户可能改过)保持不动,
|
||||
// 只把新版本新增的文件补进去。想拿全部新内容就点「恢复内置」。
|
||||
copyAssetDir(assets, "ui-packs/$name", File(root, name), overwrite = false)
|
||||
}
|
||||
marker.writeText(version)
|
||||
} catch (t: Throwable) {
|
||||
// 播种失败不能让内核起不来:顶多没有内置皮肤,App 回退原生界面
|
||||
android.util.Log.w("DoubaoKernel", "游戏界面模板包播种失败(不影响启动)", t)
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyAssetDir(
|
||||
assets: AssetManager,
|
||||
assetPath: String,
|
||||
target: File,
|
||||
overwrite: Boolean,
|
||||
) {
|
||||
val children = try {
|
||||
assets.list(assetPath)
|
||||
} catch (t: Throwable) {
|
||||
// 某些 ROM/AssetManager 实现对"文件路径"调 list 会抛异常 —— 当成文件处理
|
||||
null
|
||||
}
|
||||
if (children.isNullOrEmpty()) {
|
||||
// 叶子节点是文件:assets.list 对文件返回空数组
|
||||
if (!overwrite && target.exists()) return
|
||||
target.parentFile?.mkdirs()
|
||||
assets.open(assetPath).use { input ->
|
||||
target.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
return
|
||||
}
|
||||
target.mkdirs()
|
||||
for (child in children) {
|
||||
copyAssetDir(assets, "$assetPath/$child", File(target, child), overwrite)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,10 +35,32 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
private val client = KernelClient()
|
||||
|
||||
companion object {
|
||||
/** 发通知权限的请求码(只要不和别的撞就行) */
|
||||
private const val REQ_NOTIF = 0x4D32
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
// ★★ 申请「发通知」权限(用户要求"还可以发送通知")。
|
||||
//
|
||||
// Android 13(API 33) 起这是**运行时权限**,新装的 App **默认拒绝** ——
|
||||
// 不申请的话 `NotificationManager.notify()` 不报错、但通知**根本不显示**。
|
||||
// 实测踩到:渠道建出来了(importance=3),App 级却是 `importance=NONE`,
|
||||
// 通知栏里什么都没有,而工具还返回"发送成功"。
|
||||
//
|
||||
// ★ 只在 33+ 申请:低版本没这个权限,申请了系统会直接忽略(但会打日志)。
|
||||
// ★ 用户拒绝也不影响别的功能 —— 只是发通知会失败,而且工具会如实报错。
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) {
|
||||
val need = checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
if (need) {
|
||||
requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIF)
|
||||
}
|
||||
}
|
||||
|
||||
var kernelUrl by mutableStateOf("")
|
||||
var status by mutableStateOf("正在启动本地内核…")
|
||||
var termuxReady by mutableStateOf(false)
|
||||
@@ -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
|
||||
@@ -39,9 +40,17 @@ import java.util.concurrent.TimeUnit
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
/**
|
||||
* 一次最多列多少个 App。
|
||||
*
|
||||
* ★ 必须有上限:手机上有 100~300 个 App,全塞给模型光这一条就几千 token,
|
||||
* 而且它多半只需要"找那一个"。要全量就用 query 过滤。
|
||||
*/
|
||||
private val APP_LIST_MAX = 120
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
/** 统一的入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
@@ -86,6 +95,68 @@ class NativeBridge(private val activity: Activity) {
|
||||
"session_message" -> sessionMessage(req)
|
||||
// AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult)
|
||||
"ui_result" -> pushUiResult(req)
|
||||
// ---- 操作手机:通知 / 打开 App / 音量 ----
|
||||
"notifications" -> notifications(req)
|
||||
"notification_access" -> JSONObject()
|
||||
.put("granted", PhoneOps.hasNotificationAccess(activity))
|
||||
.put("kept", DoubaoNotificationListener.count())
|
||||
"notification_settings" -> {
|
||||
// 带用户去开「通知使用权」—— Android 没有这个权限的运行时申请弹窗,
|
||||
// 只能跳到设置页让他自己勾
|
||||
activity.startActivity(PhoneOps.notificationAccessIntent())
|
||||
JSONObject().put("ok", true).put("opened", "通知使用权设置页")
|
||||
}
|
||||
"notification_clear" -> {
|
||||
DoubaoNotificationListener.clear()
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// ★ AI 主动发一条通知(用户要求"还可以发送通知")
|
||||
"notification_post" -> {
|
||||
val title = req.optString("title")
|
||||
val text = req.optString("text")
|
||||
if (title.isBlank() && text.isBlank()) {
|
||||
JSONObject().put("error", "title 和 text 至少要给一个")
|
||||
} else {
|
||||
PhoneOps.postNotification(
|
||||
activity, title, text, req.optBoolean("autoCancel", true),
|
||||
)
|
||||
}
|
||||
}
|
||||
"apps" -> appsList(req)
|
||||
"app_launch" -> appLaunch(req)
|
||||
// ★ 预设快捷入口(用户要求"预设几个比如微信对话,支付宝菜鸟")
|
||||
"app_shortcuts" -> {
|
||||
val arr = JSONArray()
|
||||
AppShortcuts.all(activity).forEach { m ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("id", m["id"])
|
||||
.put("label", m["label"])
|
||||
.put("app", m["app"])
|
||||
.put("installed", m["installed"])
|
||||
.put("keywords", JSONArray(m["keywords"] as List<*>)),
|
||||
)
|
||||
}
|
||||
JSONObject().put("shortcuts", arr)
|
||||
}
|
||||
"app_shortcut_open" -> {
|
||||
val key = req.optString("shortcut").ifBlank { req.optString("name") }
|
||||
val hit = AppShortcuts.find(key)
|
||||
if (hit == null) {
|
||||
JSONObject()
|
||||
.put("error", "没有叫「$key」的预设快捷入口")
|
||||
.put("hint", "可以用的有:" + AppShortcuts.ids().joinToString("、"))
|
||||
} else {
|
||||
AppShortcuts.run(activity, hit)
|
||||
}
|
||||
}
|
||||
"volume" -> JSONObject().put("state", PhoneOps.volumeState(activity))
|
||||
"volume_set" -> PhoneOps.setVolume(
|
||||
activity,
|
||||
req.optString("stream", "music"),
|
||||
req.optString("mode", "set"),
|
||||
req.optInt("value", 0),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -170,6 +241,9 @@ class NativeBridge(private val activity: Activity) {
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**(用户要求"AI 询问界面不要限时")。
|
||||
* 想限时得模型显式传 timeout。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
@@ -198,7 +272,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
fullHtml = fullHtml,
|
||||
conversationId = convId,
|
||||
wait = wait,
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
screenId = screenId,
|
||||
)
|
||||
}
|
||||
@@ -263,8 +337,12 @@ class NativeBridge(private val activity: Activity) {
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点或超时 ——
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**。用户的原话是"AI 询问界面不要限时":
|
||||
* 他在思考的时候弹窗到点自己消失、模型还收到 timeout 当成"用户不理我",
|
||||
* 这一轮就答非所问了。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
@@ -292,7 +370,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -342,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")
|
||||
@@ -365,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")
|
||||
@@ -378,6 +456,145 @@ class NativeBridge(private val activity: Activity) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 App。
|
||||
*
|
||||
* ★ 没传 query 就返回全部(截前 [APP_LIST_MAX] 个)——
|
||||
* 模型可以先看一眼有哪些 App,再决定开哪个。
|
||||
*/
|
||||
private fun appsList(req: JSONObject): JSONObject {
|
||||
val query = req.optString("query").trim()
|
||||
val all = PhoneOps.installedApps(activity)
|
||||
val out = JSONArray()
|
||||
if (query.isBlank()) {
|
||||
all.take(APP_LIST_MAX).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("apps", out)
|
||||
}
|
||||
val q = query.lowercase()
|
||||
all.filter {
|
||||
it.first.lowercase().contains(q) || it.second.lowercase().contains(q)
|
||||
}.take(30).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("matched", out.length()).put("apps", out)
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个 App。
|
||||
*
|
||||
* ★ 找不到时**明确报错并给出相近的名字** —— 让模型能自己改一个再来,
|
||||
* 而不是回一个干巴巴的"失败"(那样它只会反复重试同一个错名字)。
|
||||
*/
|
||||
private fun appLaunch(req: JSONObject): JSONObject {
|
||||
// 已经知道包名和 Activity(从上一步 app_list 拿到的)就直接开,省一次全表扫描
|
||||
val pkg = req.optString("package").trim()
|
||||
val cls = req.optString("activity").trim()
|
||||
if (pkg.isNotEmpty()) {
|
||||
// ★ 只给包名不给 activity 是**最常见的用法**(比如"打开微信"),
|
||||
// 这时候自己去查它的 launcher activity —— 让模型去记
|
||||
// `com.tencent.mm.ui.LauncherUI` 这种名字既没必要也容易记错。
|
||||
val realCls = cls.ifEmpty { AppShortcuts.mainActivityOf(activity, pkg) }
|
||||
if (realCls.isEmpty()) {
|
||||
return JSONObject()
|
||||
.put("error", "找不到 $pkg 的启动入口(可能没装,或者它没有可启动的界面)")
|
||||
}
|
||||
// ★ 有 activity 时先试"直接拉起那个 Activity"(能直达指定页面),
|
||||
// 失败再退回标准 launcher 方式 —— App 内部 Activity 常常没导出,
|
||||
// 直接拉会被系统拒。
|
||||
if (cls.isNotEmpty()) {
|
||||
val directErr = PhoneOps.launchActivity(activity, pkg, cls)
|
||||
if (directErr == null) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", cls).put("how", "direct")
|
||||
}
|
||||
// 直拉失败就退回标准方式;两者都失败才报错
|
||||
if (PhoneOps.launchApp(activity, pkg, realCls)) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
.put("note", "没法直达指定页面($directErr),已经打开 App 主界面")
|
||||
}
|
||||
// ★ 两边都失败:错误里**两个原因都要说**。
|
||||
// 只说直拉那个的话会误导 —— 用户/模型以为是"activity 名字写错了",
|
||||
// 其实退回主界面也失败了(那才是更严重的问题)。
|
||||
return JSONObject().put(
|
||||
"error",
|
||||
"启动 $pkg 失败:直达指定页面不行($directErr)," +
|
||||
"退回主界面也不行($realCls 打不开)。这个 App 可能被停用了。",
|
||||
)
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, pkg, realCls)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
} else {
|
||||
JSONObject().put("error", "启动 $pkg 失败(系统拒绝了,可能被停用)")
|
||||
}
|
||||
}
|
||||
|
||||
val name = req.optString("name").trim()
|
||||
if (name.isEmpty()) {
|
||||
return JSONObject().put("error", "至少要给 name(App 名字)或 package+activity")
|
||||
}
|
||||
val hit = PhoneOps.findApp(activity, name)
|
||||
?: run {
|
||||
// 给几个名字相近的当提示
|
||||
val q = name.lowercase()
|
||||
val near = PhoneOps.installedApps(activity)
|
||||
.filter { it.first.lowercase().contains(q.take(2)) }
|
||||
.take(5)
|
||||
.map { it.first }
|
||||
return JSONObject()
|
||||
.put("error", "没找到叫「$name」的 App")
|
||||
.put("hint", if (near.isEmpty()) {
|
||||
// ★ 这里写的 action 名必须和 tools/apps.py 里 enum 的一致。
|
||||
// 第一版写的 `app_list` —— 那个名字不存在,模型照着调会失败。
|
||||
"可以用 action=list 看看装了哪些 App"
|
||||
} else {
|
||||
"名字相近的有:" + near.joinToString("、") + "。换个名字再试"
|
||||
})
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, hit.second, hit.third)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true)
|
||||
.put("label", hit.first)
|
||||
.put("package", hit.second)
|
||||
} else {
|
||||
JSONObject().put("error", "找到「${hit.first}」但启动失败(系统拒绝了)")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读通知。
|
||||
*
|
||||
* ★ 权限没开时**返回明确错误**,不是空列表。
|
||||
* 返回空列表的话模型会说"最近没有通知" —— 那是**错的**
|
||||
* (明明有几条,只是我们读不到),用户会被误导。
|
||||
*/
|
||||
private fun notifications(req: JSONObject): JSONObject {
|
||||
if (!PhoneOps.hasNotificationAccess(activity)) {
|
||||
return JSONObject()
|
||||
.put("error", "没有「通知使用权」,读不到任何通知")
|
||||
.put("granted", false)
|
||||
.put(
|
||||
"hint",
|
||||
"这个权限安卓不给运行时申请,必须用户手动开:" +
|
||||
"设置 → 通知 → 通知使用权(或「通知读取权限」)→ 找到本 App 打开。" +
|
||||
"调用 action=notification_settings 可以直接跳到那个设置页。",
|
||||
)
|
||||
}
|
||||
val arr = DoubaoNotificationListener.recent(
|
||||
limit = req.optInt("limit", 20),
|
||||
onlyAlive = req.optBoolean("onlyAlive", false),
|
||||
query = req.optString("query"),
|
||||
)
|
||||
return JSONObject()
|
||||
.put("granted", true)
|
||||
.put("count", arr.length())
|
||||
.put("notifications", arr)
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
@@ -621,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()
|
||||
}
|
||||
@@ -664,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")
|
||||
374
豆鲍/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -0,0 +1,374 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★ 三个"操作手机"的能力:读通知 / 打开 App / 调音量。
|
||||
*
|
||||
* 抽成一个文件是因为它们同类(都是"AI 要动手机"),
|
||||
* 而且都要处理"权限没给"这一种失败 —— 收在一起比较好统一口径。
|
||||
*
|
||||
* ## 一律"如实报错",不假装成功
|
||||
*
|
||||
* 通知使用权没开、找不到那个 App、音量被系统锁住 —— 这些都会**明确返回错误**,
|
||||
* 而不是返回一个空列表或者一个看起来成功的值。
|
||||
* 模型拿到"权限没开"才会去告诉用户怎么开;拿到空列表它只会说
|
||||
* "最近没有通知",那是**错的**(明明有几条,只是我们读不到)。
|
||||
*/
|
||||
object PhoneOps {
|
||||
|
||||
private const val TAG = "DoubaoPhone"
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 通知使用权开了没有 */
|
||||
fun hasNotificationAccess(ctx: Context): Boolean {
|
||||
val flat = Settings.Secure.getString(ctx.contentResolver, "enabled_notification_listeners")
|
||||
?: return false
|
||||
if (flat.isBlank()) return false
|
||||
val me = ComponentName(ctx, DoubaoNotificationListener::class.java)
|
||||
// enabled_notification_listeners 是 `pkg/cls:pkg/cls` 的形式,
|
||||
// 而且**不同 ROM 的大小写和简写不一样**,所以比对时统一转小写再找
|
||||
return flat.lowercase().split(':').any { entry ->
|
||||
val e = entry.trim()
|
||||
e == me.flattenToString().lowercase() ||
|
||||
e == me.flattenToShortString().lowercase() ||
|
||||
e.startsWith(me.packageName.lowercase() + "/")
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知使用权的设置页(带用户去开) */
|
||||
fun notificationAccessIntent(): Intent =
|
||||
Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 四、发通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 通知渠道 id。
|
||||
*
|
||||
* ★ Android 8+ 必须挂在渠道上,否则通知**直接被丢掉**(连报错都没有)。
|
||||
* 渠道的重要性用 DEFAULT:太低会被折叠成静音,用户根本注意不到;
|
||||
* 太高(HIGH)会弹横幅 —— 对"AI 提醒你一件事"这种场景
|
||||
* 弹横幅太打扰了,DEFAULT 正合适(有声音 + 进通知栏,不弹横幅)。
|
||||
*/
|
||||
private const val CHANNEL_ID = "doubao_ai"
|
||||
private const val CHANNEL_NAME = "AI 提醒"
|
||||
|
||||
private fun ensureChannel(ctx: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
// ★ 不要"渠道已存在就 return":v3.17 换了 App 名之后,老用户的渠道里
|
||||
// 还留着旧描述(系统设置 → 通知里能看到)。`createNotificationChannel`
|
||||
// 用同一个 id 再调一次只会更新 name/description,不动用户改过的
|
||||
// importance,所以每次发通知前顺手刷一遍是安全的。
|
||||
// ★ CHANNEL_ID 保持 `doubao_ai`:改 id 会新建一个渠道、老渠道的设置/通知记录全丢。
|
||||
val ch = android.app.NotificationChannel(
|
||||
CHANNEL_ID, CHANNEL_NAME, android.app.NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "小人间主动发出来的提醒"
|
||||
enableVibration(true)
|
||||
}
|
||||
nm.createNotificationChannel(ch)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 发一条通知 —— 用户要求"还可以发送通知"。
|
||||
*
|
||||
* 用途:AI 说到点提醒你什么、长任务跑完了通知一声。
|
||||
*
|
||||
* ★ 点通知要能回到 App:用 `PendingIntent` 打开 MainActivity。
|
||||
* 不给 PendingIntent 的话点了没反应 —— 用户会觉得"这通知是死的"。
|
||||
*
|
||||
* ★ 用 `System.currentTimeMillis()` 当通知 id:每条独立存在,不会互相覆盖。
|
||||
* 固定 id 的话后一条会把前一条顶掉("我刚收到的提醒怎么没了")。
|
||||
*/
|
||||
fun postNotification(ctx: Context, title: String, text: String, autoCancel: Boolean): JSONObject {
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
ensureChannel(ctx)
|
||||
|
||||
val t = title.trim().ifBlank { "小人间" }
|
||||
val body = text.trim()
|
||||
|
||||
// 点通知打开 App
|
||||
val open = Intent(ctx, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
var flags = android.app.PendingIntent.FLAG_UPDATE_CURRENT
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags = flags or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
}
|
||||
val pi = android.app.PendingIntent.getActivity(ctx, 0, open, flags)
|
||||
|
||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
android.app.Notification.Builder(ctx, CHANNEL_ID)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
android.app.Notification.Builder(ctx)
|
||||
}
|
||||
builder
|
||||
// ★ v3.17 起不能再用 applicationInfo.icon:自适应图标是 108dp 的
|
||||
// 图层组合,setSmallIcon 拿到它有些机型会渲成空白。小图标要单色剪影,
|
||||
// 所以单独做了个 ic_notify(纯白房子,系统自己染色)。
|
||||
.setSmallIcon(R.drawable.ic_notify) // ★ 不给 smallIcon 通知**不会显示**
|
||||
.setContentTitle(t)
|
||||
.setContentText(body)
|
||||
.setAutoCancel(autoCancel)
|
||||
.setContentIntent(pi)
|
||||
// 正文长的话展开显示(否则通知栏只显示一行,被截断)
|
||||
if (body.length > 40) {
|
||||
builder.setStyle(android.app.Notification.BigTextStyle().bigText(body))
|
||||
}
|
||||
|
||||
val id = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
|
||||
return try {
|
||||
nm.notify(id, builder.build())
|
||||
JSONObject().put("ok", true).put("id", id)
|
||||
.put("title", t)
|
||||
.put("chars", body.length)
|
||||
} catch (t2: Throwable) {
|
||||
Log.w(TAG, "发通知失败:${t2.message}")
|
||||
JSONObject().put("error", "发通知失败:${t2.javaClass.simpleName}: ${t2.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、打开 App */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 能启动的 App 列表(系统 + 用户装的) */
|
||||
fun installedApps(ctx: Context): List<Triple<String, String, String>> {
|
||||
val pm = ctx.packageManager
|
||||
val main = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
// ★ Android 11+ 必须先在 Manifest 的 <queries> 里声明 LAUNCHER intent,
|
||||
// 否则这里返回空列表(看着像"这台手机没有 App",很误导)
|
||||
val list = if (Build.VERSION.SDK_INT >= 33) {
|
||||
pm.queryIntentActivities(
|
||||
main,
|
||||
android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
pm.queryIntentActivities(main, 0)
|
||||
}
|
||||
return list.mapNotNull { ri ->
|
||||
val pkg = ri.activityInfo?.packageName ?: return@mapNotNull null
|
||||
val cls = ri.activityInfo?.name ?: return@mapNotNull null
|
||||
val label = ri.loadLabel(pm).toString()
|
||||
Triple(label, pkg, cls)
|
||||
}.sortedBy { it.first }
|
||||
}
|
||||
|
||||
/** 模糊匹配一个 App;找不到返回 null */
|
||||
fun findApp(ctx: Context, query: String): Triple<String, String, String>? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
val all = installedApps(ctx)
|
||||
// 优先级:包名完全相同 > 名字完全相同 > 名字以它开头 > 包含 > 包名包含
|
||||
return all.firstOrNull { it.second.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase().startsWith(q) }
|
||||
?: all.firstOrNull { it.first.lowercase().contains(q) }
|
||||
?: all.firstOrNull { it.second.lowercase().contains(q) }
|
||||
}
|
||||
|
||||
/** 启动一个 App */
|
||||
fun launchApp(ctx: Context, pkg: String, cls: String): Boolean = try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "启动 $pkg/$cls 失败:${t.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接拉起某个 Activity(不一定是 launcher 那个)。
|
||||
*
|
||||
* 用途:微信的某些页面有独立 Activity,用它能直达。
|
||||
*
|
||||
* ★ 会被系统拦的情况很多:Activity 没导出(`android:exported=false`)、
|
||||
* 被 App 的权限保护、或者版本更新后改了名字。
|
||||
* 所以**返回具体原因**,不要只回一个 false —— 模型据此决定要不要退回主界面。
|
||||
*/
|
||||
fun launchActivity(ctx: Context, pkg: String, cls: String): String? = try {
|
||||
ctx.startActivity(
|
||||
Intent().setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
null
|
||||
} catch (t: Throwable) {
|
||||
"${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
|
||||
/**
|
||||
* 用自定义 scheme 打开(深链)。
|
||||
*
|
||||
* ★ 这是"预设快捷入口"的主力:像 `weixin://`、`alipays://` 这种,
|
||||
* 比猜 Activity 名字稳得多 —— Activity 名字随版本变,scheme 通常不变。
|
||||
*
|
||||
* ★ 必须查 `resolveActivity`:没装那个 App、或者它不认这个 scheme 时,
|
||||
* `startActivity` 会抛 `ActivityNotFoundException`。
|
||||
* 先查一遍能给出**更准确的错误**("没装"vs"不认这个链接")。
|
||||
*/
|
||||
fun launchUri(ctx: Context, uri: String): String? {
|
||||
val parsed = try {
|
||||
android.net.Uri.parse(uri)
|
||||
} catch (t: Throwable) {
|
||||
return "链接解析失败:${t.message}"
|
||||
}
|
||||
val intent = Intent(Intent.ACTION_VIEW, parsed).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val hit = if (Build.VERSION.SDK_INT >= 33) {
|
||||
ctx.packageManager.resolveActivity(
|
||||
intent, android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ctx.packageManager.resolveActivity(intent, 0)
|
||||
}
|
||||
if (hit == null) {
|
||||
return "没有 App 能处理这个链接(对应 App 没装,或者版本不认这个 scheme)"
|
||||
}
|
||||
return try {
|
||||
ctx.startActivity(intent)
|
||||
null
|
||||
} catch (t: Throwable) {
|
||||
"${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
}
|
||||
|
||||
/** 某个包装了没有 */
|
||||
fun isInstalled(ctx: Context, pkg: String): Boolean = try {
|
||||
ctx.packageManager.getApplicationInfo(pkg, 0)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、音量 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 音量流。
|
||||
*
|
||||
* ★ 用**字符串名**而不是整数常量:模型要写 `music` / `ring` 这种可读的名字,
|
||||
* 让它记 `STREAM_MUSIC = 3` 既没必要也容易错。
|
||||
*/
|
||||
private fun streamOf(name: String): Int = when (name.trim().lowercase()) {
|
||||
"ring", "ringtone", "铃声" -> AudioManager.STREAM_RING
|
||||
"alarm", "闹钟" -> AudioManager.STREAM_ALARM
|
||||
"call", "voice_call", "通话" -> AudioManager.STREAM_VOICE_CALL
|
||||
"system", "系统" -> AudioManager.STREAM_SYSTEM
|
||||
"notification", "通知" -> AudioManager.STREAM_NOTIFICATION
|
||||
else -> AudioManager.STREAM_MUSIC // 默认媒体音量(最常用)
|
||||
}
|
||||
|
||||
private fun streamName(stream: Int): String = when (stream) {
|
||||
AudioManager.STREAM_RING -> "ring"
|
||||
AudioManager.STREAM_ALARM -> "alarm"
|
||||
AudioManager.STREAM_VOICE_CALL -> "call"
|
||||
AudioManager.STREAM_SYSTEM -> "system"
|
||||
AudioManager.STREAM_NOTIFICATION -> "notification"
|
||||
else -> "music"
|
||||
}
|
||||
|
||||
/**
|
||||
* 读所有音量流的当前值。
|
||||
*
|
||||
* ★ 同时给**原始值**和**百分比**:模型想"调到一半"用百分比直观,
|
||||
* 想"加一格"用原始值准。两个都给,它自己挑。
|
||||
*/
|
||||
fun volumeState(ctx: Context): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val arr = JSONArray()
|
||||
val streams = listOf(
|
||||
AudioManager.STREAM_MUSIC, AudioManager.STREAM_RING, AudioManager.STREAM_ALARM,
|
||||
AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_SYSTEM,
|
||||
AudioManager.STREAM_NOTIFICATION,
|
||||
)
|
||||
for (s in streams) {
|
||||
val cur = am.getStreamVolume(s)
|
||||
val max = am.getStreamMaxVolume(s).coerceAtLeast(1)
|
||||
val pct = Math.round(cur * 100f / max)
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("stream", streamName(s))
|
||||
.put("current", cur)
|
||||
.put("max", max)
|
||||
.put("percent", pct)
|
||||
.put("muted", cur == 0),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("streams", arr)
|
||||
}
|
||||
|
||||
/**
|
||||
* 调音量。
|
||||
*
|
||||
* @param mode set=设成具体值 / up=加 / down=减 / mute=静音 / unmute=取消静音
|
||||
* @param value set 时的值,或 up/down 的步数(默认 1)
|
||||
*/
|
||||
fun setVolume(ctx: Context, streamArg: String, mode: String, value: Int): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val stream = streamOf(streamArg)
|
||||
val max = am.getStreamMaxVolume(stream).coerceAtLeast(1)
|
||||
val before = am.getStreamVolume(stream)
|
||||
|
||||
val target: Int = when (mode.trim().lowercase()) {
|
||||
"mute" -> 0
|
||||
"unmute" -> {
|
||||
// 取消静音:恢复到"上次非零"不好拿,用 max 的一半,至少能听见
|
||||
if (before > 0) before else (max / 2).coerceAtLeast(1)
|
||||
}
|
||||
"up" -> (before + value.coerceAtLeast(1)).coerceAtMost(max)
|
||||
"down" -> (before - value.coerceAtLeast(1)).coerceAtLeast(0)
|
||||
else -> value.coerceIn(0, max)
|
||||
}
|
||||
|
||||
// ★ DND(勿扰)开着时系统会**拒绝**改铃声/通知音量 —— 静默失败。
|
||||
// 所以改完必须**回读**确认,不能假定成功。
|
||||
var err = ""
|
||||
try {
|
||||
am.setStreamVolume(stream, target, 0)
|
||||
} catch (t: Throwable) {
|
||||
err = "${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
val after = am.getStreamVolume(stream)
|
||||
|
||||
val ok = if (err.isEmpty()) after == target else false
|
||||
val out = JSONObject()
|
||||
.put("stream", streamName(stream))
|
||||
.put("before", before)
|
||||
.put("requested", target)
|
||||
.put("current", after)
|
||||
.put("max", max)
|
||||
.put("percent", Math.round(after * 100f / max))
|
||||
.put("ok", ok)
|
||||
if (err.isNotEmpty()) out.put("error", err)
|
||||
if (!ok && err.isEmpty()) {
|
||||
// 回读和请求不一致 = 系统拦了(多半是勿扰模式)
|
||||
out.put(
|
||||
"error",
|
||||
"系统没有接受这次调整(可能开了勿扰模式,或该音量流被系统锁定)。" +
|
||||
"当前值仍是 $after。",
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.doubao.lynxclone.data
|
||||
|
||||
/**
|
||||
* 客户端这边的超时缓存。
|
||||
*
|
||||
* ## 为什么客户端也要有一份
|
||||
*
|
||||
* 权威在**内核**(`android/kernel/timeouts.py`,界面通过 `GET /api/timeouts` 拿)。
|
||||
* 但客户端有几处**没法在用的那一刻去问内核**:
|
||||
*
|
||||
* · OkHttp 的连接池 —— 建连接时就要 readTimeout,而"去问内核"本身要用这个连接
|
||||
* · 文件选择(SAF)—— 那是系统界面的等待,内核根本不知情
|
||||
*
|
||||
* 所以这里缓存一份,App 启动时拉一次、用户改完设置再刷新一次。
|
||||
*
|
||||
* ★ 拿不到时一律回落**和内核一样的默认值** —— 不回落的话,"内核还没起来"
|
||||
* 会让连接超时变成 0(每次都断)。两边的默认值要保持一致,
|
||||
* `scripts/verify-timeouts.py` 会检查内核对不对得上。
|
||||
*/
|
||||
object AppTimeouts {
|
||||
|
||||
@Volatile
|
||||
private var values: Map<String, Double> = emptyMap()
|
||||
|
||||
/** 内核给的清单(界面上那份),缓存着免得每次进设置页都请求 */
|
||||
@Volatile
|
||||
var state: TimeoutsState = TimeoutsState()
|
||||
private set
|
||||
|
||||
fun update(next: TimeoutsState) {
|
||||
state = next
|
||||
values = next.values
|
||||
}
|
||||
|
||||
fun seconds(key: String, fallback: Double): Double {
|
||||
val v = values[key] ?: return fallback
|
||||
return if (v <= 0.0) fallback else v
|
||||
}
|
||||
|
||||
fun millis(key: String, fallbackMs: Long): Long =
|
||||
(seconds(key, fallbackMs / 1000.0) * 1000).toLong()
|
||||
|
||||
/**
|
||||
* 等用户的那两项:**0 是有意义的值**(不限时),所以不能按上面的写法回落。
|
||||
*/
|
||||
fun userWaitMillis(key: String): Long {
|
||||
val v = values[key] ?: return 0L
|
||||
return if (v <= 0.0) 0L else (v * 1000).toLong()
|
||||
}
|
||||
|
||||
/** 读 SSE 的间隔上限 —— 必须大于心跳间隔,否则等用户时连接会被自己掐掉 */
|
||||
fun sseReadSeconds(): Long = seconds("sseRead", 120.0).toLong().coerceAtLeast(20L)
|
||||
}
|
||||
3041
豆鲍/android/app/src/main/java/com/doubao/lynxclone/data/Models.kt
Normal file
@@ -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)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
@@ -234,8 +234,10 @@ object AiSurface {
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★ 超时必须有:用户可能锁屏走了。不设的话内核工作线程永远挂着,
|
||||
* 而 HTTP 是每请求一线程,挂一个少一个。
|
||||
* ★★ [timeoutMs] <= 0 表示**不限时**(等用户到天荒地老),这是默认。
|
||||
* 以前默认 120 秒,用户明确要求"AI 询问界面不要限时"——
|
||||
* 他可能看着界面想很久,120 秒到点界面自己收掉,体验很差。
|
||||
* 现在想限时得由模型显式传 timeout。
|
||||
*/
|
||||
fun showScreen(
|
||||
html: String,
|
||||
@@ -243,7 +245,7 @@ object AiSurface {
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 120_000L,
|
||||
timeoutMs: Long = 0L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(
|
||||
@@ -257,7 +259,7 @@ object AiSurface {
|
||||
Log.i(
|
||||
TAG,
|
||||
"AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," +
|
||||
if (wait) "等用户操作(最多 ${timeoutMs / 1000}s)" else "不等待",
|
||||
if (wait) "等用户操作(${waitLabel(timeoutMs)})" else "不等待",
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
@@ -271,7 +273,7 @@ object AiSurface {
|
||||
|
||||
// ---- 等待模式 ----
|
||||
val latch = screenLatch
|
||||
val answered = latch?.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS) ?: false
|
||||
val answered = latch?.let { awaitUser(it, timeoutMs) } ?: false
|
||||
val answer = screenAnswer
|
||||
val closed = screenClosed
|
||||
screenLatch = null
|
||||
@@ -342,10 +344,18 @@ object AiSurface {
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完或超时。
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完。
|
||||
*
|
||||
* ★ 超时是必须的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
* 而且因为 HTTP 是每请求一线程,挂一个少一个。
|
||||
* ★★ [timeoutMs] <= 0 = **不限时**(默认)。这是用户明确要求的:
|
||||
* "AI 询问界面不要限时" —— 他可能对着选项想很久,或者在忙别的事,
|
||||
* 120 秒到点弹窗自己消失、模型收到 `timeout=true` 以为他不想理,
|
||||
* 然后自说自话往下走 —— 整轮就废了。
|
||||
*
|
||||
* ★ 放行的方式(用户总得有一个出口,不然内核线程永远挂着):
|
||||
* · 点任意一个选项 → [answerDialog] → countDown
|
||||
* · 点「取消」(`allowCancel` 默认 true)→ 同上,`cancelled=true`
|
||||
* · 关掉 App → 进程结束,线程一起没了
|
||||
* 所以只要界面上留着取消按钮,无限等就不会变成死锁。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
@@ -364,9 +374,9 @@ object AiSurface {
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,最多等 ${timeoutMs / 1000}s)")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,${waitLabel(timeoutMs)})")
|
||||
|
||||
val answered = latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
val answered = awaitUser(latch, timeoutMs)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
@@ -384,6 +394,27 @@ object AiSurface {
|
||||
return a
|
||||
}
|
||||
|
||||
/**
|
||||
* 等用户动作。
|
||||
*
|
||||
* [timeoutMs] <= 0 → **无限等**(`await()` 不带超时);否则最多等那么久。
|
||||
* 返回 true 表示等到了。
|
||||
*
|
||||
* ★ 只有这一个地方做等待,[ask] 和 [showScreen] 都走它 ——
|
||||
* 两处各写一遍的话,"不限时"这种改动迟早只改到一处。
|
||||
*/
|
||||
private fun awaitUser(latch: CountDownLatch, timeoutMs: Long): Boolean =
|
||||
if (timeoutMs <= 0L) {
|
||||
latch.await()
|
||||
true
|
||||
} else {
|
||||
latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
/** 日志里怎么描述等待时长 */
|
||||
private fun waitLabel(timeoutMs: Long): String =
|
||||
if (timeoutMs <= 0L) "不限时,等用户回答" else "最多等 ${timeoutMs / 1000}s"
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
@@ -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>,
|
||||
937
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt
Normal file
@@ -0,0 +1,937 @@
|
||||
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 -> if (vm.gameUiActive) GameUiScreen(vm) else 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)),
|
||||
) {
|
||||
if (vm.gameUiActive) {
|
||||
GameUiRouteScreen(
|
||||
vm = vm, route = "bag",
|
||||
containerId = vm.userItemsContainerId,
|
||||
conversationId = vm.activeConversationId,
|
||||
onClose = { vm.closeUserItems() },
|
||||
onMoved = { pid, name -> vm.onGameUserMoved(pid, vm.userItemsContainerId, name) },
|
||||
)
|
||||
} else {
|
||||
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)),
|
||||
) {
|
||||
if (vm.gameUiActive) {
|
||||
GameUiRouteScreen(
|
||||
vm = vm, route = "map",
|
||||
containerId = vm.mapContainerId,
|
||||
conversationId = vm.activeConversationId,
|
||||
onClose = { vm.closeMap() },
|
||||
onMoved = { pid, name -> vm.onMapMoved(pid, name) },
|
||||
)
|
||||
} else {
|
||||
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)),
|
||||
) {
|
||||
if (vm.gameUiActive) {
|
||||
GameUiRouteScreen(
|
||||
vm = vm, route = "duel",
|
||||
containerId = vm.currentContainerId(),
|
||||
conversationId = vm.activeConversationId,
|
||||
onClose = { vm.closeDuelScreen() },
|
||||
)
|
||||
} else {
|
||||
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() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「游戏界面(HTML)」设置页(v3.36)—— 选皮肤 / 开关 / 恢复内置。
|
||||
// 放在超时页后面:它也是个全屏设置页,从设置入口进来。
|
||||
AnimatedVisibility(
|
||||
visible = vm.gameUiSettingsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
GameUiSettingsScreen(vm = vm, onBack = { vm.closeGameUiSettings() })
|
||||
}
|
||||
|
||||
// 「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.39):UI 包里的 HTML 想跳哪里就跳哪里。
|
||||
// 页面数量/文件名不限;编辑器预览和页面里的 GameUI.openPage 都走这里。
|
||||
AnimatedVisibility(
|
||||
visible = vm.gameUiPage.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
GameUiRouteScreen(
|
||||
vm = vm,
|
||||
route = vm.gameUiPage,
|
||||
containerId = vm.gameUiPageContainerId,
|
||||
conversationId = vm.gameUiPageConversationId,
|
||||
query = vm.gameUiPageQuery,
|
||||
packId = vm.gameUiPagePack,
|
||||
onClose = { vm.closeGameUiPage() },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 提示条(吐司)----------------
|
||||
*
|
||||
* ★★ 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 -> "自动"
|
||||
}
|
||||
4308
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt
Normal file
@@ -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
@@ -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("决斗")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||