Compare commits
154 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | ||
|
|
b1dd740b0d | ||
|
|
103c939051 | ||
|
|
885a1f0123 | ||
|
|
ba429e67cd | ||
|
|
5f138be5fa | ||
|
|
f7454c0b60 | ||
|
|
0ad999b6e6 | ||
|
|
e18970c85f | ||
|
|
0fe43d67df | ||
|
|
f789803eae | ||
|
|
52680b9eb7 | ||
|
|
6197b726a5 | ||
|
|
cead531983 | ||
|
|
2601e9ae43 | ||
|
|
8123fff9ca | ||
|
|
c25e94583a | ||
|
|
ecb6e6f924 | ||
|
|
028d67c3ec | ||
| 982c64939b | |||
| b39c23b4dd | |||
| 82fbbe8887 | |||
| 9dc26ed427 | |||
| 85238013a1 | |||
| 97793231c1 | |||
| 59e12a7261 | |||
| dd7bce574e | |||
| 71703c173c | |||
| ed97ec6c63 | |||
| 0f618ba2b0 | |||
| 04f00d1114 | |||
| 754ff80b2b | |||
| 19fe7a6af6 | |||
| 659a212465 | |||
| 626ac89ac8 | |||
| df909f3dd6 | |||
| 5c157c3044 | |||
| 7705a3eb7e | |||
| 52feef35cd | |||
| d88a7aa8aa | |||
| fb105377a9 | |||
| a536b7ba27 | |||
| 519250b109 | |||
| cfdf10a035 | |||
| 7f3dbb4002 | |||
| bec25b71ac | |||
| 19a03724bb | |||
| 5ed71f4f1b | |||
| 3266afd1a4 | |||
| bc6a172888 | |||
| 4883cedfeb | |||
| c8c3dfd59c | |||
| affc407f5e | |||
| 29f29a4524 | |||
| 2a459dd5a4 | |||
| a661102bf1 | |||
| d46008cb11 | |||
| 999ad82065 | |||
| cb7e3a91db | |||
| ed5a3115df | |||
| 66b5f13c4e | |||
| c3eb714b10 |
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/
|
||||
|
||||
101
AGENTS.md
@@ -1,68 +1,61 @@
|
||||
# 界面约定
|
||||
# AGENTS.md(入口)
|
||||
|
||||
适用于本仓库的 Android / Compose 界面。
|
||||
**项目约定在 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)** ——
|
||||
代码托管(两个 remote、推送注意事项)和界面约定(少用弹窗、能开界面就开界面、
|
||||
全屏界面骨架、几个反复踩的坑)都在那份里。
|
||||
|
||||
## 少用弹窗,能开界面就开界面
|
||||
请以那份为准,本文只做入口。
|
||||
|
||||
用户明确要求:**尽量减少弹窗那种,能加界面就加界面。**
|
||||
|
||||
理由(也是判断标准):
|
||||
|
||||
- **弹窗装不下东西**。一屏对话框的高度大概只够三四行内容,一旦要放的
|
||||
东西超过这个量(列表、代码框、多组配置),用户就得在弹窗里滚动 ——
|
||||
那还不如直接开一屏。
|
||||
- **弹窗会互相压**。弹窗里再弹一个(比如"变量管理"里点"新建",
|
||||
或者"节点管理"里点"编辑")在手机上是灾难:返回键的行为变得说不清,
|
||||
用户也不知道自己在第几层。
|
||||
- **弹窗盖住上下文**。这个 App 的会议画布本身就是要看着的,
|
||||
一个盖住半屏的对话框让人没法一边看图一边改配置。
|
||||
|
||||
### 该怎么做
|
||||
|
||||
| 内容量 | 用什么 |
|
||||
|---|---|
|
||||
| 一次确认("要删除吗") | `AlertDialog` ✓ 弹窗合适 |
|
||||
| 纯菜单(两三个入口,点完就走) | 底部弹层或 `AlertDialog` ✓ |
|
||||
| 列表 / 多组配置 / 代码 / 任何要滚动的 | **独立全屏界面**,顶栏 `← 返回` + 标题 + 右侧动作 |
|
||||
|
||||
### 全屏界面的骨架
|
||||
|
||||
统一用同一套顶栏,别各写各的(不然返回的位置、标题的大小、
|
||||
右边按钮的样式会到处不一样):
|
||||
## 这个仓库的目录
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
豆鲍/ 完整工程(android / server / web / desktop / scripts / docs …)
|
||||
豆鲍编辑器/ 独立「豆鲍编辑器」:桌面 app + Windows exe + APK,
|
||||
给豆包世界状态等系统写 Python 脚本用(见它的 README)
|
||||
.git/
|
||||
```
|
||||
|
||||
参考实现:`NodeBlockEditorScreen`(`NodeBlockEditor.kt`)的顶栏。
|
||||
**所有工程操作都从 `豆鲍/` 里执行**:
|
||||
|
||||
### 返回键
|
||||
```bash
|
||||
cd 豆鲍
|
||||
python scripts/probe-agent-system.py # 探针
|
||||
node scripts/build-apk.mjs # 构建 APK
|
||||
```
|
||||
|
||||
全屏界面要能被系统返回键关掉(用状态变量控制显示时,
|
||||
记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 ——
|
||||
比弹窗还糟。
|
||||
## 三条最容易忘的
|
||||
|
||||
## 已经欠着的(按这个原则该改还没改的)
|
||||
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)。
|
||||
|
||||
- [ ] 节点管理 `NodeManagerDialog` → 全屏
|
||||
- [ ] 节点编辑 `NodeEditDialog` → 全屏(代码编辑要有整屏)
|
||||
- [ ] 变量管理 `VarManagerDialog` → 全屏
|
||||
- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层
|
||||
- [ ] 导入会议 `ImportDialog` → 全屏
|
||||
- [ ] 节点配置 `NodeConfigDialog` → 全屏(字段很多)
|
||||
## 安卓模拟器(要装 App / 截图验证时看这份)
|
||||
|
||||
**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。
|
||||
```powershell
|
||||
cd 豆鲍
|
||||
powershell -ExecutionPolicy Bypass -File scripts\emulator-up.ps1 # 拉起 doubao14(emulator-5558)
|
||||
```
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
坑和完整操作(装 APK、截图、点按、抓内核日志、连设备内核 API)都在
|
||||
[`豆鲍/docs/安卓模拟器-操作手册.md`](豆鲍/docs/安卓模拟器-操作手册.md)。
|
||||
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」),
|
||||
事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走
|
||||
`applyMeetingEvent`。
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
详细约定见 [`豆鲍/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,371 +0,0 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.net.Uri
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 暴露给 Python 内核的原生能力。
|
||||
*
|
||||
* Chaquopy 允许 Python 直接调这个类的方法(`from java import jclass` 那套),
|
||||
* 所以内核里的 `device` 工具、剪贴板钩子、选文件钩子都落到这里。
|
||||
*
|
||||
* 线程约定:device() 可能阻塞几秒(采传感器、等定位),
|
||||
* 它只会在内核的 HTTP 工作线程上被调用,**不会**卡住 UI 线程。
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
JSONObject(payloadJson)
|
||||
} catch (e: Exception) {
|
||||
JSONObject()
|
||||
}
|
||||
val action = req.optString("action", "info")
|
||||
return try {
|
||||
when (action) {
|
||||
"info" -> deviceInfo()
|
||||
"battery" -> batteryInfo()
|
||||
"location" -> locationInfo()
|
||||
"sensors" -> sensorList()
|
||||
"sensor" -> sensorSample(req.optString("sensor"), req.optDouble("duration", 1.5))
|
||||
"clipboard_get" -> JSONObject().put("text", readClipboard())
|
||||
"clipboard_set" -> {
|
||||
setClipboard(req.optString("text"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// 内置 Termux:完整 Linux 用户态(真 bash / 真 pkg / 真子进程)
|
||||
"termux_available" -> JSONObject().put("installed", TermuxShell.isReady(activity))
|
||||
"termux_run" -> TermuxShell.run(
|
||||
activity,
|
||||
req.optString("command"),
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}.toString()
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
val totalGb = stat.totalBytes / 1024.0 / 1024.0 / 1024.0
|
||||
return JSONObject()
|
||||
.put("platform", "Android")
|
||||
.put("model", Build.MODEL)
|
||||
.put("manufacturer", Build.MANUFACTURER)
|
||||
.put("brand", Build.BRAND)
|
||||
.put("device", Build.DEVICE)
|
||||
.put("android", Build.VERSION.RELEASE)
|
||||
.put("sdk", Build.VERSION.SDK_INT)
|
||||
.put("abis", JSONArray(Build.SUPPORTED_ABIS.toList()))
|
||||
.put("storage_free_gb", String.format("%.1f", freeGb))
|
||||
.put("storage_total_gb", String.format("%.1f", totalGb))
|
||||
.put("screen", screenInfo())
|
||||
.put("battery", batteryInfo())
|
||||
}
|
||||
|
||||
private fun screenInfo(): String {
|
||||
val metrics = activity.resources.displayMetrics
|
||||
return "${metrics.widthPixels}x${metrics.heightPixels} @${metrics.density}x"
|
||||
}
|
||||
|
||||
private fun batteryInfo(): JSONObject {
|
||||
val bm = activity.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
|
||||
return JSONObject()
|
||||
.put("level_percent", bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1)
|
||||
.put("charging", bm?.isCharging ?: false)
|
||||
}
|
||||
|
||||
/** 定位:先拿最后已知位置,拿不到就等一次单次更新(最多 8 秒) */
|
||||
private fun locationInfo(): JSONObject {
|
||||
val lm = activity.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
?: return JSONObject().put("error", "没有 LocationManager")
|
||||
val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
|
||||
var best: Location? = null
|
||||
for (p in providers) {
|
||||
try {
|
||||
if (!lm.isProviderEnabled(p)) continue
|
||||
val loc = lm.getLastKnownLocation(p) ?: continue
|
||||
if (best == null || loc.time > best!!.time) best = loc
|
||||
} catch (t: SecurityException) {
|
||||
return JSONObject().put("error", "缺少定位权限(ACCESS_FINE_LOCATION)")
|
||||
} catch (_: Throwable) {
|
||||
// 某些机型会抛 IllegalArgumentException,忽略继续
|
||||
}
|
||||
}
|
||||
if (best == null) {
|
||||
val latch = CountDownLatch(1)
|
||||
var fresh: Location? = null
|
||||
val listener = object : android.location.LocationListener {
|
||||
override fun onLocationChanged(location: Location) {
|
||||
fresh = location
|
||||
latch.countDown()
|
||||
}
|
||||
// 老 API 要求实现,留着空实现
|
||||
override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
|
||||
override fun onProviderEnabled(provider: String) {}
|
||||
override fun onProviderDisabled(provider: String) {}
|
||||
}
|
||||
try {
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, listener)
|
||||
} catch (_: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(8, TimeUnit.SECONDS)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
} finally {
|
||||
try {
|
||||
lm.removeUpdates(listener)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
best = fresh
|
||||
}
|
||||
if (best == null) {
|
||||
return JSONObject()
|
||||
.put("available", false)
|
||||
.put("hint", "没拿到定位:确认已开定位开关、已授予权限、或在室内 GPS 信号差时稍后再试")
|
||||
}
|
||||
return JSONObject()
|
||||
.put("available", true)
|
||||
.put("latitude", best!!.latitude)
|
||||
.put("longitude", best!!.longitude)
|
||||
.put("accuracy_m", best!!.accuracy.toDouble())
|
||||
.put("provider", best!!.provider)
|
||||
.put("age_seconds", (System.currentTimeMillis() - best!!.time) / 1000.0)
|
||||
}
|
||||
|
||||
private val keywordToType = mapOf(
|
||||
"accelerometer" to Sensor.TYPE_ACCELEROMETER,
|
||||
"gyroscope" to Sensor.TYPE_GYROSCOPE,
|
||||
"magnetic" to Sensor.TYPE_MAGNETIC_FIELD,
|
||||
"light" to Sensor.TYPE_LIGHT,
|
||||
"pressure" to Sensor.TYPE_PRESSURE,
|
||||
"proximity" to Sensor.TYPE_PROXIMITY,
|
||||
"gravity" to Sensor.TYPE_GRAVITY,
|
||||
"linear_acceleration" to Sensor.TYPE_LINEAR_ACCELERATION,
|
||||
"rotation_vector" to Sensor.TYPE_ROTATION_VECTOR,
|
||||
"step_counter" to Sensor.TYPE_STEP_COUNTER,
|
||||
"humidity" to Sensor.TYPE_RELATIVE_HUMIDITY,
|
||||
"temperature" to Sensor.TYPE_AMBIENT_TEMPERATURE,
|
||||
"game_rotation_vector" to Sensor.TYPE_GAME_ROTATION_VECTOR,
|
||||
)
|
||||
|
||||
private fun sensorManager(): SensorManager? =
|
||||
activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
|
||||
|
||||
private fun sensorList(): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val arr = JSONArray()
|
||||
for (s in sm.getSensorList(Sensor.TYPE_ALL)) {
|
||||
val key = keywordToType.entries.firstOrNull { it.value == s.type }?.key
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("key", key ?: "type_${s.type}")
|
||||
.put("name", s.name)
|
||||
.put("vendor", s.vendor)
|
||||
.put("type", s.type)
|
||||
.put("power_ma", s.power.toDouble()),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("count", arr.length()).put("sensors", arr)
|
||||
}
|
||||
|
||||
/** 采样:注册监听 duration 秒,返回样本序列与统计 */
|
||||
private fun sensorSample(key: String, duration: Double): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val name = key.ifBlank { "accelerometer" }
|
||||
val type = keywordToType[name] ?: return JSONObject()
|
||||
.put("error", "不认识的传感器:$name(可用:${keywordToType.keys.joinToString(", ")})")
|
||||
val sensor = sm.getDefaultSensor(type)
|
||||
?: return JSONObject().put("error", "这台设备没有 $name 传感器")
|
||||
|
||||
val seconds = duration.coerceIn(0.2, 10.0)
|
||||
val samples = mutableListOf<FloatArray>()
|
||||
val latch = CountDownLatch(1)
|
||||
val listener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
if (samples.size < 500) samples.add(event.values.copyOf())
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
|
||||
}
|
||||
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME)
|
||||
try {
|
||||
// 用 latch 等不到就超时,靠 await 的返回值判断即可
|
||||
latch.await((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
|
||||
} finally {
|
||||
sm.unregisterListener(listener)
|
||||
}
|
||||
if (samples.isEmpty()) return JSONObject().put("error", "$name 在采样期内没出数据")
|
||||
|
||||
val dims = samples.first().size
|
||||
val stats = JSONArray()
|
||||
for (d in 0 until dims) {
|
||||
val values = samples.map { it[d].toDouble() }
|
||||
stats.put(
|
||||
JSONObject()
|
||||
.put("avg", values.average())
|
||||
.put("min", values.min())
|
||||
.put("max", values.max())
|
||||
.put("last", values.last()),
|
||||
)
|
||||
}
|
||||
val last = JSONArray()
|
||||
samples.last().forEach { last.put(it.toDouble()) }
|
||||
return JSONObject()
|
||||
.put("sensor", name)
|
||||
.put("unit", unitOf(name))
|
||||
.put("sample_count", samples.size)
|
||||
.put("seconds", seconds)
|
||||
.put("axes", axisNames(dims))
|
||||
.put("last", last)
|
||||
.put("stats", stats)
|
||||
}
|
||||
|
||||
private fun axisNames(dims: Int): JSONArray {
|
||||
val names = listOf("x", "y", "z", "w")
|
||||
val arr = JSONArray()
|
||||
for (i in 0 until dims) arr.put(names.getOrElse(i) { "v$i" })
|
||||
return arr
|
||||
}
|
||||
|
||||
private fun unitOf(name: String): String = when (name) {
|
||||
"accelerometer", "gravity", "linear_acceleration" -> "m/s^2"
|
||||
"gyroscope" -> "rad/s"
|
||||
"magnetic" -> "uT"
|
||||
"light" -> "lx"
|
||||
"pressure" -> "hPa"
|
||||
"proximity" -> "cm"
|
||||
"humidity" -> "%"
|
||||
"temperature" -> "°C"
|
||||
else -> ""
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 剪贴板 / 选文件
|
||||
|
||||
@Suppress("unused")
|
||||
fun setClipboard(text: String) {
|
||||
activity.runOnUiThread {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("doubao", text))
|
||||
}
|
||||
}
|
||||
|
||||
private fun readClipboard(): String {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = cm.primaryClip ?: return ""
|
||||
if (clip.itemCount == 0) return ""
|
||||
return clip.getItemAt(0).coerceToText(activity).toString()
|
||||
}
|
||||
|
||||
/** 内核请求"用户选个文件"时调用;把选中的文件复制到 App 私有目录再返回路径 */
|
||||
@Volatile
|
||||
private var pickLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var pickedUris: List<Uri> = emptyList()
|
||||
|
||||
@Suppress("unused")
|
||||
fun pickFile(): Array<String> {
|
||||
val latch = CountDownLatch(1)
|
||||
pickLatch = latch
|
||||
pickedUris = emptyList()
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = "*/*"
|
||||
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||
}
|
||||
activity.startActivityForResult(intent, REQ_PICK)
|
||||
} catch (t: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
|
||||
/** MainActivity 的 onActivityResult 转进来 */
|
||||
fun onPicked(data: Intent?) {
|
||||
val uris = mutableListOf<Uri>()
|
||||
data?.clipData?.let { clip ->
|
||||
for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri)
|
||||
}
|
||||
data?.data?.let { uris.add(it) }
|
||||
pickedUris = uris
|
||||
pickLatch?.countDown()
|
||||
}
|
||||
|
||||
private fun copyIntoCache(uri: Uri): String? = try {
|
||||
val name = displayName(uri) ?: "upload_${System.currentTimeMillis()}"
|
||||
val dir = File(activity.cacheDir, "picked").apply { mkdirs() }
|
||||
val dest = File(dir, name)
|
||||
activity.contentResolver.openInputStream(uri)?.use { input ->
|
||||
dest.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
dest.absolutePath
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun displayName(uri: Uri): String? = try {
|
||||
activity.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
/** 安卓上没有"打开文件夹",直接返回提示(设置页会显示不可用) */
|
||||
@Suppress("unused")
|
||||
fun reveal(path: String): String? = null
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
entry.callAttr("set_android_bridge", bridge)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.util.zip.ZipInputStream
|
||||
|
||||
/**
|
||||
* 把 Termux 的根文件系统(bootstrap)装进应用私有目录。
|
||||
*
|
||||
* 这套逻辑是从 Termux 自己的 `TermuxInstaller.java` 移植过来的(Apache-2.0),
|
||||
* 关键就三步:
|
||||
* 1. 从 `lib/<abi>/libtermux-bootstrap.so` 读 zip(它其实就是个改了名的 zip,
|
||||
* 放在 lib 目录是为了让系统在安装时原样解出来、不被压缩)
|
||||
* 2. 逐条解压到 files/usr,并给 bin/ lib/ 下的文件加可执行位
|
||||
* 3. 读 SYMLINKS.txt(格式 `目标←链接路径`),**用 /system/bin/sh 建符号链接**
|
||||
* —— Java 的 File API 建不了符号链接,只能借 shell
|
||||
*
|
||||
* 为什么必须 targetSdk=28:Android 10 起 targetSdk>=29 的应用不允许执行自己数据目录里的二进制,
|
||||
* 而 bash/python 全在这个目录里。Termux 自己也是锁 28 才活下来的。
|
||||
*/
|
||||
object TermuxInstaller {
|
||||
|
||||
private const val TAG = "DoubaoTermux"
|
||||
private const val BOOTSTRAP_LIB = "libtermux-bootstrap.so"
|
||||
private const val ARROW = "\u2190" // SYMLINKS.txt 里的分隔符
|
||||
|
||||
fun prefix(context: Context): File = File(context.filesDir, "usr")
|
||||
fun home(context: Context): File = File(context.filesDir, "home")
|
||||
fun bashPath(context: Context): String = File(prefix(context), "bin/bash").absolutePath
|
||||
|
||||
/** 装没装:看 bash 在不在(Termux 的 bootstrap 一定带 bash) */
|
||||
fun isInstalled(context: Context): Boolean =
|
||||
File(prefix(context), "bin/bash").exists() && File(prefix(context), "bin/login").exists()
|
||||
|
||||
/** 剩余没装的标记文件,避免半途失败后反复重来 */
|
||||
private fun stampFile(context: Context) = File(context.filesDir, ".termux-bootstrap-ok")
|
||||
|
||||
/**
|
||||
* 安装日志。
|
||||
*
|
||||
* 为什么要写文件而不是只打 Logcat:部分国产 ROM(实测 realme/ColorOS)会把应用自己打的
|
||||
* log 全过滤掉,出问题时 adb logcat 里一条都看不到,只能靠落盘来诊断。
|
||||
* 位置:files/termux-install.log,可以直接 `adb shell run-as <包名> cat files/termux-install.log`
|
||||
*/
|
||||
private fun logFile(context: Context) = File(context.filesDir, "termux-install.log")
|
||||
|
||||
fun trace(context: Context, message: String) { Log.i(TAG, message)
|
||||
try {
|
||||
logFile(context).appendText("${System.currentTimeMillis()} $message\n")
|
||||
} catch (_: Throwable) {
|
||||
// 落盘失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装(幂等)。要在后台线程调用。progress 会报告阶段,给界面显示。
|
||||
* @return true 表示装好(或本来就装好了)
|
||||
*/
|
||||
fun install(context: Context, progress: (String) -> Unit): Boolean {
|
||||
trace(context, "install() 开始;isInstalled=${isInstalled(context)} stamp=${stampFile(context).exists()}")
|
||||
if (stampFile(context).exists() && isInstalled(context)) {
|
||||
// 已经装过也别直接返回:rc 文件是 App 生成的,升级 App 后要跟着更新
|
||||
writeBashRc(context)
|
||||
progress("Termux 环境已就绪")
|
||||
return true
|
||||
}
|
||||
|
||||
val prefix = prefix(context)
|
||||
if (prefix.exists()) prefix.deleteRecursively()
|
||||
prefix.mkdirs()
|
||||
trace(context, "prefix 准备完成:$prefix")
|
||||
|
||||
return try {
|
||||
progress("正在解压运行环境(约 95 MB,首次会慢一点)…")
|
||||
trace(context, "开始解压 bootstrap")
|
||||
val count = extractBootstrap(context, prefix)
|
||||
trace(context, "解压结束,文件数=$count")
|
||||
if (count < 50) {
|
||||
progress("解压结果不对:只出来 $count 个文件")
|
||||
return false
|
||||
}
|
||||
|
||||
progress("正在建立符号链接…")
|
||||
createSymlinks(prefix)
|
||||
trace(context, "符号链接完成")
|
||||
|
||||
progress("正在准备目录…")
|
||||
File(prefix, "tmp").mkdirs()
|
||||
File(prefix, "var").mkdirs()
|
||||
home(context).mkdirs()
|
||||
writeBashRc(context)
|
||||
|
||||
progress("正在修正脚本的解释器路径…")
|
||||
val fixed = fixShebangs(context)
|
||||
trace(context, "改写了 $fixed 个脚本的 shebang")
|
||||
|
||||
val binCount = File(prefix, "bin").list()?.size ?: 0
|
||||
stampFile(context).writeText("ok")
|
||||
progress("Termux 环境安装完成($binCount 个命令)")
|
||||
trace(context, "安装完成:files=$count bin=$binCount")
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
trace(context, "安装失败:${t.javaClass.simpleName}: ${t.message}")
|
||||
progress("安装失败:${t.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压 bootstrap。
|
||||
*
|
||||
* ★ 这里有个坑:`libtermux-bootstrap.so` **不是纯 zip**,而是
|
||||
* 「1328 字节的 ELF 头 + 一个完整 zip」(Android 要求 lib 下的 so 得像 ELF,
|
||||
* Termux 就把 zip 接在 ELF 头后面)。
|
||||
* `ZipInputStream` 是按本地文件头顺序扫的,在安卓上实测一个条目都读不出来;
|
||||
* 而 `ZipFile` 走的是文件尾的中央目录,能直接跳过前面的 ELF 头 —— 所以先落盘再用 ZipFile。
|
||||
*
|
||||
* 注意注释里千万别写 "lib" 加斜杠星号那种通配(Kotlin 块注释会嵌套,会把后面代码全注释掉)。
|
||||
*/
|
||||
private fun extractBootstrap(context: Context, targetDir: File): Int {
|
||||
val cacheZip = File(context.cacheDir, "termux-bootstrap.zip")
|
||||
try {
|
||||
// ① 从 APK 里把那份 .so 原样拷出来
|
||||
val apk = File(context.applicationInfo.sourceDir)
|
||||
val abi = android.os.Build.SUPPORTED_ABIS.firstOrNull() ?: "arm64-v8a"
|
||||
val candidates = listOf(abi, "arm64-v8a", "x86_64")
|
||||
var copied = false
|
||||
java.util.zip.ZipFile(apk).use { apkZip ->
|
||||
for (candidate in candidates) {
|
||||
val entry = apkZip.getEntry("lib/$candidate/$BOOTSTRAP_LIB") ?: continue
|
||||
Log.i(TAG, "bootstrap 来自 APK: lib/$candidate/$BOOTSTRAP_LIB (${entry.size} 字节)")
|
||||
apkZip.getInputStream(entry).use { input ->
|
||||
cacheZip.outputStream().use { out -> input.copyTo(out, 256 * 1024) }
|
||||
}
|
||||
copied = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!copied) {
|
||||
// 退路:有些打包方式会把 .so 解到 nativeLibraryDir
|
||||
val fromLib = File(context.applicationInfo.nativeLibraryDir, BOOTSTRAP_LIB)
|
||||
if (!fromLib.exists()) throw IllegalStateException("APK 里找不到 $BOOTSTRAP_LIB")
|
||||
fromLib.copyTo(cacheZip, overwrite = true)
|
||||
Log.i(TAG, "bootstrap 来自 nativeLibraryDir")
|
||||
}
|
||||
|
||||
// ② 把 ELF 头切掉,得到纯 zip
|
||||
//
|
||||
// ★ 为什么必须切:安卓的 ZipFile **不会**像桌面 JVM 那样自动跳过前缀,
|
||||
// 它按中央目录里记的偏移去读,读到文件开头是 ELF 就报
|
||||
// "Entry at offset zero has invalid LFH signature 464c457f"
|
||||
// (464c457f 就是 \x7FELF 的小端十六进制)。
|
||||
// 模拟器上碰巧宽松能过,真机 Android 16 直接失败 —— 所以自己切最稳。
|
||||
val pureZip = File(context.cacheDir, "termux-bootstrap-pure.zip")
|
||||
val zipOffset = stripPrefix(cacheZip, pureZip)
|
||||
trace(context, "ELF 前缀 ${zipOffset} 字节,已切掉")
|
||||
|
||||
// ③ 用 ZipFile 读纯 zip
|
||||
var count = 0
|
||||
var skipped = 0
|
||||
java.util.zip.ZipFile(pureZip).use { zip ->
|
||||
val entries = zip.entries()
|
||||
while (entries.hasMoreElements()) {
|
||||
val entry = entries.nextElement()
|
||||
val name = entry.name
|
||||
if (name.startsWith("..") || name.contains("../")) continue
|
||||
val outFile = File(targetDir, name)
|
||||
if (entry.isDirectory) {
|
||||
outFile.mkdirs()
|
||||
continue
|
||||
}
|
||||
val parent = outFile.parentFile
|
||||
if (parent != null && !parent.exists()) parent.mkdirs()
|
||||
|
||||
// ★ 单个文件失败不能把整次安装毁掉:安卓上有个别人为拦的怪名字
|
||||
// (比如 bin/su 会 ENOENT),跳过去照样能用。
|
||||
try {
|
||||
zip.getInputStream(entry).use { input ->
|
||||
FileOutputStream(outFile).use { out -> input.copyTo(out, 256 * 1024) }
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
skipped += 1
|
||||
if (skipped <= 5) {
|
||||
Log.w(
|
||||
TAG,
|
||||
"跳过 $name(${t.javaClass.simpleName}: ${t.message})" +
|
||||
" parent=${parent?.absolutePath} exists=${parent?.exists()}" +
|
||||
" isDir=${parent?.isDirectory}",
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// bin/ lib/ libexec/ 和根目录下的东西要可执行
|
||||
val rel = name.replace('\\', '/')
|
||||
if (rel.startsWith("bin/") || rel.startsWith("lib/") ||
|
||||
rel.startsWith("libexec/") || !rel.contains('/')
|
||||
) {
|
||||
outFile.setExecutable(true, false)
|
||||
}
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "解压完成,$count 个文件(跳过 $skipped 个)")
|
||||
pureZip.delete()
|
||||
return count
|
||||
} finally {
|
||||
cacheZip.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `ELF 头 + zip` 切成纯 zip,返回被切掉的前缀长度。
|
||||
* ZIP 的第一个本地文件头签名是 `PK\x03\x04`;ELF 头只有一千多字节,扫前 64KB 足够。
|
||||
*/
|
||||
private fun stripPrefix(src: File, dst: File): Long {
|
||||
FileInputStream(src).use { input ->
|
||||
val head = ByteArray(64 * 1024)
|
||||
val n = input.read(head)
|
||||
if (n <= 4) throw IllegalStateException("bootstrap 文件太小($n 字节)")
|
||||
|
||||
var offset = -1
|
||||
for (i in 0 until n - 3) {
|
||||
if (head[i] == 0x50.toByte() && head[i + 1] == 0x4b.toByte() &&
|
||||
head[i + 2] == 0x03.toByte() && head[i + 3] == 0x04.toByte()
|
||||
) {
|
||||
offset = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if (offset < 0) throw IllegalStateException("在文件头 64KB 里找不到 ZIP 签名(PK\\x03\\x04)")
|
||||
|
||||
FileOutputStream(dst).use { out ->
|
||||
out.write(head, offset, n - offset)
|
||||
input.copyTo(out, 256 * 1024)
|
||||
}
|
||||
return offset.toLong()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建符号链接。Java 建不了 symlink,只能把上千条 ln -s 拼成脚本交给 /system/bin/sh 执行。
|
||||
* SYMLINKS.txt 里的相对路径是相对 prefix 的,所以 cwd 必须设成 prefix。
|
||||
*/
|
||||
private fun createSymlinks(prefix: File) {
|
||||
val symlinksFile = File(prefix, "SYMLINKS.txt")
|
||||
if (!symlinksFile.exists()) {
|
||||
Log.w(TAG, "没有 SYMLINKS.txt,跳过")
|
||||
return
|
||||
}
|
||||
|
||||
val commands = symlinksFile.readLines()
|
||||
.filter { it.contains(ARROW) }
|
||||
.map { line ->
|
||||
val idx = line.indexOf(ARROW)
|
||||
val target = line.substring(0, idx)
|
||||
val link = line.substring(idx + ARROW.length)
|
||||
"ln -sf '$target' '$link'"
|
||||
}
|
||||
symlinksFile.delete()
|
||||
|
||||
if (commands.isEmpty()) return
|
||||
|
||||
// 一次别塞太多,命令行有长度上限
|
||||
commands.chunked(200).forEach { chunk ->
|
||||
val script = chunk.joinToString(" ; ")
|
||||
val proc = ProcessBuilder("/system/bin/sh", "-c", script)
|
||||
.directory(prefix)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val output = proc.inputStream.bufferedReader().readText()
|
||||
val code = proc.waitFor()
|
||||
if (code != 0) {
|
||||
Log.w(TAG, "建链接返回 $code:${output.take(400)}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写一份我们自己的 bash rc。
|
||||
*
|
||||
* 为什么需要:Termux 的 bash 是带着编译期路径 `/data/data/com.termux/files/usr/etc/profile`
|
||||
* 构建的,而我们的 prefix 是 `/data/user/0/<我们的包名>/files/usr`。
|
||||
* termux-exec 只重写 **exec 的路径**,管不到 bash 自己 open("/etc/profile"),
|
||||
* 所以登录式 bash 一启动就会报 "Permission denied"。
|
||||
*
|
||||
* ★ 这里**故意不去 source Termux 自带的 etc/profile**:
|
||||
* 真机实测 source 之后 bash 会立刻退出,终端上只留一句 "[Process completed]"
|
||||
* (那份 profile 里有一堆 dpkg/init 的假设,在别人的 prefix 下不成立)。
|
||||
* 交互式终端真正需要的变量这里手工设全就够了。
|
||||
*/
|
||||
private fun writeBashRc(context: Context) {
|
||||
val prefix = prefix(context).absolutePath
|
||||
val home = home(context).absolutePath
|
||||
val rc = File(prefix, "etc/doubao.bashrc")
|
||||
rc.parentFile?.mkdirs()
|
||||
rc.writeText(
|
||||
"""
|
||||
# 由豆包 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||
export PREFIX="$prefix"
|
||||
export HOME="$home"
|
||||
export TMPDIR="$prefix/tmp"
|
||||
export PATH="$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin"
|
||||
export LD_LIBRARY_PATH="$prefix/lib"
|
||||
export LD_PRELOAD="$prefix/lib/libtermux-exec.so"
|
||||
export TERM=xterm-256color
|
||||
export LANG=en_US.UTF-8
|
||||
export COLORTERM=truecolor
|
||||
cd "${'$'}HOME" 2>/dev/null || cd /
|
||||
export PS1='\[\e[32m\]\u@termux\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '
|
||||
echo "豆包内置 Termux —— 试试 pkg install python"
|
||||
""".trimIndent() + "\n",
|
||||
Charsets.UTF_8,
|
||||
)
|
||||
trace(context, "已写入 bash rc: ${rc.absolutePath}")
|
||||
}
|
||||
|
||||
/**
|
||||
* 把脚本里 shebang 的硬编码前缀改成我们自己的。
|
||||
*
|
||||
* 为什么必须做:Termux 的 bin 下不少命令(getprop、pkg 之类)是 shell 脚本,
|
||||
* 第一行写死了 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
* 那个路径属于**另一个包**,我们 exec 它会 EACCES ——
|
||||
* 表现是 "bad interpreter: Permission denied"。
|
||||
* termux-exec 只重写 execve 的参数,管不到内核解析 shebang 这一步,所以直接改文件最省事。
|
||||
*/
|
||||
private fun fixShebangs(context: Context): Int {
|
||||
val prefix = prefix(context)
|
||||
val oldPrefix = "/data/data/com.termux/files/usr"
|
||||
val newPrefix = prefix.absolutePath
|
||||
var fixed = 0
|
||||
|
||||
val dirs = listOf(File(prefix, "bin"), File(prefix, "libexec"), File(prefix, "libexec/termux-am"))
|
||||
for (dir in dirs) {
|
||||
val files = dir.listFiles() ?: continue
|
||||
for (file in files) {
|
||||
if (!file.isFile || file.length() > 512 * 1024) continue
|
||||
val head = try {
|
||||
file.inputStream().use { input ->
|
||||
val buf = ByteArray(256)
|
||||
val n = input.read(buf)
|
||||
if (n <= 0) return@use "" else String(buf, 0, n, Charsets.UTF_8)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
continue
|
||||
}
|
||||
if (!head.startsWith("#!$oldPrefix")) continue
|
||||
|
||||
try {
|
||||
val text = file.readText(Charsets.UTF_8)
|
||||
file.writeText(text.replaceFirst(oldPrefix, newPrefix), Charsets.UTF_8)
|
||||
file.setExecutable(true, false)
|
||||
fixed += 1
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "改 shebang 失败:${file.name}", t)
|
||||
}
|
||||
}
|
||||
}
|
||||
return fixed
|
||||
}
|
||||
|
||||
/** 交互式终端应该跑的 shell(配我们自己的 rc) */
|
||||
fun interactiveShellArgs(context: Context): Array<String> =
|
||||
arrayOf("--rcfile", File(prefix(context), "etc/doubao.bashrc").absolutePath, "-i")
|
||||
|
||||
/** 装完之后给内核/工具用的环境变量(Termux 的标准一套) */
|
||||
fun environment(context: Context): Map<String, String> {
|
||||
val prefix = prefix(context).absolutePath
|
||||
val home = home(context).absolutePath
|
||||
val filesDir = context.filesDir.absolutePath
|
||||
val legacy = "/data/data/${context.packageName}/files"
|
||||
return mapOf(
|
||||
"PREFIX" to prefix,
|
||||
"HOME" to home,
|
||||
"TMPDIR" to "$prefix/tmp",
|
||||
"PATH" to "$prefix/bin:$prefix/bin/applets:/system/bin:/system/xbin",
|
||||
"LD_LIBRARY_PATH" to "$prefix/lib",
|
||||
// ★ 这个 LD_PRELOAD 是 Termux 能在 Android 上正常跑命令的关键:
|
||||
// 它把二进制里写死的 /data/data/com.termux/files/usr 重写到我们自己的 prefix。
|
||||
// 不开的话 bash 会去找别的 App 的 profile,报 Permission denied。
|
||||
"LD_PRELOAD" to "$prefix/lib/libtermux-exec.so",
|
||||
/**
|
||||
* ★ 下面这两个是 termux-exec 用来确定"真实 prefix"的变量(从它的 .so 里扫出来的符号名):
|
||||
* TERMUX__PREFIX —— 注意是**双下划线**,写成 TERMUX_PREFIX 它不认
|
||||
* TERMUX_APP__DATA_DIR —— 应用数据目录
|
||||
* 少一个路径重写就不生效,表现是 bash 去读 /data/data/com.termux/... 然后权限拒绝。
|
||||
*/
|
||||
"TERMUX__PREFIX" to prefix,
|
||||
"TERMUX__ROOTFS" to "/",
|
||||
"TERMUX_APP__DATA_DIR" to filesDir,
|
||||
"TERMUX_APP__LEGACY_DATA_DIR" to legacy,
|
||||
"TERMUX_APP__PACKAGE_NAME" to context.packageName,
|
||||
"TERMUX_APP__APP_VERSION_NAME" to "0.3.0",
|
||||
"TERMUX_IS_DEBUGGABLE_BUILD" to "1",
|
||||
"LANG" to "en_US.UTF-8",
|
||||
"LC_ALL" to "en_US.UTF-8",
|
||||
"TERM" to "xterm-256color",
|
||||
"TZ" to "Asia/Shanghai",
|
||||
"ANDROID_ROOT" to "/system",
|
||||
"ANDROID_DATA" to "/data",
|
||||
"EXTERNAL_STORAGE" to "/sdcard",
|
||||
"TERMUX_VERSION" to "0.118.3",
|
||||
"TERMUX_MAIN_PACKAGE_FORMAT" to "debian",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
|
||||
/**
|
||||
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||
*
|
||||
* 为什么不用 `Runtime.exec` 拼一个假终端:那样跑不了 vim/top、没有颜色、没有方向键,
|
||||
* 也不是 tty,很多命令行为会不一样。Termux 这套是完整 pty + ANSI 渲染。
|
||||
*/
|
||||
class TermuxTerminal(private val context: Context) {
|
||||
|
||||
@Volatile
|
||||
var session: TerminalSession? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* 开一个登录 shell。Termux 的标准做法就是跑 `$PREFIX/bin/login`,
|
||||
* 它会按 /etc/profile 把 PATH、PS1、动态库路径都准备好。
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val env = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
|
||||
val client = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(context, "终端会话结束,退出码=${finishedSession.exitStatus}")
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线,用 Termux 的默认值 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
val created = TerminalSession(
|
||||
"$prefix/bin/bash",
|
||||
home,
|
||||
// 用我们自己的 rc:Termux 的 bash 带的是编译期路径 /data/data/com.termux/...,
|
||||
// 直接当登录 shell 跑会去读别的包的 profile,报权限拒绝
|
||||
TermuxInstaller.interactiveShellArgs(context),
|
||||
env,
|
||||
2000,
|
||||
client,
|
||||
)
|
||||
session = created
|
||||
return created
|
||||
}
|
||||
|
||||
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||
fun viewClient(): TerminalViewClient = object : TerminalViewClient {
|
||||
override fun onScale(scale: Float): Float = scale
|
||||
override fun onSingleTapUp(e: MotionEvent) {
|
||||
// 点一下就把软键盘叫出来,手机上最常用
|
||||
(e.source)
|
||||
}
|
||||
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = false
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = true
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) {}
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = false
|
||||
override fun readAltKey(): Boolean = false
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {}
|
||||
// TerminalViewClient 也继承了 Logger,这 7 个必须实现
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
try {
|
||||
session?.finishIfRunning()
|
||||
} catch (t: Throwable) {
|
||||
Log.w("DoubaoTermux", "关闭会话失败", t)
|
||||
}
|
||||
session = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 给 Compose 的 AndroidView 用:把 view 绑上会话 */
|
||||
fun bindSession(view: TerminalView, terminal: TermuxTerminal, onTitle: (String) -> Unit, onExit: () -> Unit) {
|
||||
val s = terminal.session ?: terminal.createSession(onTitle, onExit)
|
||||
if (view.currentSession !== s) {
|
||||
view.attachSession(s)
|
||||
}
|
||||
view.requestFocus()
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
import com.doubao.lynxclone.data.KernelClient
|
||||
|
||||
/** 建 ViewModel 并把 client 注入进去(没上 DI 框架,手写个工厂就够) */
|
||||
@Composable
|
||||
fun rememberAppViewModel(client: KernelClient): AppViewModel =
|
||||
viewModel(factory = object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T = AppViewModel(client) as T
|
||||
})
|
||||
|
||||
@Composable
|
||||
fun AppRoot(
|
||||
client: KernelClient,
|
||||
termuxReady: Boolean,
|
||||
termuxStatus: String,
|
||||
onInstallTermux: () -> Unit,
|
||||
) {
|
||||
val vm = rememberAppViewModel(client)
|
||||
LaunchedEffect(Unit) { vm.refresh() }
|
||||
|
||||
// 提示条 2.5 秒后自动消失
|
||||
LaunchedEffect(vm.hint) {
|
||||
if (vm.hint.isNotBlank()) {
|
||||
kotlinx.coroutines.delay(2500)
|
||||
vm.hint = ""
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg())
|
||||
// edge-to-edge 下得自己吃系统栏/输入法内边距
|
||||
.windowInsetsPadding(WindowInsets.safeDrawing),
|
||||
) {
|
||||
// 页面切换带淡入 + 轻微位移,不然是"啪"一下就换了
|
||||
AnimatedContent(
|
||||
targetState = vm.screen,
|
||||
transitionSpec = {
|
||||
val forward = targetState != Screen.Chat
|
||||
val dir = if (forward) 1 else -1
|
||||
(slideInHorizontally(tween(240)) { it / 14 * dir } + fadeIn(tween(200))) togetherWith
|
||||
(slideOutHorizontally(tween(200)) { -it / 14 * dir } + fadeOut(tween(150)))
|
||||
},
|
||||
label = "screen",
|
||||
) { screen ->
|
||||
when (screen) {
|
||||
Screen.Chat -> ChatScreen(vm)
|
||||
Screen.Profile -> ProfileScreen(vm)
|
||||
Screen.Settings -> SettingsScreen(vm)
|
||||
Screen.Skills -> SkillsScreen(vm)
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
Screen.Meetings -> MeetingsScreen(vm)
|
||||
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||
}
|
||||
}
|
||||
|
||||
// 抽屉:左边滑进来 + 遮罩淡入
|
||||
AnimatedVisibility(
|
||||
visible = vm.drawerOpen,
|
||||
enter = slideInHorizontally(tween(260)) { -it } + fadeIn(tween(180)),
|
||||
exit = slideOutHorizontally(tween(220)) { -it } + fadeOut(tween(150)),
|
||||
) {
|
||||
DrawerOverlay(vm)
|
||||
}
|
||||
|
||||
if (vm.hint.isNotBlank()) {
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(24.dp)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(Color(0xE61F2329))
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 抽屉 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DrawerOverlay(vm: AppViewModel) {
|
||||
Row(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxHeight()
|
||||
.width(300.dp)
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 20.dp, end = 16.dp, top = 18.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("豆包", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Icon(
|
||||
Icons.Filled.Search, "搜索", tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable { vm.showHint("搜索还没做") },
|
||||
)
|
||||
}
|
||||
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.AccountTree, "会议模式") {
|
||||
vm.screen = Screen.Meetings; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Terminal, "终端") {
|
||||
vm.screen = Screen.Terminal; vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Settings, "设置") {
|
||||
vm.screen = Screen.Settings; vm.drawerOpen = false
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("置顶", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
ConversationRow(vm, vm.state.conversations[i])
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.screen = Screen.Profile; vm.drawerOpen = false }
|
||||
.padding(horizontal = 20.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).background(Doubao.Blue),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(vm.settings.nickname.take(1), color = Color.White, fontSize = 14.sp)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(vm.settings.nickname, fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.background(Doubao.Scrim)
|
||||
.clickable { vm.drawerOpen = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerItem(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
trailing: String = "",
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val bg by animateColorAsState(
|
||||
targetValue = if (pressed) doubaoCard() else Color.Transparent,
|
||||
animationSpec = tween(120),
|
||||
label = "itemBg",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(14.dp))
|
||||
Text(label, fontSize = 16.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (trailing.isNotBlank()) {
|
||||
Text(trailing, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConversationRow(vm: AppViewModel, conv: Conversation) {
|
||||
val active = conv.id == vm.activeConversationId
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (active) doubaoCard() else Color.Transparent)
|
||||
.clickable { vm.openConversation(conv.id) }
|
||||
.padding(horizontal = 10.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(RoundedCornerShape(19.dp)).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(conv.title.take(1), color = Doubao.Blue, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(conv.title, fontSize = 15.sp, color = doubaoText(), maxLines = 1)
|
||||
Text(
|
||||
conv.preview.ifBlank { "还没有消息" },
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp).clickable { vm.deleteConversation(conv) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 文案小工具 ------------------------------ */
|
||||
|
||||
fun shortModel(model: String): String = when {
|
||||
model.isBlank() -> "未设置"
|
||||
model.startsWith("ep-") -> "接入点 ${model.take(8)}"
|
||||
model.startsWith("doubao-seed-2-1-pro") -> "豆包 Pro"
|
||||
model.startsWith("doubao-seed-1-8") -> "豆包 1.8"
|
||||
model.startsWith("doubao-seed-1-6") -> "豆包 1.6"
|
||||
model.startsWith("doubao") -> "豆包"
|
||||
model.startsWith("deepseek-r1") -> "DeepSeek R1"
|
||||
model.startsWith("deepseek") -> "DeepSeek"
|
||||
model.startsWith("gpt-5") -> if (model.contains("mini")) "GPT-5 mini" else "GPT-5"
|
||||
model.startsWith("gpt-4o") -> if (model.contains("mini")) "GPT-4o mini" else "GPT-4o"
|
||||
else -> if (model.length > 16) model.take(14) + "…" else model
|
||||
}
|
||||
|
||||
fun thinkingLabel(level: String): String = when (level) {
|
||||
"off" -> "快速"
|
||||
"low" -> "低"
|
||||
"medium" -> "中"
|
||||
"high" -> "深度思考"
|
||||
else -> "自动"
|
||||
}
|
||||
@@ -1,508 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.AppState
|
||||
import com.doubao.lynxclone.data.Attachment
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
import com.doubao.lynxclone.data.KernelClient
|
||||
import com.doubao.lynxclone.data.MeetingEvent
|
||||
import com.doubao.lynxclone.data.MeetingMeta
|
||||
import com.doubao.lynxclone.data.StreamEvent
|
||||
import com.doubao.lynxclone.data.ToolTrace
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */
|
||||
enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal, Meetings }
|
||||
|
||||
/**
|
||||
* 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。
|
||||
*/
|
||||
class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
var state by mutableStateOf(AppState())
|
||||
private set
|
||||
var screen by mutableStateOf(Screen.Chat)
|
||||
var drawerOpen by mutableStateOf(false)
|
||||
var loading by mutableStateOf(true)
|
||||
var bootError by mutableStateOf("")
|
||||
var hint by mutableStateOf("")
|
||||
|
||||
val messages = mutableStateListOf<ChatMessage>()
|
||||
var activeConversationId by mutableStateOf("c_main")
|
||||
var streaming by mutableStateOf(false)
|
||||
private set
|
||||
var draft by mutableStateOf("")
|
||||
val attachments = mutableStateListOf<Attachment>()
|
||||
/** 正在看「思考过程」的消息下标;-1 表示没开 */
|
||||
var thinkingIndex by mutableStateOf(-1)
|
||||
/** 模型 / 思考强度面板(底部升起) */
|
||||
var modelPickerOpen by mutableStateOf(false)
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
val settings get() = state.settings
|
||||
val agents: List<Agent> get() = state.agents
|
||||
val activeAgent: Agent? get() = state.activeAgent
|
||||
|
||||
fun refresh(onDone: (() -> Unit)? = null) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
state = withContext(Dispatchers.IO) { client.state() }
|
||||
bootError = ""
|
||||
} catch (e: Exception) {
|
||||
bootError = e.message ?: "连不上内核"
|
||||
} finally {
|
||||
loading = false
|
||||
onDone?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun showHint(text: String) {
|
||||
hint = text
|
||||
}
|
||||
|
||||
/** 点赞/点踩:只改本地状态(没接后端反馈接口),点同一个再点一次就取消 */
|
||||
fun onFeedback(index: Int, kind: String) {
|
||||
if (index !in messages.indices) return
|
||||
val current = messages[index]
|
||||
messages[index] = current.copy(feedback = if (current.feedback == kind) null else kind)
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动朗读开关。
|
||||
*
|
||||
* 声音那边由 SpeechController 立即生效;这里负责**落盘**,
|
||||
* 否则退出 App 再进来又变回关的,用户会以为没保存上。
|
||||
*/
|
||||
fun setAutoRead(on: Boolean) {
|
||||
saveSettings(mapOf("speech" to mapOf("autoRead" to on)))
|
||||
}
|
||||
|
||||
/* ------------------------------ 会话 ------------------------------ */
|
||||
|
||||
fun openConversation(id: String) {
|
||||
activeConversationId = id
|
||||
drawerOpen = false
|
||||
screen = Screen.Chat
|
||||
viewModelScope.launch {
|
||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||
messages.clear()
|
||||
messages.addAll(list)
|
||||
}
|
||||
}
|
||||
|
||||
fun newTopic() {
|
||||
viewModelScope.launch {
|
||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||
refresh()
|
||||
if (conv != null) openConversation(conv.id) else {
|
||||
messages.clear()
|
||||
activeConversationId = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteConversation(conv: Conversation) {
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.deleteConversation(conv.id) } }
|
||||
refresh()
|
||||
showHint("已删除「${conv.title}」")
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 发消息 ------------------------------ */
|
||||
|
||||
fun send() {
|
||||
val text = draft.trim()
|
||||
if (text.isEmpty() && attachments.isEmpty()) return
|
||||
if (streaming) return
|
||||
|
||||
val files = attachments.toList()
|
||||
draft = ""
|
||||
attachments.clear()
|
||||
runChat(text, files)
|
||||
}
|
||||
|
||||
fun regenerate() {
|
||||
if (streaming) return
|
||||
val lastUser = messages.lastOrNull { it.role == "user" } ?: return
|
||||
// 去掉最后一条助手回复再重来
|
||||
while (messages.isNotEmpty() && messages.last().role != "user") messages.removeAt(messages.size - 1)
|
||||
runChat(lastUser.content, emptyList())
|
||||
}
|
||||
|
||||
private fun runChat(text: String, files: List<Attachment>) {
|
||||
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||
streaming = true
|
||||
|
||||
val cancel = AtomicBoolean(false)
|
||||
chatJob = cancel
|
||||
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
client.chat(
|
||||
conversationId = activeConversationId.ifBlank { "c_main" },
|
||||
message = text,
|
||||
attachments = files,
|
||||
agentId = activeAgent?.id,
|
||||
cancelled = cancel,
|
||||
) { event -> onStreamEvent(event) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
|
||||
showHint("出错了:${e.message}")
|
||||
} finally {
|
||||
streaming = false
|
||||
chatJob = null
|
||||
patchLast { it.copy(pending = false) }
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
|
||||
private fun onStreamEvent(event: StreamEvent) {
|
||||
viewModelScope.launch {
|
||||
when (event) {
|
||||
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
|
||||
is StreamEvent.Reasoning -> patchLast { it.copy(reasoning = it.reasoning + event.text) }
|
||||
is StreamEvent.ToolCall -> patchLast {
|
||||
it.copy(toolTrace = it.toolTrace + ToolTrace(id = event.id, name = event.name))
|
||||
}
|
||||
is StreamEvent.ToolResult -> patchLast { msg ->
|
||||
msg.copy(toolTrace = msg.toolTrace.map {
|
||||
if (it.id == event.id) it.copy(ok = event.ok, result = event.result) else it
|
||||
})
|
||||
}
|
||||
is StreamEvent.Failure -> {
|
||||
val text = if (event.hint.isNotBlank()) "出错了:${event.message}|${event.hint}" else "出错了:${event.message}"
|
||||
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { text }) }
|
||||
showHint(text)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun patchLast(fn: (ChatMessage) -> ChatMessage) {
|
||||
for (i in messages.indices.reversed()) {
|
||||
if (messages[i].role == "assistant") {
|
||||
messages[i] = fn(messages[i])
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 设置 / 工具 ------------------------------ */
|
||||
|
||||
fun saveSettings(patch: Map<String, Any?>, onDone: (() -> Unit)? = null) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val json = patchToJson(patch)
|
||||
state = withContext(Dispatchers.IO) { client.saveSettings(json) }
|
||||
showHint("已保存")
|
||||
} catch (e: Exception) {
|
||||
showHint("保存失败:${e.message}")
|
||||
} finally {
|
||||
onDone?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setThinkingLevel(level: String) = saveSettings(mapOf("thinkingLevel" to level))
|
||||
fun setModel(model: String) = saveSettings(mapOf("model" to model))
|
||||
fun runTool(name: String, args: JSONObject, onResult: (Boolean, String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val res = withContext(Dispatchers.IO) { client.runTool(name, args) }
|
||||
onResult(res.ok, if (res.ok) res.result.toString() else res.error)
|
||||
} catch (e: Exception) {
|
||||
onResult(false, e.message ?: "执行失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveMcpConfig(text: String, onResult: (Boolean, String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val json = withContext(Dispatchers.IO) { client.saveMcpConfig(text) }
|
||||
refresh()
|
||||
val results = json.optJSONArray("results")
|
||||
val summary = if (results != null) {
|
||||
(0 until results.length()).joinToString(",") { i ->
|
||||
val item = results.optJSONObject(i) ?: return@joinToString ""
|
||||
val ok = item.optBoolean("ok")
|
||||
"${item.optString("name")}${if (ok) "✓" else "✗" + item.optString("error")}"
|
||||
}
|
||||
} else ""
|
||||
onResult(json.optBoolean("ok"), if (json.optBoolean("ok")) "已重连:$summary" else json.optString("error"))
|
||||
} catch (e: Exception) {
|
||||
onResult(false, e.message ?: "保存失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 简化的协程入口。
|
||||
*
|
||||
* 页面里到处写 `viewModelScope.launch { try { … } catch (e) { showHint(…) } }`
|
||||
* 太啰嗦,而且很容易漏 catch(漏了就是静默失败,最难查)。
|
||||
* 统一走这里:出错一律弹提示。
|
||||
*/
|
||||
fun launch(block: suspend () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
block()
|
||||
} catch (e: Exception) {
|
||||
showHint(e.message ?: "操作失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 会议模式 ------------------------------ */
|
||||
|
||||
/** 编辑器要用的元信息(节点类型 / 判断条件 / 可用智能体)。进页面时拉一次。 */
|
||||
var meetingMeta by mutableStateOf(MeetingMeta())
|
||||
private set
|
||||
|
||||
private var meetingMetaLoaded = false
|
||||
|
||||
fun ensureMeetingMeta() {
|
||||
if (meetingMetaLoaded) return
|
||||
launch {
|
||||
meetingMeta = client.meetingMeta()
|
||||
meetingMetaLoaded = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新拉一次 meta。
|
||||
*
|
||||
* ★ 导入/删掉节点文件之后必须调它 —— 自定义节点是**运行期从磁盘读**的,
|
||||
* 不重拉的话界面上还是旧的那一套引脚,用户会以为导入没生效。
|
||||
* (ensureMeetingMeta 有 loaded 缓存,所以这里要单独一个不走缓存的入口。)
|
||||
*/
|
||||
fun reloadMeetingMeta() {
|
||||
launch {
|
||||
meetingMeta = client.meetingMeta()
|
||||
meetingMetaLoaded = true
|
||||
}
|
||||
}
|
||||
|
||||
/** 列出 nodes/ 里的自定义节点文件 */
|
||||
suspend fun nodeFiles(): org.json.JSONArray = client.nodeFiles()
|
||||
|
||||
/** 读一个自定义节点的源码 */
|
||||
suspend fun readNode(file: String): org.json.JSONObject = client.readNode(file)
|
||||
|
||||
/** 导入一个自定义节点文件;成功返回节点名,失败抛异常(错误信息给用户看) */
|
||||
suspend fun importNodeFile(file: String, code: String): String {
|
||||
val res = client.importNode(file, code)
|
||||
reloadMeetingMeta()
|
||||
return res.optString("label").ifBlank { file }
|
||||
}
|
||||
|
||||
/** 删掉一个自定义节点文件 */
|
||||
suspend fun deleteNodeFile(file: String) {
|
||||
client.deleteNode(file)
|
||||
reloadMeetingMeta()
|
||||
}
|
||||
|
||||
private var meetingJob: Job? = null
|
||||
|
||||
/**
|
||||
* 跑一场会议。事件边收边回调。
|
||||
*
|
||||
* 同时只能跑一场:再点一次运行会先掐掉上一场 —— 否则两个图同时往
|
||||
* 同一批节点上写输出,界面上会看到内容互相覆盖。
|
||||
*/
|
||||
fun runMeeting(
|
||||
meetingId: String,
|
||||
input: String,
|
||||
onEvent: (MeetingEvent) -> Unit,
|
||||
onError: (String) -> Unit,
|
||||
) {
|
||||
meetingJob?.cancel()
|
||||
val cancelled = AtomicBoolean(false)
|
||||
meetingJob = viewModelScope.launch {
|
||||
// ★ 事件在 IO 线程上产生,但**必须回主线程再交给界面**。
|
||||
//
|
||||
// 之前直接在 IO 线程里改 Compose 状态(mutableStateMapOf),
|
||||
// 结果是"日志里事件全收到了、节点上就是不显示"—— 状态写进去了,
|
||||
// 界面却不一定重组。用 Channel 过一道,既保证在主线程执行,
|
||||
// 又保证顺序(trySend 是有序的)。
|
||||
val events = Channel<MeetingEvent>(Channel.UNLIMITED)
|
||||
val consumer = launch {
|
||||
for (ev in events) onEvent(ev)
|
||||
}
|
||||
try {
|
||||
val seen = LinkedHashMap<String, Int>()
|
||||
client.runMeeting(meetingId, input, cancelled) { ev ->
|
||||
seen[ev.type] = (seen[ev.type] ?: 0) + 1
|
||||
events.trySend(ev)
|
||||
}
|
||||
android.util.Log.i(
|
||||
"DoubaoMeeting",
|
||||
"事件统计: " + seen.entries.joinToString(", ") { "${it.key}=${it.value}" },
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
events.close()
|
||||
consumer.cancel()
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
onError(e.message ?: "运行失败")
|
||||
} finally {
|
||||
events.close()
|
||||
}
|
||||
consumer.join()
|
||||
}
|
||||
}
|
||||
|
||||
fun stopMeeting() {
|
||||
meetingJob?.cancel()
|
||||
meetingJob = null
|
||||
}
|
||||
|
||||
fun saveAgent(id: String?, draft: Agent, onDone: () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val body = JSONObject()
|
||||
.put("name", draft.name)
|
||||
.put("avatar", draft.avatar)
|
||||
.put("systemPrompt", draft.systemPrompt)
|
||||
// 内核字段叫 tagline;UI 上叫"一句话介绍"
|
||||
.put("tagline", draft.greeting)
|
||||
// 智能体自己的模型与语音(留空 = 继承全局)
|
||||
.put("provider", draft.provider)
|
||||
.put("model", draft.model)
|
||||
.put("baseUrl", draft.baseUrl)
|
||||
.put("ttsEngine", draft.ttsEngine)
|
||||
.put("ttsVoice", draft.ttsVoice)
|
||||
// 0 = 跟随全局。语速合法范围是 0.5~2.0,0 不可能是有效值
|
||||
if (draft.ttsSpeed > 0) body.put("ttsSpeed", draft.ttsSpeed)
|
||||
withContext(Dispatchers.IO) {
|
||||
if (id.isNullOrBlank()) client.createAgent(body) else client.updateAgent(id, body)
|
||||
}
|
||||
refresh()
|
||||
onDone()
|
||||
} catch (e: Exception) {
|
||||
showHint("保存失败:${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAgent(id: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.deleteAgent(id) } }
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
fun useAgent(id: String) {
|
||||
saveSettings(mapOf("activeAgentId" to id))
|
||||
}
|
||||
|
||||
/* ------------------------------ 附件 ------------------------------ */
|
||||
|
||||
fun addAttachment(file: Attachment) {
|
||||
if (attachments.none { it.id == file.id }) attachments.add(file)
|
||||
}
|
||||
|
||||
fun removeAttachment(id: String) {
|
||||
attachments.removeAll { it.id == id }
|
||||
}
|
||||
|
||||
fun uploadAndAttach(name: String, mime: String, bytes: ByteArray) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val file = withContext(Dispatchers.IO) { client.uploadFile(name, mime, bytes, false) }
|
||||
// uploadFile 现在失败会抛异常并带上内核原话,所以走到这儿基本就是成功;
|
||||
// 留个兜底是因为万一内核换了个返回形状,也不能静默什么都不做
|
||||
if (file != null) {
|
||||
addAttachment(file)
|
||||
showHint("已添加 ${file.name}")
|
||||
} else {
|
||||
showHint("上传失败:内核没有返回文件信息")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
showHint("上传失败:${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 从内核拉待处理附件(比如 Termux 里刚生成的文件) */
|
||||
fun syncPendingUploads() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val json = withContext(Dispatchers.IO) { client.state() }
|
||||
state = json
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 工具权限:切模式 / 勾白名单 */
|
||||
fun saveSecurity(mode: String, allow: List<String>) {
|
||||
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
||||
saveSettings(mapOf("security" to json))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把补丁 Map 转成 JSONObject。
|
||||
*
|
||||
* ★ 为什么必须显式递归转换,不能直接 `json.put(k, mapOf(...))`:
|
||||
*
|
||||
* Android 的 org.json **不会**把 `Map` 自动当成 JSON 对象 —— `put(String, Object)`
|
||||
* 只是把 Map 原样塞进内部表,`toString()` 时按普通对象处理,
|
||||
* 于是发出去的是 `{"speech":"{autoRead=true}"}`:值是**字符串**而不是对象。
|
||||
*
|
||||
* 内核那边 `speech` 本来是个 dict,被字符串覆盖之后,之后**每一次**读配置
|
||||
* (`{**默认, **字符串}`)都会抛 TypeError,`/api/state` 从此一直返回
|
||||
* `{"error":"'str' object is not a mapping"}`;而 App 把这个错误 JSON 解析成了
|
||||
* 「全默认状态」且不抛异常 —— 表现就是:
|
||||
* **点一下语音按钮,模型变"未设置"、昵称变"我"、会话列表全空,还弹"已保存"。**
|
||||
*
|
||||
* 这个坑很隐蔽:只有"嵌套对象"才会触发,而在此之前 App 从没发过嵌套补丁。
|
||||
*/
|
||||
fun patchToJson(patch: Map<String, Any?>): JSONObject {
|
||||
val json = JSONObject()
|
||||
for ((key, value) in patch) {
|
||||
json.put(key, toJsonValue(value))
|
||||
}
|
||||
return json
|
||||
}
|
||||
|
||||
private fun toJsonValue(value: Any?): Any = when (value) {
|
||||
null -> JSONObject.NULL
|
||||
is JSONObject, is JSONArray -> value
|
||||
is Map<*, *> -> {
|
||||
val obj = JSONObject()
|
||||
for ((k, v) in value) obj.put(k.toString(), toJsonValue(v))
|
||||
obj
|
||||
}
|
||||
is List<*> -> {
|
||||
val arr = JSONArray()
|
||||
for (item in value) arr.put(toJsonValue(item))
|
||||
arr
|
||||
}
|
||||
else -> value
|
||||
}
|
||||
@@ -1,874 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.provider.OpenableColumns
|
||||
import android.util.Log
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.doubao.lynxclone.speech.SpeechController
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val TAG = "ChatScreen"
|
||||
|
||||
/**
|
||||
* 附件大小上限,和内核对齐:uploads.COPY_LIMIT 是 100MB,
|
||||
* 而 base64 会让体积涨 1/3,正好卡在内核 /api/upload 那条 150MB 的请求体上限内。
|
||||
* 客户端先挡一道,免得几百 MB 的流量白传一趟再被拒。
|
||||
*
|
||||
* ⚠ 内存:读进来是 100MB 的 ByteArray,再 base64 成 133MB 的字符串,
|
||||
* 峰值两百多 MB。低端机上大文件有被系统杀掉的风险 —— 真要传超大文件,
|
||||
* 正确做法是分片上传,不是继续抬这个数。
|
||||
*/
|
||||
private const val MAX_UPLOAD_BYTES = 100 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* 对话页。
|
||||
*
|
||||
* 视觉对着豆包真机截图抠的:纯白底、顶部三段式(左右图标 + 居中智能体名)、
|
||||
* 大头像 + 灰色问候气泡、白底描边快捷胶囊、输入框是大圆角描边胶囊、发送键是蓝色圆钮。
|
||||
* 动效:气泡淡入上移、思考面板从底部升起、typing 三点跳动、按钮按下回弹。
|
||||
*/
|
||||
@Composable
|
||||
private fun ScrollToBottomChip(
|
||||
visible: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn() + slideInVertically { it / 2 },
|
||||
exit = fadeOut() + slideOutVertically { it / 2 },
|
||||
modifier = modifier,
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
color = doubaoCard(),
|
||||
border = BorderStroke(1.dp, doubaoBorder()),
|
||||
shadowElevation = 3.dp,
|
||||
onClick = onClick,
|
||||
) {
|
||||
Row(
|
||||
Modifier.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown,
|
||||
"回到底部",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(3.dp))
|
||||
Text("回到底部", color = Doubao.Blue, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ChatScreen(vm: AppViewModel) {
|
||||
val agent = vm.activeAgent
|
||||
val listState = rememberLazyListState()
|
||||
val context = LocalContext.current
|
||||
|
||||
// ★ 必须声明在 picker 之前:picker 的回调要捕获它
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// ★ 用 OpenDocument 而不是 GetContent。
|
||||
//
|
||||
// GetContent 走的是 ACTION_GET_CONTENT —— **任何 App 都能注册这个 intent**。
|
||||
// 实测在真机上点「附件」直接打开了豆包 App 的拍照界面
|
||||
// (com.larus.nova/…CameraCaptureActivity),压根选不到文件,
|
||||
// 这就是"无法上传文件"的直接原因。
|
||||
//
|
||||
// OpenDocument 走 ACTION_OPEN_DOCUMENT,只有系统文档提供者(文件/相册)能响应,
|
||||
// 抢不走;顺带还拿到长期可读权限。
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri == null) return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
// 读文件放 IO 线程:手机上随手一张照片就几 MB,在主线程 readBytes
|
||||
// 轻则掉帧重则 ANR。回调本身是在主线程跑的。
|
||||
val picked = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val resolver = context.contentResolver
|
||||
// 文件名必须查 OpenableColumns:文档 URI 的 lastPathSegment 是
|
||||
// "image:1234" 这种内部 id,不是文件名,直接拿来当文件名会很难看
|
||||
val display = runCatching {
|
||||
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||
}.getOrNull()
|
||||
val name = display?.takeIf { it.isNotBlank() }
|
||||
?: uri.lastPathSegment?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
|
||||
?: "upload"
|
||||
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
Log.i(TAG, "选到文件 name=$name mime=$mime size=${bytes?.size ?: -1}")
|
||||
Triple(name, mime, bytes)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "读文件失败", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
if (picked == null) {
|
||||
vm.showHint("读取文件失败,换个文件试试")
|
||||
return@launch
|
||||
}
|
||||
val (name, mime, bytes) = picked
|
||||
// 以前 bytes 为 null 时是**静默什么都不做**的 —— 用户点了半天没反应也没提示。
|
||||
// 每种失败都得说清楚。
|
||||
when {
|
||||
bytes == null -> vm.showHint("打不开这个文件(可能已被移动或没有权限)")
|
||||
bytes.isEmpty() -> vm.showHint("「$name」是空文件")
|
||||
bytes.size > MAX_UPLOAD_BYTES ->
|
||||
vm.showHint("「$name」${bytes.size / 1024 / 1024}MB,超过了 ${MAX_UPLOAD_BYTES / 1024 / 1024}MB 上限")
|
||||
else -> vm.uploadAndAttach(name, mime, bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
// OpenDocument 要的是 MIME 数组,不是单个字符串
|
||||
val onPickFile: () -> Unit = { picker.launch(arrayOf("*/*")) }
|
||||
|
||||
// ---------------- 语音 ----------------
|
||||
val speech = remember { SpeechController(context, vm.client, scope) }
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { speech.release() }
|
||||
}
|
||||
// 设置里的开关同步到控制器
|
||||
LaunchedEffect(vm.state.speech.autoRead) { speech.autoRead = vm.state.speech.autoRead }
|
||||
// 控制器自己产生的提示(云端失败、没听清…)也走统一的提示条
|
||||
LaunchedEffect(speech.notice) {
|
||||
if (speech.notice.isNotBlank()) {
|
||||
vm.showHint(speech.notice)
|
||||
speech.notice = ""
|
||||
}
|
||||
}
|
||||
|
||||
// 录音权限:用户第一次点麦克风时才要,不在启动时要
|
||||
val micPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) speech.startRecording() else vm.showHint("没有录音权限,去系统设置里给一下")
|
||||
}
|
||||
val onMic: () -> Unit = {
|
||||
when {
|
||||
speech.recording -> speech.stopRecording { text -> vm.draft = text }
|
||||
speech.transcribing -> vm.showHint("还在识别上一段…")
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
|
||||
== PackageManager.PERMISSION_GRANTED -> speech.startRecording()
|
||||
else -> micPermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}
|
||||
|
||||
// 自动朗读:最后一条回复从「进行中」变成「已落地」时念出来
|
||||
//
|
||||
// ★ key 里**不能带 content.length**。带上它的话,流式过程中的每一次增量、
|
||||
// 以及回复落地后 vm.refresh() 把消息换成本地存储版本,都会让这个 effect 重跑;
|
||||
// 而 speak() 对"同一条 + 正在播"的语义是**停止**(手动再点一次就是停),
|
||||
// 于是每重跑一次就把朗读掐掉一次 —— 表现就是"读一半就不读了、时长不定"。
|
||||
// 这里只留 size + pending:只在"多了一条消息 / 它从进行中变成完成"时重跑。
|
||||
val lastMsg = vm.messages.lastOrNull()
|
||||
val lastDoneKey = lastMsg?.let { "${vm.messages.size}:${it.pending}" }
|
||||
LaunchedEffect(lastDoneKey) {
|
||||
val msg = vm.messages.lastOrNull() ?: return@LaunchedEffect
|
||||
if (msg.role == "assistant" && !msg.pending && !msg.error && msg.content.isNotBlank()) {
|
||||
// 内容还在变(流式)时别念,等它稳定一下
|
||||
delay(600)
|
||||
val now = vm.messages.lastOrNull()
|
||||
if (now === msg && !now.pending && now.content == msg.content) {
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 新消息 / 流式增量都滚到底,但**只在用户本来就贴着底部时**才跟。
|
||||
//
|
||||
// ★ 这里曾经有两个叠在一起的毛病,表现是"输出过长的回答时拉不下来":
|
||||
// 1. animateScrollToItem(index) 是把这一项的**顶部**对齐到视口顶部。
|
||||
// 长回答比一屏高得多,所以它压根没"滚到底",只是回到那条回答的开头。
|
||||
// 2. 流式输出时 content.length 每一帧都在变 → 这个 effect 每一帧重跑 →
|
||||
// 用户刚往下滑一点就被拽回开头,等于根本滑不动。
|
||||
// 现在:贴着底部才跟;跟的时候用 scrollToItem + 大 offset 滚到**内容末尾**;
|
||||
// 用户自己往上翻了就完全不打扰(要回底部有下面的按钮)。
|
||||
val atBottom by remember {
|
||||
derivedStateOf {
|
||||
val info = listState.layoutInfo
|
||||
val last = info.visibleItemsInfo.lastOrNull() ?: return@derivedStateOf true
|
||||
last.index >= vm.messages.size - 1 &&
|
||||
last.offset + last.size <= info.viewportEndOffset + 24
|
||||
}
|
||||
}
|
||||
val contentLen = vm.messages.lastOrNull()?.content?.length ?: 0
|
||||
LaunchedEffect(vm.messages.size, contentLen) {
|
||||
if (vm.messages.isEmpty() || !atBottom) return@LaunchedEffect
|
||||
// 不用 animate:流式时每帧都要跟,动画会互相打架,看起来就是抖
|
||||
listState.scrollToItem(vm.messages.size - 1, Int.MAX_VALUE)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (vm.messages.isEmpty()) {
|
||||
val tagline = agent?.greeting.orEmpty().trim()
|
||||
val looksLikeSentence = tagline.length >= 12 &&
|
||||
(tagline.endsWith("。") || tagline.endsWith("!") ||
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
item { AppearOnce { HeroSection(greeting) } }
|
||||
}
|
||||
items(vm.messages.size) { index ->
|
||||
AppearOnce(offsetY = 10.dp) {
|
||||
MessageItem(vm, index, vm.messages[index], speech)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 「回到底部」:长回答往上翻之后,得有个一键回去的路。
|
||||
// 只在用户确实翻上去了、且内容装不下一屏时才出现,平时不占地方。
|
||||
//
|
||||
// ★ 这里必须抽成独立 composable,不能直接在这儿写 AnimatedVisibility:
|
||||
// 我们现在在 Box 里,但外层还有个 Column,Kotlin 会解析到
|
||||
// ColumnScope.AnimatedVisibility 那个重载,报"不能在这个上下文调用"。
|
||||
// 放到一个没有 receiver 的函数里,就只会解析到顶层那个。
|
||||
ScrollToBottomChip(
|
||||
visible = !atBottom && vm.messages.isNotEmpty(),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp),
|
||||
) {
|
||||
scope.launch { listState.animateScrollToItem(vm.messages.size - 1, Int.MAX_VALUE) }
|
||||
}
|
||||
}
|
||||
|
||||
if (vm.messages.isEmpty()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
listOf("对话", "AI创作", "出行用豆包", "豆包").forEach { label ->
|
||||
DoubaoPill(text = label, onClick = { vm.draft = label })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
|
||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||
AnimatedVisibility(
|
||||
visible = thinkingVisible,
|
||||
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
|
||||
) {
|
||||
val index = vm.thinkingIndex
|
||||
if (index in vm.messages.indices) ThinkingSheet(vm.messages[index]) { vm.thinkingIndex = -1 }
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = vm.modelPickerOpen,
|
||||
enter = slideInVertically(initialOffsetY = { it }) + fadeIn(tween(160)),
|
||||
exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(tween(160)),
|
||||
) {
|
||||
ModelPickerSheet(vm) { vm.modelPickerOpen = false }
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 顶部栏 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechController) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
HeaderIcon(Icons.Filled.Menu, "菜单") { vm.drawerOpen = true }
|
||||
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
|
||||
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.clickable { vm.modelPickerOpen = true }
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
}
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Icon(Icons.Filled.ChevronRight, null, tint = doubaoText(), modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
|
||||
HeaderIcon(Icons.Filled.Call, "通话") { vm.showHint("通话模式还没做(方案在 README 里)") }
|
||||
// 这个喇叭是「自动朗读」开关:开了之后每条新回复自动念
|
||||
HeaderIcon(
|
||||
if (speech.autoRead) Icons.Filled.VolumeUp else Icons.Filled.VolumeOff,
|
||||
if (speech.autoRead) "自动朗读已开" else "自动朗读已关",
|
||||
tint = if (speech.autoRead) Doubao.Blue else null,
|
||||
) {
|
||||
val next = !speech.autoRead
|
||||
speech.autoRead = next
|
||||
vm.setAutoRead(next)
|
||||
vm.showHint(if (next) "新回复会自动朗读" else "已关闭自动朗读")
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"AI 生成可能有误 注意核实",
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HeaderIcon(
|
||||
icon: ImageVector,
|
||||
desc: String,
|
||||
tint: androidx.compose.ui.graphics.Color? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.86f else 1f, tween(110), label = "hdr")
|
||||
Box(
|
||||
Modifier
|
||||
.size(44.dp)
|
||||
.scale(scale)
|
||||
.clip(CircleShape)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, desc, tint = tint ?: doubaoText(), modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 空态大头像 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun HeroSection(greeting: String) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||
}
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(doubaoBubble())
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val speaking = speech.speakingIndex == index
|
||||
|
||||
if (msg.role == "user") {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
msg.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoBubble())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.Image, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(file.name, fontSize = 13.sp, color = doubaoText(), maxLines = 1)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
if (msg.content.isNotBlank()) {
|
||||
Box(
|
||||
Modifier
|
||||
.widthIn(max = 288.dp)
|
||||
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
|
||||
.background(Doubao.Blue)
|
||||
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||
val hasReasoning = msg.reasoning.isNotBlank()
|
||||
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||
|
||||
if (hasReasoning || hasTrace || msg.pending) {
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { vm.thinkingIndex = index }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.AutoAwesome, null, tint = Doubao.Blue, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
when {
|
||||
// 强度本身就叫"深度思考",拼上去会变成"深度思考 · 深度思考"
|
||||
hasReasoning -> "深度思考"
|
||||
hasTrace -> "执行过程"
|
||||
else -> "深度思考中"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
if (hasReasoning || hasTrace) {
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
} else {
|
||||
TypingDots(dot = 4.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
msg.toolTrace.forEach { trace ->
|
||||
var open by remember(trace.id) { mutableStateOf(false) }
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { open = !open }
|
||||
.padding(horizontal = 12.dp, vertical = 9.dp),
|
||||
) {
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Build, null, tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(trace.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
when (trace.ok) {
|
||||
true -> "完成"
|
||||
false -> "失败"
|
||||
null -> "进行中"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = if (trace.ok == false) Doubao.Error else Doubao.Blue,
|
||||
)
|
||||
Icon(
|
||||
Icons.Filled.ChevronRight, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
}
|
||||
if (open && trace.result.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
trace.result.take(800),
|
||||
fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
.widthIn(max = 300.dp)
|
||||
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
when {
|
||||
// 助手回复按 Markdown 渲染(代码块、标题、列表、粗体…)。
|
||||
// 用户那条不渲染:用户输入里的 `2 * 3 * 4`、`_x_` 会被当成标记,
|
||||
// 显示出来跟输入的不一样会让人以为打错了。
|
||||
msg.content.isNotBlank() -> if (msg.error) {
|
||||
Text(msg.content, fontSize = 16.sp, lineHeight = 26.sp, color = Doubao.Error)
|
||||
} else {
|
||||
SelectionContainer {
|
||||
MarkdownText(
|
||||
markdown = msg.content,
|
||||
color = doubaoText(),
|
||||
fontSize = 16,
|
||||
lineHeight = 26,
|
||||
)
|
||||
}
|
||||
}
|
||||
msg.pending -> TypingDots()
|
||||
else -> Text("…", color = doubaoTextSecondary(), fontSize = 16.sp)
|
||||
}
|
||||
}
|
||||
|
||||
if (!msg.pending && msg.content.isNotBlank() && !msg.error) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RoundIconButton(Icons.Filled.ContentCopy, "复制") {
|
||||
clipboard.setText(AnnotatedString(msg.content))
|
||||
vm.showHint("已复制")
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
if (speaking) {
|
||||
// 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停"
|
||||
RoundIconButton(
|
||||
Icons.Filled.Stop, "停止朗读",
|
||||
tint = Doubao.Blue,
|
||||
bg = doubaoHeroRing(),
|
||||
) { speech.stopSpeaking() }
|
||||
} else {
|
||||
RoundIconButton(Icons.Filled.VolumeUp, "朗读") {
|
||||
// 手动点朗读时清掉"自动朗读念过了"的记录:
|
||||
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
|
||||
speech.forgetAutoRead()
|
||||
speech.speak(msg.content, index)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RoundIconButton(
|
||||
Icons.Filled.ThumbUp, "赞",
|
||||
tint = if (msg.feedback == "up") Doubao.Blue else null,
|
||||
) { vm.onFeedback(index, "up") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RoundIconButton(
|
||||
Icons.Filled.ThumbDown, "踩",
|
||||
tint = if (msg.feedback == "down") Doubao.Blue else null,
|
||||
) { vm.onFeedback(index, "down") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RoundIconButton(Icons.Filled.Share, "分享") { vm.showHint("分享还没做") }
|
||||
Spacer(Modifier.weight(1f))
|
||||
RoundIconButton(Icons.Filled.Refresh, "重新生成") { vm.regenerate() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 附件 / 输入栏 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun AttachmentStrip(vm: AppViewModel) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
vm.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 10.dp, vertical = 7.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.AttachFile, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(15.dp),
|
||||
)
|
||||
Spacer(Modifier.width(5.dp))
|
||||
Text(file.name, fontSize = 12.sp, color = doubaoText(), maxLines = 1)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.Filled.Close, "移除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(14.dp).clickable { vm.removeAttachment(file.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputBar(
|
||||
vm: AppViewModel,
|
||||
onPickFile: () -> Unit,
|
||||
onMic: () -> Unit,
|
||||
speech: SpeechController,
|
||||
) {
|
||||
val canSend = vm.draft.isNotBlank() || vm.attachments.isNotEmpty()
|
||||
val sendSource = remember { MutableInteractionSource() }
|
||||
val sendPressed by sendSource.collectIsPressedAsState()
|
||||
val sendScale by animateFloatAsState(if (sendPressed) 0.88f else 1f, tween(110), label = "send")
|
||||
|
||||
// 录音时把输入框整条换成"正在听…",跟豆包按住说话一个观感
|
||||
if (speech.recording || speech.transcribing) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.08f))
|
||||
.border(1.dp, Doubao.Blue, RoundedCornerShape(26.dp))
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (speech.transcribing) Icons.Filled.HourglassTop else Icons.Filled.Mic,
|
||||
null, tint = Doubao.Blue, modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
if (speech.transcribing) "识别中…" else "正在听…",
|
||||
fontSize = 15.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
// 简易波形:用实时音量画几根高低不同的柱子,能看出"在收音"
|
||||
Row(
|
||||
Modifier.weight(1f).height(24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
val amp = if (speech.transcribing) 8 else speech.level
|
||||
repeat(18) { i ->
|
||||
// 中间高两边低,再叠加实时音量,看着像声波
|
||||
val shape = 1f - kotlin.math.abs(i - 8.5f) / 10f
|
||||
val h = (6 + amp * shape * 0.16f).coerceIn(4f, 24f)
|
||||
Box(
|
||||
Modifier
|
||||
.width(3.dp)
|
||||
.height(h.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.35f + 0.5f * shape)),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Doubao.Blue)
|
||||
.clickable { onMic() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Check, "完成", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), RoundedCornerShape(26.dp))
|
||||
.padding(horizontal = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (vm.attachments.isEmpty()) Icons.Filled.PhotoCamera else Icons.Filled.Add,
|
||||
"附件",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable(onClick = onPickFile),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
|
||||
if (vm.draft.isEmpty()) {
|
||||
Text("发消息或按住说话…", fontSize = 15.sp, color = Doubao.TextTertiary)
|
||||
}
|
||||
BasicTextField(
|
||||
value = vm.draft,
|
||||
onValueChange = { vm.draft = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = TextStyle(fontSize = 15.sp, color = doubaoText()),
|
||||
cursorBrush = SolidColor(Doubao.Blue),
|
||||
maxLines = 3,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||
keyboardActions = KeyboardActions(onSend = { vm.send() }),
|
||||
)
|
||||
}
|
||||
if (!canSend) {
|
||||
Icon(
|
||||
Icons.Filled.Mic, "语音输入", tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable(onClick = onMic),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (canSend) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.scale(sendScale)
|
||||
.clip(CircleShape)
|
||||
.background(Doubao.Blue)
|
||||
.clickable(interactionSource = sendSource, indication = null) { vm.send() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.ArrowUpward, "发送", tint = Color.White, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), CircleShape)
|
||||
.clickable(onClick = onPickFile),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Add, "更多", tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 思考过程弹层 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(Doubao.Scrim).clickable(onClick = onClose),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 560.dp)
|
||||
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable(enabled = false) {}
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||
) {
|
||||
// 顶上那条小横杠:一眼看出是从底部拉起来的
|
||||
Box(
|
||||
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
|
||||
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
|
||||
)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RoundIconButton(Icons.Filled.Close, "关闭", size = 30.dp, iconSize = 15.dp, onClick = onClose)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text("思考过程", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Spacer(Modifier.width(30.dp))
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
LazyColumn(Modifier.fillMaxWidth()) {
|
||||
if (msg.toolTrace.isNotEmpty()) {
|
||||
items(msg.toolTrace.size) { i ->
|
||||
val trace = msg.toolTrace[i]
|
||||
Row(Modifier.padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.Build, null,
|
||||
tint = doubaoTextSecondary(), modifier = Modifier.size(14.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"${if (trace.ok == false) "失败" else "已调用"} ${trace.name}",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Text(
|
||||
msg.reasoning.ifBlank { "这次没有返回思维链(模型不支持,或思考强度被关掉了)。" },
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* 极简 Markdown 渲染。
|
||||
*
|
||||
* 为什么自己写而不引库:
|
||||
* 项目一直坚持"零第三方依赖"(安卓端构建要能离线完成),而 Markdown 渲染
|
||||
* 在这个规模下不需要一个几百 KB 的库 —— 聊天里真正会出现的就那几种:标题、
|
||||
* 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。
|
||||
*
|
||||
* 支持:
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、> 引用、--- 分隔线、普通段落
|
||||
* 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接)
|
||||
*
|
||||
* 不支持(有意为之):表格、嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 而且做全了就得处理各种边界,性价比很低。
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
markdown: String,
|
||||
// ★ color 不能给默认值:默认参数里不能调用 @Composable 函数
|
||||
// (doubaoText() 是 @Composable,写成 `color: Color = doubaoText()` 直接编译不过)
|
||||
color: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
linkColor: Color = Doubao.Blue,
|
||||
fontSize: Int = 16,
|
||||
lineHeight: Int = 26,
|
||||
) {
|
||||
val blocks = remember(markdown) { parseMarkdown(markdown) }
|
||||
val codeBg = if (isDark()) Color(0xFF1B1F27) else Color(0xFFF3F4F6)
|
||||
val quoteBar = Doubao.Blue.copy(alpha = 0.55f)
|
||||
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (block in blocks) {
|
||||
when (block) {
|
||||
is MdBlock.Code -> {
|
||||
// 代码块单独一块:等宽字体 + 底色 + 可横向滚动(长行不折行更好读)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(codeBg)
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
block.text.trimEnd(),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = (fontSize - 3).sp,
|
||||
lineHeight = (fontSize + 5).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Quote -> {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
// 左边一条竖线,跟正文区分开
|
||||
Box(
|
||||
Modifier
|
||||
.width(3.dp)
|
||||
.heightIn(min = 20.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(quoteBar),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color.copy(alpha = 0.85f),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Numbered -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"${block.number}.",
|
||||
fontSize = fontSize.sp,
|
||||
color = color.copy(alpha = 0.7f),
|
||||
modifier = Modifier.width(22.dp),
|
||||
)
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 2.dp)
|
||||
.height(1.dp)
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 块级解析 ------------------------------ */
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
data class Paragraph(val text: String) : MdBlock
|
||||
data class Heading(val level: Int, val text: String) : MdBlock
|
||||
data class Bullet(val text: String) : MdBlock
|
||||
data class Numbered(val number: String, val text: String) : MdBlock
|
||||
data class Quote(val text: String) : MdBlock
|
||||
data class Code(val text: String, val lang: String = "") : MdBlock
|
||||
data object Divider : MdBlock
|
||||
}
|
||||
|
||||
private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$")
|
||||
private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$")
|
||||
private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$")
|
||||
private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$")
|
||||
private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$")
|
||||
private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$")
|
||||
|
||||
internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
val out = ArrayList<MdBlock>()
|
||||
val lines = src.replace("\r\n", "\n").split("\n")
|
||||
val para = StringBuilder()
|
||||
var i = 0
|
||||
|
||||
fun flushPara() {
|
||||
if (para.isNotBlank()) out.add(MdBlock.Paragraph(para.toString().trim()))
|
||||
para.setLength(0)
|
||||
}
|
||||
|
||||
while (i < lines.size) {
|
||||
val line = lines[i]
|
||||
|
||||
// 代码块:``` 开头到下一个 ```(或文件结束)
|
||||
val fence = RE_FENCE.find(line)
|
||||
if (fence != null) {
|
||||
flushPara()
|
||||
val lang = fence.groupValues[1]
|
||||
val body = StringBuilder()
|
||||
i += 1
|
||||
while (i < lines.size && RE_FENCE.find(lines[i]) == null) {
|
||||
body.append(lines[i]).append('\n')
|
||||
i += 1
|
||||
}
|
||||
i += 1 // 跳过收尾的 ```
|
||||
out.add(MdBlock.Code(body.toString(), lang))
|
||||
continue
|
||||
}
|
||||
|
||||
when {
|
||||
line.isBlank() -> flushPara()
|
||||
|
||||
RE_DIVIDER.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Divider)
|
||||
}
|
||||
|
||||
RE_HEADING.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_HEADING.find(line)!!
|
||||
out.add(MdBlock.Heading(m.groupValues[1].length, m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_QUOTE.matches(line) -> {
|
||||
flushPara()
|
||||
// 连续的引用行合成一段
|
||||
val q = StringBuilder()
|
||||
while (i < lines.size && RE_QUOTE.matches(lines[i])) {
|
||||
if (q.isNotEmpty()) q.append(' ')
|
||||
q.append(RE_QUOTE.find(lines[i])!!.groupValues[1])
|
||||
i += 1
|
||||
}
|
||||
out.add(MdBlock.Quote(q.toString().trim()))
|
||||
continue
|
||||
}
|
||||
|
||||
RE_BULLET.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim()))
|
||||
}
|
||||
|
||||
RE_NUMBERED.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_NUMBERED.find(line)!!
|
||||
out.add(MdBlock.Numbered(m.groupValues[1], m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
else -> {
|
||||
if (para.isNotEmpty()) para.append('\n')
|
||||
para.append(line)
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
flushPara()
|
||||
return out
|
||||
}
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 行内标记 → AnnotatedString。
|
||||
*
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*/
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
when {
|
||||
// 行内代码:`code`
|
||||
text[i] == '`' -> {
|
||||
val end = text.indexOf('`', i + 1)
|
||||
if (end > i) {
|
||||
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp)) {
|
||||
append(text.substring(i + 1, end))
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 粗斜体 / 粗体 / 斜体:***x***、**x**、*x*
|
||||
text.startsWith("***", i) || text.startsWith("**", i) || text[i] == '*' -> {
|
||||
val marker = when {
|
||||
text.startsWith("***", i) -> "***"
|
||||
text.startsWith("**", i) -> "**"
|
||||
else -> "*"
|
||||
}
|
||||
val end = text.indexOf(marker, i + marker.length)
|
||||
// 找不到收尾、或者里面是空的,就当普通字符
|
||||
if (end > i + marker.length) {
|
||||
val inner = text.substring(i + marker.length, end)
|
||||
val style = when (marker) {
|
||||
"***" -> SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic)
|
||||
"**" -> SpanStyle(fontWeight = FontWeight.Bold)
|
||||
else -> SpanStyle(fontStyle = FontStyle.Italic)
|
||||
}
|
||||
withStyle(style) { append(inner) }
|
||||
i = end + marker.length
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 删除线:~~x~~
|
||||
text.startsWith("~~", i) -> {
|
||||
val end = text.indexOf("~~", i + 2)
|
||||
if (end > i + 2) {
|
||||
withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) {
|
||||
append(text.substring(i + 2, end))
|
||||
}
|
||||
i = end + 2
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 链接:[文字](地址)
|
||||
text[i] == '[' -> {
|
||||
val close = text.indexOf(']', i)
|
||||
val open = if (close > 0 && close + 1 < text.length && text[close + 1] == '(') close + 1 else -1
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||
import com.termux.view.TerminalView
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* 内置 Termux 终端。
|
||||
*
|
||||
* 这里是**真的终端**,不是"命令框":
|
||||
* - 进程侧用 Termux 的 pty(libtermux.so 的 JNI 直接调 forkpty),所以是 tty,能跑 vim/top
|
||||
* - 渲染侧用 Termux 的 TerminalView,ANSI 颜色、光标、选区都是现成的
|
||||
*
|
||||
* 手机上没有 Esc/Tab/方向键,所以额外加了一排功能键 —— 没有它连 vim 都退不出来。
|
||||
*/
|
||||
@Composable
|
||||
fun TerminalScreen(
|
||||
vm: AppViewModel,
|
||||
termuxReady: Boolean,
|
||||
termuxStatus: String,
|
||||
onInstallTermux: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val terminal = remember { TermuxTerminal(context) }
|
||||
var title by remember { mutableStateOf("termux") }
|
||||
/** pty 起不来(有些 ROM 的 /dev/pts 不给应用用)时切成命令控制台 */
|
||||
var ptyFailed by remember { mutableStateOf(false) }
|
||||
var startedAt by remember { mutableStateOf(0L) }
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { terminal.destroy() }
|
||||
}
|
||||
|
||||
// pty 不可用的判定:会话建起来后 2 秒内就结束,说明 bash 拿不到 tty(stdin 直接 EOF)
|
||||
val onSessionExit = {
|
||||
if (startedAt > 0 && System.currentTimeMillis() - startedAt < 2000) {
|
||||
ptyFailed = true
|
||||
TermuxInstaller.trace(context, "pty 不可用(会话秒退),切换到命令控制台")
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(Color(0xFF14161A))) {
|
||||
// ---------------- 顶部栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(Color(0xFF1C1F24)).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
IconButton(onClick = { vm.screen = Screen.Chat }) {
|
||||
Icon(Icons.Filled.ArrowBack, "返回", tint = Color.White)
|
||||
}
|
||||
Text(title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.weight(1f))
|
||||
IconButton(onClick = {
|
||||
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
|
||||
terminal.session?.write("\u0003".toByteArray(), 0, 1)
|
||||
}) { Icon(Icons.Filled.Stop, "Ctrl+C", tint = Color.White) }
|
||||
IconButton(onClick = {
|
||||
terminal.session?.write("clear\n".toByteArray(), 0, 6)
|
||||
}) { Icon(Icons.Filled.DeleteSweep, "清屏", tint = Color.White) }
|
||||
}
|
||||
|
||||
// ---------------- 环境状态 / 安装入口 ----------------
|
||||
if (!termuxReady) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(
|
||||
if (termuxStatus.isBlank()) "正在准备内置 Termux 环境…" else termuxStatus,
|
||||
color = Color(0xFFFFD08A),
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
if (termuxStatus.contains("失败")) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
TextButton(onClick = onInstallTermux) { Text("重试安装") }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Surface(color = Color(0xFF16301F), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Termux 已内置 · ${TermuxInstaller.prefix(context).absolutePath}\n" +
|
||||
"试试点上面的 + 装东西:pkg install python nodejs-lts",
|
||||
color = Color(0xFF9BE7B4),
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 终端本体 ----------------
|
||||
if (termuxReady && ptyFailed) {
|
||||
// pty 用不了 → 命令控制台(跑的是同一条 Termux bash,只是没有 tty)
|
||||
Box(Modifier.weight(1f).fillMaxWidth().background(Color(0xFF14161A))) {
|
||||
CommandConsole(
|
||||
onRun = { command, done ->
|
||||
vm.runTool("shell", org.json.JSONObject().put("command", command)) { ok, text ->
|
||||
done(ok, text)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
} else if (termuxReady) {
|
||||
AndroidView(
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
factory = { ctx ->
|
||||
TerminalView(ctx, null).apply {
|
||||
setTerminalViewClient(terminal.viewClient())
|
||||
setTextSize(28)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
try {
|
||||
val session = terminal.session ?: run {
|
||||
startedAt = System.currentTimeMillis()
|
||||
terminal.createSession(onTitle = { title = it }, onExit = onSessionExit)
|
||||
}
|
||||
if (view.currentSession !== session) {
|
||||
view.attachSession(session)
|
||||
view.requestFocus()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
title = "会话启动失败:${t.message}"
|
||||
ptyFailed = true
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
// 没就绪时给一块占位区,别留空白让人以为卡死了
|
||||
Box(
|
||||
Modifier.weight(1f).fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"内置 Termux 环境还没装好,装好后这里就是真终端。",
|
||||
color = Color(0xFF8A93A0),
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 功能键(手机没键盘,必须有这一排) ----------------
|
||||
if (termuxReady) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(Color(0xFF1C1F24))
|
||||
.horizontalScroll(rememberScrollState()).padding(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
data class Key(val label: String, val bytes: String)
|
||||
val keys = listOf(
|
||||
Key("ESC", "\u001b"),
|
||||
Key("TAB", "\t"),
|
||||
Key("CTRL+C", "\u0003"),
|
||||
Key("CTRL+D", "\u0004"),
|
||||
Key("↑", "\u001b[A"),
|
||||
Key("↓", "\u001b[B"),
|
||||
Key("←", "\u001b[D"),
|
||||
Key("→", "\u001b[C"),
|
||||
Key("HOME", "\u001b[H"),
|
||||
Key("END", "\u001b[F"),
|
||||
Key("|", "|"),
|
||||
Key("/", "/"),
|
||||
Key("-", "-"),
|
||||
Key("ENTER", "\n"),
|
||||
)
|
||||
keys.forEach { key ->
|
||||
Surface(
|
||||
shape = RoundedCornerShape(6.dp),
|
||||
color = Color(0xFF2A2F37),
|
||||
modifier = Modifier.padding(end = 6.dp).clickable {
|
||||
val s = terminal.session ?: return@clickable
|
||||
val bytes = key.bytes.toByteArray()
|
||||
s.write(bytes, 0, bytes.size)
|
||||
},
|
||||
) {
|
||||
Text(
|
||||
key.label,
|
||||
color = Color(0xFFD7DAE0),
|
||||
fontSize = 12.sp,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
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,182 +0,0 @@
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
open 所有工具都交给模型
|
||||
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||||
|
||||
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||||
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Callable, Optional
|
||||
|
||||
import store
|
||||
import tools_runtime
|
||||
from providers import stream_chat
|
||||
|
||||
MAX_TOOL_RESULT_CHARS = 6000
|
||||
|
||||
|
||||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||
if isinstance(text, str):
|
||||
out = text
|
||||
else:
|
||||
try:
|
||||
out = json.dumps(text, ensure_ascii=False)
|
||||
except (TypeError, ValueError):
|
||||
out = str(text)
|
||||
return f'{out[:max_len]}\n…(已截断)' if len(out) > max_len else out
|
||||
|
||||
|
||||
def _max_rounds(settings: dict) -> int:
|
||||
raw = settings.get('maxRounds')
|
||||
try:
|
||||
value = int(float(raw))
|
||||
except (TypeError, ValueError):
|
||||
value = 6
|
||||
if not value: # 0 / 空 都按默认 6 处理(对应 JS 的 `Number(x) || 6`)
|
||||
value = 6
|
||||
return max(1, min(12, value))
|
||||
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
settings 当前设置
|
||||
messages [{role, content}] 历史(不含 system)
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
"""
|
||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||
provider = store.provider_info(settings, agent)
|
||||
provider_key = provider.get('provider') or settings.get('provider')
|
||||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
'type': 'start',
|
||||
'provider': provider_key,
|
||||
'model': provider.get('model'),
|
||||
'tools': len(tool_defs),
|
||||
'mode': mode,
|
||||
'thinkingLevel': thinking_level,
|
||||
'agent': {'id': agent.get('id'), 'name': agent.get('name')} if agent else None,
|
||||
})
|
||||
|
||||
convo = []
|
||||
if system_prompt.strip():
|
||||
convo.append({'role': 'system', 'content': system_prompt})
|
||||
convo.extend(messages)
|
||||
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
round_text = ''
|
||||
tool_calls = []
|
||||
|
||||
for event in stream_chat(
|
||||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||||
provider=provider_key,
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=convo,
|
||||
tools=tool_defs if tool_defs else None,
|
||||
temperature=settings.get('temperature'),
|
||||
thinking_level=thinking_level,
|
||||
should_stop=should_stop,
|
||||
):
|
||||
kind = event.get('type')
|
||||
if kind == 'text':
|
||||
round_text += event['text']
|
||||
# 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||||
# 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||||
answer += event['text']
|
||||
emit({'type': 'delta', 'text': event['text'], 'round': round_index})
|
||||
elif kind == 'reasoning':
|
||||
reasoning_all += event['text']
|
||||
emit({'type': 'reasoning', 'text': event['text'], 'round': round_index})
|
||||
elif kind == 'tool_calls':
|
||||
tool_calls = event.get('toolCalls') or []
|
||||
elif kind == 'usage':
|
||||
usage = event.get('usage')
|
||||
|
||||
if not tool_calls:
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
'role': 'assistant',
|
||||
'content': round_text or '',
|
||||
'tool_calls': [
|
||||
{
|
||||
'id': tc.get('id'),
|
||||
'type': 'function',
|
||||
'function': {
|
||||
'name': tc.get('name'),
|
||||
# 参数原样回传:模型可能给出坏 JSON,服务端往往还能自己纠正
|
||||
'arguments': tc.get('argsRaw') or json.dumps(tc.get('args') or {}, ensure_ascii=False),
|
||||
},
|
||||
}
|
||||
for tc in tool_calls
|
||||
],
|
||||
})
|
||||
|
||||
for tc in tool_calls:
|
||||
tool_call_count += 1
|
||||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||||
try:
|
||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if result.get('ok'):
|
||||
raw = result.get('result')
|
||||
payload = truncate('(无输出)' if raw is None else raw)
|
||||
else:
|
||||
payload = f"调用失败:{result.get('error') or '未知错误'}"
|
||||
emit({
|
||||
'type': 'tool_result',
|
||||
'id': tc.get('id'),
|
||||
'name': tc.get('name'),
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': max_rounds,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
'truncated': True,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
"""
|
||||
常量表:提供商预设、默认设置、内置智能体。
|
||||
|
||||
这些值必须和 Node 版 server/src/config.mjs、server/src/agents.mjs 逐字段一致,
|
||||
否则 Lynx 前端读到的设置会出现"字段名对但默认值不同"的细微差异。
|
||||
"""
|
||||
|
||||
DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||
[
|
||||
'你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。',
|
||||
'',
|
||||
'回答要求:',
|
||||
'1. 用简体中文回答,除非用户要求其他语言。',
|
||||
'2. 先给结论,再给必要的解释,避免空话和过度铺垫。',
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
]
|
||||
)
|
||||
|
||||
# 提供商预设。
|
||||
#
|
||||
# 全都是 **OpenAI 兼容协议**(POST {baseUrl}/chat/completions),区别只有
|
||||
# baseUrl、模型名,以及"思考强度怎么传"。
|
||||
#
|
||||
# thinkingMode 就是在说这件事,别写死成"非 ark 即 openai":
|
||||
# 'ark' → 顶层 thinking: {type: enabled|disabled}(火山方舟、智谱 GLM 同形状)
|
||||
# 'effort' → reasoning_effort: low|medium|high(OpenAI 推理模型、OpenRouter 透传)
|
||||
# 'none' → 什么都不发。★ 安全默认值:给不认 reasoning_effort 的服务发这个字段,
|
||||
# 有些会直接 400。DeepSeek / Kimi / 通义 / 硅基流动 的思考由模型自己决定。
|
||||
PROVIDER_PRESETS = {
|
||||
'ark': {
|
||||
'label': '火山方舟(豆包)',
|
||||
'baseUrl': 'https://ark.cn-beijing.volces.com/api/v3',
|
||||
'apiKeyEnv': 'ARK_API_KEY',
|
||||
'defaultModel': 'doubao-seed-2-1-pro-260628',
|
||||
'modelHint': '填模型 ID(如 doubao-seed-2-1-pro-260628)或推理接入点 ID(ep-xxxxxxxx)',
|
||||
'docs': 'https://www.volcengine.com/docs/82379/1298454',
|
||||
'thinkingMode': 'ark',
|
||||
'models': [
|
||||
'doubao-seed-2-1-pro-260628',
|
||||
'doubao-seed-1-8-251228',
|
||||
'deepseek-r1-250528',
|
||||
],
|
||||
},
|
||||
'openai': {
|
||||
'label': 'OpenAI 官方',
|
||||
'baseUrl': 'https://api.openai.com/v1',
|
||||
'apiKeyEnv': 'OPENAI_API_KEY',
|
||||
'defaultModel': 'gpt-4o-mini',
|
||||
'modelHint': '填 model 名称;推理模型(o 系 / gpt-5 系)会自动剥离 temperature 等参数',
|
||||
'docs': 'https://platform.openai.com/docs/api-reference/chat',
|
||||
'thinkingMode': 'effort',
|
||||
'models': ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-5-mini'],
|
||||
},
|
||||
'deepseek': {
|
||||
'label': 'DeepSeek',
|
||||
'baseUrl': 'https://api.deepseek.com/v1',
|
||||
'apiKeyEnv': 'DEEPSEEK_API_KEY',
|
||||
'defaultModel': 'deepseek-chat',
|
||||
'modelHint': 'deepseek-chat 是通用对话;deepseek-reasoner 会自动返回思维链',
|
||||
'docs': 'https://api-docs.deepseek.com/zh-cn/',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['deepseek-chat', 'deepseek-reasoner'],
|
||||
},
|
||||
'kimi': {
|
||||
'label': 'Kimi(月之暗面)',
|
||||
'baseUrl': 'https://api.moonshot.cn/v1',
|
||||
'apiKeyEnv': 'MOONSHOT_API_KEY',
|
||||
'defaultModel': 'kimi-k2-0905-preview',
|
||||
'modelHint': 'Kimi K2 支持工具调用;moonshot-v1-* 是上一代长文本模型',
|
||||
'docs': 'https://platform.moonshot.cn/docs/api/chat',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['kimi-k2-0905-preview', 'kimi-latest', 'moonshot-v1-128k'],
|
||||
},
|
||||
'zhipu': {
|
||||
'label': '智谱 GLM',
|
||||
'baseUrl': 'https://open.bigmodel.cn/api/paas/v4',
|
||||
'apiKeyEnv': 'ZHIPU_API_KEY',
|
||||
'defaultModel': 'glm-4.6',
|
||||
'modelHint': 'GLM 的思考开关和方舟同形状(顶层 thinking),已按这个发',
|
||||
'docs': 'https://docs.bigmodel.cn/cn/guide/develop/openai/introduction',
|
||||
'thinkingMode': 'ark',
|
||||
'models': ['glm-4.6', 'glm-4.5', 'glm-4-flash'],
|
||||
},
|
||||
'dashscope': {
|
||||
'label': '通义千问(阿里云)',
|
||||
'baseUrl': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
'apiKeyEnv': 'DASHSCOPE_API_KEY',
|
||||
'defaultModel': 'qwen-plus',
|
||||
'modelHint': 'Qwen3 系列自己会思考,这里不发思考参数',
|
||||
'docs': 'https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['qwen3-max', 'qwen-plus', 'qwen-turbo'],
|
||||
},
|
||||
'siliconflow': {
|
||||
'label': '硅基流动',
|
||||
'baseUrl': 'https://api.siliconflow.cn/v1',
|
||||
'apiKeyEnv': 'SILICONFLOW_API_KEY',
|
||||
'defaultModel': 'deepseek-ai/DeepSeek-V3',
|
||||
'modelHint': '模型名带斜杠(组织/模型),例如 deepseek-ai/DeepSeek-V3',
|
||||
'docs': 'https://docs.siliconflow.cn/cn/api-reference/chat-completions/chat-completions',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['deepseek-ai/DeepSeek-V3', 'Qwen/Qwen3-235B-A22B', 'THUDM/glm-4-9b-chat'],
|
||||
},
|
||||
'openrouter': {
|
||||
'label': 'OpenRouter(聚合)',
|
||||
'baseUrl': 'https://openrouter.ai/api/v1',
|
||||
'apiKeyEnv': 'OPENROUTER_API_KEY',
|
||||
'defaultModel': 'openai/gpt-4o-mini',
|
||||
'modelHint': '一个 Key 调各家模型,模型名是「厂商/模型」;会透传 reasoning_effort',
|
||||
'docs': 'https://openrouter.ai/docs/api-reference/overview',
|
||||
'thinkingMode': 'effort',
|
||||
'models': ['openai/gpt-4o-mini', 'deepseek/deepseek-chat', 'anthropic/claude-3.5-sonnet'],
|
||||
},
|
||||
'ollama': {
|
||||
'label': '本地 Ollama',
|
||||
'baseUrl': 'http://127.0.0.1:11434/v1',
|
||||
'apiKeyEnv': 'OLLAMA_API_KEY',
|
||||
'defaultModel': 'qwen2.5:7b',
|
||||
'modelHint': '本地跑,Key 随便填(Ollama 不校验)。手机连电脑要填电脑的局域网 IP',
|
||||
'docs': 'https://github.com/ollama/ollama/blob/main/docs/openai.md',
|
||||
'thinkingMode': 'none',
|
||||
'models': ['qwen2.5:7b', 'llama3.1:8b', 'deepseek-r1:7b'],
|
||||
},
|
||||
'custom': {
|
||||
'label': '自定义(任意兼容网关)',
|
||||
'baseUrl': '',
|
||||
'apiKeyEnv': 'CUSTOM_API_KEY',
|
||||
'defaultModel': '',
|
||||
'modelHint': '填完整的 /v1 地址和模型名,只要兼容 OpenAI 的 chat/completions 就能用',
|
||||
'docs': '',
|
||||
'thinkingMode': 'none',
|
||||
'models': [],
|
||||
},
|
||||
}
|
||||
|
||||
# 各家控制台「申请 API Key」的直达链接。
|
||||
#
|
||||
# 为什么单独一张表、而不是塞进每个预设里:这些地址会变
|
||||
# (实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com,
|
||||
# 旧地址 301 跳过去),集中一处以后好改。
|
||||
# 已逐个访问核实过可达(返回 200 或 302 到登录页都算通)。
|
||||
PROVIDER_CONSOLE_URLS = {
|
||||
'ark': 'https://console.volcengine.com/ark/region:cn-beijing/apiKey',
|
||||
'openai': 'https://platform.openai.com/api-keys',
|
||||
'deepseek': 'https://platform.deepseek.com/api_keys',
|
||||
'kimi': 'https://platform.kimi.com/console/api-keys',
|
||||
'zhipu': 'https://open.bigmodel.cn/usercenter/apikeys',
|
||||
'dashscope': 'https://bailian.console.aliyun.com/?apiKey=1',
|
||||
'siliconflow': 'https://cloud.siliconflow.cn/account/ak',
|
||||
'openrouter': 'https://openrouter.ai/keys',
|
||||
'ollama': 'https://ollama.com/download',
|
||||
'custom': '',
|
||||
}
|
||||
for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
if _key in PROVIDER_PRESETS:
|
||||
PROVIDER_PRESETS[_key]['consoleUrl'] = _url
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
'apiKey': '',
|
||||
'temperature': 0.7,
|
||||
'maxRounds': 6,
|
||||
# 思考强度:off / low / medium / high / auto
|
||||
# - 方舟:映射到顶层 thinking 字段
|
||||
# - OpenAI:映射到 reasoning_effort(推理模型)
|
||||
'thinkingLevel': 'auto',
|
||||
# 额外工具目录(留空则用内置 tools/);安卓端可以指到手机上的目录
|
||||
'toolsDir': '',
|
||||
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||
'tools': {'python': True, 'mcp': True},
|
||||
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||
'speech': {
|
||||
'ttsEngine': 'system', # system | volc | openai
|
||||
'ttsVoice': '', # volc: voice_type;openai: alloy/nova/...
|
||||
'ttsSpeed': 1.0,
|
||||
'autoRead': False, # 新回复自动念出来
|
||||
'sttEngine': 'system', # system | openai
|
||||
'sttModel': 'whisper-1',
|
||||
'sttLanguage': '', # 留空 = 自动判断
|
||||
'volcAppId': '',
|
||||
'volcToken': '',
|
||||
'volcCluster': 'volcano_tts',
|
||||
'volcEncoding': 'mp3',
|
||||
'openaiApiKey': '', # 留空则复用主对话的 Key
|
||||
'openaiBaseUrl': '', # 留空则复用主对话的 Base URL
|
||||
'ttsModel': 'tts-1',
|
||||
},
|
||||
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
|
||||
'security': {'mode': 'open', 'allow': []},
|
||||
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
|
||||
'pythonBin': '',
|
||||
'nickname': '我',
|
||||
'doubaoId': '378269252',
|
||||
'activeAgentId': 'a_doubao',
|
||||
}
|
||||
|
||||
SECRET_KEYS = {'apiKey'}
|
||||
|
||||
# 内置智能体(前端有同名头像,靠 avatar 字段对应)
|
||||
DEFAULT_AGENTS = [
|
||||
{
|
||||
'id': 'a_doubao',
|
||||
'name': '豆包',
|
||||
'avatar': 'doubao',
|
||||
'tagline': '通用助手',
|
||||
'systemPrompt': '',
|
||||
'builtin': True,
|
||||
},
|
||||
{
|
||||
'id': 'a_coder',
|
||||
'name': '代码搭子',
|
||||
'avatar': 'coder',
|
||||
'tagline': '只聊代码,直接给能跑的',
|
||||
'systemPrompt': '\n'.join(
|
||||
[
|
||||
'你是一个资深工程师。',
|
||||
'1. 先给可以直接复制运行的代码,再解释关键点。',
|
||||
'2. 代码里不要有省略号,不要写"此处省略"。',
|
||||
'3. 指出你方案里的坑和替代做法。',
|
||||
'4. 涉及文件读写、执行命令时优先调用可用工具。',
|
||||
]
|
||||
),
|
||||
'builtin': True,
|
||||
},
|
||||
{
|
||||
'id': 'a_writer',
|
||||
'name': '文案师',
|
||||
'avatar': 'writer',
|
||||
'tagline': '写东西、改稿子',
|
||||
'systemPrompt': '\n'.join(
|
||||
[
|
||||
'你是中文文案编辑。',
|
||||
'1. 先问清楚用途、受众、字数要求,信息不全就按最常见的场景先给一版。',
|
||||
'2. 给成品,不要给"写作思路"。',
|
||||
'3. 口语化、短句、少用形容词堆砌,别用"赋能/闭环/抓手"这类词。',
|
||||
]
|
||||
),
|
||||
'builtin': True,
|
||||
},
|
||||
{
|
||||
'id': 'a_analyst',
|
||||
'name': '数据分析',
|
||||
'avatar': 'analyst',
|
||||
'tagline': '算数、看数据、讲结论',
|
||||
'systemPrompt': '\n'.join(
|
||||
[
|
||||
'你是数据分析师。',
|
||||
'1. 任何计算都必须调用 calc 工具,不要心算。',
|
||||
'2. 先给结论,再给口径和数据来源。',
|
||||
'3. 样本不足或数据可疑时直接说出来。',
|
||||
]
|
||||
),
|
||||
'builtin': True,
|
||||
},
|
||||
]
|
||||
|
||||
# 可选头像(前端有同名 SVG,这里只做白名单校验)
|
||||
AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'robot', 'star', 'cloud', 'custom']
|
||||
@@ -1,508 +0,0 @@
|
||||
"""
|
||||
持久化:设置 / 会话 / 智能体。
|
||||
|
||||
对应 Node 版的 config.mjs(设置)+ store.mjs(会话)+ agents.mjs(智能体),
|
||||
文件名也保持一致(settings.json / conversations.json / agents.json),
|
||||
这样安卓内核和桌面内核可以共用同一个数据目录。
|
||||
|
||||
为什么用 JSON 文件而不是 SQLite:
|
||||
* 数据量极小(几条会话、几个智能体),前端还要能直接看到/改这些文件;
|
||||
* 安卓上 Chaquopy 自带 sqlite3,但跨端"人肉可读"更重要;
|
||||
* 写盘走"临时文件 + 原子替换",避免安卓被杀进程时留下半个 JSON。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS
|
||||
|
||||
_lock = threading.RLock()
|
||||
_conv_state = None # 会话状态在内存里缓存(和 Node 版 store.mjs 一样只 load 一次)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 通用小工具
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def now_iso() -> str:
|
||||
"""
|
||||
和 JS 的 new Date().toISOString() 完全一致的格式:
|
||||
2025-01-01T12:00:00.000Z(毫秒精度 + Z 后缀)。
|
||||
前端会把这些字符串直接排序/展示,格式不一致会出现"时间跳来跳去"。
|
||||
"""
|
||||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def _read_json(file_path: str):
|
||||
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
return None
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as fh:
|
||||
return json.load(fh)
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f'[store] {os.path.basename(file_path)} 解析失败:{exc}', file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _write_json(file_path: str, payload) -> None:
|
||||
"""原子写:先写 .tmp 再 os.replace,避免掉电/被杀时留下半个文件。"""
|
||||
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
||||
tmp = f'{file_path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as fh:
|
||||
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, file_path)
|
||||
|
||||
|
||||
def _as_text(value) -> str:
|
||||
"""JS 的 String(x):None 会变成空串而不是 'None'。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 设置
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_dotenv_loaded = False
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""
|
||||
极简 .env 解析。Node 版读 server/.env;Python 版读数据目录和内核目录下的 .env,
|
||||
这样安卓上把 key 放在数据目录里就能用,不需要动源码目录。
|
||||
"""
|
||||
global _dotenv_loaded
|
||||
if _dotenv_loaded:
|
||||
return
|
||||
_dotenv_loaded = True
|
||||
p = paths.get()
|
||||
for folder in (p.data_dir, os.path.dirname(os.path.abspath(__file__))):
|
||||
env_file = os.path.join(folder, '.env')
|
||||
if not os.path.isfile(env_file):
|
||||
continue
|
||||
try:
|
||||
with open(env_file, 'r', encoding='utf-8') as fh:
|
||||
lines = fh.read().splitlines()
|
||||
except OSError:
|
||||
continue
|
||||
for raw in lines:
|
||||
line = raw.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
key, _, value = line.partition('=')
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
|
||||
value = value[1:-1]
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
def mask_settings(settings: dict) -> dict:
|
||||
"""脱敏:apiKey / 语音 Token 只回掩码 + has* 标志(前端据此显示"已配置")。"""
|
||||
out = dict(settings)
|
||||
out['apiKey'] = '••••••••' if settings.get('apiKey') else ''
|
||||
out['hasApiKey'] = bool(settings.get('apiKey'))
|
||||
speech = dict(out.get('speech') or {})
|
||||
speech['volcToken'] = '••••••••' if speech.get('volcToken') else ''
|
||||
speech['volcApiKey'] = '••••••••' if speech.get('volcApiKey') else ''
|
||||
speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else ''
|
||||
out['speech'] = speech
|
||||
return out
|
||||
|
||||
|
||||
def read_settings() -> dict:
|
||||
"""读设置:默认值 + 文件 + 环境变量兜底(字段与 Node 版一致)。"""
|
||||
_load_dotenv()
|
||||
stored = _read_json(paths.get().settings_file) or {}
|
||||
if not isinstance(stored, dict):
|
||||
stored = {}
|
||||
settings = dict(DEFAULT_SETTINGS)
|
||||
settings.update(stored)
|
||||
# 子对象要深合并,否则用户只改 security.allow 会把 security.mode 冲掉。
|
||||
# ★ 而且必须防住"子对象被非字典值覆盖":曾经前端把嵌套 Map 序列化成了字符串
|
||||
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
|
||||
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||||
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
|
||||
for key in ('tools', 'security', 'speech'):
|
||||
defaults = DEFAULT_SETTINGS.get(key) or {}
|
||||
raw = stored.get(key)
|
||||
if not isinstance(raw, dict):
|
||||
if raw is not None:
|
||||
print(f'[config] settings.json 里的 {key} 不是对象,已回落默认值', file=sys.stderr, flush=True)
|
||||
raw = {}
|
||||
settings[key] = {**defaults, **raw}
|
||||
if not isinstance(settings['security'].get('allow'), list):
|
||||
settings['security']['allow'] = []
|
||||
settings.pop('hasApiKey', None)
|
||||
|
||||
# 环境变量兜底:没填 key 时用 .env / 系统环境变量里的
|
||||
preset = _preset_of(settings)
|
||||
if not settings.get('apiKey') and preset.get('apiKeyEnv'):
|
||||
settings['apiKey'] = os.environ.get(preset['apiKeyEnv'], '')
|
||||
return settings
|
||||
|
||||
|
||||
def _preset_of(settings: dict) -> dict:
|
||||
from defaults import PROVIDER_PRESETS # 局部导入,避免循环依赖
|
||||
|
||||
return PROVIDER_PRESETS.get(settings.get('provider')) or PROVIDER_PRESETS['ark']
|
||||
|
||||
|
||||
def write_settings(patch: dict) -> dict:
|
||||
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
|
||||
if not isinstance(patch, dict):
|
||||
patch = {}
|
||||
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
|
||||
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
|
||||
# systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求。
|
||||
for key in ('baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel'):
|
||||
if key in patch and isinstance(patch[key], str) and not patch[key].strip():
|
||||
patch.pop(key)
|
||||
current = read_settings()
|
||||
nxt = {**current, **patch}
|
||||
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
|
||||
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
|
||||
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||
for key in ('tools', 'security', 'speech'):
|
||||
if key not in patch:
|
||||
continue
|
||||
if isinstance(patch[key], dict):
|
||||
nxt[key] = {**(current.get(key) or {}), **patch[key]}
|
||||
else:
|
||||
nxt[key] = current.get(key) or {}
|
||||
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||
if patch.get('apiKey') == '••••••••':
|
||||
nxt['apiKey'] = current.get('apiKey', '')
|
||||
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
|
||||
# 这个掩码会跟着 patch 回来。不处理的话真 Token 就被这八个点覆盖了,
|
||||
# 下次朗读直接报"缺 Token" —— 这类"看一眼就坏"的 bug 最难查。
|
||||
speech_next = nxt.get('speech')
|
||||
if isinstance(speech_next, dict):
|
||||
speech_cur = current.get('speech') or {}
|
||||
for secret in ('volcToken', 'volcApiKey', 'openaiApiKey'):
|
||||
if speech_next.get(secret) == '••••••••':
|
||||
speech_next[secret] = speech_cur.get(secret, '')
|
||||
# ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。
|
||||
# 引擎名一空,界面上一张卡片都不会高亮(看起来就是"设置被清空了");
|
||||
# 模型名一空,朗读/识别会直接调不通。
|
||||
# 注意 ttsVoice / volcAppId / sttLanguage 不在此列 —— 它们留空是合理需求
|
||||
# (留空 = 用引擎默认音色 / 还没填)。
|
||||
for key in ('ttsEngine', 'sttEngine', 'sttModel', 'ttsModel', 'volcCluster', 'volcEncoding'):
|
||||
if key in speech_next and isinstance(speech_next[key], str) and not speech_next[key].strip():
|
||||
speech_next[key] = speech_cur.get(key) or DEFAULT_SETTINGS['speech'].get(key, '')
|
||||
nxt['speech'] = speech_next
|
||||
nxt.pop('hasApiKey', None)
|
||||
_write_json(paths.get().settings_file, nxt)
|
||||
return nxt
|
||||
|
||||
|
||||
def provider_info(settings: dict, agent: dict = None) -> dict:
|
||||
"""
|
||||
当前提供商的完整信息(预设 + 生效的 baseUrl/model)。
|
||||
|
||||
★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。
|
||||
这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事,
|
||||
不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。
|
||||
"""
|
||||
agent = agent or {}
|
||||
provider_key = (agent.get('provider') or '').strip() or settings.get('provider')
|
||||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||||
return {
|
||||
**preset,
|
||||
'provider': provider_key,
|
||||
# baseUrl 也是三层:智能体 > 全局 > 预设
|
||||
'baseUrl': (agent.get('baseUrl') or '').strip() or settings.get('baseUrl') or preset.get('baseUrl', ''),
|
||||
'model': (agent.get('model') or '').strip() or settings.get('model') or preset.get('defaultModel', ''),
|
||||
}
|
||||
|
||||
|
||||
def agent_or_empty(agent_id: str) -> dict:
|
||||
"""按 id 找智能体;找不到返回空 dict(调用方按"没指定"处理)。
|
||||
|
||||
包一层是因为 get_agent 返回 None,而调用方(会议引擎、朗读路由)基本都是
|
||||
"有就用、没有就继承全局"的语义,到处写 `or {}` 太啰嗦。
|
||||
"""
|
||||
return get_agent(agent_id) or {}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 会话
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _rid_conv() -> str:
|
||||
# 和 Node 的 `c_${Date.now().toString(36)}_${random}` 同风格;不必逐字符相同
|
||||
return f'c_{_ts36()}_{_rand36(5)}'
|
||||
|
||||
|
||||
def _ts36() -> str:
|
||||
return _base36(int(datetime.now(timezone.utc).timestamp() * 1000))
|
||||
|
||||
|
||||
def _base36(num: int) -> str:
|
||||
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
|
||||
if num == 0:
|
||||
return '0'
|
||||
out = ''
|
||||
while num:
|
||||
num, rem = divmod(num, 36)
|
||||
out = digits[rem] + out
|
||||
return out
|
||||
|
||||
|
||||
def _rand36(length: int) -> str:
|
||||
import random
|
||||
|
||||
return ''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz') for _ in range(length))
|
||||
|
||||
|
||||
def _fresh_state() -> dict:
|
||||
stamp = now_iso()
|
||||
return {
|
||||
'conversations': [
|
||||
{
|
||||
'id': 'c_main',
|
||||
'title': '主对话',
|
||||
'agentId': 'a_doubao',
|
||||
'pinned': True,
|
||||
'createdAt': stamp,
|
||||
'updatedAt': stamp,
|
||||
'messages': [],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _load_conversations() -> dict:
|
||||
global _conv_state
|
||||
with _lock:
|
||||
if _conv_state is None:
|
||||
state = _read_json(paths.get().conversations_file)
|
||||
if state is None:
|
||||
state = _fresh_state()
|
||||
if not isinstance(state.get('conversations'), list) or not state['conversations']:
|
||||
state = _fresh_state()
|
||||
_conv_state = state
|
||||
return _conv_state
|
||||
|
||||
|
||||
def _persist_conversations() -> None:
|
||||
_write_json(paths.get().conversations_file, _load_conversations())
|
||||
|
||||
|
||||
def _preview_of(messages: list) -> str:
|
||||
"""列表预览:取最后一条有内容的消息,用户消息加"我:"前缀。"""
|
||||
for msg in reversed(messages or []):
|
||||
content = msg.get('content')
|
||||
if not content:
|
||||
continue
|
||||
text = re.sub(r'\s+', ' ', _as_text(content)).strip()
|
||||
if not text:
|
||||
continue
|
||||
tag = '我:' if msg.get('role') == 'user' else ''
|
||||
return f'{tag}{text[:30]}…' if len(text) > 30 else f'{tag}{text}'
|
||||
return ''
|
||||
|
||||
|
||||
def list_conversations() -> list:
|
||||
"""列表:带最后一条消息预览,置顶优先 + 更新时间倒序。"""
|
||||
items = list(_load_conversations()['conversations'])
|
||||
items.sort(
|
||||
key=lambda c: (1 if c.get('pinned') else 0, _as_text(c.get('updatedAt'))),
|
||||
reverse=True,
|
||||
)
|
||||
out = []
|
||||
for conv in items:
|
||||
messages = conv.get('messages') or []
|
||||
meta = {k: v for k, v in conv.items() if k != 'messages'}
|
||||
meta['messageCount'] = len(messages)
|
||||
meta['preview'] = _preview_of(messages)
|
||||
out.append(meta)
|
||||
return out
|
||||
|
||||
|
||||
def get_conversation(conv_id: str):
|
||||
for conv in _load_conversations()['conversations']:
|
||||
if conv.get('id') == conv_id:
|
||||
return conv
|
||||
return None
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
'title': title,
|
||||
'agentId': agent_id or '',
|
||||
'pinned': False,
|
||||
'createdAt': now_iso(),
|
||||
'updatedAt': now_iso(),
|
||||
'messages': [],
|
||||
}
|
||||
with _lock:
|
||||
_load_conversations()['conversations'].insert(0, item)
|
||||
_persist_conversations()
|
||||
return item
|
||||
|
||||
|
||||
def update_conversation(conv_id: str, patch: dict):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
with _lock:
|
||||
if isinstance(patch, dict):
|
||||
item.update(patch)
|
||||
item['updatedAt'] = now_iso()
|
||||
_persist_conversations()
|
||||
return item
|
||||
|
||||
|
||||
def delete_conversation(conv_id: str) -> bool:
|
||||
with _lock:
|
||||
state = _load_conversations()
|
||||
index = next((i for i, c in enumerate(state['conversations']) if c.get('id') == conv_id), -1)
|
||||
if index < 0:
|
||||
return False
|
||||
state['conversations'].pop(index)
|
||||
# 删光了就把"主对话"补回来,界面上不能出现空列表
|
||||
if not state['conversations']:
|
||||
state['conversations'].extend(_fresh_state()['conversations'])
|
||||
_persist_conversations()
|
||||
return True
|
||||
|
||||
|
||||
def append_messages(conv_id: str, messages: list):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
with _lock:
|
||||
item.setdefault('messages', []).extend(messages)
|
||||
item['updatedAt'] = now_iso()
|
||||
_persist_conversations()
|
||||
return item
|
||||
|
||||
|
||||
def auto_title(conv_id: str, text: str) -> None:
|
||||
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item or item.get('title') not in ('新对话', '主对话'):
|
||||
return
|
||||
title = re.sub(r'\s+', ' ', _as_text(text)).strip()[:18]
|
||||
if title:
|
||||
update_conversation(conv_id, {'title': title})
|
||||
|
||||
|
||||
def store_file_path() -> str:
|
||||
return paths.get().conversations_file
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 智能体可以独立指定的字段。**留空一律表示"继承全局设置"** ——
|
||||
# 这样"代码搭子走 DeepSeek、文案师用另一个音色"只改那一个智能体,
|
||||
# 而全局设置仍然是没配过的智能体的默认值。
|
||||
#
|
||||
# 提成常量是为了 create / update 两边不会漂移:
|
||||
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
|
||||
# 表现就是"界面上填了、保存后再打开又变空了"。
|
||||
AGENT_FIELDS = (
|
||||
'provider', # 走哪家(留空 = 全局)
|
||||
'model', # 用哪个模型
|
||||
'baseUrl', # 自定义网关地址
|
||||
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
|
||||
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
|
||||
'ttsSpeed', # 语速
|
||||
)
|
||||
|
||||
|
||||
def _rid_agent() -> str:
|
||||
return f'a_{_ts36()}_{_rand36(4)}'
|
||||
|
||||
|
||||
def list_agents() -> list:
|
||||
file_path = paths.get().agents_file
|
||||
if not os.path.isfile(file_path):
|
||||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||
return [dict(a) for a in DEFAULT_AGENTS]
|
||||
data = _read_json(file_path)
|
||||
if not isinstance(data, dict) or not isinstance(data.get('agents'), list) or not data['agents']:
|
||||
print('[store] agents.json 损坏,重建内置智能体', file=sys.stderr)
|
||||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||
return [dict(a) for a in DEFAULT_AGENTS]
|
||||
return data['agents']
|
||||
|
||||
|
||||
def get_agent(agent_id: str | None):
|
||||
if not agent_id:
|
||||
return None
|
||||
for agent in list_agents():
|
||||
if agent.get('id') == agent_id:
|
||||
return agent
|
||||
return None
|
||||
|
||||
|
||||
def create_agent(payload: dict) -> dict:
|
||||
payload = payload or {}
|
||||
state = {'agents': list_agents()}
|
||||
agent = {
|
||||
'id': _rid_agent(),
|
||||
'name': _as_text(payload.get('name') or '新智能体')[:24],
|
||||
'avatar': payload.get('avatar') or 'custom',
|
||||
'tagline': _as_text(payload.get('tagline'))[:40],
|
||||
'systemPrompt': _as_text(payload.get('systemPrompt')),
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
}
|
||||
# 智能体自己的模型/语音(留空 = 继承全局)
|
||||
for key in AGENT_FIELDS:
|
||||
if payload.get(key) is not None:
|
||||
agent[key] = _as_text(payload.get(key))
|
||||
state['agents'].append(agent)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
|
||||
|
||||
def update_agent(agent_id: str, patch: dict):
|
||||
state = {'agents': list_agents()}
|
||||
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
|
||||
if not agent:
|
||||
return None
|
||||
patch = patch or {}
|
||||
for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS):
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = patch[key]
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
|
||||
|
||||
def delete_agent(agent_id: str) -> bool:
|
||||
state = {'agents': list_agents()}
|
||||
index = next((i for i, a in enumerate(state['agents']) if a.get('id') == agent_id), -1)
|
||||
if index < 0:
|
||||
return False
|
||||
state['agents'].pop(index)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return True
|
||||
|
||||
|
||||
def reset_runtime_cache() -> None:
|
||||
"""测试/热重载用:丢掉会话内存缓存(设置本来就不缓存)。"""
|
||||
global _conv_state, _dotenv_loaded
|
||||
with _lock:
|
||||
_conv_state = None
|
||||
_dotenv_loaded = False
|
||||
@@ -1,408 +0,0 @@
|
||||
"""
|
||||
工具运行时:发现、过滤、执行。
|
||||
|
||||
对应 Node 版 server/src/python-tools.mjs + agent.mjs 里的工具部分。
|
||||
|
||||
★ 最重要的安卓取舍:用 importlib 直接 import 工具模块,绝不用 subprocess 调 python。
|
||||
|
||||
Node 版是 `python tool.py --spec` / `python tool.py --input args.json`,
|
||||
因为桌面上一定有解释器。安卓(Chaquopy)里**没有独立的 python 可执行文件**,
|
||||
解释器只存在于本进程内,spawn('python') 一定 ENOENT。
|
||||
所以这里改成:
|
||||
importlib.util.spec_from_file_location(...) → exec_module
|
||||
→ 取模块的 TOOL(工具描述)和 run(执行函数)
|
||||
代价是工具代码和内核同进程(崩溃会一起死、全局状态会互相影响),
|
||||
但对"安卓上必须能跑"这个目标,这是唯一可行的路。
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import mcp_client
|
||||
import paths
|
||||
from builtin_tools import BUILTIN_TOOLS, run_with_timeout
|
||||
|
||||
# 文件工具的缓存:path -> {'mtime':..., 'spec':..., 'error':...}
|
||||
_spec_cache: dict = {}
|
||||
_cache_lock = threading.Lock()
|
||||
# 已经 import 过的模块名(重载时要先从 sys.modules 里摘掉)
|
||||
_loaded_modules: dict = {}
|
||||
|
||||
TOOL_TIMEOUT_S = 60
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 目录与文件
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def tools_dir() -> str:
|
||||
"""
|
||||
工具目录:settings.toolsDir 优先(安卓端指到手机上的目录),
|
||||
否则用内置 tools/(--tools-dir / DOUBAO_TOOLS 指定)。
|
||||
"""
|
||||
import store # 局部导入:store 不依赖本模块,但放在顶部会让 import 顺序更难读
|
||||
|
||||
custom = (store.read_settings() or {}).get('toolsDir')
|
||||
if custom and os.path.isdir(custom):
|
||||
return os.path.abspath(custom)
|
||||
return paths.get().tools_dir
|
||||
|
||||
|
||||
def python_files() -> list:
|
||||
folder = tools_dir()
|
||||
if not os.path.isdir(folder):
|
||||
return []
|
||||
# 排序:Node 那边 readdir 在 NTFS 上正好是字典序,这里显式排序保证工具顺序稳定
|
||||
names = sorted(
|
||||
n for n in os.listdir(folder)
|
||||
if n.endswith('.py') and not n.startswith('_')
|
||||
)
|
||||
return [os.path.join(folder, n) for n in names]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 导入工具模块
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _import_tool_module(file_path: str, folder: str):
|
||||
"""
|
||||
用 importlib 按文件路径导入工具模块。
|
||||
|
||||
要点:
|
||||
* 模块名带 `_doubao_tool_` 前缀 + 文件名哈希,避免和内核自己的模块重名;
|
||||
* 把工具目录插进 sys.path —— tools/*.py 里有 `from _protocol import serve`,
|
||||
它们自己也会 insert 一次,但我们先插好更稳(顺序:我们自己在前);
|
||||
* 重新 import 前先 sys.modules.pop,否则拿到的是改了文件也没更新的旧模块。
|
||||
"""
|
||||
stem = os.path.splitext(os.path.basename(file_path))[0]
|
||||
safe_stem = re.sub(r'\W', '_', stem)
|
||||
mod_name = f'_doubao_tool_{safe_stem}_{abs(hash(os.path.abspath(file_path))) % 100000}'
|
||||
old = _loaded_modules.get(file_path)
|
||||
if old and old in sys.modules:
|
||||
sys.modules.pop(old, None)
|
||||
if folder and folder not in sys.path:
|
||||
sys.path.insert(0, folder)
|
||||
spec = importlib.util.spec_from_file_location(mod_name, file_path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ImportError(f'无法为 {file_path} 建立模块 spec')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[mod_name] = module
|
||||
try:
|
||||
spec.loader.exec_module(module)
|
||||
except BaseException:
|
||||
sys.modules.pop(mod_name, None)
|
||||
raise
|
||||
_loaded_modules[file_path] = mod_name
|
||||
return module
|
||||
|
||||
|
||||
def _spec_from_module(module, file_path: str) -> dict:
|
||||
tool = getattr(module, 'TOOL', None)
|
||||
if not isinstance(tool, dict) or not tool.get('name'):
|
||||
raise ValueError('模块里没有合法的 TOOL(需要 {name, description, parameters})')
|
||||
if not callable(getattr(module, 'run', None)):
|
||||
raise ValueError('模块里没有可调用的 run(args)')
|
||||
spec = dict(tool)
|
||||
spec.setdefault('description', spec['name'])
|
||||
spec.setdefault('parameters', {'type': 'object', 'properties': {}})
|
||||
spec['file'] = os.path.basename(file_path)
|
||||
spec['_path'] = file_path
|
||||
return spec
|
||||
|
||||
|
||||
def _builtin_spec(name: str, file_path: str = '') -> dict:
|
||||
"""
|
||||
内置工具的工具描述。
|
||||
|
||||
file 字段:如果工具目录里存在同名文件(例如 tools/shell.py),就沿用它的文件名,
|
||||
这样 /api/state 的 python.tools 和 Node 版逐字段一致(前端 Skills 页显示的就是它);
|
||||
找不到同名文件时才写 <内置>。另外附一个 builtin=true 供调试识别(前端不读它)。
|
||||
"""
|
||||
entry = BUILTIN_TOOLS[name]
|
||||
spec = dict(entry['spec'])
|
||||
spec['file'] = os.path.basename(file_path) if file_path else BUILTIN_FILE_LABEL
|
||||
spec['builtin'] = True
|
||||
spec['_path'] = ''
|
||||
spec['_builtin'] = True
|
||||
return spec
|
||||
|
||||
|
||||
def discover_python_tools(force: bool = False) -> dict:
|
||||
"""
|
||||
扫描并加载全部 Python 工具。
|
||||
|
||||
返回 {'tools': [...], 'errors': [{'file','error'}], 'python': {'bin','prefix'}|None}
|
||||
语义与 Node 版 discoverPythonTools 一致;区别是用 import 代替子进程 --spec。
|
||||
"""
|
||||
folder = tools_dir()
|
||||
files = python_files()
|
||||
tools, errors = [], []
|
||||
emitted_builtins = set()
|
||||
|
||||
for file_path in files:
|
||||
try:
|
||||
mtime = os.path.getmtime(file_path)
|
||||
except OSError as exc:
|
||||
errors.append({'file': os.path.basename(file_path), 'error': f'无法读取文件:{exc}'})
|
||||
continue
|
||||
with _cache_lock:
|
||||
cached = _spec_cache.get(file_path)
|
||||
if not force and cached and cached.get('mtime') == mtime:
|
||||
spec, error, module = cached.get('spec'), cached.get('error'), cached.get('module')
|
||||
else:
|
||||
spec, error, module = None, None, None
|
||||
try:
|
||||
module = _import_tool_module(file_path, folder)
|
||||
spec = _spec_from_module(module, file_path)
|
||||
except BaseException as exc: # noqa: BLE001 - 单个工具坏掉不能拖垮内核
|
||||
module = None
|
||||
error = f'{type(exc).__name__}: {exc}'
|
||||
with _cache_lock:
|
||||
# 缓存里同时留着模块对象:执行时不必再 import 一遍
|
||||
_spec_cache[file_path] = {'mtime': mtime, 'spec': spec, 'error': error, 'module': module}
|
||||
|
||||
if error:
|
||||
errors.append({'file': os.path.basename(file_path), 'error': str(error)[:400]})
|
||||
continue
|
||||
if not spec:
|
||||
continue
|
||||
name = spec.get('name')
|
||||
# 内置工具优先:同名文件工具被替换(安卓上 shell/python_run 必须走进程内实现),
|
||||
# 但 file 字段仍沿用同名文件,保持和 Node 版一致的用户可见信息
|
||||
if name in BUILTIN_TOOLS:
|
||||
tools.append(_builtin_spec(name, file_path))
|
||||
emitted_builtins.add(name)
|
||||
else:
|
||||
tools.append(spec)
|
||||
|
||||
# 文件目录里没有、但内置提供的工具(比如用户把 tools/ 指到空目录)
|
||||
for name in BUILTIN_TOOLS:
|
||||
if name not in emitted_builtins:
|
||||
tools.append(_builtin_spec(name))
|
||||
|
||||
return {
|
||||
'tools': tools,
|
||||
'errors': errors,
|
||||
'python': {'bin': sys.executable or '<进程内>', 'prefix': []},
|
||||
}
|
||||
|
||||
|
||||
def _find_entry(name: str):
|
||||
"""按名字找工具(内置优先),返回 (spec, module);找不到返回 (None, None)。"""
|
||||
if name in BUILTIN_TOOLS:
|
||||
file_path = ''
|
||||
for candidate in python_files():
|
||||
if os.path.splitext(os.path.basename(candidate))[0] == name:
|
||||
file_path = candidate
|
||||
break
|
||||
return _builtin_spec(name, file_path), None
|
||||
found = discover_python_tools()
|
||||
for spec in found['tools']:
|
||||
if spec.get('name') == name:
|
||||
file_path = spec.get('_path') or ''
|
||||
with _cache_lock:
|
||||
module = (_spec_cache.get(file_path) or {}).get('module')
|
||||
if module is None and file_path:
|
||||
# 缓存里没模块(进程重启 / force 刷新过),重新 import 一次
|
||||
module = _import_tool_module(file_path, os.path.dirname(file_path))
|
||||
return spec, module
|
||||
return None, None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 执行
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def run_python_tool(name: str, args: dict) -> dict:
|
||||
"""
|
||||
执行一个进程内工具,返回 {'ok':bool, 'result':..., 'error':...}。
|
||||
结构与 Node 版 runPythonTool 的返回值保持兼容。
|
||||
"""
|
||||
spec, module = _find_entry(name)
|
||||
if not spec:
|
||||
raise RuntimeError(f'没有名为 {name} 的 Python 工具')
|
||||
|
||||
if spec.get('_builtin'):
|
||||
runner = BUILTIN_TOOLS[name]['run']
|
||||
else:
|
||||
if module is None:
|
||||
raise RuntimeError(f'工具 {name} 的模块已失效,请重新加载')
|
||||
runner = getattr(module, 'run')
|
||||
|
||||
payload = args if isinstance(args, dict) else {}
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
return {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if outcome is None:
|
||||
return {'ok': False, 'error': f'工具执行超时({TOOL_TIMEOUT_S}s)'}
|
||||
result = outcome
|
||||
# 工具可以像 _protocol 那样返回 {"ok":..,"result":..},也可以直接返回业务结果
|
||||
if isinstance(result, dict) and 'ok' in result:
|
||||
return {
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': result.get('result'),
|
||||
'error': result.get('error'),
|
||||
}
|
||||
return {'ok': True, 'result': result}
|
||||
|
||||
|
||||
def to_openai_tool(spec: dict) -> dict:
|
||||
"""转成 OpenAI tools 定义(与 Node 版 toOpenAITool 一致)。"""
|
||||
return {
|
||||
'type': 'function',
|
||||
'function': {
|
||||
'name': spec.get('name'),
|
||||
'description': spec.get('description') or spec.get('name'),
|
||||
'parameters': spec.get('parameters') or {'type': 'object', 'properties': {}},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def public_spec(spec: dict) -> dict:
|
||||
"""去掉内部字段(下划线开头),得到能直接塞进 JSON 响应的工具描述。"""
|
||||
return {k: v for k, v in spec.items() if not k.startswith('_')}
|
||||
|
||||
|
||||
def dump_specs_json(specs: list) -> str:
|
||||
"""调试用:把工具描述打成 JSON(避免直接 print 中文在窄编码终端炸掉)。"""
|
||||
return json.dumps([public_spec(s) for s in specs], ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 汇总 / 安全模式
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def list_all_tools(settings: dict) -> dict:
|
||||
"""汇总当前可用的全部工具(Python + MCP),与 Node 版 listAllTools 对齐。"""
|
||||
out = {'python': [], 'mcp': [], 'errors': [], 'pythonInfo': None}
|
||||
if (settings.get('tools') or {}).get('python', True) is not False:
|
||||
res = discover_python_tools()
|
||||
out['python'] = res['tools']
|
||||
out['errors'] = res['errors']
|
||||
out['pythonInfo'] = res['python']
|
||||
if (settings.get('tools') or {}).get('mcp', True) is not False:
|
||||
out['mcp'] = mcp_client.mcp_tool_defs()
|
||||
return out
|
||||
|
||||
|
||||
# 只读工具的名字特征,用来给"限制模式"生成一份保守的默认白名单
|
||||
READONLY_NAME = re.compile(
|
||||
r'^(read|list|get|search|open|find|fetch|show|describe|query|inspect|calc|now|web_fetch)',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def suggest_allowlist(tool_names: list) -> list:
|
||||
return [n for n in tool_names if READONLY_NAME.match((n.split('__') or [n])[-1] or n)]
|
||||
|
||||
|
||||
def apply_security(defs: list, settings: dict) -> list:
|
||||
"""按安全模式过滤工具定义(restricted 时只留白名单)。"""
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
if mode != 'restricted':
|
||||
return defs
|
||||
allow = set((settings.get('security') or {}).get('allow') or [])
|
||||
return [d for d in defs if d.get('function', {}).get('name') in allow]
|
||||
|
||||
|
||||
def node_tool_defs(settings: dict) -> list:
|
||||
"""
|
||||
会议里的 **Python 节点**当工具用。
|
||||
|
||||
★ 用户要求"智能体可以调用节点工具":在会议里写一个 Python 节点、
|
||||
在智能体节点上勾选它,这个智能体就能调用那段代码。
|
||||
|
||||
为什么走 settings 而不是直接传会议:工具定义是在 agent_loop 里
|
||||
统一组装的(它只拿得到 settings),把节点工具塞进 settings 是最短的路径 ——
|
||||
也为的是**只有一份组装逻辑**(分成两处就会像之前几次那样,
|
||||
改了这边忘了那边)。
|
||||
"""
|
||||
defs = []
|
||||
for t in (settings or {}).get('nodeTools') or []:
|
||||
name = str(t.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
defs.append({
|
||||
'type': 'function',
|
||||
'function': {
|
||||
'name': name,
|
||||
'description': str(t.get('description') or '会议里的自定义 Python 工具'),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'input': {
|
||||
'type': 'string',
|
||||
'description': '传给这个工具的文本输入',
|
||||
},
|
||||
},
|
||||
'required': [],
|
||||
},
|
||||
},
|
||||
})
|
||||
return defs
|
||||
|
||||
|
||||
def node_tool_names(settings: dict) -> set:
|
||||
return {str(t.get('name')) for t in ((settings or {}).get('nodeTools') or [])}
|
||||
|
||||
|
||||
def run_node_tool(name: str, args: dict, settings: dict) -> dict:
|
||||
"""执行一个会议节点工具"""
|
||||
for t in (settings or {}).get('nodeTools') or []:
|
||||
if str(t.get('name')) != name:
|
||||
continue
|
||||
import meeting as meeting_mod
|
||||
variables = t.get('variables') or {}
|
||||
logs = []
|
||||
out, err = meeting_mod.run_py_node(
|
||||
t.get('code') or '',
|
||||
str((args or {}).get('input') or ''),
|
||||
variables,
|
||||
t.get('node') or {},
|
||||
logs,
|
||||
)
|
||||
if err:
|
||||
return {'ok': False, 'error': err}
|
||||
return {'ok': True, 'output': out, 'logs': logs}
|
||||
return {'ok': False, 'error': f'没有这个节点工具:{name}'}
|
||||
|
||||
|
||||
def build_tool_defs(settings: dict) -> list:
|
||||
all_tools = list_all_tools(settings)
|
||||
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
|
||||
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
|
||||
defs = defs + node_tool_defs(settings)
|
||||
return apply_security(defs, settings)
|
||||
|
||||
|
||||
def execute_tool(name: str, args: dict, settings: dict) -> dict:
|
||||
"""
|
||||
执行任意工具(Python 或 MCP)。
|
||||
限制模式下即使模型硬编出工具名也不能执行(第二道拦截,与 Node 版一致)。
|
||||
"""
|
||||
if ((settings or {}).get('security') or {}).get('mode', 'open') == 'restricted':
|
||||
allow = ((settings or {}).get('security') or {}).get('allow') or []
|
||||
if name not in allow:
|
||||
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
|
||||
# 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义)
|
||||
if name in node_tool_names(settings):
|
||||
return run_node_tool(name, args, settings)
|
||||
if mcp_client.is_mcp_tool(name):
|
||||
res = mcp_client.call_mcp_tool(name, args)
|
||||
parts = []
|
||||
for item in (res or {}).get('content') or []:
|
||||
if item.get('type') == 'text':
|
||||
parts.append(item.get('text') or '')
|
||||
else:
|
||||
parts.append(f"[{item.get('type')}]")
|
||||
return {'ok': not (res or {}).get('isError'), 'result': '\n'.join(parts) or '(空结果)'}
|
||||
return run_python_tool(name, args)
|
||||
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,39 +0,0 @@
|
||||
修复:节点编辑点不了 + py 代码编辑的两个布局 bug
|
||||
|
||||
用户:"节点编辑点不了,py代码编辑有bug"
|
||||
|
||||
【1. 节点编辑点不了】
|
||||
根因是**挂载顺序**:
|
||||
blockEdit?.let { ... return@MeetingEditorScreen } ← 积木编辑器
|
||||
if (showNodeMgr) { ... return@MeetingEditorScreen } ← 节点管理(全屏)
|
||||
if (editCode.isNotEmpty() || ...) { ... } ← 代码编辑(全屏)
|
||||
|
||||
onEdit 读完源码后只设了 editCode,**没关 showNodeMgr** ——
|
||||
管理页在它上面,先 return 掉了,代码编辑页永远轮不到渲染。
|
||||
表现就是"点了没反应"(其实状态都对了,只是没机会画)。
|
||||
|
||||
修:onNew / onEdit 里都补上 showNodeMgr = false,并写清楚为什么
|
||||
(这类"界面按顺序 return"的写法,谁在上面谁优先,下面那些必须先关掉上面的)。
|
||||
|
||||
【2. py 代码编辑:软换行】
|
||||
截图里 ` else:` 被折成两行、缩进全乱 —— **Python 的缩进就是语法**,
|
||||
折行了根本读不了。
|
||||
|
||||
本来想换 BasicTextField(能直接 softWrap = false),但这个 Compose 版本
|
||||
(BOM 2024.09.03)里它的经典重载选不中,只会落到新的 state 版。
|
||||
|
||||
改用等价做法:**把输入框塞进一个足够宽的横向滚动容器** ——
|
||||
宽度给到 2400dp,正常代码行到不了那么长,自然就不折了;
|
||||
手指左右划能看全,光标定位照常。
|
||||
|
||||
【3. py 代码编辑:补全条被挤到屏幕外】
|
||||
代码框原来只写了 heightIn(min=...),没有上限 ——
|
||||
文件一长,框就长到屏幕外,把下面的补全条顶出去了,**够不着**。
|
||||
|
||||
修:给代码框加 max 高度(min + 160dp),补全条固定在它下面。
|
||||
|
||||
【验证】
|
||||
- APK 构建通过、装机通过
|
||||
- 截图确认:「编辑」能打开代码页;长行不折行、缩进正常;
|
||||
底部补全条可见(ctx.log / ctx.set_var / ctx.get_var …)
|
||||
- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致
|
||||
@@ -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
|
||||
792
豆鲍/AGENTS.md
Normal file
@@ -0,0 +1,792 @@
|
||||
# 项目约定
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
|
||||
---
|
||||
|
||||
# 代码托管
|
||||
|
||||
## 两个 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` 表记标记 —— **别写"每次启动都跑"的迁移**,
|
||||
它会把手写的新数据也搬走。
|
||||
- **独自一人的地点禁言**:内核 `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。
|
||||
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")
|
||||
@@ -20,8 +20,18 @@ android {
|
||||
* 代价:上不了应用商店;部分新系统行为按旧版走(对我们这种本地工具无所谓)。
|
||||
*/
|
||||
targetSdk = 28
|
||||
versionCode = 3
|
||||
versionName = "0.3.0"
|
||||
/**
|
||||
* 版本号跟着 release 标签走。
|
||||
*
|
||||
* ★ 之前一直停在 0.3.0,而 git 标签已经从 1.0 走到 v2.0 了 ——
|
||||
* 装到手机上根本分不清装的是哪一版("我装的是不是最新的"这个
|
||||
* 最基本的问题都答不了)。发 release 前必须对上。
|
||||
*
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 366
|
||||
versionName = "2.0.166"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -29,14 +39,77 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lint 不挡 release 构建。
|
||||
*
|
||||
* ★ 唯一让它报错的是 `targetSdk = 28` 那条:
|
||||
*
|
||||
* Error: Google Play requires that apps target API level 33 or higher.
|
||||
* [ExpiredTargetSdkVersion]
|
||||
*
|
||||
* 而 **28 是必须的**,不能改 —— Android 10 起 targetSdk>=29 的应用
|
||||
* 不允许执行自己数据目录里的二进制(W^X 限制),而 bash / python /
|
||||
* dpkg 全在 /data/data/<包名>/files/usr 里。Termux 自己也是锁 28
|
||||
* 才活下来的。这条 lint 检查针对的是"上架 Google Play",而我们
|
||||
* 这个 App 本来就上不了架(自签证书 + 这个 targetSdk)。
|
||||
*
|
||||
* ★ 设 `abortOnError = false` 而不是 `checkReleaseBuilds = false`:
|
||||
* lint **照常跑**、报告照常生成,只是不因为这一条把构建打断。
|
||||
* 别的真问题仍然看得到。
|
||||
*/
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名。
|
||||
*
|
||||
* ★ 用的是**原来那个 debug 证书**(fingerprint 83:28:15:D6…),
|
||||
* 只是把它**拷进了仓库**,并且**显式开了 v1/v2/v3**。
|
||||
*
|
||||
* 为什么这么做(踩过两次,记下来):
|
||||
*
|
||||
* 1. **不能随便换证书**。Android 不允许同包名不同签名覆盖安装 ——
|
||||
* 换了之后用户必须**先卸载**(数据全丢)。
|
||||
* 我第一次"修签名问题"时顺手换了一把新证书,结果老用户装不上,
|
||||
* 报"已安装了签名冲突的应用"。**修 A 问题不能引入 B 问题。**
|
||||
*
|
||||
* 2. **缺 v1(JAR)签名会让很多安装器拒绝**。Android 7+ 自己装没问题,
|
||||
* 但从远程传过去再装(MT 管理器 / UU远程 之类)会报
|
||||
* "解析失败:安装包没有签名文件"。所以 v1/v2/v3 全开。
|
||||
*
|
||||
* 3. **debug 证书默认在 ~/.android/ 里,换台机器就变**。
|
||||
* 拷进仓库(连密码一起)之后,**哪台机器构建出来的指纹都一样**,
|
||||
* 能互相覆盖安装。
|
||||
*
|
||||
* ★ 密码是 debug 证书的标准密码,**它不是秘密**。
|
||||
* 自签证书只保证"指纹稳定、能覆盖安装",不证明"是谁发的"。
|
||||
*/
|
||||
signingConfigs {
|
||||
create("doubao") {
|
||||
storeFile = file("../doubao-release.jks")
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
enableV1Signing = true
|
||||
enableV2Signing = true
|
||||
enableV3Signing = true
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
debug {
|
||||
// debug 包也用同一把 —— 本地调试的包和发出去的包能互相覆盖安装
|
||||
signingConfig = signingConfigs.getByName("doubao")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -108,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 @@
|
||||
4
|
||||
|
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();
|
||||
})();
|
||||
1185
豆鲍/android/app/src/main/assets/ui-packs/galgame/game.js
Normal file
124
豆鲍/android/app/src/main/assets/ui-packs/galgame/index.html
Normal file
@@ -0,0 +1,124 @@
|
||||
<!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">
|
||||
<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 class="quick" id="quick"></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) -->
|
||||
<nav class="actions">
|
||||
<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>
|
||||
</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();
|
||||
})();
|
||||
1660
豆鲍/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
|
||||
}
|
||||
866
豆鲍/android/app/src/main/assets/ui-packs/ui-sdk/sdk.js
Normal file
@@ -0,0 +1,866 @@
|
||||
/**
|
||||
* 小人间 · 游戏界面 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() {
|
||||
const 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.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;
|
||||
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}`,
|
||||
);
|
||||
} catch (err) {
|
||||
if (flushing) break;
|
||||
idle += 1;
|
||||
if (idle > 30) throw err;
|
||||
await sleep(400);
|
||||
continue;
|
||||
}
|
||||
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 分钟没有新内容,已停止等待');
|
||||
await sleep(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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
|
||||
/**
|
||||
* 内核监听的端口。
|
||||
*
|
||||
* ## 为什么要有这个单例
|
||||
*
|
||||
* 端口原来是 `MainActivity` 里一个局部变量(`client.baseUrl` 也在那儿设)。
|
||||
* 但 `NativeBridge` 也需要打内核的接口 —— `end_conversation` 要
|
||||
* `PATCH /api/conversations/<id>` 把"这次对话已结束"落盘,而
|
||||
* `NativeBridge` 在**内核的工作线程**上被调,拿不到 Activity 的局部变量,
|
||||
* 也不该去依赖 UI 层的 `KernelClient`。
|
||||
*
|
||||
* 所以放一个进程级的单例:`MainActivity` 启动内核后写一次,别处只读。
|
||||
*/
|
||||
object KernelHost {
|
||||
|
||||
/** 内核端口;0 表示还没起来 */
|
||||
@Volatile
|
||||
var port: Int = 0
|
||||
|
||||
/** 内核起来之后由 MainActivity 调 */
|
||||
fun set(p: Int) {
|
||||
port = p
|
||||
}
|
||||
|
||||
fun baseUrl(): String = if (port > 0) "http://127.0.0.1:$port" else ""
|
||||
}
|
||||
|
||||
/** 全项目统一的 JSON 请求体类型(别在各处手写字符串,写错一个字符就是 415) */
|
||||
val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType()
|
||||
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)
|
||||
@@ -70,6 +92,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (port != null && port > 0) {
|
||||
client.baseUrl = "http://127.0.0.1:$port"
|
||||
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||
KernelHost.set(port)
|
||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||
withContext(Dispatchers.IO) {
|
||||
@@ -0,0 +1,912 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.net.Uri
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.data.AppTimeouts
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 暴露给 Python 内核的原生能力。
|
||||
*
|
||||
* Chaquopy 允许 Python 直接调这个类的方法(`from java import jclass` 那套),
|
||||
* 所以内核里的 `device` 工具、剪贴板钩子、选文件钩子都落到这里。
|
||||
*
|
||||
* 线程约定:device() 可能阻塞几秒(采传感器、等定位),
|
||||
* 它只会在内核的 HTTP 工作线程上被调用,**不会**卡住 UI 线程。
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
/**
|
||||
* 一次最多列多少个 App。
|
||||
*
|
||||
* ★ 必须有上限:手机上有 100~300 个 App,全塞给模型光这一条就几千 token,
|
||||
* 而且它多半只需要"找那一个"。要全量就用 query 过滤。
|
||||
*/
|
||||
private val APP_LIST_MAX = 120
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一的入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
JSONObject(payloadJson)
|
||||
} catch (e: Exception) {
|
||||
JSONObject()
|
||||
}
|
||||
val action = req.optString("action", "info")
|
||||
return try {
|
||||
when (action) {
|
||||
"info" -> deviceInfo()
|
||||
"battery" -> batteryInfo()
|
||||
"location" -> locationInfo()
|
||||
"sensors" -> sensorList()
|
||||
"sensor" -> sensorSample(req.optString("sensor"), req.optDouble("duration", 1.5))
|
||||
"clipboard_get" -> JSONObject().put("text", readClipboard())
|
||||
"clipboard_set" -> {
|
||||
setClipboard(req.optString("text"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// 内置 Termux:完整 Linux 用户态(真 bash / 真 pkg / 真子进程)
|
||||
"termux_available" -> JSONObject().put("installed", TermuxShell.isReady(activity))
|
||||
"termux_run" -> TermuxShell.run(
|
||||
activity,
|
||||
req.optString("command"),
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
|
||||
//
|
||||
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
|
||||
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
|
||||
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
|
||||
"ui_screen" -> uiScreen(req)
|
||||
// 再打开一个存下来的界面(用户要求"AI 写的界面可以再点开")
|
||||
"ui_screen_reopen" -> uiScreenReopen(req)
|
||||
"ui_screen_list" -> uiScreenList(req)
|
||||
"ui_screen_delete" -> uiScreenDelete(req)
|
||||
"ui_dialog" -> uiDialog(req)
|
||||
"end_conversation" -> endConversation(req)
|
||||
// AI 主动往会话里发一条消息(tools/send_message.py)
|
||||
"session_message" -> sessionMessage(req)
|
||||
// AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult)
|
||||
"ui_result" -> pushUiResult(req)
|
||||
// ---- 操作手机:通知 / 打开 App / 音量 ----
|
||||
"notifications" -> notifications(req)
|
||||
"notification_access" -> JSONObject()
|
||||
.put("granted", PhoneOps.hasNotificationAccess(activity))
|
||||
.put("kept", DoubaoNotificationListener.count())
|
||||
"notification_settings" -> {
|
||||
// 带用户去开「通知使用权」—— Android 没有这个权限的运行时申请弹窗,
|
||||
// 只能跳到设置页让他自己勾
|
||||
activity.startActivity(PhoneOps.notificationAccessIntent())
|
||||
JSONObject().put("ok", true).put("opened", "通知使用权设置页")
|
||||
}
|
||||
"notification_clear" -> {
|
||||
DoubaoNotificationListener.clear()
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
// ★ AI 主动发一条通知(用户要求"还可以发送通知")
|
||||
"notification_post" -> {
|
||||
val title = req.optString("title")
|
||||
val text = req.optString("text")
|
||||
if (title.isBlank() && text.isBlank()) {
|
||||
JSONObject().put("error", "title 和 text 至少要给一个")
|
||||
} else {
|
||||
PhoneOps.postNotification(
|
||||
activity, title, text, req.optBoolean("autoCancel", true),
|
||||
)
|
||||
}
|
||||
}
|
||||
"apps" -> appsList(req)
|
||||
"app_launch" -> appLaunch(req)
|
||||
// ★ 预设快捷入口(用户要求"预设几个比如微信对话,支付宝菜鸟")
|
||||
"app_shortcuts" -> {
|
||||
val arr = JSONArray()
|
||||
AppShortcuts.all(activity).forEach { m ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("id", m["id"])
|
||||
.put("label", m["label"])
|
||||
.put("app", m["app"])
|
||||
.put("installed", m["installed"])
|
||||
.put("keywords", JSONArray(m["keywords"] as List<*>)),
|
||||
)
|
||||
}
|
||||
JSONObject().put("shortcuts", arr)
|
||||
}
|
||||
"app_shortcut_open" -> {
|
||||
val key = req.optString("shortcut").ifBlank { req.optString("name") }
|
||||
val hit = AppShortcuts.find(key)
|
||||
if (hit == null) {
|
||||
JSONObject()
|
||||
.put("error", "没有叫「$key」的预设快捷入口")
|
||||
.put("hint", "可以用的有:" + AppShortcuts.ids().joinToString("、"))
|
||||
} else {
|
||||
AppShortcuts.run(activity, hit)
|
||||
}
|
||||
}
|
||||
"volume" -> JSONObject().put("state", PhoneOps.volumeState(activity))
|
||||
"volume_set" -> PhoneOps.setVolume(
|
||||
activity,
|
||||
req.optString("stream", "music"),
|
||||
req.optString("mode", "set"),
|
||||
req.optInt("value", 0),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 主动往**当前会话**里发一条消息(`tools/send_message.py`)。
|
||||
*
|
||||
* 走内核的 `/api/session-message` —— 那边负责落进会话历史、
|
||||
* 以及**两道防死循环的闸**(嵌套深度、每会话条数)。
|
||||
*
|
||||
* ★ 为什么闸不在 Kotlin 这层做:内核才有会话上下文和那两处的计数。
|
||||
* 这层只转发,判断留给一处,避免两个地方规则不一致。
|
||||
*/
|
||||
private fun sessionMessage(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId").trim()
|
||||
val text = req.optString("text").trim()
|
||||
if (conv.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
if (text.isEmpty()) return JSONObject().put("error", "text 是空的")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("conversationId", conv)
|
||||
.put("text", text)
|
||||
.put("role", req.optString("role", "user"))
|
||||
.put("reply", req.optBoolean("reply", false))
|
||||
.put("depth", req.optInt("depth", 1))
|
||||
val resp = kernelPost("/api/session-message", body) ?: return JSONObject()
|
||||
.put("error", "内核没响应,消息没发出去")
|
||||
// 内核把"闸门拒绝"也放在 error 字段里(HTTP 200 + error)——
|
||||
// 所以这里原样透传,别把它当成成功。
|
||||
resp
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。**
|
||||
*
|
||||
* AI 在 `show_ui` 的 HTML 里写 `Doubao.sendToAi('值')`,那个值会打到这里,
|
||||
* 然后 POST 到内核的 `/api/ui-result` 排队。
|
||||
* 下一轮对话开始时,`agent_loop` 会把队里的东西作为上下文交给模型 ——
|
||||
* 于是模型**真的知道**用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 为什么经内核排队、而不是让 Kotlin 直接起一轮对话:
|
||||
* 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型既慢又费 token,
|
||||
* 而且用户还没说完。排队 → 下一次说话时一起带上,语义上也更对:
|
||||
* **界面上的选择是提问的一部分,不是提问本身**。
|
||||
*
|
||||
* ★ 失败不抛异常,只回 ok:false:这是"用户点了一下按钮",
|
||||
* 内核没起来不该让 App 崩(用户会看到提示,也能再点一次)。
|
||||
*/
|
||||
private fun pushUiResult(req: JSONObject): JSONObject {
|
||||
val value = req.optString("value").trim()
|
||||
val convId = req.optString("conversationId").trim()
|
||||
if (value.isEmpty()) return JSONObject().put("error", "value 是空的")
|
||||
if (convId.isEmpty()) return JSONObject().put("error", "缺少 conversationId")
|
||||
return try {
|
||||
val body = JSONObject().put("conversationId", convId).put("value", value)
|
||||
val resp = kernelPost("/api/ui-result", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,这次选择没能送出去")
|
||||
} else {
|
||||
JSONObject().put("ok", true).put("queued", resp.optInt("queued"))
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||
*
|
||||
* [wait] 由工具参数决定:
|
||||
* · false(默认)——**不阻塞**,弹出来就返回,用户看完自己关
|
||||
* · true ——**等用户操作**:点了回传按钮或关掉界面才返回,
|
||||
* 用户点的值原样带回给模型
|
||||
*
|
||||
* ★ 等待模式下要**先备好闩再弹** —— 顺序反了的话,
|
||||
* 用户手快先点了(界面已经显示、按钮就在那儿),
|
||||
* `countDown()` 打在空闩上,然后我们才开始等,直接等满超时。
|
||||
* 这类"用户比代码快"的竞态在真机上很容易出现。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**(用户要求"AI 询问界面不要限时")。
|
||||
* 想限时得模型显式传 timeout。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
val wait = req.optBoolean("wait", false)
|
||||
val title = req.optString("title")
|
||||
val fullHtml = req.optBoolean("full_html", false)
|
||||
val convId = req.optString("conversationId")
|
||||
|
||||
// ★★ 先存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
// 用户的原话:"AI 写的界面可以再点开"。
|
||||
// 以前界面只活在内存里,一关(或退出 App)就没了;想再看只能让 AI
|
||||
// 重新生成,而重新生成的内容不一定一样(模型有随机性)——
|
||||
// 用户会觉得"我明明看过的东西怎么变了"。
|
||||
//
|
||||
// 存失败不影响弹出(用户至少还能看这一眼),所以不抛异常。
|
||||
val saved = runCatching {
|
||||
AiSurface.saveScreen(activity, html, title, fullHtml, convId)
|
||||
}.getOrNull()
|
||||
val screenId = saved?.optString("id").orEmpty()
|
||||
|
||||
if (wait) AiSurface.armScreenLatch()
|
||||
return AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = convId,
|
||||
wait = wait,
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
screenId = screenId,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 再打开一个存下来的界面。
|
||||
*
|
||||
* ★ 和 [uiScreen] 的区别:那个是"AI 刚写了一个新界面",
|
||||
* 这个是"用户想再看一遍**以前那个**"。后者不需要模型参与 ——
|
||||
* 内容就在磁盘上,读出来直接显示。
|
||||
*/
|
||||
private fun uiScreenReopen(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
val html = AiSurface.readScreen(activity, id)
|
||||
?: return JSONObject().put("error", "这个界面已经不在了(可能被清理或删除)")
|
||||
|
||||
// 从索引里把标题 / fullHtml 取回来,不然重开之后标题会变成"AI 界面"
|
||||
var title = ""
|
||||
var fullHtml = false
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") == id) {
|
||||
title = it.optString("title")
|
||||
fullHtml = it.optBoolean("fullHtml")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
AiSurface.showScreen(
|
||||
html = html,
|
||||
title = title,
|
||||
fullHtml = fullHtml,
|
||||
conversationId = req.optString("conversationId"),
|
||||
wait = false,
|
||||
screenId = id,
|
||||
)
|
||||
return JSONObject().put("ok", true).put("screenId", id)
|
||||
}
|
||||
|
||||
/** 列出存下来的界面(消息操作栏的「界面」按钮用它) */
|
||||
private fun uiScreenList(req: JSONObject): JSONObject {
|
||||
val conv = req.optString("conversationId")
|
||||
val arr = AiSurface.loadScreenIndex(activity)
|
||||
val out = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (conv.isNotBlank() && it.optString("conversationId") != conv) continue
|
||||
out.put(it)
|
||||
}
|
||||
return JSONObject().put("screens", out)
|
||||
}
|
||||
|
||||
private fun uiScreenDelete(req: JSONObject): JSONObject {
|
||||
val id = req.optString("screenId")
|
||||
if (id.isBlank()) return JSONObject().put("error", "缺少 screenId")
|
||||
AiSurface.deleteScreen(activity, id)
|
||||
return JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*
|
||||
* ★ timeoutMs 缺省 / <= 0 = **不限时**。用户的原话是"AI 询问界面不要限时":
|
||||
* 他在思考的时候弹窗到点自己消失、模型还收到 timeout 当成"用户不理我",
|
||||
* 这一轮就答非所问了。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
if (question.isBlank()) return JSONObject().put("error", "question 是空的")
|
||||
|
||||
val options = mutableListOf<AiSurface.Option>()
|
||||
val arr = req.optJSONArray("options") ?: JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val label = o.optString("label").ifBlank { o.optString("value") }
|
||||
if (label.isBlank()) continue
|
||||
options.add(
|
||||
AiSurface.Option(
|
||||
label = label,
|
||||
value = o.optString("value").ifBlank { label },
|
||||
description = o.optString("description"),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (options.isEmpty()) return JSONObject().put("error", "至少要有一个选项")
|
||||
|
||||
return AiSurface.ask(
|
||||
question = question,
|
||||
options = options,
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 0L),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 永久结束当前对话(tools/end_conversation.py)。
|
||||
*
|
||||
* ★ 必须**落盘**(PATCH /api/conversations/<id>),不能只改界面状态 ——
|
||||
* 界面状态一刷新就没了,用户重进会看到一个能继续输入的框,
|
||||
* 而模型以为自己已经结束了。两边状态不一致是这类功能最容易出的问题。
|
||||
*/
|
||||
private fun endConversation(req: JSONObject): JSONObject {
|
||||
val convId = req.optString("conversationId").ifBlank {
|
||||
return JSONObject().put("error", "没有 conversationId,无法结束对话")
|
||||
}
|
||||
val reason = req.optString("reason")
|
||||
val summary = req.optString("summary")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("ended", true)
|
||||
.put("endedAt", System.currentTimeMillis())
|
||||
.put("endedReason", reason)
|
||||
if (summary.isNotBlank()) body.put("endedSummary", summary)
|
||||
// 走内核自己的 HTTP 接口 —— 这是唯一一条"由 Kotlin 写内核数据"的既有通道
|
||||
val resp = kernelPatch("/api/conversations/$convId", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,对话状态没写进去")
|
||||
} else {
|
||||
AiSurface.markEnded(convId)
|
||||
JSONObject().put("ok", true).put("conversationId", convId)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH 一下内核的接口。
|
||||
*
|
||||
* ★ 这里**不能用 KernelClient** —— 那是 ViewModel 层的东西,NativeBridge
|
||||
* 拿不到(而且它跑在内核工作线程上,不该依赖 UI 层的对象)。
|
||||
* 直接用 OkHttp 打本机端口,和内核在同一个进程里,开销可以忽略。
|
||||
*
|
||||
* 端口从 [KernelHost.port] 取(内核起来之后写进去的)。
|
||||
*/
|
||||
private fun kernelPatch(path: String, body: JSONObject): String? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.patch(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
client.newCall(req).execute().use { resp ->
|
||||
return if (resp.isSuccessful) resp.body?.string() else null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 一下内核的接口,返回解析好的 JSON;失败返回 null。
|
||||
*
|
||||
* ★ 和 [kernelPatch] 共用同一套"直接打本机端口"的做法 ——
|
||||
* 不用 `KernelClient`(那是 ViewModel 层的东西,NativeBridge 拿不到,
|
||||
* 而且这里是内核工作线程,不该依赖 UI 层对象)。
|
||||
*/
|
||||
private fun kernelPost(path: String, body: JSONObject): JSONObject? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.post(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
return client.newCall(req).execute().use { resp ->
|
||||
if (!resp.isSuccessful) return null
|
||||
val text = resp.body?.string() ?: return null
|
||||
runCatching { JSONObject(text) }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 App。
|
||||
*
|
||||
* ★ 没传 query 就返回全部(截前 [APP_LIST_MAX] 个)——
|
||||
* 模型可以先看一眼有哪些 App,再决定开哪个。
|
||||
*/
|
||||
private fun appsList(req: JSONObject): JSONObject {
|
||||
val query = req.optString("query").trim()
|
||||
val all = PhoneOps.installedApps(activity)
|
||||
val out = JSONArray()
|
||||
if (query.isBlank()) {
|
||||
all.take(APP_LIST_MAX).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("apps", out)
|
||||
}
|
||||
val q = query.lowercase()
|
||||
all.filter {
|
||||
it.first.lowercase().contains(q) || it.second.lowercase().contains(q)
|
||||
}.take(30).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("matched", out.length()).put("apps", out)
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个 App。
|
||||
*
|
||||
* ★ 找不到时**明确报错并给出相近的名字** —— 让模型能自己改一个再来,
|
||||
* 而不是回一个干巴巴的"失败"(那样它只会反复重试同一个错名字)。
|
||||
*/
|
||||
private fun appLaunch(req: JSONObject): JSONObject {
|
||||
// 已经知道包名和 Activity(从上一步 app_list 拿到的)就直接开,省一次全表扫描
|
||||
val pkg = req.optString("package").trim()
|
||||
val cls = req.optString("activity").trim()
|
||||
if (pkg.isNotEmpty()) {
|
||||
// ★ 只给包名不给 activity 是**最常见的用法**(比如"打开微信"),
|
||||
// 这时候自己去查它的 launcher activity —— 让模型去记
|
||||
// `com.tencent.mm.ui.LauncherUI` 这种名字既没必要也容易记错。
|
||||
val realCls = cls.ifEmpty { AppShortcuts.mainActivityOf(activity, pkg) }
|
||||
if (realCls.isEmpty()) {
|
||||
return JSONObject()
|
||||
.put("error", "找不到 $pkg 的启动入口(可能没装,或者它没有可启动的界面)")
|
||||
}
|
||||
// ★ 有 activity 时先试"直接拉起那个 Activity"(能直达指定页面),
|
||||
// 失败再退回标准 launcher 方式 —— App 内部 Activity 常常没导出,
|
||||
// 直接拉会被系统拒。
|
||||
if (cls.isNotEmpty()) {
|
||||
val directErr = PhoneOps.launchActivity(activity, pkg, cls)
|
||||
if (directErr == null) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", cls).put("how", "direct")
|
||||
}
|
||||
// 直拉失败就退回标准方式;两者都失败才报错
|
||||
if (PhoneOps.launchApp(activity, pkg, realCls)) {
|
||||
return JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
.put("note", "没法直达指定页面($directErr),已经打开 App 主界面")
|
||||
}
|
||||
// ★ 两边都失败:错误里**两个原因都要说**。
|
||||
// 只说直拉那个的话会误导 —— 用户/模型以为是"activity 名字写错了",
|
||||
// 其实退回主界面也失败了(那才是更严重的问题)。
|
||||
return JSONObject().put(
|
||||
"error",
|
||||
"启动 $pkg 失败:直达指定页面不行($directErr)," +
|
||||
"退回主界面也不行($realCls 打不开)。这个 App 可能被停用了。",
|
||||
)
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, pkg, realCls)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true).put("package", pkg)
|
||||
.put("activity", realCls).put("how", "launcher")
|
||||
} else {
|
||||
JSONObject().put("error", "启动 $pkg 失败(系统拒绝了,可能被停用)")
|
||||
}
|
||||
}
|
||||
|
||||
val name = req.optString("name").trim()
|
||||
if (name.isEmpty()) {
|
||||
return JSONObject().put("error", "至少要给 name(App 名字)或 package+activity")
|
||||
}
|
||||
val hit = PhoneOps.findApp(activity, name)
|
||||
?: run {
|
||||
// 给几个名字相近的当提示
|
||||
val q = name.lowercase()
|
||||
val near = PhoneOps.installedApps(activity)
|
||||
.filter { it.first.lowercase().contains(q.take(2)) }
|
||||
.take(5)
|
||||
.map { it.first }
|
||||
return JSONObject()
|
||||
.put("error", "没找到叫「$name」的 App")
|
||||
.put("hint", if (near.isEmpty()) {
|
||||
// ★ 这里写的 action 名必须和 tools/apps.py 里 enum 的一致。
|
||||
// 第一版写的 `app_list` —— 那个名字不存在,模型照着调会失败。
|
||||
"可以用 action=list 看看装了哪些 App"
|
||||
} else {
|
||||
"名字相近的有:" + near.joinToString("、") + "。换个名字再试"
|
||||
})
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, hit.second, hit.third)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true)
|
||||
.put("label", hit.first)
|
||||
.put("package", hit.second)
|
||||
} else {
|
||||
JSONObject().put("error", "找到「${hit.first}」但启动失败(系统拒绝了)")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读通知。
|
||||
*
|
||||
* ★ 权限没开时**返回明确错误**,不是空列表。
|
||||
* 返回空列表的话模型会说"最近没有通知" —— 那是**错的**
|
||||
* (明明有几条,只是我们读不到),用户会被误导。
|
||||
*/
|
||||
private fun notifications(req: JSONObject): JSONObject {
|
||||
if (!PhoneOps.hasNotificationAccess(activity)) {
|
||||
return JSONObject()
|
||||
.put("error", "没有「通知使用权」,读不到任何通知")
|
||||
.put("granted", false)
|
||||
.put(
|
||||
"hint",
|
||||
"这个权限安卓不给运行时申请,必须用户手动开:" +
|
||||
"设置 → 通知 → 通知使用权(或「通知读取权限」)→ 找到本 App 打开。" +
|
||||
"调用 action=notification_settings 可以直接跳到那个设置页。",
|
||||
)
|
||||
}
|
||||
val arr = DoubaoNotificationListener.recent(
|
||||
limit = req.optInt("limit", 20),
|
||||
onlyAlive = req.optBoolean("onlyAlive", false),
|
||||
query = req.optString("query"),
|
||||
)
|
||||
return JSONObject()
|
||||
.put("granted", true)
|
||||
.put("count", arr.length())
|
||||
.put("notifications", arr)
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
val totalGb = stat.totalBytes / 1024.0 / 1024.0 / 1024.0
|
||||
return JSONObject()
|
||||
.put("platform", "Android")
|
||||
.put("model", Build.MODEL)
|
||||
.put("manufacturer", Build.MANUFACTURER)
|
||||
.put("brand", Build.BRAND)
|
||||
.put("device", Build.DEVICE)
|
||||
.put("android", Build.VERSION.RELEASE)
|
||||
.put("sdk", Build.VERSION.SDK_INT)
|
||||
.put("abis", JSONArray(Build.SUPPORTED_ABIS.toList()))
|
||||
.put("storage_free_gb", String.format("%.1f", freeGb))
|
||||
.put("storage_total_gb", String.format("%.1f", totalGb))
|
||||
.put("screen", screenInfo())
|
||||
.put("battery", batteryInfo())
|
||||
}
|
||||
|
||||
private fun screenInfo(): String {
|
||||
val metrics = activity.resources.displayMetrics
|
||||
return "${metrics.widthPixels}x${metrics.heightPixels} @${metrics.density}x"
|
||||
}
|
||||
|
||||
private fun batteryInfo(): JSONObject {
|
||||
val bm = activity.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
|
||||
return JSONObject()
|
||||
.put("level_percent", bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1)
|
||||
.put("charging", bm?.isCharging ?: false)
|
||||
}
|
||||
|
||||
/** 定位:先拿最后已知位置,拿不到就等一次单次更新(最多 8 秒) */
|
||||
private fun locationInfo(): JSONObject {
|
||||
val lm = activity.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
|
||||
?: return JSONObject().put("error", "没有 LocationManager")
|
||||
val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
|
||||
var best: Location? = null
|
||||
for (p in providers) {
|
||||
try {
|
||||
if (!lm.isProviderEnabled(p)) continue
|
||||
val loc = lm.getLastKnownLocation(p) ?: continue
|
||||
if (best == null || loc.time > best!!.time) best = loc
|
||||
} catch (t: SecurityException) {
|
||||
return JSONObject().put("error", "缺少定位权限(ACCESS_FINE_LOCATION)")
|
||||
} catch (_: Throwable) {
|
||||
// 某些机型会抛 IllegalArgumentException,忽略继续
|
||||
}
|
||||
}
|
||||
if (best == null) {
|
||||
val latch = CountDownLatch(1)
|
||||
var fresh: Location? = null
|
||||
val listener = object : android.location.LocationListener {
|
||||
override fun onLocationChanged(location: Location) {
|
||||
fresh = location
|
||||
latch.countDown()
|
||||
}
|
||||
// 老 API 要求实现,留着空实现
|
||||
override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
|
||||
override fun onProviderEnabled(provider: String) {}
|
||||
override fun onProviderDisabled(provider: String) {}
|
||||
}
|
||||
try {
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, listener)
|
||||
} catch (_: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(8, TimeUnit.SECONDS)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
} finally {
|
||||
try {
|
||||
lm.removeUpdates(listener)
|
||||
} catch (_: Throwable) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
best = fresh
|
||||
}
|
||||
if (best == null) {
|
||||
return JSONObject()
|
||||
.put("available", false)
|
||||
.put("hint", "没拿到定位:确认已开定位开关、已授予权限、或在室内 GPS 信号差时稍后再试")
|
||||
}
|
||||
return JSONObject()
|
||||
.put("available", true)
|
||||
.put("latitude", best!!.latitude)
|
||||
.put("longitude", best!!.longitude)
|
||||
.put("accuracy_m", best!!.accuracy.toDouble())
|
||||
.put("provider", best!!.provider)
|
||||
.put("age_seconds", (System.currentTimeMillis() - best!!.time) / 1000.0)
|
||||
}
|
||||
|
||||
private val keywordToType = mapOf(
|
||||
"accelerometer" to Sensor.TYPE_ACCELEROMETER,
|
||||
"gyroscope" to Sensor.TYPE_GYROSCOPE,
|
||||
"magnetic" to Sensor.TYPE_MAGNETIC_FIELD,
|
||||
"light" to Sensor.TYPE_LIGHT,
|
||||
"pressure" to Sensor.TYPE_PRESSURE,
|
||||
"proximity" to Sensor.TYPE_PROXIMITY,
|
||||
"gravity" to Sensor.TYPE_GRAVITY,
|
||||
"linear_acceleration" to Sensor.TYPE_LINEAR_ACCELERATION,
|
||||
"rotation_vector" to Sensor.TYPE_ROTATION_VECTOR,
|
||||
"step_counter" to Sensor.TYPE_STEP_COUNTER,
|
||||
"humidity" to Sensor.TYPE_RELATIVE_HUMIDITY,
|
||||
"temperature" to Sensor.TYPE_AMBIENT_TEMPERATURE,
|
||||
"game_rotation_vector" to Sensor.TYPE_GAME_ROTATION_VECTOR,
|
||||
)
|
||||
|
||||
private fun sensorManager(): SensorManager? =
|
||||
activity.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
|
||||
|
||||
private fun sensorList(): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val arr = JSONArray()
|
||||
for (s in sm.getSensorList(Sensor.TYPE_ALL)) {
|
||||
val key = keywordToType.entries.firstOrNull { it.value == s.type }?.key
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("key", key ?: "type_${s.type}")
|
||||
.put("name", s.name)
|
||||
.put("vendor", s.vendor)
|
||||
.put("type", s.type)
|
||||
.put("power_ma", s.power.toDouble()),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("count", arr.length()).put("sensors", arr)
|
||||
}
|
||||
|
||||
/** 采样:注册监听 duration 秒,返回样本序列与统计 */
|
||||
private fun sensorSample(key: String, duration: Double): JSONObject {
|
||||
val sm = sensorManager() ?: return JSONObject().put("error", "没有 SensorManager")
|
||||
val name = key.ifBlank { "accelerometer" }
|
||||
val type = keywordToType[name] ?: return JSONObject()
|
||||
.put("error", "不认识的传感器:$name(可用:${keywordToType.keys.joinToString(", ")})")
|
||||
val sensor = sm.getDefaultSensor(type)
|
||||
?: return JSONObject().put("error", "这台设备没有 $name 传感器")
|
||||
|
||||
val seconds = duration.coerceIn(0.2, 10.0)
|
||||
val samples = mutableListOf<FloatArray>()
|
||||
val latch = CountDownLatch(1)
|
||||
val listener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
if (samples.size < 500) samples.add(event.values.copyOf())
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
|
||||
}
|
||||
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME)
|
||||
try {
|
||||
// 用 latch 等不到就超时,靠 await 的返回值判断即可
|
||||
latch.await((seconds * 1000).toLong(), TimeUnit.MILLISECONDS)
|
||||
} finally {
|
||||
sm.unregisterListener(listener)
|
||||
}
|
||||
if (samples.isEmpty()) return JSONObject().put("error", "$name 在采样期内没出数据")
|
||||
|
||||
val dims = samples.first().size
|
||||
val stats = JSONArray()
|
||||
for (d in 0 until dims) {
|
||||
val values = samples.map { it[d].toDouble() }
|
||||
stats.put(
|
||||
JSONObject()
|
||||
.put("avg", values.average())
|
||||
.put("min", values.min())
|
||||
.put("max", values.max())
|
||||
.put("last", values.last()),
|
||||
)
|
||||
}
|
||||
val last = JSONArray()
|
||||
samples.last().forEach { last.put(it.toDouble()) }
|
||||
return JSONObject()
|
||||
.put("sensor", name)
|
||||
.put("unit", unitOf(name))
|
||||
.put("sample_count", samples.size)
|
||||
.put("seconds", seconds)
|
||||
.put("axes", axisNames(dims))
|
||||
.put("last", last)
|
||||
.put("stats", stats)
|
||||
}
|
||||
|
||||
private fun axisNames(dims: Int): JSONArray {
|
||||
val names = listOf("x", "y", "z", "w")
|
||||
val arr = JSONArray()
|
||||
for (i in 0 until dims) arr.put(names.getOrElse(i) { "v$i" })
|
||||
return arr
|
||||
}
|
||||
|
||||
private fun unitOf(name: String): String = when (name) {
|
||||
"accelerometer", "gravity", "linear_acceleration" -> "m/s^2"
|
||||
"gyroscope" -> "rad/s"
|
||||
"magnetic" -> "uT"
|
||||
"light" -> "lx"
|
||||
"pressure" -> "hPa"
|
||||
"proximity" -> "cm"
|
||||
"humidity" -> "%"
|
||||
"temperature" -> "°C"
|
||||
else -> ""
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 剪贴板 / 选文件
|
||||
|
||||
@Suppress("unused")
|
||||
fun setClipboard(text: String) {
|
||||
activity.runOnUiThread {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("doubao", text))
|
||||
}
|
||||
}
|
||||
|
||||
private fun readClipboard(): String {
|
||||
val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = cm.primaryClip ?: return ""
|
||||
if (clip.itemCount == 0) return ""
|
||||
return clip.getItemAt(0).coerceToText(activity).toString()
|
||||
}
|
||||
|
||||
/** 内核请求"用户选个文件"时调用;把选中的文件复制到 App 私有目录再返回路径 */
|
||||
@Volatile
|
||||
private var pickLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var pickedUris: List<Uri> = emptyList()
|
||||
|
||||
@Suppress("unused")
|
||||
fun pickFile(): Array<String> {
|
||||
val latch = CountDownLatch(1)
|
||||
pickLatch = latch
|
||||
pickedUris = emptyList()
|
||||
activity.runOnUiThread {
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = "*/*"
|
||||
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||
}
|
||||
activity.startActivityForResult(intent, REQ_PICK)
|
||||
} catch (t: Throwable) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(
|
||||
AppTimeouts.seconds("filePicker", PICK_TIMEOUT_S.toDouble()).toLong(),
|
||||
TimeUnit.SECONDS,
|
||||
)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
|
||||
/** MainActivity 的 onActivityResult 转进来 */
|
||||
fun onPicked(data: Intent?) {
|
||||
val uris = mutableListOf<Uri>()
|
||||
data?.clipData?.let { clip ->
|
||||
for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri)
|
||||
}
|
||||
data?.data?.let { uris.add(it) }
|
||||
pickedUris = uris
|
||||
pickLatch?.countDown()
|
||||
}
|
||||
|
||||
private fun copyIntoCache(uri: Uri): String? = try {
|
||||
val name = displayName(uri) ?: "upload_${System.currentTimeMillis()}"
|
||||
val dir = File(activity.cacheDir, "picked").apply { mkdirs() }
|
||||
val dest = File(dir, name)
|
||||
activity.contentResolver.openInputStream(uri)?.use { input ->
|
||||
dest.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
dest.absolutePath
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
private fun displayName(uri: Uri): String? = try {
|
||||
activity.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
if (idx >= 0 && cursor.moveToFirst()) cursor.getString(idx) else null
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
/** 安卓上没有"打开文件夹",直接返回提示(设置页会显示不可用) */
|
||||
@Suppress("unused")
|
||||
fun reveal(path: String): String? = null
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
|
||||
/**
|
||||
* AI 让你挑文件时等多久的**兜底值**。
|
||||
*
|
||||
* ★ 真实值从设置读(设置 → 超时 → 选文件等多久)——
|
||||
* 去相册里翻一张老照片可能不止两分钟。这里是拿不到设置时的兜底。
|
||||
*/
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/**
|
||||
* 打本机内核端口([kernelPost] / [kernelPatch])的读超时。
|
||||
*
|
||||
* ★ 也做成可调的(设置 → 超时 → 本地接口请求):这些请求里有几个
|
||||
* 体积不小(读一条很长的会话、传附件),老设备上 10 秒不一定够。
|
||||
* 每次现读而不是建 client 时读一次 —— 改完立刻生效。
|
||||
*/
|
||||
private val LOCAL_READ_S: Long
|
||||
get() = AppTimeouts.seconds("kernelLocal", 10.0).toLong().coerceAtLeast(3L)
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
entry.callAttr("set_android_bridge", bridge)
|
||||
}
|
||||
}
|
||||
}
|
||||
374
豆鲍/android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -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)
|
||||
}
|
||||
2988
豆鲍/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)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
@@ -0,0 +1,443 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
/**
|
||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||
*
|
||||
* ## 为什么要一个单例控制器
|
||||
*
|
||||
* 内核(Python,跑在 HTTP 工作线程上)通过 `NativeBridge.device()` 说
|
||||
* "给我弹个界面",而界面是 Compose 画的、归 `AppViewModel` 管。
|
||||
* 这两边**没有互相引用**:
|
||||
*
|
||||
* · `NativeBridge` 在 `MainActivity` 里 new 出来(见 MainActivity:76)
|
||||
* · `AppViewModel` 在 Compose 树里由 `rememberAppViewModel` 造
|
||||
*
|
||||
* 所以中间放一个单例:NativeBridge 往里写,ViewModel 订阅。
|
||||
* 这也让"内核线程"和"UI 状态"的边界很清楚 —— 内核永远不直接碰 Compose。
|
||||
*
|
||||
* ## 线程模型(这是最容易出错的地方)
|
||||
*
|
||||
* `device()` 是在**内核的 HTTP 工作线程**上被调的,而:
|
||||
* · 写状态:用 `@Volatile` + 监听器回调,ViewModel 在自己的协程里切主线程更新 Compose
|
||||
* · 等用户选择:用 [CountDownLatch] 阻塞**那个工作线程**(不能阻塞 UI 线程)
|
||||
*
|
||||
* 跟 `NativeBridge.pickFile()` 是同一套路子(它已经验证过可行)。
|
||||
*/
|
||||
object AiSurface {
|
||||
|
||||
private const val TAG = "DoubaoAiSurface"
|
||||
|
||||
/** 一次 AI 界面的标识。每次弹出都换一个,用来让 Compose 重建 WebView。 */
|
||||
private val seq = AtomicLong(0)
|
||||
|
||||
/** 正在显示的 HTML 界面;null 表示没有 */
|
||||
@Volatile
|
||||
var screen: Screen? = null
|
||||
private set
|
||||
|
||||
/** 正在等的选择弹窗;null 表示没有 */
|
||||
@Volatile
|
||||
var dialog: Dialog? = null
|
||||
private set
|
||||
|
||||
/** 当前对话被 AI 结束过 —— 界面据此禁用输入框 */
|
||||
@Volatile
|
||||
var endedConversationId: String = ""
|
||||
private set
|
||||
|
||||
data class Screen(
|
||||
val id: Long,
|
||||
val html: String,
|
||||
val title: String,
|
||||
val fullHtml: Boolean,
|
||||
val conversationId: String,
|
||||
/** true = 这一屏在等用户操作(用户点了回传按钮后自动收掉) */
|
||||
val waiting: Boolean = false,
|
||||
/** 磁盘上那一份的 id(空 = 没存)。再打开时靠它去读。 */
|
||||
val screenId: String = "",
|
||||
)
|
||||
|
||||
data class Option(val label: String, val value: String, val description: String)
|
||||
|
||||
data class Dialog(
|
||||
val id: Long,
|
||||
val question: String,
|
||||
val options: List<Option>,
|
||||
val multiple: Boolean,
|
||||
val allowCancel: Boolean,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** ViewModel 订阅这个来把状态同步进 Compose。参数是"发生了什么"。 */
|
||||
@Volatile
|
||||
private var listener: ((String) -> Unit)? = null
|
||||
|
||||
fun subscribe(fn: ((String) -> Unit)?) {
|
||||
listener = fn
|
||||
}
|
||||
|
||||
private fun notify(kind: String) {
|
||||
try {
|
||||
listener?.invoke(kind)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "通知界面失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 把界面存一份到磁盘 —— **关掉之后还能再打开**。
|
||||
*
|
||||
* ## 为什么需要(用户的原话:"AI 写的界面可以再点开")
|
||||
*
|
||||
* 界面以前只活在内存里:用户一关(或者退出 App),那份 HTML 就没了。
|
||||
* 过一会儿想"刚才那个图表再看一眼"就再也找不回来,只能让 AI 重新生成 ——
|
||||
* 而重新生成的内容**和上次不一定一样**(模型有随机性),
|
||||
* 用户看到的是"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* ## 为什么不放内核(Python)那边
|
||||
*
|
||||
* 内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
|
||||
* `device()` 参数。要走内核就得 Kotlin 再 POST 一次上去,多一次往返、
|
||||
* 还多一个失败点。而 App 私有目录本来就是 Kotlin 最顺手的地方。
|
||||
*
|
||||
* 存法:
|
||||
* `<app files>/ai-screens/<id>.html` 正文
|
||||
* `<app files>/ai-screens/index.json` 索引(列表只读这个)
|
||||
*/
|
||||
private val screensLock = Any()
|
||||
|
||||
fun screenDir(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(ctx.filesDir, "ai-screens").apply { mkdirs() }
|
||||
|
||||
fun screenIndexFile(ctx: android.content.Context): java.io.File =
|
||||
java.io.File(screenDir(ctx), "index.json")
|
||||
|
||||
fun loadScreenIndex(ctx: android.content.Context): JSONArray = synchronized(screensLock) {
|
||||
try {
|
||||
val text = screenIndexFile(ctx).readText()
|
||||
JSONArray(text)
|
||||
} catch (_: Throwable) {
|
||||
JSONArray()
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveScreenIndex(ctx: android.content.Context, arr: JSONArray) {
|
||||
try {
|
||||
screenIndexFile(ctx).writeText(arr.toString())
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "写界面索引失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 存下一个界面,返回它的索引项(含 id)。
|
||||
*
|
||||
* ★ 每个会话只留最近 [KEEP_PER_CONV] 个:用户跟 AI 聊久了会弹出几十个界面,
|
||||
* 列表没法看、磁盘也白占。超出时把**最旧的正文删掉**(索引项也去掉),
|
||||
* 保留最近这些。
|
||||
*/
|
||||
fun saveScreen(
|
||||
ctx: android.content.Context,
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
): JSONObject? {
|
||||
val id = "s_" + java.util.UUID.randomUUID().toString().replace("-", "").take(12)
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").writeText(html)
|
||||
val item = JSONObject()
|
||||
.put("id", id)
|
||||
.put("title", title.ifBlank { "AI 界面" })
|
||||
.put("fullHtml", fullHtml)
|
||||
.put("bytes", html.length)
|
||||
.put("conversationId", conversationId)
|
||||
.put("preview", previewOf(html))
|
||||
.put("at", System.currentTimeMillis())
|
||||
synchronized(screensLock) {
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray().put(item)
|
||||
var kept = 0
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("conversationId") != conversationId) {
|
||||
next.put(it); continue
|
||||
}
|
||||
if (kept < KEEP_PER_CONV) {
|
||||
next.put(it); kept++
|
||||
} else {
|
||||
runCatching { java.io.File(screenDir(ctx), "${it.optString("id")}.html").delete() }
|
||||
}
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
item
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "存界面失败:${t.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** 读一个界面的正文 */
|
||||
fun readScreen(ctx: android.content.Context, id: String): String? {
|
||||
if (id.isBlank() || id.contains('/') || id.contains("..")) return null
|
||||
return try {
|
||||
java.io.File(screenDir(ctx), "$id.html").readText()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteScreen(ctx: android.content.Context, id: String) {
|
||||
synchronized(screensLock) {
|
||||
runCatching { java.io.File(screenDir(ctx), "$id.html").delete() }
|
||||
val arr = loadScreenIndex(ctx)
|
||||
val next = JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val it = arr.optJSONObject(i) ?: continue
|
||||
if (it.optString("id") != id) next.put(it)
|
||||
}
|
||||
saveScreenIndex(ctx, next)
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 HTML 里抠一小段纯文字做预览(列表里靠它认出是哪个界面) */
|
||||
private fun previewOf(html: String): String =
|
||||
html.replace(Regex("(?is)<(script|style)[^>]*>.*?</\\1>"), " ")
|
||||
.replace(Regex("<[^>]+>"), " ")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
.take(120)
|
||||
|
||||
private const val KEEP_PER_CONV = 30
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。
|
||||
*
|
||||
* [wait] = false(默认):**不阻塞** —— 弹出来就返回。
|
||||
* [wait] = true:**等用户交互**(点回传按钮 / 关掉界面),最多等 [timeoutMs]。
|
||||
*
|
||||
* ★ 为什么要两种:
|
||||
* 展示性的界面(图表、报告)不该把对话卡住 —— 用户可能盯着看很久。
|
||||
* 但"让用户在几个选项里挑一个"必须拿到答案才能继续,那就是阻塞语义。
|
||||
* 以前只有前者,于是 AI 想"问一个带图的选择题"就没辙了。
|
||||
*
|
||||
* ★ 阻塞是怎么实现的:和 [ask](ask_user 弹窗)、`NativeBridge.pickFile`
|
||||
* 同一套路 —— `CountDownLatch` 等用户动作。**只会阻塞内核的工作线程**,
|
||||
* 不碰 UI 线程。
|
||||
*
|
||||
* ★★ [timeoutMs] <= 0 表示**不限时**(等用户到天荒地老),这是默认。
|
||||
* 以前默认 120 秒,用户明确要求"AI 询问界面不要限时"——
|
||||
* 他可能看着界面想很久,120 秒到点界面自己收掉,体验很差。
|
||||
* 现在想限时得由模型显式传 timeout。
|
||||
*/
|
||||
fun showScreen(
|
||||
html: String,
|
||||
title: String,
|
||||
fullHtml: Boolean,
|
||||
conversationId: String,
|
||||
wait: Boolean = false,
|
||||
timeoutMs: Long = 0L,
|
||||
screenId: String = "",
|
||||
): JSONObject {
|
||||
val s = Screen(
|
||||
seq.incrementAndGet(), html, title, fullHtml, conversationId,
|
||||
waiting = wait, screenId = screenId,
|
||||
)
|
||||
screen = s
|
||||
screenClosed = false
|
||||
screenAnswer = null
|
||||
notify("screen")
|
||||
Log.i(
|
||||
TAG,
|
||||
"AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}," +
|
||||
if (wait) "等用户操作(${waitLabel(timeoutMs)})" else "不等待",
|
||||
)
|
||||
|
||||
if (!wait) {
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
// ★ 带上 id —— 它一路回到模型的工具返回值、再进 ToolTrace,
|
||||
// 消息操作栏据此显示「界面」按钮(用户要求"可以再点开")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
// ---- 等待模式 ----
|
||||
val latch = screenLatch
|
||||
val answered = latch?.let { awaitUser(it, timeoutMs) } ?: false
|
||||
val answer = screenAnswer
|
||||
val closed = screenClosed
|
||||
screenLatch = null
|
||||
|
||||
// 等到答案(或超时)之后把界面收掉 —— 否则用户看到一个已经"用完了"
|
||||
// 的界面还开着,会以为还能再点。
|
||||
if (answered) {
|
||||
screen = null
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
return JSONObject()
|
||||
.put("shown", true)
|
||||
.put("bytes", html.length)
|
||||
.put("waited", true)
|
||||
.put("timeout", !answered)
|
||||
.put("closed", closed)
|
||||
// 用户点的值。超时/直接关掉时是空串。
|
||||
.put("value", answer ?: "")
|
||||
.put("screenId", screenId)
|
||||
}
|
||||
|
||||
/** 等用户交互用的闩。非等待模式下是 null。 */
|
||||
@Volatile
|
||||
private var screenLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var screenAnswer: String? = null
|
||||
|
||||
@Volatile
|
||||
private var screenClosed: Boolean = false
|
||||
|
||||
/**
|
||||
* 用户在界面上点了回传按钮(`Doubao.sendToAi` / `data-doubao-result`)。
|
||||
*
|
||||
* ★ 等待模式下这一下就是"用户答完了"的信号:记下值、放行。
|
||||
* 界面侧收到后会把自己收掉。
|
||||
*/
|
||||
fun screenResult(value: String) {
|
||||
Log.i(TAG, "界面里点了:$value")
|
||||
lastScreenResult = value
|
||||
screenAnswer = value
|
||||
screenClosed = false
|
||||
screenLatch?.countDown()
|
||||
notify("screenResult")
|
||||
}
|
||||
|
||||
@Volatile
|
||||
var lastScreenResult: String = ""
|
||||
private set
|
||||
|
||||
/** 用户把界面关掉了 */
|
||||
fun closeScreen() {
|
||||
screen = null
|
||||
// 等待模式下"关掉"也是一个答案(用户不想选)—— 放行,值是空串
|
||||
screenClosed = true
|
||||
screenLatch?.countDown()
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
/** 进等待模式前由 NativeBridge 调一次,准备闩 */
|
||||
fun armScreenLatch() {
|
||||
screenLatch = CountDownLatch(1)
|
||||
screenAnswer = null
|
||||
screenClosed = false
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完。
|
||||
*
|
||||
* ★★ [timeoutMs] <= 0 = **不限时**(默认)。这是用户明确要求的:
|
||||
* "AI 询问界面不要限时" —— 他可能对着选项想很久,或者在忙别的事,
|
||||
* 120 秒到点弹窗自己消失、模型收到 `timeout=true` 以为他不想理,
|
||||
* 然后自说自话往下走 —— 整轮就废了。
|
||||
*
|
||||
* ★ 放行的方式(用户总得有一个出口,不然内核线程永远挂着):
|
||||
* · 点任意一个选项 → [answerDialog] → countDown
|
||||
* · 点「取消」(`allowCancel` 默认 true)→ 同上,`cancelled=true`
|
||||
* · 关掉 App → 进程结束,线程一起没了
|
||||
* 所以只要界面上留着取消按钮,无限等就不会变成死锁。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
*/
|
||||
fun ask(
|
||||
question: String,
|
||||
options: List<Option>,
|
||||
multiple: Boolean,
|
||||
allowCancel: Boolean,
|
||||
conversationId: String,
|
||||
timeoutMs: Long,
|
||||
): JSONObject {
|
||||
val d = Dialog(seq.incrementAndGet(), question, options, multiple, allowCancel, conversationId)
|
||||
val latch = CountDownLatch(1)
|
||||
answerLatch = latch
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,${waitLabel(timeoutMs)})")
|
||||
|
||||
val answered = awaitUser(latch, timeoutMs)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
dialog = null
|
||||
notify("dialog")
|
||||
|
||||
if (!answered || a == null) {
|
||||
Log.i(TAG, "用户没在时限内回答")
|
||||
return JSONObject()
|
||||
.put("timeout", true)
|
||||
.put("multiple", multiple)
|
||||
.put("choice", "")
|
||||
.put("values", JSONArray())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
/**
|
||||
* 等用户动作。
|
||||
*
|
||||
* [timeoutMs] <= 0 → **无限等**(`await()` 不带超时);否则最多等那么久。
|
||||
* 返回 true 表示等到了。
|
||||
*
|
||||
* ★ 只有这一个地方做等待,[ask] 和 [showScreen] 都走它 ——
|
||||
* 两处各写一遍的话,"不限时"这种改动迟早只改到一处。
|
||||
*/
|
||||
private fun awaitUser(latch: CountDownLatch, timeoutMs: Long): Boolean =
|
||||
if (timeoutMs <= 0L) {
|
||||
latch.await()
|
||||
true
|
||||
} else {
|
||||
latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
}
|
||||
|
||||
/** 日志里怎么描述等待时长 */
|
||||
private fun waitLabel(timeoutMs: Long): String =
|
||||
if (timeoutMs <= 0L) "不限时,等用户回答" else "最多等 ${timeoutMs / 1000}s"
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var answer: JSONObject? = null
|
||||
|
||||
/** 用户选了。界面调这个。 */
|
||||
fun answerDialog(values: List<String>, cancelled: Boolean) {
|
||||
val arr = JSONArray()
|
||||
values.forEach { arr.put(it) }
|
||||
answer = JSONObject()
|
||||
.put("timeout", false)
|
||||
.put("cancelled", cancelled)
|
||||
.put("multiple", dialog?.multiple ?: false)
|
||||
.put("choice", values.firstOrNull() ?: "")
|
||||
.put("values", arr)
|
||||
answerLatch?.countDown()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 结束对话
|
||||
|
||||
fun markEnded(conversationId: String) {
|
||||
endedConversationId = conversationId
|
||||
notify("ended")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Termux 的软件源(apt 源)管理。
|
||||
*
|
||||
* ★ 为什么要单独做这个:Termux 官方源(packages.termux.dev)在国内**基本连不上**,
|
||||
* 表现是 `pkg install` 卡在 "Reading package lists..." 或者直接超时 ——
|
||||
* 用户会以为"内置的 Termux 坏了",其实是源的问题。
|
||||
*
|
||||
* 国内几个镜像都是完整同步的,换一下就好。做成界面而不是让用户手敲 sed:
|
||||
* 换源这件事**每次重装都要做**,而且 apt 的源格式写错一点就整个不能用。
|
||||
*/
|
||||
object TermuxMirror {
|
||||
|
||||
/**
|
||||
* 一个源。
|
||||
*
|
||||
* @param id 稳定标识(存进偏好,别用下标 —— 以后插入新源会串位)
|
||||
* @param name 显示名
|
||||
* @param host 给 termux-main 用的仓库根地址(不带 /apt/ 之后的部分)
|
||||
* @param note 副标题:速度/稳定性之类的实话
|
||||
*/
|
||||
data class Mirror(val id: String, val name: String, val host: String, val note: String)
|
||||
|
||||
/**
|
||||
* 源列表。
|
||||
*
|
||||
* ★ 顺序是有讲究的:**默认放第一个**。
|
||||
* 镜像偶尔会挂(同步中断、证书过期),所以官方源要留着能切回去。
|
||||
*/
|
||||
val MIRRORS = listOf(
|
||||
Mirror(
|
||||
"tuna", "清华 TUNA", "http://mirrors.tuna.tsinghua.edu.cn/termux",
|
||||
"国内最快最稳的一个,推荐",
|
||||
),
|
||||
Mirror(
|
||||
"ustc", "中科大 USTC", "http://mirrors.ustc.edu.cn/termux",
|
||||
"同样完整同步,教育网更快",
|
||||
),
|
||||
Mirror(
|
||||
"aliyun", "阿里云", "http://mirrors.aliyun.com/termux",
|
||||
"公网覆盖好,偶尔缺 science 仓库",
|
||||
),
|
||||
Mirror(
|
||||
"bfsu", "北外 BFSU", "http://mirrors.bfsu.edu.cn/termux",
|
||||
"清华的备份站",
|
||||
),
|
||||
Mirror(
|
||||
"official", "官方源", "http://packages.termux.dev/apt",
|
||||
"国内经常连不上,镜像挂了才用它",
|
||||
),
|
||||
)
|
||||
|
||||
/** Termux 的仓库分几个「频道」,各自一条 sources.list 行 */
|
||||
private data class Channel(val name: String, val path: String, val components: String)
|
||||
|
||||
private val CHANNELS = listOf(
|
||||
Channel("termux-main", "apt/termux-main", "stable main"),
|
||||
Channel("termux-root", "apt/termux-root", "root stable"),
|
||||
Channel("termux-x11", "apt/termux-x11", "x11 main"),
|
||||
)
|
||||
|
||||
private fun aptDir(context: Context) = File(TermuxInstaller.prefix(context), "etc/apt")
|
||||
fun sourcesFile(context: Context) = File(aptDir(context), "sources.list")
|
||||
|
||||
/** 当前用的是哪个源(认不出来就返回 null) */
|
||||
fun current(context: Context): Mirror? {
|
||||
val file = sourcesFile(context)
|
||||
if (!file.exists()) return null
|
||||
val text = try {
|
||||
file.readText()
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
return MIRRORS.firstOrNull { text.contains(it.host) }
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 让 **`pkg`** 也认这个源。
|
||||
*
|
||||
* 踩过的坑:一开始只写了 `etc/apt/sources.list`,结果 `pkg update` 说
|
||||
* "No mirror or mirror group selected",然后**把全世界几十个镜像测了一遍**,
|
||||
* 最后挑了中国连不上的俄罗斯源 —— 用户看到一屏 `bad` 加一句
|
||||
* `E: Unable to determine a suitable packaging system type`。
|
||||
*
|
||||
* 原因:**`pkg` 不看 `sources.list`**,它自己有一套(见 `bin/pkg`):
|
||||
*
|
||||
* if [ -d .../etc/termux/chosen_mirrors ] → 镜像组(取目录下所有文件)
|
||||
* elif [ -f .../etc/termux/chosen_mirrors ] → 单个镜像(**文件本身**就是路径)
|
||||
* elif [ -L ... ] → 断链,退回测全部
|
||||
* else → 没选,测全部
|
||||
*
|
||||
* bootstrap 已经带了 `etc/termux/mirrors/<地区>/<主机名>` 这些源文件,
|
||||
* 内容是 `WEIGHT= / MAIN= / ROOT= / X11=` 的 shell 片段。
|
||||
* `termux-change-repo` 的做法就是**建个符号链接**指过去。这里照做。
|
||||
*/
|
||||
private fun selectForPkg(context: Context, mirror: Mirror): String {
|
||||
val termuxDir = File(TermuxInstaller.prefix(context), "etc/termux")
|
||||
val mirrorsDir = File(termuxDir, "mirrors")
|
||||
val chosen = File(termuxDir, "chosen_mirrors")
|
||||
if (!mirrorsDir.isDirectory) return "没有 mirrors 目录,跳过"
|
||||
|
||||
val hostOnly = mirror.host
|
||||
.removePrefix("https://").removePrefix("http://")
|
||||
.substringBefore('/')
|
||||
|
||||
val target = mirrorsDir.walkTopDown()
|
||||
.filter { it.isFile && it.name == hostOnly }
|
||||
.firstOrNull()
|
||||
?: return "mirrors/ 里没有 $hostOnly"
|
||||
|
||||
try {
|
||||
chosen.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
return try {
|
||||
java.nio.file.Files.createSymbolicLink(chosen.toPath(), target.toPath())
|
||||
"链接到 ${target.name}"
|
||||
} catch (t: Throwable) {
|
||||
// 有些文件系统不给建链接 → 退回复制(pkg 读的是文件内容,效果一样)
|
||||
try {
|
||||
target.copyTo(chosen, overwrite = true)
|
||||
"复制 ${target.name}(建链接失败:${t.javaClass.simpleName})"
|
||||
} catch (t2: Throwable) {
|
||||
"失败:${t2.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 换源。
|
||||
*
|
||||
* ★ 有个坑:Termux 官方的 sources.list **里面是带注释和 deb-src 的**,
|
||||
* 直接整份覆盖会丢掉用户自己加的东西。所以这里只**替换行**:
|
||||
* 凡是以 `deb ` 开头、且指向 termux 仓库的行,按频道重写;
|
||||
* 其余(注释、第三方源)原样留着。
|
||||
*
|
||||
* @return 写进去的行数
|
||||
*/
|
||||
fun set(context: Context, mirror: Mirror): Int {
|
||||
val dir = aptDir(context)
|
||||
dir.mkdirs()
|
||||
val file = sourcesFile(context)
|
||||
|
||||
val existing = if (file.exists()) {
|
||||
try {
|
||||
file.readLines()
|
||||
} catch (_: Throwable) {
|
||||
emptyList()
|
||||
}
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
// 保留非 termux 的行(注释、用户自己加的源)
|
||||
val kept = existing.filter { line ->
|
||||
val t = line.trim()
|
||||
!t.startsWith("deb ") || !t.contains("termux")
|
||||
}
|
||||
|
||||
// ★ 只写**原本就有**的频道:termux-root / termux-x11 这两个仓库
|
||||
// 国内镜像不一定同步了,凭空写进去会让 apt update 整条报错
|
||||
// (一个源 404,apt 就整个失败,用户看到的是"换源之后更坏了")。
|
||||
// main 永远要(没有它 pkg 什么都装不了)。
|
||||
val original = existing.joinToString("\n")
|
||||
val wanted = CHANNELS.filter {
|
||||
it.name == "termux-main" || original.contains(it.name)
|
||||
}
|
||||
|
||||
val header = listOf(
|
||||
"# 由小人间 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 换源:内置终端右上角「源」按钮;也可以手动改这个文件",
|
||||
)
|
||||
val lines = wanted.map { "deb ${mirror.host}/${it.path} ${it.components}" }
|
||||
|
||||
file.writeText(
|
||||
(header + kept.filter { it.isNotBlank() } + lines).joinToString("\n") + "\n",
|
||||
)
|
||||
|
||||
// ★★ 光写 sources.list **不够** —— `pkg` 不看这个文件!
|
||||
// 它有自己的 chosen_mirrors(见 selectForPkg 的注释)。
|
||||
// 不写的话 `pkg update` 会把全世界几十个镜像挨个测一遍,
|
||||
// 最后挑中一个国内连不上的(实测挑中了俄罗斯的 mephi),
|
||||
// 用户看到一屏 `bad` 和 `E: Unable to determine a suitable packaging system type`。
|
||||
val pkgNote = try {
|
||||
selectForPkg(context, mirror)
|
||||
} catch (t: Throwable) {
|
||||
"失败:${t.message}"
|
||||
}
|
||||
android.util.Log.i(
|
||||
"DoubaoTermux",
|
||||
"换源 ${mirror.name}:sources.list ${lines.size} 条;pkg $pkgNote",
|
||||
)
|
||||
return lines.size
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 当前源要是**用不了**,自动换一个能用的。
|
||||
*
|
||||
* ## 为什么需要
|
||||
*
|
||||
* 用户实测撞到的(原话):
|
||||
*
|
||||
* E: Failed to fetch .../binary-x86_64/Packages.bz2
|
||||
* File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
* E: Some index files failed to download. They have been ignored,
|
||||
* or old ones used instead.
|
||||
*
|
||||
* 这是**镜像正在同步**时的典型症状:`InRelease` 已经是新的了,
|
||||
* 但 `Packages.bz2` 还是旧的,apt 一对哈希就拒绝。用户侧完全没辙 ——
|
||||
* 「源」按钮他按了也没用(换到的还是同一个坏源,或者他根本不知道该换)。
|
||||
*
|
||||
* 而我们**默认给的就是清华**([MIRRORS] 第一个)。镜像偶尔同步是常态,
|
||||
* 所以这不是"清华不好",是"任何单一默认值都会偶尔把用户卡死"。
|
||||
*
|
||||
* ## 做法
|
||||
*
|
||||
* 真跑一次 `apt-get update` 当探测 —— **不自己写校验逻辑**:
|
||||
*
|
||||
* · apt 的校验比我们严(哈希、时间戳、架构都对),复用它最准
|
||||
* · 反正换源之后本来就要 update,探测这一步不白花
|
||||
* · 自己写"拉 InRelease 看看"那种轻量探针**测不出这个 bug** ——
|
||||
* InRelease 恰恰是好的那一半
|
||||
*
|
||||
* 当前源能用就**什么都不做**(不打扰用户的选择)。
|
||||
* 用不了才按 [MIRRORS] 顺序往下试,换成功就记住(写 sources.list + pkg 那套)。
|
||||
*
|
||||
* @param onSwitched 换成功时回调(给界面提示用),参数是新的源
|
||||
* @return 最终可用的源;全都不可用时返回 null
|
||||
*/
|
||||
fun autoPickIfBroken(context: Context, onSwitched: ((Mirror) -> Unit)? = null): Mirror? {
|
||||
val current = current(context) ?: MIRRORS.first()
|
||||
|
||||
if (probe(context, current)) return current
|
||||
|
||||
android.util.Log.i("DoubaoTermux", "源 ${current.name} 探测失败,开始找能用的")
|
||||
for (candidate in MIRRORS) {
|
||||
if (candidate.id == current.id) continue
|
||||
if (!probe(context, candidate)) continue
|
||||
val n = set(context, candidate)
|
||||
android.util.Log.i("DoubaoTermux", "已自动切到 ${candidate.name}($n 条)")
|
||||
onSwitched?.invoke(candidate)
|
||||
return candidate
|
||||
}
|
||||
android.util.Log.w("DoubaoTermux", "所有源都探测失败,保持 ${current.name}")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测一个源能不能用:**临时**写进 sources.list 跑一次 `apt-get update`,
|
||||
* 不管成败都把原来的 sources.list 还原回去。
|
||||
*
|
||||
* ★ 必须还原:探测失败时若留着半个写入状态,用户会看到"源莫名其妙变了"。
|
||||
*/
|
||||
private fun probe(context: Context, mirror: Mirror): Boolean {
|
||||
val file = sourcesFile(context)
|
||||
val backup = try {
|
||||
if (file.exists()) file.readText() else null
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
return try {
|
||||
set(context, mirror)
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val pb = ProcessBuilder("$prefix/bin/apt-get", "update")
|
||||
.directory(TermuxInstaller.home(context))
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
// 输出必须读掉,否则管道写满会把子进程卡死(apt 输出很多)
|
||||
val sink = Thread { proc.inputStream.readBytes(); proc.errorStream.readBytes() }
|
||||
sink.isDaemon = true
|
||||
sink.start()
|
||||
val ok = proc.waitFor(PROBE_TIMEOUT_S, java.util.concurrent.TimeUnit.SECONDS) &&
|
||||
proc.exitValue() == 0
|
||||
if (!ok) proc.destroyForcibly()
|
||||
ok
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.i("DoubaoTermux", "探测 ${mirror.name} 抛异常:${t.message}")
|
||||
false
|
||||
} finally {
|
||||
try {
|
||||
if (backup != null) file.writeText(backup) else file.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测超时。apt 卡住时不能把用户等死 */
|
||||
private const val PROBE_TIMEOUT_S = 45L
|
||||
}
|
||||
@@ -39,10 +39,21 @@ object TermuxShell {
|
||||
return try {
|
||||
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
|
||||
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
|
||||
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
//
|
||||
// ★★★ 用 `childEnvMap()` 而不是 `environment()`:ProcessBuilder 起的是
|
||||
// 子进程,**默认继承整个 App 进程的环境**,而里面带着 Chaquopy 注入的
|
||||
// `PYTHONPATH`(指向 3.13 编的 .imy)。不清掉的话 Termux 的 python 3.14
|
||||
// 一起来就读到 3.13 的 encodings/__init__.pyc,魔数不符直接核心崩溃:
|
||||
// Fatal Python error: Failed to import encodings module
|
||||
// 详见 TermuxInstaller.childEnv 的注释。
|
||||
//
|
||||
// ★ `environment().putAll(...)` 这种写法是**追加**,删不掉已有的键 ——
|
||||
// 所以必须显式摘掉那几个变量(childEnvMap 做了这件事)。
|
||||
val pb = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
.directory(workdir)
|
||||
.apply { environment().putAll(TermuxInstaller.environment(context)) }
|
||||
.start()
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
|
||||
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
|
||||
val outBuf = StringBuilder()
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 真·终端会话:用 Termux 自己的 pty(libtermux.so 的 JNI)+ 它的终端模拟器。
|
||||
*
|
||||
* 为什么不用 `Runtime.exec` 拼一个假终端:那样跑不了 vim/top、没有颜色、没有方向键,
|
||||
* 也不是 tty,很多命令行为会不一样。Termux 这套是完整 pty + ANSI 渲染。
|
||||
*/
|
||||
class TermuxTerminal(private val context: Context) {
|
||||
|
||||
@Volatile
|
||||
var session: TerminalSession? = null
|
||||
private set
|
||||
|
||||
/** 这次是用哪种起法建起来的(写进日志,排查时一眼能看到是哪一步坏的) */
|
||||
@Volatile
|
||||
var startedWith: String = ""
|
||||
private set
|
||||
|
||||
/**
|
||||
* ★★★ 必须把 `TerminalView` 接进来,否则**屏幕永远不刷新**。
|
||||
*
|
||||
* Termux 的分工是:会话把输出解析进 emulator 的屏幕缓冲,
|
||||
* 然后通过 `TerminalSessionClient.onTextChanged()` 通知"该重画了",
|
||||
* 由 `TerminalView.onScreenUpdated()` 真正去 invalidate。
|
||||
*
|
||||
* 我这里的 `onTextChanged` 之前是**空的** —— 于是:pty 通了、bash 活着、
|
||||
* 输出也解析进缓冲了,**但屏幕一动不动**,看起来像"什么都没发生"。
|
||||
* (这个坑和 pty 那个是两回事,修好 argv 之后才暴露出来。)
|
||||
*/
|
||||
@Volatile
|
||||
var view: TerminalView? = null
|
||||
|
||||
|
||||
/** 用完了没有(决定要不要切成命令控制台) */
|
||||
val candidatesExhausted: Boolean get() = candidateIndex >= candidateCount
|
||||
|
||||
private var candidateIndex = 0
|
||||
private var candidateCount = 0
|
||||
|
||||
/**
|
||||
* ★ 诊断用:`cat` 无参数时**一直读 stdin**,不会自己退出。
|
||||
*
|
||||
* 三种环境各试一次,就能定位到底哪一段环境变量把子进程搞坏了:
|
||||
* A. 干净环境(只留 PATH=/system/bin)—— 系统二进制,测 pty 本身
|
||||
* B. 干净环境 + 我们自己的 bash —— 测 bash 在干净环境下活不活
|
||||
* C. 完整环境(现在的默认)
|
||||
*
|
||||
* 怀疑点:`LD_LIBRARY_PATH=$prefix/lib` 会**屏蔽系统库**,
|
||||
* 系统二进制(toybox 之类)因此加载失败 → exec 返回 127。
|
||||
* 定位完这几条诊断候选都删掉。
|
||||
*/
|
||||
private fun cleanEnv(): List<String> = listOf(
|
||||
"PATH=/system/bin:/system/xbin",
|
||||
"HOME=/data",
|
||||
"TERM=xterm-256color",
|
||||
"LANG=en_US.UTF-8",
|
||||
)
|
||||
|
||||
private fun candidateList(): List<Triple<String, Array<String>, Boolean>> {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val rc = TermuxInstaller.interactiveShellArgs(context)
|
||||
return listOf(
|
||||
// ⓪-A 干净环境跑 cat:能挂住 → pty 没问题
|
||||
// ⓪-B 干净环境跑我们的 bash
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ★★ 决定性实验(定位完删):让**子进程自己**把关键信息
|
||||
// **重定向到文件**(这样绕开 pty,不依赖输出通道通不通)。
|
||||
//
|
||||
// 要看的是 fd 0/1/2 到底指向什么:
|
||||
// · 指向 /dev/pts/N → 从端接上了,EIO 另有原因
|
||||
// · 指向别的东西/没有 → 从端根本没接上(那就是根因)
|
||||
// `tty` 和 `stty` 顺带验证"是不是一个真正的终端"。
|
||||
// ★ 用 **/system/bin/sh**(toybox 的 sh)而不是我们 prefix 里的:
|
||||
// 它不依赖 Termux 的库,变量最少,能干净地回答"子进程的 fd 是什么"。
|
||||
// 输出写**绝对路径**,别用 $PREFIX(那种环境里不一定会展开)。
|
||||
Triple(
|
||||
"/system/bin/sh",
|
||||
arrayOf(
|
||||
"-c",
|
||||
"{ echo '=== fds ==='; ls -l /proc/self/fd; " +
|
||||
"echo '=== tty ==='; tty; echo tty_exit=$?; " +
|
||||
"echo '=== stty ==='; stty -a 2>&1 | head -2; " +
|
||||
"echo '=== tty_nr ==='; awk '{print $7}' /proc/self/stat; " +
|
||||
"} > /data/user/0/com.doubao.lynxclone/files/childinfo.txt 2>&1; sleep 20",
|
||||
),
|
||||
true,
|
||||
),
|
||||
// ① 直接 bash + 我们自己的 rc(正常路径)
|
||||
Triple("$prefix/bin/bash", rc, true),
|
||||
// ② ★ **不带 LD_PRELOAD** 起。
|
||||
//
|
||||
// `libtermux-exec.so` 是拦 execve/open 的 .so,让二进制里写死的
|
||||
// `/data/data/com.termux/...` 在运行时被改写到我们的 prefix。
|
||||
// 但它**在 pty 里可能把 stdin 搞坏** —— 实测现象是:
|
||||
// bash 的 rc 正常跑完(那行 echo 打出来了),然后读 stdin 直接 EOF
|
||||
// 就退出(退出码 0),终端上只剩 [Process completed]。
|
||||
// 去掉它 bash 只认编译期路径(读不到 /etc/profile),
|
||||
// 但**至少能交互** —— 哪个能用用哪个。
|
||||
Triple("$prefix/bin/bash", rc, false),
|
||||
// ③ Termux 的登录入口(有些机型上它才行;实测退出码 126)
|
||||
Triple("$prefix/bin/login", arrayOf("$prefix/bin/login", "-shell", "$prefix/bin/bash"), true),
|
||||
// ④ 最朴素的兜底:不带 preload。★ 第一个元素仍是程序名(见 interactiveShellArgs)
|
||||
Triple("$prefix/bin/bash", arrayOf("$prefix/bin/bash", "-i"), false),
|
||||
)
|
||||
}
|
||||
|
||||
private fun tryCreate(
|
||||
onTitle: (String) -> Unit,
|
||||
onExit: () -> Unit,
|
||||
): TerminalSession? {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val baseEnv = TermuxInstaller.childEnv(context)
|
||||
|
||||
val list = candidateList()
|
||||
candidateCount = list.size
|
||||
if (candidateIndex >= list.size) {
|
||||
TermuxInstaller.trace(context, "所有起法都试过了")
|
||||
return null
|
||||
}
|
||||
val (shell, args, usePreload) = list[candidateIndex]
|
||||
if (!File(shell).exists()) {
|
||||
TermuxInstaller.trace(context, "$shell 不在,跳过")
|
||||
return tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
// 前两条候选(诊断用)走**干净环境**:只留 PATH/HOME/TERM/LANG。
|
||||
// 目的就是把"环境变量把子进程搞坏"这个可能性单独拎出来验。
|
||||
val env = when {
|
||||
candidateIndex < 0 -> cleanEnv()
|
||||
usePreload -> baseEnv
|
||||
else -> baseEnv.filterNot { s: String -> s.startsWith("LD_PRELOAD=") }
|
||||
}
|
||||
startedWith = "$shell ${args.joinToString(" ")}" + if (usePreload) "" else "(不带 preload)"
|
||||
return try {
|
||||
val created = TerminalSession(shell, home, args, env.toTypedArray(), 2000, client(onTitle, onExit))
|
||||
TermuxInstaller.trace(context, "终端会话已建:$startedWith")
|
||||
session = created
|
||||
created
|
||||
} catch (t: Throwable) {
|
||||
TermuxInstaller.trace(context, "起 $shell 抛异常:${t.javaClass.simpleName}: ${t.message}")
|
||||
tryNextCandidate(onTitle, onExit)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ 秒退之后换下一种起法。
|
||||
*
|
||||
* 关键点:**"起法失败"不是靠异常发现的** ——
|
||||
* bash 起得来(构造函数不抛)、rc 也跑了,然后读 stdin 拿到 EOF 就退出。
|
||||
* 从代码角度看一切正常,只有"退出得太快"这个**事件**能说明它坏了。
|
||||
* 所以回退必须由秒退来驱动(TerminalScreen 在秒退回调里调这个)。
|
||||
*
|
||||
* @return 还有下一种就返回新会话;都用完了返回 null
|
||||
*/
|
||||
fun tryNextCandidate(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession? {
|
||||
candidateIndex += 1
|
||||
TermuxInstaller.trace(context, "换下一种起法(第 ${candidateIndex + 1} 种)")
|
||||
return tryCreate(onTitle, onExit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 开一个登录 shell。
|
||||
*
|
||||
* ★ 会**依次试几种起法**,哪个活下来用哪个。
|
||||
* 为什么要试:pty 的从端没接上时 shell 的 stdin 立刻 EOF,
|
||||
* bash 读不到东西**直接退出(退出码 0)** —— 现象是"终端一闪就没了",
|
||||
* 而且**看不出是哪一步坏的**。分步试 + 每步落盘就能定位。
|
||||
*/
|
||||
fun createSession(onTitle: (String) -> Unit, onExit: () -> Unit): TerminalSession {
|
||||
candidateIndex = 0
|
||||
return tryCreate(onTitle, onExit)
|
||||
?: throw IllegalStateException("$prefixPath 下没有能用的 shell")
|
||||
}
|
||||
|
||||
private val prefixPath: String get() = TermuxInstaller.prefix(context).absolutePath
|
||||
|
||||
private fun client(onTitle: (String) -> Unit, onExit: () -> Unit) = object : TerminalSessionClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
// ★ 这一行就是"屏幕刷新"的开关,别删(见 view 字段的注释)
|
||||
val v = view ?: return
|
||||
v.post { v.onScreenUpdated() }
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = onTitle(changedSession.title ?: "termux")
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
// 会话退出很值得记一笔:真机上 OEM 会把 Logcat 吞掉,只能落盘查
|
||||
TermuxInstaller.trace(
|
||||
context,
|
||||
"终端会话结束,退出码=${finishedSession.exitStatus} 用的=$startedWith",
|
||||
)
|
||||
onExit()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cm.setPrimaryClip(ClipData.newPlainText("termux", text))
|
||||
}
|
||||
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val text = cm.primaryClip?.takeIf { it.itemCount > 0 }
|
||||
?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (!text.isNullOrEmpty() && session.emulator != null) session.emulator.paste(text)
|
||||
}
|
||||
|
||||
override fun onBell(session: TerminalSession) {}
|
||||
override fun onColorsChanged(session: TerminalSession) {}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {}
|
||||
/** 光标样式:0=块 1=竖线 2=下划线 */
|
||||
override fun getTerminalCursorStyle(): Int = 1
|
||||
// 注意:Java 接口是 void,Kotlin 里必须写成代码块,不能写成 = Log.x(...)(那会返回 Int)
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
/** 给 TerminalView 用的客户端:把按键/手势接上,其余保持默认行为 */
|
||||
fun viewClient(): TerminalViewClient = object : TerminalViewClient {
|
||||
override fun onScale(scale: Float): Float = scale
|
||||
override fun onSingleTapUp(e: MotionEvent) {
|
||||
// 点一下就把软键盘叫出来,手机上最常用
|
||||
(e.source)
|
||||
}
|
||||
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = false
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = true
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) {}
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = false
|
||||
override fun readAltKey(): Boolean = false
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {}
|
||||
// TerminalViewClient 也继承了 Logger,这 7 个必须实现
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, "stack", e) }
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
try {
|
||||
session?.finishIfRunning()
|
||||
} catch (t: Throwable) {
|
||||
Log.w("DoubaoTermux", "关闭会话失败", t)
|
||||
}
|
||||
session = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 给 Compose 的 AndroidView 用:把 view 绑上会话 */
|
||||
fun bindSession(view: TerminalView, terminal: TermuxTerminal, onTitle: (String) -> Unit, onExit: () -> Unit) {
|
||||
val s = terminal.session ?: terminal.createSession(onTitle, onExit)
|
||||
if (view.currentSession !== s) {
|
||||
view.attachSession(s)
|
||||
}
|
||||
view.requestFocus()
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.foundation.Image
|
||||
|
||||
/*
|
||||
* 智能体的完整编辑界面(需求 2.5 / 3.1 / 3.3 / 3.5 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## ★ 为什么是全屏,而不是沿用那个弹窗
|
||||
*
|
||||
* 字段从 8 个涨到了二十多个(外观四件套、模型引用、世界观、限额、技能……)。
|
||||
* AGENTS.md 里那张表写得很清楚:「**列表 / 多组配置 / 任何要滚动的 → 独立全屏界面**」,
|
||||
* 而"节点配置 NodeConfigDialog → 全屏(字段很多)"到现在还挂在待办清单上 ——
|
||||
* 这次不再欠新账。
|
||||
*
|
||||
* ## 三处会让人困惑的地方,界面上直接说清
|
||||
*
|
||||
* ① **介绍(description)和一句话介绍(tagline)不是一回事**:
|
||||
* 前者只在选择界面的介绍框里显示,后者是列表里的摘要。
|
||||
* ② **绑了世界观 = 记忆变成共享的**(需求 3.6)—— 不写清楚,
|
||||
* 用户会以为"我给 A 记的东西怎么 B 也知道"。
|
||||
* ③ **限额 0 就是无限制**,不是"限额为 0"。
|
||||
*/
|
||||
|
||||
/** 除立绘以外的三件套(立绘是**五档**的,单独处理) */
|
||||
private val ASSET_SLOTS = listOf(
|
||||
Triple("back", "背景图", "铺在展示区最底层;缺了用内置默认背景"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区;缺了用简单方框"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本;缺了跟主体边框一个样式"),
|
||||
)
|
||||
|
||||
/** 立绘五档各档的说明 —— 每档都要写清"缺了会退回哪张",不然用户不知道该传几张 */
|
||||
private fun portraitHint(preset: String): String = when (preset) {
|
||||
"喜" -> "高兴时用这张;缺了用「平常」那张"
|
||||
"怒" -> "发怒时用这张;缺了用「平常」那张"
|
||||
"哀" -> "悲伤时用这张;缺了用「平常」那张"
|
||||
"死亡" -> "死亡时用这张(那时不能对话);缺了用「平常」那张"
|
||||
else -> "其他档都缺时兜底用这张;连它也没有就用内置默认人物"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AgentEditScreen(
|
||||
vm: AppViewModel,
|
||||
initial: Agent?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
val isNew = initial == null
|
||||
var draft by remember { mutableStateOf(initial ?: Agent(avatar = "custom")) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var promptDraft by remember { mutableStateOf(draft.systemPrompt) }
|
||||
var limitDraft by remember { mutableStateOf(
|
||||
if (draft.tokenLimit > 0) draft.tokenLimit.toInt().toString() else ""
|
||||
) }
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// 选一张外观图 → 读字节 → base64 → 立刻上传
|
||||
// ★ 不等"保存":图片可能好几 MB,混在保存里用户会以为卡死了
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
|
||||
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
|
||||
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
|
||||
}
|
||||
|
||||
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
|
||||
// ★ 包里**只有**名字/介绍/提示词/外观四件套 —— 模型引用、世界观绑定、限额
|
||||
// 一律不进包(需求 2.5 的"包的边界约定"),更不会有 API Key。
|
||||
var pendingZip by remember { mutableStateOf<String?>(null) }
|
||||
val saveZip = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.CreateDocument("application/zip"),
|
||||
) { uri ->
|
||||
val data = pendingZip
|
||||
pendingZip = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)
|
||||
?.use { it.write(Base64.decode(data, Base64.DEFAULT)) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (isNew) "新建智能体" else "编辑智能体",
|
||||
subtitle = if (isNew) "保存后可以加外观图片" else draft.name,
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
vm.saveAgentFull(
|
||||
draft.copy(systemPrompt = promptDraft, tokenLimit = limitDraft.toDoubleOrNull() ?: 0.0),
|
||||
isNew,
|
||||
) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
// 编辑中的智能体可能是**别处刚改过**的(比如刚上传完图片)——
|
||||
// vm.agents 里的那份才是最新的,这里同步一下,否则预览是旧的
|
||||
val fresh = vm.agents.firstOrNull { it.id == draft.id }
|
||||
if (!isNew && fresh != null && fresh.image != draft.image) {
|
||||
draft = draft.copy(image = fresh.image)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
|
||||
/* ---------------- 基本信息 ---------------- */
|
||||
SectionLabel("基本信息")
|
||||
Card {
|
||||
LabeledField("名字", draft.name, "比如:玄辰") { draft = draft.copy(name = it) }
|
||||
Spacer(Modifier.height(10.dp))
|
||||
LabeledField("一句话介绍", draft.greeting, "列表里的摘要,比如:仙门大师兄") {
|
||||
draft = draft.copy(greeting = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("显示在智能体列表里。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
LabeledField("介绍文案", draft.description, "选择界面右边那个介绍框里显示的话") {
|
||||
draft = draft.copy(description = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("★ 和上面那条不一样:这条只在选择智能体时的介绍框里显示。留空就只显示名字。")
|
||||
}
|
||||
|
||||
/* ---------------- 外观 ---------------- */
|
||||
SectionLabel("外观")
|
||||
Card {
|
||||
if (isNew) {
|
||||
// ★ 图片要落到"这个智能体的资源目录"里,所以必须先在库里有一条记录
|
||||
Text(
|
||||
"先点右上角「保存」把智能体建出来,再回来加外观图片。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// ---- 立绘:五档(v1.2 需求 2.5 / 2.6)----
|
||||
//
|
||||
// ★ 槽位名带档位(`front:喜`),内核按这个落到不同文件 ——
|
||||
// 五档存成一张的话会互相覆盖。
|
||||
Text("角色立绘(按情绪换)", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Hint(
|
||||
"情绪的五档各自一张图,缺哪档就退回「平常」那张。" +
|
||||
"现在显示的是「${draft.image.portrait.ifBlank { "内置默认人物" }}」那张。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (preset in PRESETS) {
|
||||
AssetRow(
|
||||
title = preset,
|
||||
desc = portraitHint(preset),
|
||||
path = draft.image.slot(preset),
|
||||
onPick = {
|
||||
pendingSlot = "front:$preset"
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// ---- 其余三件套 ----
|
||||
Text("其他三件套", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for ((key, title, desc) in ASSET_SLOTS) {
|
||||
AssetRow(
|
||||
title = title,
|
||||
desc = desc,
|
||||
path = draft.image.pathOf(key),
|
||||
onPick = { pendingSlot = key; pickImage.launch(arrayOf("image/*")) },
|
||||
onClear = { vm.uploadAgentAsset(draft.id, key, "", "") },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("支持 PNG / JPG / GIF(动图会动)。SVG 也能显示。缺哪张就用内置默认。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 人设 ---------------- */
|
||||
SectionLabel("人设(系统提示词)")
|
||||
Card {
|
||||
OutlinedTextField(
|
||||
value = promptDraft,
|
||||
onValueChange = { promptDraft = it },
|
||||
placeholder = { Text("你是一个……", fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("留空就用全局系统提示词。记忆、情绪、世界观、技能会自动拼在这后面,不用你自己写。")
|
||||
}
|
||||
|
||||
/* ---------------- 模型 ---------------- */
|
||||
SectionLabel("模型")
|
||||
Card {
|
||||
val entries = vm.state.modelEntries
|
||||
if (entries.isEmpty()) {
|
||||
Hint("还没有全局模型。去「设置 → 超时」上面的「全局模型」里加一个,就能在这里引用它。")
|
||||
} else {
|
||||
ChipRow(
|
||||
options = listOf("" to "跟随全局") + entries.map { it.id to it.name },
|
||||
active = draft.modelId,
|
||||
onPick = { draft = draft.copy(modelId = it) },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("选了它就固定用那个模型;「跟随全局」= 用设置里当前选的那个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 世界观 ---------------- */
|
||||
SectionLabel("世界观")
|
||||
Card {
|
||||
val worlds = vm.state.worldviews
|
||||
ChipRow(
|
||||
options = listOf("" to "不绑定") + worlds.map { it.id to it.name },
|
||||
active = draft.worldviewId,
|
||||
onPick = { draft = draft.copy(worldviewId = it) },
|
||||
)
|
||||
if (draft.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// ★ 选世界观的时候就要看到"已经有谁在"(用户问的"哪些智能体绑了它")。
|
||||
// 这是**决策依据**:如果里面已经有三个角色,加进去意味着
|
||||
// 四份记忆混在一个空间里;如果只有它一个,那基本等于私有。
|
||||
val wv = vm.state.worldviews.firstOrNull { it.id == draft.worldviewId }
|
||||
val others = (wv?.agents ?: emptyList()).filter { it.id != draft.id }
|
||||
Text(
|
||||
if (others.isEmpty()) "目前只有它用这个世界观(记忆实际上还是自己一份)"
|
||||
else "已经有 ${others.size} 个智能体在用:${others.joinToString("、") { it.name }}",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (others.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定," +
|
||||
"而且记忆会和上面这些智能体共享(它们也能看到并写入同一个空间," +
|
||||
"但只能改自己写的那几条)。\n" +
|
||||
"情绪仍然是私有的(不会共享)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
if (worlds.isEmpty()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("还没有世界观。在「更多功能 → 世界观」里新建或导入一个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 能力 ---------------- */
|
||||
SectionLabel("能力")
|
||||
Card {
|
||||
ToggleRow(
|
||||
title = "情绪感知",
|
||||
sub = "能看到同世界观其他智能体当前的情绪(只读,单向)",
|
||||
checked = draft.emotionEnabled,
|
||||
onChange = { draft = draft.copy(emotionEnabled = it) },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("Token 限额", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = limitDraft,
|
||||
onValueChange = { s -> limitDraft = s.filter { it.isDigit() }.take(9) },
|
||||
placeholder = { Text("留空 = 无限制", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
// ★ v1.2 §6.1:拉起其他智能体的方式。
|
||||
// 内核(`agent_tools.invite_agent`)早就按这个字段分流了,
|
||||
// 但界面上一直**没有入口** —— 于是 `confirm` 那一档
|
||||
// 用户永远打不开,等于需求里这个选项不存在。
|
||||
ToggleRow(
|
||||
title = "拉人要先问我",
|
||||
sub = "打开后,AI 想邀请别的智能体进群时会先问一句;" +
|
||||
"关闭则直接拉进来(都会在正文里说一声)。",
|
||||
checked = draft.inviteMode == "confirm",
|
||||
onChange = { draft = draft.copy(inviteMode = if (it) "confirm" else "silent") },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
SectionLabel("技能(Skill)")
|
||||
Card {
|
||||
val all = vm.state.skills
|
||||
if (all.isEmpty()) {
|
||||
Hint("还没有自定义 Skill。内置的记忆/情绪/用量手册默认就生效,不用在这里选。")
|
||||
} else {
|
||||
for (s in all) {
|
||||
val on = s.id in draft.skillIds
|
||||
ToggleRow(
|
||||
title = s.name.ifBlank { "未命名 Skill" },
|
||||
sub = s.content.lineSequence().firstOrNull()?.take(60) ?: "",
|
||||
checked = on,
|
||||
onChange = { v ->
|
||||
draft = draft.copy(
|
||||
// ★ 按**勾选顺序**排:需求 3.7 说"按绑定顺序拼接注入",
|
||||
// 顺序会影响模型读到的先后,所以不能是 Set
|
||||
skillIds = if (v) draft.skillIds + s.id
|
||||
else draft.skillIds.filter { it != s.id },
|
||||
)
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("勾选顺序就是注入顺序(先勾的在前)。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 语音 ---------------- */
|
||||
SectionLabel("语音")
|
||||
Card {
|
||||
// ★ 这里**只选音色**,不选引擎 —— 引擎是"用哪套语音服务",
|
||||
// 属于全局设置(换引擎时音色名整套都不一样,混在一个界面里
|
||||
// 必然出现"选了引擎、音色还是上一家的"这种状态)。
|
||||
Hint("引擎跟随全局(在「设置 → 语音」里换)。想给这个智能体一个不同的嗓音,就在下面选音色。")
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val engine = vm.state.speech.ttsEngine
|
||||
VoicePickerInline(
|
||||
engine = engine,
|
||||
voices = vm.state.speechVoices[engine] ?: emptyList(),
|
||||
voicesAll = vm.state.speechVoicesAll[engine] ?: emptyList(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 状态数值 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
BigAction("看它记住了什么") { vm.openMemories(draft.id) }
|
||||
BigAction("看它用了多少") { vm.openTokenUsage(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★★ 「它的状态」这个标题下面**原来只有记忆和用量两个按钮** ——
|
||||
// 状态数值页自己写着"三个入口:聊天页状态栏 / 智能体编辑的
|
||||
// 它的状态 / 群成员的状态",而中间那个**从来没做出来**。
|
||||
// 结果是:用户在群里能点到「状态」,在智能体编辑页却点不到。
|
||||
BigAction("看它的数值和状态") { vm.openStats(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp)) {
|
||||
Hint(
|
||||
"记忆是 AI 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。数值和状态由它绑定的世界观上的" +
|
||||
"「数值状态包」定义。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 删除 ---------------- */
|
||||
if (!isNew) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
RowAction("导出这个智能体(.zip)") {
|
||||
vm.exportPackage("agents", draft.id) { content, _ -> pendingZip = content }
|
||||
}
|
||||
Text(
|
||||
"包里只有名字、介绍、提示词和外观图片;模型、世界观、限额不进包,更没有 API Key。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
if (pendingZip != null) {
|
||||
LaunchedEffect(pendingZip) {
|
||||
saveZip.launch("${draft.name.ifBlank { "agent" }}.zip")
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isNew && !draft.builtin) {
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) {
|
||||
RowAction("删除这个智能体", danger = true) {
|
||||
vm.deleteAgentFull(draft.id) { onDone() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun AgentImage.pathOf(key: String): String = when (key) {
|
||||
// v1.2:立绘是五档表,编辑界面的**预览**用内核算好的那张
|
||||
// (其他三件套还是单张)
|
||||
"front" -> portrait
|
||||
"back" -> back
|
||||
"border-main" -> borderMain
|
||||
else -> borderInfo
|
||||
}
|
||||
|
||||
// ★ `Card` / `Hint` 已经挪到 DoubaoUi.kt 变成公共组件了 ——
|
||||
// 原来它们是这个文件私有的,于是别的界面想用只能复制一份
|
||||
// ([群成员] 就要用),而"同一段逻辑抄两份"是这个仓库的老毛病。
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
private fun BigAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LabeledField(
|
||||
label: String,
|
||||
value: String,
|
||||
placeholder: String,
|
||||
onChange: (String) -> Unit,
|
||||
) {
|
||||
Text(label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onChange,
|
||||
placeholder = { Text(placeholder, fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChipRow(
|
||||
options: List<Pair<String, String>>,
|
||||
active: String,
|
||||
onPick: (String) -> Unit,
|
||||
) {
|
||||
Column {
|
||||
for (row in options.chunked(3)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 3.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
for ((key, label) in row) {
|
||||
val on = key == active
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { onPick(key) }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToggleRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
checked: Boolean,
|
||||
onChange: (Boolean) -> Unit,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
if (sub.isNotBlank()) {
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 15.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (checked) Doubao.Blue else Doubao.Border)
|
||||
.clickable { onChange(!checked) },
|
||||
contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 一个外观槽位:小预览 + 标题说明 + 选图 / 清除 */
|
||||
@Composable
|
||||
private fun AssetRow(
|
||||
title: String,
|
||||
desc: String,
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(52.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (path.isBlank()) {
|
||||
if (showDefaultPerson) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
} else {
|
||||
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
} else {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, lineHeight = 14.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
RowAction("选择") { onPick() }
|
||||
if (path.isNotBlank()) RowAction("清除", danger = true) { onClear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/*
|
||||
* 智能体选择界面(需求第二章)。
|
||||
*
|
||||
* ## 布局(需求 2.1)
|
||||
*
|
||||
* 左侧:智能体列表(纵向、当前项高亮)
|
||||
* 右侧:角色展示区,**四层叠加**:
|
||||
* ① 背景图(铺满)② 主体边框(框住展示区)③ 角色图(居中)④ 介绍边框(围住介绍文本)
|
||||
*
|
||||
* ## 切换动画(需求 2.3,定稿参数)
|
||||
*
|
||||
* ① 旧角色图渐出 + 侧移 0.3s ease-in
|
||||
* ② 间隔 0.5s
|
||||
* ③ 边框/背景/介绍 滑出滑入 0.4s ease-in-out
|
||||
* ④ 新角色图渐入 + 侧移到位 0.3s ease-out
|
||||
* 合计约 1.5s。
|
||||
*
|
||||
* **方向**:目标在当前**之下**(列表靠后)→ 向左切换;**之上** → 向右。
|
||||
*
|
||||
* **连续快速切换立即打断**:靠 `LaunchedEffect(选中的 id)` —— 换目标时
|
||||
* 上一个协程直接被取消,而 `Animatable` 会**停在当前值**,所以新动画
|
||||
* 是从眼前的画面接着走的,不会闪回。这正是需求要的"从当前视觉状态
|
||||
* 直接过渡到最新目标,不做排队"。
|
||||
*
|
||||
* ## ★ 默认资源回退(需求 2.6)
|
||||
*
|
||||
* 角色图缺 → 内置默认人物;背景缺 → 内置默认背景;边框缺 → **简单方框**。
|
||||
* 回退优先级:`smartInfo.json 指定 → 包内同名 → 内置默认`。
|
||||
* 前两级在内核导入时就落定了(存的是绝对路径),所以这里只做最后一级。
|
||||
*
|
||||
* ★ "任何智能体至少能以「默认人物 + 默认背景 + 方框边框」正常展示" ——
|
||||
* 所以**每个槽位都必须有兜底**,不能出现空白展示区。
|
||||
*/
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 动画参数(需求 2.3:所有时长收进全局配置) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* ★ 下面这四个是**兜底默认值**,真正生效的值从全局配置里读
|
||||
* (设置 →「超时」→「动画」那一组,内核 `timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 为什么不在这里写死:需求 2.3 明确要求"所有时长与缓动数值收进全局配置"。
|
||||
* 用户嫌 1.5 秒的切换太慢时,改「中间留白」就能缩到 1.0 秒。
|
||||
*
|
||||
* 复用"超时"那套数值体系(而不是在 settings 里再开一个 agentAnim 对象)
|
||||
* 的理由写在 timeouts.py 那一段注释里:再造一套就是第二份要同步的东西。
|
||||
*/
|
||||
private fun animMs(key: String, fallback: Int): Int {
|
||||
val sec = com.doubao.lynxclone.data.AppTimeouts.seconds(key, fallback / 1000.0)
|
||||
// 0 是合法的(「中间留白」调成 0 = 不停顿),所以不能拿 0 当"没配"
|
||||
return if (sec.isNaN() || sec < 0) fallback else (sec * 1000).toInt()
|
||||
}
|
||||
|
||||
private const val DEF_FRONT_OUT = 300 // ① 旧角色图出
|
||||
private const val DEF_GAP = 500 // ② 间隔
|
||||
private const val DEF_FRAME = 400 // ③ 边框/背景/介绍(滑出 + 滑入各一半)
|
||||
private const val DEF_FRONT_IN = 300 // ④ 新角色图进
|
||||
|
||||
/** 侧移幅度占展示区宽度的比例。需求只说"侧移",幅度大了像翻页、小了看不出来 */
|
||||
private const val SHIFT = 0.10f
|
||||
|
||||
@Composable
|
||||
fun AgentSelectScreen(
|
||||
vm: AppViewModel,
|
||||
agents: List<Agent>,
|
||||
activeId: String,
|
||||
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
|
||||
onEnter: (Agent) -> Unit,
|
||||
/** 「更多」→ Token 用量详情(需求 2.4) */
|
||||
onMore: (Agent) -> Unit,
|
||||
/** 「记忆」→ 看它记住了什么(记忆管理界面的主入口) */
|
||||
onMemories: (Agent) -> Unit,
|
||||
/** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */
|
||||
onManage: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
if (agents.isEmpty()) {
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg()), verticalArrangement = Arrangement.Center) {
|
||||
Text("还没有智能体", Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = doubaoText())
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("点右上角「管理」新建或导入一个", Modifier.fillMaxWidth(),
|
||||
textAlign = TextAlign.Center, fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TopAction("去管理", onClick = onManage)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val startIndex = agents.indexOfFirst { it.id == activeId }.coerceAtLeast(0)
|
||||
var picked by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
// `shown` 是**画面上正在显示**的那个;picked 变了之后要等动画走到第③阶段才换它
|
||||
var shown by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
val shownAgent = agents.getOrNull(shown) ?: agents.first()
|
||||
val pickedAgent = agents.getOrNull(picked) ?: agents.first()
|
||||
|
||||
// ★ 进这一页就拉一遍所有智能体的数值/状态(卡片上要显示)。
|
||||
// 失败就保持上一份 —— 卡片上少几个数字不该报错打扰用户。
|
||||
LaunchedEffect(Unit) { vm.refreshAllStats() }
|
||||
|
||||
val frontAlpha = remember { Animatable(1f) }
|
||||
val frontShift = remember { Animatable(0f) }
|
||||
val frameAlpha = remember { Animatable(1f) }
|
||||
val frameShift = remember { Animatable(0f) }
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
// 每次重组都读一遍全局配置(用户在设置里改完回来,下一次切换就是新时长)
|
||||
val tFrontOut = animMs("agentAnim.frontOut", DEF_FRONT_OUT)
|
||||
val tGap = animMs("agentAnim.gap", DEF_GAP)
|
||||
val tFrame = animMs("agentAnim.frame", DEF_FRAME)
|
||||
val tFrontIn = animMs("agentAnim.frontIn", DEF_FRONT_IN)
|
||||
|
||||
LaunchedEffect(picked, agents.size) {
|
||||
if (picked == shown) return@LaunchedEffect
|
||||
// 目标在列表靠后 = 向左切换(新内容从右边进来)
|
||||
val dir = if (picked > shown) 1f else -1f
|
||||
|
||||
// ① 旧角色图渐出 + 侧移
|
||||
launch { frontAlpha.animateTo(0f, tween(tFrontOut, easing = FastOutSlowInEasing)) }
|
||||
frontShift.animateTo(-dir * SHIFT, tween(tFrontOut, easing = FastOutSlowInEasing))
|
||||
|
||||
// ② 间隔(需求明确定义了这一段留白;调成 0 就跳过)
|
||||
if (tGap > 0) delay(tGap.toLong())
|
||||
|
||||
// ③ 边框 / 背景 / 介绍:滑出 → 换数据 → 滑入
|
||||
val half = (tFrame / 2).coerceAtLeast(1)
|
||||
launch { frameAlpha.animateTo(0f, tween(half, easing = FastOutSlowInEasing)) }
|
||||
frameShift.animateTo(-dir * SHIFT, tween(half, easing = FastOutSlowInEasing))
|
||||
shown = picked
|
||||
launch { frameAlpha.animateTo(1f, tween(half, easing = LinearOutSlowInEasing)) }
|
||||
frameShift.animateTo(0f, tween(half, easing = LinearOutSlowInEasing))
|
||||
|
||||
// ④ 新角色图渐入 + 侧移到位
|
||||
frontShift.snapTo(dir * SHIFT)
|
||||
launch { frontAlpha.animateTo(1f, tween(tFrontIn, easing = LinearOutSlowInEasing)) }
|
||||
frontShift.animateTo(0f, tween(tFrontIn, easing = LinearOutSlowInEasing))
|
||||
}
|
||||
|
||||
// 选中的那项滚进视野(列表长了之后不滚的话用户看不到自己选了谁)
|
||||
LaunchedEffect(picked) {
|
||||
runCatching { listState.animateScrollToItem(picked) }
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
// ---------------- 顶栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"← 返回",
|
||||
fontSize = 14.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onBack() }.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
"选择智能体",
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
TopTextAction("管理", onClick = onManage)
|
||||
}
|
||||
|
||||
// ---------------- 展示区 ----------------
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(horizontal = 8.dp)
|
||||
.clip(RoundedCornerShape(18.dp)),
|
||||
) {
|
||||
// ① 背景图(最底层,铺满)—— 缺就用内置默认背景
|
||||
ArtworkFill(shownAgent.image.back, R.drawable.agent_default_background)
|
||||
|
||||
// ② 左侧列表(浮在背景上)
|
||||
AgentList(
|
||||
agents = agents,
|
||||
picked = picked,
|
||||
onPick = { picked = it },
|
||||
state = listState,
|
||||
// ★★ 用户要求「数字界面在智能体卡片里展示」——
|
||||
// 卡片上直接显示这个角色的数值和状态,不用点进去才看得到。
|
||||
stats = vm.allStats,
|
||||
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
|
||||
)
|
||||
|
||||
// ③ 角色图(居中)。★ 它和右侧的边框/介绍一起跟着 frameShift 动
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = 96.dp, end = 10.dp, top = 10.dp, bottom = 10.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.offset(x = (frameShift.value * 180).dp)
|
||||
.alpha(frameAlpha.value),
|
||||
) {
|
||||
// ③-1 角色图
|
||||
Box(
|
||||
Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp),
|
||||
) {
|
||||
ArtworkFill(
|
||||
shownAgent.image.portrait,
|
||||
R.drawable.agent_default_character,
|
||||
alpha = frontAlpha.value,
|
||||
scale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
|
||||
// ③-2 介绍边框 + 介绍文本(需求 2.1 的第 4 层)
|
||||
IntroCard(
|
||||
agent = shownAgent,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(end = 6.dp, bottom = 10.dp)
|
||||
.width(200.dp),
|
||||
)
|
||||
|
||||
// ③-3 主体边框(画在最上层,纯装饰)
|
||||
MainBorder(shownAgent.image.borderMain)
|
||||
}
|
||||
}
|
||||
|
||||
// ④ 「更多」按钮(需求 2.4:圆形、竖排三点、在角色图附近)→ Token 用量
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 10.dp, end = 12.dp)
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color(0xCC1B2430))
|
||||
.clickable { onMore(shownAgent) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.MoreVert,
|
||||
contentDescription = "用量详情",
|
||||
tint = Color(0xFFE8EAED),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 底部:进对话 / 看记忆 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★「记忆」和「开始对话」并排:进对话之前顺手看一眼它记住了什么。
|
||||
// 记忆是这个功能里最需要"用户能看见"的东西 —— AI 会记错
|
||||
// (把"喜欢猫"记成"讨厌猫"很常见),看见了才能改。
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { onMemories(pickedAgent) }
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("记忆", fontSize = 15.sp, color = doubaoText())
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(
|
||||
Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))),
|
||||
)
|
||||
.clickable { onEnter(pickedAgent) }
|
||||
.padding(vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"开始对话",
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color.White,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 四层的具体画法 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** 铺满一层图;没有就用内置默认(需求 2.6 的最后一级回退) */
|
||||
@Composable
|
||||
private fun ArtworkFill(
|
||||
path: String,
|
||||
fallbackRes: Int,
|
||||
alpha: Float = 1f,
|
||||
scale: ContentScale = ContentScale.Crop,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().alpha(alpha)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
fallback = {
|
||||
// ★ 内置默认图:**必须画出来**,不能是空白 ——
|
||||
// 需求原话"任何智能体至少能以默认人物+默认背景+方框边框正常展示"
|
||||
Image(
|
||||
painter = painterResource(fallbackRes),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 主体边框。缺的时候用**简单方框**(纯色细线矩形)兜底 */
|
||||
@Composable
|
||||
private fun MainBorder(path: String) {
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
if (canShowImage(path)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.FillBounds,
|
||||
fallback = { SimpleFrame(shape) },
|
||||
)
|
||||
} else {
|
||||
SimpleFrame(shape)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SimpleFrame(shape: RoundedCornerShape) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.border(1.dp, Doubao.Blue.copy(alpha = 0.45f), shape),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 介绍卡片(需求 2.1 的"介绍边框 + 介绍文本")。
|
||||
*
|
||||
* 文本来自 `description`;缺失时**只显示智能体名**(需求原文)。
|
||||
*/
|
||||
@Composable
|
||||
private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Color(0xE6FFFDF5))
|
||||
.border(1.dp, Color(0x66B9A46A), RoundedCornerShape(14.dp))
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
agent.name,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color(0xFF2A2419),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val desc = agent.description.trim().ifBlank { agent.greeting.trim() }
|
||||
if (desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
desc,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF4A4232),
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字 + **数值/状态**;当前项高亮 */
|
||||
@Composable
|
||||
private fun AgentList(
|
||||
agents: List<Agent>,
|
||||
picked: Int,
|
||||
onPick: (Int) -> Unit,
|
||||
state: androidx.compose.foundation.lazy.LazyListState,
|
||||
/** agentId → 它的数值/状态(只有挂了规则包的智能体在里面) */
|
||||
stats: Map<String, com.doubao.lynxclone.data.AgentStats>,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
itemsIndexed(agents) { index, agent ->
|
||||
val on = index == picked
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (on) Color(0xCC2B7BFF) else Color(0x99101820))
|
||||
.border(
|
||||
width = if (on) 1.5.dp else 0.5.dp,
|
||||
color = if (on) Color(0xFFFFE08A) else Color(0x33FFFFFF),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.clickable { onPick(index) }
|
||||
.padding(4.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
// 缩略图:也用角色图(缺就默认人物)—— 和右侧是同一套回退。
|
||||
// ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会
|
||||
// 裁出"腰到大腿",一排缩略图全是裤子
|
||||
AssetImage(
|
||||
path = agent.image.portrait,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
fallback = {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
agent.name.ifBlank { "未命名" },
|
||||
fontSize = 11.sp,
|
||||
color = Color.White,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
|
||||
// ★★ 数值和状态(用户要求「数字界面在智能体卡片里展示」)。
|
||||
//
|
||||
// 卡片只有 96dp 宽,所以这里**极简**:
|
||||
// · 第一条数值 + 迷你进度条(一眼看出高低)
|
||||
// · 有状态就再压一行名字(圆点 + 名字,多了就 N 个点)
|
||||
//
|
||||
// ★ 只显示**第一条**数值是有意的:卡片上放大而全的数值表
|
||||
// 等于把 [状态数值] 页塞进 96dp,谁也看不清;
|
||||
// 想细看就点进去。这里要回答的只是"这个角色现在什么情况"。
|
||||
val st = stats[agent.id]
|
||||
if (st != null && st.stats.isNotEmpty()) {
|
||||
val main = st.stats.first()
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"${main.name} ${fmtNum(main.value)}",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFFFFE08A),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
// 迷你进度条:3dp 高,一眼看出比例,不占地方
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(3.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(main.ratio())
|
||||
.height(3.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Color(0xFFFFE08A)),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (st != null && st.statuses.isNotEmpty()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
st.statuses.joinToString(" · ") { it.name },
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8FE0A0),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.StatValue
|
||||
import com.doubao.lynxclone.data.StatusInstance
|
||||
|
||||
/**
|
||||
* [状态数值](v1.2 §3.10 数值 / §3.11 状态)。
|
||||
*
|
||||
* ## 三个入口共用这一个界面
|
||||
*
|
||||
* 需求 §6.1 指定的三个入口:**聊天页状态栏** / **智能体编辑的"它的状态"** /
|
||||
* **群成员的「状态」按钮**。三处都调 `vm.openStats(agentId)`。
|
||||
*
|
||||
* ★ 只写一个界面是有意的:三个入口各写一份的话,"数值怎么显示、
|
||||
* 能不能改、状态剩几轮怎么标"这三件事会各有一套说法 ——
|
||||
* 而这个仓库里"同一逻辑抄两份"已经反复出现过。
|
||||
*
|
||||
* ## 用户能直接改数值,AI 不能
|
||||
*
|
||||
* AI 的 `change_stat` 只能申请**增量**,还要过脚本裁决(§3.10)。
|
||||
* 用户是规则的主人 —— 点一下就能直接设成任何值。
|
||||
* 但内核照样会 clamp 到 `[min,max]`:超出范围的值会让进度条和区间注入
|
||||
* 全都错位。所以**回来之后要以返回值刷新**,不能乐观地先用自己填的。
|
||||
*/
|
||||
@Composable
|
||||
fun AgentStatsScreen(
|
||||
vm: AppViewModel,
|
||||
agentId: String,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val stats = vm.agentStats
|
||||
var editing by remember { mutableStateOf("") }
|
||||
var input by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "状态数值",
|
||||
subtitle = stats?.name?.takeIf { it.isNotBlank() } ?: "读不出来",
|
||||
onBack = onBack,
|
||||
) {
|
||||
if (stats == null) {
|
||||
Hint("正在读……")
|
||||
return@FullScreen
|
||||
}
|
||||
if (stats.rulePackId.isBlank()) {
|
||||
// 没挂规则包就没有数值系统 —— 如实说清楚,别让用户以为是加载失败
|
||||
Hint(
|
||||
"这个智能体还没有数值系统。\n\n" +
|
||||
"数值和状态由「数值状态包」定义 —— 去 资源 → 规则包 " +
|
||||
"建一个(或导入一个),再把它挂到智能体所在的世界观上。",
|
||||
)
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("数值")
|
||||
Card {
|
||||
if (stats.stats.isEmpty()) {
|
||||
Hint("这个规则包里没有数值。")
|
||||
}
|
||||
for (s in stats.stats) {
|
||||
StatRow(
|
||||
stat = s,
|
||||
editing = editing == s.name,
|
||||
input = input,
|
||||
onInput = { input = it },
|
||||
onStartEdit = { editing = s.name; input = fmtNum(s.value) },
|
||||
onCancel = { editing = "" },
|
||||
onCommit = {
|
||||
vm.setStatDirect(s.name, input.toDoubleOrNull() ?: s.value)
|
||||
editing = ""
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (stats.rulePackName.isNotBlank()) {
|
||||
Hint("来自规则包「${stats.rulePackName}」。")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态")
|
||||
Card {
|
||||
if (stats.statuses.isEmpty()) {
|
||||
Hint("身上没有状态。")
|
||||
}
|
||||
for (st in stats.statuses) {
|
||||
// ★ 每条状态都能**清掉**。AI 手里只有 `grant_status`(只能加),
|
||||
// 没有任何工具能移除状态 —— 所以这个按钮是唯一的出口:
|
||||
// `persistent` 状态不会自己过期,没有它就永远下不来。
|
||||
StatusRow(st, onDrop = { vm.dropStatusDirect(st.name) })
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"定时状态每参与一轮减 1,归零就消失;持久状态不会自己过期。" +
|
||||
"状态提示词会被注入到它的系统提示里。",
|
||||
)
|
||||
|
||||
// ---- 手动挂一个状态 ----
|
||||
//
|
||||
// 只在包里有**还没挂上**的状态定义时才显示 —— 全都挂上了就没东西可加了,
|
||||
// 摆一排点不动的按钮反而让人以为坏了。
|
||||
val notOn = stats.statusDefs.filter { d -> stats.statuses.none { it.name == d.name } }
|
||||
if (notOn.isNotEmpty()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("加一个")
|
||||
Card {
|
||||
Hint("AI 只能给自己加状态,你也可以直接挂 —— 用来测效果或者补剧情。")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for (d in notOn) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth()
|
||||
.clickable { vm.addStatusDirect(d.name, d.turns) }
|
||||
.padding(vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(d.name, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
if (d.isPersistent) "持久 · 不会自己过期"
|
||||
else "定时 · ${d.turns} 轮后消失",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("挂上") { vm.addStatusDirect(d.name, d.turns) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatRow(
|
||||
stat: StatValue,
|
||||
editing: Boolean,
|
||||
input: String,
|
||||
onInput: (String) -> Unit,
|
||||
onStartEdit: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
onCommit: () -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stat.name, fontSize = 13.sp, color = doubaoText(), modifier = Modifier.weight(1f))
|
||||
if (stat.shared) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag("全世界观共用")
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
if (editing) {
|
||||
// 直接设值 —— 用户主权。★ 就地在行内变成输入框,不再压一层
|
||||
// 对话框(AGENTS.md:一次输入用弹窗也行,但这里已经有上下文,
|
||||
// 就地改更省事,而且弹窗会盖住进度条)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = onInput,
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.width(84.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("好") { onCommit() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
RowAction("取消") { onCancel() }
|
||||
} else {
|
||||
Text(
|
||||
"${fmtNum(stat.value)} / ${fmtNum(stat.max)}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("改") { onStartEdit() }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// 进度条:`ratio()` 在模型里(三个入口共用一份换算,圆角和取整才不会各说各话)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
if (stat.text.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(stat.text, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(st: StatusInstance, onDrop: () -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(st.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag(if (st.isPersistent) "持久" else "剩 ${st.remaining} 轮")
|
||||
if (st.stacks > 1) {
|
||||
Spacer(Modifier.width(4.dp))
|
||||
TinyTag("×${st.stacks}")
|
||||
}
|
||||
}
|
||||
if (st.hint.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(st.hint, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
// ★ 清掉。这是用户手动移除状态的**唯一出口**(AI 没这个能力)。
|
||||
// 不做二次确认:状态本来就可以再加回来,而多一层确认会让
|
||||
// "连清五个"变成五次弹窗 —— 手机上很烦。
|
||||
RowAction("清掉") { onDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TinyTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭。
|
||||
*
|
||||
* ★ 现在**两处**在用(状态数值页 + 智能体卡片),所以是 `internal` 不是 private ——
|
||||
* 卡片那边要显示同样的数字,抄一份就是第二份实现("同一逻辑只能有一份")。
|
||||
*/
|
||||
internal fun fmtNum(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
@@ -72,15 +73,33 @@ import com.doubao.lynxclone.data.VoiceOption
|
||||
*/
|
||||
@Composable
|
||||
fun AgentsScreen(vm: AppViewModel) {
|
||||
var editing by remember { mutableStateOf<Agent?>(null) }
|
||||
var creating by remember { mutableStateOf(false) }
|
||||
var confirmDelete by remember { mutableStateOf<Agent?>(null) }
|
||||
|
||||
// ★ 导入智能体包(需求 2.5):zip → base64 → 内核解包。
|
||||
// 不走 Kotlin 解压是因为安卓的 `ZipInputStream` **读不出**这类 zip
|
||||
// (Termux bootstrap 那个坑,见 TermuxInstaller 的注释),
|
||||
// 而内核的 Python `zipfile` 没这个问题 —— 少踩一次已知的坑。
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
val importPackage = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
vm.importPackage("agents", android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP), "")
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
val activeId = vm.state.activeAgent?.id.orEmpty()
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) {
|
||||
TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) }
|
||||
TextButton(onClick = {
|
||||
importPackage.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
}) { Text("导入", fontSize = 13.sp) }
|
||||
TextButton(onClick = { vm.openAgentEdit(null) }) { Text("新建", fontSize = 13.sp) }
|
||||
}
|
||||
|
||||
Column(
|
||||
@@ -103,8 +122,11 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
agent = agent,
|
||||
active = agent.id == activeId,
|
||||
onUse = { vm.useAgent(agent.id) },
|
||||
onEdit = { editing = agent },
|
||||
onEdit = { vm.openAgentEdit(agent) },
|
||||
onMemories = { vm.openMemories(agent.id) },
|
||||
onDelete = { confirmDelete = agent },
|
||||
worldName = vm.state.worldviews
|
||||
.firstOrNull { it.id == agent.worldviewId }?.name.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -113,7 +135,7 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { creating = true },
|
||||
onClick = { vm.openAgentEdit(null) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
contentPadding = PaddingValues(vertical = 12.dp),
|
||||
@@ -129,41 +151,29 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
/* ---------------- 新建 / 编辑 ---------------- */
|
||||
if (creating || editing != null) {
|
||||
val target = editing
|
||||
AgentEditDialog(
|
||||
agent = target,
|
||||
providers = vm.state.providers.values.toList(),
|
||||
voices = vm.state.speechVoices,
|
||||
voicesAll = vm.state.speechVoicesAll,
|
||||
globalTtsEngine = vm.state.speech.ttsEngine,
|
||||
onDismiss = { creating = false; editing = null },
|
||||
onSave = { draft ->
|
||||
vm.saveAgent(target?.id, draft) {
|
||||
creating = false
|
||||
editing = null
|
||||
}
|
||||
},
|
||||
onDelete = if (target != null && !target.builtin) {
|
||||
{ confirmDelete = target }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
//
|
||||
// ★ 编辑走的是 **AgentEditScreen(全屏)**,不是这里原来那个弹窗。
|
||||
// 字段从 8 个涨到二十多个(外观四件套 / 模型引用 / 世界观 / 限额 / 技能……),
|
||||
// 弹窗装不下 —— AGENTS.md 那张表写得很清楚。
|
||||
// 删除确认**仍然是弹窗**:它就是"一次确认",正好是弹窗该用的地方。
|
||||
|
||||
/* ---------------- 删除确认 ---------------- */
|
||||
confirmDelete?.let { agent ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = null },
|
||||
title = { Text("删除智能体", fontSize = 16.sp) },
|
||||
text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"确定删除「${agent.name}」吗?\n\n" +
|
||||
"它的系统提示词和外观会一起删掉,不能撤销。\n" +
|
||||
"**记忆会保留**(那是你攒下来的东西,删之前建议先导出)。",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.deleteAgent(agent.id)
|
||||
confirmDelete = null
|
||||
// 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404
|
||||
if (editing?.id == agent.id) editing = null
|
||||
}) { Text("删除") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } },
|
||||
@@ -179,7 +189,11 @@ private fun AgentRow(
|
||||
active: Boolean,
|
||||
onUse: () -> Unit,
|
||||
onEdit: () -> Unit,
|
||||
/** 看这个智能体记住了什么(记忆管理界面的入口之一) */
|
||||
onMemories: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
/** 它绑的世界观叫什么(空 = 没绑)。交互是双向的,这边也要看得见 */
|
||||
worldName: String = "",
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||
@@ -215,7 +229,23 @@ private fun AgentRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
// ★ 绑了哪个世界观(用户要求"互通")——
|
||||
// 重点不是"它有个世界观",而是**它和谁共用记忆**。
|
||||
// 所以文案直接写"共用记忆",而不是干巴巴一个名字。
|
||||
if (agent.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"世界观「${worldName.ifBlank { "已失效" }}」· 记忆与同世界的智能体共用",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★「记忆」放在「编辑」**左边**:它是"看它记住了什么",
|
||||
// 属于日常动作;编辑是配置动作,用得少。
|
||||
TextButton(onClick = onMemories) { Text("记忆", fontSize = 12.sp) }
|
||||
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
|
||||
if (!agent.builtin) {
|
||||
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
|
||||
@@ -255,185 +285,6 @@ private fun ActiveBadge() {
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun AgentEditDialog(
|
||||
agent: Agent?,
|
||||
providers: List<ProviderPreset>,
|
||||
voices: Map<String, List<VoiceOption>>,
|
||||
voicesAll: Map<String, List<VoiceOption>>,
|
||||
/** 全局当前的朗读引擎:智能体没选引擎时,音色列表要按它来给 */
|
||||
globalTtsEngine: String,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (Agent) -> Unit,
|
||||
onDelete: (() -> Unit)?,
|
||||
) {
|
||||
// 整份草稿:加字段时只要往 Agent 里加,不用再改一遍这里的所有 var
|
||||
var draft by remember {
|
||||
mutableStateOf(
|
||||
agent ?: Agent(avatar = "doubao"),
|
||||
)
|
||||
}
|
||||
var error by remember { mutableStateOf("") }
|
||||
val name = draft.name
|
||||
val avatar = draft.avatar
|
||||
val prompt = draft.systemPrompt
|
||||
val greeting = draft.greeting
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
FormLabel("头像")
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
AvatarKeys.forEach { key ->
|
||||
Box(Modifier.clickable { draft = draft.copy(avatar = key) }) {
|
||||
// 选中态画在 AvatarCircle 的外圈上,不改变尺寸
|
||||
AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("名称")
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { draft = draft.copy(name = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("例如:翻译官", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("问候语 / 一句话介绍")
|
||||
OutlinedTextField(
|
||||
value = greeting,
|
||||
onValueChange = { draft = draft.copy(greeting = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Text(
|
||||
"列表摘要会显示这句;新会话首屏也用它打招呼。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("系统提示词")
|
||||
OutlinedTextField(
|
||||
value = prompt,
|
||||
onValueChange = { draft = draft.copy(systemPrompt = it) },
|
||||
modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp),
|
||||
placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) },
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
)
|
||||
Text(
|
||||
"和它聊天时,这段提示词会覆盖全局系统提示词。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
/* ---------------- 模型(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("模型")
|
||||
Text(
|
||||
"不选就跟随「设置 → 连接与模型」里的全局配置。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") +
|
||||
providers.map { it.key to it.label },
|
||||
active = draft.provider,
|
||||
) { draft = draft.copy(provider = it) }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
// ★ 别把 `ifBlank{…} == "x" ? a : b` 写成一整行:Kotlin 会把那个 `?`
|
||||
// 当成安全调用开始解析,报一堆看不懂的语法错。拆成变量最稳。
|
||||
val followGlobalModel = draft.provider.isBlank()
|
||||
OutlinedTextField(
|
||||
value = draft.model,
|
||||
onValueChange = { draft = draft.copy(model = it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
placeholder = {
|
||||
Text(
|
||||
if (followGlobalModel) "留空 = 用全局模型" else "留空 = 用这家的默认模型",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
/* ---------------- 语音(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("语音")
|
||||
Text(
|
||||
"多人会议里靠它区分谁在说话 —— 几个智能体一个嗓子的话根本听不出谁在讲。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") + TtsEngineChoices,
|
||||
active = draft.ttsEngine,
|
||||
) { engine ->
|
||||
// 换引擎顺手清掉音色:音色是按引擎命名的(BVxxx / zh_xxx_bigtts),
|
||||
// 留着上一家的值一定会被判非法
|
||||
draft = draft.copy(ttsEngine = engine, ttsVoice = "")
|
||||
}
|
||||
val voiceEngine = draft.ttsEngine.ifBlank { globalTtsEngine }
|
||||
if (voiceEngine != "" && voiceEngine != "system") {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
VoicePickerInline(
|
||||
engine = voiceEngine,
|
||||
voices = voices[voiceEngine].orEmpty(),
|
||||
voicesAll = voicesAll[voiceEngine].orEmpty(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
if (error.isNotBlank()) {
|
||||
Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
if (draft.name.isBlank()) {
|
||||
error = "名称不能为空"
|
||||
} else {
|
||||
onSave(draft.copy(name = draft.name.trim(), greeting = draft.greeting.trim()))
|
||||
}
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = {
|
||||
Row {
|
||||
if (onDelete != null) {
|
||||
TextButton(onClick = onDelete) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
TextButton(onClick = onDismiss) { Text("取消") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 列表里那一行摘要文案 */
|
||||
private fun agentSummary(agent: Agent): String = when {
|
||||
agent.greeting.isNotBlank() -> agent.greeting
|
||||
agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手"
|
||||
@@ -495,7 +346,7 @@ internal fun WrapChips(
|
||||
* 拽进智能体页 —— 真要统一的话应该把它提成公共组件,那是另一件事。
|
||||
*/
|
||||
@Composable
|
||||
private fun VoicePickerInline(
|
||||
internal fun VoicePickerInline(
|
||||
engine: String,
|
||||
voices: List<VoiceOption>,
|
||||
voicesAll: List<VoiceOption>,
|
||||
@@ -0,0 +1,207 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
import androidx.compose.material.icons.filled.OpenInNew
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* ★★ 「AI 界面」列表 —— 用户要求"AI 写的界面可以再点开"。
|
||||
*
|
||||
* ## 为什么要有它
|
||||
*
|
||||
* 界面以前只活在内存里,一关就没了。用户过一会儿想"刚才那个图表再看一眼"
|
||||
* 就找不回来,只能让 AI 重新生成 —— 而**重新生成的内容不一定一样**
|
||||
* (模型有随机性),用户会觉得"我明明看过的东西怎么变了"。
|
||||
*
|
||||
* 所以每次 `show_ui` 都存一份到磁盘,这里列出它们。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面,不是弹窗
|
||||
*
|
||||
* 列表要滚动(一个会话可能攒十几个界面),弹窗装不下。
|
||||
* 顶栏用统一的 `← 返回 | 标题 | 副标题`。
|
||||
*/
|
||||
@Composable
|
||||
fun AiScreenListScreen(
|
||||
screens: List<AiScreenItem>,
|
||||
onOpen: (String) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("AI 界面", onBack = onClose) {
|
||||
Text(
|
||||
if (screens.isEmpty()) "还没有" else "${screens.size} 个",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
if (screens.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"AI 还没给你弹过界面。\n让它「弹个界面」试试。",
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 22.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
"点一下就能再打开。AI 生成的界面都存下来了,不用让它重做。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
items(screens.size) { index ->
|
||||
val s = screens[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onOpen(s.id) }
|
||||
.padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
s.title,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (s.preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
s.preview,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"${formatTime(s.at)} · ${formatBytes(s.bytes)}",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// 删除:单独一个小按钮,别让"点卡片"和"删除"挤在一起误触
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.clickable { onDelete(s.id) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
"删除",
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.OpenInNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 列表里的一条(从 AiSurface 的索引 JSON 转过来) */
|
||||
data class AiScreenItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val preview: String,
|
||||
val bytes: Int,
|
||||
val at: Long,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** 时间戳 → 「今天 14:03」/「10-15 14:03」。手机上不显示年份,太占地方 */
|
||||
private fun formatTime(ms: Long): String {
|
||||
if (ms <= 0) return ""
|
||||
val now = java.util.Calendar.getInstance()
|
||||
val then = java.util.Calendar.getInstance().apply { timeInMillis = ms }
|
||||
val sameDay = now.get(java.util.Calendar.YEAR) == then.get(java.util.Calendar.YEAR) &&
|
||||
now.get(java.util.Calendar.DAY_OF_YEAR) == then.get(java.util.Calendar.DAY_OF_YEAR)
|
||||
val fmt = SimpleDateFormat(if (sameDay) "'今天' HH:mm" else "MM-dd HH:mm", Locale.getDefault())
|
||||
return fmt.format(Date(ms))
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节数 → 人能看的字符串。
|
||||
*
|
||||
* ★ 不足 1KB 的要显示字节数:第一版写的是 `bytes / 1024` + "KB",
|
||||
* 于是 524 字节的界面显示成 **"0KB"**(看起来像"这个界面是空的")。
|
||||
* 整数除法把小于 1024 的一律变成 0 了。
|
||||
*/
|
||||
private fun formatBytes(n: Int): String = when {
|
||||
n <= 0 -> "—"
|
||||
n < 1024 -> "${n}B"
|
||||
n < 1024 * 1024 -> "${n / 1024}KB"
|
||||
else -> String.format(Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0)
|
||||
}
|
||||
@@ -0,0 +1,785 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.net.Uri
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
|
||||
/**
|
||||
* AI 主动弹出来的三个界面(都带进出动画)。
|
||||
*
|
||||
* 放在**导航之上**(见 AppRoot):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话在会议/设置页就看不到。
|
||||
*
|
||||
* 三个东西的动画各有讲究:
|
||||
* · HTML 界面 —— 从中心"长大"+ 淡入(像开一扇门),退出反向
|
||||
* · 选择弹窗 —— 从下方滑上来 + 淡入(手机上的惯例手势方向)
|
||||
* · 结束横幅 —— 从下方滑到**屏幕中间**停住,并且**留在那儿**(不自动消失)
|
||||
*/
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、AI 的 HTML 界面(show_ui) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiHtmlScreenOverlay(
|
||||
screen: AiSurface.Screen?,
|
||||
onClose: () -> Unit,
|
||||
onResult: (String) -> Unit,
|
||||
/** 等待模式:用户点了回传按钮之后自动把界面收掉(这是"用户答完了"的信号) */
|
||||
autoCloseOnResult: Boolean = false,
|
||||
) {
|
||||
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||
val shown = screen ?: last
|
||||
|
||||
// WebView 实例 + "能不能回退"。
|
||||
// ★ 拿到了 WebView 才能调 goBack();canGoBack 要轮询(WebView 没有变更回调)。
|
||||
var web by remember { mutableStateOf<WebView?>(null) }
|
||||
var canGoBack by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(web, screen) {
|
||||
while (web != null && screen != null) {
|
||||
canGoBack = web?.canGoBack() == true
|
||||
kotlinx.coroutines.delay(400)
|
||||
}
|
||||
canGoBack = false
|
||||
}
|
||||
|
||||
// 系统返回键:能回退就先回退(用户点进去了一页,返回键该带他回来),
|
||||
// 不能回退才关掉整个界面 —— 比直接关掉符合直觉。
|
||||
BackHandler(enabled = screen != null) {
|
||||
if (web?.canGoBack() == true) web?.goBack() else onClose()
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = screen != null,
|
||||
enter = fadeIn(tween(180)) +
|
||||
scaleIn(tween(240, easing = androidx.compose.animation.core.FastOutSlowInEasing), initialScale = 0.86f),
|
||||
exit = fadeOut(tween(150)) + scaleOut(tween(180), targetScale = 0.92f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
shown.title.ifBlank { "AI 界面" },
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// 「返回上一页」只在真能回退时出现 —— 一直显示一个点了没反应的
|
||||
// 箭头比不显示更让人困惑
|
||||
AnimatedVisibility(
|
||||
visible = canGoBack,
|
||||
enter = fadeIn(tween(150)),
|
||||
exit = fadeOut(tween(120)),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { web?.goBack() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
"返回上一页",
|
||||
tint = doubaoText(),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
AiWebView(
|
||||
screen = shown,
|
||||
onResult = { value ->
|
||||
onResult(value)
|
||||
// ★ 等待模式下这一下就是"用户答完了" —— 把界面收掉,
|
||||
// 否则用户看到一个已经用完的界面还开着,会以为还能再点。
|
||||
if (autoCloseOnResult) onClose()
|
||||
},
|
||||
onClose = onClose,
|
||||
onWebView = { web = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 AI 写的 HTML。
|
||||
*
|
||||
* ## JS 开着,但 `@JavascriptInterface` 只在"我们自己那一页"暴露
|
||||
*
|
||||
* 用户要求"支持 js"。开了 JS 之后最大的风险不是 JS 本身,而是
|
||||
* **`addJavascriptInterface` 注入的那个桥**:它对**之后加载的每一个页面**
|
||||
* 都可见。AI 的页面里如果有个链接,用户点进去落到一个外部站点,
|
||||
* 那个站点的 JS 也能调我们的桥 —— 等于把 App 的内部接口交给它。
|
||||
*
|
||||
* 所以这里**按 origin 收口**:
|
||||
*
|
||||
* · 初始文档用 `loadDataWithBaseURL(null, …)` 加载 —— 它的 document origin
|
||||
* 是**不透明(opaque)**的,WebView 会把它当作"没有来源"
|
||||
* · 导航到任何 **http/https** 之前,先把桥撤掉(`removeJavascriptInterface`)
|
||||
* · 外部页面在 WebView 里正常打开(用户要的"点进去"就是它),
|
||||
* 但它没有桥;而且 `onPageStarted` 里会再兜一次
|
||||
*
|
||||
* ## 依然保持关闭的那些
|
||||
*
|
||||
* · `allowFileAccess` / `allowContentAccess` —— 不让页面读本地文件
|
||||
* · `setAllowFileAccessFromFileURLs` / `setAllowUniversalAccessFromFileURLs`
|
||||
* · `mixedContentMode = NEVER` —— 不让 https 页面加载 http 资源
|
||||
*
|
||||
* ## 可点按钮的两条路都留着
|
||||
*
|
||||
* 1. `<button data-doubao-result="值">` —— App 侧字符串替换成
|
||||
* `doubao://pick?...`,由 `shouldOverrideUrlLoading` 拦。
|
||||
* **不依赖 JS**,所以页面即使 JS 出错也能用
|
||||
* 2. `Doubao.pick("值")` / `Doubao.close()` —— 给会写 JS 的模型用
|
||||
* (图表上点一个点回传、定时刷新之类)
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
private fun AiWebView(
|
||||
screen: AiSurface.Screen,
|
||||
onResult: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onWebView: (WebView) -> Unit = {},
|
||||
) {
|
||||
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||
// 记一下"桥还在不在",避免同一页里反复 remove/add
|
||||
val host = remember(screen.id) { AiWebHost() }
|
||||
host.onResult = onResult
|
||||
host.onClose = onClose
|
||||
|
||||
DisposableEffect(screen.id) {
|
||||
onDispose { host.detach() }
|
||||
}
|
||||
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
isVerticalScrollBarEnabled = true
|
||||
|
||||
/**
|
||||
* ★★ 桥的挂/摘时机 —— 这里改了两版才对,把结论记下来。
|
||||
*
|
||||
* **第一版**(错的):`loadDataWithBaseURL` 之前就 add,导航到
|
||||
* http(s) 时 remove。问题:外部页面在 `onPageStarted` 摘桥**之前**
|
||||
* 有个"已经开始加载、桥还在"的窗口期。
|
||||
*
|
||||
* **第二版**(也是错的):只在 `onPageFinished` 里判 url 是不是
|
||||
* `about:blank` 才 add。实测页面报
|
||||
* `Uncaught ReferenceError: Doubao is not defined`
|
||||
* —— `onPageFinished` 的**回调时机比页面内联 <script> 执行还晚**,
|
||||
* 脚本跑的时候桥还没挂上。
|
||||
*
|
||||
* **第三版**(现在这个):初始 load **之前就挂**(保证脚本能用到),
|
||||
* 然后靠 [AiWebHost.payloadLoaded] 这个标志挡住窗口期 ——
|
||||
* loadUrl 到别的地址时,`payloadLoaded` 已经是 true,
|
||||
* 所以立刻摘桥,外部页面**从头到尾**都碰不到它。
|
||||
*/
|
||||
addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
// 开始加载"非初始页"了 —— 说明初始页已经加载过(标志为 true),
|
||||
// 而这次是一个**导航**:立刻摘桥。
|
||||
//
|
||||
// ★ 纯锚点跳转(#xxx)不算导航,不能摘 —— 否则页面内
|
||||
// "跳到某一段"之后 JS 就废了。
|
||||
val anchorOnly = url != null && url.startsWith("about:blank#")
|
||||
if (host.payloadLoaded && !anchorOnly) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
if (!host.payloadLoaded) {
|
||||
// 初始那页加载完成。**马上补挂一次** —— 实测
|
||||
// loadDataWithBaseURL 的页面在脚本执行时桥可能还没生效,
|
||||
// 补挂之后重新 load 才稳。
|
||||
host.payloadLoaded = true
|
||||
view?.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS, null)
|
||||
return
|
||||
}
|
||||
// 之后每次加载完都探一次:**页面里有我们的标记**才重挂桥。
|
||||
//
|
||||
// ★ 为什么用"页面里有没有标记变量"而不是看 url:
|
||||
// 实测从外部页返回(goBack)时,onPageFinished 收到的 url
|
||||
// 并不是 `about:blank`,用 url 判会漏 —— 表现是
|
||||
// "点进去再返回,页面上的 JS 按钮全失灵"。
|
||||
// 标记变量是**页面自己的属性**,页面被换掉它就没了,
|
||||
// 比 url 可靠。
|
||||
//
|
||||
// ★ 如果标记在**但桥不在**,说明这一页是我们的,
|
||||
// 而桥在上一次导航时被摘了 → 重挂。
|
||||
// 如果标记在**桥也在**,什么都不用做。
|
||||
view?.evaluateJavascript(AiWebHost.PROBE_JS) { result ->
|
||||
// ★ evaluateJavascript 的回调参数是**字符串**,
|
||||
// 而且返回值经 JSON 编码("1" 带着引号)。
|
||||
// 我第一版按 Boolean 处理,条件永远不成立。
|
||||
val ok = (result ?: "").trim('"', ' ')
|
||||
if (ok == "1" && !host.bridgeAttached) {
|
||||
view.addJavascriptInterface(host, AiWebHost.NAME)
|
||||
host.bridgeAttached = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
): Boolean {
|
||||
val u = url ?: return false
|
||||
|
||||
// ① 我们自己约定的回传协议
|
||||
if (u.startsWith("doubao://pick")) {
|
||||
val v = Uri.decode(Uri.parse(u).getQueryParameter("value") ?: "")
|
||||
if (v.isNotEmpty()) onResult(v)
|
||||
return true
|
||||
}
|
||||
if (u.startsWith("doubao://close")) {
|
||||
onClose()
|
||||
return true
|
||||
}
|
||||
|
||||
// ② http(s):**在 WebView 里打开**(用户要的"点进去")。
|
||||
// 桥会在 onPageStarted 里被摘掉(那时 payloadLoaded 已 true),
|
||||
// 所以外部站点碰不到 App。
|
||||
if (u.startsWith("http://") || u.startsWith("https://")) {
|
||||
view?.removeJavascriptInterface(AiWebHost.NAME)
|
||||
host.bridgeAttached = false
|
||||
return false
|
||||
}
|
||||
|
||||
// ③ 页内锚点(#xxx)交给 WebView 自己处理
|
||||
if (u.startsWith("#")) return false
|
||||
|
||||
// ④ 别的协议(tel: / mailto: / intent: …)交给系统
|
||||
return try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(u))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
true
|
||||
} catch (_: Throwable) {
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||
onWebView(this)
|
||||
}
|
||||
},
|
||||
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 给 AI 页面用的 JS 桥。
|
||||
*
|
||||
* 暴露两个方法(页面上写 `Doubao.pick("值")` / `Doubao.close()`):
|
||||
*
|
||||
* · `pick(value)` —— 回传一个值,和点 `data-doubao-result` 按钮等价。
|
||||
* 适合"图表上点一个点"、"定时刷新后回传结果"这类需要脚本的场景。
|
||||
* · `close()` —— 关掉这个界面。
|
||||
*
|
||||
* ★ 方法名和 [NAME] 都刻意短且通用,因为模型要在 HTML 里手写它们;
|
||||
* 但**只暴露这两个** —— 桥能调到的越少,万一被滥用时的损失越小。
|
||||
*
|
||||
* ★ 注意:这个对象**只挂在初始那一页**上(见 [AiWebView] 的注释)。
|
||||
* 导航到外部站点时会被 `removeJavascriptInterface` 摘掉。
|
||||
*/
|
||||
class AiWebHost {
|
||||
@Volatile
|
||||
var onResult: ((String) -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onClose: (() -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 初始那一页(AI 写的那份 HTML)加载完成了没有。
|
||||
*
|
||||
* 用来区分"初始加载"和"用户点链接导航" —— 两者都会走 `onPageStarted`,
|
||||
* 但只有后者该摘桥。见 [AiWebView] 里那段注释。
|
||||
*/
|
||||
@Volatile
|
||||
var payloadLoaded: Boolean = false
|
||||
|
||||
/** 桥现在挂着没有。重挂前要先看它,不然会重复 add。 */
|
||||
@Volatile
|
||||
var bridgeAttached: Boolean = false
|
||||
|
||||
@JavascriptInterface
|
||||
fun pick(value: String?) {
|
||||
val v = (value ?: "").trim()
|
||||
if (v.isEmpty()) return
|
||||
onResult?.invoke(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* `pick` 的别名 —— **这是"AI 自己能写进网页里的接口"**。
|
||||
*
|
||||
* AI 在它生成的 HTML 里写:
|
||||
* ```html
|
||||
* <button onclick="Doubao.sendToAi('用户选了方案 B')">方案 B</button>
|
||||
* ```
|
||||
* 那个值就会经安卓桥 POST 到内核排队,**下一轮对话时作为上下文交给模型**。
|
||||
* 也就是模型真的能知道用户在它自己写的界面上选了什么。
|
||||
*
|
||||
* ★ 两个名字都留着(`pick` / `sendToAi`):模型有时写这个有时写那个,
|
||||
* 收两个比让它猜、猜错了整段交互失效要省事得多。
|
||||
*/
|
||||
@JavascriptInterface
|
||||
fun sendToAi(value: String?) = pick(value)
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
|
||||
/** 页面销毁时断开引用,别把 Compose 的东西一直攥着 */
|
||||
fun detach() {
|
||||
onResult = null
|
||||
onClose = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "Doubao"
|
||||
|
||||
/**
|
||||
* 往页面里写一个标记并回读 —— 用来判断"当前这一页是不是我们自己注入的"。
|
||||
*
|
||||
* ★ 走 `evaluateJavascript` 而不是看 url:实测从外部页返回时
|
||||
* `onPageFinished` 收到的 url 不是 `about:blank`,用 url 判会漏。
|
||||
* 标记是页面自己的属性,页面被换掉它就没了,可靠得多。
|
||||
*
|
||||
* 返回 "1" 表示是我们的页。
|
||||
*/
|
||||
const val PROBE_JS =
|
||||
"(function(){try{" +
|
||||
"if(!window.__doubaoAiPage){window.__doubaoAiPage=1;}" +
|
||||
"return '1';" +
|
||||
"}catch(e){return '0';}})()"
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 `data-doubao-result="x"` 变成可点的链接,再套一层骨架 */
|
||||
private fun buildAiHtml(screen: AiSurface.Screen): String {
|
||||
val body = if (screen.fullHtml) screen.html else wrapSkeleton(screen.html)
|
||||
return rewriteResultLinks(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `<button data-doubao-result="值">文字</button>` 重写成
|
||||
* `<a class="db-btn" href="doubao://pick?value=值">文字</a>`。
|
||||
*
|
||||
* ★ 用正则做单遍替换,**不引 HTML 解析器** —— 这点转换不值得多一个依赖,
|
||||
* 而且 AI 的输出是受控的(我们自己提示词里教的写法)。
|
||||
* `button` 和 `a` 两种都收,模型有时会写成链接。
|
||||
*/
|
||||
private fun rewriteResultLinks(html: String): String {
|
||||
val pattern = Regex(
|
||||
"""<(button|a)\b([^>]*?)data-doubao-result\s*=\s*["']([^"']*)["']([^>]*?)>(.*?)</\1>""",
|
||||
setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),
|
||||
)
|
||||
return pattern.replace(html) { m ->
|
||||
val value = android.net.Uri.encode(m.groupValues[3])
|
||||
val inner = m.groupValues[5]
|
||||
"""<a class="db-btn" href="doubao://pick?value=$value">$inner</a>"""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给"片段式" HTML 套一层骨架。
|
||||
*
|
||||
* 为什么要套:模型每次都要重复写 `<meta viewport>`、暗色主题背景、字体、
|
||||
* 边距 —— 既啰嗦又容易和 App 的主题打架。套一层之后它只管写内容。
|
||||
*/
|
||||
private fun wrapSkeleton(fragment: String): String = """
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 16px 16px 40px;
|
||||
background: #121317; color: #e8eaed;
|
||||
font: 15px/1.7 -apple-system, "PingFang SC", "Noto Sans CJK SC", sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
h1 { font-size: 21px; margin: 4px 0 12px; }
|
||||
h2 { font-size: 18px; margin: 20px 0 8px; }
|
||||
h3 { font-size: 16px; margin: 16px 0 6px; }
|
||||
p { margin: 8px 0; }
|
||||
a { color: #7cb0ff; }
|
||||
code, pre {
|
||||
background: #1d1f25; border-radius: 8px;
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px;
|
||||
}
|
||||
code { padding: 2px 5px; }
|
||||
pre { padding: 12px; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||
th, td { border: 1px solid #2c2f36; padding: 8px 10px; text-align: left; }
|
||||
th { background: #1b1d22; font-weight: 600; }
|
||||
blockquote {
|
||||
margin: 12px 0; padding: 8px 14px;
|
||||
border-left: 3px solid #3d4450; color: #b9bdc4;
|
||||
}
|
||||
img, svg, canvas { max-width: 100%; height: auto; }
|
||||
hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; }
|
||||
|
||||
/* ★★ 按钮 —— 这里刻意做得**非常显眼**。
|
||||
*
|
||||
* 起因:用户连着两次反馈"哪有按键,网页里的按键也点不了"、"没有一个按键能用"。
|
||||
* 实测下来**功能是好的**(点了值确实回到模型手里),问题出在**视觉**:
|
||||
*
|
||||
* · `data-doubao-result` 的按钮会被 App 改写成 `<a class="db-btn">`,
|
||||
* 拿到亮蓝整行的样式 → 看得出来能点
|
||||
* · 而 `onclick="Doubao.sendToAi(...)"` 的按钮**保持原样**,
|
||||
* 落进下面那条"普通按钮"规则 → 小灰块,在深色主题里跟正文几乎一样
|
||||
*
|
||||
* 同一屏里一半亮蓝一半灰暗,用户当然会以为"只有蓝的能点"甚至"都不能点"。
|
||||
*
|
||||
* 所以现在**所有 button / .db-btn 一律是同样显眼的实心蓝**,
|
||||
* 普通按钮那条规则删掉了。`!important` 是为了压掉模型内联的
|
||||
* `style="background:..."`(模型很爱写这个,一写就把我们的样式盖掉)。 */
|
||||
.db-btn, button, [data-doubao-result], [role=button] {
|
||||
display: block !important;
|
||||
width: 100% !important;
|
||||
margin: 10px 0 !important;
|
||||
padding: 15px 18px !important;
|
||||
background: #2b7bff !important;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none !important;
|
||||
text-align: center !important;
|
||||
border: 0 !important;
|
||||
border-radius: 12px !important;
|
||||
font-size: 16px !important;
|
||||
font-weight: 500 !important;
|
||||
line-height: 1.4 !important;
|
||||
cursor: pointer !important;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
.db-btn:active, button:active, [data-doubao-result]:active, [role=button]:active {
|
||||
background: #1e63d6 !important;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
/* 次要按钮(模型想要不那么抢眼的):加个 class 就能变灰 */
|
||||
.db-plain, button.db-plain {
|
||||
background: #262a31 !important;
|
||||
color: #e8eaed !important;
|
||||
border: 1px solid #3d4450 !important;
|
||||
}
|
||||
/* 两个按钮并排时用这个包一层 */
|
||||
.db-row { display: flex; gap: 10px; }
|
||||
.db-row > * { flex: 1; }
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、AI 的选择弹窗(ask_user) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiDialogOverlay(dialog: AiSurface.Dialog?, onAnswer: (List<String>, Boolean) -> Unit) {
|
||||
var last by remember { mutableStateOf<AiSurface.Dialog?>(null) }
|
||||
LaunchedEffect(dialog) { if (dialog != null) last = dialog }
|
||||
val shown = dialog ?: last
|
||||
|
||||
// 多选时先把已勾的攒起来,点「确定」才回传
|
||||
val picked = remember(dialog?.id) { mutableStateListOf<String>() }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
enter = fadeIn(tween(180)),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color(0xB3000000))
|
||||
.clickable(enabled = shown?.allowCancel == true) { onAnswer(emptyList(), true) },
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
enter = slideInVertically(tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) { it / 3 } +
|
||||
fadeIn(tween(200)) + scaleIn(tween(280), initialScale = 0.94f),
|
||||
exit = slideOutVertically(tween(200)) { it / 4 } + fadeOut(tween(150)) +
|
||||
scaleOut(tween(200), targetScale = 0.96f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 24.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(20.dp),
|
||||
) {
|
||||
Text("AI 想问你", fontSize = 12.sp, color = doubaoTextDim())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
shown.question,
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
lineHeight = 24.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("可多选", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
// 选项多时中间区域自己滚,按钮不跟着滚出去
|
||||
Column(
|
||||
Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
shown.options.forEach { opt ->
|
||||
val on = opt.value in picked
|
||||
OptionRow(
|
||||
label = opt.label,
|
||||
description = opt.description,
|
||||
selected = on,
|
||||
multiple = shown.multiple,
|
||||
onClick = {
|
||||
if (shown.multiple) {
|
||||
if (on) picked.remove(opt.value) else picked.add(opt.value)
|
||||
} else {
|
||||
onAnswer(listOf(opt.value), false)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (shown.allowCancel) {
|
||||
OutlinedButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
}
|
||||
Button(
|
||||
onClick = { onAnswer(picked.toList(), false) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("确定") }
|
||||
}
|
||||
} else if (shown.allowCancel) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
TextButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) { Text("取消") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OptionRow(
|
||||
label: String,
|
||||
description: String,
|
||||
selected: Boolean,
|
||||
multiple: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
// 选中时轻微放大 —— 比单纯变色更能让人感到"点到了"
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (selected) 1.02f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "optScale",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (selected) doubaoAccentSoft() else doubaoSurfaceAlt())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 15.sp,
|
||||
color = if (selected) doubaoAccent() else doubaoText(),
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
if (description.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(description, fontSize = 12.sp, color = doubaoTextDim(), lineHeight = 17.sp)
|
||||
}
|
||||
}
|
||||
if (multiple && selected) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("✓", fontSize = 16.sp, color = doubaoAccent())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、对话被 AI 结束 —— 屏幕中间的横幅 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* ★ 用户明确要求的样子:**屏幕中间一个横幅,写着 AI 关闭的原因**。
|
||||
*
|
||||
* 几个细节:
|
||||
* · **停在屏幕正中间**(不是顶部也不是底部)—— 这是"这次对话到此为止"
|
||||
* 这种终局状态,摆在视线中心最合适
|
||||
* · **不自动消失**。它不是提示条,是状态;消失了用户就不知道
|
||||
* 为什么发不出消息了
|
||||
* · 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
* · 只显示在与它相关的那次对话里(调用方按 conversationId 判断)
|
||||
*/
|
||||
@Composable
|
||||
fun EndedBanner(reason: String, onNewConversation: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
AnimatedVisibility(
|
||||
visible = true,
|
||||
enter = slideInVertically(
|
||||
tween(420, easing = androidx.compose.animation.core.FastOutSlowInEasing),
|
||||
) { it } + fadeIn(tween(280)) + scaleIn(tween(420), initialScale = 0.9f),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 28.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 20.dp, vertical = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.PowerSettingsNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("这次对话已结束", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
reason.ifBlank { "AI 结束了这次对话" },
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Button(
|
||||
onClick = onNewConversation,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = doubaoAccent()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("开始新对话", color = Color.White) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 -> "自动"
|
||||
}
|
||||