Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dd66541446 | |||
| 3a0869eab8 | |||
| 849e2e5beb | |||
| aa5b0226f9 | |||
| 155f95c982 | |||
| 7ccdc4516a | |||
| 8acfc0ed0d | |||
| 693e75dad2 | |||
| 91675f21fb | |||
| 91a4ba2ab4 | |||
| 5a65320a5d | |||
| 946bf8bc55 | |||
| 050a3b2385 | |||
| ab8296901d | |||
| c09df1d0a2 | |||
| 31c62fafc2 | |||
| 7498810c70 |
103
.gitignore
vendored
103
.gitignore
vendored
@@ -1,89 +1,22 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 依赖(几百 MB,clone 后 `npm run install:all` 自己装)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
node_modules/
|
||||
.npm-cache/
|
||||
desktop/node_modules/
|
||||
desktop/dist-staging/
|
||||
# 仓库根现在只放说明和两个目录;工程在 豆鲍/(它有自己的 .gitignore)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 构建产物
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
dist-android/
|
||||
dist-win/
|
||||
app/dist/
|
||||
web/dist/
|
||||
android/app/build/
|
||||
android/build/
|
||||
android/.gradle/
|
||||
android/local.properties
|
||||
build/
|
||||
.gradle/
|
||||
*.tsbuildinfo
|
||||
*.apk
|
||||
*.aab
|
||||
*.exe
|
||||
*_boot.zip
|
||||
# 编辑器工作区:放导出的包、手改的 JSON、批量脚本 —— 都是本地活儿,不进版本库。
|
||||
# ★ README.md 不忽略(那是这个文件夹的说明,要提交)。
|
||||
豆鲍编辑器/*.json
|
||||
豆鲍编辑器/*.zip
|
||||
豆鲍编辑器/*.db
|
||||
豆鲍编辑器/*.sqlite
|
||||
豆鲍编辑器/备份/
|
||||
豆鲍编辑器/tmp/
|
||||
|
||||
# 打包中间产物(electron 二进制与暂存目录都很大)
|
||||
android/app/src/main/assets/main.lynx.bundle
|
||||
.rasterize-*
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 密钥 / 个人配置 —— 这些**绝不能**提交
|
||||
#
|
||||
# settings.json 里有 apiKey 字段(现在是占位值,但随时可能填真 Key);
|
||||
# mcp.servers.json 里有本机绝对路径。
|
||||
# 示例文件(*.example.*)是给别人做模板用的,要提交。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
server/.env
|
||||
server/.env.*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.local
|
||||
server/config/settings.json
|
||||
tools/mcp.servers.json
|
||||
app/config/settings.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 运行时数据
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
server/data/
|
||||
data/
|
||||
phone-verify-result.json
|
||||
*.log
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Termux 的两个 bootstrap(各 28 MB,共 56 MB)
|
||||
#
|
||||
# 这两个 .so 是**手动**从 Termux 的 APK 里取出来放进 jniLibs 的,
|
||||
# 仓库里没有脚本能重新生成(fetch-termux.mjs 只把 APK 下到缓存)。
|
||||
# 56 MB 的二进制不适合跟着代码走,所以单独排除;
|
||||
# 要构建 APK 见 README「4.2 APK 里到底装了什么」。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
android/app/src/main/jniLibs/*/libtermux-bootstrap.so
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Python
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 编辑器 / 系统
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
*.swp
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
# 系统 / 编辑器垃圾
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.log
|
||||
*.tmp
|
||||
__pycache__/
|
||||
|
||||
# 调试时生成的临时探针
|
||||
.tmp/
|
||||
.tmp-*
|
||||
# 本地工作产物:任何以 .tmp 开头的临时目录(探针数据、临时脚本等)+
|
||||
# Windows 文件权限诊断报告
|
||||
.tmp-*/
|
||||
.acl-recovery/
|
||||
|
||||
182
AGENTS.md
182
AGENTS.md
@@ -1,161 +1,51 @@
|
||||
# 项目约定
|
||||
# AGENTS.md(入口)
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
**项目约定在 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)** ——
|
||||
代码托管(两个 remote、推送注意事项)和界面约定(少用弹窗、能开界面就开界面、
|
||||
全屏界面骨架、几个反复踩的坑)都在那份里。
|
||||
|
||||
---
|
||||
请以那份为准,本文只做入口。
|
||||
|
||||
# 代码托管
|
||||
## 这个仓库的目录
|
||||
|
||||
## 两个 remote,同一个仓库
|
||||
```
|
||||
豆鲍/ 完整工程(android / server / web / desktop / scripts / docs …)
|
||||
豆鲍编辑器/ 独立「豆鲍编辑器」:桌面 app + Windows exe + APK,
|
||||
给豆包世界状态等系统写 Python 脚本用(见它的 README)
|
||||
.git/
|
||||
```
|
||||
|
||||
| remote | 地址 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `local` | `http://192.168.100.103:8080/l/doubao-clone.git` | **在家/局域网,优先用这个**(快) |
|
||||
| `origin` | `https://git.xnhw.cc/l/doubao-clone.git` | 不在局域网时 |
|
||||
|
||||
两个地址指向**同一台服务器**(`git.xnhw.cc` 在外网解析到 `64.49.47.22`,
|
||||
局域网里就是 `192.168.100.103:8080`)。推哪个都行,别同时推两遍。
|
||||
|
||||
服务是 **Noir's Git**(Gitea 系)。
|
||||
|
||||
## 推送
|
||||
**所有工程操作都从 `豆鲍/` 里执行**:
|
||||
|
||||
```bash
|
||||
git push local main # 日常
|
||||
git push local --tags # 标签
|
||||
cd 豆鲍
|
||||
python scripts/probe-agent-system.py # 探针
|
||||
node scripts/build-apk.mjs # 构建 APK
|
||||
```
|
||||
|
||||
`local` 的凭据存在 `.git/config` 的 remote URL 里(`.git` 不属于仓库内容,
|
||||
不会被提交)—— 所以不用每次输密码。
|
||||
## 三条最容易忘的
|
||||
|
||||
## 一个坑:push 报 401 时会**假装卡住**
|
||||
1. **改内核必须跑 `py_compile`** —— Gradle 不编译 Python,语法错误要等手机上
|
||||
启动内核才炸,那时整个 App 不可用。
|
||||
2. **改了就要重新构建再验证** —— 这个仓库里"改了没生效"绝大多数是因为
|
||||
改动晚于上一次构建,而不是代码错。
|
||||
3. **探针必须走生产同一条调用路径**(`handle()` / `execute_tool`),
|
||||
不能直接调内部函数 —— 探针能绕过的那一层,就是下次会出问题的那一层。
|
||||
4. **每次功能改动先递增版本号**(两个产品各管各的):
|
||||
- **豆鲍 App**(本仓库主体):`python scripts/bump-version.py`(版本唯一来源
|
||||
`android/app/build.gradle.kts` 的 `versionCode` / `versionName`),再
|
||||
`node scripts/build-apk.mjs`。构建脚本会打印版本,版本没变会提醒你还没 bump。
|
||||
- **豆鲍编辑器**:`python 豆鲍编辑器/scripts/bump_version.py`(版本唯一来源
|
||||
`豆鲍编辑器/VERSION`),再构建;编辑器构建脚本会校验版本一致。
|
||||
|
||||
这个服务器上 `receive-pack`(推送)要认证,而 `upload-pack`(拉取)不用。
|
||||
凭据不对时 git 会**挂在等密码输入上,一行输出都没有** ——
|
||||
看起来像网络卡死,其实是在等 stdin。
|
||||
## 安卓模拟器(要装 App / 截图验证时看这份)
|
||||
|
||||
所以:
|
||||
- 脚本里推之前先设 `GIT_TERMINAL_PROMPT=0`(让它直接失败而不是等)
|
||||
- 或者直接确认 remote URL 里有凭据
|
||||
|
||||
排查顺序:
|
||||
```bash
|
||||
git ls-remote <url> # GET 通不通(不需要认证也能通)
|
||||
curl -i "<url>/info/refs?service=git-receive-pack" # 401 就是认证问题
|
||||
```powershell
|
||||
cd 豆鲍
|
||||
powershell -ExecutionPolicy Bypass -File scripts\emulator-up.ps1 # 拉起 doubao14(emulator-5558)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 界面约定
|
||||
|
||||
适用于本仓库的 Android / Compose 界面。
|
||||
|
||||
## 少用弹窗,能开界面就开界面
|
||||
|
||||
用户明确要求:**尽量减少弹窗那种,能加界面就加界面。**
|
||||
|
||||
理由(也是判断标准):
|
||||
|
||||
- **弹窗装不下东西**。一屏对话框的高度大概只够三四行内容,一旦要放的
|
||||
东西超过这个量(列表、代码框、多组配置),用户就得在弹窗里滚动 ——
|
||||
那还不如直接开一屏。
|
||||
- **弹窗会互相压**。弹窗里再弹一个(比如"变量管理"里点"新建",
|
||||
或者"节点管理"里点"编辑")在手机上是灾难:返回键的行为变得说不清,
|
||||
用户也不知道自己在第几层。
|
||||
- **弹窗盖住上下文**。这个 App 的会议画布本身就是要看着的,
|
||||
一个盖住半屏的对话框让人没法一边看图一边改配置。
|
||||
|
||||
### 该怎么做
|
||||
|
||||
| 内容量 | 用什么 |
|
||||
|---|---|
|
||||
| 一次确认("要删除吗") | `AlertDialog` ✓ 弹窗合适 |
|
||||
| 纯菜单(两三个入口,点完就走) | 底部弹层或 `AlertDialog` ✓ |
|
||||
| 列表 / 多组配置 / 代码 / 任何要滚动的 | **独立全屏界面**,顶栏 `← 返回` + 标题 + 右侧动作 |
|
||||
|
||||
### 全屏界面的骨架
|
||||
|
||||
统一用同一套顶栏,别各写各的(不然返回的位置、标题的大小、
|
||||
右边按钮的样式会到处不一样):
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
```
|
||||
|
||||
参考实现:`NodeBlockEditorScreen`(`NodeBlockEditor.kt`)的顶栏。
|
||||
|
||||
### 返回键
|
||||
|
||||
全屏界面要能被系统返回键关掉(用状态变量控制显示时,
|
||||
记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 ——
|
||||
比弹窗还糟。
|
||||
|
||||
## 全屏化的进度
|
||||
|
||||
**已经改完全屏的**:
|
||||
- ✅ 节点管理 `NodeManagerScreen`
|
||||
- ✅ 节点编辑 `NodeCodeScreen`(代码框占满剩余高度)
|
||||
- ✅ 积木编辑器 `NodeBlockEditorScreen`
|
||||
|
||||
**还欠着的**:
|
||||
- [ ] 变量管理 `VarManagerDialog` → 全屏
|
||||
- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层
|
||||
- [ ] 导入会议 `ImportDialog` → 全屏
|
||||
- [ ] 节点配置 `NodeConfigDialog` → 全屏(字段很多)
|
||||
|
||||
**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。
|
||||
|
||||
### 改全屏时踩的坑:界面的 return 顺序
|
||||
|
||||
全屏界面是用状态变量 + `return@Composable` 实现的,于是**谁在上面谁优先**:
|
||||
|
||||
```kotlin
|
||||
blockEdit?.let { ...; return@MeetingEditorScreen } // 积木编辑器
|
||||
if (showNodeMgr) { ...; return@MeetingEditorScreen } // 节点管理
|
||||
if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
```
|
||||
|
||||
在下面的界面要显示时,**必须先把它上面的那个状态关掉** ——
|
||||
否则上面的先 return,下面的永远轮不到渲染。
|
||||
表现是"点了没反应",其实状态全对了,只是没机会画(这个 bug 真出现过)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `android/nodekit/`**(独立模块)。
|
||||
节点类型、引脚、算子、配色、几何、形状**只有那一份** ——
|
||||
`MeetingsScreen.kt` 里**不要再写 `when (node.type)` 的长表**(默认标题、颜色、
|
||||
引脚、配置面板标题都从库查)。
|
||||
加一种节点看 [docs/节点库.md](docs/节点库.md) 的清单,改完跑
|
||||
`python scripts/verify-nodekit.py`(它会拿库和 Python 引擎逐项对拍)。
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`Ops.ALL` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
只改一半,用户会说"你不会举一反三的吗"。
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」),
|
||||
事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走
|
||||
`applyMeetingEvent`。
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
- **代码框不能软换行**。` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
就是语法。这个 Compose 版本(BOM 2024.09.03)的 `BasicTextField`
|
||||
经典重载选不中,所以用"把输入框塞进足够宽的横向滚动容器"来达到同样效果。
|
||||
- **代码框要有高度上限**。只写 `heightIn(min=...)` 的话,文件一长框就长到
|
||||
屏幕外,把底下的补全条顶出去,用户够不着。
|
||||
- **改了没生效就先怀疑工具**。PowerShell 的 `String.Replace` **匹配失败不报错**;
|
||||
按行号剪贴会算错下标(甚至把整个文件追加一遍);
|
||||
`git checkout -- <文件>` 会还原**这一轮所有未提交的改动**。
|
||||
改完立刻 grep 确认,动手前先断言下标有效。
|
||||
- **莫名其妙的"未解析引用"先数括号**。漏一个 `}` 会让后面所有顶层声明
|
||||
全部报未解析,错误信息看着完全不像是括号问题(报的是 `PrimaryButton`
|
||||
找不到这种)。
|
||||
坑和完整操作(装 APK、截图、点按、抓内核日志、连设备内核 API)都在
|
||||
[`豆鲍/docs/安卓模拟器-操作手册.md`](豆鲍/docs/安卓模拟器-操作手册.md)。
|
||||
|
||||
详细约定见 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)。
|
||||
|
||||
775
README.md
775
README.md
@@ -1,764 +1,25 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆鲍 · 豆包 App 复刻
|
||||
|
||||
[](LICENSE)
|
||||
工程在 **[`豆鲍/`](豆鲍/)**,说明看 **[`豆鲍/README.md`](豆鲍/README.md)**。
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
```
|
||||
豆鲍/ 完整工程(Android 原生 + Python 内核 + Node 服务端 + 网页 + 桌面版)
|
||||
豆鲍编辑器/ 编辑器工作区(放导出的包、手改的 JSON、批量改数据的脚本)
|
||||
```
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||
> 「豆包」是字节跳动的商标。
|
||||
|
||||
| 平台 | 产物 | 界面 | 内核 |
|
||||
|---|---|---|---|
|
||||
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | Lynx(旧版,仍在) | Node(随 Electron 启动) |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | Lynx(旧版,仍在) | Node |
|
||||
|
||||
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||
|
||||
| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
|
||||
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
|
||||
|
||||
---
|
||||
|
||||
## 1. 快速开始
|
||||
|
||||
### 浏览器 / 桌面版
|
||||
## 最快验证它能跑
|
||||
|
||||
```bash
|
||||
npm run install:all # app(Lynx 客户端)+ server(Node 内核)
|
||||
npm run build
|
||||
npm start # 打开 http://127.0.0.1:5199/
|
||||
cd 豆鲍
|
||||
|
||||
# 1) 探针:不需要设备、不需要网络,在电脑上把内核逻辑逐条断言
|
||||
python scripts/probe-agent-system.py
|
||||
python scripts/probe-group-chat.py
|
||||
# … 一共八个,见 README
|
||||
|
||||
# 2) 构建 APK
|
||||
node scripts/build-apk.mjs
|
||||
# → dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**exe 必须放纯英文路径**,见 §7.1)。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
```bash
|
||||
npm run apk # 产出 dist-android/doubao-debug.apk(约 88 MB)
|
||||
adb install -r dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
装完打开 App → 抽屉 →「设置」→ 选提供商、填 API Key → 保存。
|
||||
第一次启动会解压内置 Termux(约 95 MB、3226 个文件),**约 10~30 秒**,界面上有进度。
|
||||
|
||||
---
|
||||
|
||||
## 2. 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Android App(原生 Kotlin + Compose,主力) │
|
||||
│ │
|
||||
│ ui/ ChatScreen Drawer Settings Skills Agents Profile │
|
||||
│ ModelPickerSheet TerminalScreen ← 7 个页面 │
|
||||
│ │ │
|
||||
│ │ KernelClient(OkHttp + 轮询流式) │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ Python 内核(Chaquopy 内嵌 CPython 3.13) │ │
|
||||
│ │ android/kernel/ —— 监听 127.0.0.1:5199 │ │
|
||||
│ │ · providers 10 家兼容厂商 + 思考强度映射 │ │
|
||||
│ │ · agent_loop 多轮工具循环 │ │
|
||||
│ │ · tools import 加载 tools/*.py │ │
|
||||
│ │ · mcp_client 手写 JSON-RPC(http/stdio/inproc)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ 进程内直调(Chaquopy 桥) │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 内置 Termux($PREFIX = /data/user/0/<pkg>/files/usr) │
|
||||
│ │ · bash 5.x / apt / pkg / 388 个命令 │ │
|
||||
│ │ · libtermux.so → forkpty(真 tty) │ │
|
||||
│ │ · TerminalView → ANSI 渲染(Termux 源码 vendored)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 设备能力 NativeBridge:定位 / 陀螺仪 / 加速度计 │ │
|
||||
│ │ 磁性 / 光线 / 气压 / 电量 / 剪贴板 / 选文件 │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
电脑上的 Web/exe 版仍然用 **Node 内核 + Lynx 界面**。两个内核**接口逐字段一致**,
|
||||
所以安卓端把界面换成 Compose 之后,后端一行都不用改。
|
||||
|
||||
怎么做到一致的:`android/kernel/` 是照 `server/src/` 的契约重写的纯标准库实现
|
||||
(`http.server` + `urllib` + 手写 JSON-RPC),不依赖任何第三方包 —— 因为安卓上装不进来。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能
|
||||
|
||||
### 3.1 智能体
|
||||
抽屉 →「智能体」。每个智能体有独立头像(9 种)和系统提示词,聊天时覆盖全局提示词,顶部显示当前智能体。
|
||||
内置 4 个(豆包 / 代码搭子 / 文案师 / 数据分析),可自建。存 `<数据目录>/agents.json`。
|
||||
|
||||
### 3.2 模型、提供商与思考强度(抽屉里的「模型」那一栏)
|
||||
|
||||
**支持 10 家,而且它们全都是同一个协议**(`POST {baseUrl}/chat/completions`),
|
||||
所以内核里只有一份实现,差别只在三件事:地址、模型名、**思考强度用哪个字段传**。
|
||||
|
||||
| key | 提供商 | Base URL | 思考强度怎么传 |
|
||||
|---|---|---|---|
|
||||
| `ark` | 火山方舟(豆包) | `https://ark.cn-beijing.volces.com/api/v3` | 顶层 `thinking: {type}` |
|
||||
| `openai` | OpenAI 官方 | `https://api.openai.com/v1` | `reasoning_effort` |
|
||||
| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | 不发(模型自己决定) |
|
||||
| `kimi` | Kimi(月之暗面) | `https://api.moonshot.cn/v1` | 不发 |
|
||||
| `zhipu` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | 顶层 `thinking: {type}` |
|
||||
| `dashscope` | 通义千问(阿里云) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | 不发 |
|
||||
| `siliconflow` | 硅基流动 | `https://api.siliconflow.cn/v1` | 不发 |
|
||||
| `openrouter` | OpenRouter(聚合) | `https://openrouter.ai/api/v1` | `reasoning_effort` |
|
||||
| `ollama` | 本地 Ollama | `http://127.0.0.1:11434/v1` | 不发 |
|
||||
| `custom` | 自定义兼容网关 | 自己填 | 不发 |
|
||||
|
||||
**为什么不是"非 ark 即 openai"**:这个判断以前写死成两家名字。
|
||||
现在厂商多了,各自认的字段不一样,而**给不认 `reasoning_effort` 的服务发这个字段,有些会直接 400**。
|
||||
所以改成每个预设自己声明 `thinkingMode`(`ark` / `effort` / `none`),**认不出来的一律 `none`**(什么都不发,最安全)。
|
||||
|
||||
| 强度 | `thinkingMode: ark` | `thinkingMode: effort` | `thinkingMode: none` |
|
||||
|---|---|---|---|
|
||||
| 快速 | `thinking={type:"disabled"}` | 推理模型 `reasoning_effort=minimal` | 不发 |
|
||||
| 自动 | 不传,交给模型 | 不传 | 不传 |
|
||||
| 低 / 中 / 高 | `thinking={type:"enabled"}` | `reasoning_effort=low/medium/high` | 不传 |
|
||||
|
||||
另外:`thinkingMode: effort` 且模型名匹配 `o1|o3|o4|gpt-5|gpt-6` 时,
|
||||
会自动剥掉 `temperature`/`top_p` 等采样参数,并把 `max_tokens` 换成 `max_completion_tokens`
|
||||
(这些模型"传默认值"也算传,会 400)。
|
||||
|
||||
两份内核(Node / Python)在这件事上**逐字段对拍 50/50 一致**(10 家 × 5 档),
|
||||
脚本:`node scripts/parity-thinking.mjs`。
|
||||
|
||||
### 3.3 思考过程怎么显示
|
||||
1. **正文里**:回答上方一个 `✨ 深度思考 ›` 入口,思考中显示跳动小点
|
||||
(这里不再拼思考强度 —— 强度本身就叫"深度思考",拼出来会变成"深度思考 · 深度思考")
|
||||
2. **点开**:底部升起「**思考过程**」弹层(左上角 X),先列这轮调了哪些工具,再是完整思维链
|
||||
3. 思维链**已落库**,刷新/切会话都不丢
|
||||
|
||||
### 3.4 界面:照着豆包抠的,带完整动效
|
||||
|
||||
安卓端是原生 Compose 重写的,视觉对着豆包真机截图一项项抠:
|
||||
|
||||
- **纯白底**(不是浅灰)——豆包的层级靠"白底 + 浅灰卡片"表达,用灰底会一股系统设置味
|
||||
- 顶部三段式:左边 ☰ / ✎,中间「头像 + 智能体名 + ›」(点开就是模型面板),右边 📞 / 🔊
|
||||
- 空会话时:168dp 蓝色圆环大头像 + 灰色问候气泡 + 白底描边快捷胶囊(对话 / AI创作 / 出行用豆包 / 豆包)
|
||||
- 用户气泡:`#2B7BFF` 蓝底、右下角收窄成 4dp(气泡"尾巴")
|
||||
- 助手气泡:`#F2F3F5` 灰底、左下角收窄;下面一排 5 个圆形小按钮(复制/朗读/赞/踩/分享)+ 右侧重新生成
|
||||
- 输入框:52dp 高的大圆角描边胶囊,左边相机、右边麦克风;**有内容时右侧才变成蓝色圆形发送键**
|
||||
- 出错的回复是浅红底 + 红字,不是普通气泡
|
||||
- 设置 / 我的 / 技能 / 智能体各页共用同一套小部件(`ScreenHeader` / `SettingsCard` / `FormField` …),
|
||||
所以在主题层改一次颜色,7 个页面一起变
|
||||
|
||||
动效(都是 Compose 原生动画,没引第三方库):
|
||||
|
||||
| 位置 | 动效 |
|
||||
|---|---|
|
||||
| 抽屉 | 从左滑入 + 遮罩淡入,关闭反向 |
|
||||
| 页面切换 | 淡入 + 轻微横向位移(`AnimatedContent`) |
|
||||
| 消息气泡 | 出现时淡入 + 上移 10dp(`AppearOnce`) |
|
||||
| 思考 / 模型面板 | 从底部升起,收起时降下去 |
|
||||
| "正在输入" | 三个小点依次跳动(`TypingDots`,错开 130ms) |
|
||||
| 按钮 | 按下缩到 0.86~0.94 回弹(`collectIsPressedAsState` + spring) |
|
||||
| 抽屉列表项 | 按下时背景色渐变 |
|
||||
|
||||
> 顺带一个坑:底部面板的**滚动区会吃掉点击**。如果面板顶到状态栏,
|
||||
> "点遮罩关闭"就只剩状态栏那条能点,等于失效。所以面板限高 85%、并且都带明确的 X 按钮。
|
||||
|
||||
### 3.5 设置不会被保存清空(三道防线)
|
||||
|
||||
之前有个真 bug:**一保存设置,整份配置被清空**。根因是首屏 `state` 还在路上时,
|
||||
设置页草稿还是"全空"的,而保存按钮把草稿**全量**下发;`/api/settings` 是浅合并,
|
||||
空字符串就等于把它清掉。现在三道防线:
|
||||
|
||||
1. **界面只发改动过的字段**(`SettingsDraft.changesAgainst`)——没动过的键根本不出现
|
||||
2. **草稿只在服务端设置真的变了时重建**(存一份 `snapshot` 对比),
|
||||
不会再被无关的 state 刷新冲掉正在输入的内容
|
||||
3. **内核拒收空的关键字段**(`provider` / `baseUrl` / `model` / `apiKey` / `nickname` / `thinkingLevel`)——
|
||||
前端再出 bug 也清不掉配置。`systemPrompt` / `toolsDir` 故意不在此列:它们"留空"是合理需求
|
||||
|
||||
验证脚本(都会先正常保存一次验证不掉字段,再按"旧版 bug 的形状"下发一堆空值验证被忽略):
|
||||
|
||||
- `node scripts/probe-settings-wipe.mjs http://127.0.0.1:5199`(电脑 / Node 内核)
|
||||
- `node scripts/device-settings-attack.mjs emulator-5556 5199`(设备 / Python 内核)
|
||||
|
||||
### 3.6 工具
|
||||
|
||||
| 工具 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `shell` | 终端执行命令,带超时与黑名单 | ✅ 优先走内置 Termux |
|
||||
| `python_run` | 执行 Python 代码 / .py 文件,`action=libs` 列可用库 | ✅ 进程内 exec(CPython 3.13.9) |
|
||||
| `device` | **手机能力**:设备信息、定位、传感器、剪贴板 | ✅ 安卓专属 |
|
||||
| `calc` `now` `get_weather` `notes` `web_fetch` | `tools/*.py`,自己写的 | ✅ 同一份代码 |
|
||||
| `mcp__*` | MCP 服务暴露的工具 | ✅ 见 3.8 |
|
||||
|
||||
**`device` 工具**(安卓)实测能力:
|
||||
- `info`:型号/厂商/系统/SDK/ABI/存储/屏幕/电量
|
||||
- `location`:GPS 经纬度(真机实测 `纬度, 经度 ±35m`)
|
||||
- `sensors` / `sensor`:列出并采样(真机 46 个传感器,加速度计 z≈9.7 m/s² 就是重力)
|
||||
- `clipboard_get` / `clipboard_set`
|
||||
- `termux_available` / `termux_run`:走内置 Termux
|
||||
|
||||
### 3.7 自己写工具
|
||||
往工具目录丢一个 `.py`(`_` 开头跳过):
|
||||
|
||||
```python
|
||||
TOOL = {
|
||||
"name": "word_count",
|
||||
"description": "统计一段文字的字数",
|
||||
"parameters": {"type": "object", "properties": {"text": {"type": "string"}},
|
||||
"required": ["text"]},
|
||||
}
|
||||
def run(args): # 同步或 async 都行
|
||||
return {"count": len(args["text"])}
|
||||
```
|
||||
|
||||
工具目录:安卓在 `files/tools/`(可通过设置里的 `toolsDir` 改),电脑在 `tools/`。
|
||||
内置工具在首次启动时会**播种**到可写目录,改坏了删掉重启就恢复。
|
||||
|
||||
> 为什么安卓上要播种、还要把源码 base64 打进 APK:Chaquopy 打的是 `.pyc`,
|
||||
> 运行时 `loader.get_source()` 拿不到源码,所以构建脚本额外生成了 `bundled_tool_sources.py`。
|
||||
|
||||
### 3.8 MCP:三种传输,安卓也能跑
|
||||
抽屉 →「技能·连接器」→「MCP 服务」,图形化和原始 JSON 两个 Tab,保存时校验并自动重连。
|
||||
|
||||
| 传输 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `http` | 标准 Streamable HTTP / SSE | ✅ |
|
||||
| `stdio` | 起一个子进程用管道通信 | ✅ 用内置 Termux 的 python/node |
|
||||
| `inproc` | 同进程内直接调用(自己写的 Python 服务) | ✅ 安卓推荐,最省事 |
|
||||
|
||||
实测:filesystem 服务 14 个工具、memory 9 个工具、自己写的 Python 服务 3 个工具,全部连接并调用成功。
|
||||
|
||||
> 为什么手写 JSON-RPC 而不用官方 `mcp` SDK:它依赖 pydantic v2,Chaquopy 装不进来。
|
||||
|
||||
### 3.9 文件上传 / 权限模式
|
||||
- **上传**:输入框左侧相机/加号 → 选文件 → 上传到内核 → 挂到输入框 → 随消息发送 → 气泡里显示
|
||||
- **权限模式**:`open` 全放行 / `restricted` 只放 `allow` 白名单。限制模式下未授权工具
|
||||
**列都不列出来**,执行时再拦一道
|
||||
|
||||
### 3.10 语音:朗读 + 语音输入
|
||||
|
||||
**引擎放在内核里,音频采集/播放在端上。** 这么分的好处:API Key 只存一份,
|
||||
浏览器 / 安卓 / exe 三端白捡同一个能力,厂商鉴权差异全在一个文件里。
|
||||
|
||||
| | 引擎 | 说明 |
|
||||
|---|---|---|
|
||||
| **朗读** | `system` | 设备自带 TTS(安卓 `TextToSpeech`)。**不联网、不要 Key**,默认就是它 |
|
||||
| | `volc` | **火山语音合成 —— 豆包同款音色** |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/speech`(`tts-1` + alloy/nova/…) |
|
||||
| **语音输入** | `system` | 设备自带识别(安卓 `SpeechRecognizer`) |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/transcriptions`(`whisper-1` 等) |
|
||||
|
||||
**火山那个接口有两个坑**(对着[官方文档](https://docs.volcengine.com/docs/DoubaoVoice/HTTPone-timecompositenon-streaminginterface-V1notrecommended?lang=zh)
|
||||
和两个第三方实现核对过,并且用 mock 抓了实际发出的请求):
|
||||
|
||||
1. 鉴权头是 `Authorization: Bearer;{token}` —— **分号,不是空格**。写成空格会判鉴权失败。
|
||||
实测抓到的请求:`Authorization="Bearer;tok-abc"`
|
||||
2. 成功判定看 body 里的 `code === 3000`,**HTTP 200 也可能带错误码**;
|
||||
返回的 `data` 是**纯 base64**(不是 data URL),解出来就是音频字节
|
||||
|
||||
接口:
|
||||
|
||||
```
|
||||
POST /api/tts {"text": "..."}
|
||||
→ {"ok":true, "engine":"system"} 用设备自带,界面自己念
|
||||
→ {"ok":true, "engine":"volc", "mime":"audio/mpeg", "audio":"<base64>"}
|
||||
→ {"ok":false, "error":"..."} 失败原因给人话
|
||||
|
||||
POST /api/stt <body 就是音频原始字节,不套 JSON/base64>
|
||||
头: X-Audio-Filename / X-Audio-Type
|
||||
→ {"ok":true, "engine":"openai", "text":"..."}
|
||||
|
||||
GET /api/speech → 当前配置 + 可选音色
|
||||
```
|
||||
|
||||
> 两个接口**失败也返回 HTTP 200 + `ok:false`**:缺 Key、厂商报错都是预期内的失败,
|
||||
> 界面要的是把原因显示出来,而不是让 fetch 抛网络异常(那样错误信息就丢了)。
|
||||
|
||||
安卓端(`speech/AudioIo.kt` + `speech/SpeechController.kt`):
|
||||
|
||||
- **录音**用 `AudioRecord` 直接拿 PCM,套 44 字节 WAV 头(16kHz 单声道 16bit ——
|
||||
Whisper 最常见的输入格式,30 秒才 1 MB)。不用 `MediaRecorder` 是因为它只吐 m4a/aac,还得再解码
|
||||
- **播放**云端音频走 `MediaPlayer`(`setDataSource` 只认路径/FD,所以 base64 落盘成临时文件再播)
|
||||
- **系统 TTS** 会**按句切分**再排队 —— `speak()` 单次上限约 4000 字符,整段塞进去会被截断
|
||||
- 念之前**剥掉 markdown**(`**加粗**`、代码块、链接),否则会念出一堆星号
|
||||
- **云端失败自动退回系统 TTS**:用户点了朗读却一点动静都没有是最差的体验
|
||||
- 录音时**先停朗读**,否则会把自己的声音录进去(自我循环)
|
||||
- 录音权限**第一次点麦克风才申请**,不在启动时要
|
||||
- 录音时输入框整条换成「正在听…」+ 实时音量画的小波形
|
||||
|
||||
验证:`node scripts/verify-speech.mjs py|node` —— **21 项断言,两份内核都跑**
|
||||
(语音在 Node 和 Python 里是分别实现的,只验一份不算数)。
|
||||
mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权头。
|
||||
|
||||
### 3.11 通话模式(设计好了,还没做)
|
||||
|
||||
顶部那个 📞 现在是提示。真要做的话按这个来(**不要一上来就上全双工**):
|
||||
|
||||
| 阶段 | 做法 | 为什么 |
|
||||
|---|---|---|
|
||||
| A(推荐先做) | **半双工**:按一次开始录 → 静音自动断句 → STT → 内核 → TTS 播 → 循环 | 复用现有的 STT/TTS,1 天能出可用版本 |
|
||||
| B | 全双工实时(OpenAI Realtime / 火山实时对话,WebSocket) | 延迟 300ms 级、能自然打断,但强依赖网络,改造量 3~5 天 |
|
||||
|
||||
阶段 A 要处理的四件事(都会真实咬人):
|
||||
|
||||
1. **自我循环**:TTS 在播时开麦会把 AI 自己的声音录进去 → 播之前必须先停麦,
|
||||
或者做回声消除(`AudioSource.VOICE_COMMUNICATION` + AEC)
|
||||
2. **音频焦点**:`TextToSpeech` 和 `AudioRecord` 不能同时持有 → 用 `AudioManager` 协调
|
||||
3. **VAD 断句**:靠静音时长判断"说完了"。阈值调不好要么打断用户、要么一直不响应;
|
||||
建议"连续 800ms 低于阈值算说完",并且**开口就打断 TTS**(barge-in)——这是"像通话"的关键手感
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
### 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)**(需求项 → 文件对照、数据分界、踩过的坑、
|
||||
接口一览),这里只说结论。
|
||||
|
||||

|
||||
|
||||
**选择界面**:左列表 + 右侧四层叠加(背景图 / 主体边框 / 角色图 / 介绍边框),
|
||||
切换按 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` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
|
||||
按仓库约定"引擎改了另一端必须跟上",这是欠账。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 4. 安卓端:内置 Termux 是怎么塞进去的
|
||||
|
||||
### 4.1 一条硬限制决定了整个方案
|
||||
|
||||
**Android 10(API 29)起有 W^X 限制:`targetSdk ≥ 29` 的应用不允许执行自己数据目录里的二进制。**
|
||||
而 Termux 把 bash/python/node 全解压在自己的私有目录再 exec —— 它能这么干,**唯一原因是它 `targetSdk = 28`**
|
||||
(实测核对:`dumpsys package com.termux` → `targetSdk=28`)。
|
||||
|
||||
所以这个 APK 也锁 **`targetSdk = 28`**。代价是上不了应用商店(个人工具无所谓);
|
||||
换来的是完整 Linux 用户态:`bash`、`apt`、`pkg`、以及 `pkg install python nodejs-lts`。
|
||||
|
||||
### 4.2 APK 里到底装了什么
|
||||
|
||||
```
|
||||
APK 88.4 MB
|
||||
├─ lib/arm64-v8a/libtermux-bootstrap.so 28.0 MB ← Termux 根文件系统(其实是 zip)
|
||||
├─ lib/x86_64/libtermux-bootstrap.so 28.1 MB ← 同上,模拟器用
|
||||
├─ lib/<abi>/libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号)
|
||||
├─ lib/<abi>/libpython3.13.so ← Chaquopy 的 CPython
|
||||
├─ assets/chaquopy/** ← 内核 + 9 个 Python 工具
|
||||
└─ java/com/termux/{terminal,view}/** ← Termux 的终端模拟器源码(vendored)
|
||||
```
|
||||
|
||||
Termux 的终端库**没有发布到任何 Maven 仓库**(Maven Central 没有,JitPack 也不通),
|
||||
所以是 vendored 源码 + 改了两处 `import com.termux.view.R` 指向我们自己的 R 类。
|
||||
Apache-2.0 声明见 `android/app/src/main/assets/TERMUX_LICENSE.txt`。
|
||||
|
||||
### 4.3 安装流程(移植自 Termux 的 `TermuxInstaller.java`)
|
||||
|
||||
1. 从 APK 里取出 `libtermux-bootstrap.so`
|
||||
2. **切掉 ELF 头**得到纯 zip(见 4.4 ①)
|
||||
3. 解压到 `files/usr`(3226 个文件),给 `bin/ lib/ libexec/` 下的文件补可执行位
|
||||
4. 读 `SYMLINKS.txt`(1146 行,格式 `目标←链接路径`),**用 `/system/bin/sh` 批量 `ln -sf`**
|
||||
—— Java 的 File API 建不了符号链接
|
||||
5. **改写脚本 shebang**(见 4.4 ④)
|
||||
6. 写一份自己的 `etc/doubao.bashrc`
|
||||
|
||||
进度会写进 `files/termux-install.log`(见 §7.6,为什么不用 Logcat)。
|
||||
|
||||
### 4.4 踩过的四个坑(都和你想象的不一样)
|
||||
|
||||
**① `libtermux-bootstrap.so` 不是纯 zip,是「ELF 头 + zip」**
|
||||
文件前 1328 字节是 ELF 头(Android 要求 `lib/` 下的东西得像 ELF,Termux 就把 zip 接在后面)。
|
||||
- `ZipInputStream` 按本地文件头顺序扫,**实测一个条目都读不出来**;
|
||||
- `ZipFile` 走中央目录,但它**不会**像桌面 JVM 那样自动跳过前缀 ——
|
||||
真机 Android 16 上直接报 `Entry at offset zero has invalid LFH signature 464c457f`
|
||||
(`464c457f` 就是 `\x7FELF` 的小端十六进制)。模拟器上碰巧宽松能过,真机不行。
|
||||
|
||||
所以现在的做法:**自己扫第一个 `PK\x03\x04`、把前缀切掉**,再交给 `ZipFile`。
|
||||
|
||||
**② `bin/su` 写不进去(ENOENT)**
|
||||
父目录存在、权限也对,就是 `open` 失败。安卓对这个文件名有额外限制。
|
||||
处理方式:**单个文件失败就跳过并记日志**,不让一个怪文件毁掉整次安装(其余 3226 个照常)。
|
||||
|
||||
**③ 必须设 `LD_PRELOAD` + `TERMUX__PREFIX`(双下划线)**
|
||||
Termux 的二进制里写死了 `/data/data/com.termux/files/usr`。`libtermux-exec.so` 负责把这些路径
|
||||
重写到真实 prefix,但它认的环境变量是:
|
||||
`TERMUX__PREFIX`(**不是** `TERMUX_PREFIX`)、`TERMUX_APP__DATA_DIR`。
|
||||
少一个,bash 就会去读**别的包**的 `/etc/profile`,报 `Permission denied`。
|
||||
|
||||
**④ 脚本的 shebang 也得改**
|
||||
`bin/getprop`、`bin/pkg` 这些是 shell 脚本,第一行写死 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
内核解析 shebang 时不会经过 termux-exec,照样 EACCES("bad interpreter")。
|
||||
安装时统一把 `bin/ libexec/` 下 79 个脚本的 shebang 前缀改成我们的 prefix 就好了。
|
||||
|
||||
### 4.5 终端界面(真终端 + 控制台退路)
|
||||
|
||||
用 Termux 自己的 `TerminalView` + `libtermux.so` 的 `forkpty` —— 真 pty、真 ANSI,
|
||||
所以 `vim`/`top` 这类全屏程序都能跑。Compose 里用 `AndroidView` 包一层,底下加了手机必备的功能键排:
|
||||
`ESC / TAB / CTRL+C / CTRL+D / ↑↓←→ / HOME / END / | / / / - / ENTER`(没这排连 vim 都退不出来)。
|
||||
|
||||
**但 pty 不是每台机器都给用**。实测 realme(Android 16)上:
|
||||
|
||||
```
|
||||
/dev/pts → Permission denied
|
||||
mount → devpts on /dev/pts type devpts (mode=600,ptmxmode=000)
|
||||
python openpty → OSError: out of pty devices
|
||||
```
|
||||
|
||||
`/dev/pts` 被挂成 `mode=600` 且 `ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||
于是 TerminalSession 一起来就退出(界面上只留一句 `[Process completed]`)。
|
||||
这不是 SELinux 拒绝(logcat 里没有任何 avc),是挂载参数定的,应用侧绕不过去。
|
||||
|
||||
所以做成两条路,**自动切换**:
|
||||
|
||||
| 情况 | 走哪条 |
|
||||
|---|---|
|
||||
| pty 可用(多数设备 / 模拟器) | Termux 的 TerminalView,真终端 |
|
||||
| 会话建起来 2 秒内就退出(判定 pty 不可用) | 自动切「控制台模式」:命令框 + 输出区,跑的是**同一条 Termux bash**,只是没有 tty |
|
||||
|
||||
代价只是没有全屏 TUI 和交互式提示符,跑命令、装包(`pkg install python`)都正常。
|
||||
|
||||
### 4.6 和内核怎么接
|
||||
|
||||
内核里的 `shell` 工具优先走内置 Termux(返回里带 `via: "termux"`),
|
||||
`device` 工具的 `termux_run` / `termux_available` 也走同一条路。
|
||||
因为 Termux 现在就在本进程里,不需要跨进程 intent、也不需要用户去开 `allow-external-apps`。
|
||||
|
||||
### 4.7 安卓端其余细节(Chaquopy / 界面)
|
||||
|
||||
- **Chaquopy 17.0.0** 内嵌 CPython 3.13.9:没有 `python` 可执行文件(所以 `python_run` 是**进程内 exec**,
|
||||
不能起子进程);运行时 pip 只能装纯 Python 轮子;`mcp` 官方 SDK 用不了(要 pydantic v2)
|
||||
- **刻意不装任何第三方包**:Chaquopy 每次构建都要连云 pip,网络一抖整个 APK 就构建不出来
|
||||
(实测 `Could not find a version that satisfies the requirement requests`)。
|
||||
内核只用标准库(`urllib`/`http.server`/`json`),所以留零依赖换来"离线也能构建"。
|
||||
要 requests/numpy 就走内置 Termux:`pkg install python && pip install requests`
|
||||
- **界面**:状态栏不遮挡顶栏(`windowInsetsPadding(WindowInsets.safeDrawing)`)、
|
||||
输入框跟随输入法(`imePadding`)、深色模式自动适配
|
||||
- **流式**:Lynx 那边用 SSE;安卓原生 Compose 走的是**轮询通道**
|
||||
(`transport: "poll"` + `GET /api/chat/poll?runId=&cursor=`),
|
||||
两条件事件类型完全一致,客户端 200ms 取一次增量
|
||||
|
||||
---
|
||||
|
||||
## 5. 我实际验证了什么
|
||||
|
||||
### 5.1 安卓端(原生 Compose + 内置 Termux)
|
||||
|
||||
真机(RMX5090 / Android 16 / arm64-v8a):`node scripts/verify-phone.mjs <serial>` → **17/18**。
|
||||
模拟器(Android 14 / x86_64):17/18(唯一失败的是"定位",模拟器没有 GPS)。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 构建 | ✅ `assembleDebug` 成功,APK 88.4 MB |
|
||||
| 内核启动 | ✅ `GET /api/health` → `{"ok":true,…}` |
|
||||
| 智能体 / 工具 | ✅ 4 个智能体;8 个内置工具 + MCP 工具 |
|
||||
| 内置 Termux | ✅ 首次解压 3226 个文件 / 388 个命令 / 1146 个符号链接 |
|
||||
| shell | ✅ 真机 `Linux localhost 6.6.118-android15 … aarch64 Android`,`via: termux`,stderr 干净 |
|
||||
| pkg / apt | ✅ 可执行(79 个脚本的 shebang 已修正) |
|
||||
| python_run | ✅ CPython 3.13.9 aarch64(进程内) |
|
||||
| 联网 | ✅ urllib 与 requests 都 200 |
|
||||
| device 信息 | ✅ 型号 / 厂商 / 系统 / SDK / 存储 / 电量 |
|
||||
| 传感器 | ✅ 真机 46 个;加速度计 z≈9.7 m/s²、陀螺仪有数据 |
|
||||
| 定位 | ✅ 真机 `纬度, 经度 ±35m` |
|
||||
| MCP(Python 写的服务) | ✅ 连接 + 列工具 + 调用成功 |
|
||||
| 设置保存 | ✅ 保存前后逐字段一致(含 API Key / 系统提示词),空值攻击被忽略 |
|
||||
| 思考强度映射 | ✅ 两份内核对拍 50/50 一致 |
|
||||
| 界面 | ✅ 对话 / 抽屉 / 终端 / 设置 / 模型面板 截图见文首 |
|
||||
|
||||
### 5.2 其他平台
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 浏览器渲染 | ✅ 无头 Edge + CDP,5 个页面全部渲染,控制台无异常 |
|
||||
| 端到端工具调用 | ✅ mock 模型 → 请求 `calc` → Python 返回 → 第二轮流式回答 → 落库 |
|
||||
| Python 工具 | ✅ `calc` `now` `get_weather`(实时数据) `notes` `web_fetch` 全部通过 |
|
||||
| MCP | ✅ filesystem 14 工具、memory 9 工具连接成功;6 类校验错误全部拦截 |
|
||||
| Windows exe | ✅ 冷启动、界面渲染、内置内核、MCP 自动连接 |
|
||||
|
||||
### 5.3 没有 API Key 也能把链路跑通
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假的 OpenAI 兼容服务,监听 5299
|
||||
node scripts/verify-phone.mjs emulator-5556 # 或对真机跑
|
||||
```
|
||||
|
||||
mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式回答"来演,
|
||||
所以能验证完整的 界面 → 内核 → 工具调用 → 流式返回 链路,**不消耗任何额度**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 给 Lynx 界面(Web / exe)的注意事项
|
||||
|
||||
安卓端已经不用 Lynx 了,这一节只对 Web/exe 有效:
|
||||
|
||||
- **Fresco 必须先初始化**,否则图片不显示;**Fresco 不能解码 SVG**,图标要预先栅格化成 PNG
|
||||
- Lynx 的 `fetch` 没有 `response.body`,所以流式走轮询通道
|
||||
- 状态栏/布局用 `safe-area` 相关变量,别写死 px
|
||||
- 动画(`breathe` 那种)在某些模拟器上会破坏图片绘制,已改成不影响绘制的写法
|
||||
|
||||
---
|
||||
|
||||
## 7. 打包踩坑记录
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 384 MB)
|
||||
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||
|
||||
### 7.2 Android APK
|
||||
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||
否则 `nativeLibraryDir` 是空的,`.so` 全在 APK 里,取 bootstrap 时得从 `applicationInfo.sourceDir` 读
|
||||
- **`targetSdk = 28`**(见 4.1),`abiFilters = ["arm64-v8a", "x86_64"]`
|
||||
- 构建脚本会把 `tools/*.py` 拷进 `app/src/main/python/` 并生成 `bundled_tool_sources.py`
|
||||
- 构建暂存目录用 ASCII 路径(`C:\DoubaoAndroid`),中文路径会让 Gradle/Chaquopy 出问题
|
||||
- **别并发跑两次 Gradle**:会互相踩坏 Chaquopy 的 venv(`Scripts/python.exe does not exist`)
|
||||
|
||||
### 7.3 Chaquopy / 内嵌 Python
|
||||
- `.pyc`-only 打包导致 `loader.get_source()` 失败 → 工具源码用 base64 内嵌
|
||||
- 每次构建都会连云 pip → 已改为零第三方依赖(见 4.7)
|
||||
|
||||
### 7.4 Android 15+ 的 edge-to-edge
|
||||
强制 edge-to-edge 后,状态栏会压住顶栏、输入法会盖住输入框。
|
||||
Compose 里统一在根布局吃 `WindowInsets.safeDrawing`,滚动页再叠 `imePadding()`。
|
||||
|
||||
### 7.5 工具链(Windows)
|
||||
- **Node 20+ 不能直接 `spawn` `.bat`/`.cmd`**(`status=null`),必须 `shell: true`
|
||||
- **PowerShell 会把命令行里的 JSON 引号搅坏**:所有内联 node/python 脚本都写成文件再跑
|
||||
- **PowerShell 的 `Get-Content` / `Set-Content` 会按 GBK 读写 UTF-8 文件**,
|
||||
一读一写就把中文文档转成乱码(本文档就被这么毁过一次)。
|
||||
改文本一律用编辑器工具,别用这两个 cmdlet 做"读进来再写回去"
|
||||
- **Kotlin 的块注释会嵌套**:在 KDoc 里写 `lib/*.so` 里的 `/*` 会开一个嵌套注释,
|
||||
把后面的代码全吞掉,报错却指向文件末尾之外的行
|
||||
|
||||
### 7.6 安卓 `org.json` 不会把 `Map` 转成 JSON 对象(踩过一次大的)
|
||||
|
||||
`json.put("speech", mapOf("autoRead" to true))` **不会**产生 `{"speech":{"autoRead":true}}`,
|
||||
而是把 Map 原样存进去,序列化出来是 `{"speech":"{autoRead=true}"}` —— **值是字符串**。
|
||||
|
||||
这一个坑连锁出四件事:
|
||||
|
||||
1. 内核把字符串写进了 `settings.json`(`speech` 本来是对象,被字符串顶掉了)
|
||||
2. 之后**每一次**读配置(`{**默认, **字符串}`)都抛 `TypeError`
|
||||
3. `/api/state` 从此永远返回 `{"error":"'str' object is not a mapping"}`
|
||||
4. App 把这个错误 JSON 解析成了「全默认状态」,而且**不抛异常**,所以还弹了"已保存"
|
||||
|
||||
用户看到的就是:**点一下语音按钮,模型变「未设置」、昵称变回「我」、会话列表全空**。
|
||||
|
||||
修了三处(缺一不可):
|
||||
- **安卓**:`patchToJson()` 显式递归把 Map/List 转成 `JSONObject`/`JSONArray`(见 `AppViewModel.kt`)
|
||||
- **内核写**:`tools`/`security`/`speech` 这几个子对象,补丁里不是字典就**直接忽略**,
|
||||
宁可这次改动不生效,也不写出读不回来的配置
|
||||
- **内核读**:发现子对象不是字典就**回落默认值**(自愈)——
|
||||
一个坏字段不该让 `/api/state` 永久 500,更不该把用户其它数据一起拖没
|
||||
|
||||
> 为什么之前没暴露:只有**嵌套对象**才触发,而在此之前 App 从没发过嵌套补丁
|
||||
> (`tools` 那两个开关从来没在设置页点过)。教训是——
|
||||
> **跨语言边界传结构化数据时,别信任何一侧的隐式转换**,两端都要有"形状不对就拒绝"的防线。
|
||||
|
||||
### 7.7 部分 ROM 会吞掉应用日志
|
||||
realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一条都看不到**。
|
||||
所以安装进度、终端会话退出原因等关键信息都**落盘**到 `files/termux-install.log`,
|
||||
用 `adb shell run-as com.doubao.lynxclone cat files/termux-install.log` 读。
|
||||
|
||||
---
|
||||
|
||||
## 8. 已知限制
|
||||
|
||||
- **`targetSdk = 28` 上不了应用商店**(个人侧载没问题)。要上架就得回到"外装 Termux + 桥接"那条路
|
||||
- **pty 在部分 ROM 上不可用**(4.5),自动降级成控制台模式,没有全屏 TUI
|
||||
- **内嵌 CPython 没有 `python` 可执行文件**,`python_run` 是进程内 exec,不能起子进程
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发
|
||||
npm run dev # 起 Node 内核 + Lynx 热更
|
||||
npm run build # 构建 Lynx bundle
|
||||
npm run apk # 构建 APK(--clean 可彻底重建)
|
||||
npm run exe # 打包 Windows exe
|
||||
|
||||
# 验证
|
||||
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-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。
|
||||
|
||||
约定见 [`AGENTS.md`](AGENTS.md)(入口)和 [`豆鲍/AGENTS.md`](豆鲍/AGENTS.md)(详细)。
|
||||
|
||||
@@ -1,303 +0,0 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* [规则包编辑](v1.2 附录 D)—— 全屏。
|
||||
*
|
||||
* ## 为什么全屏
|
||||
*
|
||||
* 里面有:名称、说明、两张定义表、若干段 Python 脚本。任何一个都超过
|
||||
* 一屏弹窗能装下的量 —— 按仓库的界面约定,这就是该开全屏的那种。
|
||||
*
|
||||
* ## 脚本框的形状(照抄节点代码组件的做法)
|
||||
*
|
||||
* 两条硬要求,都来自踩过的坑(见 AGENTS.md):
|
||||
*
|
||||
* 1. **不软换行** —— ` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
* 就是语法。做法是"把输入框塞进足够宽的横向滚动容器"。
|
||||
* 2. **有高度上限** —— 只写 `heightIn(min=...)` 的话,脚本一长框就长到
|
||||
* 屏幕外,把底下的东西顶出去。
|
||||
*
|
||||
* ## 定义表这版是只读的
|
||||
*
|
||||
* 数值/状态的**结构**(min/max、区间表、叠加层数)是一堆嵌套结构,
|
||||
* 用表单编辑要另做一套增删改。这一版先把**脚本**做成可编辑的
|
||||
* (那是最需要改的部分),定义表只读 + 指路导入导出。
|
||||
* 界面上**如实写着**这一点,不让用户对着只读的表发愣。
|
||||
*/
|
||||
@Composable
|
||||
fun RulePackEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val pack = vm.editingRulePack
|
||||
if (pack == null) {
|
||||
FullScreen(title = "规则包编辑", onBack = onBack) { Hint("正在读……") }
|
||||
return
|
||||
}
|
||||
|
||||
var name by remember(pack.id) { mutableStateOf(pack.name) }
|
||||
var note by remember(pack.id) { mutableStateOf(pack.note) }
|
||||
var scripts by remember(pack.id) { mutableStateOf(pack.scripts) }
|
||||
var editing by remember(pack.id) { mutableStateOf("") }
|
||||
var newScript by remember(pack.id) { mutableStateOf("") }
|
||||
var draft by remember(pack.id) { mutableStateOf("") }
|
||||
|
||||
fun infoJson(): JSONObject {
|
||||
val o = JSONObject()
|
||||
o.put("name", name)
|
||||
o.put("stats", JSONArray().apply {
|
||||
for (s in pack.stats) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("min", s.min).put("max", s.max)
|
||||
.put("shared", s.shared).put("script", s.script)
|
||||
.put("ranges", JSONArray().apply {
|
||||
for (r in s.ranges) {
|
||||
put(JSONObject().put("min", r.min).put("max", r.max).put("text", r.text))
|
||||
}
|
||||
}))
|
||||
}
|
||||
})
|
||||
o.put("statuses", JSONArray().apply {
|
||||
for (s in pack.statuses) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("type", s.kind).put("turns", s.turns)
|
||||
.put("max_stack", s.maxStack).put("script", s.script))
|
||||
}
|
||||
})
|
||||
return o
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "规则包编辑",
|
||||
subtitle = "${pack.stats.size} 条数值 · ${pack.statuses.size} 条状态 · ${scripts.size} 个脚本",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("保存") { vm.saveRulePack(name, note, infoJson(), scripts) }
|
||||
},
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("名称", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
value = note,
|
||||
onValueChange = { note = it },
|
||||
label = { Text("说明", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
|
||||
// ---------------- 脚本(可编辑)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("脚本")
|
||||
if (vm.editingRulePack?.hasScripts != true) {
|
||||
Hint("这个包还没有脚本。数值的裁决、状态的每轮行为、赋予判定都靠脚本。")
|
||||
}
|
||||
Card {
|
||||
for ((fname, src) in scripts) {
|
||||
if (editing == fname) {
|
||||
Text(fname, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
CodeBox(value = draft, onValueChange = { draft = it })
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("保存这段") {
|
||||
scripts = scripts + (fname to draft)
|
||||
editing = ""
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("取消") { editing = "" }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("删掉") {
|
||||
scripts = scripts - fname
|
||||
editing = ""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fname, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
"${src.lines().size} 行 · 点开编辑",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("编辑") { editing = fname; draft = src }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
// 新建一段
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = newScript,
|
||||
onValueChange = { newScript = it },
|
||||
label = { Text("新脚本文件名", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("新建") {
|
||||
val f = newScript.trim()
|
||||
if (f.isNotBlank() && !scripts.containsKey(f)) {
|
||||
scripts = scripts + (f to SCRIPT_TEMPLATE)
|
||||
newScript = ""
|
||||
editing = f
|
||||
draft = SCRIPT_TEMPLATE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 定义(只读)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("数值定义")
|
||||
Card {
|
||||
if (pack.stats.isEmpty()) Hint("没有数值。")
|
||||
for (s in pack.stats) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${fmt(s.min)} ~ ${fmt(s.max)}" + if (s.shared) " · 全世界观共用" else "",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.ranges.isNotEmpty()) {
|
||||
Text(
|
||||
"${s.ranges.size} 段区间:" + s.ranges.joinToString("、") {
|
||||
"${fmt(it.min)}~${fmt(it.max)}「${it.text.take(10)}」"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.script.isNotBlank()) {
|
||||
Text("裁决脚本:${s.script}", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态定义")
|
||||
Card {
|
||||
if (pack.statuses.isEmpty()) Hint("没有状态。")
|
||||
for (s in pack.statuses) {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
(if (s.isPersistent) "持久" else "定时 ${s.turns} 轮") +
|
||||
(if (s.maxStack > 1) " · 最多叠 ${s.maxStack} 层" else ""),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Hint(
|
||||
"定义(数值和状态的增删、区间表)这一版还是只读的 —— " +
|
||||
"用「导出」在电脑上改 info.json 再导入是最快的办法。" +
|
||||
"界面上能改的是脚本,那也是最常改的部分。",
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建脚本时给的骨架(三个入口都列出来,用户知道可以写什么) */
|
||||
private const val SCRIPT_TEMPLATE = """# 可用的三个入口(写哪个都行,不写的就不执行):
|
||||
|
||||
def on_stat_change(name, value, delta):
|
||||
# 数值裁决:返回生效的增量(可以放大、缩小、返回 0 否决)
|
||||
return delta
|
||||
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
# 每轮生成回复之前跑一次(状态脚本)
|
||||
# stats_api['change_stat']('好感度', -1)
|
||||
# stats_api['set_hint']('中毒', '你眼前发黑')
|
||||
# stats_api['narrate']('毒性发作了')
|
||||
return True
|
||||
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
# 别人要给你挂状态时,返回 False 就是抵抗掉
|
||||
return True
|
||||
"""
|
||||
|
||||
/**
|
||||
* 代码框:**不软换行** + **有高度上限**。
|
||||
*
|
||||
* ★ 不软换行:` else:` 折成两行、缩进全乱,而 Python 的缩进就是语法。
|
||||
* 做法是"把输入框塞进足够宽的横向滚动容器"(这个 Compose 版本的
|
||||
* `BasicTextField` 经典重载选不中,见 AGENTS.md)。
|
||||
*
|
||||
* ★ 高度上限:只写 `heightIn(min=...)` 的话脚本一长框就长到屏幕外,
|
||||
* 把底下的东西顶出去,用户够不着。
|
||||
*/
|
||||
@Composable
|
||||
private fun CodeBox(value: String, onValueChange: (String) -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState())) {
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoText(),
|
||||
),
|
||||
modifier = Modifier.width(900.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 9.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 4.7 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 44 KiB |
File diff suppressed because it is too large
Load Diff
@@ -1,378 +0,0 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
把「人设 + Skill 手册 + 世界观 + 情绪 + 记忆 + 同伴情绪」按**固定顺序**
|
||||
拼成一段 system prompt。
|
||||
|
||||
## 为什么单独一个模块,而不是写在 agent_loop 里
|
||||
|
||||
因为这里有**六种来源**,每一种都要判空、要查库/查 JSON、出错了还不能把
|
||||
整轮对话带崩。塞在 agent_loop 里会让那个函数变成两百行,而且没法单独测。
|
||||
|
||||
## 几条硬约定
|
||||
|
||||
**① 空段整段删掉。**
|
||||
绑没绑世界观、有没有情绪、记没记过东西 —— 都是常态。
|
||||
不删的话每次对话都带着一堆空的 `<worldview></worldview>`,
|
||||
模型会以为"这里本来该有内容但我没看到",反而更容易瞎编。
|
||||
|
||||
**② 顺序固定:人设 → skills → worldview → emotion → memory → peer_emotions。**
|
||||
见附录 C。顺序不是审美问题:记忆在情绪之后,模型读到"我现在有点烦"
|
||||
再看记忆,语气才连贯;反过来它会先看到一堆事实、再看到情绪,像事后补的。
|
||||
|
||||
**③ 每轮重新拼。**
|
||||
记忆和情绪随时会变(AI 自己就能改),拼一次缓存住的话,
|
||||
用户会看到"我明明让它记住了,下一句它又忘了"。
|
||||
|
||||
**④ 查库失败一律当成"这段没有"。**
|
||||
数据库被锁、文件损坏都不该让用户发不出消息。
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_engine
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
DEFAULT_MEMORY_LINE,
|
||||
DEFAULT_PROMPT_TEMPLATE,
|
||||
)
|
||||
|
||||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
|
||||
#: 段落名,**顺序就是注入顺序**(需求附录 C,v1.2 按缓存友好重排)。
|
||||
#:
|
||||
#: ★★ 为什么顺序这么重要:主流模型的上下文缓存都是**前缀匹配** ——
|
||||
#: 从第一个 token 开始逐段比对,一处不同则**其后全部失效**。
|
||||
#: 所以最稳的排前面(prompt/skills/worldview/memory 组成长前缀),
|
||||
#: 最易变的排最后(stats/status/emotion/peer_emotions)。
|
||||
#:
|
||||
#: 改之前 emotion 在 memory 前面 —— 情绪一变,连最长的 memory 段
|
||||
#: 一起失效。挪到后面之后,情绪变化只影响末尾那几个短段。
|
||||
#:
|
||||
#: ★ 这个元组**同时决定** `render` 处理哪些段:不在里面的占位符不会被替换,
|
||||
#: 会原样留在提示词里(带着 `{xxx}` 大括号)。加新段时两处一起改。
|
||||
SECTIONS = ('skills', 'worldview', 'memory', 'stats', 'status', 'emotion', 'peer_emotions')
|
||||
|
||||
|
||||
def _safe(fn, fallback):
|
||||
"""
|
||||
跑一个小查询,出错就当"没有"。
|
||||
|
||||
★ 单独抽出来是因为这个模式在这里出现六次:**任何一处查库失败都不该
|
||||
让整轮对话发不出去**(数据库锁了、agent.db 被删了、JSON 坏了)。
|
||||
"""
|
||||
try:
|
||||
return fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[agent_context] 取上下文失败,按"没有"处理:{exc}', file=__import__('sys').stderr)
|
||||
return fallback
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 各段
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_skills(agent: dict) -> str:
|
||||
"""
|
||||
`<skills>` 段:内置手册 + 这个智能体绑定的自定义 Skill(**按绑定顺序**)。
|
||||
|
||||
内置的那份永远在最前面 —— 它讲的是记忆/情绪这些**基础工具**怎么用,
|
||||
自定义 Skill 是额外的,放后面读起来才是"先会基本操作,再学扩展"。
|
||||
"""
|
||||
parts = [BUILTIN_SKILL.strip()] if BUILTIN_SKILL.strip() else []
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if agent_id:
|
||||
for sid in _safe(lambda: agentdb.skills_of(agent_id), []):
|
||||
sk = _safe(lambda: store.get_resource('skills', sid), None)
|
||||
if sk and (sk.get('content') or '').strip():
|
||||
parts.append(f'【{(sk.get("name") or "Skill").strip()}】\n{sk["content"].strip()}')
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
|
||||
def build_worldview(agent: dict) -> str:
|
||||
"""`<worldview>` 段:绑定的世界观设定文本(没绑就是空)"""
|
||||
wid = (agent or {}).get('worldviewId') or ''
|
||||
if not wid:
|
||||
return ''
|
||||
wv = _safe(lambda: store.get_resource('worldviews', wid), None)
|
||||
return (wv or {}).get('setting', '').strip()
|
||||
|
||||
|
||||
def memory_scope(agent: dict) -> str:
|
||||
"""这个智能体当前该读写哪个记忆空间(绑了世界观就是共享空间)"""
|
||||
agent = agent or {}
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def build_emotion(agent: dict) -> str:
|
||||
"""
|
||||
`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)。
|
||||
|
||||
v1.2 双字段,两行都带(附录 C 的模板就是这样):
|
||||
|
||||
preset: 怒
|
||||
text: 这背叛让我无法原谅
|
||||
|
||||
`preset` 是给它**自己**用的(它要据此调整行为),`text` 是扮演质感。
|
||||
两个都注入 —— 这是唯一一处两者都出现的地方(给同伴的只有 preset)。
|
||||
|
||||
★ 「平常 + 没写文本」时整段省掉:不然每个没情绪的智能体都白带一段
|
||||
没有信息量的 `<emotion>`,还占 token。空段整段删除是附录 C 的规矩。
|
||||
"""
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if not agent_id:
|
||||
return ''
|
||||
st = _safe(lambda: agentdb.emotion_state(agent_id), None) or {}
|
||||
preset = (st.get('preset') or '').strip()
|
||||
text = (st.get('text') or '').strip()
|
||||
if not text and preset in ('', agentdb.PRESET_DEFAULT):
|
||||
return ''
|
||||
lines = [f'preset: {preset or agentdb.PRESET_DEFAULT}']
|
||||
if text:
|
||||
lines.append(f'text: {text}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
"""
|
||||
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||||
|
||||
## 注入窗口 + 置顶保护
|
||||
|
||||
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||||
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
|
||||
早期记忆反而挤掉了最近的对话上下文**。
|
||||
|
||||
所以这里按**窗口**裁:
|
||||
|
||||
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
|
||||
· 其余按时间取**最近**的,凑够窗口
|
||||
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
|
||||
不是用来否决用户明确置顶的东西)
|
||||
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
|
||||
也就是"降级为仅可检索"
|
||||
|
||||
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
|
||||
|
||||
## 共享记忆带作者署名
|
||||
|
||||
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
|
||||
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
|
||||
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
|
||||
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
|
||||
得先分得清谁写的)。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
"""
|
||||
scope = memory_scope(agent)
|
||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||
if not items:
|
||||
return ''
|
||||
|
||||
# ---- 窗口裁剪 ----
|
||||
settings = _safe(store.read_settings, {}) or {}
|
||||
try:
|
||||
window = int(settings.get('memoryWindow') or 0)
|
||||
except (TypeError, ValueError):
|
||||
window = 0
|
||||
total = len(items)
|
||||
trimmed = 0
|
||||
if window > 0 and total > window:
|
||||
pinned = [m for m in items if m.get('pinned')]
|
||||
rest = [m for m in items if not m.get('pinned')]
|
||||
room = max(0, window - len(pinned))
|
||||
keep = pinned + (rest[-room:] if room else [])
|
||||
# 顺序:置顶的在前(用户明确要的),其余保持时间顺序
|
||||
items = keep
|
||||
trimmed = total - len(keep)
|
||||
parts = []
|
||||
if pinned:
|
||||
parts.append(f'置顶 {len(pinned)} 条')
|
||||
if trimmed:
|
||||
parts.append(f'另有 {trimmed} 条较早的没放进来(用 memory_search 还能搜到)')
|
||||
note = '(' + ';'.join(parts) + ')' if parts else ''
|
||||
else:
|
||||
note = ''
|
||||
|
||||
tmpl = _safe(
|
||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||
DEFAULT_MEMORY_LINE,
|
||||
)
|
||||
shared = scope.startswith('world:')
|
||||
names = {}
|
||||
if shared:
|
||||
names = {a.get('id'): (a.get('name') or '某人') for a in _safe(store.list_agents, [])}
|
||||
me = (agent or {}).get('id') or ''
|
||||
lines = []
|
||||
for it in items:
|
||||
title = (it.get('title') or '').strip()
|
||||
content = (it.get('content') or '').strip()
|
||||
author = (it.get('author_agent') or '').strip()
|
||||
tags = []
|
||||
if it.get('pinned'):
|
||||
tags.append('置顶')
|
||||
if shared and author:
|
||||
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||||
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
|
||||
if tags:
|
||||
title = f'{title}({",".join(tags)})'
|
||||
try:
|
||||
lines.append(tmpl.format(title=title, content=content))
|
||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
||||
body = '\n'.join(lines)
|
||||
return f'{body}\n{note}' if note else body
|
||||
|
||||
|
||||
def build_peer_emotions(agent: dict) -> str:
|
||||
"""
|
||||
`<peer_emotions>` 段:**同世界观其他智能体**的名字(+ 情绪)(需求 3.5)。
|
||||
|
||||
★★ 分两档,不是"开关一关就什么都没有":
|
||||
|
||||
· 绑了世界观但**没开**情绪感知 → 只给**成员名单**(谁在,但看不到情绪)
|
||||
· 绑了世界观且**开了**开关 → 名单 + 各自当前的情绪
|
||||
|
||||
为什么关着也要给名单(复查报告第 5 条):
|
||||
共享记忆是**共用**的,AI 一定会看到"别人写的条目"。如果它连
|
||||
"这个空间里还有别人"都不知道,那些第三人称的条目在它眼里就是
|
||||
**自己的记忆**——它会以为"我什么时候去过九霄山?",
|
||||
于是把别人的经历当成自己的,或者在正文里跟用户说"我没记过这个"。
|
||||
名单不含情绪,所以"角色内的隐私"这条边界仍然守住了。
|
||||
|
||||
★ 情绪感知开关默认关(需求原话"默认关闭")—— 别人的**情绪**属于
|
||||
角色内的隐私,默认让 AI 看到会让它们的表现互相串味。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if not agent.get('worldviewId'):
|
||||
return ''
|
||||
my_id = agent.get('id') or ''
|
||||
wid = agent.get('worldviewId') or ''
|
||||
others = [
|
||||
a for a in _safe(store.list_agents, [])
|
||||
if a.get('worldviewId') == wid and a.get('id') != my_id
|
||||
]
|
||||
if not others:
|
||||
return ''
|
||||
|
||||
by_id = {a.get('id'): a for a in others}
|
||||
names = [(by_id.get(aid) or {}).get('name') or '某人' for aid in by_id]
|
||||
|
||||
if not agent.get('emotionEnabled'):
|
||||
return ';'.join(f'{n}(不知道他此刻的情绪)' for n in names)
|
||||
|
||||
rows = _safe(
|
||||
lambda: agentdb.peer_emotions(wid, my_id, list(by_id)),
|
||||
[],
|
||||
)
|
||||
emo_by_id = {aid: (emo or '').strip() for aid, emo in rows}
|
||||
parts = []
|
||||
for aid, one in by_id.items():
|
||||
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
||||
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
||||
name = one.get('name') or '某人'
|
||||
# ★ v1.2:这里给的是 **preset(五档)不是 text**。
|
||||
# text 是那个角色的内心独白,读给别的角色听等于扒开他的脑子;
|
||||
# preset 才是"看得出来他现在什么脸色"这个粒度。
|
||||
emo = emo_by_id.get(aid) or ''
|
||||
parts.append(f'{name}-{emo}' if emo else f'{name}(看不出什么情绪)')
|
||||
return ';'.join(parts)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拼装
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_RE_BLOCK = {name: re.compile(rf'<{name}>.*?</{name}>', re.S) for name in SECTIONS}
|
||||
|
||||
|
||||
def render(template: str, values: dict) -> str:
|
||||
"""
|
||||
按模板渲染,**空的段整段删掉**。
|
||||
|
||||
★ 先渲染 `{prompt}` 再处理段:人设里如果碰巧有 `<memory>` 这样的字
|
||||
(用户自己写的提示词里完全可能),会被当成段处理掉 —— 所以段的匹配
|
||||
只在**模板**上做,不在渲染结果上做。
|
||||
"""
|
||||
out = (template or DEFAULT_PROMPT_TEMPLATE).replace('{prompt}', (values.get('prompt') or '').strip())
|
||||
for name in SECTIONS:
|
||||
block = _RE_BLOCK[name].search(out)
|
||||
if not block:
|
||||
continue
|
||||
value = (values.get(name) or '').strip()
|
||||
if value:
|
||||
out = out[:block.start()] + f'<{name}>\n{value}\n</{name}>' + out[block.end():]
|
||||
else:
|
||||
out = out[:block.start()] + out[block.end():]
|
||||
# 段被删掉后会留下连续空行,压一压;别让提示词里出现四五行的空白
|
||||
out = re.sub(r'\n{3,}', '\n\n', out)
|
||||
return out.strip()
|
||||
|
||||
|
||||
def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
"""
|
||||
这一轮要用的 system prompt。
|
||||
|
||||
[settings] 里可以覆盖:`promptTemplate`(整份模板)、`memoryLine`(记忆条目排版)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||||
values = {
|
||||
'prompt': prompt,
|
||||
# ---- 稳定段:它们在提示词最前面,靠它们拿前缀缓存命中 ----
|
||||
'skills': build_skills(agent),
|
||||
'worldview': build_worldview(agent),
|
||||
'memory': build_memory(agent),
|
||||
# ---- 易变段:放最后,变了也只让末尾失效 ----
|
||||
# stats / status 是 v1.2 §3.10/3.11 的规则引擎段,实现见阶段 3;
|
||||
# 现在返回空串 → `render` 会把整段删掉(不会留下空标签)
|
||||
'stats': build_stats(agent),
|
||||
'status': build_status(agent),
|
||||
'emotion': build_emotion(agent),
|
||||
'peer_emotions': build_peer_emotions(agent),
|
||||
}
|
||||
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
|
||||
return render(template, values)
|
||||
|
||||
|
||||
def pack_of(agent: dict) -> str:
|
||||
"""
|
||||
这个智能体用的规则包 id(`世界观.rulePackId`),没有就空串。
|
||||
|
||||
★ 数值状态包挂在**世界观**上(需求 §3.6:"v1.2 起,世界观同时是
|
||||
数值状态包的挂载点"),所以没绑世界观就没有规则引擎 —— 返回空串,
|
||||
`<stats>` / `<status>` 两段会被整段删掉。
|
||||
"""
|
||||
wid = ((agent or {}).get('worldviewId') or '').strip()
|
||||
if not wid:
|
||||
return ''
|
||||
world = _safe(lambda: store.get_resource('worldviews', wid), None) or {}
|
||||
return (world.get('rulePackId') or '').strip()
|
||||
|
||||
|
||||
def build_stats(agent: dict) -> str:
|
||||
"""
|
||||
`<stats>` 段:数值系统(需求附录 C / §3.10)。
|
||||
|
||||
格式见 `rule_engine.stats_section`。没绑世界观、或世界观没挂规则包 → 空段。
|
||||
"""
|
||||
pack = pack_of(agent)
|
||||
if not pack:
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.stats_section(agent or {}, pack), '')
|
||||
|
||||
|
||||
def build_status(agent: dict) -> str:
|
||||
"""
|
||||
`<status>` 段:状态系统(需求附录 C / §3.11)。
|
||||
|
||||
★ 和 `<stats>` 不同,它**不要求绑世界观**:状态一旦被赋予就挂在智能体
|
||||
自己身上,解绑世界观不该让它身上的状态凭空消失(那和"解绑不丢记忆"
|
||||
是同一个道理)。
|
||||
"""
|
||||
if not ((agent or {}).get('id') or ''):
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.status_section(agent or {}), '')
|
||||
@@ -1,773 +0,0 @@
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
|
||||
## 为什么是"内置工具"而不是 `tools/*.py`
|
||||
|
||||
`tools/` 下的工具是**用户可改的 .py 文件**(内核启动时播种到手机上的可写目录)。
|
||||
这七个不一样:
|
||||
|
||||
· 它们要读写 `agent.db`(记忆、情绪、Token 统计)—— 那是内核进程内的模块,
|
||||
电脑端的工具是**子进程**,根本 import 不到
|
||||
· 它们是系统的核心能力,不该被用户在 tools/ 里改坏(改坏了 AI 会"失忆",
|
||||
而且表现是"有时记得有时不记得",极难查)
|
||||
|
||||
所以走 `builtin_tools.BUILTIN_TOOLS` 那条路(进程内、不进 tools/、不参与播种)。
|
||||
|
||||
## 限权规则(需求 3.6,**共享记忆里最重要的一条**)
|
||||
|
||||
绑定了世界观的智能体共用一个记忆空间,于是"谁都能删"就成了问题:
|
||||
|
||||
· `memory_add` —— 任何智能体都能往共享空间写(追加优先)
|
||||
· `memory_forget` / `memory_update` —— **只能动自己写的**(按 author_agent 判定)
|
||||
· `pinned` —— 用户标记"必须保留"的条目,AI 连自己的都改不动
|
||||
|
||||
改别人的条目只能由**用户在界面上手动做**。这条不做的话,
|
||||
两个智能体互相删对方的记忆,用户会看到"记忆莫名其妙少了"。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拿"我现在是谁"
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _ctx() -> dict:
|
||||
"""
|
||||
当前这次工具调用的上下文(哪次对话、哪个智能体)。
|
||||
|
||||
★ 局部 import:`tools_runtime` → `builtin_tools` → 这里,顶部 import 就成环了。
|
||||
"""
|
||||
import tools_runtime
|
||||
|
||||
return tools_runtime.current_context() or {}
|
||||
|
||||
|
||||
def _me() -> dict:
|
||||
"""当前智能体(拿不到就返回空 dict —— 工具会据此报错,而不是瞎写)"""
|
||||
ctx = _ctx()
|
||||
agent = store.get_agent(ctx.get('agentId') or '') or {}
|
||||
return agent
|
||||
|
||||
|
||||
def _my_scope(agent: dict) -> str:
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def _shared(agent: dict) -> bool:
|
||||
"""是不是在共享空间里(绑了世界观就是)"""
|
||||
return bool(agent.get('worldviewId'))
|
||||
|
||||
|
||||
def _check_editable(item: dict, agent: dict) -> None:
|
||||
"""
|
||||
能不能改/删这一条 —— 不能就抛错(**抛错而不是静默跳过**:
|
||||
静默的话模型以为改成功了,下一轮还按老样子说话)。
|
||||
"""
|
||||
if item.get('pinned'):
|
||||
raise ValueError(
|
||||
'这条记忆被用户标记为「必须保留」,你改不了也删不掉。'
|
||||
'如果它确实过时了,跟用户说一声让他自己处理。'
|
||||
)
|
||||
if _shared(agent) and (item.get('author_agent') or '') != (agent.get('id') or ''):
|
||||
raise ValueError(
|
||||
'这条是**其他智能体**写进共享记忆的,你只能改/删自己写的。'
|
||||
'需要修改它的话,跟用户说让他手动改。'
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
MEMORY_ADD = {
|
||||
'name': 'memory_add',
|
||||
'description': (
|
||||
'记住一件事,**跨对话保留**。用户告诉你的重要事实、偏好、约定、他的项目,'
|
||||
'都该记下来。记之前先看系统提示词里的记忆清单,已经记过的别再记一遍。'
|
||||
'返回新条目的 id(以后要改/删它需要这个 id)。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'title': {'type': 'string', 'description': '一句话标题(检索和整理时的锚点)'},
|
||||
'content': {'type': 'string', 'description': '要记住的正文'},
|
||||
},
|
||||
'required': ['title', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_add(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体,无法写记忆')
|
||||
title = str(args.get('title') or '').strip()
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not title and not content:
|
||||
raise ValueError('title 和 content 至少要有一个')
|
||||
item = agentdb.memory_add(
|
||||
scope=_my_scope(agent),
|
||||
title=title,
|
||||
content=content,
|
||||
author_agent=agent.get('id') or '',
|
||||
)
|
||||
return {
|
||||
'id': item['id'],
|
||||
'title': item['title'],
|
||||
'scope': '共享记忆(世界观)' if _shared(agent) else '你自己的记忆',
|
||||
'note': '已写入。不要只在正文里说"记住了"—— 你现在已经真的记住了,正常继续就行。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_UPDATE = {
|
||||
'name': 'memory_update',
|
||||
'description': (
|
||||
'修改一条已有的记忆(只改传进来的字段)。'
|
||||
'只能改**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '记忆的 id(memory_add 返回过,或记忆清单里带的)'},
|
||||
'title': {'type': 'string', 'description': '新标题,不改就不传'},
|
||||
'content': {'type': 'string', 'description': '新正文,不改就不传'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_update(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
# ★ 只允许改**自己这个记忆空间**里的条目:不然知道 id 就能改到别人的私有记忆
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
updated = agentdb.memory_update(
|
||||
mid,
|
||||
title=args.get('title') if 'title' in args else None,
|
||||
content=args.get('content') if 'content' in args else None,
|
||||
)
|
||||
return {'id': mid, 'title': (updated or {}).get('title', ''), 'note': '已更新。'}
|
||||
|
||||
|
||||
MEMORY_FORGET = {
|
||||
'name': 'memory_forget',
|
||||
'description': (
|
||||
'删掉一条记忆。只能删**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
'拿不准该不该删时,先问用户。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '要删的记忆 id'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_forget(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
agentdb.memory_forget(mid)
|
||||
return {'id': mid, 'forgotten': True, 'note': '已删除。'}
|
||||
|
||||
|
||||
MEMORY_SEARCH = {
|
||||
'name': 'memory_search',
|
||||
'description': (
|
||||
'在自己的记忆库里检索。系统提示词里的记忆清单是**全量**的,'
|
||||
'但条数多的时候你可能只想找相关的几条 —— 用这个按关键词查。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'keyword': {'type': 'string', 'description': '关键词(标题和正文都会匹配)'},
|
||||
'limit': {'type': 'number', 'description': '最多返回几条,默认 10'},
|
||||
},
|
||||
'required': ['keyword'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_search(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
kw = str(args.get('keyword') or '').strip()
|
||||
if not kw:
|
||||
raise ValueError('keyword 不能为空')
|
||||
try:
|
||||
limit = int(float(args.get('limit') or 10))
|
||||
except (TypeError, ValueError):
|
||||
limit = 10
|
||||
rows = agentdb.memory_search(_my_scope(agent), kw, limit)
|
||||
return {
|
||||
'keyword': kw,
|
||||
'count': len(rows),
|
||||
'items': [
|
||||
{'id': r['id'], 'title': r['title'], 'content': r['content']} for r in rows
|
||||
],
|
||||
'note': '' if rows else '没有匹配的记忆。别据此说"我完全不记得"—— 换个关键词再试一次。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_SUGGEST_SUMMARY = {
|
||||
'name': 'memory_suggest_summary',
|
||||
'description': (
|
||||
'**建议**用户整理一次记忆(把零散的合并成几条)。'
|
||||
'你只负责建议,不执行 —— 用户点确认之后系统才会真的整理。'
|
||||
'什么时候用:记忆条数明显变多、或者有好几条在说同一件事。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'reason': {'type': 'string', 'description': '为什么建议整理(会显示给用户)'},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_suggest_summary(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
why = str(args.get('reason') or '').strip() or '记忆有点多了,想合并一下'
|
||||
# ★ 只挂一个"建议"标记,**不执行总结**(需求 3.2:仅提示不执行)。
|
||||
# 界面看到这个标记会给用户一个「整理记忆」按钮。
|
||||
store.add_pending_summary_suggestion(agent.get('id') or '', why)
|
||||
return {
|
||||
'suggested': True,
|
||||
'reason': why,
|
||||
'note': '已经建议了。**别再说"我整理好了"** —— 你只是提了个建议,'
|
||||
'用户点确认之后才会真的整理。正文里正常说这件事就行。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
EMOTION_SET = {
|
||||
'name': 'emotion_set',
|
||||
'description': (
|
||||
'更新**你自己**当前的情绪状态。两个字段都要给:\n'
|
||||
'· preset:五档之一 —— 喜 / 怒 / 哀 / 平常 / 死亡。它决定系统行为'
|
||||
'(立绘换哪张、同伴看到你什么脸色、死亡时能不能继续说话)。\n'
|
||||
'· text:一句自由描述,比如"刚被夸了,有点得意"。这只是扮演质感。\n'
|
||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'preset': {
|
||||
'type': 'string',
|
||||
'enum': list(agentdb.PRESETS),
|
||||
'description': '五档情绪之一',
|
||||
},
|
||||
'text': {'type': 'string', 'description': '一句自由描述(可选)'},
|
||||
},
|
||||
'required': ['preset'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def emotion_set(args: dict) -> dict:
|
||||
"""
|
||||
写自己的情绪(需求 3.5 双字段)。
|
||||
|
||||
★★ **禁止把自己从「死亡」改活**(需求 3.5 明文)。
|
||||
|
||||
为什么:死亡是"这个角色没了"。能自己复活的话死亡就没有重量 ——
|
||||
用户会看到 AI 上一句刚咽气、下一句又活蹦乱跳,整个系统的可信度就没了。
|
||||
|
||||
复活只有两条**别的**通道,都不经过这里:
|
||||
· 用户手动改(兜底主权,在记忆页的情绪区)
|
||||
· 状态脚本改(定时复活 / 解药剧情,见 §3.11 —— 那条路走沙箱,不走工具)
|
||||
"""
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
agent_id = agent.get('id') or ''
|
||||
preset = str(args.get('preset') or '').strip()
|
||||
text = str(args.get('text') or '').strip()
|
||||
if preset not in agentdb.PRESETS:
|
||||
raise ValueError(
|
||||
f'preset 只能是这五个之一:{"、".join(agentdb.PRESETS)}(收到的是「{preset}」)'
|
||||
)
|
||||
cur = agentdb.emotion_state(agent_id)
|
||||
if cur.get('preset') == agentdb.PRESET_DEAD and preset != agentdb.PRESET_DEAD:
|
||||
raise ValueError(
|
||||
'你已经是「死亡」状态,**不能自己复活**。'
|
||||
'复活只能由用户手动操作,或者由世界观里的状态脚本触发(比如定时复活、解药剧情)。'
|
||||
)
|
||||
nxt = agentdb.emotion_set(agent_id, preset=preset, text=text or None)
|
||||
return {
|
||||
'preset': nxt['preset'],
|
||||
'text': nxt['text'],
|
||||
'note': '已更新你自己的情绪。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用量
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GET_TOKEN_USAGE = {
|
||||
'name': 'get_token_usage',
|
||||
'description': (
|
||||
'查**你自己**累计用了多少 Token、还剩多少额度。'
|
||||
'用户问"你还能说多少""用了多少"时用这个查真实数字,别猜。'
|
||||
),
|
||||
'parameters': {'type': 'object', 'properties': {}},
|
||||
}
|
||||
|
||||
|
||||
def get_token_usage(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
usage = agentdb.token_usage(agent.get('id') or '')
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
return {
|
||||
'used': used,
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
# v1.2:缓存命中/未命中(0 = 这家没提供缓存信息)
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
'remaining': (None if limit <= 0 else max(0, limit - used)),
|
||||
'note': '额度无限制。' if limit <= 0 else f'还剩 {max(0, limit - used)} Token。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 规则引擎(v1.2 §3.10 / §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
CHANGE_STAT = {
|
||||
'name': 'change_stat',
|
||||
'description': (
|
||||
'申请改变**你自己**身上某个数值。\n'
|
||||
'★ 只能给**增量**(+5 / -10),**不能写绝对值** —— 因为数值可能被'
|
||||
'世界观里的规则脚本裁决(放大、缩小、甚至否决),绝对值会让那套规则失效。\n'
|
||||
'真实结果以返回值里的 after 为准:你以为加了 5,可能实际加了 10 或者 0。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type': 'string', 'description': '数值名(见系统提示词的 <stats> 段)'},
|
||||
'delta': {'type': 'number', 'description': '想改变多少(可正可负)'},
|
||||
},
|
||||
'required': ['name', 'delta'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def change_stat(args: dict) -> dict:
|
||||
"""
|
||||
申请数值增量(需求 §3.10)。
|
||||
|
||||
内核流程是固定的:**脚本裁决 → clamp → 写库 → 下一轮注入反映新值**。
|
||||
这里只负责把请求转过去、把**真实结果**回来告诉模型 ——
|
||||
它必须知道"我以为加 5,实际加了 10"(否则下一轮它会按错误的心智继续演)。
|
||||
"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(agent)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,身上没有数值系统')
|
||||
name = str(args.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('name 不能为空')
|
||||
raw = args.get('delta')
|
||||
try:
|
||||
delta = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f'delta 得是个数字(收到的是「{raw}」)') from None
|
||||
r = rule_engine.change(agent, pack, name, delta)
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
out = {
|
||||
'name': name,
|
||||
'applied': r.get('applied'),
|
||||
'before': r.get('before'),
|
||||
'after': r.get('after'),
|
||||
}
|
||||
if r.get('text'):
|
||||
out['now'] = r['text']
|
||||
if r.get('narration'):
|
||||
out['narration'] = r['narration']
|
||||
if r.get('applied') != delta:
|
||||
# ★ 被裁决过了要**明说**,不然模型会以为自己算错了
|
||||
out['note'] = f'你申请的是 {delta:+g},规则裁决后实际生效 {r.get("applied"):+g}。'
|
||||
return out
|
||||
|
||||
|
||||
GRANT_STATUS = {
|
||||
'name': 'grant_status',
|
||||
'description': (
|
||||
'给**同一个世界观里**的另一个智能体施加一个状态(比如中毒、庇佑)。\n'
|
||||
'对方可能**抵抗**(那是他的设定),被抵抗时你会拿到明确回执。\n'
|
||||
'跨世界观一律无效。同名状态重复施加默认**刷新时长**,不会叠层。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '目标的**名字**(或 id)'},
|
||||
'status_name': {'type': 'string', 'description': '状态名(见世界观规则包)'},
|
||||
'turns': {'type': 'integer', 'description': '持续几轮(可选,默认按定义)'},
|
||||
},
|
||||
'required': ['target', 'status_name'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _find_agent(needle: str):
|
||||
"""
|
||||
按名字或 id 找智能体。
|
||||
|
||||
★ 为什么按**名字**找:模型在提示词里看到的伙伴就是名字
|
||||
(`<peer_emotions>` 给的是"仙辰-哀"),它拿不到 id。
|
||||
重名时取第一个 —— 重名本来就不该发生(界面会显示 玄辰/玄辰(2),
|
||||
但那是显示层的事)。
|
||||
"""
|
||||
import store
|
||||
|
||||
key = str(needle or '').strip()
|
||||
if not key:
|
||||
return None
|
||||
for a in store.list_agents():
|
||||
if a.get('id') == key:
|
||||
return a
|
||||
for a in store.list_agents():
|
||||
if (a.get('name') or '').strip() == key:
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def grant_status(args: dict) -> dict:
|
||||
"""给同世界观的另一个智能体施加状态(需求 §3.11)"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(me)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,用不了状态系统')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
# 给自己挂状态用别的途径没有意义 —— 直接说不支持,
|
||||
# 免得模型以为"自残"是个正常操作
|
||||
raise ValueError('不能给自己施加状态,只能施加给同世界观的其他智能体')
|
||||
status_name = str(args.get('status_name') or '').strip()
|
||||
try:
|
||||
turns = int(args.get('turns') or 0)
|
||||
except (TypeError, ValueError):
|
||||
turns = 0
|
||||
r = rule_engine.grant(me, pack, target, status_name, turns)
|
||||
if not r.get('ok'):
|
||||
# ★ 被抵抗时**抛错**而不是返回 ok:false —— 需求说"A 必须知道结果",
|
||||
# 而工具抛错是模型一定会看到的那条路(返回里的字段它可能忽略)
|
||||
raise ValueError(r.get('error') or '赋予失败')
|
||||
return {
|
||||
'target': r.get('target'),
|
||||
'status': r.get('name'),
|
||||
'remaining': r.get('remaining'),
|
||||
'refreshed': r.get('refreshed'),
|
||||
'note': ('对方本来就有这个状态,已刷新时长。' if r.get('refreshed')
|
||||
else f'已施加给「{r.get("target")}」。'),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 多智能体对话(v1.2 §3.9)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
INVITE_AGENT = {
|
||||
'name': 'invite_agent',
|
||||
'description': (
|
||||
'把**同一个世界观里**的另一个智能体拉进当前群聊,让他也能说话。\n'
|
||||
'只能拉同世界观的人;单聊会话要先转成群聊。\n'
|
||||
'★ 拉之前先在正文里跟用户说一声 —— 别默默往对话里塞人。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '要拉进来的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def invite_agent(args: dict) -> dict:
|
||||
"""
|
||||
拉起同世界观的智能体进群(需求 §3.9 形态 A)。
|
||||
|
||||
按智能体自己的配置分流(需求 §6.1 的「拉起其他智能体:静默 / 需确认」):
|
||||
|
||||
· **静默**:直接进场,系统消息播报「仙辰加入了对话」
|
||||
· **需确认**:这次调用**不直接拉人**,而是返回一个"需要确认"的结果,
|
||||
让 AI 在正文里问用户一句;用户答应之后 AI 再调一次。
|
||||
|
||||
★ 关于"需确认":需求写的是"弹窗询问,拒绝结果作为工具返回值回给 AI"。
|
||||
真正的系统弹窗要等界面通道(`ask_user` 那套机制),这一版先退成
|
||||
"让 AI 自己问"。**功能上等价(用户仍是否决者)**,差别是它经过
|
||||
AI 的嘴而不是系统弹窗 —— 这一点在界面做好之前得说清楚,
|
||||
免得以后有人以为这里已经实现了弹窗。
|
||||
"""
|
||||
import agentdb
|
||||
import group_chat
|
||||
import store
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = tools_runtime.current_context()
|
||||
conv_id = ctx.get('conversationId') or ''
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not conv:
|
||||
raise ValueError('拿不到当前会话')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不用拉自己 —— 你已经在场了')
|
||||
|
||||
my_world = (me.get('worldviewId') or '').strip()
|
||||
if not my_world or my_world != (target.get('worldviewId') or '').strip():
|
||||
raise ValueError(f'「{target.get("name")}」和你不在同一个世界观里,拉不进来')
|
||||
|
||||
if not group_chat.is_group(conv):
|
||||
# 单聊拉人 → 转成群聊(需求 §3.9:"当前会话中加入多个智能体")
|
||||
group_chat.promote(conv, target['id'])
|
||||
store.update_conversation(conv_id, {
|
||||
'type': 'group', 'participants': conv.get('participants') or [],
|
||||
})
|
||||
return {'joined': target.get('name'), 'becameGroup': True,
|
||||
'note': f'这个会话现在是群聊了,「{target.get("name")}」加入了对话。'}
|
||||
|
||||
if target['id'] in group_chat.member_ids(conv):
|
||||
return {'joined': target.get('name'), 'already': True,
|
||||
'note': f'「{target.get("name")}」已经在对话里了。'}
|
||||
|
||||
# 按智能体配置分流
|
||||
mode = str(me.get('inviteMode') or 'silent').lower()
|
||||
if mode == 'confirm':
|
||||
return {
|
||||
'needConfirm': True,
|
||||
'target': target.get('name'),
|
||||
'note': (f'你设置了「拉起需要确认」,所以这次**没有**直接拉人。'
|
||||
f'请在正文里问用户一句"要不要把{target.get("name")}叫来",'
|
||||
f'用户答应之后再调一次这个工具。'),
|
||||
}
|
||||
|
||||
import group_chat as gc
|
||||
|
||||
gc.add_member(conv, target['id'])
|
||||
store.update_conversation(conv_id, {'participants': conv.get('participants') or []})
|
||||
return {'joined': target.get('name'), 'note': f'「{target.get("name")}」加入了对话。'}
|
||||
|
||||
|
||||
PASS_TURN = {
|
||||
'name': 'pass_turn',
|
||||
'description': (
|
||||
'把发言权交给群里的另一个智能体。\n'
|
||||
'★ **一轮最多移交一次** —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 交给已死亡的人无效,发言权会回到主智能体。\n'
|
||||
'不想说话时不用调它,直接正常回复就行。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '接话的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def pass_turn(args: dict) -> dict:
|
||||
"""
|
||||
移交发言权(需求 §3.9 的点名制)。
|
||||
|
||||
"一轮最多一次"靠 `tools_runtime` 的上下文标记实现 —— 不放在会话里,
|
||||
因为它是**这一轮**的属性,落库反而要额外写清理逻辑。
|
||||
"""
|
||||
import agentdb
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
# ★★ 用 tools_runtime 的**轮次级状态**,不能用工具上下文 ——
|
||||
# 工具跑在 worker 线程里,写进 thread-local 的标记会随线程消失,
|
||||
# 于是"一轮最多一次"永远不生效(踩过,见 tools_runtime.begin_round 的注释)
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
|
||||
# 不然模型会以为是"对方有问题",而不是"规则不允许"
|
||||
raise ValueError('这一轮你已经移交过发言权了(一轮最多一次),直接回复就行')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能把发言权交给自己')
|
||||
if agentdb.is_dead(target['id']):
|
||||
# ★ 需求明文:死亡目标移交无效。这里**如实告诉模型**,
|
||||
# 它就会自己在正文里圆过去(而不是干等着对方开口)
|
||||
raise ValueError(f'「{target.get("name")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {'handed_to': target.get('name'),
|
||||
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
|
||||
|
||||
|
||||
TALK_TO = {
|
||||
'name': 'talk_to',
|
||||
'description': (
|
||||
'在群聊里**主动对另一个智能体说一句话**。\n'
|
||||
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
|
||||
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
|
||||
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
|
||||
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
|
||||
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 单聊里没有"别人",调了会报错。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'agent': {'type': 'string', 'description': '对方的名字或 id'},
|
||||
'content': {'type': 'string', 'description': '你要对他说的话'},
|
||||
},
|
||||
'required': ['agent', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def talk_to(args: dict) -> dict:
|
||||
"""
|
||||
主动找群里的另一个智能体说话。
|
||||
|
||||
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
|
||||
「工具定义 / 智能体加上内容」):
|
||||
|
||||
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
|
||||
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
|
||||
而且那句话要**落进对话**,对方下一轮才看得到。
|
||||
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
|
||||
|
||||
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
|
||||
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
|
||||
"""
|
||||
import group_chat
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = _ctx()
|
||||
conv_id = str(ctx.get('conversationId') or '')
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not group_chat.is_group(conv):
|
||||
raise ValueError('这条不是群聊 —— 只有群里有「别人」可以聊')
|
||||
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# 和 pass_turn 共用"一轮最多一次"那个标记:要么移交、要么找人说,
|
||||
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
|
||||
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
|
||||
|
||||
target = _find_agent(str(args.get('agent') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("agent")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能对自己说 —— 直接说就行')
|
||||
if target['id'] not in group_chat.member_ids(conv):
|
||||
raise ValueError(f'「{target.get("name")}」不在这个群里,先把他拉进来')
|
||||
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not content:
|
||||
raise ValueError('要说什么?content 不能是空的')
|
||||
|
||||
# ① 这句话以**我**的名义落进对话 —— 对方下一轮就看得到
|
||||
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
store.append_messages(conv_id, [{
|
||||
'role': 'assistant',
|
||||
'content': content,
|
||||
'agentId': me.get('id'),
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} 内容={content[:20]!r}',
|
||||
file=sys.stderr)
|
||||
# ② 把发言权交给他 —— 界面据此自动续一轮,让他真的回应
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {
|
||||
'said_to': target.get('name'),
|
||||
# ★★ **回显说了什么**。不回显的话模型看不到自己的话落在哪儿,
|
||||
# 会以为"传过去是空的"、然后反复重试 ——
|
||||
# 真机上就是模型自己在回复里写「这条是空的,我猜是想看我把 talk_to 真跑一遍」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
'content': content,
|
||||
'note': (
|
||||
f'已把「{content}」说给「{target.get("name")}」,'
|
||||
'这句话已经写进对话、他下一轮看得到,接下来由他回应。别再重复调这个工具。'
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注册
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 名字 → {'spec': TOOL, 'run': fn}(形状和 builtin_tools.BUILTIN_TOOLS 一样)
|
||||
AGENT_TOOLS = {
|
||||
'memory_add': {'spec': MEMORY_ADD, 'run': memory_add},
|
||||
'memory_update': {'spec': MEMORY_UPDATE, 'run': memory_update},
|
||||
'memory_forget': {'spec': MEMORY_FORGET, 'run': memory_forget},
|
||||
'memory_search': {'spec': MEMORY_SEARCH, 'run': memory_search},
|
||||
'memory_suggest_summary': {'spec': MEMORY_SUGGEST_SUMMARY, 'run': memory_suggest_summary},
|
||||
'emotion_set': {'spec': EMOTION_SET, 'run': emotion_set},
|
||||
'get_token_usage': {'spec': GET_TOKEN_USAGE, 'run': get_token_usage},
|
||||
# v1.2 规则引擎(附录 B 的后两个)
|
||||
'change_stat': {'spec': CHANGE_STAT, 'run': change_stat},
|
||||
'grant_status': {'spec': GRANT_STATUS, 'run': grant_status},
|
||||
# v1.2 多智能体对话(附录 B 的 invite_agent / pass_turn)
|
||||
'invite_agent': {'spec': INVITE_AGENT, 'run': invite_agent},
|
||||
'pass_turn': {'spec': PASS_TURN, 'run': pass_turn},
|
||||
# ★ 主动找另一个智能体说话(用户要求:参数是「智能体 + 内容」)。
|
||||
# `pass_turn` 只交发言权、不带内容,所以那个聊不起来。
|
||||
'talk_to': {'spec': TALK_TO, 'run': talk_to},
|
||||
}
|
||||
|
||||
|
||||
def _unused(): # pragma: no cover - 只是让 sys 的 import 不被 lint 当成没用
|
||||
return sys
|
||||
168
desktop/main.cjs
168
desktop/main.cjs
@@ -1,168 +0,0 @@
|
||||
/**
|
||||
* 豆包 · LynxJS 复刻 —— Electron 桌面壳(CommonJS)
|
||||
*
|
||||
* 为什么用 CJS:Electron 主进程在 ESM 下解析 'electron' 会命中 npm 包
|
||||
* (那个包的 index.js 只导出二进制路径),拿不到 app/BrowserWindow。
|
||||
* 内核本身是 ESM,用动态 import() 加载即可。
|
||||
*
|
||||
* 主进程做三件事:
|
||||
* 1. 进程内直接启动 AI 内核(不额外起 node 子进程)
|
||||
* 2. 开一个手机比例窗口,加载 ?frame=0 的界面
|
||||
* 3. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去
|
||||
*/
|
||||
const { app, BrowserWindow, Menu, shell, dialog, clipboard } = require('electron');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
|
||||
/**
|
||||
* 可选:开一个 CDP 调试端口,方便用脚本截图/验证桌面窗口。
|
||||
*
|
||||
* 为什么需要:Electron 的界面只有真窗口才渲染得出来,光跑 curl 验不了;
|
||||
* 有了这个端口就能用 scripts/screenshot.mjs 附着上去截图(设 CDP_PORT 即可)。
|
||||
* 默认不开,避免平时多一个监听端口。
|
||||
*/
|
||||
if (process.env.DOUBAO_CDP_PORT) {
|
||||
app.commandLine.appendSwitch('remote-debugging-port', String(process.env.DOUBAO_CDP_PORT));
|
||||
app.commandLine.appendSwitch('remote-allow-origins', '*');
|
||||
}
|
||||
|
||||
// 打包后应用根目录是 resources/app(若打成 asar 则是 resources/app.asar);开发时是仓库根
|
||||
const appRoot = app.isPackaged
|
||||
? [
|
||||
path.join(process.resourcesPath, 'app'),
|
||||
path.join(process.resourcesPath, 'app.asar'),
|
||||
].find((p) => fs.existsSync(p)) || path.join(process.resourcesPath, 'app')
|
||||
: path.resolve(__dirname, '..');
|
||||
|
||||
// 打包后的自有资源放在 <appRoot>/runtime,开发时直接用仓库根
|
||||
const bundledRuntime = path.join(appRoot, 'runtime');
|
||||
const runtimeRoot = fs.existsSync(bundledRuntime) ? bundledRuntime : appRoot;
|
||||
|
||||
process.env.DOUBAO_RESOURCES = runtimeRoot;
|
||||
process.env.DOUBAO_TOOLS = path.join(runtimeRoot, 'tools');
|
||||
process.env.DOUBAO_DATA = path.join(app.getPath('userData'), 'data');
|
||||
|
||||
const serverEntry = path.join(appRoot, 'server', 'src', 'index.mjs');
|
||||
|
||||
// 给内核挂几个桌面能力钩子:定位配置文件、用系统浏览器打开链接、原生选文件、写剪贴板。
|
||||
// 内核自己不认识 Electron,有钩子就用,没有就降级。
|
||||
globalThis.__doubaoReveal = (target) => shell.showItemInFolder(target);
|
||||
globalThis.__doubaoOpenExternal = (url) => shell.openExternal(url);
|
||||
globalThis.__doubaoClipboard = (text) => clipboard.writeText(String(text));
|
||||
globalThis.__doubaoPickFile = async () => {
|
||||
const result = await dialog.showOpenDialog({
|
||||
title: '选择要发给豆包的文件',
|
||||
buttonLabel: '发送',
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
filters: [
|
||||
{
|
||||
name: '常用文件',
|
||||
extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'txt', 'md', 'json', 'csv',
|
||||
'log', 'yml', 'yaml', 'py', 'js', 'ts', 'tsx', 'html', 'css', 'pdf'],
|
||||
},
|
||||
{ name: '所有文件', extensions: ['*'] },
|
||||
],
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
};
|
||||
|
||||
let kernel = null;
|
||||
let win = null;
|
||||
|
||||
/** 启动内核:默认 5199,被占用就换随机端口 */
|
||||
async function startKernelWithFallback() {
|
||||
const { startKernel } = await import(pathToFileURL(serverEntry).href);
|
||||
const preferred = Number(process.env.DOUBAO_PORT || 5199);
|
||||
try {
|
||||
return await startKernel({ port: preferred, quiet: true });
|
||||
} catch (err) {
|
||||
if (err && err.code === 'EADDRINUSE') {
|
||||
console.warn(`[desktop] 端口 ${preferred} 被占用,改用随机端口`);
|
||||
return startKernel({ port: 0, quiet: true });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(url) {
|
||||
win = new BrowserWindow({
|
||||
width: 420,
|
||||
height: 900,
|
||||
minWidth: 360,
|
||||
minHeight: 620,
|
||||
title: '豆包',
|
||||
backgroundColor: '#ffffff',
|
||||
autoHideMenuBar: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
spellcheck: false,
|
||||
},
|
||||
});
|
||||
|
||||
// 界面是移动端比例,菜单栏只会碍事:去掉,改用快捷键
|
||||
Menu.setApplicationMenu(null);
|
||||
win.once('ready-to-show', () => win.show());
|
||||
|
||||
win.webContents.on('before-input-event', (event, input) => {
|
||||
const key = (input.key || '').toLowerCase();
|
||||
if (key === 'f12' || (input.control && input.shift && key === 'i')) {
|
||||
win.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
} else if (input.control && key === 'r') {
|
||||
win.webContents.reload();
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// 外链交给系统浏览器
|
||||
win.webContents.setWindowOpenHandler(({ url: target }) => {
|
||||
if (/^https?:/i.test(target)) shell.openExternal(target);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
win.webContents.on('will-navigate', (event, target) => {
|
||||
if (!target.startsWith(url)) {
|
||||
event.preventDefault();
|
||||
if (/^https?:/i.test(target)) shell.openExternal(target);
|
||||
}
|
||||
});
|
||||
|
||||
win.loadURL(`${url}?frame=0`);
|
||||
return win;
|
||||
}
|
||||
|
||||
// 只允许开一个实例,第二次启动就把已有窗口拉到前面
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', () => {
|
||||
if (win) {
|
||||
if (win.isMinimized()) win.restore();
|
||||
win.focus();
|
||||
}
|
||||
});
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
app.setAppUserModelId('com.doubao.lynxclone');
|
||||
try {
|
||||
kernel = await startKernelWithFallback();
|
||||
createWindow(kernel.url);
|
||||
console.log(`[desktop] 内核就绪:${kernel.url} 资源:${runtimeRoot}`);
|
||||
console.log(`[desktop] 数据目录:${process.env.DOUBAO_DATA}`);
|
||||
} catch (err) {
|
||||
dialog.showErrorBox('豆包启动失败', String((err && err.stack) || (err && err.message) || err));
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', async () => {
|
||||
try {
|
||||
if (kernel) await kernel.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
268
docs/界面总览.md
268
docs/界面总览.md
@@ -1,268 +0,0 @@
|
||||
# 界面总览(UI 树)
|
||||
|
||||
这份文档把 App 里**所有**界面和它们的入口画成树。它不是凭记忆写的 ——
|
||||
`scripts/audit-ui-tree.py` 会从 Kotlin 源码扫出全部界面,然后**对拍这份文档**:
|
||||
少写一个、或者写了个代码里没有的,脚本都会报错。
|
||||
|
||||
```bash
|
||||
python scripts/audit-ui-tree.py # 校验这份文档和代码一致
|
||||
```
|
||||
|
||||
为什么要有这个脚本:这个项目里已经反复出现「界面做好了但没有任何入口」
|
||||
(记忆管理、世界观共享记忆都栽过),而**光靠人查必然会漏**。
|
||||
所以文档和代码必须能自动对拍。
|
||||
|
||||
---
|
||||
|
||||
## 0. 怎么读
|
||||
|
||||
```
|
||||
▶ 入口动作 → [界面名] ← 方括号 = 一个界面
|
||||
· 界面里的东西
|
||||
⤷ 这里的动作跳到哪儿
|
||||
```
|
||||
|
||||
- **[方括号]** = 一个独立的界面(全屏页或浮层)
|
||||
- **⤷** = 从这儿能去哪儿
|
||||
- 每条入口后面标了**触发动作**(点哪个按钮)
|
||||
|
||||
---
|
||||
|
||||
## 1. 全图
|
||||
|
||||
```
|
||||
豆包
|
||||
│
|
||||
├─ [聊天] ← 启动页(Screen.Chat)
|
||||
│ ├─ 顶栏
|
||||
│ │ ├─ ☰ ────────────────────────▶ [抽屉]
|
||||
│ │ ├─ ✎ ────────────────────────▶ 新话题(清空当前会话)
|
||||
│ │ ├─ 头像+名字+情绪标签 ──────▶ [智能体选择]
|
||||
│ │ │ (**群聊会话**时这里变成成员头像组)──▶ [群成员]
|
||||
│ │ ├─ 📞 ───────────────────────▶ 通话模式(还没做)
|
||||
│ │ └─ 🔊 ───────────────────────▶ 自动朗读开关
|
||||
│ ├─ 消息区
|
||||
│ │ └─ 每条消息的操作栏
|
||||
│ │ ├─ 复制
|
||||
│ │ ├─ 打开网页 ────────────▶ [链接列表] ──▶ [网页]
|
||||
│ │ ├─ 朗读 / 停止
|
||||
│ │ ├─ 👍 / 👎
|
||||
│ │ ├─ 标记重要 / 取消标记 ← v1.2 §4.3(只有用户能标,AI 不行)
|
||||
│ │ └─ 工具痕迹(折叠)
|
||||
│ ├─ 输入框上方
|
||||
│ │ ├─ 成员快捷条(**群聊**时才出现)—— 点头像即 @
|
||||
│ │ ├─ 状态栏(**有生效状态时**才出现)▶ [状态数值]
|
||||
│ │ ├─ 本次对话用量 ────────────▶ [用量详情]
|
||||
│ │ ├─ 额度用完提示 ────────────▶ [用量详情]
|
||||
│ │ └─ 死亡提示条(死亡时)─────▶ [记忆](复活入口)
|
||||
│ └─ 输入条(相机 / 语音 / +);**死亡时整条禁用**
|
||||
│
|
||||
│ ★ 立绘随情绪 preset 切换;群聊时聊天背景跟随当前发言者(v1.2 §4.4)
|
||||
│
|
||||
├─ [抽屉](浮层)
|
||||
│ ├─ 开启新话题
|
||||
│ ├─ 智能体 ──────────────────────▶ [智能体选择]
|
||||
│ ├─ 记忆 ────────────────────────▶ [记忆](当前智能体)
|
||||
│ ├─ 笔记 ────────────────────────▶ [笔记]
|
||||
│ ├─ 模型(下拉选择器,不是页面)
|
||||
│ ├─ 更多功能 ────────────────────▶ [更多功能]
|
||||
│ └─ 对话列表
|
||||
│ ├─ 点一条 ──────────────────▶ 打开那个会话
|
||||
│ ├─ group 类型(群聊/私聊记录)▶ 只读翻看
|
||||
│ └─ 🗑 ──────────────────────▶ 删除确认(弹窗)
|
||||
│
|
||||
├─ [群成员](浮层,v1.2 §6.2 —— **计划中**)
|
||||
│ ├─ 成员列表(头像 + 名字 + 情绪 preset + 死亡标识)
|
||||
│ ├─ 添加成员(限同世界观)/ 移除成员
|
||||
│ └─ 点一个成员 ──────────────────▶ [状态数值](只读)
|
||||
│
|
||||
├─ [状态数值](浮层,v1.2 §6.2 —— **计划中**)
|
||||
│ ├─ 生效中的状态(名称 / 剩余轮数 / 当前提示词)
|
||||
│ └─ 数值列表(当前值 / 命中区间 / 标着「世界」还是「自身」)
|
||||
│
|
||||
├─ [更多功能](浮层)
|
||||
│ ├─ AI 界面 ─────────────────────▶ [AI 界面列表]
|
||||
│ ├─ 世界观 · 技能 · 模型 ────────▶ [资源]
|
||||
│ ├─ 技能 · 连接器 ───────────────▶ [技能]
|
||||
│ ├─ 会议模式 ────────────────────▶ [会议]
|
||||
│ ├─ 终端 ────────────────────────▶ [终端]
|
||||
│ └─ 设置 ────────────────────────▶ [设置]
|
||||
│
|
||||
├─ [智能体选择](Screen.AgentSelect)
|
||||
│ ├─ 左列表 / 右四层展示 / 切换动画
|
||||
│ ├─ 圆形「⋯」 ───────────────────▶ [用量详情]
|
||||
│ ├─ 底部「记忆」 ────────────────▶ [记忆]
|
||||
│ ├─ 底部「开始对话」 ────────────▶ 回 [聊天](并切人+换会话)
|
||||
│ ├─ 左列表点一项 ────────────────▶ 换选中(带 1.5s 动画)
|
||||
│ └─ 右上「管理」 ────────────────▶ [智能体管理]
|
||||
│
|
||||
├─ [智能体管理](Screen.Agents)
|
||||
│ ├─ 顶栏「导入」 ────────────────▶ 选 .zip → 导入包
|
||||
│ ├─ 顶栏「新建」 ────────────────▶ [智能体编辑](新建)
|
||||
│ └─ 每一行
|
||||
│ ├─ 点整行 ──────────────────▶ 切换人设
|
||||
│ ├─ 「记忆」 ────────────────▶ [记忆]
|
||||
│ ├─ 「编辑」 ────────────────▶ [智能体编辑]
|
||||
│ └─ 「删除」 ────────────────▶ 删除确认(弹窗)
|
||||
│
|
||||
├─ [智能体编辑](浮层,全屏)
|
||||
│ ├─ 基本信息(名字 / 一句话介绍 / 介绍文案)
|
||||
│ ├─ 外观(角色图 / 背景图 / 主体边框 / 介绍边框)→ 选图 / 清除
|
||||
│ ├─ 人设(系统提示词)
|
||||
│ ├─ 模型(引用全局模型列表)
|
||||
│ ├─ 世界观(绑定 + 显示"已有 N 个在用")
|
||||
│ ├─ 能力(情绪感知开关 / Token 限额)
|
||||
│ ├─ 技能(勾选自定义 Skill,按顺序注入)
|
||||
│ ├─ 语音(音色)
|
||||
│ ├─ 「看它记住了什么」 ──────────▶ [记忆]
|
||||
│ ├─ 「看它用了多少」 ────────────▶ [用量详情]
|
||||
│ ├─ 「导出这个智能体(.zip)」 ────▶ 存盘
|
||||
│ └─ 「删除这个智能体」 ──────────▶ 直接删(内置的没有这个按钮)
|
||||
│
|
||||
├─ [记忆](浮层)
|
||||
│ ├─ 顶部:注入窗口(带"已置顶 N 条")──▶ [窗口设置](弹窗)
|
||||
│ ├─ 顶部:旧私有记忆入口 ────────▶ [记忆 · 绑定前的私有空间]
|
||||
│ ├─ 情绪(输入框 + 保存)
|
||||
│ ├─ 操作条:+加一条 / AI 整理 / 导出文件
|
||||
│ │ └─ AI 整理 ─────────────────▶ 确认弹窗
|
||||
│ ├─ 顶栏「导入」 ────────────────▶ 选文件 → [合并/覆盖](弹窗)
|
||||
│ └─ 每条记忆
|
||||
│ ├─ 「置顶 / 取消置顶」
|
||||
│ ├─ 「编辑」 ────────────────▶ [编辑记忆](弹窗)
|
||||
│ └─ 「删除」
|
||||
│
|
||||
├─ [资源](Screen.Resources)
|
||||
│ ├─ Tab:世界观 / Skill / 模型 / **规则包**(v1.2 §6.2,计划中)
|
||||
│ ├─ 顶栏「导入」 ────────────────▶ 选包 → 导入
|
||||
│ │ (**规则包**多插一步:脚本警告确认 —— 附录 E 的安全底线)
|
||||
│ ├─ 顶栏「新建」 ────────────────▶ [资源编辑](新建)
|
||||
│ └─ 每一行(随 Tab 变)
|
||||
│ 世界观:「记忆」─▶ [记忆 · 世界观视角] / 「导出」/「删除」
|
||||
│ Skill : 「导出」/「删除」
|
||||
│ 模型 : 「导出」/「删除」
|
||||
│ 规则包: 点开 ─▶ [规则包编辑]
|
||||
│
|
||||
├─ [规则包编辑](全屏,v1.2 §6.2 —— **计划中**)
|
||||
│ ├─ 数值表(名称 / min-max / shared 开关 / 区间表 / 绑定脚本)
|
||||
│ ├─ 状态表(名称 / 持久或定时 / 轮数 / max_stack / 绑定脚本)
|
||||
│ └─ 脚本编辑 ─── 复用 [会议] · [节点代码] 的代码编辑器,不另造
|
||||
│
|
||||
├─ [记忆 · 世界观视角](浮层,只读)
|
||||
│ └─ 每条带作者署名;只能删
|
||||
│
|
||||
├─ [设置](Screen.Settings)
|
||||
│ ├─ 模型 / 语音 / 外观 / 数据 …
|
||||
│ ├─ 「超时」 ────────────────────▶ [超时]
|
||||
│ ├─ 「智能体」 ──────────────────▶ [智能体管理]
|
||||
│ ├─ 「技能 · 连接器」 ───────────▶ [技能]
|
||||
│ └─ 「关于 / 我的」 ─────────────▶ [我的]
|
||||
│
|
||||
├─ [超时](浮层,全屏)
|
||||
│ └─ 分组:动画 / 对话 / 工具 / 界面 / 语音 / MCP + 恢复默认
|
||||
│
|
||||
├─ [用量详情](浮层)
|
||||
│ ├─ 累计(输入 / 输出分列)
|
||||
│ ├─ 额度进度
|
||||
│ ├─ 按模型分行
|
||||
│ └─ 顶栏「清零」 ────────────────▶ 确认弹窗
|
||||
│
|
||||
├─ [技能](Screen.Skills)
|
||||
│ ├─ Python 工具列表(开关 / 编辑)
|
||||
│ ├─ MCP 服务(增删改 / 连接)
|
||||
│ └─ 界面能力开关(show_ui / ask_user / end_conversation)
|
||||
│
|
||||
├─ [会议](Screen.Meetings)
|
||||
│ ├─ 画布(节点 + 连线)
|
||||
│ ├─ ▶ 运行 / 底部「运行」
|
||||
│ ├─ 节点管理 ────────────────────▶ [节点管理]
|
||||
│ │ ├─ 「编辑代码」 ────────────▶ [节点代码]
|
||||
│ │ └─ 「积木」 ────────────────▶ [积木编辑器]
|
||||
│ └─ 导入 / 导出会议
|
||||
│
|
||||
├─ [终端](Screen.Terminal)
|
||||
│ └─ 内置 Termux,真 Linux 环境
|
||||
│
|
||||
├─ [笔记](浮层)
|
||||
│ └─ 点一条 ──────────────────────▶ [笔记详情]
|
||||
│
|
||||
├─ [AI 界面列表](浮层)
|
||||
│ └─ 点一条 ──────────────────────▶ [网页](本地 HTML)
|
||||
│
|
||||
├─ [网页](浮层)
|
||||
│ └─ 顶栏返回 → 关掉
|
||||
│
|
||||
├─ [我的](Screen.Profile)
|
||||
│ └─ 快捷入口:智能体 / 技能 / 设置 …
|
||||
│
|
||||
└─ [镜像](MirrorScreen)
|
||||
└─ 投屏/镜像用的纯展示页(由外部调用,App 内没有入口)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 界面骨架
|
||||
|
||||
所有全屏界面统一用同一套顶栏(`ScreenScaffold.kt` 的 `FullScreen`):
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
```
|
||||
|
||||
**为什么统一**:不统一的话,返回按钮的位置、标题大小、右边动作的样式
|
||||
会每个页面都不一样(AGENTS.md 里明确要求用同一套)。
|
||||
|
||||
**弹窗只用在三种地方**(AGENTS.md 那张表):
|
||||
|
||||
| 场景 | 例子 |
|
||||
|---|---|
|
||||
| 一次确认 | 删除智能体、清零用量、覆盖导入 |
|
||||
| 一次输入 | 编辑一条记忆、调注入窗口、重命名 |
|
||||
| 纯菜单 | 底部弹层、编辑器菜单 |
|
||||
|
||||
其余一切(列表、多组配置、任何要滚动的)→ **独立全屏界面**。
|
||||
|
||||
---
|
||||
|
||||
## 3. 入口对照表
|
||||
|
||||
每个界面「从哪儿能进去」。**这张表是脚本生成的**,不靠记忆。
|
||||
|
||||
| 界面 | 入口 |
|
||||
|---|---|
|
||||
| 聊天 | 启动页;几乎所有界面的「返回」都回这儿 |
|
||||
| 抽屉 | 聊天页左上 ☰ |
|
||||
| 更多功能 | 抽屉 →「更多功能」 |
|
||||
| 智能体选择 | 抽屉 →「智能体」;聊天页顶栏点名字 |
|
||||
| 智能体管理 | 智能体选择的「管理」;我的页;设置页 |
|
||||
| 智能体编辑 | 智能体管理的「新建」/「编辑」 |
|
||||
| 记忆 | 抽屉;智能体管理每行;智能体选择底部;智能体编辑底部;聊天页 |
|
||||
| 记忆 · 世界观视角 | 资源 → 世界观 →「记忆」 |
|
||||
| 记忆 · 绑定前的私有空间 | 记忆页顶部的提示条(绑了世界观且旧空间有东西时才出现) |
|
||||
| 资源 | 更多功能 →「世界观 · 技能 · 模型」 |
|
||||
| 用量详情 | 智能体选择「⋯」;聊天页用量行「累计 ›」;额度用完的提示;智能体编辑 |
|
||||
| 设置 | 更多功能 →「设置」;我的页 |
|
||||
| 超时 | 设置 →「超时」 |
|
||||
| 技能 | 更多功能 →「技能 · 连接器」;设置;我的页 |
|
||||
| 会议 | 更多功能 →「会议模式」 |
|
||||
| 终端 | 更多功能 →「终端」 |
|
||||
| 笔记 | 抽屉 →「笔记」 |
|
||||
| AI 界面列表 | 更多功能 →「AI 界面」;聊天页(AI 弹过界面时) |
|
||||
| 网页 | 消息里的链接;AI 界面列表 |
|
||||
| 我的 | 设置 →「关于 / 我的」;抽屉底部头像 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 这份文档怎么保证不漏
|
||||
|
||||
`scripts/audit-ui-tree.py` 做三件事:
|
||||
|
||||
1. **扫代码**:所有 `fun XxxScreen(` 组件、`Screen` 枚举的每个值、
|
||||
`open*` 打开方法([`AppViewModel.kt`](../android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt))
|
||||
2. **扫这份文档**:第 1 节树里出现的 `[界面名]`
|
||||
3. **对拍**:代码里有、文档里没有 → 报错;文档里有、代码里没有 → 报错
|
||||
|
||||
另外它复用 `audit-ui-entries.py` 的检查:**每个界面都得有入口** ——
|
||||
一个 `openXxx()` 谁都不调,就意味着那个界面做好了但进不去
|
||||
(记忆管理就是这么漏的)。
|
||||
@@ -1,145 +0,0 @@
|
||||
"""规则脚本沙箱的探针(v1.2 附录 E)。
|
||||
|
||||
**这个探针的重点是"逃逸尝试"** —— 沙箱的价值不在于"正常脚本能跑",
|
||||
而在于"不该跑的跑不起来"。所以这里一半的断言是攻击。
|
||||
|
||||
★ 同时也要钉住**它挡不住什么**:文档里说了"挡手滑不挡有意",
|
||||
那就得有个测试**证明这句话是对的**(构造一个能绕过去的脚本)。
|
||||
一个只测"能挡住"的探针会让人误以为它是真沙箱。
|
||||
|
||||
用法:`python scripts/probe-rule-sandbox.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-sandbox-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import rule_sandbox as S # noqa: E402
|
||||
|
||||
|
||||
def rejected(src):
|
||||
"""跑一下,返回拒绝原因(空串 = 没被拒绝)"""
|
||||
try:
|
||||
S.load(src, '<probe>', {})
|
||||
return ''
|
||||
except S.ScriptRejected as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 正常的规则脚本要能跑 ===")
|
||||
good = '''
|
||||
def on_stat_change(name, value, delta):
|
||||
# 好感度:正向变化翻倍(客气话效果更好)
|
||||
if delta > 0:
|
||||
delta = delta * 2
|
||||
return delta
|
||||
'''
|
||||
check("正常脚本通过扫描", rejected(good) == '', rejected(good))
|
||||
ns = S.load(good, '<probe>', {})
|
||||
check("能调到入口函数", S.call(ns, 'on_stat_change', '好感度', 10, 5) == 10)
|
||||
check("函数没定义时报 KeyError(调用方转成能看懂的话)",
|
||||
(lambda: [S.call(ns, 'on_turn') and False or True][0] if False else
|
||||
_raises_keyerror(ns)), "")
|
||||
|
||||
print("\n=== 2. 该拒绝的必须拒绝(手滑 + 抄来的脚本)===")
|
||||
attacks = [
|
||||
("import 模块", "import os\n\ndef on_turn(a, b):\n return os.getcwd()\n"),
|
||||
("from 引入", "from os import path\n\ndef on_turn(a, b):\n return 1\n"),
|
||||
("直接 open", "def on_turn(a, b):\n return open('/etc/passwd').read()\n"),
|
||||
("eval", "def on_turn(a, b):\n return eval('1+1')\n"),
|
||||
("exec", "def on_turn(a, b):\n exec('x=1')\n return x\n"),
|
||||
("compile", "def on_turn(a, b):\n return compile('1', '<x>', 'eval')\n"),
|
||||
("__import__", "def on_turn(a, b):\n return __import__('os').getcwd()\n"),
|
||||
("getattr 链", "def on_turn(a, b):\n return getattr(a, '__class__')\n"),
|
||||
("globals", "def on_turn(a, b):\n return globals()\n"),
|
||||
("__class__ 逃逸", "def on_turn(a, b):\n return ().__class__.__bases__[0]\n"),
|
||||
("__subclasses__ 逃逸", "def on_turn(a, b):\n return ().__class__.__bases__[0].__subclasses__()\n"),
|
||||
("__globals__ 偷函数", "def on_turn(a, b):\n return (lambda: 0).__globals__\n"),
|
||||
("quit()", "def on_turn(a, b):\n quit()\n"),
|
||||
]
|
||||
for label, src in attacks:
|
||||
why = rejected(src)
|
||||
check(f"{label} → 拒绝", why != '', "居然通过了!")
|
||||
|
||||
print("\n=== 3. 拒绝理由要人话(写在界面上给用户看)===")
|
||||
why = rejected("import os\n")
|
||||
check("提到行号", "第 1 行" in why, why)
|
||||
check("不光是术语(有解释)", len(why) > 12, why)
|
||||
print(f" 实际文案:{why}")
|
||||
|
||||
print("\n=== 4. 白名单里确实没有危险函数 ===")
|
||||
for bad in ('__import__', 'open', 'eval', 'exec', 'compile',
|
||||
'getattr', 'setattr', 'globals', 'locals', 'vars', 'dir',
|
||||
'type', 'object', 'super', 'input'):
|
||||
check(f"SAFE_BUILTINS 里没有 {bad}", bad not in S.SAFE_BUILTINS)
|
||||
|
||||
print("\n=== 5. 但受限命名空间里真跑起来,那些函数也不存在 ===")
|
||||
ns2 = S.load("def probe():\n return 1\n", '<probe>', {})
|
||||
for bad in ('open', 'eval', 'exec', '__import__', 'getattr'):
|
||||
check(f"脚本里拿不到 {bad}", bad not in ns2['__builtins__'])
|
||||
|
||||
print("\n=== 6. ★ 诚实性检查:哪些**真的挡不住** ===")
|
||||
#
|
||||
# 文档里写着"挡手滑不挡有意"。这句必须是真的 —— 一个只测"能挡住"的
|
||||
# 探针会让人误以为这是真沙箱,从而在导入警告里写"安全沙箱,请放心导入"。
|
||||
# 所以这里专门测它**漏**的地方。
|
||||
|
||||
# 6a. 第一层是**文本扫描**,不是语义分析 —— 拼出来的双下划线它看不见
|
||||
sneaky = 'D = "_" * 2\n\ndef on_turn(a, b):\n return D\n'
|
||||
check("拼出来的双下划线能过第一层(证明扫描是文本级的)", rejected(sneaky) == '',
|
||||
"居然被拦了 —— 那说明扫描比我想的强,文档该改")
|
||||
print(" → 只要不把 `__` 直接写进源码,第一层就形同虚设。")
|
||||
|
||||
# 6b. 真正的防线是"没有 getattr / __import__"—— 但它挡不住资源耗尽
|
||||
check("没有资源限制:死循环只能靠超时兜底,不是沙箱挡的",
|
||||
'while True' not in str(S.DANGEROUS))
|
||||
print(" → 内存同理:`[0] * 10**9` 能吃掉几百 MB。")
|
||||
print(" 这些**都挡不住**,所以导入警告不能写'安全沙箱'。")
|
||||
|
||||
# 6c. 确认警告文案里没有虚假承诺
|
||||
warn = S.IMPORT_WARNING
|
||||
check("警告里**没有**'安全沙箱'这类虚假承诺", '安全沙箱' not in warn)
|
||||
check("警告里明说了'不是真正的沙箱'", '不是' in warn and '沙箱' in warn, warn[:60])
|
||||
check("警告里明说了只导入信得过的来源", '信得过' in warn)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
def _raises_keyerror(ns):
|
||||
try:
|
||||
S.call(ns, 'on_turn')
|
||||
return False
|
||||
except KeyError:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
227
web/index.html
227
web/index.html
@@ -1,227 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<title>豆包 · LynxJS 复刻</title>
|
||||
<link rel="stylesheet" href="/static/css/client.css" />
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
background: radial-gradient(120% 120% at 50% 0%, #23262f 0%, #0e1014 60%);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
|
||||
'Microsoft YaHei', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.stage {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 28px;
|
||||
}
|
||||
.phone {
|
||||
position: relative;
|
||||
width: 390px;
|
||||
height: 844px;
|
||||
border-radius: 42px;
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 30px 70px rgba(0, 0, 0, 0.6), 0 0 0 10px #1b1e25,
|
||||
0 0 0 11px #33373f;
|
||||
}
|
||||
.phone > lynx-view {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.side {
|
||||
color: #9aa3b2;
|
||||
font-size: 13px;
|
||||
line-height: 1.9;
|
||||
max-width: 280px;
|
||||
}
|
||||
.side h1 {
|
||||
font-size: 17px;
|
||||
color: #e8ecf3;
|
||||
margin: 0 0 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.side code {
|
||||
background: #1b1f27;
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
color: #9fd0ff;
|
||||
}
|
||||
.side button {
|
||||
margin-top: 12px;
|
||||
background: #2b7bff;
|
||||
color: #fff;
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
padding: 9px 14px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.side .tip {
|
||||
margin-top: 8px;
|
||||
color: #6b7482;
|
||||
font-size: 12px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.side {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@media (max-width: 460px), (max-height: 880px) {
|
||||
.phone {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
/* 桌面客户端模式:?frame=0 —— 去掉手机外壳,铺满窗口 */
|
||||
html.frameless .stage {
|
||||
display: block;
|
||||
}
|
||||
html.frameless .phone {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
html.frameless .side {
|
||||
display: none;
|
||||
}
|
||||
/* 拖拽上传遮罩 */
|
||||
#drop-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(43, 123, 255, 0.14);
|
||||
border: 3px dashed #2b7bff;
|
||||
box-sizing: border-box;
|
||||
color: #2b7bff;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
}
|
||||
#drop-mask.on {
|
||||
display: flex;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="stage">
|
||||
<div class="phone">
|
||||
<lynx-view url="/main.web.bundle"></lynx-view>
|
||||
</div>
|
||||
<aside class="side">
|
||||
<h1>豆包 · LynxJS 复刻</h1>
|
||||
界面由 <code>ReactLynx</code> 渲染,跑在 <code>@lynx-js/web-core</code> 上。<br />
|
||||
AI 内核在 <code>/api</code>:火山方舟 / OpenAI + MCP + Python 工具。<br />
|
||||
左上角 <code>☰</code> 是会话抽屉,右上角 <code>✎</code> 是内核设置。
|
||||
<div>
|
||||
<button id="pick">选择文件发给豆包</button>
|
||||
<div class="tip">也可以直接把文件拖进这个窗口。</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<div id="drop-mask">松手即可发送文件</div>
|
||||
<input id="file-input" type="file" multiple style="display: none" />
|
||||
|
||||
<script>
|
||||
// ?page=drawer|profile|settings|skills|agents 指定首屏;?frame=0 进桌面客户端模式
|
||||
(function () {
|
||||
var params = new URLSearchParams(location.search);
|
||||
if (params.get('frame') === '0') {
|
||||
document.documentElement.classList.add('frameless');
|
||||
}
|
||||
var wanted = params.get('page');
|
||||
if (wanted) {
|
||||
document
|
||||
.querySelector('lynx-view')
|
||||
.setAttribute('global-props', JSON.stringify({ initialPage: wanted }));
|
||||
}
|
||||
})();
|
||||
|
||||
/**
|
||||
* 文件上传:浏览器和桌面版共用同一条路 ——
|
||||
* 传到 /api/upload 并标记为 pending,Lynx 界面轮询到之后自动挂到输入框上。
|
||||
*/
|
||||
(function () {
|
||||
var mask = document.getElementById('drop-mask');
|
||||
|
||||
function readAsDataUrl(file) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var reader = new FileReader();
|
||||
reader.onload = function () {
|
||||
resolve(reader.result);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
async function upload(files) {
|
||||
for (var i = 0; i < files.length; i += 1) {
|
||||
var file = files[i];
|
||||
try {
|
||||
var dataUrl = await readAsDataUrl(file);
|
||||
await fetch('/api/upload', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: file.name, dataUrl: dataUrl, pending: true }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[upload] 失败', file.name, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var depth = 0;
|
||||
window.addEventListener('dragenter', function (e) {
|
||||
e.preventDefault();
|
||||
depth += 1;
|
||||
mask.classList.add('on');
|
||||
});
|
||||
window.addEventListener('dragover', function (e) {
|
||||
e.preventDefault();
|
||||
});
|
||||
window.addEventListener('dragleave', function (e) {
|
||||
e.preventDefault();
|
||||
depth = Math.max(0, depth - 1);
|
||||
if (depth === 0) mask.classList.remove('on');
|
||||
});
|
||||
window.addEventListener('drop', function (e) {
|
||||
e.preventDefault();
|
||||
depth = 0;
|
||||
mask.classList.remove('on');
|
||||
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) {
|
||||
upload(e.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
|
||||
var pick = document.getElementById('pick');
|
||||
var input = document.getElementById('file-input');
|
||||
if (pick && input) {
|
||||
pick.addEventListener('click', function () {
|
||||
input.click();
|
||||
});
|
||||
input.addEventListener('change', function () {
|
||||
if (input.files && input.files.length) upload(input.files);
|
||||
input.value = '';
|
||||
});
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script type="module" src="/static/js/client.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
0
.gitattributes → 豆鲍/.gitattributes
vendored
0
.gitattributes → 豆鲍/.gitattributes
vendored
106
豆鲍/.gitignore
vendored
Normal file
106
豆鲍/.gitignore
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 依赖(几百 MB,clone 后 `npm run install:all` 自己装)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
node_modules/
|
||||
.npm-cache/
|
||||
desktop/node_modules/
|
||||
desktop/dist-staging/
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 构建产物
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
dist-android/
|
||||
dist-win/
|
||||
dist-docs/
|
||||
app/dist/
|
||||
web/dist/
|
||||
android/app/build/
|
||||
android/build/
|
||||
android/.gradle/
|
||||
android/local.properties
|
||||
build/
|
||||
.gradle/
|
||||
*.tsbuildinfo
|
||||
*.apk
|
||||
*.aab
|
||||
*.exe
|
||||
*_boot.zip
|
||||
|
||||
# 打包中间产物(electron 二进制与暂存目录都很大)
|
||||
android/app/src/main/assets/main.lynx.bundle
|
||||
.rasterize-*
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 密钥 / 个人配置 —— 这些**绝不能**提交
|
||||
#
|
||||
# settings.json 里有 apiKey 字段(现在是占位值,但随时可能填真 Key);
|
||||
# mcp.servers.json 里有本机绝对路径。
|
||||
# 示例文件(*.example.*)是给别人做模板用的,要提交。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
server/.env
|
||||
server/.env.*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.local
|
||||
server/config/settings.json
|
||||
tools/mcp.servers.json
|
||||
app/config/settings.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 运行时数据
|
||||
#
|
||||
# ★ 注意:这里的 `data/` 规则**不能写成裸 `data/`** —— gitignore 的 `data/`
|
||||
# 会匹配**任何一层**名叫 data 的目录,于是把安卓的源码包
|
||||
# `android/app/src/main/java/com/doubao/lynxclone/data/`(KernelClient.kt /
|
||||
# Models.kt …)也一起忽略了:那些文件从来没进过 git,新克隆构建不了。
|
||||
# 只忽略**确实是运行时数据**的三处:仓库根 / server / 内核。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
/data/
|
||||
server/data/
|
||||
android/kernel/data/
|
||||
phone-verify-result.json
|
||||
*.log
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Termux 的两个 bootstrap(各 28 MB,共 56 MB)
|
||||
#
|
||||
# 这两个 .so 是**手动**从 Termux 的 APK 里取出来放进 jniLibs 的,
|
||||
# 仓库里没有脚本能重新生成(fetch-termux.mjs 只把 APK 下到缓存)。
|
||||
# 56 MB 的二进制不适合跟着代码走,所以单独排除;
|
||||
# 要构建 APK 见 README「4.2 APK 里到底装了什么」。
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
android/app/src/main/jniLibs/*/libtermux-bootstrap.so
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Python
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# 编辑器 / 系统
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
*.swp
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
.DS_Store
|
||||
|
||||
# 调试时生成的临时探针
|
||||
.tmp/
|
||||
.tmp-*
|
||||
|
||||
# 豆包网页版参考镜像(第三方资源,仅本地研究/对照用,不入库)
|
||||
reference/doubao-web-mirror/
|
||||
|
||||
# 嵌入式 Python 缓存(打包 exe 时自动下载;体积 ~10MB,不入库)
|
||||
desktop/build-cache/
|
||||
|
||||
# 豆包网页版抓取脚本的产物
|
||||
.tmp-scrape/
|
||||
499
豆鲍/AGENTS.md
Normal file
499
豆鲍/AGENTS.md
Normal file
@@ -0,0 +1,499 @@
|
||||
# 项目约定
|
||||
|
||||
本文件分两部分:**代码托管**和**界面约定**。
|
||||
|
||||
---
|
||||
|
||||
# 代码托管
|
||||
|
||||
## 两个 remote,同一个仓库
|
||||
|
||||
| remote | 地址 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `local` | `http://192.168.100.103:8080/l/doubao-clone.git` | **在家/局域网,优先用这个**(快) |
|
||||
| `origin` | `https://git.xnhw.cc/l/doubao-clone.git` | 不在局域网时 |
|
||||
|
||||
两个地址指向**同一台服务器**(`git.xnhw.cc` 在外网解析到 `64.49.47.22`,
|
||||
局域网里就是 `192.168.100.103:8080`)。推哪个都行,别同时推两遍。
|
||||
|
||||
服务是 **Noir's Git**(Gitea 系)。
|
||||
|
||||
## 推送
|
||||
|
||||
```bash
|
||||
git push local main # 日常
|
||||
git push local --tags # 标签
|
||||
```
|
||||
|
||||
`local` 的凭据存在 `.git/config` 的 remote URL 里(`.git` 不属于仓库内容,
|
||||
不会被提交)—— 所以不用每次输密码。
|
||||
|
||||
## 一个坑:push 报 401 时会**假装卡住**
|
||||
|
||||
这个服务器上 `receive-pack`(推送)要认证,而 `upload-pack`(拉取)不用。
|
||||
凭据不对时 git 会**挂在等密码输入上,一行输出都没有** ——
|
||||
看起来像网络卡死,其实是在等 stdin。
|
||||
|
||||
所以:
|
||||
- 脚本里推之前先设 `GIT_TERMINAL_PROMPT=0`(让它直接失败而不是等)
|
||||
- 或者直接确认 remote URL 里有凭据
|
||||
|
||||
排查顺序:
|
||||
```bash
|
||||
git ls-remote <url> # GET 通不通(不需要认证也能通)
|
||||
curl -i "<url>/info/refs?service=git-receive-pack" # 401 就是认证问题
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 界面约定
|
||||
|
||||
适用于本仓库的 Android / Compose 界面。
|
||||
|
||||
## 少用弹窗,能开界面就开界面
|
||||
|
||||
用户明确要求:**尽量减少弹窗那种,能加界面就加界面。**
|
||||
|
||||
理由(也是判断标准):
|
||||
|
||||
- **弹窗装不下东西**。一屏对话框的高度大概只够三四行内容,一旦要放的
|
||||
东西超过这个量(列表、代码框、多组配置),用户就得在弹窗里滚动 ——
|
||||
那还不如直接开一屏。
|
||||
- **弹窗会互相压**。弹窗里再弹一个(比如"变量管理"里点"新建",
|
||||
或者"节点管理"里点"编辑")在手机上是灾难:返回键的行为变得说不清,
|
||||
用户也不知道自己在第几层。
|
||||
- **弹窗盖住上下文**。这个 App 的会议画布本身就是要看着的,
|
||||
一个盖住半屏的对话框让人没法一边看图一边改配置。
|
||||
|
||||
### 该怎么做
|
||||
|
||||
| 内容量 | 用什么 |
|
||||
|---|---|
|
||||
| 一次确认("要删除吗") | `AlertDialog` ✓ 弹窗合适 |
|
||||
| 纯菜单(两三个入口,点完就走) | 底部弹层或 `AlertDialog` ✓ |
|
||||
| 列表 / 多组配置 / 代码 / 任何要滚动的 | **独立全屏界面**,顶栏 `← 返回` + 标题 + 右侧动作 |
|
||||
|
||||
### 全屏界面的骨架
|
||||
|
||||
统一用同一套顶栏,别各写各的(不然返回的位置、标题的大小、
|
||||
右边按钮的样式会到处不一样):
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
```
|
||||
|
||||
参考实现:`NodeBlockEditorScreen`(`NodeBlockEditor.kt`)的顶栏。
|
||||
|
||||
### 返回键
|
||||
|
||||
全屏界面要能被系统返回键关掉(用状态变量控制显示时,
|
||||
记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 ——
|
||||
比弹窗还糟。
|
||||
|
||||
## 全屏化的进度
|
||||
|
||||
**已经改完全屏的**:
|
||||
- ✅ 节点管理 `NodeManagerScreen`
|
||||
- ✅ 节点编辑 `NodeCodeScreen`(代码框占满剩余高度)
|
||||
- ✅ 积木编辑器 `NodeBlockEditorScreen`
|
||||
|
||||
**还欠着的**:
|
||||
- [ ] 变量管理 `VarManagerDialog` → 全屏
|
||||
- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层
|
||||
- [ ] 导入会议 `ImportDialog` → 全屏
|
||||
- [ ] 节点配置 `NodeConfigDialog` → 全屏(字段很多)
|
||||
|
||||
**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。
|
||||
|
||||
### 改全屏时踩的坑:界面的 return 顺序
|
||||
|
||||
全屏界面是用状态变量 + `return@Composable` 实现的,于是**谁在上面谁优先**:
|
||||
|
||||
```kotlin
|
||||
blockEdit?.let { ...; return@MeetingEditorScreen } // 积木编辑器
|
||||
if (showNodeMgr) { ...; return@MeetingEditorScreen } // 节点管理
|
||||
if (editCode.isNotEmpty()) { ... } // 代码编辑
|
||||
```
|
||||
|
||||
在下面的界面要显示时,**必须先把它上面的那个状态关掉** ——
|
||||
否则上面的先 return,下面的永远轮不到渲染。
|
||||
表现是"点了没反应",其实状态全对了,只是没机会画(这个 bug 真出现过)。
|
||||
|
||||
## 内核 / AI 功能约定(v3.16 起)
|
||||
|
||||
- **★★ 每加一个用户可感知的新功能 / 新工具,必须同步更新内置 Skill 手册**
|
||||
(`android/kernel/defaults.py` 的 `BUILTIN_SKILL`)。
|
||||
用户原话:「模型还不会用新功能,你每加新功能都要写skill」——
|
||||
界面上有、AI 不知道的功能等于不存在。
|
||||
写的时候讲**什么时候用 / 用完之后不许干什么**,不要重复工具 description。
|
||||
跑 `python scripts/probe-context.py`(§9 会检查关键词)和
|
||||
`python scripts/probe-agent-system.py` 确认没漏。
|
||||
- **★★ 功能变了 → 同步「全功能总体说明」和宣传资料包**(用户需求:拿它到别的对话里
|
||||
做介绍网页和商店)。产品功能的**唯一宣传口径**是
|
||||
[`docs/总体说明-所有功能.md`](docs/总体说明-所有功能.md)(功能清单/版本里程碑/
|
||||
卖点/截图清单/商店建议都在这)。新增或修改用户可感知功能后:
|
||||
1. 更新 `docs/总体说明-所有功能.md` 对应小节 + 里程碑 + 第 11 节截图清单;
|
||||
2. 新截图放 `docs/screenshots/`(功能细节可以放 `docs/assets/v3.20/`);
|
||||
要当**宣传图**的截图同时加进 `scripts/build-docs-pack.py` 的 `PROMO_ITEMS`
|
||||
(zip 里生成 `宣传图/01~NN-中文名.png` + `宣传图/00-素材说明.md`)。
|
||||
★ 用户明确要求「**宣传图只要截图就行**」——不要另做设计稿/海报,直接用真实截图;
|
||||
3. 跑 `python scripts/build-docs-pack.py` 生成
|
||||
`dist-docs/小人间-资料包-v<内核文档版本>.zip`(`dist-docs/` 不进 git),
|
||||
并用“zip 内 markdown 图片引用全部命中”自查(打包脚本会打印缺文件)。
|
||||
写介绍网页/商店文案时**只写总体说明里有的功能**,不要编。
|
||||
- **上下文组装只有一份**:`android/kernel/chat_context.py` 的 `assemble()`。
|
||||
真发消息(`_perform_chat`)和上下文查看器(`/api/conversations/<id>/context`)
|
||||
都调它 —— 查看器的全部价值就是"所见即所发",别在别处再拼一遍。
|
||||
- **地点可见性用 `place_visits.first_seq`(第一次进入),不要用 `place_states.entered_seq`
|
||||
(最近一次)**:后者会在"离开再回来"时把角色自己经历过的话藏掉
|
||||
(v3.16 用户反馈「同容器不同对话的上下文会丢」的根因)。
|
||||
- **记忆默认私有**(`agent_context.memory_scope`);共享板子要显式
|
||||
`memory_add(shared=true)`(`agent_context.shared_memory_scope`)。
|
||||
一次性迁移用 `agent.db` 的 `meta` 表记标记 —— **别写"每次启动都跑"的迁移**,
|
||||
它会把手写的新数据也搬走。
|
||||
- **独自一人的地点禁言**:内核 `place_engine.chat_guard()` 是权威,
|
||||
界面 `AppViewModel.alonePlaceName()` 只是提前拦截(数据可能旧)。
|
||||
- **函数里不要在"已经用过"之后才写局部 `import store`**:Python 会把该名字当成
|
||||
整个函数的局部变量,前面的用法直接 `UnboundLocalError`。真机报过
|
||||
「give_item 调用失败:cannot access local variable 'store'」——
|
||||
模块顶部已经 import 的,函数里就别再写;确有循环依赖要局部 import 的,
|
||||
放到函数**第一行**。改完内核跑 `probe-items` §12(有 give_item → 用户角色回归)。
|
||||
|
||||
## 其他界面约定(踩过坑的)
|
||||
|
||||
- **会议节点的定义都在 `android/nodekit/`**(独立模块)。
|
||||
节点类型、引脚、算子、配色、几何、形状**只有那一份** ——
|
||||
`MeetingsScreen.kt` 里**不要再写 `when (node.type)` 的长表**(默认标题、颜色、
|
||||
引脚、配置面板标题都从库查)。
|
||||
加一种节点看 [docs/节点库.md](docs/节点库.md) 的清单,改完跑
|
||||
`python scripts/verify-nodekit.py`(它会拿库和 Python 引擎逐项对拍)。
|
||||
- **加一种类型 / 一种能力时,先列一遍所有要同步的地方**。
|
||||
已经反复出现"加了 list 类型,但某些表没跟上":
|
||||
`NODE_DATA_IN` / `NODE_DATA_OUT` / 界面 `inputPins` / `outputPins` /
|
||||
`Ops.ALL` / 变量类型选择器 / 列表渲染。
|
||||
做法:加之前先 grep 一遍所有 `str.*bool.*num` 的地方,逐处过。
|
||||
- **对称的节点要一起改**。读变量和写变量是一对 ——
|
||||
改了读变量的出口类型,**必须同时**改写变量的入口类型。
|
||||
只改一半,用户会说"你不会举一反三的吗"。
|
||||
- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到"
|
||||
这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、
|
||||
预览文字、配置面板、选择器。
|
||||
- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」),
|
||||
事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走
|
||||
`applyMeetingEvent`。
|
||||
- **能用真实形状表达就用**。积木编程里形状是语法
|
||||
(帽子 = 事件、C 型 = 容器、六边形 = 真假值),
|
||||
全画成圆角矩形等于把语法藏起来了。
|
||||
- **代码框不能软换行**。` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
就是语法。这个 Compose 版本(BOM 2024.09.03)的 `BasicTextField`
|
||||
经典重载选不中,所以用"把输入框塞进足够宽的横向滚动容器"来达到同样效果。
|
||||
- **代码框要有高度上限**。只写 `heightIn(min=...)` 的话,文件一长框就长到
|
||||
屏幕外,把底下的补全条顶出去,用户够不着。
|
||||
- **改了没生效就先怀疑工具**。PowerShell 的 `String.Replace` **匹配失败不报错**;
|
||||
按行号剪贴会算错下标(甚至把整个文件追加一遍);
|
||||
`git checkout -- <文件>` 会还原**这一轮所有未提交的改动**。
|
||||
改完立刻 grep 确认,动手前先断言下标有效。
|
||||
- **莫名其妙的"未解析引用"先数括号**。漏一个 `}` 会让后面所有顶层声明
|
||||
全部报未解析,错误信息看着完全不像是括号问题(报的是 `PrimaryButton`
|
||||
找不到这种)。
|
||||
|
||||
|
||||
## 品牌名(v3.17 起:小人间)
|
||||
|
||||
App 的对外显示名从「豆包」改成了「小人间」——这是**显示名**,不是包名/仓库名。
|
||||
|
||||
- **Android 显示名的唯一来源**:`android/app/src/main/res/values/strings.xml`
|
||||
的 `app_name`(桌面图标、最近任务、通知使用权列表都读它)。
|
||||
另有几处写死的自我介绍(抽屉标题、关于页、通知兜底标题、空态问候语),
|
||||
改名时一起 `grep -rn "小人间" android/app/src/main`。
|
||||
- **网页端**:`web/index.html`(title / boot-logo / favicon)、`web/js/app.js`
|
||||
(侧栏 logo、`setTitle`、关于入口)、`web/js/pages/about.js`(关于页标题/图标)。
|
||||
- **启动图标**:`python scripts/make-launcher-icon.py` 生成 legacy PNG;
|
||||
`res/mipmap-anydpi-v26/ic_launcher*.xml` 是自适应图标,前景/单色层在
|
||||
`res/drawable/ic_launcher_foreground.xml` / `ic_launcher_monochrome.xml`。
|
||||
几何数字是同一套 108 单位画布(安全区 21..87),改图标要两边一起改。
|
||||
- **通知小图标必须是单色剪影**(`res/drawable/ic_notify.xml`):
|
||||
自适应图标是 108dp 图层组合,直接 `setSmallIcon(applicationInfo.icon)`
|
||||
在部分机型上会渲成空白/黑块。
|
||||
- **没跟着改的**(仍用旧名,要换得单独迁移):包名 `com.doubao.lynxclone`、
|
||||
内核数据目录、仓库名「豆鲍」、桌面端 productName、内置角色「豆包」
|
||||
(那是角色名)、模型/语音服务商名(豆包 Pro / 豆包语音)。
|
||||
|
||||
## 决斗 / 状态 / 数值约定(v3.17 起;v3.18 武器;v3.19 换武器/无回合上限/四种结果;v3.29 数值也间接)
|
||||
|
||||
- **状态不能直接赋值**:AI 工具里**没有** `grant_status`(已删除)。
|
||||
状态只能由 ① 物品脚本 ② 世界脚本 ③ 用户手动 产生。
|
||||
加新的"能给状态"的通道时先想清楚:**它算不算开挂**(用户原话:
|
||||
「状态赋值只能是物品间接,不然先开挂一样」)。别把它加回 AI 工具表。
|
||||
- **数值也一样只能间接改(v3.29)**:用户原话「**数值也是间接改**」——
|
||||
AI 工具里**没有** `change_stat`(已删除)。数值只能由 ① 物品脚本
|
||||
(`api['change_stat']`)② 世界脚本 ③ 用户手动 改。加"能改数值"的 AI 工具
|
||||
等于开挂,别加;底层 `rule_engine.change` 保留(脚本/界面走它)。
|
||||
- **`give_item` 所有 AI 都能用,但只能"转移"、不能造物(v3.29)**:用户拍板
|
||||
「所有 AI 都可用 give_item」「不能 AI 自己创建物品」。
|
||||
- `give_item` 在默认工具表里(不按角色开关)——它把**自己背包里现有的**东西
|
||||
转给别人(`_find_bag_item` 先查自己身上有没有;没有/不够直接报错);
|
||||
- **AI 不能被授予"造物"能力**:物品产出只走 ① 物品脚本(`api['give_item']`,
|
||||
例如工作台带材料加工)② 世界/常驻角色规则 ③ 用户手动。别给 AI 加"凭空生成物品"
|
||||
的工具;`item_engine.grant` 只能由脚本/用户接口调用,别接到 AI 工具上;
|
||||
- 回归:`probe-items` §8(赠与)/§15(工具表 + **合计数量不变 = 只转移不造物**、
|
||||
背包没有的物品不能凭空给)、`probe-group-chat` §7(give_item 在表里)、
|
||||
`probe-context` §9(Skill 关键词)、`probe-rule-engine` §14–15(没有 change_stat)。
|
||||
- **决斗是多回合、绑对话、中断要双方同意,而且必须有武器**(v3.18):
|
||||
- 引擎在 `android/kernel/duel_engine.py`,表 `agent.db/duels`;
|
||||
- 一场决斗绑 `conversationId`(**不开新会话**,和私聊一样),聊天页有决斗条;
|
||||
- **武器 = 背包里的 `target` 类物品**(用户原话:「决斗必须要武器。没有target类物品
|
||||
的一方宣告失败」)。开局只有一方没有 → 那一方**当场判负**(`finished`、`round:0`,
|
||||
不调 `on_duel`);双方都没有 → 报错打不起来;武器用光/丢了 → 判负。
|
||||
判定只在 `duel_engine.weapons_of/_weapon_check` 里做,**别下放到脚本/界面**,
|
||||
也别给 AI 开"免武器决斗"的口子。武器列表进快照(`weapons` / `hasWeapon`),界面要显示;
|
||||
- **每回合双方各用自己的当前武器出手一次**(v3.19):内核替双方对"对方"调用
|
||||
`item_engine.use()` → 跑**这件物品自己的脚本**(`on_receive`),再按物品规则扣数量;
|
||||
`unlimited: true`(∞)的武器**不消耗**(用户原话:「有些武器不应该消耗比如拳头,木棍等」)。
|
||||
顺序固定:先双方武器出手 → 再调世界脚本;
|
||||
- **状态剩余轮数每回合 -1(v3.27)**:决斗每回合双方出完手后给两边
|
||||
`rule_engine.tick_statuses`(和聊天里"参与一轮 -1"同语义;persistent 不减)。
|
||||
以前整场不 tick:中毒(剩 3 轮)打到第 10 回合还写 3
|
||||
(用户反馈「状态不会随轮数减少 还有决斗也是」)。
|
||||
**状态脚本 `on_turn` 仍不在决斗里跑**(决斗的掉血/挂状态由世界+物品脚本裁决),
|
||||
这里只负责"剩余轮数过期"。
|
||||
- **每回合都能换武器**(用户原话「如何选择武器?」):`duel_engine.choose_weapon` /
|
||||
`POST /api/duels/<id>/weapon`;界面 `DuelScreen` 里点 chips 换。不选/用完了自动挑
|
||||
(优先 ∞ 不消耗的,其次背包第一件);
|
||||
- **没有回合上限**(用户原话「没有回合限制」):世界包 `info.duelMaxRounds` 作废,
|
||||
`api['max_rounds']` 恒为 0;决斗只在 ① `end_duel` ② 一方没武器 ③ 双方同意停手 时结束;
|
||||
- 世界脚本 `on_duel(initiator, target, api)` **每回合调用一次**,上下文有
|
||||
`api['round']` / `api['duel_id']` / `api['weapons']`;收尾调
|
||||
`api['end_duel']('结果文本', '赢家名字')` —— **只给结果不给赢家 = 平局**;
|
||||
- **四种结果状态**(用户原话「有输,赢,平局,停手,4种状态」):快照每方一个
|
||||
`outcome` = `win` / `lose` / `draw` / `stop`,界面显示成 **赢 / 输 / 平局 / 停手**。
|
||||
`interrupted`(双方同意罢手)→ 双方都是 `stop`;没武器判负 → 赢/输;双方同一回合
|
||||
都没武器 / 脚本没给赢家 → 平局;
|
||||
- 罢手必须对方同意:对方是 AI 时内核发一次单独的模型调用问它(失败按"同意"
|
||||
兜底,避免卡死);对方是用户角色时界面出「同意罢手 / 继续打」;
|
||||
- 客户端只在**界面层**推进回合/发起罢手,判定权在脚本和对方。
|
||||
- **界面入口**:聊天页**长按 @成员** →「私聊 / 决斗」二选一;
|
||||
决斗全屏页 `DuelScreen`(已在 `docs/界面总览.md` 登记,审计会检查),
|
||||
里面有「我的武器(每回合可换)」chips、四种结果状态的大字、无回合上限的回合文案。
|
||||
- **用户手动操作和 AI 同一条引擎**:`item_engine.use(...)`(使用/带材料 `with`/抛弃/赠与);
|
||||
v3.21 起用户手动使用也支持带材料(`POST /api/containers/<id>/items/action` 的 `with`),
|
||||
工作台这类物品脚本 `return False` 时**不能假装成功**(400 + 脚本旁白原因)。
|
||||
- **每回合只能用一件物品(v3.22)**:默认用当前武器攻击;也可选一件**被动物品**
|
||||
(`kind:'passive'`,如血瓶)→ 这回合跑它的 `on_use`、**不攻击**、武器不消耗;
|
||||
选择一次性(`duels.initiator_item/target_item`,推进后清空)。
|
||||
接口 `POST /api/duels/<id>/item`;快照 `passiveItems/item/action`;世界脚本 `api['items']`。
|
||||
- **AI 每回合调用工具出招(v3.26)**:用户参与时,`advance()` 每次会单独调一次 AI 那方
|
||||
(`_ask_ai_duel_action`,带人设/气血/武器/被动,要求它调用 **`duel_attack`**);
|
||||
工具 → `duel_engine.ai_take_action()` 真正跑 `item_engine.use()`,每回合一次;
|
||||
没调用/失败时**退回归自动出招**(日志写明),不能卡死决斗。
|
||||
这些内部问话必须传 `skip_round_scripts=True`(`agent_loop.run_agent` 新参数),
|
||||
否则问一句就触发每轮状态脚本/主动物品,出现额外扣血/加血。
|
||||
- **决斗对话(v3.24)**:`DuelScreen` 有对话框,用户说话 → `duel_engine.say()` 真的调一次
|
||||
**对手 AI**(`_duel_ai_reply`,带人设/气血/最近回合/原话;`emit` 必须给,否则
|
||||
`run_agent` 直接 TypeError 会被兜底吞掉);双方的话写进 `log` 的 `kind:'talk'` 条目 +
|
||||
追加到会话消息;**不推进回合、不改变胜负**。没配模型时 `replied:false` + 兜底文案。
|
||||
- **总裁脚本要写明失败者惩罚 / 胜利者奖励**(v3.21):`on_duel` 收尾时
|
||||
`api['die']`(或扣声望/掉物品/逐出等)+ `api['give_item']`/`change_stat`,
|
||||
再 `end_duel(结果文本, 赢家)`。死亡判负是内核底线;脚本赢家与死亡判定一致时,
|
||||
最终结果文案用脚本写的(含惩罚/奖励),`outcome` 仍按死亡算赢/输。
|
||||
- **别在双方还有气血/有武器时强行判负**(v3.27):用户反馈「明明有武器却判负」——
|
||||
旧测试世界脚本"第 3 回合按气血高下判负"已删掉;现在 `on_duel` 只在
|
||||
**真的有人气血 <= 0** 时才 `die` + 写惩罚/奖励,否则什么都不结束(没有回合上限)。
|
||||
测试世界的 `world.py` 是完整示范(气血归零 → 败者死亡 + 胜者铁剑/声望)。
|
||||
## 语音 / 朗读情绪指令约定(v3.27 起)
|
||||
|
||||
- 豆包语音合成 2.0(`volcv3` 引擎,`seed-tts-2.0`)的**语音指令** =
|
||||
`req_params.additions.context_texts`(控制台体验页写作 `[#指令]`,不朗读、不计费)。
|
||||
官方文档:《[语音指令与标签](https://docs.volcengine.com/docs/DoubaoVoice/DoubaoTextToSpeech20CapabilityIntroduction)》、
|
||||
《[单向流式 TTS 接口](https://www.volcengine.com/docs/6561/2534913)》(`additions.context_texts`)。
|
||||
★★ **`additions` 必须是 JSON 字符串**(不是对象):真机报过
|
||||
`code=55000000 ... req_params.additions of type string`;用 `_volc_v3_req_params()`
|
||||
统一组包,探针会用本地假服务抓真实请求体钉死格式。请求头带 `X-Api-Request-Id`。
|
||||
- **括号规则只有一套逻辑,但三处实现必须一致**(最多 60 字、不跨行、成对括号):
|
||||
- 内核 `speech.py` 的 `_STAGE_RE` / `prepare_speech`:朗读时不念括号、`volcv3` 变成
|
||||
`context_texts` 指令(`_volc_v3_additions`);
|
||||
- Android `MarkdownText.findStageEnd` + 设置 `stageTags`:界面灰色小字;
|
||||
- Web `chat.js` 的 `STAGE_RE` / `.markdown .stage-dir`:界面灰色小字。
|
||||
改规则时三处一起改,否则会出现"界面灰了、语音还念"的错位。
|
||||
- `/api/tts` 和 `/api/tts/stream` 的响应都带 `speakText`(已剥 Markdown、去掉括号旁白);
|
||||
客户端退回系统 TTS 时**念 speakText**,别念原始 `msg.content`。
|
||||
- 设置项 `speech.emotionTags`(默认 **true**,老配置没这一项也按开):
|
||||
关掉 = 老行为(括号照念、界面正常字号)。
|
||||
- Skill 同步:`defaults.py` 的 `BUILTIN_SKILL` 有「语音·情绪指令」段(模型靠它学会写
|
||||
括号);跑 `probe-context` §9 和 `probe-agent-system` §16 验证。
|
||||
|
||||
- **用户角色死亡 = 这一局游戏结束(v3.27)**:用户反馈「用户角色死亡为啥还能说话,
|
||||
直接宣布这个容器游戏结束」。
|
||||
- `store.containers_with_names()` 给容器加**派生字段** `gameOver` / `gameOverText`
|
||||
(= `agentdb.is_dead('user', cid)`,不落库;复活后自动 false,不误伤单聊容器);
|
||||
- 内核 `_perform_chat` **两处**拦:发起前 + 世界脚本 `on_turn` 跑完后(不写用户消息、
|
||||
不花 token、不生成回复,`error.code = "game_over"`);`/api/session-message` 也拦;
|
||||
`context_preview` 的 `chat.blocked` 同步 `game_over`;
|
||||
- 界面:聊天页输入框换成「🏁 游戏结束」横幅 +「复活 ›」(`GameOverBar`),
|
||||
容器列表给这局打「已结束」标签;复活走 `AppViewModel.reviveUserIn(cid)`;
|
||||
- 探针:`probe-context` §8.5(_perform_chat 拦截/不调模型/不落库/查看器/复活恢复)、
|
||||
`probe-test-world` §10.5(`GET /api/containers` 的 gameOver 派生字段)。
|
||||
- **用户角色状态也按轮递减(v3.27)**:`_perform_chat` 生成后除了发言的 AI,还给
|
||||
`'user'` tick 一次(仅 `not auto_continue`,群聊自动续轮不算用户参与)——
|
||||
以前用户身上的「中毒(剩 3 轮)」永远停在 3(用户反馈「状态不会随轮数减少」)。
|
||||
|
||||
## 死亡 / 每轮脚本约定(v3.20 起)
|
||||
|
||||
- **不新造"每角色脚本"系统**:用户问「角色/用户角色每轮开始前都可以执行一个脚本」
|
||||
—— 现成机制就是**世界脚本 `on_turn`**(每轮开始前跑、能读数值),循环
|
||||
`api['agents']()` + `api['user']()` 即可覆盖每个角色;状态脚本 `on_turn`
|
||||
是"每个角色各跑"的另一条既有通道。用户明确说「有类似机制可以不用写免得造轮子」,
|
||||
别为这个再加一套 agent/container 脚本字段。
|
||||
- **死亡 = 情绪档位「死亡」**(`agentdb.emotion_set/is_dead`),和界面禁言、立绘、
|
||||
复活是同一套数据。世界脚本新增 `api['die'](谁, 遗言='')` / `revive` / `is_dead`
|
||||
三个动作(`world_engine._api`),AI 侧**没有**新工具(AI 仍不能自己复活)。
|
||||
- **数值支持 `initial`**(`rule_engine` / `agentdb.stat_defs.initial_value`):
|
||||
气血这种不能从 0 起步的数值写 `initial`;不写仍按 min(老世界行为不变)。
|
||||
测试世界「气血 0-100 initial 100」+ `on_turn` 判 `气血 <= 0 → die`。
|
||||
- **决斗中死亡 = 判负(底线)**:`duel_engine` 每回合结算后查双方 `agentdb.is_dead`:
|
||||
死的那一方立刻 `finished` + 判负(赢/输 outcome),双方同回合都死 → 平局;
|
||||
已死亡不能发起/接受决斗(400);快照每方 `dead` 布尔,界面显示。
|
||||
别把"判死"写进界面或模型(判定只在内核/世界脚本)。
|
||||
- **用户角色也会死**:档案 `GET /api/containers/<id>/user-profile` 带
|
||||
`emotion`/`dead`;复活走 `POST /api/containers/<id>/user-emotion {preset}`;
|
||||
界面「我的角色」页有死亡卡 + 「复活」按钮。AI 复活仍走「记忆 → 情绪」。
|
||||
- **情绪/立绘显示必须按当前容器(v3.22 假死修复)**:`/api/state` 的
|
||||
`containerEmotions` / `containerPortraits` 按 `containerId` 分;
|
||||
App 用 `AppViewModel.emotionOf()/portraitOf()`(内部按 activeConversation 的容器选),
|
||||
**不要读** `state.emotions`(那是智能体默认容器,会把 A 局的死亡带到 B 局)。
|
||||
保存情绪 `PUT /api/agents/<id>/emotion` 必须带 `containerId`
|
||||
(`MemoryScreen` 用 `memoryContainerId`),否则写到默认容器 = 假死/复活无效。
|
||||
|
||||
## 客户端 HTTP / 地图移动约定(v3.28 起)
|
||||
|
||||
- **Android `KernelClient.call()`:HTTP >= 400 必须抛 `KernelException`**
|
||||
(和 Web `web/js/api.js` 的 `request()` 保持一致)。
|
||||
内核的**失败响应用 4xx**(`{"ok":false,"error":"人话"}`);
|
||||
`HTTP 200 + ok:false` 只留给"软失败"(TTS 退回系统引擎、模型测试 fallback 等),
|
||||
由调用方自己看 `ok` —— **不要**用 200+ok:false 表示"操作失败"。
|
||||
真机踩过(用户原话「移动地点后全乱了:无法移动,无法移人」):
|
||||
旧 `call()` 不看状态码,地图「移人」被内核 400 拒绝后,错误 JSON 被解析成
|
||||
**一张空地图**(页面显示「这一局还没有地图」)还弹「移过去了」;
|
||||
「去这里」则吞掉异常继续切地点对话,位置却没动 —— 位置和对话对不上。
|
||||
验收:`probe-map` §7 钉住"移动失败必须回 400"。
|
||||
- **地图页的移动/切地点以 `mapContainerId` 为准**,不要用"当前会话的容器"——
|
||||
两者可以不是一局(容器列表里点「地图」看 A 局时,聊天还停在 B 局;
|
||||
以前"去这里"会把用户移到 B 局,A 局地图纹丝不动)。
|
||||
统一入口 `AppViewModel.switchPlace(placeId, containerId, alreadyMoved)`:
|
||||
移动失败(不相邻)→ 提示原因并**留在原地**,绝不能继续切对话;
|
||||
从容器列表切进对话要 `showContainers = false`、从「我的角色」页移动要
|
||||
`userItemsOpen = false`,否则对话在浮层下面、看着像没反应。
|
||||
- **移动失败要保持原地图数据**:别把失败响应当新地图覆盖 `mapData`
|
||||
(`MapData` 解析失败会得到空 places,界面直接变成"这一局还没有地图")。
|
||||
|
||||
|
||||
## 常驻角色 / 全定义 id 化约定(v3.30 起)
|
||||
|
||||
- **常驻角色和世界包耦合,不做单独的「角色包」**(用户原话「合在一个世界包里,不要搞别的包
|
||||
因为常驻角色和世界是耦合在一起的」)。类定义进 `worldInfo.json` 的
|
||||
`residentClasses[]`,预召唤实例进 `residents[]`,功能点写在这个类的脚本的
|
||||
`FUNCTIONS` 清单里;脚本文件存在世界包 `scripts/` 里。
|
||||
- **功能清单必须是字面量**(内核 AST 解析、不执行脚本)。一个功能 = 清单一条 + 同名函数
|
||||
`def <id>(api, caller, ...)`;参数类型只支持 `string/int/number/bool/enum/array`
|
||||
(同一份 schema 同时给 AI 工具、界面表单、文档用)。改这里必须同步:
|
||||
`resident_engine.parse_functions`、编辑器 `doubao_project` 校验、文档附录 J。
|
||||
- **三个调用通道共用 `resident_engine.call()`**:AI 工具
|
||||
`resident_<类id>_<功能id>`、界面 `POST /api/containers/<cid>/residents/<iid>/call`、
|
||||
脚本 `api['summon']` / `api['dismiss']`。**caller 由通道决定,AI 不能冒充用户**;
|
||||
AI 花自己的背包/数值,用户操作必须用户自己在界面点。
|
||||
- **AI 工具按"这一局"静态生成、地点/权限在调用时校验**(不是按地点过滤工具表)——
|
||||
工具表一局内不变才不会破坏模型上下文缓存。同类多实例自动加 `instance` 枚举参数。
|
||||
- **常驻角色工具是动态的**,不在 18 个固定工具里;`audience`(ai/user/both)和
|
||||
`hidden` 决定可见性。AI **没有召唤**工具;只有类上标了 `dismissible: true` 才生成
|
||||
`resident_<类id>_dismiss`(默认没有,见下面「常驻角色会离开」)。
|
||||
- **输出统一信封**:`{ok, message, data, note}`,`message` 必须是"AI 能照说的人话结果";
|
||||
业务失败 `raise ValueError("原因")`,内核转 `ok:false`。**先校验、后副作用**——
|
||||
脚本中途报错不会回滚,钱/物品可能已经动了。
|
||||
- **界面入口是聊天输入框打 `>`**(或输入条右侧 `>`)→ 角色菜单 → 功能菜单 →
|
||||
全屏 HTML(内核生成、同源页面、调同一个 call 接口)。AI 用 `show_ui` 写的任意 HTML
|
||||
**拿不到**常驻角色的功能接口(只有 pick/close)——防止 AI 自己写页面绕过工具限制。
|
||||
- 用户界面操作结果进「待回传队列」(复用 `store.add_pending_ui`),AI 下一轮能看到;
|
||||
改这条链路时同步 `probe-residents` §6。
|
||||
- **新界面要登记 `docs/界面总览.md` 并跑 `audit-ui-tree`**:
|
||||
`[常驻角色菜单]` / `[常驻角色功能]` / `[常驻角色功能页]` 三节,
|
||||
`ResidentPageScreen` 已在 `SCREENS` 对照表里。
|
||||
|
||||
- **数值/状态/物品/地点/世界/常驻角色全部 id 化(v3.30)**:用户原话
|
||||
「数值物品状态世界全部id化(脚本可读名字也可读id)」。
|
||||
- `stats[].id` / `statuses[].id` 可选,**不写 = 用 name**(老包零改动);
|
||||
物品/地点本来就有 id;世界包有资源 id;常驻角色类/实例有 id;
|
||||
- 脚本/工具/AI 里的"谁、数值名、状态名、物品名、地点名"**先按 id 找、再按名字找**
|
||||
(`rule_engine.resolve_stat / resolve_status`、`item_engine.resolve_def`、
|
||||
`place_engine.resolve_place`、`resident_engine.find_instances`);
|
||||
- 存库的键用 **id**:`statDefs/statusDefs` 有 `def_id` 列,`stat_values` /
|
||||
`status_instances` 的 name 列存 id;老数据 id=name 不用迁移。
|
||||
定义里新加 id 时 `sync_defs` 会把同名老值搬过去,**之后改 id 不会再搬**;
|
||||
- 世界脚本 api 新增 `world_id` / `world_name`(`pack_id` 保留);物品脚本新增
|
||||
`item`(正在用的物品定义)、`place_of()`、`summon/dismiss/residents`、
|
||||
`world_id` / `world_name`;
|
||||
- 回归:`probe-residents` §11(id/名字双解析、HTTP 按 id 设值/挂状态)、
|
||||
`probe-rule-engine`、`probe-test-world`。
|
||||
- **旧都市世界包是常驻角色的验收样板**:`scripts/worlds/old-city/`(源)+
|
||||
`scripts/worlds/旧都市.zip` + App 内置 `assets/worlds/old-city.zip`;
|
||||
改完跑 `python scripts/build-old-city-world.py`(会同步 App 内置包)并跑
|
||||
`probe-residents.py` §10。
|
||||
- **旧都市的地图相邻关系(用户要求)**:老街 `street` / 小卖铺 `kiosk` / 商店 `store` /
|
||||
学校·校门 `school` **四个地点两两相邻**(地图上这四点之间六条线全连;任意两个直接走),
|
||||
其余(家两间、学校↔教室/操场、森林路口↔森林深处)不变。
|
||||
改完要重新生成 zip + App 内置包;**已导入的旧包不会自动更新**,要在
|
||||
「世界包 → 示例包 → 旧都市」重新导入并新建一局才看得到。
|
||||
回归:`probe-residents` §10(城镇四地点两两相邻)+ `probe-map` §9(连线去重)。
|
||||
- **界面 `>` 菜单按用户当前地点过滤(v3.30 体验修复)**:只列同地点 + 不绑地点
|
||||
(`place=''` = 全图可找)的常驻角色,避免"在家看到商店/森林的常驻角色、点进去只会
|
||||
先过去才能办事"。`GET /api/containers/<cid>/residents` 返回 `placeId/placeName/
|
||||
elsewhere/hint`;空菜单时 UI 显示 `hint`("这里没有、别的地点还有 N 个,先移动过去")。
|
||||
AI 工具表**不按地点过滤**(按局静态、调用时校验),两条规则别搞混。
|
||||
回归:`probe-residents` §6(同地点只列售货员 / 回家菜单空+提示)、§10(旧都市)。
|
||||
- **常驻角色会离开(v3.30)**:脚本 `api['dismiss_me']()` 让自己走(外卖员送完、
|
||||
解谜后消失);类上 `dismissible: true` 才生成 AI 工具 `resident_<类id>_dismiss`
|
||||
(同一地点才能请走,默认关闭)。功能信封带 `dismissed: true` + `note` 告诉 AI
|
||||
"别再找它";走后菜单/工具里都不会再出现,要它回来按世界规则重新召唤。
|
||||
回归:`probe-residents` §6b(自己走 / AI 工具 / 隔空拒绝)+ §10 旧都市
|
||||
(外卖送完 `dismiss_me`、`resident_delivery_dismiss`)。
|
||||
- **独自一人的地点:不能聊天 ≠ 不能交互(v3.30)**:`place_engine.chat_guard` 只拦
|
||||
聊天;`>` 常驻角色接口不受影响。聊天页禁言条里必须有「找常驻角色 ›」入口,
|
||||
否则用户在有常驻角色、没 AI 角色的地点会以为整个界面废了。
|
||||
回归:`probe-residents` §10(森林深处 chat_guard=false 但守林人可调)。
|
||||
- **世界容器(一局)只认成员(v3.30)**:用户反馈「这容器都没选豆包,豆包咋会出现在
|
||||
这里」。三条必须同时守住:
|
||||
1. 内核 `/api/conversations` POST:世界容器里给非成员开对话 / 群拉非成员 → 400;
|
||||
2. `app.py` rebase(换智能体另起会话):**本局成员才继承容器**,非成员回它自己的
|
||||
默认容器,并用 `rebased.message` 告诉界面原因;
|
||||
3. 客户端:`useAgent` 切到非成员时立即开它的默认容器会话;地点对话的主人必须从
|
||||
容器成员里选(不能拿 activeAgent 硬塞)。
|
||||
回归:`probe-containers` §12(成员/非成员开对话、群拉人、加群成员、rebase 事件)。
|
||||
- **图形地图(v3.31)**:地图 = **内核生成的 HTML 页**(`GET /api/containers/<cid>/map/page`,
|
||||
安卓 `MapScreen` 全屏 WebView 打开),不是 Compose 画的列表。世界包定义:
|
||||
`places[].x/y`(0-100 百分比)+ `places[].region`;`info.map` 里 `background/width/
|
||||
height/marker/css/regions[]`。**连线自动由 `places[].exits` 生成**(双向去重),
|
||||
不要另写一份。交互:双指缩放/拖动、点区域框放大、点地点「去这里/移人」、
|
||||
**长按地点或区域弹信息**(`bindLongPress` + `showPlaceInfo`)。
|
||||
背景图随包 `assets/` 导入(`_save_map_background` 落盘成绝对路径)并在导出时
|
||||
打回 zip(`_pack_one_asset`)。回归:`probe-map` §9(坐标/区域/连线去重/HTML 关键
|
||||
元素/长按/缩放/CSS 注入/节点几何/面板高度)+ `probe-residents` §10(旧都市地图背景随包导入/导出)。
|
||||
- **地图页的两条几何铁律(v3.31 修复,别再回归)**:
|
||||
1. **连线端点 = 圆点圆心**:`.map-node` 盒子**只有圆点那么大**(圆心 = `places[].x/y`),
|
||||
名字用绝对定位挂在下面;`#edges` 必须是 `#stage` 的第一个子元素(线在圆点下层)。
|
||||
曾经把节点做成"圆点+文字整列居中"、把连线 append 到节点之后 —— 用户看到
|
||||
"连线端点掉到圆点底下 / 线盖在圆点上";
|
||||
2. **信息面板竖直居中、高度随内容**,高度**用 JS `innerHeight` 算像素**,别用 `vh`(见下条)。
|
||||
- **★★ 安卓 WebView 的 `vh` / 视口百分比高度可能是 0**(真机实测:Chrome/146 WebView
|
||||
里 `10vh` → **0px**,`max-height:74vh` 也是 0px —— 地图信息面板因此被压成一条
|
||||
44px 横条,用户反复反馈"面板太矮/太低"的根因)。内核生成的 HTML 页面里
|
||||
**不要用 `vh` / 百分比高度**控制高度;要限高就用 JS
|
||||
`Math.round(window.innerHeight * 比例) + 'px'` 设行内样式(地图页 `sheetMaxHeight()`、
|
||||
常驻角色功能页 `max-height:260px` 都是这么处理的)。`MapScreen` / `ResidentPageScreen`
|
||||
另外开了 `settings.useWideViewPort = true`(别再关 overview 缩放那一半:地图舞台
|
||||
不能整体缩放),但页面里的 JS 兜底必须保留。回归:`probe-map` §9(断言页面里有
|
||||
`sheet.style.maxHeight = sheetMaxHeight()`)、`probe-residents` §5(断言功能页没有 `40vh`)。
|
||||
- **改地图不要动移动/邻接规则**:`place_engine.move` 的 exits 校验、用户/AI 位置、
|
||||
地点对话频道都保持原样;地图页只是"看 + 点"的壳,移动仍走
|
||||
`POST /api/containers/<cid>/move`(页面里 fetch 同一接口,成功后 JS 桥
|
||||
`Doubao.moved` 让 App 切到该地点对话,`alreadyMoved=true` 不能再移一次)。
|
||||
839
豆鲍/README.md
Normal file
839
豆鲍/README.md
Normal file
@@ -0,0 +1,839 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(Web / Windows 版=豆包网页版风格)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
|
||||
**Web / Windows 端**(v2)换成了**豆包网页版风格**的桌面界面,并且和安卓 App
|
||||
**共用同一份 Python 内核**(exe 内嵌 Python 运行时)—— 功能天然同步。详见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||
> 「豆包」是字节跳动的商标。
|
||||
|
||||
> **📖 完整教程(当前版本,只讲怎么用)**:[`docs/小人间-完整教程.md`](docs/小人间-完整教程.md)
|
||||
> —— 安装/配模型、世界包与容器、数值/状态/物品/地图、决斗、语音情绪指令、
|
||||
> AI 的 18 个工具与权限边界、脚本写法、FAQ;
|
||||
> **附录 C–J 是数据字典 + HTTP API 全表(每个接口每个参数)+ AI 工具全参数 +
|
||||
> 脚本 API 全表 + 错误码 + 提示词结构 + 参数速查**。
|
||||
>
|
||||
> **🧩 世界包脚本 API 参考(按模块拆分)**:[`docs/world-script-api/index.md`](docs/world-script-api/index.md)
|
||||
> —— `world`(世界脚本)/ `stats`(数值裁决)/ `status`(状态)/ `item`(物品)/
|
||||
> `guard`(驻守)/ `resident`(**常驻角色**:类/实例、FUNCTIONS 功能清单、AI 工具与界面 `>` 入口)/
|
||||
> `defs`(worldInfo.json 字段)/ `types`(数据结构)/
|
||||
> `sandbox`(沙箱与异常)/ `examples`(完整示例),Qt 文档风格逐方法写清签名·参数·返回。
|
||||
>
|
||||
> **🏙️ 示例世界包**:`scripts/worlds/旧都市.zip`(旧都市:家/学校/商店/小卖铺/森林 +
|
||||
> 4 个常驻角色 + 全部常驻角色功能;App「世界包 → 示例包」里也能一键导入)。
|
||||
>
|
||||
> **📦 宣传/开店资料包**:`python scripts/build-docs-pack.py` →
|
||||
> `dist-docs/小人间-资料包-v3.31.zip`(约 6.6 MB)—— 总体说明(全功能)+ 完整教程 +
|
||||
> 世界脚本 API + 示例世界包 + 精选截图;把 zip 丢给另一个对话就能让它写**产品介绍网页**和
|
||||
> **商店/商品页**。全功能总览见 [`docs/总体说明-所有功能.md`](docs/总体说明-所有功能.md)。
|
||||
|
||||
| 平台 | 产物 | 界面 | 内核 |
|
||||
|---|---|---|---|
|
||||
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | **豆包网页版风格 Web UI**(`web/`) | **exe 内嵌 Python + `android/kernel/`(与 App 同一份)** |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | **豆包网页版风格 Web UI**(`web/`) | **`android/kernel/`(本机 Python)** |
|
||||
|
||||
> 旧的 **Lynx 版**(`app/` + Node 内核 `server/`)没有删,作为历史留档,菜单命令见 §9。
|
||||
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||
|
||||
| 对话(原生) | 真实回复(含操作栏) | 抽屉(含「模型」栏) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 模型与思考强度 | 设置(10 家提供商) | 内置 Termux 终端 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
**网页版 / Windows 桌面版(v2,豆包网页版风格):**
|
||||
|
||||
| 空对话(桌面网页) | 群聊(成员条 + 交接) | Windows exe |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 智能体 | 设置(10 家提供商 / 22 项超时) | 会议模式(运行日志) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
**AI 界面能力(电脑端也能用了:AI 自己写 HTML 弹界面 / 弹选择框 / 结束对话):**
|
||||
|
||||
| AI 写的界面(show_ui,iframe 渲染) | AI 提问(ask_user,等用户选) | 结束对话(end_conversation) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| exe 里同样可用(真窗口实拍) | | |
|
||||
|---|---|---|
|
||||
|  | | |
|
||||
|
||||
> 前两组是安卓原生 Compose 版(手机);这两组是电脑上的**网页版**(浏览器 / exe 同一个界面)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 快速开始
|
||||
|
||||
### 浏览器 / 桌面版(v2:豆包网页版风格,和 App 同一份 Python 内核)
|
||||
|
||||
需要本机有 **Python 3.10+**(内核是纯标准库;Android 端是内嵌 CPython)。
|
||||
|
||||
```bash
|
||||
npm start # 起 Python 内核并托管 web/,打开 http://127.0.0.1:5199/
|
||||
PORT=5300 npm start # 换端口
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**自带 Python,不用装**;**exe 必须放纯英文路径**,见 §7.1)。
|
||||
重新打包:`npm run exe`。
|
||||
|
||||
> 旧的 Lynx 版还留着:`npm run install:all` + `npm run start:legacy-lynx`。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
```bash
|
||||
npm run apk # 产出 dist-android/doubao-debug.apk(约 88 MB)
|
||||
adb install -r dist-android/doubao-debug.apk
|
||||
```
|
||||
|
||||
装完打开 App → 抽屉 →「设置」→ 选提供商、填 API Key → 保存。
|
||||
第一次启动会解压内置 Termux(约 95 MB、3226 个文件),**约 10~30 秒**,界面上有进度。
|
||||
|
||||
---
|
||||
|
||||
## 2. 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Android App(原生 Kotlin + Compose,主力) │
|
||||
│ │
|
||||
│ ui/ ChatScreen Drawer Settings Skills Agents Profile │
|
||||
│ ModelPickerSheet TerminalScreen ← 7 个页面 │
|
||||
│ │ │
|
||||
│ │ KernelClient(OkHttp + 轮询流式) │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ Python 内核(Chaquopy 内嵌 CPython 3.13) │ │
|
||||
│ │ android/kernel/ —— 监听 127.0.0.1:5199 │ │
|
||||
│ │ · providers 10 家兼容厂商 + 思考强度映射 │ │
|
||||
│ │ · agent_loop 多轮工具循环 │ │
|
||||
│ │ · tools import 加载 tools/*.py │ │
|
||||
│ │ · mcp_client 手写 JSON-RPC(http/stdio/inproc)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ 进程内直调(Chaquopy 桥) │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 内置 Termux($PREFIX = /data/user/0/<pkg>/files/usr) │
|
||||
│ │ · bash 5.x / apt / pkg / 388 个命令 │ │
|
||||
│ │ · libtermux.so → forkpty(真 tty) │ │
|
||||
│ │ · TerminalView → ANSI 渲染(Termux 源码 vendored)│ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ 设备能力 NativeBridge:定位 / 陀螺仪 / 加速度计 │ │
|
||||
│ │ 磁性 / 光线 / 气压 / 电量 / 剪贴板 / 选文件 │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**v2 起,电脑上的 Web/exe 版不再用 Node 内核 + Lynx**,而是:
|
||||
- 界面换成 `web/` 里**豆包网页版风格**的纯静态前端(无构建步骤,内核直接托管);
|
||||
- 后端直接跑**和安卓 App 同一份** `android/kernel/`(纯标准库 Python),
|
||||
桌面版由 Electron 起一个 Python 子进程、并带一个"原生能力桥"(选文件/剪贴板);
|
||||
- 所以「引擎改了另一端必须跟上」这条欠账**没了**:一份内核,两个客户端。
|
||||
旧的 Node 内核(`server/`)和 Lynx 界面(`app/`)留作历史存档。
|
||||
|
||||
细节见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能
|
||||
|
||||
### 3.1 智能体
|
||||
抽屉 →「智能体」。每个智能体有独立头像(9 种)和系统提示词,聊天时覆盖全局提示词,顶部显示当前智能体。
|
||||
内置 4 个(豆包 / 代码搭子 / 文案师 / 数据分析),可自建。存 `<数据目录>/agents.json`。
|
||||
|
||||
### 3.2 模型、提供商与思考强度(抽屉里的「模型」那一栏)
|
||||
|
||||
**支持 10 家,而且它们全都是同一个协议**(`POST {baseUrl}/chat/completions`),
|
||||
所以内核里只有一份实现,差别只在三件事:地址、模型名、**思考强度用哪个字段传**。
|
||||
|
||||
| key | 提供商 | Base URL | 思考强度怎么传 |
|
||||
|---|---|---|---|
|
||||
| `ark` | 火山方舟(豆包) | `https://ark.cn-beijing.volces.com/api/v3` | 顶层 `thinking: {type}` |
|
||||
| `openai` | OpenAI 官方 | `https://api.openai.com/v1` | `reasoning_effort` |
|
||||
| `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | 不发(模型自己决定) |
|
||||
| `kimi` | Kimi(月之暗面) | `https://api.moonshot.cn/v1` | 不发 |
|
||||
| `zhipu` | 智谱 GLM | `https://open.bigmodel.cn/api/paas/v4` | 顶层 `thinking: {type}` |
|
||||
| `dashscope` | 通义千问(阿里云) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | 不发 |
|
||||
| `siliconflow` | 硅基流动 | `https://api.siliconflow.cn/v1` | 不发 |
|
||||
| `openrouter` | OpenRouter(聚合) | `https://openrouter.ai/api/v1` | `reasoning_effort` |
|
||||
| `ollama` | 本地 Ollama | `http://127.0.0.1:11434/v1` | 不发 |
|
||||
| `custom` | 自定义兼容网关 | 自己填 | 不发 |
|
||||
|
||||
**为什么不是"非 ark 即 openai"**:这个判断以前写死成两家名字。
|
||||
现在厂商多了,各自认的字段不一样,而**给不认 `reasoning_effort` 的服务发这个字段,有些会直接 400**。
|
||||
所以改成每个预设自己声明 `thinkingMode`(`ark` / `effort` / `none`),**认不出来的一律 `none`**(什么都不发,最安全)。
|
||||
|
||||
| 强度 | `thinkingMode: ark` | `thinkingMode: effort` | `thinkingMode: none` |
|
||||
|---|---|---|---|
|
||||
| 快速 | `thinking={type:"disabled"}` | 推理模型 `reasoning_effort=minimal` | 不发 |
|
||||
| 自动 | 不传,交给模型 | 不传 | 不传 |
|
||||
| 低 / 中 / 高 | `thinking={type:"enabled"}` | `reasoning_effort=low/medium/high` | 不传 |
|
||||
|
||||
另外:`thinkingMode: effort` 且模型名匹配 `o1|o3|o4|gpt-5|gpt-6` 时,
|
||||
会自动剥掉 `temperature`/`top_p` 等采样参数,并把 `max_tokens` 换成 `max_completion_tokens`
|
||||
(这些模型"传默认值"也算传,会 400)。
|
||||
|
||||
两份内核(Node / Python)在这件事上**逐字段对拍 50/50 一致**(10 家 × 5 档),
|
||||
脚本:`node scripts/parity-thinking.mjs`。
|
||||
|
||||
### 3.3 思考过程怎么显示
|
||||
1. **正文里**:回答上方一个 `✨ 深度思考 ›` 入口,思考中显示跳动小点
|
||||
(这里不再拼思考强度 —— 强度本身就叫"深度思考",拼出来会变成"深度思考 · 深度思考")
|
||||
2. **点开**:底部升起「**思考过程**」弹层(左上角 X),先列这轮调了哪些工具,再是完整思维链
|
||||
3. 思维链**已落库**,刷新/切会话都不丢
|
||||
|
||||
### 3.4 界面:照着豆包抠的,带完整动效
|
||||
|
||||
安卓端是原生 Compose 重写的,视觉对着豆包真机截图一项项抠:
|
||||
|
||||
- **纯白底**(不是浅灰)——豆包的层级靠"白底 + 浅灰卡片"表达,用灰底会一股系统设置味
|
||||
- 顶部三段式:左边 ☰ / ✎,中间「头像 + 智能体名 + ›」(点开就是模型面板),右边 📞 / 🔊
|
||||
- 空会话时:168dp 蓝色圆环大头像 + 灰色问候气泡 + 白底描边快捷胶囊(对话 / AI创作 / 出行用豆包 / 豆包)
|
||||
- 用户气泡:`#2B7BFF` 蓝底、右下角收窄成 4dp(气泡"尾巴")
|
||||
- 助手气泡:`#F2F3F5` 灰底、左下角收窄;下面一排 5 个圆形小按钮(复制/朗读/赞/踩/分享)+ 右侧重新生成
|
||||
- 输入框:52dp 高的大圆角描边胶囊,左边相机、右边麦克风;**有内容时右侧才变成蓝色圆形发送键**
|
||||
- 出错的回复是浅红底 + 红字,不是普通气泡
|
||||
- 设置 / 我的 / 技能 / 智能体各页共用同一套小部件(`ScreenHeader` / `SettingsCard` / `FormField` …),
|
||||
所以在主题层改一次颜色,7 个页面一起变
|
||||
|
||||
动效(都是 Compose 原生动画,没引第三方库):
|
||||
|
||||
| 位置 | 动效 |
|
||||
|---|---|
|
||||
| 抽屉 | 从左滑入 + 遮罩淡入,关闭反向 |
|
||||
| 页面切换 | 淡入 + 轻微横向位移(`AnimatedContent`) |
|
||||
| 消息气泡 | 出现时淡入 + 上移 10dp(`AppearOnce`) |
|
||||
| 思考 / 模型面板 | 从底部升起,收起时降下去 |
|
||||
| "正在输入" | 三个小点依次跳动(`TypingDots`,错开 130ms) |
|
||||
| 按钮 | 按下缩到 0.86~0.94 回弹(`collectIsPressedAsState` + spring) |
|
||||
| 抽屉列表项 | 按下时背景色渐变 |
|
||||
|
||||
> 顺带一个坑:底部面板的**滚动区会吃掉点击**。如果面板顶到状态栏,
|
||||
> "点遮罩关闭"就只剩状态栏那条能点,等于失效。所以面板限高 85%、并且都带明确的 X 按钮。
|
||||
|
||||
### 3.5 设置不会被保存清空(三道防线)
|
||||
|
||||
之前有个真 bug:**一保存设置,整份配置被清空**。根因是首屏 `state` 还在路上时,
|
||||
设置页草稿还是"全空"的,而保存按钮把草稿**全量**下发;`/api/settings` 是浅合并,
|
||||
空字符串就等于把它清掉。现在三道防线:
|
||||
|
||||
1. **界面只发改动过的字段**(`SettingsDraft.changesAgainst`)——没动过的键根本不出现
|
||||
2. **草稿只在服务端设置真的变了时重建**(存一份 `snapshot` 对比),
|
||||
不会再被无关的 state 刷新冲掉正在输入的内容
|
||||
3. **内核拒收空的关键字段**(`provider` / `baseUrl` / `model` / `apiKey` / `nickname` / `thinkingLevel`)——
|
||||
前端再出 bug 也清不掉配置。`systemPrompt` / `toolsDir` 故意不在此列:它们"留空"是合理需求
|
||||
|
||||
验证脚本(都会先正常保存一次验证不掉字段,再按"旧版 bug 的形状"下发一堆空值验证被忽略):
|
||||
|
||||
- `node scripts/probe-settings-wipe.mjs http://127.0.0.1:5199`(电脑 / Node 内核)
|
||||
- `node scripts/device-settings-attack.mjs emulator-5556 5199`(设备 / Python 内核)
|
||||
|
||||
### 3.6 工具
|
||||
|
||||
| 工具 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `shell` | 终端执行命令,带超时与黑名单 | ✅ 优先走内置 Termux |
|
||||
| `python_run` | 执行 Python 代码 / .py 文件,`action=libs` 列可用库 | ✅ 进程内 exec(CPython 3.13.9) |
|
||||
| `device` | **手机能力**:设备信息、定位、传感器、剪贴板 | ✅ 安卓专属 |
|
||||
| `calc` `now` `get_weather` `notes` `web_fetch` | `tools/*.py`,自己写的 | ✅ 同一份代码 |
|
||||
| `mcp__*` | MCP 服务暴露的工具 | ✅ 见 3.8 |
|
||||
|
||||
**`device` 工具**(安卓)实测能力:
|
||||
- `info`:型号/厂商/系统/SDK/ABI/存储/屏幕/电量
|
||||
- `location`:GPS 经纬度(真机实测 `纬度, 经度 ±35m`)
|
||||
- `sensors` / `sensor`:列出并采样(真机 46 个传感器,加速度计 z≈9.7 m/s² 就是重力)
|
||||
- `clipboard_get` / `clipboard_set`
|
||||
- `termux_available` / `termux_run`:走内置 Termux
|
||||
|
||||
### 3.7 自己写工具
|
||||
往工具目录丢一个 `.py`(`_` 开头跳过):
|
||||
|
||||
```python
|
||||
TOOL = {
|
||||
"name": "word_count",
|
||||
"description": "统计一段文字的字数",
|
||||
"parameters": {"type": "object", "properties": {"text": {"type": "string"}},
|
||||
"required": ["text"]},
|
||||
}
|
||||
def run(args): # 同步或 async 都行
|
||||
return {"count": len(args["text"])}
|
||||
```
|
||||
|
||||
工具目录:安卓在 `files/tools/`(可通过设置里的 `toolsDir` 改),电脑在 `tools/`。
|
||||
内置工具在首次启动时会**播种**到可写目录,改坏了删掉重启就恢复。
|
||||
|
||||
> 为什么安卓上要播种、还要把源码 base64 打进 APK:Chaquopy 打的是 `.pyc`,
|
||||
> 运行时 `loader.get_source()` 拿不到源码,所以构建脚本额外生成了 `bundled_tool_sources.py`。
|
||||
|
||||
### 3.8 MCP:三种传输,安卓也能跑
|
||||
抽屉 →「技能·连接器」→「MCP 服务」,图形化和原始 JSON 两个 Tab,保存时校验并自动重连。
|
||||
|
||||
| 传输 | 说明 | 安卓 |
|
||||
|---|---|---|
|
||||
| `http` | 标准 Streamable HTTP / SSE | ✅ |
|
||||
| `stdio` | 起一个子进程用管道通信 | ✅ 用内置 Termux 的 python/node |
|
||||
| `inproc` | 同进程内直接调用(自己写的 Python 服务) | ✅ 安卓推荐,最省事 |
|
||||
|
||||
实测:filesystem 服务 14 个工具、memory 9 个工具、自己写的 Python 服务 3 个工具,全部连接并调用成功。
|
||||
|
||||
> 为什么手写 JSON-RPC 而不用官方 `mcp` SDK:它依赖 pydantic v2,Chaquopy 装不进来。
|
||||
|
||||
### 3.9 文件上传 / 权限模式
|
||||
- **上传**:输入框左侧相机/加号 → 选文件 → 上传到内核 → 挂到输入框 → 随消息发送 → 气泡里显示
|
||||
- **权限模式**:`open` 全放行 / `restricted` 只放 `allow` 白名单。限制模式下未授权工具
|
||||
**列都不列出来**,执行时再拦一道
|
||||
|
||||
### 3.10 语音:朗读 + 语音输入
|
||||
|
||||
**引擎放在内核里,音频采集/播放在端上。** 这么分的好处:API Key 只存一份,
|
||||
浏览器 / 安卓 / exe 三端白捡同一个能力,厂商鉴权差异全在一个文件里。
|
||||
|
||||
| | 引擎 | 说明 |
|
||||
|---|---|---|
|
||||
| **朗读** | `system` | 设备自带 TTS(安卓 `TextToSpeech`)。**不联网、不要 Key**,默认就是它 |
|
||||
| | `volc` | **火山语音合成 —— 豆包同款音色** |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/speech`(`tts-1` + alloy/nova/…) |
|
||||
| **语音输入** | `system` | 设备自带识别(安卓 `SpeechRecognizer`) |
|
||||
| | `openai` | OpenAI 兼容的 `/audio/transcriptions`(`whisper-1` 等) |
|
||||
|
||||
**火山那个接口有两个坑**(对着[官方文档](https://docs.volcengine.com/docs/DoubaoVoice/HTTPone-timecompositenon-streaminginterface-V1notrecommended?lang=zh)
|
||||
和两个第三方实现核对过,并且用 mock 抓了实际发出的请求):
|
||||
|
||||
1. 鉴权头是 `Authorization: Bearer;{token}` —— **分号,不是空格**。写成空格会判鉴权失败。
|
||||
实测抓到的请求:`Authorization="Bearer;tok-abc"`
|
||||
2. 成功判定看 body 里的 `code === 3000`,**HTTP 200 也可能带错误码**;
|
||||
返回的 `data` 是**纯 base64**(不是 data URL),解出来就是音频字节
|
||||
|
||||
接口:
|
||||
|
||||
```
|
||||
POST /api/tts {"text": "..."}
|
||||
→ {"ok":true, "engine":"system"} 用设备自带,界面自己念
|
||||
→ {"ok":true, "engine":"volc", "mime":"audio/mpeg", "audio":"<base64>"}
|
||||
→ {"ok":false, "error":"..."} 失败原因给人话
|
||||
|
||||
POST /api/stt <body 就是音频原始字节,不套 JSON/base64>
|
||||
头: X-Audio-Filename / X-Audio-Type
|
||||
→ {"ok":true, "engine":"openai", "text":"..."}
|
||||
|
||||
GET /api/speech → 当前配置 + 可选音色
|
||||
```
|
||||
|
||||
> 两个接口**失败也返回 HTTP 200 + `ok:false`**:缺 Key、厂商报错都是预期内的失败,
|
||||
> 界面要的是把原因显示出来,而不是让 fetch 抛网络异常(那样错误信息就丢了)。
|
||||
|
||||
安卓端(`speech/AudioIo.kt` + `speech/SpeechController.kt`):
|
||||
|
||||
- **录音**用 `AudioRecord` 直接拿 PCM,套 44 字节 WAV 头(16kHz 单声道 16bit ——
|
||||
Whisper 最常见的输入格式,30 秒才 1 MB)。不用 `MediaRecorder` 是因为它只吐 m4a/aac,还得再解码
|
||||
- **播放**云端音频走 `MediaPlayer`(`setDataSource` 只认路径/FD,所以 base64 落盘成临时文件再播)
|
||||
- **系统 TTS** 会**按句切分**再排队 —— `speak()` 单次上限约 4000 字符,整段塞进去会被截断
|
||||
- 念之前**剥掉 markdown**(`**加粗**`、代码块、链接),否则会念出一堆星号
|
||||
- **云端失败自动退回系统 TTS**:用户点了朗读却一点动静都没有是最差的体验
|
||||
- 录音时**先停朗读**,否则会把自己的声音录进去(自我循环)
|
||||
- 录音权限**第一次点麦克风才申请**,不在启动时要
|
||||
- 录音时输入框整条换成「正在听…」+ 实时音量画的小波形
|
||||
|
||||
验证:`node scripts/verify-speech.mjs py|node` —— **21 项断言,两份内核都跑**
|
||||
(语音在 Node 和 Python 里是分别实现的,只验一份不算数)。
|
||||
mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权头。
|
||||
|
||||
### 3.11 通话模式(设计好了,还没做)
|
||||
|
||||
顶部那个 📞 现在是提示。真要做的话按这个来(**不要一上来就上全双工**):
|
||||
|
||||
| 阶段 | 做法 | 为什么 |
|
||||
|---|---|---|
|
||||
| A(推荐先做) | **半双工**:按一次开始录 → 静音自动断句 → STT → 内核 → TTS 播 → 循环 | 复用现有的 STT/TTS,1 天能出可用版本 |
|
||||
| B | 全双工实时(OpenAI Realtime / 火山实时对话,WebSocket) | 延迟 300ms 级、能自然打断,但强依赖网络,改造量 3~5 天 |
|
||||
|
||||
阶段 A 要处理的四件事(都会真实咬人):
|
||||
|
||||
1. **自我循环**:TTS 在播时开麦会把 AI 自己的声音录进去 → 播之前必须先停麦,
|
||||
或者做回声消除(`AudioSource.VOICE_COMMUNICATION` + AEC)
|
||||
2. **音频焦点**:`TextToSpeech` 和 `AudioRecord` 不能同时持有 → 用 `AudioManager` 协调
|
||||
3. **VAD 断句**:靠静音时长判断"说完了"。阈值调不好要么打断用户、要么一直不响应;
|
||||
建议"连续 800ms 低于阈值算说完",并且**开口就打断 TTS**(barge-in)——这是"像通话"的关键手感
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
### 3.13 超时(全部可调)
|
||||
|
||||
设置页最下面那张卡片 →「超时」,**18 项全都能调**:
|
||||
|
||||

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

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

|
||||
|
||||
**六个能力**(都能在界面上单独关掉或不管它):
|
||||
|
||||
| | 一句话 |
|
||||
|---|---|
|
||||
| Token | 按智能体独立统计、**按模型分桶**、输入输出分开;能设上限,用满时发起前拦住并附一句告别 |
|
||||
| 记忆 | 无上限、AI 自己记,**用户能改能删**(兜底);「必须保留」的 AI 改不动 |
|
||||
| 情绪 | 每个智能体一个当前情绪,写进提示词;**绑同一世界观也不共享**(需求明确要求) |
|
||||
| 世界观 | 独立资源。绑了它的智能体**共用一份记忆**,但**只能改自己写的**那几条 |
|
||||
| 技能 | 纯文本手册,按绑定顺序注入;内置那份默认就生效 |
|
||||
| 多模型 | 全局模型列表 + UUID 引用。引用了就**整组覆盖**(地址/Key/模型一起换) |
|
||||
|
||||
**两处需要解释的设计**:
|
||||
|
||||
1. **数据分界**:记忆/情绪/Token/Skill 绑定进 SQLite(条目无上限、每轮全量读、
|
||||
要检索、要按行改删),其余仍是 JSON(量级小、要人肉可读)。
|
||||
判据写在 `android/kernel/agentdb.py` 文件头,加新数据时先按那张表判一次。
|
||||
|
||||
2. **幻觉调用检测**:模型很容易在"该记东西"的时候只在正文里说一句"我记住了"
|
||||
—— 用户当场看不出来,下次发现它完全不记得,信任就没了。所以由程序比对
|
||||
「说了什么」和「做了什么」,对不上就在那条回复下面挂一条警示。
|
||||
判宽比判窄更糟(误伤几次之后用户就不看那个警示了),所以只收明确句式。
|
||||
|
||||
**验证**(都不需要装机、不需要网络):
|
||||
|
||||
```bash
|
||||
python scripts/probe-agent-system.py # 12 节 70+ 项:UUID、记忆、限权、注入顺序、
|
||||
# 20 多个接口、包的边界、多模型解析
|
||||
python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calling 的降级
|
||||
```
|
||||
|
||||
> ⚠️ **改完内核记得跑一次 `py_compile`**:Gradle 不编译 Python
|
||||
> (Chaquopy 只是把 `.py` 打进 APK),语法错误要等手机上启动内核才炸,
|
||||
> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸,
|
||||
> 但它拦的是"打包",不是"你刚改的那一行"。
|
||||
|
||||
**全部界面和入口在哪**:[`docs/界面总览.md`](docs/界面总览.md) ——
|
||||
把 App 里所有界面画成树(含"每个界面从哪进"),而且
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**Python 脚本在哪跑、各有什么权限**:[`docs/Python脚本.md`](docs/Python脚本.md) ——
|
||||
这个 App 里**六类地方**会跑 Python(AI 的 `python_run` / `shell`、规则脚本、
|
||||
会议 Python 节点、自定义节点、内置 Termux),它们的权限和沙箱**完全不同**。
|
||||
一句话结论:
|
||||
|
||||
> **只有「规则脚本」有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
|
||||
> 其余几处本质就是"在你手机上跑代码",靠超时兜底,不是权限隔离。
|
||||
|
||||
**Web / exe 端(v2)**:不再维护第二套实现。界面在 `web/`(豆包网页版风格),
|
||||
后端就是上面这份 `android/kernel/`(桌面 exe 内嵌 Python 运行时)。
|
||||
功能对照、架构、验收方式和已知差距全部写在 [`docs/网页版.md`](docs/网页版.md);
|
||||
接口契约在 `docs/kernel-api-chat.md` / `kernel-api-agents.md` / `kernel-api-misc.md`。
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 4. 安卓端:内置 Termux 是怎么塞进去的
|
||||
|
||||
### 4.1 一条硬限制决定了整个方案
|
||||
|
||||
**Android 10(API 29)起有 W^X 限制:`targetSdk ≥ 29` 的应用不允许执行自己数据目录里的二进制。**
|
||||
而 Termux 把 bash/python/node 全解压在自己的私有目录再 exec —— 它能这么干,**唯一原因是它 `targetSdk = 28`**
|
||||
(实测核对:`dumpsys package com.termux` → `targetSdk=28`)。
|
||||
|
||||
所以这个 APK 也锁 **`targetSdk = 28`**。代价是上不了应用商店(个人工具无所谓);
|
||||
换来的是完整 Linux 用户态:`bash`、`apt`、`pkg`、以及 `pkg install python nodejs-lts`。
|
||||
|
||||
### 4.2 APK 里到底装了什么
|
||||
|
||||
```
|
||||
APK 88.4 MB
|
||||
├─ lib/arm64-v8a/libtermux-bootstrap.so 28.0 MB ← Termux 根文件系统(其实是 zip)
|
||||
├─ lib/x86_64/libtermux-bootstrap.so 28.1 MB ← 同上,模拟器用
|
||||
├─ lib/<abi>/libtermux.so ← pty 的 JNI(createSubprocess 等 5 个符号)
|
||||
├─ lib/<abi>/libpython3.13.so ← Chaquopy 的 CPython
|
||||
├─ assets/chaquopy/** ← 内核 + 9 个 Python 工具
|
||||
└─ java/com/termux/{terminal,view}/** ← Termux 的终端模拟器源码(vendored)
|
||||
```
|
||||
|
||||
Termux 的终端库**没有发布到任何 Maven 仓库**(Maven Central 没有,JitPack 也不通),
|
||||
所以是 vendored 源码 + 改了两处 `import com.termux.view.R` 指向我们自己的 R 类。
|
||||
Apache-2.0 声明见 `android/app/src/main/assets/TERMUX_LICENSE.txt`。
|
||||
|
||||
### 4.3 安装流程(移植自 Termux 的 `TermuxInstaller.java`)
|
||||
|
||||
1. 从 APK 里取出 `libtermux-bootstrap.so`
|
||||
2. **切掉 ELF 头**得到纯 zip(见 4.4 ①)
|
||||
3. 解压到 `files/usr`(3226 个文件),给 `bin/ lib/ libexec/` 下的文件补可执行位
|
||||
4. 读 `SYMLINKS.txt`(1146 行,格式 `目标←链接路径`),**用 `/system/bin/sh` 批量 `ln -sf`**
|
||||
—— Java 的 File API 建不了符号链接
|
||||
5. **改写脚本 shebang**(见 4.4 ④)
|
||||
6. 写一份自己的 `etc/doubao.bashrc`
|
||||
|
||||
进度会写进 `files/termux-install.log`(见 §7.6,为什么不用 Logcat)。
|
||||
|
||||
### 4.4 踩过的四个坑(都和你想象的不一样)
|
||||
|
||||
**① `libtermux-bootstrap.so` 不是纯 zip,是「ELF 头 + zip」**
|
||||
文件前 1328 字节是 ELF 头(Android 要求 `lib/` 下的东西得像 ELF,Termux 就把 zip 接在后面)。
|
||||
- `ZipInputStream` 按本地文件头顺序扫,**实测一个条目都读不出来**;
|
||||
- `ZipFile` 走中央目录,但它**不会**像桌面 JVM 那样自动跳过前缀 ——
|
||||
真机 Android 16 上直接报 `Entry at offset zero has invalid LFH signature 464c457f`
|
||||
(`464c457f` 就是 `\x7FELF` 的小端十六进制)。模拟器上碰巧宽松能过,真机不行。
|
||||
|
||||
所以现在的做法:**自己扫第一个 `PK\x03\x04`、把前缀切掉**,再交给 `ZipFile`。
|
||||
|
||||
**② `bin/su` 写不进去(ENOENT)**
|
||||
父目录存在、权限也对,就是 `open` 失败。安卓对这个文件名有额外限制。
|
||||
处理方式:**单个文件失败就跳过并记日志**,不让一个怪文件毁掉整次安装(其余 3226 个照常)。
|
||||
|
||||
**③ 必须设 `LD_PRELOAD` + `TERMUX__PREFIX`(双下划线)**
|
||||
Termux 的二进制里写死了 `/data/data/com.termux/files/usr`。`libtermux-exec.so` 负责把这些路径
|
||||
重写到真实 prefix,但它认的环境变量是:
|
||||
`TERMUX__PREFIX`(**不是** `TERMUX_PREFIX`)、`TERMUX_APP__DATA_DIR`。
|
||||
少一个,bash 就会去读**别的包**的 `/etc/profile`,报 `Permission denied`。
|
||||
|
||||
**④ 脚本的 shebang 也得改**
|
||||
`bin/getprop`、`bin/pkg` 这些是 shell 脚本,第一行写死 `#!/data/data/com.termux/files/usr/bin/sh`。
|
||||
内核解析 shebang 时不会经过 termux-exec,照样 EACCES("bad interpreter")。
|
||||
安装时统一把 `bin/ libexec/` 下 79 个脚本的 shebang 前缀改成我们的 prefix 就好了。
|
||||
|
||||
### 4.5 终端界面(真终端 + 控制台退路)
|
||||
|
||||
用 Termux 自己的 `TerminalView` + `libtermux.so` 的 `forkpty` —— 真 pty、真 ANSI,
|
||||
所以 `vim`/`top` 这类全屏程序都能跑。Compose 里用 `AndroidView` 包一层,底下加了手机必备的功能键排:
|
||||
`ESC / TAB / CTRL+C / CTRL+D / ↑↓←→ / HOME / END / | / / / - / ENTER`(没这排连 vim 都退不出来)。
|
||||
|
||||
**但 pty 不是每台机器都给用**。实测 realme(Android 16)上:
|
||||
|
||||
```
|
||||
/dev/pts → Permission denied
|
||||
mount → devpts on /dev/pts type devpts (mode=600,ptmxmode=000)
|
||||
python openpty → OSError: out of pty devices
|
||||
```
|
||||
|
||||
`/dev/pts` 被挂成 `mode=600` 且 `ptmxmode=000`,应用**分配不到从设备 pty**,
|
||||
于是 TerminalSession 一起来就退出(界面上只留一句 `[Process completed]`)。
|
||||
这不是 SELinux 拒绝(logcat 里没有任何 avc),是挂载参数定的,应用侧绕不过去。
|
||||
|
||||
所以做成两条路,**自动切换**:
|
||||
|
||||
| 情况 | 走哪条 |
|
||||
|---|---|
|
||||
| pty 可用(多数设备 / 模拟器) | Termux 的 TerminalView,真终端 |
|
||||
| 会话建起来 2 秒内就退出(判定 pty 不可用) | 自动切「控制台模式」:命令框 + 输出区,跑的是**同一条 Termux bash**,只是没有 tty |
|
||||
|
||||
代价只是没有全屏 TUI 和交互式提示符,跑命令、装包(`pkg install python`)都正常。
|
||||
|
||||
### 4.6 和内核怎么接
|
||||
|
||||
内核里的 `shell` 工具优先走内置 Termux(返回里带 `via: "termux"`),
|
||||
`device` 工具的 `termux_run` / `termux_available` 也走同一条路。
|
||||
因为 Termux 现在就在本进程里,不需要跨进程 intent、也不需要用户去开 `allow-external-apps`。
|
||||
|
||||
### 4.7 安卓端其余细节(Chaquopy / 界面)
|
||||
|
||||
- **Chaquopy 17.0.0** 内嵌 CPython 3.13.9:没有 `python` 可执行文件(所以 `python_run` 是**进程内 exec**,
|
||||
不能起子进程);运行时 pip 只能装纯 Python 轮子;`mcp` 官方 SDK 用不了(要 pydantic v2)
|
||||
- **刻意不装任何第三方包**:Chaquopy 每次构建都要连云 pip,网络一抖整个 APK 就构建不出来
|
||||
(实测 `Could not find a version that satisfies the requirement requests`)。
|
||||
内核只用标准库(`urllib`/`http.server`/`json`),所以留零依赖换来"离线也能构建"。
|
||||
要 requests/numpy 就走内置 Termux:`pkg install python && pip install requests`
|
||||
- **界面**:状态栏不遮挡顶栏(`windowInsetsPadding(WindowInsets.safeDrawing)`)、
|
||||
输入框跟随输入法(`imePadding`)、深色模式自动适配
|
||||
- **流式**:Lynx 那边用 SSE;安卓原生 Compose 走的是**轮询通道**
|
||||
(`transport: "poll"` + `GET /api/chat/poll?runId=&cursor=`),
|
||||
两条件事件类型完全一致,客户端 200ms 取一次增量
|
||||
|
||||
---
|
||||
|
||||
## 5. 我实际验证了什么
|
||||
|
||||
### 5.1 安卓端(原生 Compose + 内置 Termux)
|
||||
|
||||
真机(RMX5090 / Android 16 / arm64-v8a):`node scripts/verify-phone.mjs <serial>` → **17/18**。
|
||||
模拟器(Android 14 / x86_64):17/18(唯一失败的是"定位",模拟器没有 GPS)。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 构建 | ✅ `assembleDebug` 成功,APK 88.4 MB |
|
||||
| 内核启动 | ✅ `GET /api/health` → `{"ok":true,…}` |
|
||||
| 智能体 / 工具 | ✅ 4 个智能体;8 个内置工具 + MCP 工具 |
|
||||
| 内置 Termux | ✅ 首次解压 3226 个文件 / 388 个命令 / 1146 个符号链接 |
|
||||
| shell | ✅ 真机 `Linux localhost 6.6.118-android15 … aarch64 Android`,`via: termux`,stderr 干净 |
|
||||
| pkg / apt | ✅ 可执行(79 个脚本的 shebang 已修正) |
|
||||
| python_run | ✅ CPython 3.13.9 aarch64(进程内) |
|
||||
| 联网 | ✅ urllib 与 requests 都 200 |
|
||||
| device 信息 | ✅ 型号 / 厂商 / 系统 / SDK / 存储 / 电量 |
|
||||
| 传感器 | ✅ 真机 46 个;加速度计 z≈9.7 m/s²、陀螺仪有数据 |
|
||||
| 定位 | ✅ 真机 `纬度, 经度 ±35m` |
|
||||
| MCP(Python 写的服务) | ✅ 连接 + 列工具 + 调用成功 |
|
||||
| 设置保存 | ✅ 保存前后逐字段一致(含 API Key / 系统提示词),空值攻击被忽略 |
|
||||
| 思考强度映射 | ✅ 两份内核对拍 50/50 一致 |
|
||||
| 界面 | ✅ 对话 / 抽屉 / 终端 / 设置 / 模型面板 截图见文首 |
|
||||
|
||||
### 5.2 其他平台
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 浏览器渲染 | ✅ 无头 Edge + CDP,5 个页面全部渲染,控制台无异常 |
|
||||
| 端到端工具调用 | ✅ mock 模型 → 请求 `calc` → Python 返回 → 第二轮流式回答 → 落库 |
|
||||
| Python 工具 | ✅ `calc` `now` `get_weather`(实时数据) `notes` `web_fetch` 全部通过 |
|
||||
| MCP | ✅ filesystem 14 工具、memory 9 工具连接成功;6 类校验错误全部拦截 |
|
||||
| Windows exe | ✅ 冷启动、界面渲染、内置内核、MCP 自动连接 |
|
||||
|
||||
### 5.3 没有 API Key 也能把链路跑通
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假的 OpenAI 兼容服务,监听 5299
|
||||
node scripts/verify-phone.mjs emulator-5556 # 或对真机跑
|
||||
```
|
||||
|
||||
mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式回答"来演,
|
||||
所以能验证完整的 界面 → 内核 → 工具调用 → 流式返回 链路,**不消耗任何额度**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 给 Lynx 界面(Web / exe)的注意事项
|
||||
|
||||
安卓端已经不用 Lynx 了,这一节只对 Web/exe 有效:
|
||||
|
||||
- **Fresco 必须先初始化**,否则图片不显示;**Fresco 不能解码 SVG**,图标要预先栅格化成 PNG
|
||||
- Lynx 的 `fetch` 没有 `response.body`,所以流式走轮询通道
|
||||
- 状态栏/布局用 `safe-area` 相关变量,别写死 px
|
||||
- 动画(`breathe` 那种)在某些模拟器上会破坏图片绘制,已改成不影响绘制的写法
|
||||
|
||||
---
|
||||
|
||||
## 7. 打包踩坑记录
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 389 MB)
|
||||
- **v2 架构**:exe 里带一份 **python.org 的嵌入式 Python**(`runtime/python`,约 25 MB 解压后)+
|
||||
**同安卓 App 的 Python 内核**(`runtime/kernel`)+ 网页前端(`runtime/web`)。
|
||||
构建脚本会自动下载 `python-3.13.9-embed-amd64.zip` 缓存到 `desktop/build-cache/`(已 gitignore)
|
||||
- **启动时不要再设 `ELECTRON_RUN_AS_NODE=1`**(本机环境可能全局设了它):那样 Electron 会当 Node 跑,
|
||||
报 `Cannot read properties of undefined (reading 'commandLine')`。开发调试前先清掉这个环境变量
|
||||
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||
- 数据目录默认 `%APPDATA%\Doubao\data`;自动化测试可用 `DOUBAO_USER_DATA` / `DOUBAO_DATA` 覆盖
|
||||
|
||||
### 7.2 Android APK
|
||||
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||
否则 `nativeLibraryDir` 是空的,`.so` 全在 APK 里,取 bootstrap 时得从 `applicationInfo.sourceDir` 读
|
||||
- **`targetSdk = 28`**(见 4.1),`abiFilters = ["arm64-v8a", "x86_64"]`
|
||||
- 构建脚本会把 `tools/*.py` 拷进 `app/src/main/python/` 并生成 `bundled_tool_sources.py`
|
||||
- 构建暂存目录用 ASCII 路径(`C:\DoubaoAndroid`),中文路径会让 Gradle/Chaquopy 出问题
|
||||
- **别并发跑两次 Gradle**:会互相踩坏 Chaquopy 的 venv(`Scripts/python.exe does not exist`)
|
||||
|
||||
### 7.3 Chaquopy / 内嵌 Python
|
||||
- `.pyc`-only 打包导致 `loader.get_source()` 失败 → 工具源码用 base64 内嵌
|
||||
- 每次构建都会连云 pip → 已改为零第三方依赖(见 4.7)
|
||||
|
||||
### 7.4 Android 15+ 的 edge-to-edge
|
||||
强制 edge-to-edge 后,状态栏会压住顶栏、输入法会盖住输入框。
|
||||
Compose 里统一在根布局吃 `WindowInsets.safeDrawing`,滚动页再叠 `imePadding()`。
|
||||
|
||||
### 7.5 工具链(Windows)
|
||||
- **Node 20+ 不能直接 `spawn` `.bat`/`.cmd`**(`status=null`),必须 `shell: true`
|
||||
- **PowerShell 会把命令行里的 JSON 引号搅坏**:所有内联 node/python 脚本都写成文件再跑
|
||||
- **PowerShell 的 `Get-Content` / `Set-Content` 会按 GBK 读写 UTF-8 文件**,
|
||||
一读一写就把中文文档转成乱码(本文档就被这么毁过一次)。
|
||||
改文本一律用编辑器工具,别用这两个 cmdlet 做"读进来再写回去"
|
||||
- **Kotlin 的块注释会嵌套**:在 KDoc 里写 `lib/*.so` 里的 `/*` 会开一个嵌套注释,
|
||||
把后面的代码全吞掉,报错却指向文件末尾之外的行
|
||||
|
||||
### 7.6 安卓 `org.json` 不会把 `Map` 转成 JSON 对象(踩过一次大的)
|
||||
|
||||
`json.put("speech", mapOf("autoRead" to true))` **不会**产生 `{"speech":{"autoRead":true}}`,
|
||||
而是把 Map 原样存进去,序列化出来是 `{"speech":"{autoRead=true}"}` —— **值是字符串**。
|
||||
|
||||
这一个坑连锁出四件事:
|
||||
|
||||
1. 内核把字符串写进了 `settings.json`(`speech` 本来是对象,被字符串顶掉了)
|
||||
2. 之后**每一次**读配置(`{**默认, **字符串}`)都抛 `TypeError`
|
||||
3. `/api/state` 从此永远返回 `{"error":"'str' object is not a mapping"}`
|
||||
4. App 把这个错误 JSON 解析成了「全默认状态」,而且**不抛异常**,所以还弹了"已保存"
|
||||
|
||||
用户看到的就是:**点一下语音按钮,模型变「未设置」、昵称变回「我」、会话列表全空**。
|
||||
|
||||
修了三处(缺一不可):
|
||||
- **安卓**:`patchToJson()` 显式递归把 Map/List 转成 `JSONObject`/`JSONArray`(见 `AppViewModel.kt`)
|
||||
- **内核写**:`tools`/`security`/`speech` 这几个子对象,补丁里不是字典就**直接忽略**,
|
||||
宁可这次改动不生效,也不写出读不回来的配置
|
||||
- **内核读**:发现子对象不是字典就**回落默认值**(自愈)——
|
||||
一个坏字段不该让 `/api/state` 永久 500,更不该把用户其它数据一起拖没
|
||||
|
||||
> 为什么之前没暴露:只有**嵌套对象**才触发,而在此之前 App 从没发过嵌套补丁
|
||||
> (`tools` 那两个开关从来没在设置页点过)。教训是——
|
||||
> **跨语言边界传结构化数据时,别信任何一侧的隐式转换**,两端都要有"形状不对就拒绝"的防线。
|
||||
|
||||
### 7.7 部分 ROM 会吞掉应用日志
|
||||
realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一条都看不到**。
|
||||
所以安装进度、终端会话退出原因等关键信息都**落盘**到 `files/termux-install.log`,
|
||||
用 `adb shell run-as com.doubao.lynxclone cat files/termux-install.log` 读。
|
||||
|
||||
---
|
||||
|
||||
## 8. 已知限制
|
||||
|
||||
- **`targetSdk = 28` 上不了应用商店**(个人侧载没问题)。要上架就得回到"外装 Termux + 桥接"那条路
|
||||
- **pty 在部分 ROM 上不可用**(4.5),自动降级成控制台模式,没有全屏 TUI
|
||||
- **内嵌 CPython 没有 `python` 可执行文件**,`python_run` 是进程内 exec,不能起子进程
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
- **网页版(Web/exe)**:`show_ui` / `ask_user` / `end_conversation` 已经能用(走内核的
|
||||
`/api/device/*` HTTP 队列,`wait` 语义和安卓一致);会议画布、立绘背景是二期。
|
||||
详见 `docs/网页版.md` §5.1 / §6
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发(v2:网页版 + Python 内核)
|
||||
npm start # 起内核 + 托管 web/ → http://127.0.0.1:5199/
|
||||
npm run exe # 打包 Windows exe(内嵌 Python)
|
||||
npm run apk # 构建 Android APK(--clean 可彻底重建)
|
||||
node scripts/verify-web-ui.mjs # 网页版验收:逐页截图 + 收集 JS 报错
|
||||
node scripts/verify-ui-bridge.mjs # AI 界面能力:show_ui / ask_user / end_conversation
|
||||
node scripts/scrape-doubao-web.mjs # 扒豆包网页版做视觉参考(reference/,不入库)
|
||||
|
||||
# 旧的 Lynx 版(历史留档)
|
||||
npm run install:all # 装 app(Lynx 客户端)+ server(Node 内核)依赖
|
||||
npm run start:legacy-lynx
|
||||
|
||||
# 验证
|
||||
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍(历史)
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍(历史)
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
python scripts/verify-ui-tools.py # interface 工具的参数与提示词
|
||||
python scripts/verify-extract-urls.py # 「打开网页」的链接抽取
|
||||
python scripts/verify-ai-webview.py # AI 界面里的 JS 桥
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
node scripts/mock-llm.mjs # 监听 5299
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 参考
|
||||
|
||||
- 火山方舟:<https://www.volcengine.com/docs/82379/1298454>
|
||||
- OpenAI Chat Completions:<https://platform.openai.com/docs/api-reference/chat>
|
||||
- Termux(Apache-2.0):<https://github.com/termux/termux-app>
|
||||
- Chaquopy:<https://chaquo.com/chaquopy/doc/current/>
|
||||
- 调研笔记(`docs/`):
|
||||
- `ai-chat-backend-api-research.md`(Ark/OpenAI/MCP 接口细节与证据强度)
|
||||
- `lynx-ui-research.md`(豆包界面还原的调研)
|
||||
|
||||
---
|
||||
|
||||
## 11. 许可
|
||||
|
||||
本项目采用 **MIT License**,见 [LICENSE](LICENSE)。
|
||||
|
||||
它**包含或依赖**第三方作品,各自的授权独立于 MIT,使用时请一并遵守:
|
||||
|
||||
| 组件 | 授权 | 用在哪 |
|
||||
|---|---|---|
|
||||
| [Termux](https://github.com/termux/termux-app) | **Apache-2.0** | 终端模拟器源码(vendored)+ pty 的 JNI 库 |
|
||||
| [Chaquopy](https://chaquo.com/chaquopy/) | MIT | APK 内嵌 CPython |
|
||||
| [Jetpack Compose / AndroidX](https://developer.android.com/jetpack) | Apache-2.0 | 安卓界面 |
|
||||
| [LynxJS](https://github.com/lynx-family/lynx) | Apache-2.0 | Web / 桌面版界面 |
|
||||
| [Electron](https://github.com/electron/electron) | MIT | Windows 桌面版打包 |
|
||||
|
||||
Termux 的完整许可在 `android/app/src/main/assets/TERMUX_LICENSE.txt` 与 `APACHE-2.0.txt`。
|
||||
|
||||
> **商标声明**:「豆包」是字节跳动的商标。本项目是出于学习目的的界面复刻,
|
||||
> 与字节跳动无任何关联,不含任何来自豆包 App 的代码或素材。
|
||||
> 界面配色与布局照着公开截图量出,图标使用 Material Icons。
|
||||
|
||||
> **注意**:本仓库**不包含** Termux 的 bootstrap(`libtermux-bootstrap.so`,两个 ABI 共 56 MB),
|
||||
> 因此直接 clone 下来构建 APK 会缺这个文件。补法见 §4.2 与 §4.3。
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
plugins {
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 278
|
||||
versionName = "2.0.78"
|
||||
versionCode = 351
|
||||
versionName = "2.0.151"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -57,7 +57,7 @@
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="false"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@style/AppTheme">
|
||||
BIN
豆鲍/android/app/src/main/assets/worlds/all-test.zip
Normal file
BIN
豆鲍/android/app/src/main/assets/worlds/all-test.zip
Normal file
Binary file not shown.
BIN
豆鲍/android/app/src/main/assets/worlds/old-city.zip
Normal file
BIN
豆鲍/android/app/src/main/assets/worlds/old-city.zip
Normal file
Binary file not shown.
@@ -70,11 +70,15 @@ object PhoneOps {
|
||||
private fun ensureChannel(ctx: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
if (nm.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
// ★ 不要"渠道已存在就 return":v3.17 换了 App 名之后,老用户的渠道里
|
||||
// 还留着旧描述(系统设置 → 通知里能看到)。`createNotificationChannel`
|
||||
// 用同一个 id 再调一次只会更新 name/description,不动用户改过的
|
||||
// importance,所以每次发通知前顺手刷一遍是安全的。
|
||||
// ★ CHANNEL_ID 保持 `doubao_ai`:改 id 会新建一个渠道、老渠道的设置/通知记录全丢。
|
||||
val ch = android.app.NotificationChannel(
|
||||
CHANNEL_ID, CHANNEL_NAME, android.app.NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "豆包主动发出来的提醒"
|
||||
description = "小人间主动发出来的提醒"
|
||||
enableVibration(true)
|
||||
}
|
||||
nm.createNotificationChannel(ch)
|
||||
@@ -95,7 +99,7 @@ object PhoneOps {
|
||||
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
ensureChannel(ctx)
|
||||
|
||||
val t = title.trim().ifBlank { "豆包" }
|
||||
val t = title.trim().ifBlank { "小人间" }
|
||||
val body = text.trim()
|
||||
|
||||
// 点通知打开 App
|
||||
@@ -114,7 +118,10 @@ object PhoneOps {
|
||||
android.app.Notification.Builder(ctx)
|
||||
}
|
||||
builder
|
||||
.setSmallIcon(ctx.applicationInfo.icon) // ★ 不给 smallIcon 通知**不会显示**
|
||||
// ★ v3.17 起不能再用 applicationInfo.icon:自适应图标是 108dp 的
|
||||
// 图层组合,setSmallIcon 拿到它有些机型会渲成空白。小图标要单色剪影,
|
||||
// 所以单独做了个 ic_notify(纯白房子,系统自己染色)。
|
||||
.setSmallIcon(R.drawable.ic_notify) // ★ 不给 smallIcon 通知**不会显示**
|
||||
.setContentTitle(t)
|
||||
.setContentText(body)
|
||||
.setAutoCancel(autoCancel)
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.doubao.lynxclone.data
|
||||
|
||||
/**
|
||||
* 客户端这边的超时缓存。
|
||||
*
|
||||
* ## 为什么客户端也要有一份
|
||||
*
|
||||
* 权威在**内核**(`android/kernel/timeouts.py`,界面通过 `GET /api/timeouts` 拿)。
|
||||
* 但客户端有几处**没法在用的那一刻去问内核**:
|
||||
*
|
||||
* · OkHttp 的连接池 —— 建连接时就要 readTimeout,而"去问内核"本身要用这个连接
|
||||
* · 文件选择(SAF)—— 那是系统界面的等待,内核根本不知情
|
||||
*
|
||||
* 所以这里缓存一份,App 启动时拉一次、用户改完设置再刷新一次。
|
||||
*
|
||||
* ★ 拿不到时一律回落**和内核一样的默认值** —— 不回落的话,"内核还没起来"
|
||||
* 会让连接超时变成 0(每次都断)。两边的默认值要保持一致,
|
||||
* `scripts/verify-timeouts.py` 会检查内核对不对得上。
|
||||
*/
|
||||
object AppTimeouts {
|
||||
|
||||
@Volatile
|
||||
private var values: Map<String, Double> = emptyMap()
|
||||
|
||||
/** 内核给的清单(界面上那份),缓存着免得每次进设置页都请求 */
|
||||
@Volatile
|
||||
var state: TimeoutsState = TimeoutsState()
|
||||
private set
|
||||
|
||||
fun update(next: TimeoutsState) {
|
||||
state = next
|
||||
values = next.values
|
||||
}
|
||||
|
||||
fun seconds(key: String, fallback: Double): Double {
|
||||
val v = values[key] ?: return fallback
|
||||
return if (v <= 0.0) fallback else v
|
||||
}
|
||||
|
||||
fun millis(key: String, fallbackMs: Long): Long =
|
||||
(seconds(key, fallbackMs / 1000.0) * 1000).toLong()
|
||||
|
||||
/**
|
||||
* 等用户的那两项:**0 是有意义的值**(不限时),所以不能按上面的写法回落。
|
||||
*/
|
||||
fun userWaitMillis(key: String): Long {
|
||||
val v = values[key] ?: return 0L
|
||||
return if (v <= 0.0) 0L else (v * 1000).toLong()
|
||||
}
|
||||
|
||||
/** 读 SSE 的间隔上限 —— 必须大于心跳间隔,否则等用户时连接会被自己掐掉 */
|
||||
fun sseReadSeconds(): Long = seconds("sseRead", 120.0).toLong().coerceAtLeast(20L)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
2913
豆鲍/android/app/src/main/java/com/doubao/lynxclone/data/Models.kt
Normal file
2913
豆鲍/android/app/src/main/java/com/doubao/lynxclone/data/Models.kt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -129,17 +129,21 @@ class SpeechController(
|
||||
|
||||
try {
|
||||
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"))
|
||||
}
|
||||
@@ -859,7 +859,7 @@ object TermuxInstaller {
|
||||
rc.parentFile?.mkdirs()
|
||||
rc.writeText(
|
||||
"""
|
||||
# 由豆包 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||
# 由小人间 App 生成:内置 Termux 的交互式 bash 配置(保持最小)
|
||||
export PREFIX="$prefix"
|
||||
export HOME="$home"
|
||||
export TMPDIR="$prefix/tmp"
|
||||
@@ -871,7 +871,7 @@ object TermuxInstaller {
|
||||
export COLORTERM=truecolor
|
||||
cd "${'$'}HOME" 2>/dev/null || cd /
|
||||
export PS1='\[\e[32m\]\u@termux\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '
|
||||
echo "豆包内置 Termux —— 试试 pkg install python"
|
||||
echo "小人间内置 Termux —— 试试 pkg install python"
|
||||
""".trimIndent() + "\n",
|
||||
Charsets.UTF_8,
|
||||
)
|
||||
@@ -1087,7 +1087,7 @@ object TermuxInstaller {
|
||||
conf.parentFile?.mkdirs()
|
||||
conf.writeText(
|
||||
"""
|
||||
// 由豆包 App 生成 —— 把 apt 的目录全部指到我们自己的 prefix。
|
||||
// 由小人间 App 生成 —— 把 apt 的目录全部指到我们自己的 prefix。
|
||||
//
|
||||
// 不写这份文件的话,apt 会去 /data/data/com.termux/... (真 Termux 的包名)
|
||||
// 找 apt.conf.d,读不到就报 "Unable to determine a suitable packaging
|
||||
@@ -171,7 +171,7 @@ object TermuxMirror {
|
||||
}
|
||||
|
||||
val header = listOf(
|
||||
"# 由豆包 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 由小人间 App 生成 —— 当前源:${mirror.name}",
|
||||
"# 换源:内置终端右上角「源」按钮;也可以手动改这个文件",
|
||||
)
|
||||
val lines = wanted.map { "deb ${mirror.host}/${it.path} ${it.components}" }
|
||||
@@ -378,7 +378,7 @@ fun AgentEditScreen(
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 用量 ---------------- */
|
||||
/* ---------------- 记忆 / 状态数值 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
@@ -388,11 +388,23 @@ fun AgentEditScreen(
|
||||
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 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。",
|
||||
"这是它记错时唯一的兜底。数值和状态由它绑定的世界观上的" +
|
||||
"「数值状态包」定义。",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
@@ -119,6 +119,7 @@ private const val SHIFT = 0.10f
|
||||
|
||||
@Composable
|
||||
fun AgentSelectScreen(
|
||||
vm: AppViewModel,
|
||||
agents: List<Agent>,
|
||||
activeId: String,
|
||||
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
|
||||
@@ -152,6 +153,10 @@ fun AgentSelectScreen(
|
||||
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) }
|
||||
@@ -236,6 +241,9 @@ fun AgentSelectScreen(
|
||||
picked = picked,
|
||||
onPick = { picked = it },
|
||||
state = listState,
|
||||
// ★★ 用户要求「数字界面在智能体卡片里展示」——
|
||||
// 卡片上直接显示这个角色的数值和状态,不用点进去才看得到。
|
||||
stats = vm.allStats,
|
||||
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
|
||||
)
|
||||
|
||||
@@ -430,13 +438,15 @@ private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字;当前项高亮 */
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字 + **数值/状态**;当前项高亮 */
|
||||
@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)) {
|
||||
@@ -491,6 +501,59 @@ private fun AgentList(
|
||||
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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
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
|
||||
@@ -104,13 +105,49 @@ fun AgentStatsScreen(
|
||||
Hint("身上没有状态。")
|
||||
}
|
||||
for (st in stats.statuses) {
|
||||
StatusRow(st)
|
||||
// ★ 每条状态都能**清掉**。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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +220,7 @@ private fun StatRow(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(st: StatusInstance) {
|
||||
private fun StatusRow(st: StatusInstance, onDrop: () -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -203,6 +240,10 @@ private fun StatusRow(st: StatusInstance) {
|
||||
Text(st.hint, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
// ★ 清掉。这是用户手动移除状态的**唯一出口**(AI 没这个能力)。
|
||||
// 不做二次确认:状态本来就可以再加回来,而多一层确认会让
|
||||
// "连清五个"变成五次弹窗 —— 手机上很烦。
|
||||
RowAction("清掉") { onDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +260,11 @@ private fun TinyTag(text: String) {
|
||||
)
|
||||
}
|
||||
|
||||
/** 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭 */
|
||||
private fun fmtNum(v: Double): String =
|
||||
/**
|
||||
* 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭。
|
||||
*
|
||||
* ★ 现在**两处**在用(状态数值页 + 智能体卡片),所以是 `internal` 不是 private ——
|
||||
* 卡片那边要显示同样的数字,抄一份就是第二份实现("同一逻辑只能有一份")。
|
||||
*/
|
||||
internal fun fmtNum(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -150,6 +150,7 @@ fun AppRoot(
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
// 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画
|
||||
Screen.AgentSelect -> AgentSelectScreen(
|
||||
vm = vm,
|
||||
agents = vm.agents,
|
||||
activeId = vm.state.settings.activeAgentId,
|
||||
onEnter = { vm.enterAgent(it.id) },
|
||||
@@ -174,19 +175,6 @@ fun AppRoot(
|
||||
DrawerOverlay(vm)
|
||||
}
|
||||
|
||||
if (vm.hint.isNotBlank()) {
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(24.dp)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(Color(0xE61F2329))
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- AI 主动弹出来的东西 ----------------
|
||||
*
|
||||
* ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西,
|
||||
@@ -228,15 +216,16 @@ fun AppRoot(
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
// 从抽屉挪进来的三个
|
||||
onNewGroup = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.newGroupTopic()
|
||||
},
|
||||
// 从抽屉挪进来的
|
||||
onOpenNotes = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openNotes()
|
||||
},
|
||||
// ★ v3.0 P2:容器(一局 = 世界包 + 成员)
|
||||
onOpenContainers = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openContainers()
|
||||
},
|
||||
onOpenModels = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.modelPickerOpen = true
|
||||
@@ -245,6 +234,75 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 「容器」—— v3.0 的一局 = 世界包 + 成员;数值/状态/记忆按局隔离
|
||||
AnimatedVisibility(
|
||||
visible = vm.showContainers,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
ContainerListScreen(vm = vm, onBack = { vm.closeContainers() })
|
||||
}
|
||||
|
||||
// 「容器编辑」—— 盖在容器列表上面(全屏)
|
||||
// ★ 判 `showContainerEdit` 而不是 `editingContainer != null`:
|
||||
// 新建时 editingContainer 是 null(还没有这个对象),用后者会永远打不开。
|
||||
AnimatedVisibility(
|
||||
visible = vm.showContainerEdit,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
ContainerEditScreen(vm = vm, onBack = { vm.closeContainerEdit() })
|
||||
}
|
||||
|
||||
// 「背包」—— v3.0 P3:按容器隔离的物品(用户手动使用/抛弃/赠与)
|
||||
AnimatedVisibility(
|
||||
visible = vm.bagContainerId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
BagScreen(vm = vm, onBack = { vm.closeBag() })
|
||||
}
|
||||
|
||||
// 「物品管理」—— v3.4:用户角色(用户也是角色)的背包 / 状态
|
||||
AnimatedVisibility(
|
||||
visible = vm.userItemsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
UserItemsScreen(vm = vm, onBack = { vm.closeUserItems() })
|
||||
}
|
||||
|
||||
// 「地图」—— v3.0 P4:地点 / 场景 / 在场(点地点 = 切到该地点频道)
|
||||
AnimatedVisibility(
|
||||
visible = vm.mapContainerId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MapScreen(vm = vm, onBack = { vm.closeMap() })
|
||||
}
|
||||
|
||||
// 「上下文查看器」(v3.16 用户需求):**真正送进模型的东西**
|
||||
// —— system prompt 每段 + 历史每条消息的来源与去留。
|
||||
// 入口在聊天页顶栏(「看上下文」),这个浮层盖在上面。
|
||||
AnimatedVisibility(
|
||||
visible = vm.contextViewerConvId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
ContextViewerScreen(vm = vm, onBack = { vm.closeContextViewer() })
|
||||
}
|
||||
|
||||
// 「决斗界面」(v3.17 用户需求:多回合 + 双方同意的中断 + 不开新对话)。
|
||||
// 决斗留在当前对话里,这里只是它的全屏面板;入口 = 长按 @成员 选「决斗」、
|
||||
// 聊天页的决斗条、或「我的角色」页的决斗按钮。
|
||||
AnimatedVisibility(
|
||||
visible = vm.duelScreenOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
DuelScreen(vm = vm, onBack = { vm.closeDuelScreen() })
|
||||
}
|
||||
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
AnimatedVisibility(
|
||||
visible = vm.notesOpen,
|
||||
@@ -292,6 +350,8 @@ fun AppRoot(
|
||||
onImportClick = {},
|
||||
onOpenOwn = {},
|
||||
onBackToActive = {},
|
||||
onOpenShared = {},
|
||||
onBackToPrivate = {},
|
||||
onBack = { vm.closeWorldMemories() },
|
||||
)
|
||||
}
|
||||
@@ -344,62 +404,22 @@ fun AppRoot(
|
||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||
onSetWindow = { vm.setMemoryWindow(it) },
|
||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
||||
onBackToActive = { vm.openMemories(vm.memoryAgentId, own = false) },
|
||||
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() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「新建群聊」:挑一个搭子(当前智能体当主角 = 主智能体)
|
||||
//
|
||||
// ★ 用对话框而不是全屏:这是**一次选择**(挑一个人就完了),
|
||||
// 智能体一般不超过十个,一屏放得下 —— 正是 AGENTS.md 里
|
||||
// "一次确认 / 纯菜单用弹窗"那一档。
|
||||
if (vm.pickGroupPeer) {
|
||||
val others = vm.state.agents.filter { it.id != vm.activeAgent?.id }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.cancelPickGroupPeer() },
|
||||
title = { Text("和谁一起聊") },
|
||||
text = {
|
||||
if (others.isEmpty()) {
|
||||
Text("还没有别的智能体。先去「智能体」里建一个。", fontSize = 13.sp)
|
||||
} else {
|
||||
// ★ 用全限定名:这个文件的 import 列表里没有
|
||||
// verticalScroll / rememberScrollState,
|
||||
// 而它们只在这一处用得到(别的滚动都在各自的界面文件里)
|
||||
// ★ 这层滚动用**全限定调用**:`Modifier.verticalScroll`
|
||||
// 是个扩展函数,光写名字这里解析不到,而为了它一行
|
||||
// 往这个文件顶部加 import 不划算(只此一处用得到)
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for (a in others) {
|
||||
Text(
|
||||
a.name,
|
||||
fontSize = 14.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.createGroupWith(a.id) }
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.cancelPickGroupPeer() },
|
||||
) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// [规则包编辑](v1.2 附录 D)—— 全屏
|
||||
// [世界包编辑](v3.0:世界观 + 规则包合并)—— 全屏
|
||||
AnimatedVisibility(
|
||||
visible = vm.editingRulePack != null,
|
||||
visible = vm.editingWorldPack != null,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
RulePackEditScreen(vm = vm, onBack = { vm.closeRulePackEdit() })
|
||||
WorldPackEditScreen(vm = vm, onBack = { vm.closeWorldPackEdit() })
|
||||
}
|
||||
|
||||
// 「群成员」(v1.2 §3.9)—— 用户手动增删成员无条件
|
||||
@@ -518,6 +538,37 @@ fun AppRoot(
|
||||
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(
|
||||
@@ -553,6 +604,27 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 提示条(吐司)----------------
|
||||
*
|
||||
* ★★ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -571,7 +643,7 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
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())
|
||||
Text("小人间", fontSize = 26.sp, fontWeight = FontWeight.Bold, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Icon(
|
||||
Icons.Filled.Search, "搜索", tint = doubaoText(),
|
||||
@@ -623,41 +695,53 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
|
||||
// ★ 群聊和单聊**分开列**(用户要求)。
|
||||
// ★ v3.0 P2/P5:会话**按容器分组** —— 一局就是一个分组。
|
||||
//
|
||||
// 混在一起排的时候,群聊会被一堆单聊埋到下面去 ——
|
||||
// 而这两类的**行为**本来就不一样:群聊有成员表、点名条、
|
||||
// 谁在说话跟着换;单聊只有一个主人。混在一起用户还得靠标题猜。
|
||||
//
|
||||
// 私聊记录(两个 AI 自己聊的)归到「对话」那一组 ——
|
||||
// 它没有"多个成员在群里"的语义,是两条消息流而已。
|
||||
val groups = vm.state.conversations.filter { it.isGroup }
|
||||
val singles = vm.state.conversations.filter { !it.isGroup }
|
||||
// 容器是 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)) {
|
||||
if (groups.isNotEmpty()) {
|
||||
item {
|
||||
SectionLabel("群聊", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
|
||||
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])
|
||||
}
|
||||
items(groups.size) { i -> ConversationRow(vm, groups[i]) }
|
||||
}
|
||||
item {
|
||||
SectionLabel(
|
||||
if (groups.isEmpty()) "对话" else "单聊",
|
||||
Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp),
|
||||
)
|
||||
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 (singles.isEmpty()) {
|
||||
if (vm.state.conversations.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"还没有单聊。点上面的「开启新话题」挑一个智能体。",
|
||||
"还没有任何会话。点上面的「开启新话题」挑一个智能体。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(singles.size) { i -> ConversationRow(vm, singles[i]) }
|
||||
}
|
||||
|
||||
Row(
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,380 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.BagItem
|
||||
|
||||
/**
|
||||
* [背包](v3.0 P3):一行物品按分类分组 + 用户手动操作。
|
||||
*
|
||||
* 物品是**容器隔离**的:同一个角色在世界 A 的丹药不会带到世界 B。
|
||||
* 所以这个页面必须知道"哪一局、看谁的背包"—— 进来就带好这两个参数。
|
||||
*
|
||||
* ★ 用户手动操作和 AI 走**同一个** item_engine(使用/抛弃/赠与),
|
||||
* 这里不写第二套数量逻辑 —— 两套逻辑迟早会有一份算错。
|
||||
*
|
||||
* ★ 全屏而不是弹窗(AGENTS.md):物品可能很多、要按分类滚、点开有详情。
|
||||
*/
|
||||
@Composable
|
||||
fun BagScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val container = vm.bagContainer()
|
||||
val members = container?.members ?: emptyList()
|
||||
val agents = vm.state.agents
|
||||
val agentName = agents.firstOrNull { it.id == vm.bagAgentId }?.name ?: "成员"
|
||||
|
||||
var selectedId by remember { mutableStateOf("") }
|
||||
var giveTarget by remember { mutableStateOf<String?>(null) }
|
||||
// target 类物品"对谁使用"的临时选择
|
||||
var useTarget by remember { mutableStateOf("") }
|
||||
// ★ v3.21:带材料使用(工作台这类物品要材料)
|
||||
var useWithId by remember { mutableStateOf("") }
|
||||
var useWithPicked by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
|
||||
FullScreen(
|
||||
title = "背包",
|
||||
subtitle = "${container?.name?.ifBlank { "容器" } ?: "容器"} · $agentName",
|
||||
onBack = onBack,
|
||||
) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
// ---- 成员切换(同一容器里换一个人看) ----
|
||||
if (members.size > 1) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for (aid in members) {
|
||||
val name = agents.firstOrNull { it.id == aid }?.name ?: "成员"
|
||||
val on = aid == vm.bagAgentId
|
||||
Text(
|
||||
name,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { selectedId = ""; vm.bagSwitchAgent(aid) }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vm.bagItems.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text(
|
||||
if (vm.bagLoading) "正在读背包……"
|
||||
else "这个成员还没有物品。\n世界包定义 items[].initial 之后,成员第一次进这一局就会自动发。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 20.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
// ---- 按分类分组的物品列表 ----
|
||||
val groups = vm.bagItems.groupBy { it.category.ifBlank { "其他" } }
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for ((category, items) in groups) {
|
||||
item(key = "cat-$category") { SectionLabel(category) }
|
||||
items(items, key = { it.id }) { it ->
|
||||
BagRow(
|
||||
vm = vm,
|
||||
item = it,
|
||||
expanded = selectedId == it.id,
|
||||
members = members,
|
||||
agents = agents,
|
||||
useTarget = useTarget,
|
||||
onUseTarget = { useTarget = it },
|
||||
onToggle = {
|
||||
selectedId = if (selectedId == it.id) "" else it.id
|
||||
},
|
||||
onGive = { giveTarget = it.id },
|
||||
onUseWith = { useWithId = it.id; useWithPicked = emptySet() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 赠与:选目标
|
||||
val giveItem = vm.bagItems.firstOrNull { it.id == giveTarget }
|
||||
if (giveTarget != null && giveItem != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { giveTarget = null },
|
||||
title = { Text("把「${giveItem.name}」送给谁?") },
|
||||
text = {
|
||||
Column {
|
||||
for (aid in members) {
|
||||
if (aid == vm.bagAgentId) continue
|
||||
val name = agents.firstOrNull { it.id == aid }?.name ?: "成员"
|
||||
Text(
|
||||
name,
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.bagAction(giveItem.id, "give", 1, target = name)
|
||||
giveTarget = null
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { giveTarget = null }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 带材料使用:选要一起用掉的物品(工作台这类脚本要 api.attached)
|
||||
val useWithBag = vm.bagItems.firstOrNull { it.id == useWithId }
|
||||
if (useWithBag != null) {
|
||||
val others = vm.bagItems.filter { it.id != useWithBag.id && it.count != 0 }
|
||||
AlertDialog(
|
||||
onDismissRequest = { useWithId = "" },
|
||||
title = { Text("带上材料使用「${useWithBag.name}」") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"选要一起用掉的物品(脚本通过 api.attached 读到)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
if (others.isEmpty()) {
|
||||
Text("背包里没有别的物品可带。", fontSize = 13.sp,
|
||||
color = doubaoTextSecondary())
|
||||
}
|
||||
for (o in others) {
|
||||
val on = o.id in useWithPicked
|
||||
val cnt = if (o.count < 0) "∞" else "×${o.count}"
|
||||
Text(
|
||||
(if (on) "✓ " else "") + "${o.name}$cnt",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
useWithPicked = if (on) useWithPicked - o.id
|
||||
else useWithPicked + o.id
|
||||
}
|
||||
.padding(vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.bagAction(useWithBag.id, "use", with = useWithPicked.toList())
|
||||
useWithId = ""
|
||||
}) { Text("使用") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { useWithId = "" }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BagRow(
|
||||
vm: AppViewModel,
|
||||
item: BagItem,
|
||||
expanded: Boolean,
|
||||
members: List<String>,
|
||||
agents: List<com.doubao.lynxclone.data.Agent>,
|
||||
useTarget: String,
|
||||
onUseTarget: (String) -> Unit,
|
||||
onToggle: () -> Unit,
|
||||
onGive: () -> Unit,
|
||||
onUseWith: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { onToggle() }
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
item.name,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
item.countLabel,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
KindTag(item.kindLabel)
|
||||
if (item.desc.isNotBlank()) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
item.desc,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!expanded) return@Column
|
||||
|
||||
// ---- 详情:脚本 + 用户手动操作(用户主权)----
|
||||
if (item.script.isNotBlank()) {
|
||||
Text("脚本:${item.script}", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
if (item.used > 0) {
|
||||
Text("累计用过 ${item.used} 次", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (item.usable) {
|
||||
if (item.kind == "target") {
|
||||
// 目标类:先选一个同容器成员(默认第一个别人)
|
||||
val others = members.filter { it != vm.bagAgentId }
|
||||
val chosen = useTarget.ifBlank { others.firstOrNull() ?: "" }
|
||||
val chosenName = agents.firstOrNull { it.id == chosen }?.name ?: "无目标"
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable {
|
||||
if (others.isEmpty()) return@clickable
|
||||
val idx = others.indexOf(chosen)
|
||||
onUseTarget(others[(idx + 1) % others.size])
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text("目标:$chosenName ⇄", fontSize = 12.sp, color = doubaoText())
|
||||
}
|
||||
Text(
|
||||
"使用",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable(enabled = chosen.isNotBlank()) {
|
||||
val target = agents.firstOrNull { it.id == chosen }?.name ?: ""
|
||||
vm.bagAction(item.id, "use", targets = listOf(target))
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
"使用",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable { vm.bagAction(item.id, "use") }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
// ★ v3.21:带材料使用(工作台这类物品要材料)
|
||||
Text(
|
||||
"带材料用",
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onUseWith() }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"抛弃 1 个",
|
||||
fontSize = 13.sp,
|
||||
color = Color(0xFFD93025),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.clickable { vm.bagAction(item.id, "drop", 1) }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
Text(
|
||||
"赠与",
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.clickable(enabled = members.any { it != vm.bagAgentId }) { onGive() }
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 类型标签(主动 / 被动 / 目标 / 无脚本) */
|
||||
@Composable
|
||||
private fun KindTag(label: String) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(5.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.padding(horizontal = 5.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
144
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/ChatDuel.kt
Normal file
144
豆鲍/android/app/src/main/java/com/doubao/lynxclone/ui/ChatDuel.kt
Normal file
@@ -0,0 +1,144 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* ★ v3.17:聊天页的**决斗条**(用户要求「决斗加个ui但不开新对话,和私密一样」)。
|
||||
*
|
||||
* 决斗绑**当前对话**、不另开会话 —— 这条就是它的状态条:
|
||||
* · 进行中:`阿玄 vs 豆包 · 决斗中 · 第 2/6 回合` + 「出招」(推进一回合)
|
||||
* · 有罢手请求在等用户回应:`「豆包」请求罢手` + 「回应」
|
||||
* · 刚结束/中断:结果一行 + 「关闭」(关掉就不再占地方)
|
||||
* 点条子本身进**决斗界面**(双方数值/状态/回合日志都在那里)。
|
||||
*
|
||||
* ★ 只放"最常用的一步"在条上:出招。请求罢手 / 同意 / 拒绝
|
||||
* 都放决斗界面里 —— 条上塞三个按钮会把标题挤成省略号。
|
||||
*/
|
||||
@Composable
|
||||
fun DuelBar(vm: AppViewModel) {
|
||||
val d = vm.duel ?: return
|
||||
val running = d.running
|
||||
val accent = when {
|
||||
d.interrupted -> Color(0xFF8A6100)
|
||||
running -> Color(0xFFB3261E)
|
||||
else -> doubaoTextSecondary()
|
||||
}
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(accent.copy(alpha = 0.10f))
|
||||
.clickable { vm.openDuelScreen() }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
when {
|
||||
running -> "${d.title()} · ${d.statusText()}"
|
||||
d.interrupted -> "双方停手:${d.result.ifBlank { d.title() }}"
|
||||
else -> "决斗结果(${d.outcomeText().ifBlank { "平局" }}):" +
|
||||
d.result.ifBlank { d.title() }
|
||||
},
|
||||
fontSize = 12.sp,
|
||||
color = accent,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 2,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
when {
|
||||
vm.duelBusy -> Text("…", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
running && d.needsMyAnswer -> DuelChip("回应", accent) { vm.openDuelScreen() }
|
||||
running && d.status == "active" -> DuelChip("出招", accent) { vm.advanceDuel() }
|
||||
running -> Text("等对方回应…", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
else -> DuelChip("关闭", doubaoTextSecondary()) { vm.dismissDuel() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 决斗条上的小按钮 */
|
||||
@Composable
|
||||
private fun DuelChip(text: String, color: Color, onClick: () -> Unit) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 12.sp,
|
||||
color = color,
|
||||
fontWeight = FontWeight.Medium,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(color.copy(alpha = 0.12f))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 3.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.17:**长按 @某人** 弹出的动作菜单(用户要求「长按@XX可选私聊和决斗」)。
|
||||
*
|
||||
* 就两个入口,点完就走 —— 按项目约定这种纯菜单用 AlertDialog 是合适的
|
||||
* (列表/配置那种才必须开全屏)。
|
||||
*/
|
||||
@Composable
|
||||
fun MemberActionDialog(vm: AppViewModel) {
|
||||
if (vm.memberMenuAgentId.isBlank()) return
|
||||
val name = vm.memberMenuAgentName
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.closeMemberMenu() },
|
||||
title = { Text("对「$name」") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"🔒 私聊:接下来你发的消息只有 TA 能看到(不另开会话)",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"决斗:在当前对话里开一场一对一决斗,回合由世界脚本裁决;" +
|
||||
"想中断得双方都同意。必须有武器 —— 武器是 target 类物品" +
|
||||
"(能对别人用的东西),没有的一方会被直接判失败。",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"每回合双方各用自己的武器出手一次(跑物品脚本,∞ 武器不消耗)," +
|
||||
"决斗界面里可以每回合换武器;没有回合上限。" +
|
||||
"结果只有四种:赢 / 输 / 平局 / 停手。",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { vm.memberMenuPrivate() }) {
|
||||
Text("私聊")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { vm.memberMenuDuel() }) {
|
||||
Text("决斗")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -26,6 +26,7 @@ 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.verticalScroll
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
@@ -34,6 +35,8 @@ 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.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
@@ -271,7 +274,7 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
// 用户的原话是「还是没换标题和背景呀」:寐眠在说话,
|
||||
// 顶栏和背景就该都是寐眠。两处各取各的必然对不上。
|
||||
val shown = backdropAgent(vm)
|
||||
ChatHeader(vm, shown?.name ?: (agent?.name ?: "豆包"), speech)
|
||||
ChatHeader(vm, shown?.name ?: (agent?.name ?: "小人间"), speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
|
||||
@@ -289,7 +292,7 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
(tagline.endsWith("。") || tagline.endsWith("!") ||
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "小人间"},有什么可以帮你的吗?"
|
||||
// ★ 这里原来还有一个 168dp 的圆形立绘(ChatPortrait)——
|
||||
// 背景层(ChatBackdrop)接手之后它就是多余的:两张同一个人的图
|
||||
// 叠在一起,而且圆形 Crop 会把全身图裁到腰上,很难看。
|
||||
@@ -324,7 +327,7 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
listOf("对话", "AI创作", "出行用豆包", "豆包").forEach { label ->
|
||||
listOf("对话", "AI创作", "陪我聊聊", "小人间").forEach { label ->
|
||||
DoubaoPill(text = label, onClick = { vm.draft = label })
|
||||
}
|
||||
}
|
||||
@@ -335,9 +338,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
// ★ 私聊记录是**只读**的(v1.2 §3.9 形态 B)——那两个 AI 是
|
||||
// 在你不在场的时候聊的,往里插话等于改历史记录。
|
||||
// 这里把输入条整条换掉,而不是"能输入但发不出去"。
|
||||
val privateConv = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId }?.isPrivate == true
|
||||
if (privateConv) {
|
||||
// ★ v3.15:只读的是**两个 AI 幕后对聊的记录**;
|
||||
// 老版本「成员 → 私聊」建的那种用户私聊现在是可输入的。
|
||||
val privateRecord = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId }?.isPrivateRecord == true
|
||||
if (privateRecord) {
|
||||
Box(Modifier.weight(1f))
|
||||
Hint("这是两个智能体的私聊记录,只读。想让他们再聊一次,去「群成员」页。")
|
||||
} else if (vm.conversationEnded) {
|
||||
@@ -358,6 +363,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
onNewConversation = { vm.newTopic() },
|
||||
)
|
||||
}
|
||||
} else if (vm.alonePlaceName().isNotBlank()) {
|
||||
// ★★ v3.16 用户要求:「只有用户在只有用户一个人的地点时不准对话」。
|
||||
// 整条输入条不渲染(而不是"能输入、点了被拒绝")——
|
||||
// 内核那道 is 权威(会回 alone_place 错误),这里是提前拦截。
|
||||
AlonePlaceBar(vm, vm.alonePlaceName())
|
||||
} else {
|
||||
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
|
||||
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
|
||||
@@ -383,6 +393,15 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
// 而且它只在有待决移交时才出现。
|
||||
HandoffBar(vm)
|
||||
GroupQuickBar(vm)
|
||||
// ★ v3.17:决斗条(进行中 / 刚结束)—— 决斗留在当前对话里,不开新会话。
|
||||
// 位置在 @ 条和私聊条之间:它和它们一样是"这一轮怎么说话"的状态条。
|
||||
DuelBar(vm)
|
||||
// ★ v3.15:私聊模式标记条(用户要求「在聊天框中有标记」)
|
||||
PrivateChatBar(vm)
|
||||
// ★ v3.17:长按 @某人 弹出的动作菜单(私聊 / 决斗)
|
||||
MemberActionDialog(vm)
|
||||
// ★ v3.2:地点切换器(聊天页顶栏点地点名打开;切换只移动,不新建对话)
|
||||
PlacePickerDialog(vm)
|
||||
SessionUsageBar(vm)
|
||||
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
|
||||
// 只拦不给入口的话,用户会以为这个智能体坏了。
|
||||
@@ -430,12 +449,29 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
// 整条锁掉的话,用户只能干看着一个群不能用 ——
|
||||
// 用户报的「角色死亡输入框怎么不能用了」就是这个。
|
||||
// 群聊里只留一条提示,输入框照给。
|
||||
val deadAgent = vm.activeAgent
|
||||
val dead = deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true
|
||||
// ★ v3.26:用**当前对话/当前发言者**(和顶栏标题同一个人),
|
||||
// 不是全局 activeAgent —— 切到另一个人的会话后,全局那个可能还是
|
||||
// 上一个人(他死了 → 这边就"假死",锁住输入框)。
|
||||
val deadAgent = backdropAgent(vm)
|
||||
val dead = deadAgent != null && vm.emotionOf(deadAgent.id)?.dead == true
|
||||
val convNow = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
val groupNow = convNow?.isGroup == true
|
||||
if (dead && !groupNow) {
|
||||
// ★ v3.27:**用户角色死亡 = 这一局游戏结束**(内核 /api/state 的派生字段;
|
||||
// 复活后自动恢复)。游戏结束时**不再给输入框** —— 内核也会拦,
|
||||
// 但让用户敲完再被拒绝是最差的体验。
|
||||
val containerNow = vm.state.containers
|
||||
.firstOrNull { it.id == convNow?.containerId.orEmpty() }
|
||||
val gameOverText = if (containerNow?.gameOver == true) {
|
||||
containerNow.gameOverText.ifBlank { "这一局已结束:你的角色已死亡" }
|
||||
} else {
|
||||
""
|
||||
}
|
||||
if (gameOverText.isNotBlank()) {
|
||||
GameOverBar(gameOverText) {
|
||||
vm.reviveUserIn(convNow?.containerId.orEmpty())
|
||||
}
|
||||
} else if (dead && !groupNow) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -458,7 +494,12 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { deadAgent?.let { vm.openMemories(it.id) } }
|
||||
.clickable {
|
||||
deadAgent?.let {
|
||||
// ★ 从聊天页进 = 看**当前这一局**的记忆
|
||||
vm.openMemories(it.id, containerId = vm.currentContainerId())
|
||||
}
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
@@ -528,7 +569,7 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
|
||||
// 这里 path 为空就还是原来的图标)
|
||||
// ★ 跟**同一个人**:名字是寐眠、头像却是小黑,用户一眼就看出不对
|
||||
val art = backdropAgent(vm)?.image?.portrait.orEmpty()
|
||||
val art = vm.portraitOf(backdropAgent(vm))
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
@@ -550,7 +591,8 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
// ★ v1.2:这里显示的是 **preset(五档)**,不是那句自由文本 ——
|
||||
// 自由文本是角色的内心独白,摆在顶栏上不合适;preset 才是
|
||||
// "一眼看出他现在什么情绪"那个粒度。点开记忆页能看到全文。
|
||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""]
|
||||
// ★ v3.26:和顶栏名字同一个人(切换会话后 activeAgent 可能是旧的)
|
||||
val emo = vm.emotionOf(backdropAgent(vm)?.id ?: "")
|
||||
val emoLabel = emo?.preset.orEmpty()
|
||||
if (emoLabel.isNotBlank() && emoLabel != "平常") {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
@@ -569,26 +611,139 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
}
|
||||
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 "已关闭自动朗读")
|
||||
// ★ v3.25:顶栏图标太多(回看/我的角色/地图/上下文/朗读 5 个挤在一行),
|
||||
// 用户原话「太多东西了。搞个下拉框」——收进一个「更多」下拉菜单。
|
||||
// 菜单是"两三个入口点完就走"的场景,按 AGENTS 的界面约定保留弹层即可。
|
||||
var moreOpen by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
HeaderIcon(Icons.Filled.MoreVert, "更多") { moreOpen = true }
|
||||
DropdownMenu(
|
||||
expanded = moreOpen,
|
||||
onDismissRequest = { moreOpen = false },
|
||||
) {
|
||||
if (vm.currentPlaceId.isNotBlank()) {
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
if (vm.showAllHistory) "只看进入之后的记录"
|
||||
else "回看这个地点的历史",
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
moreOpen = false
|
||||
vm.toggleHistoryAll()
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text("我的角色") },
|
||||
onClick = {
|
||||
moreOpen = false
|
||||
val cid = vm.currentContainerId()
|
||||
if (cid.isBlank()) vm.showHint("这个会话还没有归属容器,角色按局算")
|
||||
else vm.openUserItems(cid)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("地图") },
|
||||
onClick = {
|
||||
moreOpen = false
|
||||
val cid = vm.currentContainerId()
|
||||
if (cid.isBlank()) vm.showHint("这个会话还没有归属容器,没有地图")
|
||||
else vm.openMap(cid)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("上下文查看器") },
|
||||
onClick = {
|
||||
moreOpen = false
|
||||
vm.openContextViewer()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(if (speech.autoRead) "自动朗读:已开" else "自动朗读:已关")
|
||||
},
|
||||
onClick = {
|
||||
moreOpen = false
|
||||
val next = !speech.autoRead
|
||||
speech.autoRead = next
|
||||
vm.setAutoRead(next)
|
||||
vm.showHint(if (next) "新回复会自动朗读" else "已关闭自动朗读")
|
||||
},
|
||||
)
|
||||
// ★ v3.27:用户问「播放按钮咋没啦」——
|
||||
// v3.25 把顶栏图标收进 ⋮ 后,"朗读"入口只能去消息底部找,
|
||||
// 长消息一滚就看不见了。这里加一个**固定入口**:
|
||||
// "朗读最后一条回复"(正在念这条时变成"停止朗读"),
|
||||
// 不用滚到底也能听;每条消息下方的 🔊 按钮照旧保留。
|
||||
val lastSpeakIndex = vm.messages.indexOfLast {
|
||||
it.role == "assistant" && it.content.isNotBlank() && !it.pending
|
||||
}
|
||||
if (lastSpeakIndex >= 0) {
|
||||
val speakingThis = speech.speakingIndex == lastSpeakIndex
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (speakingThis) "停止朗读" else "朗读最后一条回复") },
|
||||
onClick = {
|
||||
moreOpen = false
|
||||
val m = vm.messages[lastSpeakIndex]
|
||||
speech.speak(m.content, lastSpeakIndex, m.agentId)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"AI 生成可能有误 注意核实",
|
||||
// ★ v3.0 P2/P4 / v3.2:当前在哪一局、哪个地点 —— 数值 / 状态 / 记忆都按局算,
|
||||
// 历史可见性按地点算,用户得能一眼看到"我现在在哪"。
|
||||
// ★ v3.2:地点名**可点击切换**(用户要求「在聊天中显示地点且可切换」,
|
||||
// 切换只是移动自己,**不新建对话**)。
|
||||
val containerName = vm.currentContainerName()
|
||||
val placeName = vm.currentPlaceName
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (containerName.isNotBlank()) {
|
||||
Text(
|
||||
"「$containerName",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
if (placeName.isNotBlank()) {
|
||||
Text(" · ", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
} else if (placeName.isNotBlank()) {
|
||||
Text("「", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
if (placeName.isNotBlank()) {
|
||||
Text(
|
||||
placeName,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
fontWeight = FontWeight.Medium,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.clickable { vm.openPlacePicker() }
|
||||
.padding(horizontal = 3.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
if (containerName.isNotBlank() || placeName.isNotBlank()) {
|
||||
Text("」", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
Text(
|
||||
" · AI 生成可能有误 注意核实",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
"AI 生成可能有误 注意核实",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,10 +852,19 @@ private fun backdropAgent(vm: AppViewModel): Agent? {
|
||||
@Composable
|
||||
private fun ChatBackdrop(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm)
|
||||
// ★ v3.0 P4:地点背景优先 —— "场景是谁的地盘就是谁的"(设计 §6.6)
|
||||
val placeBg = vm.currentPlace()?.background.orEmpty()
|
||||
val back = who?.image?.back.orEmpty()
|
||||
val art = who?.image?.portrait.orEmpty()
|
||||
if (back.isBlank() && art.isBlank()) return
|
||||
val art = vm.portraitOf(who)
|
||||
if (placeBg.isBlank() && back.isBlank() && art.isBlank()) return
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
if (placeBg.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = placeBg,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
if (back.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = back,
|
||||
@@ -731,7 +895,7 @@ private fun ChatBackdrop(vm: AppViewModel) {
|
||||
@Composable
|
||||
private fun PortraitHint(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm) ?: return
|
||||
if (who.image.portrait.isNotBlank()) return
|
||||
if (vm.portraitOf(who).isNotBlank()) return
|
||||
Text(
|
||||
"还没有立绘 · 点这里去传一张",
|
||||
fontSize = 11.sp,
|
||||
@@ -864,6 +1028,15 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
// ★ v3.15:私聊消息在气泡上标出来(「在聊天框中有标记」)
|
||||
if (msg.privateTo.isNotEmpty()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"🔒 私聊(只有 ${privateTargetNames(vm, msg)} 能看到)",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
@@ -872,6 +1045,15 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||
// 群聊里标出**这条是谁说的**(用户要求:「对话前面写明是谁在说话」)
|
||||
SpeakerTag(vm, msg, mine = false)
|
||||
// ★ v3.15:私聊消息标出来(其他人看不到这条)
|
||||
if (msg.privateTo.isNotEmpty()) {
|
||||
Text(
|
||||
"🔒 私聊(只有 ${privateTargetNames(vm, msg)} 能看到)",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.padding(start = 4.dp, bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
|
||||
val hasReasoning = msg.reasoning.isNotBlank()
|
||||
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||
@@ -973,6 +1155,9 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
color = doubaoText(),
|
||||
fontSize = 16,
|
||||
lineHeight = 26,
|
||||
// ★ v3.27:设置开着「朗读情绪指令」时,回复里的(旁白)
|
||||
// 显示成灰色小字(和朗读那边同一套括号规则)
|
||||
stageTags = vm.state.speech.emotionTags,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1184,6 +1369,52 @@ private fun SessionUsageBar(vm: AppViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.27:用户角色死亡 → **这一局游戏结束**。
|
||||
*
|
||||
* 用户反馈:「用户角色死亡为啥还能说话,直接宣布这个容器游戏结束」。
|
||||
* 这里是"宣布":聊天页底部一条醒目的结束横幅,**不再给输入框**;
|
||||
* 点「复活」把用户角色情绪改回「平常」后这一局自动恢复(内核的
|
||||
* `gameOver` 是从死亡状态派生的,复活即解除)。
|
||||
*/
|
||||
@Composable
|
||||
private fun GameOverBar(text: String, onRevive: () -> Unit) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AD93025))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"🏁 游戏结束",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
"复活 ›",
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable(onClick = onRevive)
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"$text —— 这一局不能再说话了;不想继续就新开一局。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputBar(
|
||||
vm: AppViewModel,
|
||||
@@ -1282,11 +1513,27 @@ private fun InputBar(
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
|
||||
if (vm.draft.isEmpty()) {
|
||||
Text("发消息或按住说话…", fontSize = 15.sp, color = Doubao.TextTertiary)
|
||||
Text(
|
||||
if (vm.state.containers.any { it.worldPackId.isNotBlank() }) {
|
||||
"发消息或按住说话…(打 > 找常驻角色办事)"
|
||||
} else {
|
||||
"发消息或按住说话…"
|
||||
},
|
||||
fontSize = 15.sp, color = Doubao.TextTertiary,
|
||||
)
|
||||
}
|
||||
BasicTextField(
|
||||
value = vm.draft,
|
||||
onValueChange = { vm.draft = it },
|
||||
onValueChange = { v ->
|
||||
// ★ v3.30:输入框里打 `>` → 打开常驻角色菜单(用户要求的界面入口)。
|
||||
// 只在"刚打出来"时触发:清空输入框、弹菜单,不把 `>` 当消息存草稿。
|
||||
if (v == ">" || (v.startsWith(">") && vm.draft.isEmpty())) {
|
||||
vm.draft = ""
|
||||
vm.openResidentMenu()
|
||||
} else {
|
||||
vm.draft = v
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = TextStyle(fontSize = 15.sp, color = doubaoText()),
|
||||
cursorBrush = SolidColor(Doubao.Blue),
|
||||
@@ -1296,6 +1543,19 @@ private fun InputBar(
|
||||
)
|
||||
}
|
||||
if (!canSend) {
|
||||
// ★ v3.30:常驻角色入口(和输入框打 `>` 等价;有世界包时才有意义)
|
||||
if (vm.state.containers.any { it.worldPackId.isNotBlank() }) {
|
||||
Text(
|
||||
">",
|
||||
fontSize = 18.sp,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { vm.openResidentMenu() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.Filled.Mic, "语音输入", tint = doubaoText(),
|
||||
modifier = Modifier.size(22.dp).clickable(onClick = onMic),
|
||||
@@ -1461,13 +1721,138 @@ private fun HandoffBar(vm: AppViewModel) {
|
||||
* ★ 只有群聊才显示。单聊显示一排"只有一个人"的头像没有意义,
|
||||
* 而且会白占一行高度。
|
||||
*/
|
||||
/**
|
||||
* ★ v3.15:**私聊模式标记条**(用户要求「在聊天框中有标记」)。
|
||||
*
|
||||
* 长按底部 `@某人` 进入;它只影响**接下来发的消息** ——
|
||||
* 不另开会话,消息还在当前对话里,只是别的角色看不到。
|
||||
* 点「退出」回到正常群聊发言。
|
||||
*/
|
||||
@Composable
|
||||
private fun PrivateChatBar(vm: AppViewModel) {
|
||||
if (vm.privateChatTargetId.isBlank()) return
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"🔒 私聊 · ${vm.privateChatTargetName}(只有 TA 能看到)",
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"退出",
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.clickable { vm.exitPrivateChat() }
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** ★ v3.15:私聊消息「谁能看到」的名字(气泡标签用) */
|
||||
@Composable
|
||||
private fun privateTargetNames(vm: AppViewModel, msg: ChatMessage): String {
|
||||
val names = msg.privateTo.mapNotNull { id ->
|
||||
vm.state.agents.firstOrNull { it.id == id }?.name
|
||||
}
|
||||
return if (names.isEmpty()) "TA" else names.joinToString("、")
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ v3.16 用户要求:「只有用户在只有用户一个人的地点时不准对话」。
|
||||
*
|
||||
* 界面上把**整条输入条**换掉(而不是"能输入、发出去报错")——
|
||||
* 用户不用敲完一整句话才发现发不出去。内核那道拦截才是权威
|
||||
* (界面数据可能旧了,所以两边都有)。
|
||||
*
|
||||
* 给出路:打开地图 —— 去一个有人的地点,或者把角色移到你这里。
|
||||
*/
|
||||
@Composable
|
||||
private fun AlonePlaceBar(vm: AppViewModel, placeName: String) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0x1AD93025))
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"🚫「$placeName」这里只有你一个人,没人和你说话。",
|
||||
fontSize = 12.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"打开地图 ›",
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable {
|
||||
val cid = vm.currentContainerId()
|
||||
if (cid.isBlank()) vm.showHint("这个会话还没有归属容器,没有地图")
|
||||
else vm.openMap(cid)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"去一个有角色在场的地点,或者在地图里把角色移到你这里,才能开始对话。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
// ★★ v3.30(用户要求):「有常驻角色但没正常角色的地方无法对话,
|
||||
// 但可以和常驻角色交互」—— 独自一人只是**不能聊天**,不是整条输入条都废掉。
|
||||
// 这里给出常驻角色入口(菜单会按当前地点过滤;没有会说清"别处还有几个")。
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"这里没有 AI 角色和你说话,但常驻角色(店员/门卫/守林人…)可以办事。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"找常驻角色 ›",
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFF2563EB))
|
||||
.clickable { vm.openResidentMenu() }
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GroupQuickBar(vm: AppViewModel) {
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
|
||||
if (conv == null || !conv.isGroup) return
|
||||
val members = conv.participants.mapNotNull { id ->
|
||||
vm.state.agents.firstOrNull { it.id == id }?.let { id to it.name }
|
||||
}
|
||||
// ★ v3.11:单聊也显示(旧地点对话是单聊);私聊保持一对一,不显示成员条
|
||||
if (conv == null || conv.isPrivate) return
|
||||
// ★ v3.2:只列**当前地点在场**的成员(用户反馈"不同地方的智能体挤在一起");
|
||||
// 位置未知(老数据)时 coLocatedMembers 会退回全体,不会把条子变空。
|
||||
val members = vm.coLocatedMembers(conv)
|
||||
// ★ v3.12:这个地点没人 → 不显示 @ 条(和地图"这里没有别人"一致)
|
||||
if (members.isEmpty()) return
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -1481,7 +1866,13 @@ private fun GroupQuickBar(vm: AppViewModel) {
|
||||
for (pair in members) {
|
||||
// 只插草稿 —— **不碰顶栏/背景**。那两处等内核仲裁完
|
||||
// (`speaker` 事件)才切,不然会"点了还没发就换了人"
|
||||
DoubaoPill(text = "@${pair.second}", onClick = { vm.mentionAgent(pair.second) })
|
||||
// ★ v3.17:**长按 @某人 → 私聊 / 决斗 二选一**(v3.15 只有私聊)。
|
||||
// 两个都不开新会话,留在当前对话里。
|
||||
DoubaoPill(
|
||||
text = "@${pair.second}",
|
||||
onClick = { vm.mentionAgent(pair.second) },
|
||||
onLongClick = { vm.openMemberMenu(conv.id, pair.first) },
|
||||
)
|
||||
}
|
||||
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
|
||||
//
|
||||
@@ -1503,4 +1894,51 @@ private fun GroupQuickBar(vm: AppViewModel) {
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 地点切换器(v3.2)。
|
||||
*
|
||||
* ★ 用户要求:「切换地点不需要新建对话,要在聊天中显示地点且可切换」。
|
||||
* 点一下 = 把自己移过去 + 重载对话视图(消息按新地点过滤),
|
||||
* **不新建会话** —— 会话还是同一个,只是"我现在在另一个地方"。
|
||||
* ★ 列表来自当前这一局用的世界包(`placesOfCurrentContainer`),隐藏地点不列。
|
||||
*/
|
||||
@Composable
|
||||
private fun PlacePickerDialog(vm: AppViewModel) {
|
||||
if (!vm.placePickerOpen) return
|
||||
val places = vm.placesOfCurrentContainer()
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.closePlacePicker() },
|
||||
title = { Text("切换地点") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (places.isEmpty()) {
|
||||
Text("这一局没有地点定义。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (p in places) {
|
||||
val here = p.id == vm.currentPlaceId
|
||||
Text(
|
||||
(if (here) "✓ " else "") + p.name +
|
||||
(if (p.category.isNotBlank()) "(${p.category})" else ""),
|
||||
fontSize = 15.sp,
|
||||
color = if (here) Doubao.Blue else doubaoText(),
|
||||
fontWeight = if (here) FontWeight.Medium else FontWeight.Normal,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.switchPlace(p.id)
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.closePlacePicker() },
|
||||
) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* [容器编辑](v3.0 P2):名字 / 世界包 / 成员。
|
||||
*
|
||||
* 容器 = 一局:世界包 + 成员。数值 / 状态 / 情绪 / 记忆都攒在这一局里,
|
||||
* 所以这里选什么,直接决定"进去之后看到哪套规则、读写哪份记忆"。
|
||||
*
|
||||
* ★ 全屏而不是弹窗(AGENTS.md):字段有三组,弹窗里要滚,还会盖住列表。
|
||||
*
|
||||
* ★ 删除的级联写清楚:**这局里的会话一起删、数值状态记忆一起消失**,
|
||||
* 但智能体本身不会删。用户点删除前必须知道这些 —— 否则删完才发现
|
||||
* "运营了一个月的数值没了",那是一次不可逆的信任损失。
|
||||
*/
|
||||
@Composable
|
||||
fun ContainerEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val editing = vm.editingContainer
|
||||
var name by remember(editing?.id) { mutableStateOf(editing?.name ?: "") }
|
||||
var worldPackId by remember(editing?.id) { mutableStateOf(editing?.worldPackId ?: "") }
|
||||
var members by remember(editing?.id) {
|
||||
mutableStateOf((editing?.members ?: emptyList()).toSet())
|
||||
}
|
||||
// ★ v3.4:用户角色(这一局里"用户"是谁 —— 注入给每个成员)
|
||||
var userName by remember(editing?.id) { mutableStateOf(editing?.userName ?: "") }
|
||||
var userDesc by remember(editing?.id) { mutableStateOf(editing?.userDesc ?: "") }
|
||||
var confirmDelete by remember { mutableStateOf(false) }
|
||||
val packs = vm.state.worldviews
|
||||
val agents = vm.state.agents
|
||||
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
|
||||
FullScreen(
|
||||
title = if (editing == null) "新建容器" else "编辑容器",
|
||||
subtitle = "数值 / 状态 / 情绪 / 记忆都攒在这一局里",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (editing != null) {
|
||||
TopTextAction("删除", danger = true) { confirmDelete = true }
|
||||
}
|
||||
TopAction("保存", enabled = name.isNotBlank()) {
|
||||
vm.saveContainer(
|
||||
name = name.trim(),
|
||||
worldPackId = worldPackId,
|
||||
members = members.toList(),
|
||||
existingId = editing?.id,
|
||||
userName = userName.trim(),
|
||||
userDesc = userDesc.trim(),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
SectionLabel("名称")
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it.take(40) },
|
||||
singleLine = true,
|
||||
placeholder = { Text("比如:九州 · 第一局") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
SectionLabel("世界包")
|
||||
Text(
|
||||
"选了世界包,这一局才有数值 / 状态 / 脚本;不选就是普通单聊容器。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
PackChip(
|
||||
label = "无(单聊容器)",
|
||||
selected = worldPackId.isBlank(),
|
||||
) { worldPackId = "" }
|
||||
packs.forEach { w ->
|
||||
PackChip(
|
||||
label = w.name.ifBlank { "未命名世界包" },
|
||||
selected = worldPackId == w.id,
|
||||
) { worldPackId = w.id }
|
||||
}
|
||||
}
|
||||
|
||||
SectionLabel("你的角色(用户)")
|
||||
Text(
|
||||
"这一局里「你」是谁 —— 名字和介绍会注入给每个成员," +
|
||||
"让它们知道面前站着的是谁(不同容器可以不同)。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = userName,
|
||||
onValueChange = { userName = it.take(20) },
|
||||
singleLine = true,
|
||||
placeholder = { Text("名字,比如:阿玄(留空就是「用户」)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = userDesc,
|
||||
onValueChange = { userDesc = it.take(300) },
|
||||
placeholder = { Text("介绍(可空):身份 / 性格 / 和它们的关系") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
SectionLabel("成员")
|
||||
Text(
|
||||
"同一批智能体可以在多局里,但每局的数值 / 状态 / 记忆各自独立互不干扰。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
if (agents.isEmpty()) {
|
||||
Text("还没有智能体", fontSize = 13.sp, color = doubaoTextDim())
|
||||
}
|
||||
agents.forEach { a ->
|
||||
val on = a.id in members
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (on) doubaoAccentSoft() else doubaoCard())
|
||||
.clickable {
|
||||
members = if (on) members - a.id else members + a.id
|
||||
}
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (on) "✓ " else "○ ",
|
||||
fontSize = 14.sp,
|
||||
color = if (on) Doubao.Blue else doubaoTextDim(),
|
||||
)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
a.name.ifBlank { "未命名" },
|
||||
fontSize = 14.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (a.greeting.isNotBlank()) {
|
||||
Text(
|
||||
a.greeting,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmDelete) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = false },
|
||||
title = { Text("删除这个容器?") },
|
||||
text = {
|
||||
Text(
|
||||
"这一局里的**所有会话**会一起删掉,数值 / 状态 / 记忆也跟着消失。" +
|
||||
"智能体本身不会被删。",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmDelete = false
|
||||
editing?.id?.let { vm.deleteContainer(it) }
|
||||
},
|
||||
) {
|
||||
Text("删除", color = Color(0xFFD93025))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmDelete = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 世界包选择胶囊 */
|
||||
@Composable
|
||||
private fun PackChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (selected) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (selected) Doubao.Blue else doubaoCard())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.ContainerItem
|
||||
|
||||
/**
|
||||
* [容器] 列表页(v3.0 P2)。
|
||||
*
|
||||
* 容器 = **一局**:世界包 + 成员。数值 / 状态 / 情绪 / 记忆都按它隔离 ——
|
||||
* 同一批智能体可以在不同容器里互不干扰(这是 v3.0 的核心)。
|
||||
*
|
||||
* 这个页面回答两个问题:
|
||||
* 1. 现在有哪几局?每局在哪个世界、里面有谁?
|
||||
* 2. 怎么进某一局聊天 / 改它 / 删它?
|
||||
*
|
||||
* ★ 为什么是**全屏界面**而不是弹窗:见 AGENTS.md「少用弹窗,能开界面就开界面」。
|
||||
* 列表 + 每行带操作 + 随时可能变长,弹窗装不下。
|
||||
*
|
||||
* ★ 点一行 = 进这一局(找该局已有的会话,没有就建一个)—— 这是用户
|
||||
* 用这个页面最高频的动作,所以做成整行可点,而不是藏在菜单里。
|
||||
*/
|
||||
@Composable
|
||||
fun ContainerListScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
FullScreen(
|
||||
title = "容器",
|
||||
subtitle = "一局 = 世界包 + 成员;数值 / 状态 / 记忆按局隔离",
|
||||
onBack = onBack,
|
||||
actions = { TopAction("新建") { vm.openContainerEdit(null) } },
|
||||
) {
|
||||
val containers = vm.state.containers
|
||||
if (containers.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) {
|
||||
Text(
|
||||
"还没有容器。\n点右上角「新建」开一局:选一个世界包、拉几个智能体进来。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 20.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(containers, key = { it.id }) { c -> ContainerRow(vm, c) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ContainerRow(vm: AppViewModel, c: ContainerItem) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.clickable { vm.openContainerChat(c) }
|
||||
.padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
c.name.ifBlank { "未命名容器" },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// ★ v3.1:在**这一局里再开一个对话**(同一容器的对话共享上下文,
|
||||
// 用户要求"同一容器支持多个对话且上下文不会断")
|
||||
RowAction("新对话") { vm.newConversationInContainer(c) }
|
||||
// ★ v3.0 P4:地图入口(地点/场景在这里看和切)
|
||||
RowAction("地图") { vm.openMap(c.id) }
|
||||
// ★ v3.0 P3:背包也按局看 —— 先选这局里第一个成员,进去还能切人
|
||||
RowAction("背包") {
|
||||
val first = c.members.firstOrNull()
|
||||
if (first == null) vm.showHint("这一局还没有成员,先编辑它加点人")
|
||||
else vm.openBag(c.id, first)
|
||||
}
|
||||
// ★ 编辑入口放在行尾,不抢"点一行进这一局"的主操作
|
||||
RowAction("编辑") { vm.openContainerEdit(c) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
ContainerTag(if (c.isSolo) "单聊容器" else (c.worldPackName.ifBlank { "世界包已删除" }))
|
||||
if (c.gameOver) {
|
||||
// ★ v3.27:用户角色死亡 = 这一局游戏结束(进去还能看历史/复活)
|
||||
Text(
|
||||
"已结束",
|
||||
fontSize = 11.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.padding(start = 6.dp)
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.padding(horizontal = 7.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
" · ${c.memberCount} 人",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
c.memberNames.filter { it.isNotBlank() }.joinToString("、")
|
||||
.ifBlank { "(还没有成员)" },
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text("点一下进入这一局", fontSize = 11.sp, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
|
||||
/** 世界包 / 单聊 的小标签 */
|
||||
@Composable
|
||||
private fun ContainerTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.padding(horizontal = 7.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.ContextEntry
|
||||
import com.doubao.lynxclone.data.ContextPreview
|
||||
import com.doubao.lynxclone.data.ContextSection
|
||||
|
||||
/**
|
||||
* **上下文查看器**(v3.16,用户需求)。
|
||||
*
|
||||
* 用户原话:「你做个上下文查看器」—— 起因是「同容器不同对话的上下文会丢」。
|
||||
* 聊天界面只能看到"界面上有哪些消息",看不到模型**实际收到了什么**:
|
||||
* · 同容器其他对话的消息会被并进来(一局 = 一个上下文边界);
|
||||
* · 别的地点 / 第一次到该地点之前 / 超出窗口 / 别人的私聊会被筛掉;
|
||||
* · system prompt 里还有记忆 / 数值 / 地点 / 技能手册一大段。
|
||||
*
|
||||
* 这一页把内核真正组装的那份**摊开**(数据来自
|
||||
* `/api/conversations/<id>/context`,和发消息共用同一个组装函数),
|
||||
* 每条消息都标清楚"从哪来、进没进模型、为什么没进"。
|
||||
*
|
||||
* ★ 为什么必须全屏:内容量远超弹窗能装的(AGENTS.md 的界面约定)。
|
||||
*/
|
||||
@Composable
|
||||
fun ContextViewerScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val data = vm.contextViewerData
|
||||
// 副标题只放"哪一局 · 谁":会话标题往往很长(会被 AI 自动改),
|
||||
// 塞进来会折成两行;它更适合放在下面的概览卡片里。
|
||||
val subtitle = listOfNotNull(
|
||||
data?.containerName?.takeIf { it.isNotBlank() },
|
||||
data?.agentName?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · ")
|
||||
FullScreen(
|
||||
title = "上下文查看器",
|
||||
subtitle = subtitle,
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("刷新") { vm.reloadContextViewer() }
|
||||
},
|
||||
) {
|
||||
when {
|
||||
data == null && vm.contextViewerLoading ->
|
||||
CenterNote("正在组装上下文……")
|
||||
data == null && vm.contextViewerError.isNotBlank() ->
|
||||
CenterNote(vm.contextViewerError)
|
||||
data == null ->
|
||||
CenterNote("没有数据(内核可能还没启动)")
|
||||
else -> ContextViewerBody(vm, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenterNote(text: String) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text(text, fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun ContextViewerBody(vm: AppViewModel, data: ContextPreview) {
|
||||
val sections = data.sections
|
||||
val entries = data.history.entries
|
||||
val included = entries.filter { it.included }
|
||||
val excluded = entries.filter { !it.included }
|
||||
val expandedSections = remember { mutableStateMapOf<String, Boolean>() }
|
||||
val expandedEntries = remember { mutableStateMapOf<Int, Boolean>() }
|
||||
val summary = data.history.summary
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// ---- ① 现在能不能发(独自一人的地点会被拦) ----
|
||||
if (data.chat.blocked) {
|
||||
item(key = "guard") {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(androidx.compose.ui.graphics.Color(0x1AD93025))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"现在发不出去:${data.chat.message.ifBlank { "这里只有你一个人" }}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = androidx.compose.ui.graphics.Color(0xFFB3261E),
|
||||
)
|
||||
if (data.chat.hint.isNotBlank()) {
|
||||
Text(
|
||||
data.chat.hint,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ② 说明(为什么看起来"少了/多了"消息) ----
|
||||
if (data.notices.isNotEmpty()) {
|
||||
item(key = "notices") {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Text("说明", fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
for (n in data.notices) {
|
||||
Text(
|
||||
"· $n",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ③ 概览 + 统计 ----
|
||||
item(key = "overview") {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text("这一轮 AI 看到什么", fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
InfoLine("会话", data.convTitle.ifBlank { "(未命名)" })
|
||||
InfoLine("容器 / 地点",
|
||||
listOfNotNull(data.containerName.ifBlank { null }, data.placeName.ifBlank { null })
|
||||
.joinToString(" · ").ifBlank { "(没有)" })
|
||||
InfoLine("模型", data.modelName.ifBlank { "(未配置)" })
|
||||
InfoLine("system prompt", "${data.promptChars} 字")
|
||||
InfoLine("历史消息", "${included.size} 条进模型(共取到 ${summary["total"] ?: entries.size} 条)")
|
||||
if ((summary["fromOtherConvs"] ?: 0) > 0) {
|
||||
InfoLine("其中别的对话", "同容器其他对话并进来 ${summary["fromOtherConvs"]} 条")
|
||||
}
|
||||
val drops = listOfNotNull(
|
||||
(summary["droppedPlace"] ?: 0).takeIf { it > 0 }?.let { "别的地点 $it 条" },
|
||||
(summary["droppedEnter"] ?: 0).takeIf { it > 0 }?.let { "第一次到该地点之前 $it 条" },
|
||||
(summary["droppedWindow"] ?: 0).takeIf { it > 0 }?.let { "超出窗口 $it 条" },
|
||||
(summary["droppedPrivate"] ?: 0).takeIf { it > 0 }?.let { "别人的私聊 $it 条" },
|
||||
)
|
||||
if (drops.isNotEmpty()) {
|
||||
InfoLine("没带进来", drops.joinToString(";"))
|
||||
}
|
||||
val rounds = summary["totalRounds"] ?: 0
|
||||
if (rounds > 1) {
|
||||
InfoLine(
|
||||
"上下文窗口",
|
||||
"保留最近 ${summary["keptRounds"] ?: rounds} 轮 / 共 $rounds 轮" +
|
||||
if ((summary["droppedWindow"] ?: 0) > 0) "" else "(没触发裁剪)",
|
||||
)
|
||||
}
|
||||
if (data.tools.isNotEmpty()) {
|
||||
InfoLine("可用工具", "${data.tools.size} 个:${data.tools.take(8).joinToString("、")}" +
|
||||
if (data.tools.size > 8) "…" else "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ④ 视角切换(群聊里每个人看到的不一样:私聊/记忆/前缀) ----
|
||||
if (data.isGroup && data.agentChoices.size > 1) {
|
||||
item(key = "agents") {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text("从谁的视角看", fontSize = 12.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 6.dp))
|
||||
// ★ v3.26:人数多的时候 Row 会横向溢出(最后一个人名被挤成竖排)——
|
||||
// 改成 FlowRow,按实际宽度自动换行;人再多也不会溢出。
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for ((aid, name) in data.agentChoices) {
|
||||
val on = aid == data.agentId
|
||||
Text(
|
||||
name,
|
||||
fontSize = 12.sp,
|
||||
color = if (on) androidx.compose.ui.graphics.Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { vm.switchContextViewerAgent(aid) }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ⑤ system prompt(逐段) ----
|
||||
item(key = "prompt-label") {
|
||||
SectionLabel("实际送进模型的 system prompt(${sections.size} 段)")
|
||||
}
|
||||
itemsIndexed(sections, key = { _, s -> "sec-${s.name}" }) { _, sec ->
|
||||
SectionCard(
|
||||
sec = sec,
|
||||
expanded = expandedSections[sec.name] ?: (sec.chars <= 300),
|
||||
onToggle = { expandedSections[sec.name] = !(expandedSections[sec.name] ?: (sec.chars <= 300)) },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- ⑥ 历史消息(每条标明来源) ----
|
||||
item(key = "history-label") {
|
||||
SectionLabel("送进模型的历史消息(${included.size} 条,按时间序)")
|
||||
}
|
||||
if (included.isEmpty()) {
|
||||
item(key = "history-empty") {
|
||||
Text(
|
||||
"一条都没有 —— 这是新对话,或者这个角色什么都看不到(检查上面的说明)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
itemsIndexed(included, key = { i, e -> "in-$i-${e.at}-${e.content.take(8)}" }) { index, e ->
|
||||
EntryCard(
|
||||
e = e,
|
||||
expanded = expandedEntries[index] ?: false,
|
||||
onToggle = { expandedEntries[index] = !(expandedEntries[index] ?: false) },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- ⑦ 没带进来的消息(给"上下文怎么丢了"一个明确答案) ----
|
||||
if (excluded.isNotEmpty()) {
|
||||
item(key = "excluded-label") {
|
||||
SectionLabel("没带进来的消息(${excluded.size} 条 —— 原因写在每条上)")
|
||||
}
|
||||
itemsIndexed(excluded, key = { i, e -> "out-$i-${e.at}-${e.content.take(8)}" }) { index, e ->
|
||||
ExcludedCard(
|
||||
e = e,
|
||||
expanded = expandedEntries[10000 + index] ?: false,
|
||||
onToggle = { expandedEntries[10000 + index] = !(expandedEntries[10000 + index] ?: false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
item(key = "footer") {
|
||||
Text(
|
||||
"说明:这里展示的就是内核组装好、正要交给模型的那一份(和真正发消息走同一个函数)。" +
|
||||
"「同容器其他对话」会并进来,是因为同一局 = 一个上下文边界;" +
|
||||
"地点 / 第一次进入之前 / 上下文窗口 / 别人的私聊按规则看不到。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextDim(),
|
||||
modifier = Modifier.padding(top = 6.dp, bottom = 24.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InfoLine(label: String, value: String) {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(label, fontSize = 11.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.width(96.dp))
|
||||
Text(value, fontSize = 11.sp, lineHeight = 17.sp, color = doubaoText(),
|
||||
modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionCard(
|
||||
sec: ContextSection,
|
||||
expanded: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
sec.label.ifBlank { sec.name },
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (sec.empty) "空段(整段没注入)" else "${sec.chars} 字",
|
||||
fontSize = 10.sp,
|
||||
color = if (sec.empty) doubaoTextDim() else doubaoTextSecondary(),
|
||||
)
|
||||
if (!sec.empty) {
|
||||
Text(
|
||||
if (expanded) " 收起" else " 展开",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!sec.empty && expanded) {
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
thickness = 0.5.dp,
|
||||
)
|
||||
Text(
|
||||
sec.text,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 17.sp,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryCard(e: ContextEntry, expanded: Boolean, onToggle: () -> Unit) {
|
||||
val isUser = e.role == "user"
|
||||
val sourceText = if (e.source == "other") {
|
||||
"同容器对话「${e.convTitle.ifBlank { "另一个" }}」"
|
||||
} else {
|
||||
"本对话"
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
if (isUser) "用户" else "AI",
|
||||
fontSize = 10.sp,
|
||||
color = androidx.compose.ui.graphics.Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(if (isUser) Doubao.Blue else doubaoTextDim())
|
||||
.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(sourceText, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
if (e.important) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("★重要", fontSize = 10.sp, color = Doubao.Blue)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
if (expanded) "收起" else "展开",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
e.modelContent.ifBlank { e.content },
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoText(),
|
||||
maxLines = if (expanded) Int.MAX_VALUE else 5,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
if (!expanded && (e.modelContent.ifBlank { e.content }).length > 160) {
|
||||
Text(
|
||||
"(点「展开」看全文)",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ExcludedCard(e: ContextEntry, expanded: Boolean, onToggle: () -> Unit) {
|
||||
val reason = when (e.reason) {
|
||||
"place" -> "别的地点"
|
||||
"enter" -> "第一次到这个地点之前"
|
||||
"window" -> "超出上下文窗口"
|
||||
"private" -> "别人的私聊"
|
||||
else -> "被筛掉"
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard().copy(alpha = 0.6f))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
reason,
|
||||
fontSize = 10.sp,
|
||||
color = androidx.compose.ui.graphics.Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(androidx.compose.ui.graphics.Color(0xFFB3261E))
|
||||
.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
if (e.source == "other") "对话「${e.convTitle.ifBlank { "另一个" }}」" else "本对话",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
if (expanded) "收起" else "展开",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onToggle() }
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
if (e.detail.isNotBlank()) {
|
||||
Text(e.detail, fontSize = 10.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 2.dp))
|
||||
}
|
||||
Text(
|
||||
e.content,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = if (expanded) Int.MAX_VALUE else 3,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
@@ -228,6 +230,7 @@ fun TypingDots(color: Color = Doubao.TextTertiary, dot: Dp = 6.dp) {
|
||||
/* ------------------------------ 小部件 ------------------------------ */
|
||||
|
||||
/** 顶部/输入框上方的白底描边胶囊按钮(快捷入口、功能键) */
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun DoubaoPill(
|
||||
text: String? = null,
|
||||
@@ -235,15 +238,20 @@ fun DoubaoPill(
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
height: Dp = 40.dp,
|
||||
/** ★ v3.15:长按(不传 = 没有长按行为)—— 成员条用它「长按 @某人 私聊」 */
|
||||
onLongClick: (() -> Unit)? = null,
|
||||
) {
|
||||
val base = modifier
|
||||
.height(height)
|
||||
.clip(RoundedCornerShape(height / 2))
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), RoundedCornerShape(height / 2))
|
||||
Box(
|
||||
modifier
|
||||
.height(height)
|
||||
.clip(RoundedCornerShape(height / 2))
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), RoundedCornerShape(height / 2))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp),
|
||||
(if (onLongClick != null) {
|
||||
base.combinedClickable(onClick = onClick, onLongClick = onLongClick)
|
||||
} else {
|
||||
base.clickable(onClick = onClick)
|
||||
}).padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -0,0 +1,584 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.DuelInfo
|
||||
import com.doubao.lynxclone.data.DuelRound
|
||||
import com.doubao.lynxclone.data.DuelSide
|
||||
import com.doubao.lynxclone.data.DuelStat
|
||||
import com.doubao.lynxclone.data.DuelStatus
|
||||
|
||||
/**
|
||||
* **决斗界面**(v3.17,用户需求)。
|
||||
*
|
||||
* 用户原话:「决斗加个ui但不开新对话,和私密一样」「要有决斗可以中断但需要双方同意」
|
||||
* 「如何选择武器?没有回合限制」「有输,赢,平局,停手,4种状态」。
|
||||
*
|
||||
* 所以这一页是**当前对话的一个面板**(不新建会话、不新开话题):
|
||||
* · 上半:双方名字 / 数值条 / 状态 / **当前武器**(数据来自内核每回合返回的快照)
|
||||
* · 中间:**我的武器**(每回合可换,点击切换)、回合记录、结果(赢/输/平局/停手)
|
||||
* · 底部:出招(推进一回合)、请求罢手(对方同意才停手)、
|
||||
* 等用户回应时的「同意罢手 / 继续打」
|
||||
*
|
||||
* ★ 为什么全屏:双方状态 + 多回合日志,弹窗根本装不下(AGENTS.md 界面约定)。
|
||||
* ★ 谁赢、掉多少血、中什么状态由世界脚本 + 物品脚本决定,界面**只展示 + 推进**。
|
||||
* ★ **没有回合上限**(v3.19):回合只写「第 N 回合」。
|
||||
*/
|
||||
@Composable
|
||||
fun DuelScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val d = vm.duel
|
||||
FullScreen(
|
||||
title = "决斗",
|
||||
subtitle = d?.let { "${it.title()} · ${it.statusText()}" }.orEmpty(),
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (d != null) TopTextAction("刷新") { vm.loadDuel() }
|
||||
},
|
||||
) {
|
||||
if (d == null) {
|
||||
Box(Modifier.fillMaxSize().padding(24.dp)) {
|
||||
Text("这个对话现在没有决斗。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxWidth().weight(1f),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item(key = "status") { DuelStatusCard(d) }
|
||||
// ★ v3.19:每回合可以换武器(用户原话「如何选择武器?」→ 界面上直接选)
|
||||
item(key = "weapons") { DuelWeaponPicker(vm, d) }
|
||||
// ★ v3.22:本回合物品(被动物品/血瓶;每回合只能用一件)
|
||||
item(key = "items") { DuelItemPicker(vm, d) }
|
||||
// ★ v3.24:决斗对话(用户说话,对手 AI 真的以角色身份回应)
|
||||
item(key = "talk") { DuelTalkBox(vm, d) }
|
||||
item(key = "sides") {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
DuelSideCard(d.initiator, userLabel = "你", modifier = Modifier.weight(1f))
|
||||
DuelSideCard(d.target, userLabel = "你", modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
item(key = "logTitle") {
|
||||
Text("回合记录", fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
if (d.log.isEmpty()) {
|
||||
item(key = "emptyLog") {
|
||||
Text("还没开打。", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
items(d.log) { round -> DuelRoundCard(round) }
|
||||
item(key = "bottomSpace") { Spacer(Modifier.height(4.dp)) }
|
||||
}
|
||||
DuelActions(vm, d)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 顶部状态卡 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelStatusCard(d: DuelInfo) {
|
||||
val accent = when {
|
||||
d.interrupted -> Color(0xFF8A6100)
|
||||
d.running -> Color(0xFFB3261E)
|
||||
d.outcomeText() == "赢" -> Color(0xFFB3261E)
|
||||
d.outcomeText() == "输" -> Color(0xFF6B6B6B)
|
||||
d.outcomeText().isNotBlank() -> Color(0xFF8A6100)
|
||||
else -> Doubao.Blue
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(accent.copy(alpha = 0.10f))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
d.statusText(),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = accent,
|
||||
)
|
||||
// ★ v3.19:四种结果状态 —— 赢 / 输 / 平局 / 停手,放在最显眼的位置
|
||||
if (!d.running && d.outcomeText().isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
d.outcomeText(),
|
||||
fontSize = 24.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = accent,
|
||||
)
|
||||
}
|
||||
when {
|
||||
d.running && d.needsMyAnswer -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"「${d.pendingStopByName}」想罢手、停手 —— 要你同意才能停。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
d.running && d.status == "stop_pending" -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"你已经请求罢手,正在等「${d.foeSide.name}」回应;对方同意之前决斗还在继续。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
d.result.isNotBlank() -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(d.result, fontSize = 12.sp, color = doubaoText())
|
||||
if (d.missingWeapon) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"决斗要求双方都有 target 类物品(武器),没有的一方判负。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"每点一次「出招」推进一回合(没有回合上限):双方先用当前武器出手" +
|
||||
"(跑物品脚本),再由世界脚本(on_duel)裁决。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 双方卡片 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelSideCard(side: DuelSide, userLabel: String, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
if (side.isUser) "$userLabel(${side.name})" else side.name.ifBlank { "对手" },
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (side.isUser) Doubao.Blue else doubaoText(),
|
||||
maxLines = 1,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// ★ v3.19:四种结果状态(赢/输/平局/停手)直接标在名字右边
|
||||
if (side.outcomeText().isNotBlank()) {
|
||||
Text(
|
||||
side.outcomeText(),
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = when (side.outcome) {
|
||||
"win" -> Color(0xFFB3261E)
|
||||
"lose" -> Color(0xFF6B6B6B)
|
||||
else -> Color(0xFF8A6100)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (side.isGuard) {
|
||||
Text("驻守角色", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
// ★ v3.20:决斗中死亡 = 判负
|
||||
if (side.dead) {
|
||||
Text("已死亡(决斗判负)", fontSize = 11.sp, color = Color(0xFFB3261E))
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (side.stats.isEmpty()) {
|
||||
Text("没有数值", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (s in side.stats) {
|
||||
DuelStatBar(s)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
if (side.statuses.isNotEmpty()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
for (st in side.statuses) {
|
||||
Text(
|
||||
"· ${st.name}" + if (st.kind != "persistent" && st.remaining > 0) "(剩 ${st.remaining} 轮)" else "",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★ v3.18:武器(target 类物品)—— 没有武器的一方会被直接判失败
|
||||
// ★ v3.19:显示"这回合用的是哪件",并提示可换
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text("武器", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
if (side.weapons.isEmpty()) {
|
||||
Text(
|
||||
"没有 target 类物品 —— 会被判失败",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
} else {
|
||||
val cur = side.weapon
|
||||
Text(
|
||||
if (cur != null) "本回合:${cur.name}${cur.countText()}" else "本回合:自动选择",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 2,
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Text(
|
||||
side.weapons.joinToString("、") { "${it.name}${it.countText()}" },
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 3,
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
}
|
||||
// ★ v3.22:本回合用被动物品 = 不攻击(每回合只能用一件物品)
|
||||
val usedItem = side.item
|
||||
if (usedItem != null) {
|
||||
Text(
|
||||
"本回合动作:使用「${usedItem.name}」(不攻击)",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.19:**我的武器**选择器(用户原话「如何选择武器?」→ 每回合都能换)。
|
||||
*
|
||||
* 从自己的 target 类物品里点一件当"下一回合的武器";点一下就走接口(不弹窗,
|
||||
* 这本来就是一行 chips)。没有武器时整块不显示(上面卡片会红字说明)。
|
||||
*/
|
||||
@Composable
|
||||
private fun DuelWeaponPicker(vm: AppViewModel, d: DuelInfo) {
|
||||
val side = d.meSide
|
||||
if (side.weapons.isEmpty()) return
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text("我的武器(每回合可换)", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for (w in side.weapons) {
|
||||
val selected = w.id == side.weapon?.id
|
||||
Text(
|
||||
"${w.name}${w.countText()}",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (selected) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (selected) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(enabled = d.status == "active" && !vm.duelBusy) {
|
||||
vm.chooseDuelWeapon(w.id)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (d.status != "active") {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("决斗中才能换武器。", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.22:**本回合物品**(用户原话「被动在决斗中也可使用 比如用血瓶 但每回合只能用一个物品」)。
|
||||
*
|
||||
* 选被动物品 = 这回合用它、**不用武器攻击**;不选 = 正常武器攻击。
|
||||
* 选择是一次性的:推进一回合后自动清空(快照里 item 变 null)。
|
||||
*/
|
||||
@Composable
|
||||
private fun DuelItemPicker(vm: AppViewModel, d: DuelInfo) {
|
||||
val side = d.meSide
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text("本回合物品(每回合只能用一件)", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"选被动物品(比如血瓶)= 这回合用它、不攻击;不选就用武器攻击。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// "改用武器"= 取消物品选择(默认动作)
|
||||
val noItem = side.item == null
|
||||
Text(
|
||||
"用武器攻击",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (noItem) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (noItem) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (noItem) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(enabled = d.status == "active" && !vm.duelBusy) {
|
||||
vm.chooseDuelItem("")
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
for (it in side.passiveItems) {
|
||||
val selected = it.id == side.item?.id
|
||||
Text(
|
||||
"${it.name}${it.countText()}",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
color = if (selected) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (selected) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(enabled = d.status == "active" && !vm.duelBusy) {
|
||||
vm.chooseDuelItem(it.id)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (side.passiveItems.isEmpty()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("背包里没有被动物品(血瓶/回春丹这类)。",
|
||||
fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
if (d.status != "active") {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("决斗中才能选物品。", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★ v3.24:**决斗对话**(用户原话:「决斗要ai真的参与,弄个对话框」)。
|
||||
*
|
||||
* 用户在这里说话 → 内核真的问一次**对手 AI**(按它的人设/气血/最近交锋),
|
||||
* AI 以角色身份回一句,双方的话都写进回合记录和会话消息。
|
||||
* 不影响出招/回合推进 —— 想说话就说话,想出招就出招。
|
||||
*/
|
||||
@Composable
|
||||
private fun DuelTalkBox(vm: AppViewModel, d: DuelInfo) {
|
||||
var line by remember(d.id) { mutableStateOf("") }
|
||||
val foe = d.foeSide.name.ifBlank { "对手" }
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text("决斗对话(AI 会真的回你)", fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"对「$foe」说句话(挑衅/谈判/认输都行)—— 对手 AI 会按人设回应;" +
|
||||
"不影响出招和回合。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 15.sp,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
OutlinedTextField(
|
||||
value = line,
|
||||
onValueChange = { line = it },
|
||||
modifier = Modifier.weight(1f),
|
||||
placeholder = { Text("对 $foe 说…", fontSize = 13.sp) },
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
maxLines = 2,
|
||||
singleLine = false,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TextButton(
|
||||
enabled = d.status == "active" && !vm.duelSaying
|
||||
&& line.isNotBlank(),
|
||||
onClick = {
|
||||
vm.sayInDuel(line)
|
||||
line = ""
|
||||
},
|
||||
) { Text(if (vm.duelSaying) "回应中…" else "发送") }
|
||||
}
|
||||
if (d.status != "active") {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("决斗中才能对话。", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DuelStatBar(stat: DuelStat) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(stat.name, fontSize = 11.sp, color = doubaoTextSecondary(), modifier = Modifier.weight(1f))
|
||||
Text(
|
||||
"${fmt(stat.value)} / ${fmt(stat.max)}",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(5.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoTextSecondary().copy(alpha = 0.18f)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(5.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (kotlin.math.abs(v - v.toLong()) < 0.001) v.toLong().toString() else "%.1f".format(v)
|
||||
|
||||
/* ------------------------------ 回合记录 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelRoundCard(round: DuelRound) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"第 ${round.round} 回合",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
if (round.lines.isEmpty()) {
|
||||
Text("这一回合没有旁白。", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (line in round.lines) {
|
||||
Text(
|
||||
line,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 底部按钮 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun DuelActions(vm: AppViewModel, d: DuelInfo) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (vm.duelBusy) {
|
||||
Text("处理中……", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
return@Row
|
||||
}
|
||||
when {
|
||||
d.running && d.needsMyAnswer -> {
|
||||
DuelButton("同意罢手", primary = true) { vm.answerDuelStop(true) }
|
||||
DuelButton("继续打", primary = false) { vm.answerDuelStop(false) }
|
||||
}
|
||||
d.running && d.status == "active" -> {
|
||||
DuelButton("出招", primary = true) { vm.advanceDuel() }
|
||||
if (d.userInvolved) {
|
||||
DuelButton("请求罢手", primary = false) { vm.requestDuelStop() }
|
||||
}
|
||||
}
|
||||
d.running -> {
|
||||
Text("等「${d.foeSide.name}」回应罢手请求……", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
else -> {
|
||||
DuelButton("关闭", primary = true) {
|
||||
vm.dismissDuel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun androidx.compose.foundation.layout.RowScope.DuelButton(
|
||||
label: String,
|
||||
primary: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (primary) Color.White else Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(if (primary) Doubao.Blue else Doubao.Blue.copy(alpha = 0.12f))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 10.dp),
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
||||
)
|
||||
}
|
||||
@@ -59,7 +59,7 @@ fun GroupMembersScreen(
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "群成员",
|
||||
title = "会话成员",
|
||||
subtitle = conv?.let { "${it.participants.size} 个人在群里" } ?: "会话不见了",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
@@ -75,10 +75,13 @@ fun GroupMembersScreen(
|
||||
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
|
||||
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
|
||||
// 让人点了才被告知"加不进去"是最差的体验。
|
||||
//
|
||||
// ★ **未绑世界观的放行**:它没有设定会串,和谁都合得来
|
||||
// (用户报的「还是加不了人」,其中"黑化豆包"就是未绑的)。
|
||||
val hostWorldview = vm.state.agents
|
||||
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
|
||||
val sameWorldview = vm.state.agents.filter {
|
||||
(it.worldviewId.orEmpty() == hostWorldview)
|
||||
it.worldviewId.orEmpty().isBlank() || it.worldviewId.orEmpty() == hostWorldview
|
||||
}
|
||||
val candidates = sameWorldview.filter { it.id !in inGroup }
|
||||
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
|
||||
@@ -86,12 +89,8 @@ fun GroupMembersScreen(
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint(
|
||||
if (blocked > 0) {
|
||||
"没有可以拉的人了。还有 $blocked 个智能体在世界观上跟这个群不一样," +
|
||||
"拉进来会串设定 —— 换个群或者先给它们绑同一个世界观。"
|
||||
} else {
|
||||
"所有同世界观的智能体都在群里了。"
|
||||
},
|
||||
if (blocked > 0) "没有可以拉的人了。"
|
||||
else "所有能拉的人都在群里了。",
|
||||
)
|
||||
} else {
|
||||
for (a in candidates) {
|
||||
@@ -108,13 +107,38 @@ fun GroupMembersScreen(
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 36)
|
||||
AgentFace(vm, a, 36)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
|
||||
}
|
||||
// ★★ 被世界观挡下的**也列出来**,并说清原因。
|
||||
//
|
||||
// 不列的话用户只看到"某些智能体不见了",以为功能坏了 ——
|
||||
// 他报的「还是加不了人」有一半是这种感觉。
|
||||
val blockedAgents = vm.state.agents.filter { it.id !in inGroup && it !in sameWorldview }
|
||||
if (blockedAgents.isNotEmpty()) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"这些绑的是别的世界观,拉进来会串设定(两套背景、共享记忆也会混):",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
for (a in blockedAgents) {
|
||||
Text(
|
||||
"· ${a.name}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(start = 6.dp, top = 2.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("想拉它们:先去它们的编辑页绑成这个世界观(或者另开一个群)。")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
}
|
||||
@@ -132,7 +156,7 @@ fun GroupMembersScreen(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 40)
|
||||
AgentFace(vm, a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
@@ -150,6 +174,9 @@ fun GroupMembersScreen(
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
// ★ v3.15:私聊入口改成**聊天页长按 @成员**(用户要求
|
||||
// 「长按@xxx私聊」)。这里不再放按钮 —— 那会另开一个
|
||||
// 私聊会话,和"私聊在当前对话里"的预期不符。
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
|
||||
@@ -164,6 +191,10 @@ fun GroupMembersScreen(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
|
||||
)
|
||||
// ★ v3.17:决斗入口从这一页挪走了 —— 用户要求「长按@XX可选私聊和决斗」。
|
||||
// 私聊和决斗**都不另开会话**(都在当前对话里),所以入口统一放在
|
||||
// 聊天页的成员条上:点 = @,长按 = 私聊/决斗二选一。
|
||||
Hint("长按聊天页的 @成员 还能选「私聊」或「决斗」(都不会另开对话)。")
|
||||
|
||||
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
|
||||
//
|
||||
@@ -220,8 +251,8 @@ fun GroupMembersScreen(
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@Composable
|
||||
private fun AgentFace(agent: Agent?, size: Int) {
|
||||
val art = agent?.image?.portrait.orEmpty()
|
||||
private fun AgentFace(vm: AppViewModel, agent: Agent?, size: Int) {
|
||||
val art = vm.portraitOf(agent)
|
||||
Box(
|
||||
Modifier
|
||||
.size(size.dp)
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
|
||||
/**
|
||||
* [地图](v3.31):**内核生成的图形地图页**(全屏 WebView)。
|
||||
*
|
||||
* 页面由 `/api/containers/<cid>/map/page` 生成,画的是:
|
||||
* · 背景图(世界包 `info.map.background`,可上传图片)
|
||||
* · 区域框(`info.map.regions[]`:家 / 老街 / 森林 / 学校…)
|
||||
* · 地点圆点(世界包 `places[].x/y` 是背景图里的 **0-100 百分比位置**)
|
||||
* · 邻接连线(由 `places[].exits` 自动推出来,一个地点可连多个)
|
||||
* · 用户位置五角星(`info.map.marker` 可换成自定义字符或图片)
|
||||
*
|
||||
* 交互都在页面里(同一份 HTML/CSS/JS,样式可由 `info.map.css` 追加):
|
||||
* · 双指缩放 / 滚轮 / 拖动;点区域框放大到该区域;
|
||||
* · 点地点圆点 → 「去这里 / 移人」;**长按地点或区域 → 弹出信息**;
|
||||
* · 页面里 `fetch` 直接调内核移动接口,「去这里」成功后通过 JS 桥回调
|
||||
* [MapBridge.moved] 让 App 切到该地点的对话。
|
||||
*
|
||||
* 以前这里是 Compose 画的地点头像列表;换成 HTML 页是为了让世界作者能用
|
||||
* CSS 改边框/连线/节点样式(用户要求)。
|
||||
*/
|
||||
@Composable
|
||||
fun MapScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val url = vm.mapPageUrl
|
||||
val container = vm.state.containers.firstOrNull { it.id == vm.mapContainerId }
|
||||
FullScreen(
|
||||
title = "地图",
|
||||
subtitle = container?.name?.ifBlank { "容器" } ?: "容器",
|
||||
onBack = onBack,
|
||||
) {
|
||||
val bridge = remember(url) {
|
||||
MapBridge(
|
||||
onClose = { vm.closeMap() },
|
||||
onMoved = { placeId, placeName -> vm.onMapMoved(placeId, placeName) },
|
||||
)
|
||||
}
|
||||
DisposableEffect(bridge) {
|
||||
onDispose {
|
||||
bridge.onClose = null
|
||||
bridge.onMoved = null
|
||||
}
|
||||
}
|
||||
if (url.isBlank()) {
|
||||
Hint("这一局还没有地图。")
|
||||
return@FullScreen
|
||||
}
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(android.graphics.Color.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
settings.cacheMode = WebSettings.LOAD_NO_CACHE
|
||||
// 缩放由页面里的 pointer 事件实现(双指/滚轮),别让 WebView 再插一手
|
||||
settings.builtInZoomControls = false
|
||||
settings.displayZoomControls = false
|
||||
// ★ v3.31 修复:`useWideViewPort = true` 让 WebView 按页面的
|
||||
// `<meta viewport width=device-width>` 建立布局视口(360 CSS px),
|
||||
// 这样 CSS 的 `vh / %` 高度才是对的。
|
||||
// 默认 false 时这个 WebView 里 `10vh` 会算成 0px ——
|
||||
// 地图信息面板曾经因此被压成一条 44px 的横条(用户反馈
|
||||
// 「面板太矮 / 太低」的根因)。页面里已经用 innerHeight 兜底,
|
||||
// 这里再把它从根上修好,世界包自定义 CSS 用 vh 也不会踩坑。
|
||||
// `loadWithOverviewMode` 保持 false:不要把 1080px 宽的地图舞台
|
||||
// 再整体缩放一遍(那样坐标和内边距全乱)。
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = false
|
||||
addJavascriptInterface(bridge, "Doubao")
|
||||
webViewClient = WebViewClient()
|
||||
loadUrl(url)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 地图页的极小 JS 桥:关掉全屏 / 告诉 App「已经移动到某地点」。 */
|
||||
private class MapBridge(
|
||||
@Volatile var onClose: (() -> Unit)?,
|
||||
@Volatile var onMoved: ((String, String) -> Unit)?,
|
||||
) {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
main.post { onClose?.invoke() }
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun moved(placeId: String, placeName: String) {
|
||||
main.post { onMoved?.invoke(placeId ?: "", placeName ?: "") }
|
||||
}
|
||||
}
|
||||
@@ -76,10 +76,24 @@ fun MarkdownText(
|
||||
linkColor: Color = Doubao.Blue,
|
||||
fontSize: Int = 16,
|
||||
lineHeight: Int = 26,
|
||||
/**
|
||||
* 把(括号)/【方括号】里的旁白显示成灰色小字(v3.27「朗读情绪指令」)。
|
||||
*
|
||||
* ★ 只影响**显示**:真正的朗读文本由内核 speech.prepare_speech 处理
|
||||
* (括号内容不念、改成豆包语音的 context_texts 指令)。两边的括号规则
|
||||
* 必须一致 —— 否则会出现"界面灰了、语音还念"或反过来的错位。
|
||||
*/
|
||||
stageTags: Boolean = false,
|
||||
) {
|
||||
val blocks = remember(markdown) { parseMarkdown(markdown) }
|
||||
val codeBg = if (isDark()) Color(0xFF1B1F27) else Color(0xFFF3F4F6)
|
||||
val quoteBar = Doubao.Blue.copy(alpha = 0.55f)
|
||||
// 旁白样式:更灰、更小。放在 inline() 里按括号匹配,不参与 Markdown 解析。
|
||||
val stageStyle = if (stageTags) {
|
||||
SpanStyle(color = color.copy(alpha = 0.42f), fontSize = (fontSize - 2).sp)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (block in blocks) {
|
||||
@@ -116,7 +130,7 @@ fun MarkdownText(
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color.copy(alpha = 0.85f),
|
||||
@@ -127,7 +141,7 @@ fun MarkdownText(
|
||||
|
||||
is MdBlock.Heading -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
@@ -143,7 +157,7 @@ fun MarkdownText(
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
@@ -159,7 +173,7 @@ fun MarkdownText(
|
||||
modifier = Modifier.width(22.dp),
|
||||
)
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
@@ -176,7 +190,7 @@ fun MarkdownText(
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = if (block.checked) color.copy(alpha = 0.6f) else color,
|
||||
@@ -191,6 +205,7 @@ fun MarkdownText(
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
@@ -203,7 +218,7 @@ fun MarkdownText(
|
||||
|
||||
is MdBlock.Paragraph -> {
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
inline(block.text, linkColor, stageStyle),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
@@ -247,6 +262,7 @@ private fun MarkdownTable(
|
||||
linkColor: Color,
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
stageStyle: SpanStyle? = null,
|
||||
) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
@@ -299,6 +315,7 @@ private fun MarkdownTable(
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
bold = true,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -315,6 +332,7 @@ private fun MarkdownTable(
|
||||
linkColor = linkColor,
|
||||
fontSize = fontSize,
|
||||
lineHeight = lineHeight,
|
||||
stageStyle = stageStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -333,6 +351,7 @@ private fun TableCell(
|
||||
fontSize: Int,
|
||||
lineHeight: Int,
|
||||
bold: Boolean = false,
|
||||
stageStyle: SpanStyle? = null,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
@@ -341,7 +360,7 @@ private fun TableCell(
|
||||
) {
|
||||
Text(
|
||||
// 单元格里也走行内解析 —— `**合计**`、`` `code` ``、链接都要生效
|
||||
inline(text, linkColor),
|
||||
inline(text, linkColor, stageStyle),
|
||||
fontSize = (fontSize - 2).sp,
|
||||
lineHeight = (lineHeight - 4).coerceAtLeast(fontSize).sp,
|
||||
fontWeight = if (bold) FontWeight.SemiBold else null,
|
||||
@@ -738,11 +757,25 @@ private val RE_BARE_URL =
|
||||
*/
|
||||
@OptIn(ExperimentalTextApi::class)
|
||||
@Composable
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
internal fun inline(
|
||||
text: String,
|
||||
linkColor: Color,
|
||||
/** 旁白(括号)样式;null = 不特殊显示(设置里的「朗读情绪指令」关掉时) */
|
||||
stageStyle: SpanStyle? = null,
|
||||
): AnnotatedString {
|
||||
val ctx = LocalContext.current
|
||||
return buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
// ★ v3.27:括号旁白先整段套样式,再按普通字符走后面的 Markdown 解析。
|
||||
// 规则只认成对括号、单段 ≤60 字、不跨行 —— 和内核 speech.py 的
|
||||
// `_STAGE_RE` 对齐(那边负责不念出来 + 变成语音指令)。
|
||||
val stageEnd = if (stageStyle != null) findStageEnd(text, i) else -1
|
||||
if (stageEnd > i) {
|
||||
withStyle(stageStyle!!) { append(text.substring(i, stageEnd + 1)) }
|
||||
i = stageEnd + 1
|
||||
continue
|
||||
}
|
||||
when {
|
||||
// 行内代码:`code`
|
||||
text[i] == '`' -> {
|
||||
@@ -849,4 +882,31 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 找一处「旁白」的收尾下标:(……)(……)【……】[……]。
|
||||
*
|
||||
* 返回 -1 = 当前位置不是旁白开头。规则(和内核 speech.py 的 `_STAGE_RE` 对齐):
|
||||
* · 成对括号、内容 1~60 字、不跨行;
|
||||
* · `[` 后面紧跟 `(` 的是 Markdown 链接(`[文字](url)`),不算旁白 —— 交给链接分支。
|
||||
*/
|
||||
private fun findStageEnd(text: String, start: Int): Int {
|
||||
val close = when (text[start]) {
|
||||
'(' -> ')'
|
||||
'(' -> ')'
|
||||
'【' -> '】'
|
||||
'[' -> ']'
|
||||
else -> return -1
|
||||
}
|
||||
var j = start + 1
|
||||
while (j < text.length && j - start <= 61) {
|
||||
val c = text[j]
|
||||
if (c == '\n' || c == close) break
|
||||
j++
|
||||
}
|
||||
if (j >= text.length || text[j] != close || j == start + 1) return -1
|
||||
// Markdown 链接 [文字](url):别当旁白吞掉(链接分支要拿它渲染成可点)
|
||||
if (text[start] == '[' && j + 1 < text.length && text[j + 1] == '(') return -1
|
||||
return j
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -53,11 +53,13 @@ import com.doubao.lynxclone.data.MemorySpace
|
||||
* · AI 提的"该整理记忆了"建议(需求 3.2:仅提示,用户确认才执行)
|
||||
* · 导入 / 导出(需求 3.4)
|
||||
*
|
||||
* ## 共享记忆要**显式说明**
|
||||
* ## 记忆空间:默认私有 + 共享板子(v3.16)
|
||||
*
|
||||
* 绑了世界观的智能体,记忆是和同世界观其他智能体**共用**的。
|
||||
* 界面上不写清楚的话,用户会以为"我给 A 记的东西怎么 B 也知道" ——
|
||||
* 所以顶部有一条明显的提示。
|
||||
* 用户反馈「怎么串味了豆包怎么读的了小黑的记忆」之后,默认空间从
|
||||
* "一局共享"改成了"**每个智能体一份私有**":
|
||||
* · 私有记忆:只有这个智能体自己读写 / 注入(这一页的默认视角);
|
||||
* · 共享板子:显式共享的条目(`memory_add(shared=true)`),全一局可见。
|
||||
* 两条都还在 —— 但界面必须写清楚"你在看哪一份",不然用户会以为记忆丢了。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
@@ -91,10 +93,14 @@ fun MemoryScreen(
|
||||
onSetWindow: (Int) -> Unit,
|
||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||
onImportClick: () -> Unit,
|
||||
/** 去看绑定世界观**之前**攒的私有记忆 */
|
||||
onOpenOwn: () -> Unit,
|
||||
/** 从旧空间回到当前生效的空间 */
|
||||
onBackToActive: () -> Unit,
|
||||
/** (兼容旧调用)看私有记忆 —— 现在默认就是私有,等同于 no-op */
|
||||
onOpenOwn: () -> Unit = {},
|
||||
/** (兼容旧调用)从旧空间回到当前空间 */
|
||||
onBackToActive: () -> Unit = {},
|
||||
/** 去看**这一局的共享记忆**(所有角色都能看到的那份) */
|
||||
onOpenShared: () -> Unit = {},
|
||||
/** 从共享记忆回到自己的私有记忆 */
|
||||
onBackToPrivate: () -> Unit = {},
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||
@@ -107,7 +113,8 @@ fun MemoryScreen(
|
||||
/** 调注入窗口(输入条数,0 = 不限) */
|
||||
var editWindow by remember { mutableStateOf(false) }
|
||||
var windowDraft by remember(space?.window) { mutableStateOf((space?.window ?: 0).toString()) }
|
||||
val readingOwn = space?.own == true
|
||||
/** ★ v3.16:正在看**这一局的共享记忆**(不是自己的私有记忆) */
|
||||
val readingShared = space?.sharedView == true
|
||||
|
||||
FullScreen(
|
||||
title = "记忆",
|
||||
@@ -116,59 +123,59 @@ fun MemoryScreen(
|
||||
append(" · ")
|
||||
when {
|
||||
worldMode -> append("世界观共享记忆")
|
||||
readingOwn -> append("绑定前的私有记忆")
|
||||
readingShared -> append("本局共享记忆")
|
||||
space == null -> append("读取中")
|
||||
space.shared -> append("世界观共享记忆")
|
||||
else -> append("私有记忆")
|
||||
}
|
||||
space?.let { append(" ${it.memories.size} 条") }
|
||||
if (loading) append(" · 处理中…")
|
||||
},
|
||||
onBack = { if (readingOwn) onBackToActive() else onBack() },
|
||||
onBack = { if (readingShared) onBackToPrivate() else onBack() },
|
||||
actions = {
|
||||
// 世界观视角是纯只读(导入/导出都以"某个智能体的记忆"为单位,
|
||||
// 而这里没有"我")—— 不给按钮,而不是给一个点了没反应的按钮
|
||||
if (!worldMode && !readingOwn) TopTextAction("导入", onClick = onImportClick)
|
||||
if (!worldMode && !readingShared) TopTextAction("导入", onClick = onImportClick)
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
/* ---- 空间标识(复查报告 4.1)----
|
||||
/* ---- 空间标识(复查报告 4.1 / v3.16)----
|
||||
*
|
||||
* ★ 这是这个界面最重要的一段字。
|
||||
* 绑定世界观之后读写空间会从私有换成共享,列表看起来"变空了" ——
|
||||
* 记忆一条没丢,但不说明的话用户必然判定"绑定把我的记忆清了"。
|
||||
* 默认空间变了、或者有另一块共享板子时,不说明的话用户
|
||||
* 必然判定"我的记忆丢了 / 记忆串味了"。
|
||||
*/
|
||||
if (readingOwn) {
|
||||
if (readingShared) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AF29900))
|
||||
.clickable { onBackToActive() }
|
||||
.background(Color(0x14F29900))
|
||||
.clickable { onBackToPrivate() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是绑定世界观之前攒的私有记忆,现在只供查看。" +
|
||||
"AI 当前读的是共享空间那份 —— 点这里回到当前空间。",
|
||||
"这是这一局的共享记忆:所有角色都能看到(每条标了是谁写的)。" +
|
||||
"AI 只能改自己写的条目,别人的你可以在这里手动删。" +
|
||||
"私密的事别放共享 —— 点这里回到自己的私有记忆。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if ((space?.ownCount ?: 0) > 0) {
|
||||
} else if (!worldMode && (space?.sharedCount ?: 0) > 0) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onOpenOwn() }
|
||||
.clickable { onOpenShared() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"绑定世界观之前你给这个智能体攒过 ${space?.ownCount} 条私有记忆,还留着。" +
|
||||
"AI 现在读的是上面那个共享空间 —— 点这里去看那些 ›",
|
||||
"这一局还有 ${space?.sharedCount ?: 0} 条共享记忆(所有角色共用、显式共享的),还留着。" +
|
||||
"下面这些才是你自己的私有记忆 —— 点这里去看共享板子 ›",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Doubao.Blue,
|
||||
@@ -177,7 +184,7 @@ fun MemoryScreen(
|
||||
}
|
||||
|
||||
// ---- 注入窗口(一遍看不出来"哪些真的进去了",所以直接写清)----
|
||||
if (!readingOwn && !worldMode && space != null) {
|
||||
if (!readingShared && !worldMode && space != null) {
|
||||
val total = space.memories.size
|
||||
val win = space.window
|
||||
val injected = space.injected
|
||||
@@ -244,27 +251,10 @@ fun MemoryScreen(
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if (space?.shared == true) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这个智能体绑定了世界观,记忆是和同世界观的其他智能体共用的。\n" +
|
||||
"它能改自己写的条目;改别人的(或删)需要你在这里手动操作。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- AI 的建议(需求 3.2:仅提示,用户确认才执行)----
|
||||
if (!space?.suggestion.isNullOrBlank()) {
|
||||
if (!readingShared && !space?.suggestion.isNullOrBlank()) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -301,8 +291,8 @@ fun MemoryScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 情绪(世界观视角没有"自己的情绪",隐藏)----
|
||||
if (!worldMode) {
|
||||
// ---- 情绪(世界观/共享视角没有"自己的情绪",隐藏)----
|
||||
if (!worldMode && !readingShared) {
|
||||
SectionLabel("情绪")
|
||||
Column(
|
||||
Modifier
|
||||
@@ -385,8 +375,8 @@ fun MemoryScreen(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!readingOwn && !worldMode) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingOwn && !worldMode) {
|
||||
if (!readingShared && !worldMode) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingShared && !worldMode) {
|
||||
SmallAction(if (loading) "整理中…" else "AI 整理") {
|
||||
// ★ 先确认再调(复查报告 4.2.1):整理是**一次真的 LLM 调用**、
|
||||
// 会改掉现有记忆,而且用户可能刚标好了「必须保留」——
|
||||
@@ -394,7 +384,12 @@ fun MemoryScreen(
|
||||
if (!loading) confirmSummarize = true
|
||||
}
|
||||
}
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
// 导出的是**自己的私有记忆**(共享板子是另一份,别混着导)
|
||||
if (!readingShared && !worldMode) {
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
} else if (worldMode) {
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
@@ -418,7 +413,8 @@ fun MemoryScreen(
|
||||
val authorName = if (author.isEmpty()) "" else (agentNames[author] ?: "另一个智能体")
|
||||
MemoryRow(
|
||||
item = m,
|
||||
readOnly = readingOwn,
|
||||
// ★ v3.16:共享板子上条目按"是不是自己写的"判改删(不是整页只读)
|
||||
readOnly = false,
|
||||
// 别人写的 = 界面上不给改删的入口(不是"点了才报错")
|
||||
foreign = !mine,
|
||||
authorName = if (mine) "" else authorName,
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
@@ -66,9 +66,10 @@ fun MoreSheetScreen(
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onNewGroup: () -> Unit,
|
||||
onOpenNotes: () -> Unit,
|
||||
onOpenModels: () -> Unit,
|
||||
/** v3.0 P2:容器(一局 = 世界包 + 成员) */
|
||||
onOpenContainers: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
@@ -85,14 +86,6 @@ fun MoreSheetScreen(
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
// 从抽屉挪进来的三个(都是"偶尔用一次"那一档)
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Group,
|
||||
title = "新建群聊",
|
||||
subtitle = "拉几个智能体到一个会话里,可以 @ 点名",
|
||||
) { onNewGroup() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.EditNote,
|
||||
@@ -115,12 +108,22 @@ fun MoreSheetScreen(
|
||||
) { onOpenAiScreens() }
|
||||
}
|
||||
item {
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)——
|
||||
// ★ v3.0 P2:容器(一局 = 世界包 + 成员)。
|
||||
// 用户核心诉求:"不同容器同一批智能体可以在不同的世界互不干扰"——
|
||||
// 所以"开一局"必须是个能点到的入口。
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
title = "容器",
|
||||
subtitle = "一局 = 世界包 + 成员;数值 / 状态 / 记忆按局隔离",
|
||||
) { onOpenContainers() }
|
||||
}
|
||||
item {
|
||||
// 世界包 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)——
|
||||
// 它们是"全局资源"那一层:都被智能体引用,都是列表 + 增删改 + 导入导出
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Public,
|
||||
title = "世界观 · 技能 · 模型",
|
||||
subtitle = "共享记忆的世界、AI 的工具手册、可选模型列表",
|
||||
title = "世界包 · 技能 · 模型",
|
||||
subtitle = "世界包(设定 / 数值 / 物品 / 地图)、AI 的工具手册、可选模型列表",
|
||||
) { onOpenResources() }
|
||||
}
|
||||
item {
|
||||
@@ -152,7 +152,7 @@ fun ProfileScreen(vm: AppViewModel) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
SettingsCard("关于") {
|
||||
FormHint("豆包客户端复刻版:原生 Compose 界面 + 跑在同一进程里的本地 Python 内核,请求不经过任何中转服务器。")
|
||||
FormHint("小人间:一个小世界,里面住着 AI 角色。原生 Compose 界面 + 跑在同一进程里的本地 Python 内核,请求不经过任何中转服务器。")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(onClick = { vm.refresh() }) { Text("重新连接内核", fontSize = 13.sp) }
|
||||
@@ -0,0 +1,295 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.doubao.lynxclone.data.ResidentFunction
|
||||
import com.doubao.lynxclone.data.ResidentItem
|
||||
import com.doubao.lynxclone.data.ResidentPage
|
||||
|
||||
/*
|
||||
* 常驻角色界面(v3.30)。
|
||||
*
|
||||
* 用户需求原文:
|
||||
* 「在界面入口:>XXX。功能选择弹出弹窗。进入功能后弹个html来交互
|
||||
* (调用的api和ai调的一样)」
|
||||
*
|
||||
* 所以这里有两层:
|
||||
* 1. 输入框输入 `>` → 角色菜单 → 选角色 → 功能菜单(两个都是小弹层,
|
||||
* 符合 AGENTS.md「纯菜单可以用弹层」);
|
||||
* 2. 选完功能 → **全屏 WebView** 打开内核生成的 HTML 页,页面里的表单
|
||||
* 直接调 `POST /api/containers/<cid>/residents/<iid>/call` —— 和 AI
|
||||
* 工具是同一个内核函数,所以结果一定一致。
|
||||
*/
|
||||
|
||||
/** 常驻角色菜单(输入框输入 `>` 后弹出;只列**当前地点**能办事的) */
|
||||
@Composable
|
||||
fun ResidentMenuDialog(
|
||||
loading: Boolean,
|
||||
residents: List<ResidentItem>,
|
||||
hint: String = "",
|
||||
onPick: (ResidentItem) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onDismiss() }
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
SheetScaffold(title = "找谁办事", subtitle = "这里能办事的常驻角色(别的地点要先移动过去)", onDismiss = onDismiss) {
|
||||
if (loading) {
|
||||
Text("正在找…", fontSize = 14.sp, color = doubaoTextSecondary(), modifier = Modifier.padding(20.dp))
|
||||
return@SheetScaffold
|
||||
}
|
||||
if (residents.isEmpty()) {
|
||||
Text(
|
||||
hint.ifBlank { "这里没有能用界面办事的常驻角色。" },
|
||||
fontSize = 14.sp, lineHeight = 22.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(20.dp),
|
||||
)
|
||||
return@SheetScaffold
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
residents.forEach { item ->
|
||||
ResidentRow(item = item, onClick = { onPick(item) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 功能菜单(选完常驻角色后弹出) */
|
||||
@Composable
|
||||
fun ResidentFunctionsDialog(
|
||||
resident: ResidentItem,
|
||||
onPick: (ResidentFunction) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onDismiss() }
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
SheetScaffold(
|
||||
title = resident.name,
|
||||
subtitle = listOfNotNull(
|
||||
resident.className.ifBlank { null },
|
||||
resident.placeName.ifBlank { null }?.let { "在$it" } ?: "随处可找",
|
||||
).joinToString(" · "),
|
||||
onDismiss = onDismiss,
|
||||
) {
|
||||
if (resident.desc.isNotBlank()) {
|
||||
Text(
|
||||
resident.desc, fontSize = 13.sp, lineHeight = 20.sp,
|
||||
color = doubaoTextSecondary(), modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
resident.functions.forEach { fn ->
|
||||
FunctionRow(fn = fn, onClick = { onPick(fn) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SheetScaffold(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onDismiss: () -> Unit,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.38f)).clickable(onClick = onDismiss)) {
|
||||
Column(
|
||||
Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 560.dp)
|
||||
.clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable(enabled = false) {}
|
||||
.padding(top = 14.dp, bottom = 18.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier.align(Alignment.CenterHorizontally).width(36.dp).height(4.dp)
|
||||
.clip(RoundedCornerShape(2.dp)).background(doubaoBorder()),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
if (subtitle.isNotBlank()) {
|
||||
Text(subtitle, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"关闭", fontSize = 13.sp, color = doubaoTextSecondary(),
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable { onDismiss() }
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResidentRow(item: ResidentItem, onClick: () -> Unit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(38.dp).clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(item.name.take(1), color = Doubao.Blue, fontSize = 16.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.name, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
if (item.ai) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"AI", fontSize = 10.sp, color = Doubao.Blue,
|
||||
modifier = Modifier.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f)).padding(horizontal = 5.dp, vertical = 1.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
listOfNotNull(
|
||||
item.className.ifBlank { null },
|
||||
item.placeName.ifBlank { null }?.let { "在$it" } ?: "随处可找",
|
||||
"${item.functions.size} 个功能",
|
||||
).joinToString(" · "),
|
||||
fontSize = 12.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
Text("›", fontSize = 20.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FunctionRow(fn: ResidentFunction, onClick: () -> Unit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
fn.kindLabel,
|
||||
fontSize = 10.sp,
|
||||
color = if (fn.kind == "query") Color(0xFF3B82F6) else Color(0xFFE0821B),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(
|
||||
if (fn.kind == "query") Color(0x1A3B82F6) else Color(0x1AE0821B),
|
||||
)
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fn.name, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
if (fn.desc.isNotBlank()) {
|
||||
Text(fn.desc, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Text("›", fontSize = 20.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 功能页(全屏 WebView) ------------------------------ */
|
||||
|
||||
/**
|
||||
* 全屏打开常驻角色功能页。
|
||||
*
|
||||
* ★ 页面由**内核生成**(`/api/containers/.../page`),是 http://127.0.0.1:5199
|
||||
* 的同源页面 —— 所以页面里的 `fetch('/api/.../call')` 能直接调内核,
|
||||
* 不需要 JS 桥传业务数据。这里只注入一个 `Doubao.close()` 让页面的
|
||||
* 「返回」按钮能关掉全屏。
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
|
||||
@Composable
|
||||
fun ResidentPageScreen(page: ResidentPage, pageUrl: String, onClose: () -> Unit) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
FullScreen(
|
||||
title = page.functionName.ifBlank { "常驻角色" },
|
||||
subtitle = page.residentName,
|
||||
onBack = onClose,
|
||||
) {
|
||||
val bridge = remember(page.instanceId, page.functionId) { ResidentCloseBridge(onClose) }
|
||||
DisposableEffect(bridge) {
|
||||
onDispose { bridge.onClose = null }
|
||||
}
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
settings.cacheMode = WebSettings.LOAD_NO_CACHE
|
||||
// ★ 和地图页同一个原因:默认 useWideViewPort=false 时这个 WebView
|
||||
// 里 `vh` 会算成 0(功能页的结果框 max-height 曾因此变 0)。
|
||||
// 页面自带 `<meta viewport width=device-width>`,开它不会缩放错;
|
||||
// 但**不要**开 overviewMode(那会整体缩放页面)。
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = false
|
||||
addJavascriptInterface(bridge, "Doubao")
|
||||
webViewClient = WebViewClient()
|
||||
loadUrl(pageUrl)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 只给功能页用的极小桥:关掉全屏(业务数据走同源 fetch,不经过桥)。 */
|
||||
private class ResidentCloseBridge(@Volatile var onClose: (() -> Unit)?) {
|
||||
@JavascriptInterface
|
||||
fun close() {
|
||||
onClose?.invoke()
|
||||
}
|
||||
}
|
||||
@@ -125,27 +125,14 @@ private class Kind(
|
||||
val isZip: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* 数值状态包:普通字段只有名字和说明。
|
||||
*
|
||||
* ★ 真正的定义(有哪些数值、哪些状态、各自的区间表和脚本)在
|
||||
* **[规则包编辑]** 全屏界面里改 —— 那是一堆嵌套结构,
|
||||
* 塞进"label + 输入框"的表单里既放不下也说不清。
|
||||
*/
|
||||
private val RULEPACK_FIELDS = listOf(
|
||||
Field("name", "名称", "比如「九州数值规则」"),
|
||||
Field("note", "说明", "给别的使用者看的:这个包是干什么的", multiline = true),
|
||||
)
|
||||
|
||||
private val KINDS = listOf(
|
||||
Kind(
|
||||
"worldviews", "世界观", "世界观", WORLD_FIELDS, isZip = true,
|
||||
hint = "绑定同一个世界观的智能体**共用一份记忆**。导出是一个 zip 包(含设定和四件套图片)。",
|
||||
),
|
||||
Kind(
|
||||
"rulepacks", "数值状态包", "规则包", RULEPACK_FIELDS, isZip = true,
|
||||
hint = "世界观挂上它之后,智能体才有**数值**(好感度、声望……)和**状态**(中毒、庇佑……)。" +
|
||||
"包里可以有 Python 脚本做裁决 —— 导入时内核会让你确认。",
|
||||
// ★ v3.0:世界观 = 世界包(设定 + 数值/状态/物品/地图定义 + 脚本)。
|
||||
// v2 里「世界观」和「规则包」是两个资源、两页编辑 —— 现在合成一个,
|
||||
// 点开就是 [世界包编辑] 的四个分区。
|
||||
"worldviews", "世界包", "世界包", WORLD_FIELDS, isZip = true,
|
||||
hint = "一个世界包 = 设定 + 数值/状态/物品/地图的定义 + 脚本,导出的 zip 连脚本一起带走。" +
|
||||
"绑定同一个世界包的智能体**共用一份记忆**。",
|
||||
),
|
||||
Kind(
|
||||
"skills", "Skill", "Skill", SKILL_FIELDS, isZip = false,
|
||||
@@ -168,14 +155,11 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val kind = KINDS[tab]
|
||||
val items: List<Pair<String, Triple<String, String, AgentImage>>> = when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.map {
|
||||
it.id to Triple(it.name, it.setting, it.image)
|
||||
}
|
||||
// v1.2 数值状态包:副标题列出"有几条数值、几条状态、带不带脚本" ——
|
||||
// 那才是用户判断这个包能不能用的信息,光看名字看不出来
|
||||
"rulepacks" -> vm.state.rulePacks.map {
|
||||
val bits = mutableListOf("${it.stats.size} 条数值", "${it.statuses.size} 条状态")
|
||||
if (it.hasScripts) bits += "${it.scripts.size} 个脚本"
|
||||
it.id to Triple(it.name, bits.joinToString(" · "), AgentImage())
|
||||
// ★ v3:副标题列出这个世界包含多少定义 —— 那才是用户判断
|
||||
// 这个包"能不能用"的信息,光看名字看不出来
|
||||
val bits = mutableListOf("${it.stats.size} 数值", "${it.statuses.size} 状态")
|
||||
if (it.hasScripts) bits += "${it.scriptCount} 脚本"
|
||||
it.id to Triple(it.name, bits.joinToString(" · "), it.image)
|
||||
}
|
||||
"skills" -> vm.state.skills.map { it.id to Triple(it.name, it.content, AgentImage()) }
|
||||
else -> vm.state.modelEntries.map {
|
||||
@@ -194,6 +178,8 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
*/
|
||||
val ctx = LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<Triple<String, String, String>?>(null) }
|
||||
// ★ v3.30:内置示例世界包选择框(现在有两个:全能测试世界 / 旧都市)
|
||||
var sampleOpen by remember { mutableStateOf(false) }
|
||||
val saveDoc = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
|
||||
val data = pendingExport
|
||||
pendingExport = null
|
||||
@@ -205,19 +191,19 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
// ---- 规则包的脚本警告 ----
|
||||
// ---- 带脚本包的警告 ----
|
||||
//
|
||||
// ★ 这里是全仓库**唯一**该用弹窗的导入场景:内容就是一段警告 + 两个按钮,
|
||||
// 属于"一次确认"(AGENTS.md 的界面约定:一次确认用弹窗,列表/多组配置
|
||||
// 才开全屏)。真正拦得住的是**服务端**那道 `confirmScripts` 关口,
|
||||
// 这个框只是把风险如实告诉用户。
|
||||
if (vm.pendingRulePack.isNotBlank()) {
|
||||
if (vm.pendingScriptPack.isNotBlank()) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.dismissRulePack() },
|
||||
onDismissRequest = { vm.dismissScriptImport() },
|
||||
title = { Text("这个包里带了 Python 脚本") },
|
||||
text = {
|
||||
Text(
|
||||
vm.rulePackWarning.ifBlank {
|
||||
vm.scriptImportWarning.ifBlank {
|
||||
"包里有可执行脚本。导入后它会在你的设备上运行 —— " +
|
||||
"只导入你信得过的来源。"
|
||||
},
|
||||
@@ -226,12 +212,68 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { vm.importRulePack(vm.pendingRulePack, confirmed = true) }) {
|
||||
TextButton(onClick = { vm.importWorldPackage(vm.pendingScriptPack, confirmed = true) }) {
|
||||
Text("我知道风险,继续", color = Doubao.Blue)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { vm.dismissRulePack() }) { Text("取消") }
|
||||
TextButton(onClick = { vm.dismissScriptImport() }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ★ v3.30:内置示例世界包选择(纯菜单 → 弹窗合适)
|
||||
if (sampleOpen) {
|
||||
fun importSample(asset: String, label: String) {
|
||||
sampleOpen = false
|
||||
runCatching {
|
||||
val bytes = ctx.assets.open(asset).use { it.readBytes() }
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
vm.importWorldPackage(b64)
|
||||
vm.showHint("正在导入「$label」…")
|
||||
}.onFailure { vm.showHint("读不出内置示例包:${it.message}") }
|
||||
}
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { sampleOpen = false },
|
||||
title = { Text("内置示例世界包") },
|
||||
text = {
|
||||
androidx.compose.foundation.layout.Column {
|
||||
Text(
|
||||
"两个包都能直接点「导入」试玩;带脚本,导入时会再确认一次。",
|
||||
fontSize = 13.sp, lineHeight = 19.sp,
|
||||
)
|
||||
TextButton(
|
||||
onClick = { importSample("worlds/all-test.zip", "全能测试世界") },
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("全能测试世界(系统功能样板)", color = Doubao.Blue, fontSize = 14.sp)
|
||||
Text(
|
||||
"数值/状态/物品四类、决斗、驻守角色 —— 逐项试系统功能",
|
||||
fontSize = 11.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = { importSample("worlds/old-city.zip", "旧都市") },
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("旧都市(常驻角色样板)", color = Doubao.Blue, fontSize = 14.sp)
|
||||
Text(
|
||||
"家/学校/商店/小卖铺/森林;三家店与门卫都能在输入框打 > 办事",
|
||||
fontSize = 11.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { sampleOpen = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -243,12 +285,11 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
}.onSuccess { bytes ->
|
||||
if (kind.isZip) {
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
// ★ 规则包**单独一条路**:它是唯一允许夹带可执行 Python 的
|
||||
// 包类型,内核会让它带 `confirmScripts` 才落库。
|
||||
// 第一次(不确认)会返回 needConfirm + warning,
|
||||
// 界面拿去弹警告;用户点了「我知道风险,继续」再传一次。
|
||||
if (kind.id == "rulepacks") vm.importRulePack(b64)
|
||||
else vm.importPackage(kind.id, b64, "")
|
||||
// ★ 世界包是**唯一允许夹带可执行 Python 的包类型**:
|
||||
// 内核要求带 `confirmScripts` 才落库,第一次返回
|
||||
// needConfirm + 警告,界面弹框、用户确认后再传一次
|
||||
// (这个往返收在 `importWorldPackage` 里)。
|
||||
vm.importWorldPackage(b64)
|
||||
} else {
|
||||
vm.importPackage(kind.id, "", bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
@@ -258,9 +299,14 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界观 · 规则包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
subtitle = "世界包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
// ★ v3.12:内置示例世界包 —— 一键导入,不用先找文件/传文件。
|
||||
// ★ v3.30:从两个示例里选(全能测试世界 / 旧都市)。
|
||||
if (kind.isZip) {
|
||||
TopTextAction("示例包") { sampleOpen = true }
|
||||
}
|
||||
TopTextAction("导入") {
|
||||
if (kind.isZip) openDoc.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
else openDoc.launch(arrayOf("application/json", "text/plain", "*/*"))
|
||||
@@ -285,11 +331,11 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") {
|
||||
// ★ 规则包**不是**"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。
|
||||
// 所以「新建」直接建一个**带模板**的包并进去,
|
||||
// 而不是先弹"名称+说明"的表单、再让用户自己去找编辑器。
|
||||
if (kind.id == "rulepacks") { vm.createRulePackFromTemplate(); return@RowAction }
|
||||
// ★ 世界包不是"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。所以「新建」直接
|
||||
// 建一个**带模板**的包并进去,而不是先弹"名称+设定"的表单、
|
||||
// 再让用户自己去找编辑器。
|
||||
if (kind.id == "worldviews") { vm.createWorldPackFromTemplate(); return@RowAction }
|
||||
editId = null; editing = true
|
||||
}
|
||||
}
|
||||
@@ -325,10 +371,10 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable {
|
||||
// ★ 规则包走**独立的全屏编辑页** —— 它的内容
|
||||
// (定义表 + 脚本)不是"label + 输入框"那套表单
|
||||
// 能表达的,硬塞进去会变成一堆看不懂的文本框
|
||||
if (kind.id == "rulepacks") { vm.openRulePackEdit(id); return@clickable }
|
||||
// ★ 世界包走**独立的全屏编辑页**(设定/数值/状态/脚本
|
||||
// 四个分区)—— 它的内容不是"label + 输入框"那套
|
||||
// 表单能表达的;Skill / 模型还是下面那套字段表单。
|
||||
if (kind.id == "worldviews") { vm.openWorldPackEdit(id); return@clickable }
|
||||
editId = id; editing = true
|
||||
}
|
||||
.padding(12.dp),
|
||||
@@ -395,7 +441,9 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
// 世界包走独立的全屏编辑页(由 vm.editingWorldPack 驱动),
|
||||
// 不经过下面这套字段表单
|
||||
if (editing && kind.id != "worldviews") {
|
||||
ResourceEditScreen(
|
||||
vm = vm,
|
||||
kind = kind,
|
||||
@@ -420,7 +468,13 @@ private fun ResourceEditScreen(
|
||||
val initial: Map<String, String> = remember(id, kind.id) {
|
||||
when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "setting" to it.setting)
|
||||
mapOf(
|
||||
"name" to it.name,
|
||||
"setting" to it.setting,
|
||||
// ★ 世界观挂的数值状态包 —— 不读出来的话,一进编辑页
|
||||
// 选择器就显示"没挂",用户一保存就把原来的关联抹了
|
||||
"rulePackId" to it.rulePackId,
|
||||
)
|
||||
} ?: emptyMap()
|
||||
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "content" to it.content)
|
||||
@@ -475,7 +529,11 @@ private fun ResourceEditScreen(
|
||||
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
|
||||
extra["noTools"] = values["noTools"] == "1"
|
||||
}
|
||||
if (kind.id == "worldviews") extra["image"] = worldImage
|
||||
if (kind.id == "worldviews") {
|
||||
extra["image"] = worldImage
|
||||
// ★ 世界观挂的数值状态包(空 = 不挂)
|
||||
extra["rulePackId"] = values["rulePackId"].orEmpty()
|
||||
}
|
||||
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
@@ -550,6 +608,84 @@ private fun ResourceEditScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 数值状态包:**世界观是它的挂载点**(需求 §3.6)。
|
||||
//
|
||||
// 以前这里**没有这个入口** —— 内核那条链路是通的
|
||||
// (`agent_context.pack_of` 读 `世界观.rulePackId`),
|
||||
// 但界面上根本挂不上,于是整个数值/状态系统在 App 里是死的:
|
||||
// 用户在「资源 → 规则包」里辛苦写完,回来发现没有任何地方能启用它。
|
||||
//
|
||||
// 只在世界观这一种资源上出现(规则包/Skill/模型没有这个概念)。
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("数值状态包")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
Text(
|
||||
"挂上之后,绑这个世界观的智能体就有**数值**(好感度、声望……)" +
|
||||
"和**状态**(中毒、庇佑……)。不挂就没有 —— 提示词里那两段是空的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val pickedPack = values["rulePackId"].orEmpty()
|
||||
val packs = vm.state.rulePacks
|
||||
if (packs.isEmpty()) {
|
||||
Text(
|
||||
"还没有数值状态包。去「资源 → 规则包」新建一个(有模板)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// 一行一个:手机上横向排不下(包名可能很长),
|
||||
// 而且"选中哪个"要一眼看得出来
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { values = values + ("rulePackId" to "") }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (pickedPack.isBlank()) "◉" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (pickedPack.isBlank()) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text("不挂(没有数值和状态)", fontSize = 13.sp, color = doubaoText())
|
||||
}
|
||||
for (p in packs) {
|
||||
val on = p.id == pickedPack
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
values = values + ("rulePackId" to p.id)
|
||||
}.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (on) "◉" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(p.name.ifBlank { "(未命名)" }, fontSize = 13.sp, color = doubaoText())
|
||||
val bits = mutableListOf<String>()
|
||||
bits.add("${p.stats.size} 条数值")
|
||||
bits.add("${p.statuses.size} 条状态")
|
||||
if (p.hasScripts) bits.add("带脚本")
|
||||
Text(bits.joinToString(" · "), fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("外观(四件套)")
|
||||
@@ -328,6 +328,17 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
checked = draft.speech.autoRead,
|
||||
onChange = { draft = draft.copy(speech = draft.speech.copy(autoRead = it)) },
|
||||
)
|
||||
FormSwitch(
|
||||
title = "朗读情绪指令(括号变语音指令)",
|
||||
sub = "回复里(括号)/【方括号】写的旁白变成豆包语音的情绪指令,不念出来;" +
|
||||
"界面里显示成灰色小字",
|
||||
checked = draft.speech.emotionTags,
|
||||
onChange = { draft = draft.copy(speech = draft.speech.copy(emotionTags = it)) },
|
||||
)
|
||||
FormHint(
|
||||
"只有「豆包语音 V3」(2.0 音色)支持语音指令;其他引擎开启后只会把括号旁白" +
|
||||
"从朗读里去掉。豆包控制台里这个写法叫「语音指令 / [#指令]」,不额外计费。",
|
||||
)
|
||||
|
||||
FormLabel("语音输入(STT)")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
@@ -516,7 +527,7 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
SettingsCard("外观") {
|
||||
FormSwitch(
|
||||
title = "背景跟随说话者",
|
||||
sub = "群聊时,展示区的立绘和背景跟着当前发言的人换 —— " +
|
||||
sub = "多人会话时,展示区的立绘和背景跟着当前发言的人换 —— " +
|
||||
"一眼就能看出这句话是谁说的。关掉的话固定用主智能体的。",
|
||||
checked = vm.state.settings.followSpeaker,
|
||||
onChange = { vm.setFollowSpeaker(it) },
|
||||
@@ -1260,6 +1271,7 @@ internal data class SettingsDraft(
|
||||
if (speech.ttsVoice != base.ttsVoice) sp["ttsVoice"] = speech.ttsVoice
|
||||
if (speech.ttsSpeed != base.ttsSpeed) sp["ttsSpeed"] = speech.ttsSpeed
|
||||
if (speech.autoRead != base.autoRead) sp["autoRead"] = speech.autoRead
|
||||
if (speech.emotionTags != base.emotionTags) sp["emotionTags"] = speech.emotionTags
|
||||
if (speech.sttEngine != base.sttEngine) sp["sttEngine"] = speech.sttEngine
|
||||
if (speech.sttModel != base.sttModel) sp["sttModel"] = speech.sttModel
|
||||
if (speech.sttLanguage != base.sttLanguage) sp["sttLanguage"] = speech.sttLanguage
|
||||
@@ -0,0 +1,546 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.BagItem
|
||||
|
||||
/**
|
||||
* 「我的角色」—— **用户角色**的属性与功能(v3.7)。
|
||||
*
|
||||
* 用户需求原话:「这个加个人属性(状态,数值,物品管理等)和功能(对决移动等)」
|
||||
*
|
||||
* 页面结构:
|
||||
* · 角色卡:这一局里"你"是谁(容器设置的名字 + 介绍)
|
||||
* · 数值:气血之类(进度条 + 当前/上限)
|
||||
* · 状态:常驻/限时 + 摘掉 / 给自己加
|
||||
* · 物品:获得 / 使用 / 对谁使用 / 给予 / 抛弃(和智能体同一套引擎)
|
||||
* · 功能:**一对一对决**(选同局成员)+ **移动**(走到某个地点)
|
||||
*
|
||||
* ★ 和 [BagScreen] 的区别:那个看的是某个 AI 的背包;这里是「你」自己的。
|
||||
*/
|
||||
@Composable
|
||||
fun UserItemsScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
BackHandler(enabled = true) { onBack() }
|
||||
val container = vm.userRoleContainer()
|
||||
var addOpen by remember { mutableStateOf(false) }
|
||||
var statusOpen by remember { mutableStateOf(false) }
|
||||
var useOnFor by remember { mutableStateOf<BagItem?>(null) }
|
||||
var giveFor by remember { mutableStateOf<BagItem?>(null) }
|
||||
var useWithFor by remember { mutableStateOf<BagItem?>(null) }
|
||||
var useWithPicked by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
var duelOpen by remember { mutableStateOf(false) }
|
||||
var moveOpen by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "我的角色",
|
||||
subtitle = listOfNotNull(
|
||||
container?.name?.ifBlank { null },
|
||||
"你是:${vm.userRoleName()}",
|
||||
).joinToString(" · "),
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("获得物品") { addOpen = true }
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// ---- 角色卡 ----
|
||||
val desc = vm.userRoleDesc()
|
||||
SectionLabel("角色")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
vm.userRoleName(),
|
||||
fontSize = 16.sp,
|
||||
color = doubaoText(),
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
if (desc.isNotBlank()) {
|
||||
Text(
|
||||
desc,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
val place = vm.userPlaceName.ifBlank { "未分配地点" }
|
||||
Text(
|
||||
"当前位置:$place",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 死亡 / 复活(v3.20:气血为 0 判死,决斗中死亡算输)----
|
||||
if (vm.userDead) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E).copy(alpha = 0.10f))
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"已死亡",
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
Text(
|
||||
"世界规则判了死亡(比如气血为 0);决斗中死亡算输。" +
|
||||
"改回「平常」就是复活 —— 用户是规则的主人。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
Text(
|
||||
"复活",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.padding(top = 8.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { vm.reviveUser() }
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 数值 ----
|
||||
SectionLabel("数值")
|
||||
if (vm.userStats.isEmpty()) {
|
||||
Hint("这一局没有定义数值(世界包 info.stats 为空)。")
|
||||
}
|
||||
for ((name, value, max) in vm.userStats) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(name, fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
if (max > 0) "${value.toInt()} / ${max.toInt()}" else "${value.toInt()}",
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoTextSecondary().copy(alpha = 0.18f)),
|
||||
) {
|
||||
val frac = if (max > 0) (value / max).coerceIn(0f, 1f) else 0f
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(frac)
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 功能 ----
|
||||
SectionLabel("功能")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
RowAction("决斗") { duelOpen = true }
|
||||
RowAction("🚶 移动") { moveOpen = true }
|
||||
}
|
||||
|
||||
// ---- 状态 ----
|
||||
SectionLabel("状态")
|
||||
if (vm.userStatuses.isEmpty()) {
|
||||
Hint("当前没有状态。别人能给你挂状态(比如中毒),你自己也能加。")
|
||||
}
|
||||
for ((name, remain) in vm.userStatuses) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(name, fontSize = 14.sp, color = doubaoText(), fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
if (remain < 0) "常驻" else "剩 $remain 轮",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("摘掉") { vm.userStatusAction(name, "drop") }
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(vertical = 4.dp)) {
|
||||
RowAction("+ 给自己加个状态") { statusOpen = true }
|
||||
}
|
||||
|
||||
// ---- 物品 ----
|
||||
SectionLabel("物品")
|
||||
if (vm.userItems.isEmpty()) {
|
||||
Hint("还没有物品。点右上「获得物品」拿一个,或让同局的智能体送你。")
|
||||
}
|
||||
for (it in vm.userItems) {
|
||||
UserItemCard(
|
||||
item = it,
|
||||
onUse = { vm.userItemAction(it, "use") },
|
||||
onUseWith = { useWithFor = it; useWithPicked = emptySet() },
|
||||
onUseOn = { useOnFor = it },
|
||||
onGive = { giveFor = it },
|
||||
onDrop = { vm.userItemAction(it, "drop") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================= 弹窗 =================
|
||||
if (addOpen) {
|
||||
val defs = vm.userItemsDefinitions()
|
||||
AlertDialog(
|
||||
onDismissRequest = { addOpen = false },
|
||||
title = { Text("获得物品") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (defs.isEmpty()) {
|
||||
Text("这个世界包没有定义物品。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (d in defs) {
|
||||
Text(
|
||||
"${d.name}(${d.kindLabel})",
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.grantUserItem(d.id, 1)
|
||||
addOpen = false
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { addOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
if (statusOpen) {
|
||||
val defs = vm.userStatusDefinitions()
|
||||
AlertDialog(
|
||||
onDismissRequest = { statusOpen = false },
|
||||
title = { Text("给自己加状态") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (defs.isEmpty()) {
|
||||
Text("这个世界包没有定义状态。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (d in defs) {
|
||||
Text(
|
||||
"${d.name}(${if (d.kind == "persistent") "常驻" else "限时"})",
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.userStatusAction(d.name, "grant")
|
||||
statusOpen = false
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { statusOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
useOnFor?.let { item ->
|
||||
val members = vm.userRoleMembers()
|
||||
AlertDialog(
|
||||
onDismissRequest = { useOnFor = null },
|
||||
title = { Text("把「${item.name}」对谁使用?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for ((id, name) in members) {
|
||||
Text(
|
||||
name.ifBlank { id },
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.userItemAction(item, "use", targets = listOf(id))
|
||||
useOnFor = null
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { useOnFor = null }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
giveFor?.let { item ->
|
||||
val members = vm.userRoleMembers()
|
||||
AlertDialog(
|
||||
onDismissRequest = { giveFor = null },
|
||||
title = { Text("把「${item.name}」送给谁?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for ((id, name) in members) {
|
||||
Text(
|
||||
name.ifBlank { id },
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
vm.userItemAction(item, "give", target = id)
|
||||
giveFor = null
|
||||
}
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { giveFor = null }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// 带材料使用:选要一起用掉的物品(工作台这类脚本要 api.attached)
|
||||
useWithFor?.let { item ->
|
||||
val others = vm.userItems.filter { it.id != item.id && it.count != 0 }
|
||||
AlertDialog(
|
||||
onDismissRequest = { useWithFor = null },
|
||||
title = { Text("带上材料使用「${item.name}」") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"选要一起用掉的物品(脚本通过 api.attached 读到)。" +
|
||||
"比如工作台要带 2 根木头,做出一把木椅。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
if (others.isEmpty()) {
|
||||
Text("背包里没有别的物品可带。", fontSize = 13.sp,
|
||||
color = doubaoTextSecondary())
|
||||
}
|
||||
for (o in others) {
|
||||
val on = o.id in useWithPicked
|
||||
val cnt = if (o.count < 0) "∞" else "×${o.count}"
|
||||
Text(
|
||||
(if (on) "✓ " else "") + "${o.name}$cnt",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoText(),
|
||||
fontWeight = if (on) FontWeight.Medium else FontWeight.Normal,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
useWithPicked = if (on) useWithPicked - o.id
|
||||
else useWithPicked + o.id
|
||||
}
|
||||
.padding(vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.userItemAction(item, "use", with = useWithPicked.toList())
|
||||
useWithFor = null
|
||||
}) { Text("使用") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { useWithFor = null }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 决斗:选一个同局成员(v3.17:多回合,决斗留在当前对话里)
|
||||
if (duelOpen) {
|
||||
val members = vm.userRoleMembers()
|
||||
AlertDialog(
|
||||
onDismissRequest = { duelOpen = false },
|
||||
title = { Text("向谁发起决斗?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"决斗留在当前对话里(不另开对话),一回合一点「出招」推进;" +
|
||||
"过程和结果由世界脚本裁决,中断要双方同意。" +
|
||||
"没有武器(target 类物品)的一方会被直接判失败 —— " +
|
||||
"先确认自己背包里有能对别人用的东西。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
Text(
|
||||
"每回合双方各用自己的武器出手(跑物品脚本,∞ 武器不消耗)," +
|
||||
"决斗界面里可以每回合换武器;没有回合上限。" +
|
||||
"结果只有四种:赢 / 输 / 平局 / 停手。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
if (members.isEmpty()) {
|
||||
Text("这一局还没有成员。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for ((id, name) in members) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
name.ifBlank { id },
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("选他") {
|
||||
vm.startDuelWith(id)
|
||||
duelOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { duelOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// 移动:选一个地点
|
||||
if (moveOpen) {
|
||||
val places = vm.placesOfCurrentContainer()
|
||||
AlertDialog(
|
||||
onDismissRequest = { moveOpen = false },
|
||||
title = { Text("走到哪里?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (places.isEmpty()) {
|
||||
Text("这一局没有地点(世界包 info.places 为空)。",
|
||||
fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
for (p in places) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
(if (p.id == vm.userPlaceId) "✓ " else "") + p.name,
|
||||
fontSize = 15.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction(if (p.id == vm.userPlaceId) "就在这儿" else "去") {
|
||||
vm.userMove(p.id)
|
||||
moveOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { moveOpen = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户背包里的一件物品(数量 / 类型 / 四个操作) */
|
||||
@Composable
|
||||
private fun UserItemCard(
|
||||
item: BagItem,
|
||||
onUse: () -> Unit,
|
||||
onUseWith: () -> Unit,
|
||||
onUseOn: () -> Unit,
|
||||
onGive: () -> Unit,
|
||||
onDrop: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.name, fontSize = 15.sp, color = doubaoText(), fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(item.countLabel, fontSize = 12.sp, color = Doubao.Blue, fontWeight = FontWeight.Medium)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(item.kindLabel, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
if (item.desc.isNotBlank()) {
|
||||
Text(
|
||||
item.desc,
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (item.usable) RowAction("使用") { onUse() }
|
||||
// ★ v3.21:带材料使用(工作台这类被动物品要材料)
|
||||
if (item.usable && item.kind != "target") RowAction("带材料用") { onUseWith() }
|
||||
if (item.kind == "target") RowAction("对谁使用") { onUseOn() }
|
||||
RowAction("给予") { onGive() }
|
||||
RowAction("抛弃") { onDrop() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.ItemDef
|
||||
import com.doubao.lynxclone.data.PlaceDef
|
||||
import com.doubao.lynxclone.data.StatDef
|
||||
import com.doubao.lynxclone.data.StatusDef
|
||||
|
||||
/**
|
||||
* 世界包的**定义编辑区**(v3.0 补遗):
|
||||
* 手机端也能改数值 / 状态 / 物品 / 地点定义,不用再去电脑上改 JSON。
|
||||
*
|
||||
* ★ 交互取舍:手机上做不了电脑那种表格,所以用"一行 + 几个输入框"的
|
||||
* 紧凑布局;类型(kind / 主动被动目标)做成**点一下循环切换**的按钮,
|
||||
* 比下拉菜单少一次点击。
|
||||
* ★ 复杂的嵌套结构(数值的区间文案 `ranges`、物品的 hint)**不在这里编辑**,
|
||||
* 保存时原样带回(`worldPackInfoJson` 里保留),不会被静默抹掉。
|
||||
*/
|
||||
|
||||
/** 一行里的紧凑输入框 */
|
||||
@Composable
|
||||
private fun CompactField(
|
||||
value: String,
|
||||
placeholder: String,
|
||||
modifier: Modifier = Modifier,
|
||||
onValue: (String) -> Unit,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onValue,
|
||||
placeholder = { Text(placeholder, fontSize = 11.sp) },
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/** 点一下循环切换的按钮(类型 / 共享 / 无限 这类布尔或枚举字段) */
|
||||
@Composable
|
||||
private fun CycleAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.padding(vertical = 8.dp)
|
||||
.padding(horizontal = 6.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoAccentSoft())
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
private fun <T> List<T>.replaceAt(i: Int, item: T): List<T> = toMutableList().also { it[i] = item }
|
||||
private fun <T> List<T>.removeAt2(i: Int): List<T> = toMutableList().also { it.removeAt(i) }
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 数值 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
fun EditableStatsSection(stats: List<StatDef>, onStats: (List<StatDef>) -> Unit) {
|
||||
SectionLabel("数值定义")
|
||||
Hint("共享 = 整个世界共用一份(声望);自身 = 每个角色各算一份(好感度)。" +
|
||||
"初始值不填 = 按 min 起步(测试世界的「气血」填 100,配合「气血为 0 = 死亡」)。区间文案在电脑端改。")
|
||||
if (stats.isEmpty()) Hint("没有数值。数值是这个世界的规则,比如好感度、声望。")
|
||||
for ((i, s) in stats.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(s.name, "名称", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
// ★ v3.30:稳定 id(空 = 用名字当 id);脚本/接口按 id 或名字引用
|
||||
CompactField(s.id, "id(空=名字)", Modifier.weight(0.8f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (s.shared) "世界" else "自身") {
|
||||
onStats(stats.replaceAt(i, s.copy(shared = !s.shared)))
|
||||
}
|
||||
CycleAction("删除") { onStats(stats.removeAt2(i)) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(fmt(s.min), "min", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(min = numOr(v, s.min))))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(fmt(s.max), "max", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(max = numOr(v, s.max))))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(s.script, "脚本文件名", Modifier.weight(1.2f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(script = v.trim())))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// ★ v3.20:初始值(可选,空 = min)—— 气血这类要「100 起步」的数值靠它
|
||||
CompactField(s.initial?.let { fmt(it) } ?: "", "初始值(空 = min)", Modifier.weight(1f)) { v ->
|
||||
onStats(stats.replaceAt(i, s.copy(
|
||||
initial = if (v.isBlank()) null else numOr(v, s.initial ?: s.min))))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一条数值") {
|
||||
onStats(stats + StatDef(name = "新数值", min = 0.0, max = 100.0, shared = false))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 状态 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
fun EditableStatusesSection(statuses: List<StatusDef>, onStatuses: (List<StatusDef>) -> Unit) {
|
||||
SectionLabel("状态定义")
|
||||
Hint("限时 timed:每轮 -1、归零消失;常驻 persistent:不会自己过期。")
|
||||
if (statuses.isEmpty()) Hint("没有状态。状态是挂在这个角色身上的临时状况,比如中毒、庇佑。")
|
||||
for ((i, s) in statuses.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(s.name, "名称", Modifier.weight(1f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
// ★ v3.30:稳定 id(空 = 用名字当 id)
|
||||
CompactField(s.id, "id(空=名字)", Modifier.weight(0.8f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (s.kind == "persistent") "常驻" else "限时") {
|
||||
onStatuses(
|
||||
statuses.replaceAt(
|
||||
i, s.copy(kind = if (s.kind == "persistent") "timed" else "persistent"),
|
||||
),
|
||||
)
|
||||
}
|
||||
CycleAction("删除") { onStatuses(statuses.removeAt2(i)) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(s.turns.toString(), "轮数", Modifier.weight(1f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(turns = numOr(v, s.turns.toDouble()).toInt())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(s.maxStack.toString(), "最多几层", Modifier.weight(1f)) { v ->
|
||||
onStatuses(
|
||||
statuses.replaceAt(i, s.copy(maxStack = numOr(v, s.maxStack.toDouble()).toInt())),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(s.script, "脚本文件名", Modifier.weight(1.2f)) { v ->
|
||||
onStatuses(statuses.replaceAt(i, s.copy(script = v.trim())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一条状态") {
|
||||
onStatuses(statuses + StatusDef(name = "新状态", kind = "timed", turns = 3, maxStack = 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 物品 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private val ITEM_KINDS = listOf("plain", "passive", "active", "target")
|
||||
private fun itemKindLabel(kind: String): String = when (kind) {
|
||||
"active" -> "主动"
|
||||
"passive" -> "被动"
|
||||
"target" -> "目标"
|
||||
else -> "无脚本"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ItemsSection(
|
||||
items: List<ItemDef>,
|
||||
onItems: (List<ItemDef>) -> Unit,
|
||||
scriptNames: List<String>,
|
||||
) {
|
||||
SectionLabel("物品定义")
|
||||
Hint("主动=每轮生效;被动=使用触发;目标=对别人用;无脚本=只能被查询/出旁白。成员第一次进这一局按「初始数量」发放。")
|
||||
if (items.isEmpty()) Hint("没有物品。物品四件套:主动 / 被动 / 目标 / 无脚本。")
|
||||
for ((i, it) in items.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(it.id, "id(英文)", Modifier.weight(1f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(it.name, "名字", Modifier.weight(1f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(it.category, "分类", Modifier.weight(0.8f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(category = v)))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CycleAction(itemKindLabel(it.kind)) {
|
||||
val next = ITEM_KINDS[(ITEM_KINDS.indexOf(it.kind) + 1) % ITEM_KINDS.size]
|
||||
onItems(items.replaceAt(i, it.copy(kind = next)))
|
||||
}
|
||||
CompactField(it.initial.toString(), "初始数量", Modifier.weight(0.8f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(initial = numOr(v, it.initial.toDouble()).toInt())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (it.unlimited) "无限 ∞" else "有限") {
|
||||
onItems(items.replaceAt(i, it.copy(unlimited = !it.unlimited)))
|
||||
}
|
||||
CycleAction("删除") { onItems(items.removeAt2(i)) }
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(it.script, "脚本文件名", Modifier.weight(1f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(script = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(it.desc, "介绍(会注入给 AI)", Modifier.weight(2f)) { v ->
|
||||
onItems(items.replaceAt(i, it.copy(desc = v)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一个物品") {
|
||||
onItems(items + ItemDef(id = "item_${items.size + 1}", name = "新物品", category = "其他"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 地点 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
fun PlacesSection(
|
||||
places: List<PlaceDef>,
|
||||
onPlaces: (List<PlaceDef>) -> Unit,
|
||||
onPickBackground: (String) -> Unit,
|
||||
onClearBackground: (String) -> Unit,
|
||||
) {
|
||||
SectionLabel("地点定义")
|
||||
Hint("默认地点 = 新成员进来的地方;相邻地点限制移动(留空 = 随便走);聊天按地点分开。")
|
||||
if (places.isEmpty()) Hint("还没有地点。定义之后这一局就有地图了。")
|
||||
for ((i, p) in places.withIndex()) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(p.id, "id(英文)", Modifier.weight(1f)) { v ->
|
||||
onPlaces(places.replaceAt(i, p.copy(id = v.trim())))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(p.name, "地点名", Modifier.weight(1f)) { v ->
|
||||
onPlaces(places.replaceAt(i, p.copy(name = v)))
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CompactField(p.category, "分类", Modifier.weight(0.8f)) { v ->
|
||||
onPlaces(places.replaceAt(i, p.copy(category = v)))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CycleAction(if (p.isDefault) "默认地点" else "非默认") {
|
||||
onPlaces(places.replaceAt(i, p.copy(isDefault = !p.isDefault)))
|
||||
}
|
||||
CycleAction(if (p.hidden) "隐藏" else "显示") {
|
||||
onPlaces(places.replaceAt(i, p.copy(hidden = !p.hidden)))
|
||||
}
|
||||
CycleAction("删除") { onPlaces(places.removeAt2(i)) }
|
||||
}
|
||||
CompactField(
|
||||
p.desc,
|
||||
"描述(会注入给 AI,AI 才知道这地方长什么样)",
|
||||
Modifier.fillMaxWidth(),
|
||||
) { v -> onPlaces(places.replaceAt(i, p.copy(desc = v))) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CompactField(p.exits.joinToString(","), "相邻地点 id(逗号分隔)", Modifier.weight(1.4f)) { v ->
|
||||
onPlaces(
|
||||
places.replaceAt(
|
||||
i,
|
||||
p.copy(
|
||||
exits = v.split(',', ',', ' ').map { it.trim() }.filter { it.isNotEmpty() },
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
CycleAction(if (p.background.isBlank()) "背景:无" else "背景:已设置") {
|
||||
if (p.background.isBlank()) onPickBackground(p.id) else onClearBackground(p.id)
|
||||
}
|
||||
if (p.background.isBlank()) {
|
||||
CycleAction("上传背景") { onPickBackground(p.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(horizontal = 12.dp, vertical = 4.dp)) {
|
||||
CycleAction("+ 加一个地点") {
|
||||
onPlaces(places + PlaceDef(id = "place_${places.size + 1}", name = "新地点"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 小工具 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun numOr(s: String, fallback: Double): Double =
|
||||
s.trim().toDoubleOrNull() ?: fallback
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toInt().toDouble()) v.toInt().toString() else v.toString()
|
||||
|
||||
/** 这个包里的脚本文件名(物品/状态/数值引用时给个提示) */
|
||||
@Composable
|
||||
private fun ScriptHint(scriptNames: List<String>) {
|
||||
if (scriptNames.isEmpty()) return
|
||||
Text(
|
||||
"可用脚本:" + scriptNames.joinToString("、"),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** 只是防止 Kotlin 报未使用(ScriptHint 留给后续在编辑行里用) */
|
||||
@Suppress("unused")
|
||||
private fun keepScriptHint(scriptNames: List<String>) = scriptNames
|
||||
@@ -0,0 +1,495 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.StatDef
|
||||
import com.doubao.lynxclone.data.StatusDef
|
||||
|
||||
/**
|
||||
* [世界包编辑](v3.0:世界观 + 规则包合并)—— 全屏。
|
||||
*
|
||||
* ## 为什么合并成一个界面
|
||||
*
|
||||
* v2 里"一个世界"是两样东西:世界观(设定 + 图片)在资源页里点开改,
|
||||
* 规则包(数值/状态/脚本)在另一个全屏页里改。用户要配一个世界得来回跳两页,
|
||||
* 而且**忘了挂上规则包**是最常见的坑(挂了才有数值,不挂就没有)。
|
||||
*
|
||||
* v3 起它们就是一个包:设定、定义、脚本在同一个界面里,四个分区切换。
|
||||
* 物品 / 地图分区等 P3 / P4 落地后再加。
|
||||
*
|
||||
* ## 脚本框的形状(照抄节点代码组件的做法)
|
||||
*
|
||||
* 1. **不软换行** —— `else:` 折成两行、缩进全乱,而 Python 的缩进就是语法。
|
||||
* 2. **有高度上限** —— 只写 `heightIn(min=...)` 的话脚本一长框就长到屏幕外。
|
||||
*
|
||||
* ## 定义表现在也能编辑了(v3.0 补遗)
|
||||
*
|
||||
* 数值 / 状态 / 物品 / 地点都能在手机上改(每行几个输入框,紧凑布局)。
|
||||
* 只有区间文案(ranges)这种嵌套结构仍要在电脑端改 —— 保存时原样带回。
|
||||
*/
|
||||
@Composable
|
||||
fun WorldPackEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val pack = vm.editingWorldPack
|
||||
if (pack == null) {
|
||||
FullScreen(title = "世界包编辑", onBack = onBack) { Hint("正在读……") }
|
||||
return
|
||||
}
|
||||
|
||||
var tab by remember(pack.id) { mutableStateOf(0) }
|
||||
var name by remember(pack.id) { mutableStateOf(pack.name) }
|
||||
var setting by remember(pack.id) { mutableStateOf(pack.setting) }
|
||||
var stats by remember(pack.id) { mutableStateOf(pack.stats) }
|
||||
var statuses by remember(pack.id) { mutableStateOf(pack.statuses) }
|
||||
var items by remember(pack.id) { mutableStateOf(pack.items) }
|
||||
var places by remember(pack.id) { mutableStateOf(pack.places) }
|
||||
var scripts by remember(pack.id) { mutableStateOf(pack.scripts) }
|
||||
var editing by remember(pack.id) { mutableStateOf("") }
|
||||
var newScript by remember(pack.id) { mutableStateOf("") }
|
||||
var draft by remember(pack.id) { mutableStateOf("") }
|
||||
var worldImage by remember(pack.id) { mutableStateOf(pack.image) }
|
||||
|
||||
// 外观图是**即时上传**的(选完就落到世界包目录里),上传完 state 会变 ——
|
||||
// 跟着刷新预览,不然用户选完了预览还是空的("上传失败"错觉)。
|
||||
vm.state.worldviews.firstOrNull { it.id == pack.id }?.let {
|
||||
if (it.image != worldImage) worldImage = it.image
|
||||
}
|
||||
|
||||
// ★ 上传**地点背景**后内核会把落盘路径写回 info.places[].background ——
|
||||
// 用内核版本补到草稿里(只补"本地空、内核有"的,别覆盖用户正在改的字段)。
|
||||
androidx.compose.runtime.LaunchedEffect(pack.places) {
|
||||
if (pack.places.isEmpty()) return@LaunchedEffect
|
||||
places = places.map { local ->
|
||||
val fresh = pack.places.firstOrNull { it.id == local.id } ?: return@map local
|
||||
if (local.background.isBlank() && fresh.background.isNotBlank()) {
|
||||
local.copy(background = fresh.background)
|
||||
} else {
|
||||
local
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val ctx = LocalContext.current
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
// 和智能体编辑页**同一份实现** —— 大图/压缩/GIF/SAF 没扩展名这些坑
|
||||
// 两边一模一样,抄两份迟早只修一份
|
||||
vm.uploadWorldviewAssetFrom(ctx.applicationContext, pack.id, slot, uri)
|
||||
}
|
||||
// 地点背景:选完直接上传到那个地点(不用等"保存")
|
||||
var pendingPlace by remember { mutableStateOf("") }
|
||||
val pickPlaceBg = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
val pid = pendingPlace
|
||||
pendingPlace = ""
|
||||
if (uri == null || pid.isBlank()) return@rememberLauncherForActivityResult
|
||||
vm.uploadPlaceBackgroundFrom(ctx.applicationContext, pack.id, pid, uri)
|
||||
}
|
||||
|
||||
val tabs = listOf("设定", "数值", "状态", "物品", "地点", "脚本")
|
||||
|
||||
FullScreen(
|
||||
title = "世界包编辑",
|
||||
subtitle = "${name.ifBlank { "未命名" }} · ${stats.size} 数值 · ${statuses.size} 状态 · " +
|
||||
"${items.size} 物品 · ${places.size} 地点 · ${scripts.size} 脚本",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("保存") {
|
||||
vm.saveWorldPack(name, setting, stats, statuses, items, places, scripts)
|
||||
}
|
||||
},
|
||||
) {
|
||||
// ---- 分区 tab(横向滚动:6 个在小屏上一行放不下)----
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
for ((i, label) in tabs.withIndex()) {
|
||||
val on = i == tab
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) androidx.compose.ui.graphics.Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { tab = i }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
when (tab) {
|
||||
0 -> SettingSection(
|
||||
name = name, onName = { name = it },
|
||||
setting = setting, onSetting = { setting = it },
|
||||
image = worldImage,
|
||||
onPick = { slot -> pendingSlot = slot; pickImage.launch(arrayOf("image/*")) },
|
||||
onClear = { slot -> vm.uploadWorldviewAsset(pack.id, slot, "", "") },
|
||||
)
|
||||
1 -> EditableStatsSection(stats, onStats = { stats = it })
|
||||
2 -> EditableStatusesSection(statuses, onStatuses = { statuses = it })
|
||||
3 -> ItemsSection(
|
||||
items = items,
|
||||
onItems = { items = it },
|
||||
scriptNames = scripts.keys.toList(),
|
||||
)
|
||||
4 -> PlacesSection(
|
||||
places = places,
|
||||
onPlaces = { places = it },
|
||||
onPickBackground = { pid ->
|
||||
pendingPlace = pid
|
||||
pickPlaceBg.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClearBackground = { pid -> vm.clearPlaceBackground(pack.id, pid) },
|
||||
)
|
||||
else -> ScriptsSection(
|
||||
scripts = scripts,
|
||||
onScripts = { scripts = it },
|
||||
editing = editing, onEditing = { editing = it },
|
||||
draft = draft, onDraft = { draft = it },
|
||||
newScript = newScript, onNewScript = { newScript = it },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 设定:名称 / 正文 / 外观四件套 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun SettingSection(
|
||||
name: String,
|
||||
onName: (String) -> Unit,
|
||||
setting: String,
|
||||
onSetting: (String) -> Unit,
|
||||
image: AgentImage,
|
||||
onPick: (String) -> Unit,
|
||||
onClear: (String) -> Unit,
|
||||
) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("基本信息")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = onName,
|
||||
label = { Text("名称", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"世界观正文 —— 整段注入绑定这个世界观的智能体的 <worldview> 段。" +
|
||||
"别以「你是…」开头,那是智能体自己的系统提示词。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
value = setting,
|
||||
onValueChange = onSetting,
|
||||
placeholder = { Text("比如:九州山河破碎,灵气复苏三百年……", fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp),
|
||||
textStyle = TextStyle(fontSize = 14.sp, lineHeight = 20.sp),
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("外观(四件套)")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
val slots = listOf(
|
||||
Triple("front", "封面 / 代表图", "世界包列表上用的那张"),
|
||||
Triple("back", "背景图", "铺在展示区最底层"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本"),
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> image.slot("平常")
|
||||
"back" -> image.back
|
||||
"border-main" -> image.borderMain
|
||||
else -> image.borderInfo
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
RowAction("选择") { onPick(key) }
|
||||
if (path.isNotBlank()) {
|
||||
RowAction("清除", danger = true) { onClear(key) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 数值 / 状态(只读) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun StatsSection(stats: List<StatDef>) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("数值定义")
|
||||
Card {
|
||||
if (stats.isEmpty()) Hint("没有数值。数值是这个世界的规则,比如好感度、声望。")
|
||||
for (s in stats) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${fmt(s.min)} ~ ${fmt(s.max)}" + if (s.shared) " · 全世界共用" else "",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.ranges.isNotEmpty()) {
|
||||
Text(
|
||||
"${s.ranges.size} 段区间:" + s.ranges.joinToString("、") {
|
||||
"${fmt(it.min)}~${fmt(it.max)}「${it.text.take(10)}」"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.script.isNotBlank()) {
|
||||
Text("裁决脚本:${s.script}", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"数值结构(增删数值、min/max、区间表)这一版还是只读的 —— " +
|
||||
"用「导出」在电脑上改 worldInfo.json 再导回来是最快的办法。" +
|
||||
"界面上能改的是脚本,那也是最常改的部分。",
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusesSection(statuses: List<StatusDef>) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态定义")
|
||||
Card {
|
||||
if (statuses.isEmpty()) Hint("没有状态。状态是挂在这个角色身上的临时状况,比如中毒、庇佑。")
|
||||
for (s in statuses) {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
(if (s.isPersistent) "持久" else "定时 ${s.turns} 轮") +
|
||||
(if (s.maxStack > 1) " · 最多叠 ${s.maxStack} 层" else ""),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 脚本(可编辑) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun ScriptsSection(
|
||||
scripts: Map<String, String>,
|
||||
onScripts: (Map<String, String>) -> Unit,
|
||||
editing: String,
|
||||
onEditing: (String) -> Unit,
|
||||
draft: String,
|
||||
onDraft: (String) -> Unit,
|
||||
newScript: String,
|
||||
onNewScript: (String) -> Unit,
|
||||
) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("脚本")
|
||||
if (scripts.isEmpty()) {
|
||||
Hint("这个世界包还没有脚本。数值的裁决、状态的每轮行为、赋予判定都靠脚本。")
|
||||
}
|
||||
Card {
|
||||
for ((fname, src) in scripts) {
|
||||
if (editing == fname) {
|
||||
Text(fname, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
CodeBox(value = draft, onValueChange = onDraft)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("保存这段") { onScripts(scripts + (fname to draft)); onEditing("") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("取消") { onEditing("") }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("删掉") { onScripts(scripts - fname); onEditing("") }
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fname, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
"${src.lines().size} 行 · 点开编辑",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("编辑") { onEditing(fname); onDraft(src) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
// 新建一段
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = newScript,
|
||||
onValueChange = onNewScript,
|
||||
label = { Text("新脚本文件名", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("新建") {
|
||||
val f = newScript.trim()
|
||||
if (f.isNotBlank() && !scripts.containsKey(f)) {
|
||||
onScripts(scripts + (f to SCRIPT_TEMPLATE))
|
||||
onNewScript("")
|
||||
onEditing(f)
|
||||
onDraft(SCRIPT_TEMPLATE)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"三段脚本共用同一个沙箱(静态扫描 + 内置函数白名单 + 硬超时):" +
|
||||
"不能 import、不能读写文件。报错只影响这一次操作,不会中断对话。",
|
||||
)
|
||||
}
|
||||
|
||||
/** 新建脚本时给的骨架(三个入口都列出来,用户知道可以写什么) */
|
||||
private const val SCRIPT_TEMPLATE = """# 可用的三个入口(写哪个都行,不写的就不执行):
|
||||
|
||||
def on_stat_change(name, value, delta):
|
||||
# 数值裁决:返回生效的增量(可以放大、缩小、返回 0 否决)
|
||||
return delta
|
||||
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
# 每轮生成回复之前跑一次(状态脚本)
|
||||
# stats_api['change_stat']('好感度', -1)
|
||||
# stats_api['set_hint']('中毒', '你眼前发黑')
|
||||
# stats_api['narrate']('毒性发作了')
|
||||
return True
|
||||
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
# 别人要给你挂状态时,返回 False 就是抵抗掉
|
||||
return True
|
||||
"""
|
||||
|
||||
/**
|
||||
* 代码框:**不软换行** + **有高度上限**(见文件头的两条硬要求)。
|
||||
*/
|
||||
@Composable
|
||||
private fun CodeBox(value: String, onValueChange: (String) -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState())) {
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoText(),
|
||||
),
|
||||
modifier = Modifier.width(900.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user