Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 91a4ba2ab4 | |||
| 5a65320a5d | |||
| 946bf8bc55 | |||
| 050a3b2385 | |||
| ab8296901d | |||
| c09df1d0a2 |
9
.gitignore
vendored
@@ -87,3 +87,12 @@ Desktop.ini
|
||||
# 调试时生成的临时探针
|
||||
.tmp/
|
||||
.tmp-*
|
||||
|
||||
# 豆包网页版参考镜像(第三方资源,仅本地研究/对照用,不入库)
|
||||
reference/doubao-web-mirror/
|
||||
|
||||
# 嵌入式 Python 缓存(打包 exe 时自动下载;体积 ~10MB,不入库)
|
||||
desktop/build-cache/
|
||||
|
||||
# 豆包网页版抓取脚本的产物
|
||||
.tmp-scrape/
|
||||
|
||||
105
README.md
@@ -1,19 +1,23 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(Web / Windows 版=豆包网页版风格)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
|
||||
**Web / Windows 端**(v2)换成了**豆包网页版风格**的桌面界面,并且和安卓 App
|
||||
**共用同一份 Python 内核**(exe 内嵌 Python 运行时)—— 功能天然同步。详见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 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 |
|
||||
| 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 就能用。
|
||||
|
||||
@@ -25,26 +29,45 @@
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
**网页版 / Windows 桌面版(v2,豆包网页版风格):**
|
||||
|
||||
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
|
||||
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
|
||||
| 空对话(桌面网页) | 群聊(成员条 + 交接) | 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 run install:all # app(Lynx 客户端)+ server(Node 内核)
|
||||
npm run build
|
||||
npm start # 打开 http://127.0.0.1:5199/
|
||||
npm start # 起 Python 内核并托管 web/,打开 http://127.0.0.1:5199/
|
||||
PORT=5300 npm start # 换端口
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**exe 必须放纯英文路径**,见 §7.1)。
|
||||
Windows 桌面版直接双击 `豆包.exe`(**自带 Python,不用装**;**exe 必须放纯英文路径**,见 §7.1)。
|
||||
重新打包:`npm run exe`。
|
||||
|
||||
> 旧的 Lynx 版还留着:`npm run install:all` + `npm run start:legacy-lynx`。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
@@ -92,11 +115,14 @@ adb install -r dist-android/doubao-debug.apk
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
电脑上的 Web/exe 版仍然用 **Node 内核 + Lynx 界面**。两个内核**接口逐字段一致**,
|
||||
所以安卓端把界面换成 Compose 之后,后端一行都不用改。
|
||||
**v2 起,电脑上的 Web/exe 版不再用 Node 内核 + Lynx**,而是:
|
||||
- 界面换成 `web/` 里**豆包网页版风格**的纯静态前端(无构建步骤,内核直接托管);
|
||||
- 后端直接跑**和安卓 App 同一份** `android/kernel/`(纯标准库 Python),
|
||||
桌面版由 Electron 起一个 Python 子进程、并带一个"原生能力桥"(选文件/剪贴板);
|
||||
- 所以「引擎改了另一端必须跟上」这条欠账**没了**:一份内核,两个客户端。
|
||||
旧的 Node 内核(`server/`)和 Lynx 界面(`app/`)留作历史存档。
|
||||
|
||||
怎么做到一致的:`android/kernel/` 是照 `server/src/` 的契约重写的纯标准库实现
|
||||
(`http.server` + `urllib` + 手写 JSON-RPC),不依赖任何第三方包 —— 因为安卓上装不进来。
|
||||
细节见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
---
|
||||
|
||||
@@ -440,8 +466,18 @@ python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calli
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
|
||||
按仓库约定"引擎改了另一端必须跟上",这是欠账。
|
||||
**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`。
|
||||
|
||||
|
||||
---
|
||||
@@ -621,10 +657,16 @@ mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 384 MB)
|
||||
- 打包用 `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`)。
|
||||
@@ -691,28 +733,37 @@ realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
- **网页版(Web/exe)**:`show_ui` / `ask_user` / `end_conversation` 已经能用(走内核的
|
||||
`/api/device/*` HTTP 队列,`wait` 语义和安卓一致);会议画布、立绘背景是二期。
|
||||
详见 `docs/网页版.md` §5.1 / §6
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发
|
||||
npm run dev # 起 Node 内核 + Lynx 热更
|
||||
npm run build # 构建 Lynx bundle
|
||||
npm run apk # 构建 APK(--clean 可彻底重建)
|
||||
npm run exe # 打包 Windows exe
|
||||
# 开发(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/parity-thinking.mjs # 两份内核的思考强度对拍(历史)
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍(历史)
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 280
|
||||
versionName = "2.0.80"
|
||||
versionCode = 283
|
||||
versionName = "2.0.83"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -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) },
|
||||
|
||||
@@ -273,6 +273,9 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
com.doubao.lynxclone.data.WorldviewItem(
|
||||
name = name,
|
||||
setting = text,
|
||||
// ★ 世界观挂的数值状态包。不传的话这条路**永远存成空** ——
|
||||
// 界面选了也白选("配了但读出来没有"那个经典坑)。
|
||||
rulePackId = (extra["rulePackId"] as? String).orEmpty(),
|
||||
image = (extra["image"] as? com.doubao.lynxclone.data.AgentImage)
|
||||
?: com.doubao.lynxclone.data.AgentImage(),
|
||||
),
|
||||
@@ -907,6 +910,29 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
var agentStats by mutableStateOf<com.doubao.lynxclone.data.AgentStats?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* **所有**智能体的数值/状态(智能体卡片上显示用)。
|
||||
*
|
||||
* ★★ 用户要求「数字界面在智能体卡片里展示」—— 选择页的每张卡片
|
||||
* 要在缩略图下面显示这个角色的数值和状态,所以得**一次拿全**,
|
||||
* 而不是给每张卡片各发一个请求(那样 N 个智能体就是 N 次往返,
|
||||
* 每次都重算区间、查状态表)。
|
||||
*
|
||||
* ★ 只有**挂了规则包**的智能体在里面(没挂的卡片上啥也不显示,
|
||||
* 这比显示一个空的"数值"标题诚实)。
|
||||
*/
|
||||
var allStats by mutableStateOf<Map<String, com.doubao.lynxclone.data.AgentStats>>(emptyMap())
|
||||
private set
|
||||
|
||||
/** 拉一遍所有智能体的数值(进选择页 / 改完数值后调) */
|
||||
fun refreshAllStats() {
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.allAgentStats() } }
|
||||
.onSuccess { allStats = it }
|
||||
// 失败就保持上一份 —— 卡片上少几个数字不该报错打扰用户
|
||||
}
|
||||
}
|
||||
|
||||
fun openStats(agentId: String) {
|
||||
statsAgentId = agentId
|
||||
agentStats = null
|
||||
@@ -950,6 +976,36 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户**手动给智能体挂一个状态**。
|
||||
*
|
||||
* ★ AI 只有 `grant_status`,用户也能直接挂 —— 想测某个状态的效果、
|
||||
* 或者补一个剧情里本来就该有的状态时用得上。
|
||||
*/
|
||||
fun addStatusDirect(name: String, turns: Int = 0) {
|
||||
val id = statsAgentId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.addStatus(id, name, turns) } }
|
||||
.onSuccess { agentStats = it; showHint("挂上了:$name") }
|
||||
.onFailure { showHint(it.message ?: "挂不上") }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户**直接清掉一个状态**。
|
||||
*
|
||||
* ★★ AI **没有任何工具能移除状态**,所以这是唯一的出口 ——
|
||||
* `persistent` 状态不会自己过期,没有它就只能改库。
|
||||
*/
|
||||
fun dropStatusDirect(name: String) {
|
||||
val id = statsAgentId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.dropStatus(id, name) } }
|
||||
.onSuccess { agentStats = it; showHint("清掉了:$name") }
|
||||
.onFailure { showHint(it.message ?: "清不掉") }
|
||||
}
|
||||
}
|
||||
|
||||
/** AI 整理记忆的结果提示("12 条 → 7 条"这种) */
|
||||
var memoryHint by mutableStateOf("")
|
||||
private set
|
||||
|
||||
@@ -420,7 +420,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 +481,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 +560,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("外观(四件套)")
|
||||
|
||||
@@ -492,6 +492,31 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
# GET 读一个智能体的数值和状态([状态数值] 浮层三个入口都用它)
|
||||
# POST 用户**直接改一个数值**(用户主权 —— 需求里 AI 只能申请增量,
|
||||
# 但用户是规则的主人,他可以直接设成任何值)
|
||||
#
|
||||
# ★★ 还有一种:`GET /api/agents/stats`(少了 id 那一段)——
|
||||
# **批量**读所有智能体的,给**智能体卡片**用(缩略图下面显示
|
||||
# "好感度多少、身上有没有状态")。一个一个拉 N 次会把列表拖垮,
|
||||
# 而每次都重算区间、查状态表,成本不低。
|
||||
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'stats' and method == 'GET':
|
||||
# 同一世界观下的智能体共用一个包 —— 按 worldviewId 缓存,
|
||||
# 别为了 N 个智能体把同一个世界观查 N 遍
|
||||
pack_cache = {}
|
||||
out = {}
|
||||
for a in store.list_agents():
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if wid not in pack_cache:
|
||||
pack_cache[wid] = agent_context.pack_of(a)
|
||||
pack_id = pack_cache[wid]
|
||||
if not pack_id:
|
||||
continue # 没挂规则包 → 卡片上什么都不显示
|
||||
one = _stats_payload(a, pack_id)
|
||||
# 批量版**不带** statusDefs(那是"能加哪些状态",
|
||||
# 只有点进 [状态数值] 页才需要;卡片用不上,白传一遍)
|
||||
one.pop('statusDefs', None)
|
||||
out[a['id']] = one
|
||||
handler.send_json(200, {'stats': out})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'stats':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
@@ -504,6 +529,35 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
if method == 'POST':
|
||||
b = body()
|
||||
name = str(b.get('name') or '').strip()
|
||||
|
||||
# ---- 状态管理(用户主权)----
|
||||
#
|
||||
# ★★ AI 手里只有 `grant_status`(**只能加**),没有任何工具能移除状态。
|
||||
# 于是 `persistent` 状态一旦挂上就永远下不来,
|
||||
# `timed` 的状态想立刻清掉也只能干等 —— 用户是规则的主人,
|
||||
# 这些都得能直接拨。所以 [状态数值] 页上给了「清掉」和「加一个」。
|
||||
#
|
||||
# `action` 缺省时保持老行为(改数值),老客户端不受影响。
|
||||
action = str(b.get('action') or 'set').strip()
|
||||
if action in ('addStatus', 'dropStatus'):
|
||||
sd = next((x for x in rule_engine.status_defs(pack_id)
|
||||
if x['name'] == name), None)
|
||||
if not sd:
|
||||
err(404, f'这个世界观里没有叫「{name}」的状态')
|
||||
return True
|
||||
if action == 'dropStatus':
|
||||
rule_engine.drop_status(agent['id'], name)
|
||||
else:
|
||||
# 加:持久状态记 -1;定时状态用定义里的轮数(可被 body 覆盖)
|
||||
try:
|
||||
turns = int(b.get('turns') or sd.get('turns') or 1)
|
||||
except (TypeError, ValueError):
|
||||
turns = int(sd.get('turns') or 1)
|
||||
remaining = -1 if sd.get('kind') == 'persistent' else max(1, turns)
|
||||
rule_engine.put_status(agent['id'], name, remaining, 1, '')
|
||||
handler.send_json(200, _stats_payload(agent, pack_id))
|
||||
return True
|
||||
|
||||
d = next((x for x in rule_engine.stat_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
err(404, f'这个世界观里没有叫「{name}」的数值')
|
||||
@@ -945,6 +999,13 @@ def _stats_payload(agent: dict, pack_id: str) -> dict:
|
||||
"name": agent.get("name") or "",
|
||||
"stats": stats,
|
||||
"statuses": rule_engine.list_statuses(agent.get("id") or ""),
|
||||
# ★ 这个包里**定义了哪些状态** —— 界面的「加一个」要从这里挑。
|
||||
# 不带的话界面只能瞎猜名字(而且用户看不出有哪些可用)。
|
||||
"statusDefs": [
|
||||
{"name": d["name"], "kind": d.get("kind") or "timed",
|
||||
"turns": int(d.get("turns") or 1), "maxStack": int(d.get("max_stack") or 1)}
|
||||
for d in (rule_engine.status_defs(pack_id) if pack_id else [])
|
||||
],
|
||||
"rulePackId": pack_id or "",
|
||||
"rulePackName": (pack or {}).get("name") or "",
|
||||
}
|
||||
|
||||
@@ -568,6 +568,24 @@ def invite_agent(args: dict) -> dict:
|
||||
if not my_world or my_world != (target.get('worldviewId') or '').strip():
|
||||
raise ValueError(f'「{target.get("name")}」和你不在同一个世界观里,拉不进来')
|
||||
|
||||
# ★★ 「需确认」必须**排在任何拉人动作之前**。
|
||||
#
|
||||
# 以前它排在"单聊 → 转群聊"那个分支的**后面**,于是:
|
||||
# 用户在单聊里让 AI 拉个人 → 走"转群聊"分支直接拉进来了,
|
||||
# **配置的"拉起需要确认"完全没生效**。
|
||||
# 探针里 `c2` 正好被前面删到剩一个(退化成单聊),一拉就中招。
|
||||
#
|
||||
# 正确的顺序是:**先问能不能拉,再决定怎么拉。**
|
||||
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'用户答应之后再调一次这个工具。'),
|
||||
}
|
||||
|
||||
if not group_chat.is_group(conv):
|
||||
# 单聊拉人 → 转成群聊(需求 §3.9:"当前会话中加入多个智能体")
|
||||
group_chat.promote(conv, target['id'])
|
||||
@@ -581,17 +599,6 @@ def invite_agent(args: dict) -> dict:
|
||||
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'])
|
||||
|
||||
@@ -18,6 +18,8 @@ HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上
|
||||
GET /api/agents POST /api/agents PATCH/PUT/DELETE /api/agents/<id>
|
||||
POST /api/upload POST /api/pick-file GET /api/uploads/pending
|
||||
POST /api/clipboard POST /api/chat(SSE)
|
||||
界面能力(show_ui / ask_user / end_conversation 的电脑/网页端通道):
|
||||
GET /api/device/pending POST /api/device/answer
|
||||
静态:/ /main.web.bundle /lynx-web/* /static/* /uploads/*
|
||||
"""
|
||||
|
||||
@@ -110,12 +112,179 @@ INDEX_MISSING_HINT = (
|
||||
)
|
||||
|
||||
# 安卓侧(Kotlin/Chaquopy)可以挂上原生能力钩子,等价于 Electron 主进程挂的 __doubaoXxx
|
||||
_hooks = {'clipboard': None, 'pick_file': None, 'reveal': None}
|
||||
#
|
||||
# `device` 是"界面能力"的通用入口:show_ui / ask_user / end_conversation 三个工具
|
||||
# 都通过 tools/_ui_bridge.call_device() 发一个 JSON 到这里,等一个 JSON 回去。
|
||||
# · 安卓:doubao_entry 让 Kotlin 的 NativeBridge.device(json)->json 直接可用
|
||||
# (tools/_ui_bridge 优先走它,根本到不了这里);
|
||||
# · 电脑 / 网页:没有原生桥,_ui_bridge 回落到本模块的 `_web_device()` ——
|
||||
# 内核开一条"设备请求队列",网页轮询 /api/device/pending 取走、弹界面,
|
||||
# 用户操作后 POST /api/device/answer 把结果送回来(阻塞语义和安卓一致)。
|
||||
_hooks = {'clipboard': None, 'pick_file': None, 'reveal': None, 'device': None}
|
||||
|
||||
|
||||
def set_native_hooks(clipboard=None, pick_file=None, reveal=None) -> None:
|
||||
"""注册原生钩子:clipboard(text) / pick_file()->[路径] / reveal(路径)->错误串或 None。"""
|
||||
def set_native_hooks(clipboard=None, pick_file=None, reveal=None, device=None) -> None:
|
||||
"""
|
||||
注册原生钩子:
|
||||
clipboard(text) 写剪贴板
|
||||
pick_file() -> [路径]
|
||||
reveal(路径) -> 错误串或 None
|
||||
device(json_str) -> json_str(界面能力;安卓侧挂 NativeBridge.device)
|
||||
"""
|
||||
_hooks.update({'clipboard': clipboard, 'pick_file': pick_file, 'reveal': reveal})
|
||||
if device is not None:
|
||||
_hooks['device'] = device
|
||||
|
||||
|
||||
def get_native_device_hook():
|
||||
"""
|
||||
给 tools/_ui_bridge 用:返回"电脑端界面能力"的实现。
|
||||
|
||||
安卓上 _ui_bridge 会先拿到 doubao_entry._android,不会走到这里;
|
||||
电脑/网页上没有原生桥,就交给下面的 HTTP 队列(浏览器和 exe 共用同一条路)。
|
||||
"""
|
||||
hook = _hooks.get('device')
|
||||
if callable(hook):
|
||||
return hook
|
||||
return _web_device
|
||||
|
||||
|
||||
# ---- 网页端"界面能力"队列 ------------------------------------------------ #
|
||||
#
|
||||
# 为什么用队列 + 轮询而不是 WebSocket:内核是 http.server 的零依赖实现,
|
||||
# 整套项目里没有 WS;网页本来就在轮询 /api/chat/poll,多一个 700ms 的小轮询
|
||||
# 是最小改动。也不需要区分 Electron / 浏览器 —— 两边都是普通 HTTP 客户端。
|
||||
#
|
||||
# ★ 阻塞请求用 **FIFO 队列** 而不是"一个槽位":用户可能同时开着两个对话/两个标签页,
|
||||
# 或者上一个请求还没答就发起了新的一轮。一个槽位会让后来的请求把前面的**静默顶掉**
|
||||
# (前面那个工具线程要一直等到超时),表现为"AI 问了我但界面没弹出来"。
|
||||
_DEVICE_LOCK = threading.Lock()
|
||||
_DEVICE_QUEUE = [] # 正在等用户回答的请求(网页一次处理一个,先来先到)
|
||||
_DEVICE_NOTIFY = {} # 不需要回答、只要弹出来给用户看的界面(show_ui wait=false)
|
||||
_DEVICE_DEFAULT_WAIT_S = 3600.0 # 网页没给 timeoutMs 时的兜底上限(不做无限阻塞)
|
||||
_DEVICE_QUEUE_LIMIT = 8 # 队列上限:防止网页一直不答导致线程越积越多
|
||||
|
||||
|
||||
def _json_out(obj: dict) -> str:
|
||||
return json.dumps(obj, ensure_ascii=False)
|
||||
|
||||
|
||||
def _web_device(payload_json: str) -> str:
|
||||
"""
|
||||
电脑/网页端的 device 实现(show_ui / ask_user / end_conversation)。
|
||||
|
||||
返回 JSON 字符串,形状和安卓 NativeBridge.device() 一致:
|
||||
· ui_screen(wait=true) → {timeout, closed, value, screenId}
|
||||
· ui_screen(wait=false)→ {ok:true, screenId},另外丢进"通知队列"让网页弹出来
|
||||
· ui_dialog → {timeout, cancelled, multiple, choice, values}
|
||||
· end_conversation → {ok:true, conversationId}(纯内核写操作,不用麻烦网页)
|
||||
"""
|
||||
global _DEVICE_QUEUE
|
||||
|
||||
try:
|
||||
payload = json.loads(payload_json or '{}')
|
||||
except (TypeError, ValueError):
|
||||
payload = {}
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
action = str(payload.get('action') or '')
|
||||
|
||||
# ① 结束对话:内核自己就能落盘(和安卓那边 PATCH /api/conversations/<id> 等价)
|
||||
if action == 'end_conversation':
|
||||
conv = str(payload.get('conversationId') or '')
|
||||
if not conv:
|
||||
return _json_out({'error': '没有 conversationId,无法结束对话'})
|
||||
patch = {
|
||||
'ended': True,
|
||||
'endedAt': int(time.time() * 1000),
|
||||
'endedReason': str(payload.get('reason') or ''),
|
||||
}
|
||||
summary = str(payload.get('summary') or '')
|
||||
if summary:
|
||||
patch['endedSummary'] = summary
|
||||
if not store.update_conversation(conv, patch):
|
||||
return _json_out({'error': '会话不存在'})
|
||||
return _json_out({'ok': True, 'conversationId': conv})
|
||||
|
||||
# ② 弹界面:先落盘一份(用户关掉之后还能再打开,/api/screens 也能列出来)
|
||||
screen_id = ''
|
||||
if action == 'ui_screen':
|
||||
item = store.save_screen(
|
||||
str(payload.get('conversationId') or ''),
|
||||
str(payload.get('html') or ''),
|
||||
str(payload.get('title') or ''),
|
||||
bool(payload.get('full_html')),
|
||||
) or {}
|
||||
screen_id = str(item.get('id') or '')
|
||||
payload = dict(payload)
|
||||
payload['screenId'] = screen_id
|
||||
if not payload.get('wait'):
|
||||
# 不阻塞:挂进通知队列,让网页下一个轮询把它弹出来
|
||||
req_id = 'n' + uuid.uuid4().hex[:12]
|
||||
with _DEVICE_LOCK:
|
||||
_DEVICE_NOTIFY[req_id] = payload
|
||||
return _json_out({'ok': True, 'screenId': screen_id})
|
||||
|
||||
# ③ 其余都是"要等用户操作"的:挂进阻塞队列,等网页 POST 答案
|
||||
req_id = 'd' + uuid.uuid4().hex[:12]
|
||||
try:
|
||||
timeout_ms = int(payload.get('timeoutMs') or 0)
|
||||
except (TypeError, ValueError):
|
||||
timeout_ms = 0
|
||||
timeout_s = (timeout_ms / 1000.0) if timeout_ms > 0 else _DEVICE_DEFAULT_WAIT_S
|
||||
timeout_s = max(1.0, min(3600.0, timeout_s))
|
||||
|
||||
request = {
|
||||
'id': req_id,
|
||||
'payload': payload,
|
||||
'event': threading.Event(),
|
||||
'result': None,
|
||||
'at': time.time(),
|
||||
}
|
||||
with _DEVICE_LOCK:
|
||||
if len(_DEVICE_QUEUE) >= _DEVICE_QUEUE_LIMIT:
|
||||
return _json_out({
|
||||
'error': '界面请求太多,网页那边一直没响应(先把窗口里的弹窗处理掉再试)',
|
||||
})
|
||||
_DEVICE_QUEUE.append(request)
|
||||
|
||||
answered = request['event'].wait(timeout_s)
|
||||
with _DEVICE_LOCK:
|
||||
try:
|
||||
_DEVICE_QUEUE.remove(request)
|
||||
except ValueError:
|
||||
pass
|
||||
result = request.get('result')
|
||||
|
||||
if not answered or not isinstance(result, dict):
|
||||
# 超时 / 网页一直没回:按工具侧的约定给"超时"形状(工具会注明用户没操作)
|
||||
if action == 'ui_dialog':
|
||||
return _json_out({
|
||||
'timeout': True, 'cancelled': False,
|
||||
'multiple': bool(payload.get('multiple')), 'choice': '', 'values': [],
|
||||
})
|
||||
return _json_out({'timeout': True, 'closed': False, 'value': '', 'screenId': screen_id})
|
||||
|
||||
if action == 'ui_dialog':
|
||||
values = result.get('values')
|
||||
if not isinstance(values, list):
|
||||
one = str(result.get('choice') or '')
|
||||
values = [one] if one else []
|
||||
values = [str(v) for v in values if str(v or '').strip()]
|
||||
return _json_out({
|
||||
'timeout': bool(result.get('timeout')),
|
||||
'cancelled': bool(result.get('cancelled')),
|
||||
'multiple': bool(payload.get('multiple')),
|
||||
'choice': values[0] if values else '',
|
||||
'values': values,
|
||||
})
|
||||
|
||||
return _json_out({
|
||||
'timeout': bool(result.get('timeout')),
|
||||
'closed': bool(result.get('closed')),
|
||||
'value': str(result.get('value') or ''),
|
||||
'screenId': screen_id,
|
||||
})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -296,6 +465,18 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
|
||||
# ------------------------------ 基础设施 ------------------------------ #
|
||||
|
||||
def handle_one_request(self): # noqa: N802 - 基类约定
|
||||
"""
|
||||
浏览器关标签页 / 刷新时,连接会被对端直接掐掉(WinError 10054 / ConnectionReset)。
|
||||
这对内核是**正常现象**,不该在 stderr 里打一整段 traceback —— 以前网页轮询
|
||||
(/api/chat/poll、/api/device/pending)每次关页面都会刷一屏,真出问题时反而看不见。
|
||||
"""
|
||||
try:
|
||||
return super().handle_one_request()
|
||||
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
||||
self.close_connection = True
|
||||
return None
|
||||
|
||||
def log_message(self, fmt, *args): # noqa: A003 - 覆盖基类
|
||||
if not QUIET:
|
||||
print(f'[http] {self.address_string()} {fmt % args}', file=sys.stderr)
|
||||
@@ -907,6 +1088,56 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---- 网页端的"界面能力"通道(show_ui / ask_user 等)----
|
||||
#
|
||||
# 网页每 700ms 拉一次 pending:
|
||||
# · 有阻塞请求(ask_user / show_ui wait=true)→ 弹界面,用户操作后 POST answer;
|
||||
# · 有通知请求(show_ui wait=false)→ 只弹出来给用户看,取走即可,不用回答。
|
||||
if pathname == '/api/device/pending' and method == 'GET':
|
||||
with _DEVICE_LOCK:
|
||||
req = _DEVICE_QUEUE[0] if _DEVICE_QUEUE else None
|
||||
payload = dict(req['payload']) if req else None
|
||||
req_id = req['id'] if req else ''
|
||||
notify = False
|
||||
if payload is None and _DEVICE_NOTIFY:
|
||||
req_id, payload = next(iter(_DEVICE_NOTIFY.items()))
|
||||
payload = dict(payload)
|
||||
_DEVICE_NOTIFY.pop(req_id, None)
|
||||
notify = True
|
||||
if payload is None:
|
||||
self.send_json(200, {'request': None})
|
||||
else:
|
||||
payload['id'] = req_id
|
||||
payload['notify'] = notify
|
||||
self.send_json(200, {'request': payload})
|
||||
return True
|
||||
|
||||
if pathname == '/api/device/answer' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
req_id = str(body.get('id') or '')
|
||||
result = body.get('result')
|
||||
if not req_id or not isinstance(result, dict):
|
||||
self.send_json(400, {'error': '需要 id 和 result'})
|
||||
return True
|
||||
with _DEVICE_LOCK:
|
||||
req = next((r for r in _DEVICE_QUEUE if r.get('id') == req_id), None)
|
||||
matched = req is not None
|
||||
if matched:
|
||||
req['result'] = result
|
||||
req['event'].set()
|
||||
try:
|
||||
_DEVICE_QUEUE.remove(req)
|
||||
except ValueError:
|
||||
pass
|
||||
if not matched:
|
||||
self.send_json(404, {'ok': False, 'error': '没有这个等待中的请求(可能已超时)'})
|
||||
else:
|
||||
self.send_json(200, {'ok': True})
|
||||
return True
|
||||
|
||||
# ---- AI 界面的数据回流 ----
|
||||
#
|
||||
# ★★★ 这是"AI 自己写进网页里的接口"的落点。
|
||||
@@ -1002,7 +1233,10 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
return True
|
||||
elif method == 'DELETE' and target:
|
||||
if not group_chat.remove_member(conv, target):
|
||||
self.send_json(400, {'error': '移不出去(主智能体不能被移出)'})
|
||||
# ★ 错误信息要**如实**:以前这里写"主智能体不能被移出",
|
||||
# 而那个规则已经废了(群里没有主人)。真实原因只剩
|
||||
# "人不在群里"或"就剩他一个了"。
|
||||
self.send_json(400, {'error': '移不出去(群里没这个人,或者就剩他一个了)'})
|
||||
return True
|
||||
else:
|
||||
self.send_json(405, {'error': '不支持的操作'})
|
||||
@@ -2184,6 +2418,12 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if target and os.path.isfile(target):
|
||||
return self.serve_file(target)
|
||||
|
||||
# 新网页版(web/ 目录)的静态资源:/assets/* /js/* 之类。
|
||||
# 旧 Lynx 宿主页只用 / 和 /static/*,上面几条已经先匹配掉了,这里不会抢路由。
|
||||
web_file = safe_join(p.web_dir, pathname.lstrip('/'))
|
||||
if web_file and os.path.isfile(web_file):
|
||||
return self.serve_file(web_file)
|
||||
|
||||
if pathname in ('/main.web.bundle', '/main.lynx.bundle'):
|
||||
return self.serve_file(os.path.join(p.dist_dir, os.path.basename(pathname)))
|
||||
|
||||
|
||||
@@ -226,16 +226,29 @@ def add_member(conv: dict, agent_id: str) -> bool:
|
||||
|
||||
def remove_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
移出一个成员。**主智能体不能被移出**(需求说发言权兜底靠它 ——
|
||||
移掉的话这个群聊就没有兜底了,会冷场)。
|
||||
移出一个成员。
|
||||
|
||||
★★ **谁都能移出** —— 用户要求「群聊去掉主人设定」之后,
|
||||
"主智能体不能移出"这条就失去了依据:群里已经没有"主人"这回事了,
|
||||
没人被 @ 时按顺序轮(`rotate_next`)。
|
||||
以前这里还留着 `aid == host_id(c)` 的拦截,于是**第一个进群的人删不掉**
|
||||
—— 界面上「移出」按钮人人都有,点了却没反应(真机反馈"群聊删不了人")。
|
||||
|
||||
★ 唯一的拒绝条件:**不能删到一个人都不剩**(空群没法开会话)。
|
||||
删到剩 1 个是允许的 —— 那时退化成单聊,`type` 要跟着改回去,
|
||||
不然界面还按群聊渲染、仲裁还按群聊跑,而群里只剩一个人。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
ids = member_ids(c)
|
||||
if aid not in ids or aid == host_id(c):
|
||||
if aid not in ids or len(ids) <= 1:
|
||||
return False
|
||||
ids.remove(aid)
|
||||
c['participants'] = ids
|
||||
if len(ids) <= 1:
|
||||
# 只剩一个人 → 退回单聊,并把对话主人设成他
|
||||
c['type'] = 'single'
|
||||
c['agentId'] = ids[0] if ids else ''
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -150,6 +150,44 @@ def start_kernel(
|
||||
return handle
|
||||
|
||||
|
||||
def register_desktop_hooks(bridge_url: str) -> None:
|
||||
"""
|
||||
桌面(Electron)版把原生能力委托给主进程:选文件、写剪贴板、在资源管理器里显示。
|
||||
|
||||
为什么要绕一道 HTTP:内核是 Electron 起的**子进程**,Python 里没有 Electron 的
|
||||
dialog/clipboard。安卓侧是 Kotlin 直接调 `app.set_native_hooks(...)`(见 doubao_entry.py),
|
||||
桌面侧就由主进程开一个只监听 127.0.0.1 的小桥(desktop/main.cjs),Python 通过 HTTP 调它。
|
||||
这样内核代码两边共用一份,不用为桌面另写一套。
|
||||
"""
|
||||
import urllib.request
|
||||
|
||||
def _call(path: str, payload: dict | None = None):
|
||||
data = json.dumps(payload or {}).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
bridge_url.rstrip('/') + path,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - 只连本机主进程
|
||||
return json.loads(resp.read().decode('utf-8') or '{}')
|
||||
|
||||
def _clipboard(text: str):
|
||||
_call('/clipboard', {'text': text})
|
||||
|
||||
def _pick_file():
|
||||
return list(_call('/pick-file').get('paths') or [])
|
||||
|
||||
def _reveal(target: str):
|
||||
# 约定:成功返回 None,失败返回一句人话(app.py 直接把它回给界面)
|
||||
try:
|
||||
result = _call('/reveal', {'path': target})
|
||||
except Exception as exc: # noqa: BLE001 - 桥挂了也要给人话,不能让接口 500
|
||||
return f'打开文件夹失败:{exc}'
|
||||
return None if result.get('ok') else str(result.get('error') or '打开文件夹失败')
|
||||
|
||||
app.set_native_hooks(clipboard=_clipboard, pick_file=_pick_file, reveal=_reveal)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog='doubao-kernel',
|
||||
@@ -169,6 +207,8 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
parser.add_argument('--dist-dir', default=None, help='Lynx 产物目录(默认 app/dist)')
|
||||
parser.add_argument('--web-core', default=None, help='@lynx-js/web-core 静态资源目录')
|
||||
parser.add_argument('--no-mcp-autostart', action='store_true', help='启动时不自动连 MCP 服务器')
|
||||
parser.add_argument('--desktop-bridge', default=None,
|
||||
help='桌面版原生能力桥(http://127.0.0.1:<port>),由 Electron 主进程提供')
|
||||
parser.add_argument('--quiet', action='store_true', help='不打印访问日志和启动横幅')
|
||||
parser.add_argument('--json', action='store_true', help='启动后打印一行 JSON(含真实端口),便于脚本拉起')
|
||||
return parser
|
||||
@@ -191,6 +231,13 @@ def main(argv=None) -> int:
|
||||
if args.json:
|
||||
print(json.dumps(handle.as_dict(), ensure_ascii=False), flush=True)
|
||||
|
||||
# 桌面版:把选文件/剪贴板/打开文件夹委托给 Electron 主进程(安卓不走这里)
|
||||
if args.desktop_bridge:
|
||||
try:
|
||||
register_desktop_hooks(args.desktop_bridge)
|
||||
except Exception as exc: # noqa: BLE001 - 桥连不上不该让内核起不来
|
||||
print(f'[kernel] 桌面能力桥注册失败:{exc}', file=sys.stderr)
|
||||
|
||||
stop = threading.Event()
|
||||
|
||||
def _on_signal(signum, _frame): # noqa: ANN001 - 信号回调签名固定
|
||||
|
||||
645
desktop/build-cache/embed-test/LICENSE.txt
Normal file
@@ -0,0 +1,645 @@
|
||||
A. HISTORY OF THE SOFTWARE
|
||||
==========================
|
||||
|
||||
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||
as a successor of a language called ABC. Guido remains Python's
|
||||
principal author, although it includes many contributions from others.
|
||||
|
||||
In 1995, Guido continued his work on Python at the Corporation for
|
||||
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||
in Reston, Virginia where he released several versions of the
|
||||
software.
|
||||
|
||||
In May 2000, Guido and the Python core development team moved to
|
||||
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||
year, the PythonLabs team moved to Digital Creations, which became
|
||||
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||
https://www.python.org/psf/) was formed, a non-profit organization
|
||||
created specifically to own Python-related Intellectual Property.
|
||||
Zope Corporation was a sponsoring member of the PSF.
|
||||
|
||||
All Python releases are Open Source (see https://opensource.org for
|
||||
the Open Source Definition). Historically, most, but not all, Python
|
||||
releases have also been GPL-compatible; the table below summarizes
|
||||
the various releases.
|
||||
|
||||
Release Derived Year Owner GPL-
|
||||
from compatible? (1)
|
||||
|
||||
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||
1.6 1.5.2 2000 CNRI no
|
||||
2.0 1.6 2000 BeOpen.com no
|
||||
1.6.1 1.6 2001 CNRI yes (2)
|
||||
2.1 2.0+1.6.1 2001 PSF no
|
||||
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||
2.1.2 2.1.1 2002 PSF yes
|
||||
2.1.3 2.1.2 2002 PSF yes
|
||||
2.2 and above 2.1.1 2001-now PSF yes
|
||||
|
||||
Footnotes:
|
||||
|
||||
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||
a modified version without making your changes open source. The
|
||||
GPL-compatible licenses make it possible to combine Python with
|
||||
other software that is released under the GPL; the others don't.
|
||||
|
||||
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||
because its license has a choice of law clause. According to
|
||||
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||
is "not incompatible" with the GPL.
|
||||
|
||||
Thanks to the many outside volunteers who have worked under Guido's
|
||||
direction to make these releases possible.
|
||||
|
||||
|
||||
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||
===============================================================
|
||||
|
||||
Python software and documentation are licensed under the
|
||||
Python Software Foundation License Version 2.
|
||||
|
||||
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||
the documentation are dual licensed under the PSF License Version 2
|
||||
and the Zero-Clause BSD license.
|
||||
|
||||
Some software incorporated into Python is under different licenses.
|
||||
The licenses are listed with code falling under that license.
|
||||
|
||||
|
||||
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||
--------------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||
otherwise using this software ("Python") in source or binary form and
|
||||
its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||
distribute, and otherwise use Python alone or in any derivative version,
|
||||
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||
i.e., "Copyright (c) 2001-2024 Python Software Foundation; All Rights Reserved"
|
||||
are retained in Python alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python.
|
||||
|
||||
4. PSF is making Python available to Licensee on an "AS IS"
|
||||
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. Nothing in this License Agreement shall be deemed to create any
|
||||
relationship of agency, partnership, or joint venture between PSF and
|
||||
Licensee. This License Agreement does not grant permission to use PSF
|
||||
trademarks or trade name in a trademark sense to endorse or promote
|
||||
products or services of Licensee, or any third party.
|
||||
|
||||
8. By copying, installing or otherwise using Python, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||
-------------------------------------------
|
||||
|
||||
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||
|
||||
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||
Individual or Organization ("Licensee") accessing and otherwise using
|
||||
this software in source or binary form and its associated
|
||||
documentation ("the Software").
|
||||
|
||||
2. Subject to the terms and conditions of this BeOpen Python License
|
||||
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||
and/or display publicly, prepare derivative works, distribute, and
|
||||
otherwise use the Software alone or in any derivative version,
|
||||
provided, however, that the BeOpen Python License is retained in the
|
||||
Software, alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
5. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
6. This License Agreement shall be governed by and interpreted in all
|
||||
respects by the law of the State of California, excluding conflict of
|
||||
law provisions. Nothing in this License Agreement shall be deemed to
|
||||
create any relationship of agency, partnership, or joint venture
|
||||
between BeOpen and Licensee. This License Agreement does not grant
|
||||
permission to use BeOpen trademarks or trade names in a trademark
|
||||
sense to endorse or promote products or services of Licensee, or any
|
||||
third party. As an exception, the "BeOpen Python" logos available at
|
||||
http://www.pythonlabs.com/logos.html may be used according to the
|
||||
permissions granted on that web page.
|
||||
|
||||
7. By copying, installing or otherwise using the software, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||
---------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||
source or binary form and its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||
license to reproduce, analyze, test, perform and/or display publicly,
|
||||
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||
alone or in any derivative version, provided, however, that CNRI's
|
||||
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||
Agreement, Licensee may substitute the following text (omitting the
|
||||
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||
conditions in CNRI's License Agreement. This Agreement together with
|
||||
Python 1.6.1 may be located on the internet using the following
|
||||
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||
Agreement may also be obtained from a proxy server on the internet
|
||||
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python 1.6.1.
|
||||
|
||||
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. This License Agreement shall be governed by the federal
|
||||
intellectual property law of the United States, including without
|
||||
limitation the federal copyright law, and, to the extent such
|
||||
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||
Virginia, excluding Virginia's conflict of law provisions.
|
||||
Notwithstanding the foregoing, with regard to derivative works based
|
||||
on Python 1.6.1 that incorporate non-separable material that was
|
||||
previously distributed under the GNU General Public License (GPL), the
|
||||
law of the Commonwealth of Virginia shall govern this License
|
||||
Agreement only as to issues arising under or with respect to
|
||||
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||
License Agreement shall be deemed to create any relationship of
|
||||
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||
License Agreement does not grant permission to use CNRI trademarks or
|
||||
trade name in a trademark sense to endorse or promote products or
|
||||
services of Licensee, or any third party.
|
||||
|
||||
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||
bound by the terms and conditions of this License Agreement.
|
||||
|
||||
ACCEPT
|
||||
|
||||
|
||||
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||
--------------------------------------------------
|
||||
|
||||
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||
The Netherlands. All rights reserved.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted,
|
||||
provided that the above copyright notice appear in all copies and that
|
||||
both that copyright notice and this permission notice appear in
|
||||
supporting documentation, and that the name of Stichting Mathematisch
|
||||
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||
distribution of the software without specific, written prior
|
||||
permission.
|
||||
|
||||
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
|
||||
|
||||
Additional Conditions for this Windows binary build
|
||||
---------------------------------------------------
|
||||
|
||||
This program is linked with and uses Microsoft Distributable Code,
|
||||
copyrighted by Microsoft Corporation. The Microsoft Distributable Code
|
||||
is embedded in each .exe, .dll and .pyd file as a result of running
|
||||
the code through a linker.
|
||||
|
||||
If you further distribute programs that include the Microsoft
|
||||
Distributable Code, you must comply with the restrictions on
|
||||
distribution specified by Microsoft. In particular, you must require
|
||||
distributors and external end users to agree to terms that protect the
|
||||
Microsoft Distributable Code at least as much as Microsoft's own
|
||||
requirements for the Distributable Code. See Microsoft's documentation
|
||||
(included in its developer tools and on its website at microsoft.com)
|
||||
for specific details.
|
||||
|
||||
Redistribution of the Windows binary build of the Python interpreter
|
||||
complies with this agreement, provided that you do not:
|
||||
|
||||
- alter any copyright, trademark or patent notice in Microsoft's
|
||||
Distributable Code;
|
||||
|
||||
- use Microsoft's trademarks in your programs' names or in a way that
|
||||
suggests your programs come from or are endorsed by Microsoft;
|
||||
|
||||
- distribute Microsoft's Distributable Code to run on a platform other
|
||||
than Microsoft operating systems, run-time technologies or application
|
||||
platforms; or
|
||||
|
||||
- include Microsoft Distributable Code in malicious, deceptive or
|
||||
unlawful programs.
|
||||
|
||||
These restrictions apply only to the Microsoft Distributable Code as
|
||||
defined above, not to Python itself or any programs running on the
|
||||
Python interpreter. The redistribution of the Python interpreter and
|
||||
libraries is governed by the Python Software License included with this
|
||||
file, or by other licenses as marked.
|
||||
|
||||
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
This program, "bzip2", the associated library "libbzip2", and all
|
||||
documentation, are copyright (C) 1996-2019 Julian R Seward. All
|
||||
rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. The origin of this software must not be misrepresented; you must
|
||||
not claim that you wrote the original software. If you use this
|
||||
software in a product, an acknowledgment in the product
|
||||
documentation would be appreciated but is not required.
|
||||
|
||||
3. Altered source versions must be plainly marked as such, and must
|
||||
not be misrepresented as being the original software.
|
||||
|
||||
4. The name of the author may not be used to endorse or promote
|
||||
products derived from this software without specific prior written
|
||||
permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
|
||||
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
|
||||
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Julian Seward, jseward@acm.org
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
libffi - Copyright (c) 1996-2022 Anthony Green, Red Hat, Inc and others.
|
||||
See source files for details.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
``Software''), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
This software is copyrighted by the Regents of the University of
|
||||
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
|
||||
Corporation and other parties. The following terms apply to all files
|
||||
associated with the software unless explicitly disclaimed in
|
||||
individual files.
|
||||
|
||||
The authors hereby grant permission to use, copy, modify, distribute,
|
||||
and license this software and its documentation for any purpose, provided
|
||||
that existing copyright notices are retained in all copies and that this
|
||||
notice is included verbatim in any distributions. No written agreement,
|
||||
license, or royalty fee is required for any of the authorized uses.
|
||||
Modifications to this software may be copyrighted by their authors
|
||||
and need not follow the licensing terms described here, provided that
|
||||
the new terms are clearly indicated on the first page of each file where
|
||||
they apply.
|
||||
|
||||
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
|
||||
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
|
||||
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
|
||||
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
|
||||
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
|
||||
MODIFICATIONS.
|
||||
|
||||
GOVERNMENT USE: If you are acquiring this software on behalf of the
|
||||
U.S. government, the Government shall have only "Restricted Rights"
|
||||
in the software and related documentation as defined in the Federal
|
||||
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
|
||||
are acquiring the software on behalf of the Department of Defense, the
|
||||
software shall be classified as "Commercial Computer Software" and the
|
||||
Government shall have only "Restricted Rights" as defined in Clause
|
||||
252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
|
||||
authors grant the U.S. Government and others acting in its behalf
|
||||
permission to use and distribute the software in accordance with the
|
||||
terms specified in this license.
|
||||
|
||||
This software is copyrighted by the Regents of the University of
|
||||
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
|
||||
Corporation, Apple Inc. and other parties. The following terms apply to
|
||||
all files associated with the software unless explicitly disclaimed in
|
||||
individual files.
|
||||
|
||||
The authors hereby grant permission to use, copy, modify, distribute,
|
||||
and license this software and its documentation for any purpose, provided
|
||||
that existing copyright notices are retained in all copies and that this
|
||||
notice is included verbatim in any distributions. No written agreement,
|
||||
license, or royalty fee is required for any of the authorized uses.
|
||||
Modifications to this software may be copyrighted by their authors
|
||||
and need not follow the licensing terms described here, provided that
|
||||
the new terms are clearly indicated on the first page of each file where
|
||||
they apply.
|
||||
|
||||
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
|
||||
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
|
||||
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
|
||||
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
|
||||
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
|
||||
MODIFICATIONS.
|
||||
|
||||
GOVERNMENT USE: If you are acquiring this software on behalf of the
|
||||
U.S. government, the Government shall have only "Restricted Rights"
|
||||
in the software and related documentation as defined in the Federal
|
||||
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
|
||||
are acquiring the software on behalf of the Department of Defense, the
|
||||
software shall be classified as "Commercial Computer Software" and the
|
||||
Government shall have only "Restricted Rights" as defined in Clause
|
||||
252.227-7013 (b) (3) of DFARs. Notwithstanding the foregoing, the
|
||||
authors grant the U.S. Government and others acting in its behalf
|
||||
permission to use and distribute the software in accordance with the
|
||||
terms specified in this license.
|
||||
|
||||
BIN
desktop/build-cache/embed-test/libcrypto-3.dll
Normal file
BIN
desktop/build-cache/embed-test/libffi-8.dll
Normal file
BIN
desktop/build-cache/embed-test/libssl-3.dll
Normal file
BIN
desktop/build-cache/embed-test/python.cat
Normal file
BIN
desktop/build-cache/embed-test/python3.dll
Normal file
5
desktop/build-cache/embed-test/python313._pth
Normal file
@@ -0,0 +1,5 @@
|
||||
python313.zip
|
||||
.
|
||||
|
||||
# Uncomment to run site.main() automatically
|
||||
#import site
|
||||
BIN
desktop/build-cache/embed-test/python313.dll
Normal file
BIN
desktop/build-cache/embed-test/python313.zip
Normal file
BIN
desktop/build-cache/embed-test/sqlite3.dll
Normal file
BIN
desktop/build-cache/embed-test/vcruntime140.dll
Normal file
BIN
desktop/build-cache/embed-test/vcruntime140_1.dll
Normal file
BIN
desktop/build-cache/python-3.13.9-embed-amd64.zip
Normal file
289
desktop/main.cjs
@@ -1,33 +1,39 @@
|
||||
/**
|
||||
* 豆包 · LynxJS 复刻 —— Electron 桌面壳(CommonJS)
|
||||
* 豆包 · 网页版风格桌面壳(Electron,CommonJS)
|
||||
*
|
||||
* 为什么用 CJS:Electron 主进程在 ESM 下解析 'electron' 会命中 npm 包
|
||||
* (那个包的 index.js 只导出二进制路径),拿不到 app/BrowserWindow。
|
||||
* 内核本身是 ESM,用动态 import() 加载即可。
|
||||
* 和旧版最大的区别:**界面不再是 Lynx**,而是一套真正的 Web 前端(web/ 目录),
|
||||
* AI 内核也换成了和 Android App **同一份 Python 内核**(android/kernel)。
|
||||
* 这样 exe / 浏览器 / 手机三端功能天然同步,不用再维护两套内核。
|
||||
*
|
||||
* 主进程做三件事:
|
||||
* 1. 进程内直接启动 AI 内核(不额外起 node 子进程)
|
||||
* 2. 开一个手机比例窗口,加载 ?frame=0 的界面
|
||||
* 3. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去
|
||||
* 主进程做四件事:
|
||||
* 1. 开一个只监听 127.0.0.1 的"原生能力桥"(选文件 / 剪贴板 / 打开文件夹)
|
||||
* —— Python 内核是子进程,拿不到 Electron 的 dialog/clipboard,只能由主进程代劳;
|
||||
* 2. 起 Python 内核子进程(--port 0 系统分配端口,--json 打出真实地址);
|
||||
* 3. 开一个桌面尺寸窗口加载内核托管的网页;
|
||||
* 4. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去。
|
||||
*/
|
||||
const { app, BrowserWindow, Menu, shell, dialog, clipboard } = require('electron');
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
/**
|
||||
* 可选:开一个 CDP 调试端口,方便用脚本截图/验证桌面窗口。
|
||||
*
|
||||
* 为什么需要:Electron 的界面只有真窗口才渲染得出来,光跑 curl 验不了;
|
||||
* 有了这个端口就能用 scripts/screenshot.mjs 附着上去截图(设 CDP_PORT 即可)。
|
||||
* 默认不开,避免平时多一个监听端口。
|
||||
* 设 DOUBAO_CDP_PORT=9444 启动,再用 CDP_PORT=9444 node scripts/screenshot.mjs - out.png 附着截图。
|
||||
*/
|
||||
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);开发时是仓库根
|
||||
// 用户数据目录:默认 %APPDATA%\Doubao;可用 DOUBAO_USER_DATA 覆盖(开发/自动化测试用,
|
||||
// 避免和已安装的旧版抢同一个 Electron 单实例锁)。
|
||||
if (process.env.DOUBAO_USER_DATA) {
|
||||
app.setPath('userData', path.resolve(process.env.DOUBAO_USER_DATA));
|
||||
}
|
||||
|
||||
// 打包后应用根目录是 resources/app(这里不用 asar);开发时是仓库根
|
||||
const appRoot = app.isPackaged
|
||||
? [
|
||||
path.join(process.resourcesPath, 'app'),
|
||||
@@ -38,59 +44,203 @@ const appRoot = app.isPackaged
|
||||
// 打包后的自有资源放在 <appRoot>/runtime,开发时直接用仓库根
|
||||
const bundledRuntime = path.join(appRoot, 'runtime');
|
||||
const runtimeRoot = fs.existsSync(bundledRuntime) ? bundledRuntime : appRoot;
|
||||
const packaged = fs.existsSync(path.join(runtimeRoot, 'python'));
|
||||
|
||||
process.env.DOUBAO_RESOURCES = runtimeRoot;
|
||||
process.env.DOUBAO_TOOLS = path.join(runtimeRoot, 'tools');
|
||||
process.env.DOUBAO_DATA = path.join(app.getPath('userData'), 'data');
|
||||
const pythonExe = process.env.DOUBAO_PYTHON
|
||||
|| (packaged ? path.join(runtimeRoot, 'python', 'python.exe') : 'python');
|
||||
const kernelEntry = packaged
|
||||
? path.join(runtimeRoot, 'kernel', 'main.py')
|
||||
: path.join(runtimeRoot, 'android', 'kernel', 'main.py');
|
||||
const toolsDir = path.join(runtimeRoot, 'tools');
|
||||
const webDir = path.join(runtimeRoot, 'web');
|
||||
const dataDir = 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 kernelChild = null;
|
||||
let bridgeServer = 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;
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 原生能力桥(Python 内核 ←HTTP→ Electron 主进程) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function startBridge() {
|
||||
return new Promise((resolve, reject) => {
|
||||
bridgeServer = http.createServer((req, res) => {
|
||||
const chunks = [];
|
||||
req.on('data', (c) => chunks.push(c));
|
||||
req.on('end', async () => {
|
||||
let body = {};
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
} catch { /* 空 body 也允许 */ }
|
||||
const reply = (code, obj) => {
|
||||
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify(obj));
|
||||
};
|
||||
try {
|
||||
if (req.url === '/ping') return reply(200, { ok: true });
|
||||
if (req.url === '/clipboard') {
|
||||
clipboard.writeText(String(body.text || ''));
|
||||
return reply(200, { ok: true });
|
||||
}
|
||||
if (req.url === '/pick-file') {
|
||||
const options = {
|
||||
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', 'docx', 'xlsx', 'pptx'],
|
||||
},
|
||||
{ name: '所有文件', extensions: ['*'] },
|
||||
],
|
||||
};
|
||||
const result = win
|
||||
? await dialog.showOpenDialog(win, options)
|
||||
: await dialog.showOpenDialog(options);
|
||||
return reply(200, { ok: true, paths: result.canceled ? [] : result.filePaths });
|
||||
}
|
||||
if (req.url === '/reveal') {
|
||||
const target = String(body.path || '');
|
||||
if (!target) return reply(400, { ok: false, error: 'path 为空' });
|
||||
shell.showItemInFolder(target);
|
||||
return reply(200, { ok: true });
|
||||
}
|
||||
if (req.url === '/open-external') {
|
||||
const url = String(body.url || '');
|
||||
if (!/^https?:/i.test(url)) return reply(400, { ok: false, error: '只允许 http(s)' });
|
||||
shell.openExternal(url);
|
||||
return reply(200, { ok: true });
|
||||
}
|
||||
return reply(404, { ok: false, error: '未知的桥接口' });
|
||||
} catch (err) {
|
||||
return reply(500, { ok: false, error: String((err && err.message) || err) });
|
||||
}
|
||||
});
|
||||
});
|
||||
bridgeServer.on('error', reject);
|
||||
bridgeServer.listen(0, '127.0.0.1', () => resolve(bridgeServer));
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 内核进程 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function startKernel() {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const args = [
|
||||
kernelEntry,
|
||||
'--port', '0', // 系统分配端口,避免 5199 被占用
|
||||
'--data-dir', dataDir,
|
||||
'--tools-dir', toolsDir,
|
||||
'--web-dir', webDir,
|
||||
'--quiet',
|
||||
'--json',
|
||||
];
|
||||
if (bridgeServer) {
|
||||
args.push('--desktop-bridge', `http://127.0.0.1:${bridgeServer.address().port}`);
|
||||
}
|
||||
if (process.env.DOUBAO_NO_MCP) args.push('--no-mcp-autostart');
|
||||
|
||||
console.log(`[desktop] Python: ${pythonExe}`);
|
||||
console.log(`[desktop] 内核: ${kernelEntry}`);
|
||||
console.log(`[desktop] 数据: ${dataDir}`);
|
||||
|
||||
kernelChild = spawn(pythonExe, args, {
|
||||
cwd: runtimeRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUNBUFFERED: '1',
|
||||
DOUBAO_DESKTOP: '1',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
windowsHide: true,
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let buffer = '';
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(new Error('内核启动超时(30 秒没有打出地址)'));
|
||||
}, 30000);
|
||||
|
||||
const finish = (err, url) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (err) reject(err);
|
||||
else resolve(url);
|
||||
};
|
||||
|
||||
kernelChild.stdout.on('data', (chunk) => {
|
||||
const text = chunk.toString('utf8');
|
||||
process.stdout.write(`[kernel] ${text}`);
|
||||
buffer += text;
|
||||
let idx = buffer.indexOf('\n');
|
||||
while (idx >= 0) {
|
||||
const line = buffer.slice(0, idx).trim();
|
||||
buffer = buffer.slice(idx + 1);
|
||||
idx = buffer.indexOf('\n');
|
||||
if (!line.startsWith('{')) continue;
|
||||
try {
|
||||
const info = JSON.parse(line);
|
||||
if (info && info.url) finish(null, info.url);
|
||||
} catch { /* 不是那行 JSON,跳过 */ }
|
||||
}
|
||||
});
|
||||
kernelChild.stderr.on('data', (chunk) => process.stderr.write(`[kernel] ${chunk}`));
|
||||
kernelChild.on('error', (err) => {
|
||||
const hint = err && err.code === 'ENOENT'
|
||||
? `找不到 Python(${pythonExe})。开发模式请先装 Python 3.13;打包版应带 runtime/python。`
|
||||
: String((err && err.message) || err);
|
||||
finish(new Error(hint));
|
||||
});
|
||||
kernelChild.on('exit', (code, signal) => {
|
||||
if (!settled) {
|
||||
finish(new Error(`内核启动失败(退出码 ${code}${signal ? ` / ${signal}` : ''})`));
|
||||
return;
|
||||
}
|
||||
console.error(`[desktop] 内核退出了:code=${code} signal=${signal}`);
|
||||
if (win && !win.isDestroyed()) {
|
||||
dialog.showErrorBox('内核已退出', 'AI 内核意外退出,请重启应用。');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function stopKernel() {
|
||||
if (kernelChild && !kernelChild.killed) {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
spawn('taskkill', ['/pid', String(kernelChild.pid), '/T', '/F'], { windowsHide: true });
|
||||
} else {
|
||||
kernelChild.kill('SIGTERM');
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
kernelChild = null;
|
||||
if (bridgeServer) {
|
||||
try { bridgeServer.close(); } catch { /* ignore */ }
|
||||
bridgeServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 窗口 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function createWindow(url) {
|
||||
win = new BrowserWindow({
|
||||
width: 420,
|
||||
width: 1440,
|
||||
height: 900,
|
||||
minWidth: 360,
|
||||
minHeight: 620,
|
||||
minWidth: 1024,
|
||||
minHeight: 680,
|
||||
title: '豆包',
|
||||
backgroundColor: '#ffffff',
|
||||
autoHideMenuBar: true,
|
||||
@@ -102,7 +252,6 @@ function createWindow(url) {
|
||||
},
|
||||
});
|
||||
|
||||
// 界面是移动端比例,菜单栏只会碍事:去掉,改用快捷键
|
||||
Menu.setApplicationMenu(null);
|
||||
win.once('ready-to-show', () => win.show());
|
||||
|
||||
@@ -129,7 +278,8 @@ function createWindow(url) {
|
||||
}
|
||||
});
|
||||
|
||||
win.loadURL(`${url}?frame=0`);
|
||||
win.loadURL(url);
|
||||
win.on('closed', () => { win = null; });
|
||||
return win;
|
||||
}
|
||||
|
||||
@@ -145,24 +295,23 @@ if (!app.requestSingleInstanceLock()) {
|
||||
});
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
app.setAppUserModelId('com.doubao.lynxclone');
|
||||
app.setAppUserModelId('com.doubao.webclone');
|
||||
try {
|
||||
kernel = await startKernelWithFallback();
|
||||
createWindow(kernel.url);
|
||||
console.log(`[desktop] 内核就绪:${kernel.url} 资源:${runtimeRoot}`);
|
||||
console.log(`[desktop] 数据目录:${process.env.DOUBAO_DATA}`);
|
||||
await startBridge();
|
||||
const url = await startKernel();
|
||||
createWindow(url);
|
||||
console.log(`[desktop] 界面就绪:${url}`);
|
||||
} catch (err) {
|
||||
dialog.showErrorBox('豆包启动失败', String((err && err.stack) || (err && err.message) || err));
|
||||
stopKernel();
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', async () => {
|
||||
try {
|
||||
if (kernel) await kernel.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
app.on('window-all-closed', () => {
|
||||
stopKernel();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
app.on('before-quit', () => stopKernel());
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "doubao-desktop",
|
||||
"productName": "Doubao",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"description": "豆包 · LynxJS 复刻(桌面版):内置 AI 内核,双击即用",
|
||||
"description": "豆包 · 网页版风格复刻(桌面版):内嵌 Python 内核,双击即用",
|
||||
"main": "main.cjs",
|
||||
"scripts": {
|
||||
"start": "electron ."
|
||||
@@ -13,3 +13,4 @@
|
||||
"electron": "^44.7.0"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
301
docs/Python脚本.md
Normal file
@@ -0,0 +1,301 @@
|
||||
# Python 脚本
|
||||
|
||||
这个 App 里**六类地方**会跑 Python 代码。它们的**权限、限制、超时、谁能写**
|
||||
完全不同 —— 混在一起看会出事(比如以为规则脚本也能读文件,或者以为
|
||||
`python_run` 有沙箱)。
|
||||
|
||||
结论先放这儿:
|
||||
|
||||
> **只有"规则脚本"有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
|
||||
> 其余几处(`python_run` / 会议节点 / 自定义节点)本质就是"在你手机上跑代码",
|
||||
> 靠的是**超时**兜底,不是权限隔离。
|
||||
|
||||
---
|
||||
|
||||
## 一、总览
|
||||
|
||||
| # | 在哪 | 谁写 | 能做什么 | 兜底手段 | 超时键 |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | `python_run` 工具 | AI | 任意 Python,可 `import`、可读写文件 | 只有超时 | `pythonRun`(60s) |
|
||||
| 2 | `shell` 工具 | AI | 任意命令 | 危险命令黑名单 + 超时 | `shell`(30s) |
|
||||
| 3 | **规则脚本**(数值/状态) | 用户 | 只能算数/拼字符串,**不能 import、不能读文件** | **白名单沙箱** + 超时 | `customNode`(10s) |
|
||||
| 4 | 会议画布的 Python 节点 | 用户 | 任意 Python(`run(ctx)`) | 只有超时 | `meetingNode`(10s) |
|
||||
| 5 | 自定义节点 `.py` | 用户 | 任意 Python(声明 + `run(ctx, node)`) | 只有超时 | `customNode`(10s) |
|
||||
| 6 | 内置 Termux | 用户 | 真的 bash / python3(独立进程) | Termux 自己的限制 | `termux`(30s) |
|
||||
|
||||
超时都能在**设置 → 超时**里改。0 = 不限时(只有 `askUser` / `waitUi` 允许)。
|
||||
|
||||
---
|
||||
|
||||
## 二、`python_run`:AI 写的代码(进程内执行)
|
||||
|
||||
AI 的一个内置工具,参数:
|
||||
|
||||
| 参数 | 说明 |
|
||||
|---|---|
|
||||
| `action` | `run`(默认)/ `libs`(列出环境里有哪些库) |
|
||||
| `code` | 直接给源码 |
|
||||
| `file` | 或者给一个 `.py` 文件路径 |
|
||||
| `stdin` | 喂给脚本的标准输入 |
|
||||
| `timeout` | 秒;不传就用设置里的 `pythonRun` |
|
||||
|
||||
**怎么执行的**(`kernel/builtin_tools.py` 的 `_exec_source`):
|
||||
|
||||
```python
|
||||
ns = {'__name__': '__main__', '__builtins__': builtins, ...}
|
||||
exec(compile(source, filename, 'exec'), ns) # 全 builtins,没有沙箱
|
||||
```
|
||||
|
||||
- 用的是**进程内的 CPython**(Chaquopy 嵌的)—— 安卓上起不了 Python 子进程
|
||||
- `stdout` / `stderr` 用 `redirect_*` 捕获,`sys.exit()` 的 code 当退出码
|
||||
- 其它异常打印**完整 traceback** 到 stderr(模型据此自我修正)
|
||||
- `cwd` 临时切过去、跑完恢复
|
||||
|
||||
**能干什么**:算数、数据处理(`pandas` 要自己 `pip install`)、调网络
|
||||
(`requests` / `httpx` / `urllib`)、读写文件。
|
||||
|
||||
**注意**:`redirect_stdout` 和 `chdir` 都是**进程级**的(Python 没有线程级实现),
|
||||
所以并发跑两段 `python_run` 时,另一段的 `print` 也可能被收进本次结果。
|
||||
本地单人用没问题,别指望它做多用户服务。
|
||||
|
||||
---
|
||||
|
||||
## 三、`shell`:AI 写的一条命令
|
||||
|
||||
参数 `command` / `cwd` / `timeout`。有一份**危险命令黑名单**
|
||||
(`rm -rf /`、`mkfs`、`dd if=/dev/zero`、frok 炸弹……),
|
||||
可以用环境变量 `DOUBAO_SHELL_UNSAFE=1` 关掉黑名单。
|
||||
|
||||
黑名单是**防手滑**的,不是安全边界 —— 换个写法就绕过去了。
|
||||
|
||||
---
|
||||
|
||||
## 四、规则脚本(唯一有沙箱的地方)
|
||||
|
||||
给**数值系统 / 状态系统**用的脚本。写在「数值状态包」里,每轮在设备上跑。
|
||||
|
||||
### 三个入口函数
|
||||
|
||||
```python
|
||||
def on_stat_change(name, value, delta):
|
||||
"""数值裁决:返回生效的增量。可放大/缩小/归零否决。"""
|
||||
if name == '声望':
|
||||
return delta * 2 # 加倍
|
||||
return delta # 原样
|
||||
# return None → 否决(这次改动不生效)
|
||||
# return (增量, "旁白") → 顺带给用户一句话
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
"""每轮执行(状态脚本用)"""
|
||||
...
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
"""别人给你挂状态时跑。返回 False = 抵抗掉。"""
|
||||
if status_name == '中毒' and self_agent.get('世界') == '仙门':
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
### 注给脚本的能力(`stats_api`)
|
||||
|
||||
状态脚本通过 `stats_api` 读写数值(具体字段见 `rule_engine._stat_api`),
|
||||
用它是**唯一**碰数据的方式 —— 脚本拿不到 store、agentdb 这些东西。
|
||||
|
||||
### 沙箱三层(`kernel/rule_sandbox.py`)
|
||||
|
||||
| 层 | 做什么 | 拦什么 |
|
||||
|---|---|---|
|
||||
| ① 静态扫描 | 源码里有 `__xx__`、`import`、`open/eval/exec/compile/getattr/...` → **直接拒绝** | 手滑、抄来的脚本夹带东西 |
|
||||
| ② 受限 builtins | `exec` 时只喂白名单(算数、字符串、容器、异常) | 没有 `__import__` 就没有模块系统 |
|
||||
| ③ 硬超时 | `customNode` 那一项(默认 10s) | 死循环 |
|
||||
|
||||
### 这个沙箱挡不住什么(写清楚,不装)
|
||||
|
||||
Python 的属性访问是**语法**,不走 builtins:
|
||||
|
||||
```python
|
||||
().__class__.__bases__[0].__subclasses__()
|
||||
```
|
||||
|
||||
第 1 层扫 `__` 就是堵它,但**字符串拼接能绕过去**。真想绕总能绕。
|
||||
|
||||
所以导入带脚本的规则包时,界面上的警告是**实话**:
|
||||
|
||||
> 此包包含可执行 Python 脚本,会**每轮在你的设备上运行**。
|
||||
> 脚本被限制了模块引入和文件读写,但这**不是**真正的沙箱 ——
|
||||
> 精心构造的脚本仍然可能读到设备上的文件。只导入你信得过的来源。
|
||||
|
||||
(而不是写"安全沙箱,请放心导入"。)
|
||||
|
||||
### 异常怎么处理
|
||||
|
||||
**异常 = 本次操作归零 + UI 提示,绝不中断对话。**
|
||||
脚本是用户自己写的,写错是常态;一次 `1/0` 把整轮对话搞崩,
|
||||
用户会以为整个 App 坏了。
|
||||
|
||||
### 脚本存在哪
|
||||
|
||||
- 定义在 `rulepacks.json` 的 `scripts` 字段里(跟着包走,可导出/导入)
|
||||
- 执行时从 `data/rule-scripts/` 落盘读(脚本要作为文件被 `exec`)
|
||||
|
||||
---
|
||||
|
||||
## 五、会议画布的 Python 节点
|
||||
|
||||
会议(`ui/MeetingsScreen`)里有一种节点,代码框里写:
|
||||
|
||||
```python
|
||||
def run(ctx):
|
||||
ctx.log('收到:', ctx.input)
|
||||
ctx.set_var('结果', ctx.input.upper())
|
||||
return '跑完了'
|
||||
```
|
||||
|
||||
**`ctx` 的 API**(`kernel/meeting.py`):
|
||||
|
||||
| 成员 | 说明 |
|
||||
|---|---|
|
||||
| `ctx.input` | 上游传进来的文本 |
|
||||
| `ctx.vars` | 会议变量的**只读快照**(改它不影响会议) |
|
||||
| `ctx.get_var(name, default='')` | 读变量 |
|
||||
| `ctx.set_var(name, value)` | 写变量(真的写进会议变量表) |
|
||||
| `ctx.log(*parts)` | 打印到节点日志(界面上能看到) |
|
||||
| `ctx.node` | 当前节点的信息 |
|
||||
|
||||
- 每次执行都在**全新命名空间**里(节点之间不串变量)
|
||||
- 必须定义 `run(ctx)`,否则报"代码里没有定义 run 函数"
|
||||
- 输出截断到 `PY_MAX_OUTPUT`
|
||||
- 超时 `meetingNode`(默认 10s),超了报"可能有死循环"
|
||||
|
||||
**没有沙箱** —— 就是跑代码。默认的 `__builtins__` 是全的。
|
||||
|
||||
---
|
||||
|
||||
## 六、自定义节点(`nodes/` 里的 `.py`)
|
||||
|
||||
放在**数据目录的 `nodes/`** 下(安卓上是 `files/kernel-data/nodes/`)。
|
||||
文件名按字典序加载(顺序稳定,界面列表不跳),`_` 开头的跳过。
|
||||
|
||||
一个文件里写两段:
|
||||
|
||||
```python
|
||||
ToolName = {
|
||||
'name': '转大写',
|
||||
'icon': 'text',
|
||||
'input': [
|
||||
{'type': 'str', 'name': 'A1', 'value': ''},
|
||||
{'type': 'bool', 'name': 'B1', 'value': True},
|
||||
],
|
||||
'output': [
|
||||
{'type': 'exec', 'name': 'e1'},
|
||||
{'type': 'exec', 'name': 'e2'},
|
||||
{'type': 'str', 'name': 'xx'},
|
||||
],
|
||||
}
|
||||
|
||||
def run(ctx, node):
|
||||
ctx.log('收到:', node['input']['A1'])
|
||||
node['output']['xx'] = '666'
|
||||
node['output']['e1'] = True # 多个 exec 只能一个 True
|
||||
node['output']['e2'] = False
|
||||
return node
|
||||
```
|
||||
|
||||
### 三条语义(**必须在文档和界面上都写清楚**,不然用户一定踩)
|
||||
|
||||
1. **`node['input'][名]` 是引擎填的**实际值,不是声明里的 `value`。
|
||||
声明里的 `value` 只是"这根线没接时用什么"。
|
||||
2. **多个 `exec` 输出最多只能有一个 `True`** —— 这就是多路分支:
|
||||
- 恰好一个 True → 走那一条
|
||||
- 一个都不 True → **停在原地** + 节点上一条警告(不猜、不顺走第一条)
|
||||
- 超过一个 True → 报错(引擎没法替你选)
|
||||
非 exec 的输出不受这条限制。
|
||||
3. **`return` 什么无所谓** —— 引擎读的是 `node['output']`,不看返回值。
|
||||
|
||||
声明是"**同时有 `input` 和 `output` 两个键的字典**",变量名随便叫
|
||||
(`ToolName` / `MyNode` / 中文都行)。
|
||||
|
||||
引脚类型:`exec`(执行)、`str`、`bool`、`num`、`list`。只能用标准库。
|
||||
|
||||
---
|
||||
|
||||
## 七、内置 Termux(真独立进程)
|
||||
|
||||
App 里内置了一套 Termux 环境(`files/usr/`),可以跑真的 `bash` / `python3` /
|
||||
`apt` / `pip`。这是唯一**独立进程**的一处 —— 内核通过它的 CLI 跑命令,
|
||||
超时键 `termux`(默认 30s)。
|
||||
|
||||
软件源已经指向清华 TUNA。第一次启动时会跑一串探针(12 条)验证环境可用。
|
||||
|
||||
---
|
||||
|
||||
## 八、项目自己的 `scripts/`(开发用,不跑在手机上)
|
||||
|
||||
`scripts/` 下有 60 多个 Python 脚本,分三类:
|
||||
|
||||
| 类别 | 例子 | 干什么 |
|
||||
|---|---|---|
|
||||
| **探针**(`probe-*.py`) | `probe-agent-system.py`、`probe-group-chat.py` | 不开 App、不联网,在电脑上跑内核逻辑逐条断言 |
|
||||
| **验证**(`verify-*.py`) | `verify-nodekit.py`、`verify-tts-stream.py` | 验证某个子系统的行为或产物 |
|
||||
| **审计**(`audit-*.py`) | `audit-ui-tree.py`、`audit-ui-entries.py` | 静态检查:文档和代码是否一致、每个界面有没有入口 |
|
||||
| **工具** | `publish-release.py`、`build-apk.mjs` 配套脚本 | 发版、构建辅助 |
|
||||
|
||||
**八个常驻探针**(每次改动都要全绿):
|
||||
|
||||
```bash
|
||||
python scripts/probe-agent-system.py
|
||||
python scripts/probe-degraded.py
|
||||
python scripts/probe-rule-sandbox.py
|
||||
python scripts/probe-rule-engine.py
|
||||
python scripts/probe-context-window.py
|
||||
python scripts/probe-group-chat.py
|
||||
python scripts/audit-ui-tree.py
|
||||
python scripts/audit-ui-entries.py
|
||||
```
|
||||
|
||||
它们**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
内核的存储层无状态,整条链路在一个进程里跑完。
|
||||
|
||||
### 写探针的一条硬纪律:走**生产同一条**调用路径
|
||||
|
||||
踩过:第 22 节直接调 `_set_asset`,而卡住真机的是 `handle()` 里的 `body()` ——
|
||||
探针全绿、真机全挂。
|
||||
|
||||
> **探针能绕过的那一层,就是下次会出问题的那一层。**
|
||||
|
||||
同理,工具类探针要走 `tools_runtime.execute_tool`(它会把上下文搬到 worker 线程),
|
||||
直接调 `agent_tools.xxx` 测的是"函数逻辑对不对",不是"它在这个系统里生不生效"。
|
||||
|
||||
---
|
||||
|
||||
## 九、安全边界(一张表说清)
|
||||
|
||||
| 地方 | 能读设备文件 | 能 import | 能联网 | 能起子进程 | 真沙箱 |
|
||||
|---|---|---|---|---|---|
|
||||
| `python_run` | ✅ | ✅ | ✅ | ❌(安卓没有) | ❌ |
|
||||
| `shell` | ✅ | — | ✅ | ✅ | ❌(只有黑名单) |
|
||||
| **规则脚本** | ❌ | ❌ | ❌ | ❌ | ⚠️ 白名单,**挡手滑不挡有意** |
|
||||
| 会议 Python 节点 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| 自定义节点 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| Termux | ✅ | ✅ | ✅ | ✅ | ❌ |
|
||||
|
||||
**一句话**:除了规则脚本,其它几处都是"能跑代码"级别的能力 ——
|
||||
只在你自己的设备上、你自己授权的前提下有意义。别把别人的包直接导进来。
|
||||
|
||||
---
|
||||
|
||||
## 十、相关文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `kernel/builtin_tools.py` | `shell` / `python_run` 两个内置工具 |
|
||||
| `kernel/rule_sandbox.py` | 规则脚本的三层沙箱 |
|
||||
| `kernel/rule_engine.py` | 规则脚本的入口调用、数值/状态流程 |
|
||||
| `kernel/custom_nodes.py` | 自定义节点(声明 + `run`) |
|
||||
| `kernel/meeting.py` | 会议画布、Python 节点执行 |
|
||||
| `kernel/timeouts.py` | 所有超时键的默认值和说明 |
|
||||
| `kernel/paths.py` | `rule-scripts/`、`nodes/` 等目录 |
|
||||
| `RulePackEditScreen.kt` | 规则包编辑(含脚本框) |
|
||||
| `NodeBlockEditor.kt` | 会议节点编辑(含 Python 代码框) |
|
||||
| `scripts/probe-rule-sandbox.py` | 沙箱边界验证 |
|
||||
| `scripts/probe-rule-engine.py` | 数值/状态系统验证 |
|
||||
1924
docs/kernel-api-agents.md
Normal file
1211
docs/kernel-api-chat.md
Normal file
1290
docs/kernel-api-misc.md
Normal file
BIN
docs/screenshots/agent-card-stats.png
Normal file
|
After Width: | Height: | Size: 767 KiB |
BIN
docs/screenshots/exe2-ai.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
BIN
docs/screenshots/exe2-window.png
Normal file
|
After Width: | Height: | Size: 139 KiB |
BIN
docs/screenshots/web2-agents.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/screenshots/web2-ai-ask.png
Normal file
|
After Width: | Height: | Size: 60 KiB |
BIN
docs/screenshots/web2-ai-ended.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/screenshots/web2-ai-surface.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
docs/screenshots/web2-chat.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
docs/screenshots/web2-group.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
docs/screenshots/web2-meetings.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/screenshots/web2-settings.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
340
docs/数值状态系统-教程.md
Normal file
@@ -0,0 +1,340 @@
|
||||
# 数值状态系统 · 教程
|
||||
|
||||
手把手把「好感度」和「中毒」跑起来。看完你会知道:
|
||||
|
||||
- 数值/状态**从哪进、挂在哪**
|
||||
- 一个规则包由什么组成
|
||||
- 脚本怎么写(三个入口 + 沙箱的限制)
|
||||
- **怎么确认它真的生效了**
|
||||
|
||||
配套参考:[`Python脚本.md`](Python脚本.md)(脚本的权限边界)、
|
||||
[`智能体系统.md`](智能体系统.md)(需求项 → 文件对照)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 先理解链路(这一步搞错后面全白做)
|
||||
|
||||
```
|
||||
「世界观 · 技能 · 模型 → 规则包」建包 ← 定义:有哪些数值、哪些状态
|
||||
↓
|
||||
「世界观 · 技能 · 模型 → 世界观」挂上这个包 ← ★ 挂载点是**世界观**,不是智能体
|
||||
↓
|
||||
智能体绑这个世界观 ← 同一个世界观的智能体共用一个包
|
||||
↓
|
||||
它的提示词里就出现了 <stats> / <status>
|
||||
↓
|
||||
AI 用 change_stat / grant_status 改值 → 落库 → 下一轮反映新值
|
||||
```
|
||||
|
||||
**为什么挂在世界观上**:数值是"这个世界的规则"(灵气、声望、门派贡献),
|
||||
不是一个角色的私有物。而且这么设计之后,**共享数值(`shared=1`)天然只能
|
||||
在一个世界观内共享**,和记忆用的是同一套 scope 写法 —— 用户不用学两套心智模型。
|
||||
|
||||
> ⚠️ 最容易卡住的一步:**建完包不挂到世界观**。不挂就没有
|
||||
> `<stats>` / `<status>` 两段,AI 完全不知道有这回事。
|
||||
|
||||
---
|
||||
|
||||
## 1. 五分钟跑通一个「好感度」
|
||||
|
||||
### 1.1 建包
|
||||
|
||||
**抽屉 → 更多功能 → **世界观 · 技能 · 模型** → 顶栏切到「规则包」→ 右上角「新建」**。
|
||||
|
||||
建出来的包**自带模板**(好感度 + 中毒),可以直接拿来改。
|
||||
|
||||
### 1.2 看它长什么样
|
||||
|
||||
点进包 → 进「规则包编辑」全屏页。顶部两行是**名称**和**说明**,
|
||||
下面是**脚本**区和**定义**区。
|
||||
|
||||
一个包的完整内容就是三样:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"stats": [
|
||||
{
|
||||
"name": "好感度", // ★ 唯一标识,脚本和工具里都用它
|
||||
"min": 0, // 下限
|
||||
"max": 100, // 上限
|
||||
"shared": 0, // 0 = 每个智能体各算各的;1 = 全世界观一份
|
||||
"ranges": [ // 区间表:命中哪段,就把那段文字注入提示词
|
||||
{"min": 0, "max": 30, "text": "戒备:你对他还有戒心"},
|
||||
{"min": 30, "max": 70, "text": "友善:你对他态度友善,但保持分寸"},
|
||||
{"min": 70, "max": 100, "text": "亲近:你已经把他当自己人了"}
|
||||
],
|
||||
"script": "stat.py" // 可选:数值裁决脚本
|
||||
}
|
||||
],
|
||||
"statuses": [
|
||||
{
|
||||
"name": "中毒",
|
||||
"kind": "timed", // timed = 每轮减 1;persistent = 永不过期
|
||||
"turns": 3, // timed 时持续几轮
|
||||
"max_stack": 1, // 最多叠几层
|
||||
"script": "status.py" // 可选:赋予判定 + 每轮行为
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3 挂到世界观
|
||||
|
||||
**世界观 · 技能 · 模型 → 世界观 → 点开一个世界观 → 往下找「数值状态包」** →
|
||||
选你刚建的那个包(选「不挂」就关掉)。
|
||||
|
||||
保存。
|
||||
|
||||
### 1.4 让智能体绑这个世界观
|
||||
|
||||
**智能体编辑 → 世界观** → 选同一个。
|
||||
|
||||
### 1.5 确认生效
|
||||
|
||||
打开那个智能体的对话,问它一句「你现在对我什么感觉」。
|
||||
|
||||
如果它的话里带上了 interval 表里的措辞("戒备"/"友善"/"亲近"),
|
||||
说明 `<stats>` 段注进去了。
|
||||
|
||||
**更准的自查**:聊天页顶栏点状态栏 → 进 [状态数值] 页 ——
|
||||
那里列着所有数值和当前值,**来源会写明来自哪个包**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 数值怎么变
|
||||
|
||||
AI 只能调一个工具:
|
||||
|
||||
```
|
||||
change_stat(name="好感度", delta=5)
|
||||
```
|
||||
|
||||
**注意它只能给增量,不能写绝对值。** 这是刻意的:
|
||||
|
||||
- 允许写绝对值的话,"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5,我判成加 10",而不是"你想设成 100,我判……多少"
|
||||
- 群聊里两个智能体同时改同一个 shared 数值时,**绝对值互相覆盖,增量不会**
|
||||
|
||||
### 完整流程(顺序固定)
|
||||
|
||||
```
|
||||
脚本裁决(有脚本时) → clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
```
|
||||
|
||||
| 环节 | 说明 |
|
||||
|---|---|
|
||||
| **脚本裁决** | 脚本返回生效的增量;可放大/缩小;返回 `None` = 否决 |
|
||||
| **clamp** | 超界的值被钳到 `min`/`max` |
|
||||
| **写库** | 按 scope 写(`agent:<uuid>` 或 `world:<uuid>`) |
|
||||
| **下一轮注入** | 提示词里显示新值,**并且带一个 `450→500` 的箭头** |
|
||||
|
||||
那个箭头**只显示一轮**(放内存、用完就丢),它只是提示,不是数据。
|
||||
|
||||
### 注入的实际样子
|
||||
|
||||
```
|
||||
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
|
||||
[自身] 好感度: 45/100 —— 友善:你对他态度友善,但保持分寸
|
||||
```
|
||||
|
||||
`[世界·xx]` / `[自身]` 前缀是自动加的,让模型知道哪些值是全世界的、
|
||||
哪些是它自己的。
|
||||
|
||||
---
|
||||
|
||||
## 3. 状态怎么来、怎么没
|
||||
|
||||
### 赋予
|
||||
|
||||
AI 调:
|
||||
|
||||
```
|
||||
grant_status(target="用户", status="中毒")
|
||||
```
|
||||
|
||||
流程固定四条:
|
||||
|
||||
1. **必须同世界观** —— 跨世界观一律拒绝(没有共享规则体系,"赋予"没有依据)
|
||||
2. 跑**目标方**的 `on_grant` 判定脚本 —— 判定权在被挂的人手里
|
||||
3. 接受 → 实例化;拒绝 → 发起方收到「被抵抗」的明确回执
|
||||
4. **同名重复赋予默认刷新轮数**(不是累加);定义里配了 `max_stack` 才叠层
|
||||
|
||||
### 消退
|
||||
|
||||
`timed` 的状态**每参与一轮减 1**,到 0 删除,并播报「中毒已经消退了」。
|
||||
|
||||
`persistent` 的状态**永不过期**(内部记 `remaining = -1`,不参与递减),
|
||||
要移掉得用 `drop_status`。
|
||||
|
||||
---
|
||||
|
||||
## 4. 脚本怎么写
|
||||
|
||||
脚本是**可选的**。不写脚本,数值照样按增量改、状态照样到期消失 ——
|
||||
脚本只在你要"额外的判断"时才需要。
|
||||
|
||||
### 4.1 数值裁决:`on_stat_change`
|
||||
|
||||
包里起个文件(比如 `stat.py`),在「规则包编辑 → 脚本」里新建并写:
|
||||
|
||||
```python
|
||||
def on_stat_change(name, value, delta):
|
||||
"""
|
||||
name : 数值名
|
||||
value : 改之前的值
|
||||
delta : AI 想加的增量
|
||||
返回 : 实际生效的增量
|
||||
"""
|
||||
if name == '好感度':
|
||||
# 越熟越难加(边际递减)
|
||||
if value >= 80:
|
||||
return delta * 0.3
|
||||
return delta
|
||||
return delta
|
||||
```
|
||||
|
||||
返回值有三种写法:
|
||||
|
||||
| 返回 | 含义 |
|
||||
|---|---|
|
||||
| 一个数字 | 生效的增量(可以跟 `delta` 不一样) |
|
||||
| `None` | **否决**这次改动 |
|
||||
| `(增量, "旁白")` | 顺带往这一轮的旁白里加一句 |
|
||||
|
||||
### 4.2 每轮行为:`on_turn`
|
||||
|
||||
```python
|
||||
def on_turn(self_agent, stats_api):
|
||||
"""每轮执行一次(状态脚本用)"""
|
||||
...
|
||||
```
|
||||
|
||||
### 4.3 赋予判定:`on_grant`
|
||||
|
||||
**跑在目标方** —— 被挂状态的人有权抵抗:
|
||||
|
||||
```python
|
||||
def on_grant(status_name, source_agent):
|
||||
"""返回 False = 抵抗掉这个状态"""
|
||||
if status_name == '中毒' and self_agent.get('世界') == '仙门':
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
### 4.4 脚本不能做什么(这是硬限制)
|
||||
|
||||
规则脚本跑在**白名单沙箱**里:
|
||||
|
||||
- ❌ **不能 `import`**(没有模块系统)
|
||||
- ❌ **不能 `open`**(读不了文件)
|
||||
- ❌ 不能用 `eval` / `exec` / `getattr` / `__xx__` 这类东西
|
||||
- ✅ 能算数、拼字符串、处理列表字典、`try/except`
|
||||
|
||||
**为什么这么严**:规则脚本是"数值修正器",正经写它根本用不到那些。
|
||||
静态扫描拦的是"手滑"和"抄来的脚本夹带东西"。
|
||||
|
||||
> ⚠️ 但要说实话:**这个沙箱挡得住手滑,挡不住有意。**
|
||||
> Python 的属性访问是语法,精心构造的代码*可能*绕过。
|
||||
> 所以导入带脚本的包时,请只导你信得过的来源。
|
||||
|
||||
### 4.5 脚本写错了会怎样
|
||||
|
||||
**异常 = 本次操作归零 + 界面提示,不会中断对话。**
|
||||
|
||||
数字脚本报错时"这一次改动不生效",而不是"按原值放行" ——
|
||||
宁可这一下不生效,也不能让坏脚本失控地改数值。
|
||||
|
||||
---
|
||||
|
||||
## 5. 界面上还有哪些地方能看到
|
||||
|
||||
| 界面 | 从哪进 | 看什么 |
|
||||
|---|---|---|
|
||||
| **[状态数值]** | 聊天页状态栏 / 智能体编辑的「它的状态」/ 群成员页的「状态」 | 所有数值的当前值 + 谁在挂这个包 |
|
||||
| **规则包编辑** | 世界观 · 技能 · 模型 → 规则包 → 点一个包 | 改定义、写脚本、导出/导入 |
|
||||
| **规则包列表** | 抽屉 → 更多功能 →「世界观 · 技能 · 模型」→ 切「规则包」 | 包列表,副标题写着有几条数值/状态、带不带脚本 |
|
||||
|
||||
**用户可以直接改值**(在 [状态数值] 页里)—— 这是兜底主权:
|
||||
AI 记错了、脚本判歪了,得有一个人能直接拨回去。
|
||||
|
||||
---
|
||||
|
||||
## 6. 常见问题
|
||||
|
||||
<details>
|
||||
<summary><b>AI 完全不知道有数值这回事</b></summary>
|
||||
|
||||
按顺序查:
|
||||
|
||||
1. **世界观挂包了吗** ← 最常见。「世界观 · 技能 · 模型 → 世界观 → 数值状态包」得选上
|
||||
2. **智能体绑这个世界观了吗**
|
||||
3. **包里有 `stats` 吗** —— 空包同步时会直接跳过(不动库)
|
||||
4. 提示词里 `<stats>` 段在**最末尾**,模型如果只读了开头可能没注意 ——
|
||||
直接问它"你的好感度现在多少"
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>改了值但提示词里还是旧的</b></summary>
|
||||
|
||||
数值是**每轮开始**才注入的。改完要**下一条消息**才看得到新值 ——
|
||||
一次对话只有一次注入。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>两个智能体的好感度互相串了</b></summary>
|
||||
|
||||
检查 `shared`:
|
||||
|
||||
- `shared=0` → `agent:<uuid>`,各算各的
|
||||
- `shared=1` → `world:<uuid>`,整个世界观一份
|
||||
|
||||
串了说明定义里写成了 `shared=1`。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>状态删不掉 / 想手动挂一个</b></summary>
|
||||
|
||||
在 **[状态数值]** 页里,每条状态右边都有**「清掉」**按钮,直接点就行。
|
||||
包里有还没挂上的状态时,下面还会自动出现**「加一个」**区块。
|
||||
|
||||
这背后是个真实缺口被补上的过程:AI 手里只有 `grant_status`(**只能加**),
|
||||
**没有任何工具能移除状态** —— 所以 `persistent` 状态一旦挂上就永远下不来、
|
||||
`timed` 的也只能干等。现在界面上给了出口:
|
||||
|
||||
- **清掉**:每条状态一个按钮。不做二次确认 —— 状态本来就能再加回来,
|
||||
连清五个不该弹五次窗
|
||||
- **加一个**:只列"还没挂上的",点一下直接挂。用来测某个状态的效果,
|
||||
或者补剧情里本来就该有的
|
||||
|
||||
> 这一页有三个入口:**聊天页状态栏** / **智能体编辑 →「它的状态」→
|
||||
> 「看它的数值和状态」** / **群成员页的「状态」按钮**。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>脚本报"用了双下划线属性"/"写了 import"</b></summary>
|
||||
|
||||
这是沙箱的静态扫描在拦。规则脚本**不需要**那些东西 ——
|
||||
把 `import` 删掉,把 `xxx.__yyy__` 换成普通写法。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>删了数值定义,值去哪了</b></summary>
|
||||
|
||||
**值还在库里,但读不到了** —— 定义没了它们就成了孤儿。
|
||||
|
||||
所以内核有一条保护:**空定义不同步**(不会因为读不到包就把定义清空)——
|
||||
要清定义就把整个包删掉,那是个明确得多的动作。
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 7. 最小可用清单
|
||||
|
||||
想最快看到效果,记住这四步就够:
|
||||
|
||||
1. **世界观 · 技能 · 模型 → 规则包 → 新建**(用模板)
|
||||
2. **世界观 · 技能 · 模型 → 世界观 → 数值状态包 → 选它**
|
||||
3. **智能体 → 世界观 → 选同一个**
|
||||
4. 发一句话,问它"你现在对我什么感觉"
|
||||
|
||||
脚本可以先完全不管 —— 没有脚本,数值和状态照样工作。
|
||||
261
docs/网页版.md
Normal file
@@ -0,0 +1,261 @@
|
||||
# 网页版 / Windows exe(v2:豆包网页版风格 + 与 App 同一份内核)
|
||||
|
||||
> 这份文档说的是 **Web / Windows 端**。安卓端(主力)看根目录 README 和 `docs/界面总览.md`。
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
Web/Windows 端从旧的 **Lynx 手机壳**换成了**豆包网页版风格**的真 Web 前端(`web/`),
|
||||
并且**不再维护第二套内核**:exe 会把仓库里和安卓 App 完全相同的那份 **Python 内核**
|
||||
(`android/kernel/`)作为子进程跑起来,网页前端只是它的一个客户端。
|
||||
所以「和 App 功能同步」不是逐条抄接口,而是**同一份后端** —— 内核加功能,Web 端跟着就能用。
|
||||
|
||||
| | 旧版(v1) | 现在(v2) |
|
||||
|---|---|---|
|
||||
| 界面 | Lynx(`app/`,手机比例 420×900 窗口) | 纯 HTML/CSS/JS(`web/`,1440×900 桌面网页) |
|
||||
| 视觉 | 手机 App 风格(抽屉 + 底部输入框) | 豆包**网页版**风格(左栏 280 + 中间内容列 1000 + 底部大输入框) |
|
||||
| 内核 | Node(`server/`,功能落后于 App) | **Python(`android/kernel/`,与安卓 App 同一份)** |
|
||||
| exe 运行时 | Electron + 内置 Node | Electron + **内置嵌入式 Python**(`runtime/python`) |
|
||||
| 功能同步 | 手工维护两份内核(欠账越拉越多) | 天然同步(一份内核,两个客户端) |
|
||||
|
||||
旧的 Lynx 版**没有删**:`app/` 和 `server/` 还在,`npm run start:legacy-lynx` 还能跑,只作为历史留档。
|
||||
|
||||
---
|
||||
|
||||
## 1. 怎么跑
|
||||
|
||||
### 浏览器(开发/日常)
|
||||
|
||||
需要电脑上有 **Python 3.10+**(内核用了 `str | None` 这类新语法;实测 3.12 / 3.13 都行)。
|
||||
|
||||
```bash
|
||||
npm start # = node scripts/start-web.mjs,起内核并托管 web/
|
||||
# 打开 http://127.0.0.1:5199/
|
||||
```
|
||||
|
||||
- 换端口:`PORT=5300 npm start`
|
||||
- 指定解释器:`DOUBAO_PYTHON=C:\Python313\python.exe npm start`
|
||||
- 数据目录默认是仓库里的 `data/`(已 gitignore),可用 `DOUBAO_DATA` 覆盖
|
||||
|
||||
### Windows exe
|
||||
|
||||
```bash
|
||||
npm run exe # 产出 …\DoubaoClone\Doubao-win32-x64\豆包.exe
|
||||
```
|
||||
|
||||
打包脚本会自动:
|
||||
1. 下载/复用 `desktop/build-cache/python-3.13.9-embed-amd64.zip`(python.org 的嵌入式 Python,约 10MB);
|
||||
2. 解压到 `runtime/python`(用户电脑**不需要装 Python**);
|
||||
3. 复制内核 `android/kernel/` → `runtime/kernel`、工具 `tools/` → `runtime/tools`、前端 `web/` → `runtime/web`;
|
||||
4. 用 electron-packager 打包(**输出路径必须是纯 ASCII**,否则 Electron 启动崩溃,见 README §7.1)。
|
||||
|
||||
exe 启动流程(`desktop/main.cjs`):
|
||||
|
||||
```
|
||||
Electron 主进程
|
||||
├─ 起一个只监听 127.0.0.1 的「原生能力桥」(选文件 / 剪贴板 / 在资源管理器显示)
|
||||
├─ spawn runtime/python/python.exe runtime/kernel/main.py
|
||||
│ --port 0(系统分配) --data-dir %APPDATA%\Doubao\data
|
||||
│ --tools-dir runtime/tools --web-dir runtime/web
|
||||
│ --desktop-bridge http://127.0.0.1:<桥端口>
|
||||
├─ 读内核 stdout 里的那行 JSON 拿到真实端口
|
||||
└─ 开 1440×900 窗口加载 http://127.0.0.1:<端口>/
|
||||
```
|
||||
|
||||
原生能力桥是**必需的**:Python 子进程里没有 Electron 的 `dialog/clipboard`。
|
||||
桥的实现是 `desktop/main.cjs` 的 `startBridge()` + `android/kernel/main.py` 的 `--desktop-bridge`
|
||||
(内核侧注册 `app.set_native_hooks(...)`,和安卓 Kotlin 那侧是同一个钩子接口)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目录地图
|
||||
|
||||
```
|
||||
web/ # 网页版前端(纯静态,无构建步骤)
|
||||
index.html # 入口
|
||||
assets/app.css # 设计系统 + 全部页面样式(值是对着豆包网页版实测的)
|
||||
assets/avatars/*.png # 内置智能体头像(本仓库自己的素材)
|
||||
js/
|
||||
api.js # fetch 封装 + 全局 state + 聊天轮询
|
||||
ui.js # h() / icon() / markdown / toast / 弹层 / 表单小部件
|
||||
icons.js # 74 个手写 SVG 图标(Lucide 风格,不抄豆包资源)
|
||||
app.js # 启动、侧栏、顶栏、hash 路由
|
||||
pages/ # 一页一个模块(页面契约见 app.js 头部注释)
|
||||
chat.js # 对话(流式、思考、工具轨迹、附件、群聊、交接条、朗读、语音输入)
|
||||
agents.js # 智能体列表
|
||||
agent-edit.js # 智能体编辑
|
||||
groups.js # 群聊管理
|
||||
memories.js # 记忆 + 情绪
|
||||
usage.js # Token 用量
|
||||
resources.js # 世界观 / Skill / 全局模型 / 规则包
|
||||
skills.js # Python 工具 / MCP / AI 界面开关
|
||||
notes.js / screens.js # 笔记 / AI 界面
|
||||
meetings.js # 会议模式(一期:列表/运行/结果/历史)
|
||||
settings.js # 设置(模型/对话/语音/工具/外观/超时)
|
||||
me.js / about.js # 我的 / 关于
|
||||
scripts/
|
||||
start-web.mjs # npm start:起 Python 内核托管 web/
|
||||
build-exe.mjs # 打包 Windows exe(含嵌入式 Python)
|
||||
verify-web-ui.mjs # 验收:起临时内核,逐页截图 + 收集 JS 报错
|
||||
scrape-doubao-web.mjs # 扒豆包网页版做视觉参考(产物在 reference/,不入库)
|
||||
android/kernel/ # ★ 和安卓 App 共用的 Python 内核(Web/exe 也跑它)
|
||||
desktop/main.cjs # Electron 主进程(内核子进程 + 原生桥 + 窗口)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 设计:怎么做到「看起来是豆包网页版」
|
||||
|
||||
`docs/豆包网页版-风格规范.md` 是对着**真实豆包网页版(www.doubao.com/chat,1440×900)**
|
||||
的抓取镜像逐像素量出来的规范。抓取可复现:
|
||||
|
||||
```bash
|
||||
node scripts/scrape-doubao-web.mjs # 产物 reference/doubao-web-mirror/(第三方资源,已 gitignore)
|
||||
node scripts/probe-doubao-web-metrics.mjs # 补测 CSS 变量/组件尺寸
|
||||
```
|
||||
|
||||
落到实现上的关键值(详见规范文档):
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 侧栏 | 宽 280、背景 `#f9f9f9`、右边 0.5px `rgba(0,0,0,.064)`、内边距 `10 12 12` |
|
||||
| 主区顶栏 | 高 56 |
|
||||
| 内容列 | 1000 居中(`--content-w`) |
|
||||
| 空态问候语 | 28px / 600 / 行高 42 / 块顶约 308 |
|
||||
| 输入框 | 1000×100、圆角 24、`1px rgba(0,0,0,.1)`、大阴影;聚焦变 `rgba(0,102,255,.3)` 细蓝边 + 光晕 |
|
||||
| 品牌蓝 | `#0066ff`(= `#06f`) |
|
||||
| 文字 | 主 `#000`、次 `rgba(0,0,0,.5)`、三级 `rgba(0,0,0,.35)` |
|
||||
| 空态右下角 | 浅灰圆形麦克风;有内容才换成蓝色圆形发送 |
|
||||
| 暗色 | `[data-theme=dark]` 一整套 token(侧栏 `#0f0f0f`、浮层 `#181818`) |
|
||||
|
||||
我们**只学布局/尺寸/配色**:图标全部是 `web/js/icons.js` 里手写的 74 个 SVG,
|
||||
不包含豆包的 logo、字体文件、图标资源、文案。
|
||||
|
||||
---
|
||||
|
||||
## 4. 功能同步矩阵(Web 端 vs 安卓 App)
|
||||
|
||||
内核是同一份,所以**能力**是全的;差别只在「网页端界面盖了多少」。
|
||||
|
||||
| App 里的功能 | Web 端 | 说明 |
|
||||
|---|---|---|
|
||||
| 对话、流式回复、思考过程、工具轨迹、附件、出错提示 | ✅ | `chat.js`:POST /api/chat + 轮询,事件和安卓端完全一致(`docs/kernel-api-chat.md`) |
|
||||
| 深度思考(思考强度五档)、切换智能体/模型 | ✅ | 顶栏模型菜单 + 输入框「思考」 |
|
||||
| 消息操作:复制 / 朗读 / 赞踩 / 标记重要 | ✅ | 标记重要按"内容"定位(内核要求的) |
|
||||
| 自动朗读、语音输入 | ✅(有降级) | 朗读:`system` 引擎用浏览器 `speechSynthesis`,云端引擎播内核返回的音频;语音输入:优先浏览器识别,其次录音 + 内核 `/api/stt`(需要 OpenAI 兼容 STT) |
|
||||
| 群聊:成员、@ 发言、AI 之间移交话头、让他们聊几轮 | ✅ | 群成员条 + `speaker`/`handoff` 事件 + 交接条 |
|
||||
| 智能体:列表 / 新建 / 编辑 / 删除 / 导入导出 | ✅ | `agents.js` / `agent-edit.js`(导入导出为 base64 zip 下载/上传) |
|
||||
| 记忆:增删改、置顶、AI 整理、导入导出、世界观共享记忆(只读) | ✅ | `memories.js` |
|
||||
| 情绪(活着/死亡/自定义情绪文本) | ✅ | `memories.js` 顶部情绪卡片 |
|
||||
| Token 用量:按模型分桶、额度、清零 | ✅ | `usage.js` |
|
||||
| 资源:世界观 / Skill / 全局模型 / 规则包(含脚本警告确认) | ✅ | `resources.js` |
|
||||
| 技能·连接器:Python 工具试运行、MCP 配置/连接/断开、AI 界面开关 | ✅ | `skills.js` |
|
||||
| 笔记、AI 界面列表(可重新打开) | ✅ | `notes.js` / `screens.js`;电脑端 show_ui 也会落盘,见下 |
|
||||
| 会议模式:列表 / 运行 / 实时日志 / 结果 / 历史 | ✅(一期) | `meetings.js`;节点画布是二期(Android 那份 7600 行,不硬搬) |
|
||||
| 设置:10 家提供商、思考强度、对话上下文、语音、工具与安全、外观、22 项超时 | ✅ | `settings.js` |
|
||||
| 我的 / 关于 / 主题(浅色/深色/跟随系统) | ✅ | `me.js` / `about.js` |
|
||||
| 内置 Termux 终端 | ❌(Web 端做不了) | 这是安卓专属能力;桌面等价物是"Python 工具试运行"和 shell 工具 |
|
||||
| 立绘/背景/整屏 AI 形象 | ⏳ 未做 | 内核有 `image` 字段和 asset 接口,Web 端还没画 |
|
||||
| `show_ui` / `ask_user` / `end_conversation`(AI 弹界面、提问、封笔) | ✅ | 走内核的**界面能力通道**(`/api/device/*` HTTP 队列),`wait` 语义和安卓一致;详见 §5.1 |
|
||||
| 会议节点画布 | ⏳ 二期 | 一期已能跑/看结果 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 验收
|
||||
|
||||
```bash
|
||||
node scripts/verify-web-ui.mjs # 14 个页面逐页截图 + 收集 JS 报错
|
||||
node scripts/verify-ui-bridge.mjs # AI 界面能力通道(show_ui / ask_user / end_conversation)
|
||||
```
|
||||
|
||||
`verify-web-ui.mjs`:起一个**独立临时数据目录**的 Python 内核 → 用无头 Edge 逐页打开 14 个路由 →
|
||||
每页截图到 `.tmp-verify-web/` → 收集 JS 报错 → 有报错/白屏就退出码 1。
|
||||
对着已跑着的内核验可以 `--base http://127.0.0.1:5199`。
|
||||
|
||||
`verify-ui-bridge.mjs`:同样自己起临时内核、不需要浏览器,覆盖 11 项:
|
||||
ask_user 阻塞→回答→工具拿到 choice、show_ui(wait=false) 落盘+通知队列、
|
||||
show_ui(wait=true) 阻塞→回答→工具拿到 value、end_conversation 落盘、错误路径 404。
|
||||
|
||||
### 5.1 AI 界面能力是怎么在电脑端跑通的
|
||||
|
||||
`show_ui` / `ask_user` / `end_conversation` 三个工具在安卓上走 Kotlin 的 `NativeBridge.device()`(同步阻塞)。
|
||||
电脑/网页端没有原生桥,内核加了一条 **HTTP 界面通道**(`android/kernel/app.py`):
|
||||
|
||||
```
|
||||
工具线程(_ui_bridge.call_device,阻塞)
|
||||
↓ 放入队列
|
||||
GET /api/device/pending ← 网页每 700ms 轮询(web/js/device.js)
|
||||
↓ 网页弹:ask_user → 选择弹窗;show_ui → iframe 渲染 AI 写的 HTML
|
||||
POST /api/device/answer → 用户的选择/点选值送回内核
|
||||
↓
|
||||
工具线程拿到结果继续(wait=true 的语义完整保留:点选值 / 关闭 / 超时)
|
||||
```
|
||||
|
||||
- 队列是 **FIFO** 的(同时开两个对话/标签页也不会互相顶掉),上限 8 个;
|
||||
- 网页不给 `timeoutMs` 时内核最多等 1 小时(安卓是"不限时",网页端不做无限占线程);
|
||||
- `show_ui` 的界面会**同时落盘**(`store.save_screen`),所以 `/api/screens` 在电脑端也有数据、
|
||||
「AI 界面」页能重新打开;
|
||||
- `end_conversation` 是纯内核写操作(会话标记 `ended` + 原因),网页端只负责显示
|
||||
「这次对话已结束」提示条并锁住输入框;
|
||||
- 界面里的 `Doubao.sendToAi(v)` / `Doubao.close()` / `<button data-doubao-result="…">`
|
||||
通过 `postMessage` 回到网页(iframe 用 `sandbox`,AI 的 HTML 拿不到内核接口)。
|
||||
|
||||
浏览器的 `#/settings → 工具与安全` 里打开「AI 界面能力」开关后,模型才会用这三个工具(默认关)。
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假 OpenAI 兼容服务,监听 5299
|
||||
# 在设置里把提供商选自定义,baseUrl=http://127.0.0.1:5299/v1、模型随手填、Key 随手填
|
||||
```
|
||||
|
||||
exe 的验证方式:`DOUBAO_CDP_PORT=9444` 启动后,用
|
||||
`CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着截图(Electron 界面只有真窗口渲染得出来)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 已知差距 / 坑
|
||||
|
||||
**功能差距**:
|
||||
|
||||
1. 会议画布(节点/连线编辑)是二期。
|
||||
2. 立绘/背景/整屏角色图未做(内核有 `image` 字段和 asset 接口,Web 端还没画)。
|
||||
3. 内置 Termux 终端做不了(安卓专属),桌面等价物是「Python 工具试运行」。
|
||||
|
||||
**踩过的坑(都修好了,写下来防复现)**:
|
||||
|
||||
1. **`ELECTRON_RUN_AS_NODE=1` 会让 Electron 当 Node 跑**:本机环境里全局有这个变量,
|
||||
开发时 `electron .` 直接报 `Cannot read properties of undefined (reading 'commandLine')`。
|
||||
启动 GUI 前要 `Remove-Item Env:ELECTRON_RUN_AS_NODE`(打包给用户的 exe 不受影响)。
|
||||
2. **exe 的数据目录/单实例锁**:开发时如果和旧版 Electron 抢 `%APPDATA%\Doubao`,
|
||||
会报 `Lock file can not be created (0x5)` 然后静默退出。现在支持
|
||||
`DOUBAO_USER_DATA` / `DOUBAO_DATA` 环境变量覆盖(自动化测试用,正常用户不用管)。
|
||||
3. **Electron 在中文路径下启动崩溃**(0xC0000005):打包输出目录固定用 ASCII(`C:\…\DoubaoClone`)。
|
||||
4. **内嵌 Python 必须验证 sqlite3/ssl**:Embeddable zip 自带 `_sqlite3.pyd` / `sqlite3.dll` / `_ssl.pyd`,
|
||||
内核的记忆库和 HTTPS 调用都靠它们。打包脚本不会替你检查,改动 `PY_VERSION` 后要手动跑一次。
|
||||
5. **窗口默认 1440×900,但用户可能缩小**:空态的内容高度要自适应(`padding-top` 用 `calc(100vh - …)`),
|
||||
否则推荐条目会被底部输入框盖住(踩过一次,Electron 内高约 864 时最明显)。
|
||||
6. **流式消息的"最终重渲染"**:`renderMessage()` 会把 `msg._el` 指向**新节点**,
|
||||
先取 `_el` 再 `replaceChild` 永远替换不上(表现:流式那条停在半截内容 + 操作栏已出现)。
|
||||
正确顺序是 `const oldNode = msg._el;` → `renderMessage()` → `oldNode.parentNode.replaceChild(newNode, oldNode)`。
|
||||
7. **轮询 `done` 之后还有事件**:内核的 `handoff` / `status` / `saved` 在 `done` **之后**才发,
|
||||
客户端拿到 `done:true` 要在补拉一拍(`api.js` 的 `runChat` 里有 `flushing` 逻辑)。
|
||||
8. **群聊 `@` 的按钮一直在**:`atBtn` 要先渲染再按 `isGroup` 隐藏,不能在骨架阶段条件渲染
|
||||
(骨架阶段还不知道这个会话是不是群)。
|
||||
9. **界面能力请求不能用"一个槽位"**:`/api/device/*` 一开始是单个 `_DEVICE_PENDING`,
|
||||
后来发现上一个弹窗没答时新请求会把它**静默顶掉**(那个工具线程要一直等到超时,
|
||||
用户看到的是"AI 说要问我、界面却没弹")。改成 FIFO 队列 + 上限 8 就对了。
|
||||
10. **iframe 里的 `Doubao.sendToAi` 要靠 postMessage**:`sandbox` 不带 `allow-same-origin`,
|
||||
父页面**碰不到** iframe 的 DOM;所以桥是注入到 srcdoc 里的脚本 + `parent.postMessage`,
|
||||
父页面只监听 `message` 并按 `event.source === iframe.contentWindow` 校验。
|
||||
11. **`end_conversation` 之后要重新拉会话**:工具是"写内核数据",不会自动改前端内存里的消息列表;
|
||||
聊天页在 `toolTrace` 里看到 `end_conversation` 成功后重新 `GET /api/conversations/<id>`,
|
||||
才能显示「这次对话已结束」并锁住输入框。
|
||||
|
||||
---
|
||||
|
||||
## 7. 接口契约文档(写前端时的唯一事实来源)
|
||||
|
||||
- `docs/kernel-api-chat.md` —— 聊天链路:`/api/chat` + `/api/chat/poll` 的 14 种事件、消息对象字段、
|
||||
附件/TTS/STT/UI 回流、25 条移植坑
|
||||
- `docs/kernel-api-agents.md` —— 智能体 / 记忆 / 情绪 / 用量 / 世界观 / 模型列表 / Skill / 规则包 / 设置 / 超时
|
||||
- `docs/kernel-api-misc.md` —— 工具 / MCP / 会议 / 笔记 / AI 界面 / 上传 / 语音 / 桌面桥
|
||||
|
||||
这三份是照着内核源码 + 对真实内核的 GET 探测写的(不是凭记忆),加接口时先更新它们。
|
||||
884
docs/豆包网页版-风格规范.md
Normal file
@@ -0,0 +1,884 @@
|
||||
# 豆包网页版 · 风格规范(抓取镜像实测版)
|
||||
|
||||
> 目标:让我们的 Web 前端(纯 HTML/CSS/JS,跑在本地 kernel,桌面 Electron + 浏览器)
|
||||
> **看起来就是豆包网页版那个风格**。开发者只看这一份文档 + 三张截图就能搭出首屏。
|
||||
>
|
||||
> 本文所有数字来自 `reference/doubao-web-mirror/`(**只读**镜像),不是凭印象写的。
|
||||
|
||||
---
|
||||
|
||||
## 0. 怎么读这份文档
|
||||
|
||||
### 0.1 基准
|
||||
|
||||
| 项 | 值 | 来源 |
|
||||
|---|---|---|
|
||||
| 视口 | 1440 × 900,dpr = 1 | `styles/computed-styles.json` → `viewport` |
|
||||
| 截图 | `screenshots/01-empty-chat-1440x900.png`(空态)、`02-input-filled.png`(输入有内容)、`03-work-tab.png`(工作页签) | — |
|
||||
| DOM | `dom/page.rendered.html`(402 KB,未登录 + 空会话态) | — |
|
||||
| 主题 | `<html data-theme="light" data-chatapp-style="default" style="--header-height: 56px">` | 〔DOM〕 |
|
||||
|
||||
### 0.2 来源标注约定
|
||||
|
||||
| 标记 | 含义 | 例子 |
|
||||
|---|---|---|
|
||||
| 〔像素〕 | 我在这三张 PNG 上逐像素量出来的 | `x 360..1359` |
|
||||
| 〔DOM〕 | `page.rendered.html` 里的类名 / testid / 行内 style | `data-testid="chat_input"` |
|
||||
| 〔VAR〕 | CSS 变量(`dbx-light-vars.json` 或 `computed-styles.json` 的 `cssVars`) | `--dbx-line-10` |
|
||||
| 〔CSS〕 | 镜像里 58 个 CSS 文件的实际规则 | `.panel-fvxXfj{...}` |
|
||||
| 〔推算〕 | 类名/变量能推出来、但没有像素佐证 | 折叠动画 |
|
||||
| **需实测** | 镜像推算不出来,必须自己在浏览器里量 | 选中会话的 hover |
|
||||
|
||||
### 0.3 一处必须先说清的差异
|
||||
|
||||
仓库现有 `web/assets/app.css` 里写的是 `--content-w: 996px`,输入框「996 × 约 92」。
|
||||
**本镜像实测是 1000 × 100**,依据如下(两条独立证据):
|
||||
|
||||
* 〔像素〕输入框左右边框落在 `x=360` 与 `x=1359`(y=833 的直线段),宽度 = **1000**;
|
||||
上下边框 `y=784` 与 `y=883`,高度 = **100**。
|
||||
* 〔DOM〕`#chat-route-layout` 行内 style:`--content-max-width: 1000px`;
|
||||
输入区行内 style:`--input-guidance-input-container-min-height: 100px`。
|
||||
|
||||
主区宽 1160(1440−280),内容列 1000 居中 ⇒ 左右各留 80。**本文一律用 1000 / 100。**
|
||||
(用 996 视觉上差 4px 看不出来,但高度必须是 100,不是 92。)
|
||||
|
||||
---
|
||||
|
||||
## 1. 整体布局
|
||||
|
||||
### 1.1 骨架(实测坐标,1440×900)
|
||||
|
||||
```
|
||||
┌───────────────────────────────┬────────────────────────────────────────────────────────┐
|
||||
│ 0 279 │ 280 │
|
||||
│ 侧栏 280(含左右各 1px 描边) │ main 1160 × 900 │
|
||||
│ bg #f9f9f9 │ │
|
||||
│ │ ┌── header 56 ───────────────────────────────────────┐ │
|
||||
│ ├ 品牌行 y 11..47 │ │ [◧] 296,15 26×26 [下载豆包工作 1207,10 136×36] │ │
|
||||
│ ├ 新工作任务 y 55..86 │ │ [登录 1351,10 73×36] │ │
|
||||
│ ├ 新对话 y 89..120 │ └───────────────────────────────────────── y=55 处 1px ┘ │
|
||||
│ ├ 项目 y 123..154 │ │
|
||||
│ ├ API 服务 y 157..188 │ 问候语 28/600 盒子 328..373(居中 860) │
|
||||
│ ├ 更多 y 191..222 │ 分段控件 393..446(697..1022) │
|
||||
│ ├ 最近 标题 y 231..262 │ │
|
||||
│ │ │ ── 为你推荐 540..558 ── │
|
||||
│ │ (列表滚动区,空) │ chip 570..611 / 622..663 / 674..715 / 726..767 │
|
||||
│ │ │ │
|
||||
│ └ 分隔线 y=840 │ ┌── 输入框 360..1359 × 784..883(1000×100,圆角 24)─┐ │
|
||||
│ └ 关于豆包 y 848..874 │ └────────────────────────────────────────────────────┘ │
|
||||
│ │ ↘ 底部留白 16(884..900) │
|
||||
└───────────────────────────────┴────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 1.2 DOM 骨架(可以直接照抄结构)
|
||||
|
||||
```
|
||||
body
|
||||
└ #root
|
||||
└ #chat-route-layout ← 行内 style 挂着整套布局变量
|
||||
└ #chat-route-main (行内 --sidebar-width: 280px)
|
||||
├ div.container-hzjmF1[data-presentation=inline] ← 侧栏宽度容器(宽 280 → 折叠时 0)
|
||||
│ └ nav.panel-fvxXfj
|
||||
│ └ div#flow_chat_sidebar ← p-12 / bg-dbx-bg-base-web
|
||||
│ ├ 品牌行
|
||||
│ ├ 导航(新工作任务 / 新对话 / 项目 / API 服务 / 更多)
|
||||
│ ├ 滚动区(最近 + 会话列表)
|
||||
│ └ 底部关于豆包
|
||||
└ main.flex-1.min-w-0 ← 280..1440
|
||||
└ div.flex.flex-col
|
||||
├ header(h 56)
|
||||
└ #flow-chat-guidance-page.-mt-[var(--header-height)] px-24
|
||||
├ div.relative.flex.h-0.flex-grow ← 高 784 的「内容舞台」
|
||||
│ ├ 问候语 + 分段控件(position:absolute; top:308px; left:0; right:0)
|
||||
│ └ #experiment-guidance-suggestions(absolute; inset-x:0; bottom:0; max-h:313px)
|
||||
└ div[data-guidance-input-boundary](h 100)→ 输入框
|
||||
└ div.h-16(底部留白 16)
|
||||
```
|
||||
|
||||
〔DOM〕关键值:
|
||||
* `#flow-chat-guidance-page` = `-mt-[56px] px-24 flex-col items-center`
|
||||
⇒ 主区内容左右各 24px 内边距(1112 可用),再让 1000 的内容列居中。
|
||||
* `main` = `flex-1 min-w-0 flex items-stretch relative`,`background-color: var(--chat-bg-color)`,
|
||||
而 `--chat-bg-color: var(--dbx-bg-base-5)` = **#fff**(〔VAR〕)。
|
||||
|
||||
### 1.3 1440×900 关键矩形总表
|
||||
|
||||
| 区块 | x | y | 宽 | 高 | 依据 |
|
||||
|---|---|---|---|---|---|
|
||||
| 侧栏 | 0 | 0 | 280 | 900 | 〔像素〕bg #f9f9f9 覆盖 1..278,279 是 1px 描边 |
|
||||
| 主区 | 280 | 0 | 1160 | 900 | 〔像素〕x=280 起纯白 |
|
||||
| 顶部工具条 | 280 | 0 | 1160 | 56 | 〔DOM〕`h-[var(--header-height)]`=56;〔像素〕y=55 有 1px 分隔线 |
|
||||
| 工具条下边框 | 280 | 55 | 1160 | 1 | 〔像素〕(237,237,237) = rgba(0,0,0,.071) = `--dbx-line-7` |
|
||||
| 内容列(输入框/推荐同宽) | 360 | — | **1000** | — | 〔像素〕+〔DOM〕`--content-max-width:1000px` |
|
||||
| 空态内容舞台 | 304 | 0 | 1112 | 784 | 〔DOM〕`dom-tree.txt` 第 21 行 |
|
||||
| 编辑列(消息列,非空态) | — | — | 800 | — | 〔VAR〕`--chat-area-max-width: 800px` |
|
||||
| 输入框 | 360 | 784 | 1000 | 100 | 〔像素〕 |
|
||||
| 底部留白 | — | 884 | — | 16 | 〔DOM〕`data-testid="guidance_page_bottom_height"` `h-16` |
|
||||
|
||||
### 1.4 滚动区行为
|
||||
|
||||
| 区域 | 行为 | 依据 |
|
||||
|---|---|---|
|
||||
| 外层 `body/html` | 不滚(`overflow:hidden/overflow:clip`),整页固定 900 高 | 〔CSS〕`body,html{height:100%;margin:0;overflow:hidden;overflow:clip}` |
|
||||
| 侧栏列表 | `flex-1 min-h-0 overflow-x-hidden overflow-y-auto`,顶部先塞 8px 空块(`h-8`),右移 1px 并把滚动条用负 margin 顶到侧栏右缘 | 〔DOM〕 |
|
||||
| 侧栏滚动条 | `.flow-scrollbar-stable`:宽 7px、`scrollbar-gutter: stable`、**默认滑块全透明,鼠标悬停整块才显现**;滑块 `#ccc`,悬停 `#999`,圆角 `6px 8px 8px`,无轨道底 | 〔CSS〕〔VAR〕`--scrollbar-color:#ccc` / `--scrollbar-hover-color:#999` |
|
||||
| 主区内容 | 空态不滚(`h-0` + `overflow-hidden`);有消息时消息列 `--chat-area-max-width:800px` 自己滚 | 〔DOM〕 |
|
||||
| 推荐区 | `absolute inset-x-0 bottom-0` + `max-height:313px` + `overflow-y-auto overscroll-contain`(推荐超过 313px 自己滚,且滚到底不带动外层) | 〔DOM〕 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 侧栏(280px)
|
||||
|
||||
### 2.1 容器
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 宽 | 280(`--sidebar-width: 280px`) | 〔VAR〕〔像素〕 |
|
||||
| 背景 | `#f9f9f9` = `--dbx-bg-base-web` | 〔VAR〕 |
|
||||
| 内边距 | `10px 12px 12px`(上 10 / 左右 12 / 下 12);类 `p-12` + `pt-[10px]` | 〔DOM〕`style="--g-sidebar-wrapper-padding-top:10px"` |
|
||||
| 描边 | `border-right: 0.5px solid rgba(0,0,0,.064)`(类 `border-r border-[0.5px] border-s-color-border-tertiary/80`)。dpr=1 渲染成 1 物理像素 **#e9e9e9**;视口左/上/下边缘也有同色 1px | 〔DOM〕〔像素〕x=0/279/ y=0/899 都是 (233,233,233) |
|
||||
| 圆角 | 0 | 〔像素〕四角是直角 |
|
||||
| 折叠机制 | 外层 `.container-hzjmF1{width:0}` ↔ `[data-presentation=inline]{width:280px}`,`[data-dock-transition]{transition:width .2s}`;面板 `.panel-fvxXfj{transition:transform .2s, opacity .2s}`,收起态 `translateX(-110%) + opacity:0` | 〔CSS〕 |
|
||||
|
||||
> 侧栏右缘还有一个 **6px 宽的拖拽条**:`div[data-testid=chat_route_layout_left_sash] class="absolute top-0 -right-3 z-50 h-full w-6 cursor-col-resize"`〔DOM〕,
|
||||
> 想支持拖拽改宽就照这个放。
|
||||
|
||||
### 2.2 品牌区「豆包」
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 行盒 | `x 13..266`,`y 11..47`(高 36) | 〔像素〕〔DOM〕`div.mb-8.flex.items-center.justify-between.pr-4` rect `[13,11,254,36]` |
|
||||
| 「豆包」按钮 | `h-36 px-10 rounded-10`,`cursor-default` | 〔DOM〕`data-testid="workspace-switch-chip"` |
|
||||
| 文字 | **18px / 26px / 500**,颜色 `#000` | 〔DOM〕`text-18 leading-26 font-medium` |
|
||||
| 文字墨迹 | `x 23..58`(宽 36),`y 20..35` | 〔像素〕(23 = 13 + 10px 内边距) |
|
||||
| 右侧前进/后退 | 两个 `26×26`(图标 `18px`),间距 8,整块 60×36 靠右;本态都是 **disabled(opacity .3)** | 〔DOM〕〔像素〕箭头墨迹 `209..222` / `243..256`,y `28..29` |
|
||||
|
||||
### 2.3 导航项(5 个,逐项实测矩形)
|
||||
|
||||
行样式〔DOM〕:`group/sidebar_nav_item flex items-center px-8 rounded-dbx-lg h-32 !text-dbx-text-primary hover:bg-dbx-fill-trans-10-hover mb-2`
|
||||
|
||||
⇒ **行高 32、左右内边距 8、圆角 10(`--dbx-radius-lg` = .625rem)、行间距 2(mb-2)、hover 底色 `#0000000a`、文字与图标都是 `#000`**。
|
||||
|
||||
| 项 | 行盒(x 13..266) | 图标盒 | 图标墨迹 | 文字起点 | 文字 | 右侧附加 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 新工作任务 | y 55..86 | 21..43(18px 图标 + 2px 内边距) | 24..39 × 63..78 | x 51 | 14px/22px **500** `#000`,宽 70 | hover 才显示的 `Ctrl J` |
|
||||
| 新对话 | y 89..120 | 同上 | 24..39 × 97..112 | x 51 | 14px/22px 500,宽 42 | `Ctrl Shift K` |
|
||||
| 项目 | y 123..154 | 同上 | 24..39 × 132..145 | x 51 | 14px/22px 500,宽 26 | — |
|
||||
| API 服务 | y 157..188 | 同上 | 24..38 × 165..180 | x 51 | 14px/22px 500,宽 55 | 外链箭头 ↗ `12px`,墨迹 247..254 |
|
||||
| 更多 | y 191..222 | 同上 | 24..39 × 199..214 | x 51 | 14px/22px 500,宽 27 | chevron `>` `20px`(p-3),墨迹 246..252 |
|
||||
|
||||
* 图标:`<svg class="size-18 block !box-content p-2">` ⇒ 18×18 图标 + 2px 上下左右内边距 = 22×22 盒〔DOM〕。
|
||||
* 文字:`<div class="truncate ml-[8px] flex-1 min-w-0 s-font-small">`(`--s-font-small` = 400 14px/22px)+ 内层 `<span class="font-medium">` ⇒ **14/22/500**〔DOM〕〔VAR〕。
|
||||
51 = 21(行内边距 8)+ 22(图标盒)+ 8(ml-8)✓。
|
||||
* 快捷键小字〔DOM〕:`class="text-dbx-text-tertiary opacity-0 group-hover/sidebar_nav_item:opacity-100 ml-auto text-12"`
|
||||
⇒ **12px**、颜色 `rgba(0,0,0,.349)`、**默认 opacity 0,只有 hover 整行才出现**(截图里确实看不到)。
|
||||
* 右端附加图标颜色:↗ 用 `text-dbx-text-tertiary`(12px);`>` 用 `text-s-color-text-quaternary`(= rgba(0,0,0,.3))〔DOM〕。
|
||||
* **选中态**:这一层是「动作入口」不是「选中项」,所以没有选中态。会话列表项才有:
|
||||
`.item-AHZ7rH{height:32px;border-radius:18px;padding:0 10px}` + `:hover,[data-active=true]{background:rgba(0,0,0,.04)}`〔CSS〕
|
||||
⇒ 我们要的「当前会话」选中态就照这个:**32 高、圆角 18、左右 10、底 rgba(0,0,0,.04)**。
|
||||
|
||||
### 2.4 分区标题「最近」
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<section data-testid="conversation-section" class="rounded-dbx-lg transition-colors">
|
||||
<div class="group/section-header flex h-32 items-center rounded-dbx-lg px-10
|
||||
hover:bg-dbx-fill-trans-10-hover cursor-pointer" role="button">
|
||||
<span class="truncate text-12 leading-18 font-medium text-dbx-text-tertiary">最近</span>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 行盒 | `x 13..266`,`y 231..262`(高 32;上方有 8px 空块,223+8=231) | 〔DOM〕`h-8` + `h-32`〔像素〕文字 241..251 |
|
||||
| 内边距 | 左右 10 | 〔DOM〕`px-10` |
|
||||
| 文字 | **12px / 18px / 500**,`rgba(0,0,0,.349)`(`--dbx-text-tertiary`),墨迹 `x 23..46`、`y 241..251` | 〔DOM〕〔像素〕实测 (163,163,163) 叠在 #f9f9f9 上 = α .349 ✓ |
|
||||
| hover | 整行底 `#0000000a`;右侧「…」按钮默认 `opacity-0`,hover 才出现 | 〔DOM〕 |
|
||||
| 列表项 | 本镜像未登录 ⇒ 空(只有 `div.flex.flex-col.gap-0` 空容器) | 〔DOM〕 |
|
||||
|
||||
### 2.5 底部「关于豆包」
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<div class="shrink-0">
|
||||
<div class="mx-8 border-0 border-t-1 border-solid border-s-color-border-tertiary p-4 pb-0">
|
||||
<div class="flex items-center justify-between py-4">
|
||||
<div data-testid="not_login_about_us" class="button-JoHDM4"> <!-- flex;radius:12;padding:6px 8px -->
|
||||
<svg class="text-s-color-text-tertiary size-16 p-2">ⓘ</svg>
|
||||
<span class="button-text-Y5DJOk">关于豆包</span> <!-- --s-font-small + ml-4 -->
|
||||
</div>
|
||||
<span class="inline-flex p-7 text-tertiary"><svg class="size-18">⤓</svg></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 分隔线 | `y=840`,`x 21..258`,1px `rgba(0,0,0,.08)` | 〔像素〕〔DOM〕`border-t-1 border-s-color-border-tertiary` + `mx-8` |
|
||||
| 行 | `y ≈845..886`(`p-4` + `py-4`,按钮高 34),文字/图标中线 **865** | 〔DOM〕〔像素〕 |
|
||||
| ⓘ 图标 | 16px + 2px 内边距(盒 20),墨迹 `x 35..45`、`y 860..871` | 〔像素〕 |
|
||||
| 文字 | **14px / 22px / 400**,`rgba(0,0,0,.5)`(`--s-color-text-tertiary`),墨迹 `x 52..107`、`y 860..871`,左边距 4 | 〔像素〕实测 (124,124,124) = α .5 叠 #f9f9f9 ✓ |
|
||||
| 下载按钮 | `18px` 图标 + 7px 内边距 = 32×32,文字色 `rgba(0,0,0,.5)`,墨迹 `x 232..245`、`y 858..873` | 〔DOM〕〔像素〕 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 主区顶部工具条(56px)
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<div data-header-center-mode="flow"
|
||||
class="relative z-30 flex-row flex h-header-height w-full flex-none items-center
|
||||
bg-[var(--chat-bg-color)] border-b border-b-[var(--dbx-line-7)] px-16 gap-x-8">
|
||||
<div data-header-frame-region="left" class="... gap-8 pl-g-header-left-padding transition-[padding-left] duration-200">
|
||||
<button data-testid="siderbar_close_btn" aria-label="收起侧栏"
|
||||
class="p-[4px] rounded-dbx-sm text-(--dbx-text-primary) transition-colors duration-150 ease-out
|
||||
hover:bg-dbx-fill-trans-10-hover">◧ 18px</button>
|
||||
</div>
|
||||
<div data-header-frame-region="center" class="flex-1 justify-center"></div>
|
||||
<div data-header-frame-region="right" class="flex items-center justify-end gap-8">
|
||||
[下载豆包工作] [登录]
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
| 元素 | 矩形 | 样式 | 依据 |
|
||||
|---|---|---|---|
|
||||
| 工具条 | `280,0 1160×56`,bg `#fff`,`padding 0 16`,子项间距 8 | — | 〔DOM〕〔像素〕 |
|
||||
| 下边框 | `y=55`,1px `#ededed`(`--dbx-line-7` = `#00000012`) | — | 〔像素〕〔VAR〕 |
|
||||
| 折叠按钮 | `296,15 26×26`(图标 18×18,按钮内边距 4,圆角 6) | 图标 `#000`;hover 底 `#0000000a`;`transition-colors 150ms ease-out` | 〔像素〕图标墨迹 `301..316 × 20..34`〔DOM〕 |
|
||||
| 右区容器 | `1207,10 217×36` | `display:flex; gap:8; justify-end` | 〔DOM〕`dom-tree.txt` |
|
||||
| 「下载豆包工作」 | `1207,10 136×36` | 圆角 **12**、边框 **1px #06f**、文字 **#06f**、`20×20` 图标 + 文字、hover 底 `#0000000a`。文字按类名 `text-s-font-base-strong`(500/16),实测墨迹仅 75px/6 字 ⇒ 视觉 13–14px | 〔像素〕〔DOM〕〔CSS〕`.enhanceBtn-W9xBoi` |
|
||||
| 「登录」 | `1351,10 73×36` | 圆角 **12**、底 **#232629**、字 **#fff** 14/22/500、内边距 `10px 12px` | 〔像素〕〔DOM〕`login-btn-header-CTKsn1` |
|
||||
| 右区在「工作」页签 | 「下载豆包工作」**消失**,只剩登录按钮 | — | 〔像素〕03 图 |
|
||||
|
||||
> 我们没有「登录」和「下载电脑版」这两件事,右区留给**我们自己的东西**(见 §12)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 主区空态
|
||||
|
||||
### 4.1 垂直节奏(实测)
|
||||
|
||||
| 元素 | 盒子 | 说明 |
|
||||
|---|---|---|
|
||||
| 空态舞台 | `y 0..784`(高 784) | 绝对定位的父容器 |
|
||||
| 问候语块 | `position:absolute; top:308px; left:0; right:0` | 〔DOM〕行内 style |
|
||||
| ↳ 问候语 | `y 328..373`(`min-height:45px` = `--greeting-height`),`margin-top:20` | 308+20 |
|
||||
| ↳ 分段控件 | `y 393..446`,高 54,`margin-top:20` | 373+20 |
|
||||
| 推荐区 | 底对齐 `y=784`,`max-height:313px`,`pb-16` | 内容底 768 |
|
||||
| ↳ 「为你推荐」 | 行盒 `540..558`(高 18),`mb-12` | 558+12=570 |
|
||||
| ↳ chip 1..4 | `570..611` / `622..663` / `674..715` / `726..767`(各 42 高,间距 10) | 767+16=783 ≈ 784 ✓ |
|
||||
| 输入框 | `y 784..884`(100 高) | 紧贴舞台底 |
|
||||
|
||||
> **怎么复现 308**:1440×900 下问候语块顶恰在 308。实现建议 `top:34vh`(900×0.342=308),
|
||||
> 或者「在 `[56, 784]` 里垂直居中后再上移 52px」。别用死值,窗口一改就歪。
|
||||
|
||||
### 4.2 问候语
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 文案 | 「有什么我能帮你的吗?」 | 〔像素〕 |
|
||||
| 字号/字重/行高 | **28px / 600 / 42px** | 〔DOM〕`text-28 font-semibold` +〔metrics〕lh 42px |
|
||||
| 盒 | `x 714..1005`(宽 292 = 280 文本 + `pl-12`),`y 328..373` | 〔像素〕〔DOM〕`mx-auto ... pl-12 min-h-[45px]` |
|
||||
| 居中锚点 | 文本中心 = **860**(= 280 + 1160/2) | 〔像素〕墨迹 727..990 |
|
||||
| 颜色 | `#000`(`--dbx-text-primary`) | 〔像素〕 |
|
||||
| 其他 | `cursor-default`;`mb-28 !mb-0`、`mt-20`;隐藏滑入遮罩 `greeting-text-Q0pGud:before/after`(切换文案时 0.2s linear 擦除) | 〔DOM〕〔CSS〕 |
|
||||
|
||||
### 4.3 「对话 | 工作」分段控件
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<div data-testid="conversation-mode-switch"
|
||||
class="relative flex h-54 items-center justify-center rounded-full p-[3px]
|
||||
bg-dbx-fill-trans-20 mt-20">
|
||||
<div aria-hidden="true" class="absolute left-[3px] top-[3px] h-[48px] rounded-full
|
||||
shadow-dbx-sm transition-transform duration-[150ms] ease-in-out
|
||||
bg-dbx-bg-body-overlay-web" style="width:160px; transform:translateX(0px)"></div>
|
||||
<button data-active="true" class="relative flex h-full items-center justify-center w-160 gap-6
|
||||
text-16 leading-18 transition-colors font-medium text-dbx-text-primary">对话</button>
|
||||
<button class="... w-160 gap-6 text-16 leading-18 transition-colors
|
||||
text-dbx-text-secondary hover:text-dbx-text-primary">工作</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 轨道 | `x 697..1022`(**326** 宽 = 3+160+160+3),`y 393..446`(**54** 高),圆角 **27(全圆)** | 〔像素〕〔DOM〕 |
|
||||
| 轨道底色 | **#f5f5f5**(= `--dbx-fill-trans-20` `#0000000a` 叠白) | 〔像素〕(245,245,245)〔VAR〕 |
|
||||
| 滑块 | **160 × 48**,`left:3 / top:3`,圆角 **24**,底色 **#fff**,阴影 `--dbx-drop-shadow-sm` = `0 2px 4px #00000005, 0 4px 10px #00000005` | 〔像素〕滑块 701..860 / 396..443〔DOM〕 |
|
||||
| 滑块动效 | `transition-transform 150ms ease-in-out`,切页签 `translateX(0 | 160px)` | 〔DOM〕 |
|
||||
| 段按钮 | 各 `160` 宽、`h-full`、`gap-6` | 〔DOM〕 |
|
||||
| 文字 | **16px / 18px**;选中 `500` + `#000`;未选中 `400` + `#00000080`(叠在 #f5f5f5 上 = **#7a7a7a**),hover 变 `#000` | 〔DOM〕〔像素〕实测 (122,122,122) ✓ |
|
||||
| 文字位置 | 「对话」墨迹 766..791(中心 778.5);「工作」墨迹 931..950(中心 940) | 〔像素〕 |
|
||||
|
||||
> ⚠️ 抓取异常:`03-work-tab.png` 虽然内容上已是「工作」页(推荐区消失、「下载豆包工作」消失),
|
||||
> 但滑块仍停在「对话」(实测两张图的滑块都在 701..860)。**实现时以 `data-active` 为准移动 160px。**
|
||||
|
||||
### 4.4 「为你推荐」
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<section class="mx-auto w-full max-w-(--content-max-width) pb-16">
|
||||
<h2 class="mb-12 w-full pl-4 text-12 leading-18 text-dbx-text-tertiary">为你推荐</h2>
|
||||
<div class="flex flex-col items-start w-full gap-10">
|
||||
<button class="flex max-w-full items-center gap-4 px-12 py-8 text-14 leading-22
|
||||
text-dbx-text-primary min-h-42 rounded-[var(--dbx-radius-xl,12px)] border
|
||||
border-dbx-line-7 bg-transparent transition-colors duration-150
|
||||
hover:bg-dbx-fill-trans-10-hover w-fit">
|
||||
<span class="line-clamp-2 min-w-0 flex-1 overflow-hidden leading-22 break-words">…</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 区域宽 | 1000(与输入框同宽同左边界 **x=360**) | 〔像素〕〔DOM〕`max-w-(--content-max-width)` |
|
||||
| 标题 | **12px / 18px / 400**,`rgba(0,0,0,.349)`,`padding-left:4`(墨迹从 364 起),下间距 **12** | 〔像素〕〔DOM〕 |
|
||||
| 标题对齐 | **左对齐**(不是居中) | 〔像素〕 |
|
||||
| chip 盒 | 高 **42**(`min-h-42`),圆角 **12**,边框 **1px #00000012**(渲染成 #ededed),内边距 `12px / 8px`,`gap-4` | 〔像素〕〔DOM〕 |
|
||||
| chip 文字 | **14px / 22px / 400**,`#000`,最多 2 行(`line-clamp-2`) | 〔DOM〕 |
|
||||
| chip 宽 | `w-fit` = 14×字数 + 24 + 2;实测:24 字 → 334,11 字 → 180,14 字 → 222 | 〔像素〕 |
|
||||
| chip 间距 | **10**(`gap-10`,垂直方向同一个 flex-col 的 gap) | 〔像素〕612..621 = 10 |
|
||||
| hover | 底色 `#0000000a`,`transition-colors 150ms` | 〔DOM〕 |
|
||||
| 出现/消失 | `.sug-input-visibility-motion{transition:opacity .1s ease-out,visibility 0s linear}` | 〔CSS〕 |
|
||||
| 「工作」页签 | 整块推荐区消失 | 〔像素〕03 图 |
|
||||
|
||||
> 文案别抄(镜像里是新闻/汇率类的示例问法),我们换成自己能力能回答的示例。
|
||||
|
||||
---
|
||||
|
||||
## 5. 输入框组件(最复杂的部分)
|
||||
|
||||
### 5.1 结构树(照这个搭就不会错)
|
||||
|
||||
```
|
||||
div[data-guidance-input-boundary] ← 固定 h:100,贴底
|
||||
└ div.absolute.inset-x-0.bottom-0.flex.flex-col.items-center
|
||||
└ div.relative.isolate.flex.flex-col-reverse.w-full
|
||||
max-w-(--content-max-width) ← 1000 宽
|
||||
├ #input-engine-container.rounded-dbx-4xl ← 圆角 24 + 1px 描边 + 阴影都在这一层
|
||||
│ ├ .guidance-input-surface(border/背景继承)
|
||||
│ └ .guidance-input-content.flex.flex-col-reverse.gap-14.p-10
|
||||
│ ├ .guidance-input-actions.flex.justify-between.gap-6.h-36 ← DOM 里在前 = 视觉在下
|
||||
│ │ ├ 左组(flex-1 min-w-0 overflow-hidden):
|
||||
│ │ │ [+ 36×36] [1×16 竖线] [对话 › h32] | [PPT 生成][图像生成]…[更多]
|
||||
│ │ └ 右组:
|
||||
│ │ [豆包 快速 › h32] [麦克风 36×36 / 发送 36×36]
|
||||
│ └ .guidance-input-editor-wrapper(px-10 pt-6) ← DOM 里在后 = 视觉在上
|
||||
│ └ [contenteditable] 16px/24 的富文本(空时显示 placeholder)
|
||||
└ div[data-testid=guidance_page_bottom_height].h-16 ← 下方留白 16
|
||||
```
|
||||
|
||||
> 注意:内容层用的是 **`flex-direction:column-reverse`**,所以 DOM 顺序是「按钮排在前、编辑区在后」,
|
||||
> 视觉上却是编辑区在上。**若我们用自己的普通 `flex-col`,就按视觉顺序(编辑区先、按钮排后)写即可**,
|
||||
> 别照抄 `column-reverse` 再把顺序写反。
|
||||
|
||||
### 5.2 外层容器(实测)
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 尺寸 | **1000 × 100**,`x 360..1359`,`y 784..883` | 〔像素〕〔DOM〕`min-height:100px` |
|
||||
| 圆角 | **24**(`rounded-dbx-4xl` = `--dbx-radius-4xl` = 1.5rem) | 〔DOM〕〔VAR〕 |
|
||||
| 底色 | `#fff`(`--s-color-bg-float`) | 〔VAR〕 |
|
||||
| 边框 | **1px `#0000001a`**,用伪元素铺:`after:absolute after:inset-0 after:border-1 after:border-dbx-line-10`(实测渲染 (229,229,229)) | 〔DOM〕〔像素〕 |
|
||||
| 阴影 | `--dbx-drop-shadow-lg` = `0 2px 4px #00000005, 0 4px 16px #0000000a, 0 8px 32px #00000014`(实测阴影从 x≈340 起、向下渗到 900 之外) | 〔DOM〕〔像素〕 |
|
||||
| 内边距 | 内容层 `p-10`(10px),编辑区再 `px-10 pt-6` | 〔DOM〕 |
|
||||
| 内容间距 | `flex-col-reverse` + `gap-14` ⇒ 编辑区在上、按钮排在下,中间 14 | 〔DOM〕 |
|
||||
|
||||
**聚焦态(02 图实测,重点)**
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 边框 | `rgba(0,102,255,.30)` → 叠白实测 **(178,209,255)**;类 `focus-within:after:border-dbx-fill-highlight-disable`(`--dbx-fill-highlight-disable` = `#0066ff4d`) |
|
||||
| 阴影 | 换成蓝色光晕:`--active-shadow: 0 2px 4px rgba(116,158,243,.02), 0 4px 12px rgba(102,188,253,.04), 0 8px 24px rgba(95,178,255,.17)`(实测阴影偏蓝 (228,243,255)→…) |
|
||||
| 注意 | **没有 3px ring,也没有加粗边框**——只是细边框变蓝 + 蓝光晕。我们现在 `.composer.focus` 用的是 `0 0 0 3px` ring,要改 |
|
||||
|
||||
**内部垂直分割(实测)**:容器 784..884 → 内框 785..883 → 内容 795..873(`p-10`)→ 按钮排 **837..872(36 高)** → 编辑区约 **801..825**(16px/24px 行盒)。
|
||||
|
||||
### 5.3 编辑区 / placeholder
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 文本 | **16px / 24px**,颜色 **`#000`**(实测;token 层 `--input-guidance-input-editor-color` 给的是 `rgba(0,0,0,.85)`,实测墨迹为纯黑,按 `#000` 写) | 〔VAR〕〔像素〕02 图文字 (0,0,0) |
|
||||
| placeholder | 「发消息...」,token 是 `rgba(0,0,0,.3)`(`--s-color-text-quaternary`);实测两张图墨迹 **#a6a6a6 / #b7b7b7**(抗锯齿差异),建议取 `rgba(0,0,0,.32)` | 〔VAR〕〔像素〕 |
|
||||
| 光标色 | `#0057ff`(`--input-guidance-input-caret-color` = `--s-color-accents-blue`) | 〔VAR〕 |
|
||||
| 高度 | 文本行盒最小 24(`min-height:24px`);**整个输入框最大 360px**,超出后编辑区内部滚动 | 〔VAR〕 |
|
||||
| 文本左边界 | `x 381`(360 + 1 边框 + 10 内容 + 10 编辑内边距),墨迹 380 起 | 〔像素〕〔DOM〕`px-10` |
|
||||
| 占位符基线 | 墨迹 `y 806..826` | 〔像素〕 |
|
||||
|
||||
### 5.4 底排按钮(从左到右,全部实测)
|
||||
|
||||
底排:`x 371..1348`(= 360+1+10 到 1359−1−10),`y 837..872`,**高 36**,`justify-between`,组间距 6。
|
||||
|
||||
| # | 元素 | 盒子(实测) | 样式 | 依据 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | + 上传 | 36×36 圆形,`x 371..406`;图标 18px,墨迹 `381..394` | 透明底、`rounded-full`、`p-9`;hover 底 `#0000000a`;图标 `#000` | 〔像素〕〔DOM〕`upload_file_button` |
|
||||
| 2 | 竖分隔线 | `x=414`,`1 × 16`(实测 (229,229,229)) | `mx-8 h-16 w-1 bg-dbx-line-10` | 〔像素〕〔DOM〕 |
|
||||
| 3 | 模式按钮「对话 ›」 | `h 32`,圆角 **12**,`padding-left:8 / right:4`;16px 图标 + 文字 + 12px 箭头 | 文字 **14/22 #000**,箭头 12px `>` `rgba(0,0,0,.2)`(`--dbx-text-disable`),hover 底 `#0000000a` | 〔像素〕〔DOM〕`chat_input_action_mode` |
|
||||
| 4 | 技能按钮 ×7 | 每个 `h 32`、圆角 **12**、`px-8`、`gap-4`;**16×16 PNG 图标** + 文字 | 文字 **14/22 #000**;hover 底 `#0000000a`;相邻按钮间距 4(外层 `gap-4`) | 〔像素〕〔DOM〕`skill_bar_button_*` |
|
||||
| — | 按钮清单与实测墨迹 x | PPT 生成 `512..587`;图像生成 `609..683`;帮我写作 `705..779`;视频生成 `801..875`;录音转写 `896..971`;音乐生成 `993..1067`;更多 `1089..1135` | 节距约 **96**(= 8+16+4+56+8+4) | 〔像素〕 |
|
||||
| 5 | 「豆包 快速 ›」 | `h 32`、圆角 12、`py-7 pl-8 pr-4`;文字墨迹 `x 1232..1291`,箭头 12px `x≈1296..1308` | 文字 **14/22 #000**,箭头 `rgba(0,0,0,.2)` | 〔像素〕〔DOM〕`chat_input_action_model` |
|
||||
| 6 | 麦克风(空态) | **36×36 正圆**,`x 1313..1349`,`y 838..873`;图标 18px(墨迹 14px 宽) | 底色 **#f5f5f5**(`--dbx-fill-trans-20` = `#0000000a` 叠白,**不是紫色**),图标 **#000**;hover `--dbx-fill-trans-20-hover`(`#00000012`) | 〔像素〕(245,245,245)〔DOM〕`asr_btn` |
|
||||
| 6' | 发送(有内容) | **36×36 正圆**,同位置 `x 1313..1349`,`y 838..873` | 底色 **#0066ff**(实测纯 (0,102,255)),白色向上箭头 18px;**麦克风被它替换** | 〔像素〕02 图 |
|
||||
|
||||
> **紫色麦克风是个误会**:仓库现有 `web/assets/app.css` 的 `.mic-btn` 用了 `--violet-weak`/`--violet`,
|
||||
> 但本镜像实测是 `#f5f5f5` 底 + 黑色麦克风(`bg-dbx-fill-trans-20`)。
|
||||
> 想要「豆包那种淡淡的按钮」,就用 `rgba(0,0,0,.04)`;紫色只在豆包的彩色强调(如 AI 光效)里出现。
|
||||
|
||||
### 5.5 三种状态对照
|
||||
|
||||
| 状态 | 边框 | 阴影 | 右下按钮 | 推荐区 |
|
||||
|---|---|---|---|---|
|
||||
| 空 / 未聚焦(01) | 1px `#0000001a` | 灰 `drop-shadow-lg` | 麦克风(#f5f5f5) | 显示 |
|
||||
| 聚焦 / 有内容(02) | 1px `rgba(0,102,255,.3)` | 蓝光晕 `--active-shadow` | **发送**(#06f 圆) | 消失 |
|
||||
| 工作页签(03) | 同 01 | 同 01 | 麦克风 | 消失 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 设计 token 表
|
||||
|
||||
### 6.1 颜色:豆包变量 → 我们的变量(亮 / 暗)
|
||||
|
||||
暗色值来自 `computed-styles.json → cssVars` 里的 `亮 | 暗` 对(这是豆包自己的暗色主题值,可信)。
|
||||
|
||||
| 豆包变量 | 建议我们的变量 | 亮色 | 暗色 | 用途 |
|
||||
|---|---|---|---|---|
|
||||
| `--dbx-text-primary` | `--text-primary` | `#000` | `#ffffffd9` | 正文、导航文字、按钮文字 |
|
||||
| `--dbx-text-secondary` | `--text-secondary` | `#00000080` | `#ffffff80` | 次要文字、未选中页签 |
|
||||
| `--dbx-text-tertiary` | `--text-tertiary` | `#00000059` | `#ffffff59` | 「最近」「为你推荐」、快捷键 |
|
||||
| `--dbx-text-disable` | `--text-disable` | `#0003` | `#fff3` | 禁用、下拉小箭头 |
|
||||
| `--dbx-text-markdown` | `--text-markdown` | `#000000f2` | `#ffffffd9` | 消息正文 |
|
||||
| `--dbx-bg-body-web` | `--bg-body` | `#fff` | `#000` | 主区底色 |
|
||||
| `--dbx-bg-base-web` | `--bg-sidebar` | `#f9f9f9` | `#0f0f0f` | 侧栏底色 |
|
||||
| `--dbx-bg-base-2` | `--bg-base-2` | `#f4f4f4` | `#1a1a1a` | 次级底(气泡、卡片) |
|
||||
| `--dbx-bg-float` | `--bg-float` | `#fff` | `#181818` | 浮层、输入框底 |
|
||||
| `--dbx-bg-base-5` | `--bg-base-5` | `#fff` | `#000` | `--chat-bg-color` |
|
||||
| `--dbx-fill-trans-10` | `--fill-1` | `#00000005` | `#ffffff0a` | 极淡填充 |
|
||||
| `--dbx-fill-trans-10-hover` | `--bg-hover` | `#0000000a` | `#ffffff14` | **所有 hover 底** |
|
||||
| `--dbx-fill-trans-20` | `--fill-2` | `#0000000a` | `#ffffff1a` | 分段控件轨道、麦克风底 |
|
||||
| `--dbx-fill-trans-20-hover` | `--bg-active` | `#00000012` | `#ffffff1f` | 麦克风 hover |
|
||||
| `--dbx-fill-trans-30` | `--fill-3` | `#0000000f` | `#ffffff1a` | 较重填充 |
|
||||
| `--dbx-line-7` | `--line-1` | `#00000012` | `#ffffff1a` | 顶栏下边框、chip 边框 |
|
||||
| `--dbx-line-10` | `--line-2` | `#0000001a` | `#ffffff1a` | **输入框边框**、竖分隔线 |
|
||||
| `--dbx-line-15` | `--line-3` | `#00000026` | `#ffffff26` | 强调描边 |
|
||||
| `--dbx-fill-primary-50` / `--dbx-brand-default` | `--brand` | **#06f** | `#0a84ff` | 发送按钮、主按钮 |
|
||||
| `--dbx-fill-highlight-hover` | `--brand-hover` | `#4d8eff` | `#006ce0` | 主按钮 hover |
|
||||
| `--dbx-fill-highlight-disable` | `--brand-ring` | `#0066ff4d` | `#378dff66` | **聚焦边框(30%)** |
|
||||
| `--dbx-color-blue-100` | `--brand-weak` | `#ebf2ff` | `#002658` | 选中底色 |
|
||||
| `--s-color-accents-blue` | `--caret` | `#0057ff` | `#547cff` | 输入光标、semi 系主色 |
|
||||
| `--dbx-fill-chat-bubble-bg` | `--bubble-user` | `#f4f4f4` | `#181818` | 用户气泡 |
|
||||
| `--dbx-fill-chat-bubble-bg2` | `--bubble-alt` | `#e6f0ff` | `#153453` | 蓝调气泡 |
|
||||
| `--dbx-function-danger` | `--danger` | `#ff3b30` | `#ff3b30` | 错误/删除 |
|
||||
| `--dbx-function-danger-hover` | `--danger-hover` | `#f96961` | `#f96961` | — |
|
||||
| `--dbx-function-success` | `--success` | `#34c759` | `#34c759` | 成功 |
|
||||
| `--dbx-function-warning` | `--warning` | `#ff9500` | `#ff9500` | 警告 |
|
||||
| `--dbx-function-info` | `--info` | `#0065fd` | `#378dff` | 信息 |
|
||||
| `--dbx-bg-mask` | `--bg-mask` | `#0003` | `#0009` | 遮罩 |
|
||||
| `--dbx-neutral-700` | `--neutral-700` | `#4c4c4c` | `#b2b2b2` | 中性文字 |
|
||||
| `--s-color-border-secondary` | `--border-input` | `rgba(0,0,0,.12)` | `rgba(255,255,255,.16)` | 输入框常态边框(token 层) |
|
||||
| `--s-color-border-tertiary` | `--border-soft` | `rgba(0,0,0,.08)` | `rgba(255,255,255,.12)` | 侧栏描边、分隔线 |
|
||||
|
||||
补充色阶(需要时直接取):
|
||||
* 灰阶 `--dbx-neutral-00..1000`:`#fff / #efefef / #e3e3e3 / #cacaca / #b0b0b0 / #979797 / #7e7e7e / #656565 / #4c4c4c / #323232 / #191919 / #000`(暗色为反向)。
|
||||
* 蓝 `--dbx-color-blue-100..800`:`#ebf2ff #dce8ff #b8d2ff #84b1ff #4d8eff #0065fd #004cc3 #00348c #002d7c`。
|
||||
* 紫(豆包只用于装饰/AI 光效)`--dbx-color-purple-500 #af56de`、`--s-color-accents-purple #9952e1`(暗 `#9246e0`)。
|
||||
* AI 渐变(要「豆包味」的强调面才用):`--s-color-ai-button: radial-gradient(105.79% 117.52% at 9.98% 22.03%, #0057ff 0%, #4298fd 50%)`。
|
||||
|
||||
### 6.2 字号阶梯(`--s-font-*`,直接搬)
|
||||
|
||||
| Token | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `h1` | 600 26/36 | 大标题 |
|
||||
| `h2` | 700 20/32 | 卡片主标题 |
|
||||
| `h3` / `h4` | 600 16/24 | 区块标题 |
|
||||
| `large` / `large-em` | 400·500 20/28 | 强调正文 |
|
||||
| `base` / `base-strong` / `base-em` | 400·500·600 16/24 | 正文、编辑器 |
|
||||
| `small` / `small-strong` / `small-em` | 400·500·600 14/22 | **导航项、chip、按钮文字** |
|
||||
| `pcbody` | 400 13/20 | 桌面端紧凑正文 |
|
||||
| `xs` | 400 12/18 | **分组标题「最近」「为你推荐」、快捷键** |
|
||||
| `xxs` | 400·500 11/16 | 角标 |
|
||||
| `xxxs-em` / `xxxxs` | 600 10/14、400 9/12 | 极限小字 |
|
||||
| 特例 | **28/42 600** | 空态问候语(`text-28`,不在阶梯里) |
|
||||
| 特例 | 16/18 | 分段控件文字 |
|
||||
|
||||
### 6.3 圆角阶梯
|
||||
|
||||
| Token | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `--dbx-radius-xs` / `--s-radius-xxs` | 4px | 小标签 |
|
||||
| `--dbx-radius-sm` | 6px | 顶栏图标按钮(`rounded-dbx-sm`) |
|
||||
| `--dbx-radius-md` / `--s-radius-xxss` | 8px | 菜单项 |
|
||||
| `--dbx-radius-lg` / `--s-radius-xs` | **10px** | **侧栏导航行、分区标题** |
|
||||
| `--dbx-radius-xl` / `--s-radius-s` | **12px** | **chip、输入条按钮、登录/下载按钮** |
|
||||
| `--dbx-radius-2xl` / `--s-radius-m` | 16px | 卡片、下拉面板 |
|
||||
| `--dbx-radius-3xl` / `--s-radius-l` | 20px | 大卡片 |
|
||||
| `--dbx-radius-4xl` / `--s-radius-xl` | **24px** | **输入框** |
|
||||
| `--s-radius-xxl` / `xxxl` | 32 / 36 | 大浮层 |
|
||||
| `rounded-full` | 9999px | 分段控件、麦克风、发送、+ |
|
||||
|
||||
### 6.4 阴影阶梯
|
||||
|
||||
| Token | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `--dbx-drop-shadow-xs` | `0 0 4px #00000014` | 轻浮起 |
|
||||
| `--dbx-drop-shadow-sm` | `0 2px 4px #00000005, 0 4px 10px #00000005` | **分段控件滑块**、下拉面板 |
|
||||
| `--dbx-drop-shadow-md` | `0 2px 4px #00000005, 0 4px 10px #00000008, 0 4px 16px #00000008` | 浮层 |
|
||||
| `--dbx-drop-shadow-lg` | `0 2px 4px #00000005, 0 4px 16px #0000000a, 0 8px 32px #00000014` | **输入框** |
|
||||
| `--s-shadow-lv1` | `0 1px 2px rgba(0,0,0,.05), 0 0 1px rgba(0,0,0,.15)` | 卡片 |
|
||||
| `--s-shadow-lv2` | `0 6px 10px rgba(0,0,0,.08), 0 0 1px rgba(0,0,0,.15)` | 拖拽态 |
|
||||
| `--s-shadow-lv3` | `0 10px 20px rgba(0,0,0,.1), 0 0 1px rgba(0,0,0,.15)` | 弹层 |
|
||||
| `--s-shadow-lv4` / `lv5` | `0 25px 80px rgba(0,0,0,.1)` / `0 30px 100px rgba(0,0,0,.15)` | 大浮层/引导 |
|
||||
| `--s-shadow-level1..5` | `0 0 4px rgba(0,0,0,.02), 0 {6,10,24,36,20}px {10,24,40,50,64}px rgba(47,53,64,{.1,.2,.16,.16,.36})` | 卡片/弹层另一套(带冷灰) |
|
||||
| 聚焦光晕 | `0 2px 4px rgba(116,158,243,.02), 0 4px 12px rgba(102,188,253,.04), 0 8px 24px rgba(95,178,255,.17)` | **输入框聚焦** |
|
||||
|
||||
### 6.5 间距阶梯(实际用到的值)
|
||||
|
||||
`2 · 4 · 6 · 8 · 10 · 12 · 14 · 16 · 20 · 24 · 28 · 32 · 36 · 42 · 54 · 96`
|
||||
|
||||
| 值 | 出处 |
|
||||
|---|---|
|
||||
| 2 | 导航行间距(`mb-2`)、分段控件内 gap(`gap-6`=6 是另一处) |
|
||||
| 4 | 按钮内 gap(图标↔文字)、`pl-4`、`p-4` |
|
||||
| 6 | 分段控件段内 gap、底排组间距、tab 文字 gap |
|
||||
| 8 | 行内边距(`px-8`)、子项间距(`gap-8`)、chip 上下内边距(`py-8`) |
|
||||
| 10 | 内容内边距(`p-10`)、分区标题左右(`px-10`)、输入框内容 padding |
|
||||
| 12 | 侧栏左右内边距、chip 左右内边距(`px-12`)、h2 下间距(`mb-12`) |
|
||||
| 14 | 输入框内编辑区↔按钮排(`gap-14`) |
|
||||
| 16 | 顶栏左右(`px-16`)、底部留白(`h-16`)、chip 下间距(`pb-16`) |
|
||||
| 20 | 问候语上下间距(`mt-20`)、分段控件上间距 |
|
||||
| 24 | 主区内容左右(`px-24`) |
|
||||
| 28 | 问候语下间距(`mb-28`,本态被 `!mb-0` 覆盖) |
|
||||
| 42 | chip 最小高(`min-h-42`) |
|
||||
| 54 | 分段控件高(`h-54`) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 字体
|
||||
|
||||
### 7.1 豆包用的是什么
|
||||
|
||||
〔VAR〕`--s-font-family`:
|
||||
```
|
||||
var(--dbx-font-sans-serif,
|
||||
var(--font-sans, "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue',
|
||||
Helvetica, 'Noto Sans', 'Apple Color Emoji', 'Segoe UI Emoji',
|
||||
'Noto Color Emoji', sans-serif"))
|
||||
```
|
||||
〔metrics〕`bodyFont`:`ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"`
|
||||
|
||||
**也就是说:界面正文没有自定义中文字体,全是系统字体栈。**(`--s-font-*` 全部继承 `--s-font-family`。)
|
||||
|
||||
`fonts.json` 里那些 @font-face 都是「局部用途」,不是界面主字体:
|
||||
|
||||
| 字体 | 用途 | 我们要不要 |
|
||||
|---|---|---|
|
||||
| `LarkChineseQuote` | **只用 6 个弯引号**(`U+2018-201E`),src 是 `local("PingFangSC-*")` —— 本地字体别名,不下载 | ❌ 不需要(系统字体自带引号) |
|
||||
| `LarkEmojiFont` | 4 个 emoji(`U+1F21A` 等)走本地 Apple/Noto Emoji | ❌ |
|
||||
| `LarkHackSafariFont` | Safari 补丁(`unicode-range: U+0`,即永不匹配) | ❌ |
|
||||
| `Montserrat SemiBold` | 数字/英文强调(woff2 外链) | ❌ 用系统 |
|
||||
| `JetBrains Mono` | 代码块 | ⭕ 可选,建议 `ui-monospace` 回退 |
|
||||
| `KaTeX_*` | 数学公式(21 个字体文件) | ❌ 不引;要公式再说 |
|
||||
|
||||
### 7.2 建议我们的字体栈(无字体文件)
|
||||
|
||||
```css
|
||||
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC",
|
||||
"Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif,
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji";
|
||||
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
|
||||
"Liberation Mono", "Courier New", monospace;
|
||||
```
|
||||
跟仓库现有 `web/assets/app.css` 的 `--font-sans` 一致,**不用改**;只需注意豆包的字重习惯:
|
||||
正文 400、导航/标题 500、问候语与大标题 600、h2 700。中文在 Windows 上 500 会伪粗,必要时用 600 替代。
|
||||
|
||||
---
|
||||
|
||||
## 8. 图标清单(19 个内联 SVG + 输入条 8 个 PNG)
|
||||
|
||||
> **法律边界:这些 SVG 是豆包的图标资源,只作为「形状参考」。我们要用 Material Icons 或自己手绘等效形状,不复用 path 数据。**
|
||||
> 尺寸规律:`24×24 viewBox`,通过 `size-12 / 14 / 16 / 18 / 20` + `p-2/p-3` 控制在界面里的成品尺寸。
|
||||
|
||||
| 文件 | 用途(在 DOM 里的位置) | 形状描述(我们可以照着画) | 显示尺寸 | 颜色 |
|
||||
|---|---|---|---|---|
|
||||
| `svg-01` | 侧栏品牌行「后退」`sidebar-navigation-back` | 左箭头:横杠 + 左尖角,圆头 | 18 | 继承,disabled 时 opacity .3 |
|
||||
| `svg-02` | 「前进」`sidebar-navigation-forward` | 右箭头(镜像) | 18 | 同上 |
|
||||
| `svg-03` | 「新工作任务」`create_office_task_button` | **圆角方框 + 右上角斜插一支笔**("编辑文档") | 18(+2 内边距) | `#000` |
|
||||
| `svg-04` | 「新对话」`create_conversation_button` | **圆形对话气泡,尾巴在左下** | 18 | `#000` |
|
||||
| `svg-05` | 「项目」`team-workspace-sidebar-entry` | **文件夹**:圆角矩形 + 顶部左侧标签凸起 | 18 | `#000` |
|
||||
| `svg-06` | 「API 服务」`app-open-api-service` | **两个圆角方块斜着叠在一起 + 两条斜线穿过**(像插头/连接件) | 18 | `#000` |
|
||||
| `svg-07` | 「API 服务」行右端 | **↗ 外链箭头**:一条斜线 + 右上角拐角 | 12 | `--dbx-text-tertiary` |
|
||||
| `svg-08` | 「更多」行图标 `skill-page-item-more` | **2×2 四个圆角小方块**(田字) | 18 | `#000` |
|
||||
| `svg-09` | 「更多」行右端 | **`>` chevron**,细线圆头 | 20(+p-3) | `rgba(0,0,0,.3)` |
|
||||
| `svg-10` | 底部「关于豆包」 | **圆圈 + 里面一个 i**(描边圆) | 16(+p-2) | `rgba(0,0,0,.5)` |
|
||||
| `svg-11` | 底部右下「下载」 | **向下箭头 + 底部托盘**(⤓) | 18 | `rgba(0,0,0,.5)` |
|
||||
| `svg-12` | 顶栏左「收起侧栏」`siderbar_close_btn` | **圆角方框 + 靠左一条竖线**("左侧面板"图标,竖线约在 1/3 处) | 18 | `#000` |
|
||||
| `svg-13` | 输入框左下「+」`upload_file_button` | **加号**,2px 描边圆头 | 18 | `#000` |
|
||||
| `svg-14` | 「豆包 快速」「对话」后面的**小箭头** | **`>` 细箭头**(不是下箭头;放大看是圆头折线,`rotate-0`),想表达"可展开"就转 90° 用 | 12 | `rgba(0,0,0,.2)` |
|
||||
| `svg-15` | 「更多」另一处(无 size class) | 同 `svg-08`(2×2 方块) | 继承 | 继承 |
|
||||
| `svg-16` | 输入框右下**麦克风** `asr_btn` | 麦克风:胶囊咪头 + 下方弧形托 + 竖杆 | 18 | `#000` |
|
||||
| `svg-17` | 模式下拉菜单的**选中勾** | **✓ 对勾**,粗描边圆头 | 14 | `--s-color-brand-primary-default` |
|
||||
| `svg-18` | 菜单项「本地电脑」 | **显示器**:矩形屏幕 + 底座 | 16 | 继承 |
|
||||
| `svg-19` | 菜单项「云电脑」 | **云朵** | 16 | 继承 |
|
||||
|
||||
**输入条那 8 个技能图标不是 SVG,是 16×16 的 PNG**(`<img class="size-[16px] dark:hidden">`,亮/暗各一套)〔DOM〕。
|
||||
它们的统一风格是「**圆角方框 + 内部一个符号**」:
|
||||
|
||||
| 技能 | 框内符号 |
|
||||
|---|---|
|
||||
| 对话 | 圆形气泡(尾巴左下) |
|
||||
| PPT 生成 | 圆角方框内字母 **P** |
|
||||
| 图像生成 | 方框内 **小山 + 太阳点** |
|
||||
| 帮我写作 | 方框内 **两条横线**(文档) |
|
||||
| 视频生成 | 方框内 **播放三角** |
|
||||
| 录音转写 | **麦克风 + 右侧三条短横线** |
|
||||
| 音乐生成 | **音符**(双符头 + 梁) |
|
||||
| 更多 | 2×2 四方块 |
|
||||
|
||||
> 我们用 Material Symbols Rounded 的等效图标(`edit_square`、`chat_bubble`、`folder`、`api`、`apps`、`open_in_new`、
|
||||
> `chevron_right`、`info`、`download`、`left_panel_close`、`add`、`keyboard_arrow_right`、`mic`、`check`、
|
||||
> `computer`、`cloud`、`presentation`、`image`、`edit_note`、`movie`、`graphic_eq`、`music_note`),
|
||||
> 统一 18px、线宽视觉 ~1.8–2px、圆头端点,就是豆包那种「圆润线面结合」的观感。
|
||||
|
||||
---
|
||||
|
||||
## 9. 交互 / 动效
|
||||
|
||||
### 9.1 能从 CSS / 类名确定的
|
||||
|
||||
| 场景 | 动效 | 时长/曲线 | 依据 |
|
||||
|---|---|---|---|
|
||||
| 所有 hover 变色(导航行、chip、按钮) | `background-color` 过渡 | **150ms**,`--ease-out: cubic-bezier(0,0,.2,1)` | 〔DOM〕`transition-colors duration-150 ease-out` |
|
||||
| 侧栏折叠/展开 | 容器 `width` + 面板 `transform/opacity` | **200ms**;面板 `transform .2s, opacity .2s` | 〔CSS〕 |
|
||||
| 侧栏浮层进场 | `drawer-enter` 动画 | 200ms `ease` | 〔CSS〕 |
|
||||
| 侧栏拖拽改宽时 | 全部过渡关掉(`[data-resizing=true]{transition:none}`) | — | 〔CSS〕 |
|
||||
| 分段控件滑块 | `transform: translateX()` | **150ms** `ease-in-out`(`cubic-bezier(.4,0,.2,1)`) | 〔DOM〕〔VAR〕 |
|
||||
| 推荐区淡入淡出 | `opacity` + `visibility` | **100ms** `ease-out`;隐藏时 `visibility` 延迟 100ms | 〔CSS〕`.sug-input-visibility-motion` |
|
||||
| 顶栏左区内边距 | `padding-left` | 200ms | 〔DOM〕`transition-[padding-left] duration-200` |
|
||||
| 问候语文案切换 | `::before/::after` 遮罩擦除 | 200ms `linear` | 〔CSS〕`greeting-text-Q0pGud` |
|
||||
| 输入框聚焦 | 边框色 + 阴影 | 由 Tailwind 默认过渡(约 150ms) | 〔DOM〕`focus-within:shadow/after:border` |
|
||||
| 光标闪烁 | `caret-blink` / ProseMirror gapcursor 1.1s steps(2) | 1.1s | 〔CSS〕 |
|
||||
| 语音录制 | `asr-dot-pulse` 脉冲 | — | 〔CSS〕 |
|
||||
| 降级 | `prefers-reduced-motion: reduce` 时:淡入淡出动画压到 **1ms**、推荐区过渡 `none`、`.motion-reduce:animate-none` | — | 〔CSS〕 |
|
||||
| 焦点可见 | `:focus-visible` 统一 `outline: 2px solid var(--dbx-fill-highlight)` + `outline-offset: -2px` | 即时 | 〔DOM〕 |
|
||||
|
||||
### 9.2 推不出来 / 需实测
|
||||
|
||||
| 项 | 状态 |
|
||||
|---|---|
|
||||
| 发送按钮 hover / active(是否变深、是否缩放) | **需实测**(镜像只有静态图;我们现有 `.send-btn:active{scale(.94)}` 是自创的) |
|
||||
| 麦克风按钮 hover 的具体色 | 有类名依据:`hover:bg-dbx-fill-trans-20-hover`(`#00000012`),但**视觉确认需实测** |
|
||||
| 推荐 chip 的按下态 | **需实测**(只有 hover) |
|
||||
| 侧栏「最近」右侧「…」按钮点开的菜单样式 | **需实测**(本态空列表,菜单未渲染) |
|
||||
| 输入框内换行/回车的自动增高节奏 | **需实测**(CSS 给的是 `max-height:360px`,逐帧增长曲线未知) |
|
||||
| 消息气泡 / 消息操作栏 | 本镜像为空态,**未覆盖**(只能给 token,给不了实测矩形) |
|
||||
|
||||
---
|
||||
|
||||
## 10. 响应式与折叠
|
||||
|
||||
### 10.1 断点(豆包自己定义的)
|
||||
|
||||
| Token | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| `--dbx-breakpoint-xs` | 462px | 〔VAR〕 |
|
||||
| `--dbx-breakpoint-sm` | **640px** | 〔VAR〕 |
|
||||
| `--dbx-breakpoint-md` | **868px** | 〔VAR〕 |
|
||||
| `--dbx-breakpoint-lg` | **1440px** | 〔VAR〕 |
|
||||
|
||||
CSS 里实际出现的媒体查询(`teqgtp-chat.css` 共 101 条):
|
||||
`min-width: 462 / 640 / 868 / 900 / 1440`,`max-width: 399 / 599 / 799 / 800`,以及 `@media (hover:hover)`(15 处)、
|
||||
`@media (prefers-reduced-motion:reduce)`(3 处)。移动端还有一批 `max-width:799px` 的浮层变体(`![fixed] right-0 bottom-0 z-40 w-screen`)。
|
||||
|
||||
### 10.2 侧栏的四种形态
|
||||
|
||||
〔CSS〕
|
||||
```css
|
||||
.container-hzjmF1{flex:none;height:100%;width:0;transition:none}
|
||||
.container-hzjmF1[data-presentation=inline]{width:280px} /* 展开:占位 280 */
|
||||
.container-hzjmF1[data-dock-transition]{transition:width .2s}
|
||||
.panel-fvxXfj{position:fixed;width:280px;transition:transform .2s,opacity .2s}
|
||||
.container-hzjmF1[data-presentation=inline] .panel-fvxXfj{position:relative;z-index:20}
|
||||
.container-hzjmF1[data-presentation=invisible] .panel-fvxXfj{opacity:0;pointer-events:none;transform:translateX(-110%)}
|
||||
.container-hzjmF1[data-presentation=drawer] .panel-fvxXfj{animation:drawer-enter .2s ease;z-index:40}
|
||||
```
|
||||
|
||||
| 形态 | 行为 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `inline` | 占位 280,正常流内,`position:relative` | 桌面展开 |
|
||||
| `invisible` | 占位 0,面板左移 110% + 透明 | 桌面折叠 |
|
||||
| `floating` | 占位 0,浮在内容上,`pointer-events:none` | 宽屏悬浮 |
|
||||
| `drawer` | 占位 0,抽屉式滑入,z-index 40 | 窄屏(≤799) |
|
||||
|
||||
* 侧栏类名 `relative p-12 sm:fixed` ⇒ **≥640px 面板变 fixed**(配合上面的 presentation 控制)。
|
||||
* 折叠/展开按钮在顶栏左侧(`siderbar_close_btn`),图标就是 `svg-12`。
|
||||
* 主区有 `min-width:400px` 保护(`.main-with-nav-qLRcbu{min-width:400px}`),窄于此再考虑移动布局。
|
||||
|
||||
### 10.3 我们的落地建议
|
||||
|
||||
```css
|
||||
/* 桌面 */
|
||||
#app { display:flex; height:100vh; overflow:hidden; }
|
||||
.sidebar { width:280px; flex:none; transition:width .2s, transform .2s; }
|
||||
body.sidebar-collapsed .sidebar { width:0; transform:translateX(-110%); opacity:0; }
|
||||
/* ≤868:默认折叠成抽屉 */
|
||||
@media (max-width:868px){ .sidebar{ position:fixed; inset:0 auto 0 0; z-index:40; width:280px; } }
|
||||
/* 内容列永远 1000 上限,两侧 24 内边距兜底 */
|
||||
.content-col{ width:100%; max-width:1000px; margin:0 auto; padding:0 24px; }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. 「我们怎么用」:把豆包这套往我们的 App 上映射
|
||||
|
||||
### 11.1 侧栏放什么(对照我们真实有的功能)
|
||||
|
||||
豆包这一列是:`新工作任务 / 新对话 / 项目 / API 服务 / 更多`。我们照「动作在前、内容在后、杂项在底」的顺序改:
|
||||
|
||||
| 位置 | 我们的条目 | 对应豆包哪个 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 品牌行 | **我们的名字**(当前是「豆包」两个字的纯文字) | 品牌行 | 高度 36、18/26/500;**不要放豆包官方 logo 图形**,纯文字最安全 |
|
||||
| 主动作 1 | **新对话** `Ctrl J`(放第一个,因为最常用) | 新工作任务 | 图标:气泡(`svg-04` 的等效形);快捷键 hover 才显示 |
|
||||
| 主动作 2 | **智能体** | 新对话 | 图标:机器人/星形(我们已有 avatar 资源,直接用自己的) |
|
||||
| 主动作 3 | **群聊** | 项目 | 图标:双人/群组 |
|
||||
| 主动作 4 | **资源** | API 服务 | 图标:文件夹;右端可挂「数量」小字(学它的 `12px tertiary`) |
|
||||
| 主动作 5 | **会议** | 更多 | 图标:日历/画布;右端用 `>` 表示可展开子项 |
|
||||
| 分区标题 | **最近** | 最近 | 12/18/500 tertiary,行高 32,`px-10`,hover 底色 |
|
||||
| 分区标题 2 | **收藏 / 群聊会话**(可选第二组) | — | 同样的 `h-32` 分组头,分组之间 `gap-2` |
|
||||
| 会话项 | 会话标题 + 时间 + `…` 菜单 | 会话项 | 高 32、圆角 18、`padding 0 10`、选中/hover `rgba(0,0,0,.04)` |
|
||||
| 底部 | **设置** + **关于** + (可选)用量 | 关于豆包 + 下载 | 上方 1px `rgba(0,0,0,.08)` 分隔线、左右 8、文字 14/22 `rgba(0,0,0,.5)` |
|
||||
|
||||
**不要抄**(豆包商业元素):`登录`、`下载豆包工作 / 下载电脑版`、`API 服务`(它的商业化入口)、`工作`页签里的 PPT/文档商业能力、
|
||||
Windows 四色 logo、豆包 logo 与「豆包」文案本身。
|
||||
|
||||
### 11.2 输入框那排按钮 → 我们真实能力
|
||||
|
||||
豆包:`+ | 对话 › | PPT 生成 · 图像生成 · 帮我写作 · 视频生成 · 录音转写 · 音乐生成 · 更多 | 豆包 快速 › | 🎤`
|
||||
|
||||
我们的映射(**结构不变:左 36 圆按钮 + 竖线 + 模式按钮 › + 一排能力按钮 + 右侧模型 › + 36 圆按钮**):
|
||||
|
||||
| 槽位 | 我们放什么 | 依据 |
|
||||
|---|---|---|
|
||||
| 1 | **+ 附件**(上传/拖拽文件,风格 36×36 圆、18px 图标) | 直接同构 |
|
||||
| 2 | 竖线 `1×16 rgba(0,0,0,.1)` | 同构 |
|
||||
| 3 | **模式 ▾**:`对话 / 深度思考 / 联网`(我们真有就放,没有就换成「纯聊天 / 工具调用」) | 豆包这里是「对话」,点开选模型能力 |
|
||||
| 4.1 | **深度思考**(有则放;图标:灯泡/脑子) | 替换 PPT 生成 |
|
||||
| 4.2 | **联网搜索**(有则放;图标:地球) | 替换 图像生成 |
|
||||
| 4.3 | **@ 群成员**(群聊时才有;图标:@ 或人像组) | 替换 帮我写作 |
|
||||
| 4.4 | **朗读 / 自动朗读开关**(我们已有这功能) | 替换 视频生成 |
|
||||
| 4.5 | **语音转写 / 录音**(麦克风之外的录音入口) | 替换 录音转写 |
|
||||
| 4.6 | **会议模式**(一键进会议画布) | 替换 音乐生成 |
|
||||
| 4.7 | **更多**(2×2 方块,多余能力收这里) | 同构 |
|
||||
| 5 | **模型 ▾**:`模型名 思考强度`,14/22 + 12px 箭头 | 同构(豆包是「豆包 快速 ▾」) |
|
||||
| 6 | **麦克风(空)/ 发送(有内容)**:36 圆 | 同构:空态 `#f5f5f5` 底;有内容 **#06f** 底白箭头 |
|
||||
|
||||
**按钮取舍原则**:豆包那 7 个技能按钮是它的商业能力清单;我们只保留**点了真的会发生事**的。
|
||||
数量控制在 **6 个以内**——豆包 1440 下 7 个按钮已经从 x≈509 排到 1135,离右侧「豆包 快速」只剩约 90px;
|
||||
再多就必须靠「更多」收口(它的左组本来就是 `flex-1 + overflow:hidden`,放不下会裁掉)。
|
||||
|
||||
### 11.3 别抄的清单(法律边界)
|
||||
|
||||
| 可以学 | 不能抄 |
|
||||
|---|---|
|
||||
| 布局比例、栅格、间距、行高 | 豆包 logo、品牌名「豆包」字样、字标 |
|
||||
| 色值、色阶、圆角、阴影、动效曲线 | `icons/svg-01..19.svg` 的 path 数据(形状可参考,代码不能复制) |
|
||||
| 字体栈思路(系统字体回退) | `fonts.json` 里的字体文件(`LarkChineseQuote` 等) |
|
||||
| 组件结构(输入框分层、分段控件) | 截图里的文案(推荐问法、占位符以外的示例文本) |
|
||||
| 「圆润、低对比、大量留白」的气质 | `work` 页签的商业能力命名(PPT 生成/图像生成…) |
|
||||
|
||||
**一句话**:学它的**度量与气质**,不学它的**资产与文案**。所有图标用 Material Symbols 或自己画,
|
||||
所有文字用我们自己的,产品名不叫豆包、不用豆包 logo。
|
||||
|
||||
### 11.4 与现有 `web/assets/app.css` 的对齐清单
|
||||
|
||||
| 项 | 现有实现 | 镜像实测 | 要不要改 |
|
||||
|---|---|---|---|
|
||||
| 内容列宽 | `--content-w: 996px` | **1000px** | 建议改(视觉差 4px,但别的地方都对不齐) |
|
||||
| 输入框高 | 未固定(`padding 12 14 8` + 内容撑开) | **100**(`min-height:100px`) | 改:固定 `min-height:100px`、内边距 `10`、编辑区↔按钮排 `gap:14` |
|
||||
| 输入框聚焦 | `0 0 0 3px` ring + `border rgba(0,101,253,.5)` | 细边框变 `rgba(0,102,255,.3)` + **蓝光晕**,无 ring | 改 |
|
||||
| 底排按钮高 | `.cbtn` 32 / `padding 0 10` | 32 / `padding 0 8`,圆角 12 | 微调 padding |
|
||||
| 底排按钮文字色 | `--text-secondary`(灰) | **`#000`(纯黑)**,hover 只变底不变色 | 改 |
|
||||
| 发送 / 麦克风 | 32×32 | **36×36** | 改 |
|
||||
| 麦克风配色 | 紫(`--violet-weak`/`--violet`) | **`#f5f5f5` 底 + 黑图标** | 改(紫是自创的) |
|
||||
| 分段控件 | `.pill-tabs` | 轨道 326×54 `#f5f5f5`、滑块 160×48 白 + 小阴影、文字 16/18 | 按 §4.3 对齐 |
|
||||
| chip | `.chip` | 42 高、圆角 12、边框 `#00000012`、`padding 12/8`、间距 10 | 对齐 |
|
||||
| 侧栏 hover | `--bg-hover: rgba(0,0,0,.045)` | `#0000000a`(0.039) | 基本一致,可留着 |
|
||||
|
||||
---
|
||||
|
||||
## 12. 给实现者的 Checklist
|
||||
|
||||
照着勾,首屏就能立起来。
|
||||
|
||||
**骨架**
|
||||
- [ ] `html,body{height:100%;margin:0;overflow:hidden}`,`#app{display:flex}`
|
||||
- [ ] 侧栏 `width:280px; background:#f9f9f9; padding:10px 12px 12px; border-right:1px solid #e9e9e9`
|
||||
- [ ] 主区 `flex:1; min-width:0; background:#fff`
|
||||
- [ ] 顶栏 `height:56px; padding:0 16px; display:flex; align-items:center; gap:8px; border-bottom:1px solid #ededed`
|
||||
- [ ] 内容列 `width:100%; max-width:1000px; margin:0 auto`(父级左右 24px 内边距)
|
||||
- [ ] 输入区固定 `height:100px` 贴底,下面是 **16px** 留白
|
||||
- [ ] `body,html` 不滚;只有侧栏列表和消息区各自滚
|
||||
|
||||
**侧栏**
|
||||
- [ ] 品牌行高 36,文字 18/26/500 `#000`,左内边距 10
|
||||
- [ ] 导航行 `height:32px; padding:0 8px; border-radius:10px; margin-bottom:2px`,图标 18px(22px 盒)+ 文字 14/22/500 `#000`,图标↔文字 8
|
||||
- [ ] 导航行 `hover{background:#0000000a}`,过渡 150ms `cubic-bezier(0,0,.2,1)`
|
||||
- [ ] 快捷键小字 12px `rgba(0,0,0,.35)`,默认 `opacity:0`,行 hover 才显示
|
||||
- [ ] 「最近」分组头 `height:32px; padding:0 10px; font:500 12/18; color:rgba(0,0,0,.35)`,上边 8px 间隔
|
||||
- [ ] 会话项 `height:32px; border-radius:18px; padding:0 10px`,hover/选中 `background:rgba(0,0,0,.04)`
|
||||
- [ ] 底部:1px `rgba(0,0,0,.08)` 分隔线(左右缩进 8),文字 14/22 `rgba(0,0,0,.5)`
|
||||
- [ ] 列表滚动条默认隐藏,hover 显示 7px、`#ccc`、圆角、无轨道
|
||||
|
||||
**顶栏**
|
||||
- [ ] 左:折叠按钮 26×26(图标 18,内边距 4,圆角 6,hover 底 `#0000000a`),距左 16
|
||||
- [ ] 右:我们的主按钮(36 高、圆角 12)+ 次按钮,间距 8
|
||||
|
||||
**空态**
|
||||
- [ ] 问候语 28/600、行高 42、`#000`,水平居中(中心 = 侧栏右缘 + 主区一半)
|
||||
- [ ] 问候语块顶 ≈ 视口 34%(1440×900 下 308)
|
||||
- [ ] 问候语下 20px → 分段控件
|
||||
- [ ] 分段控件:轨道 326×54 圆角全、`#f5f5f5`;滑块 160×48 白 + `0 2px 4px #00000005,0 4px 10px #00000005`,`transition:transform 150ms`;文字 16/18(选中 500 `#000`,未选中 400 `#7a7a7a`)
|
||||
- [ ] 「为你推荐」12/18 `rgba(0,0,0,.35)`,左对齐、左缩进 4、下间距 12
|
||||
- [ ] chip:42 高、圆角 12、`1px #00000012`、`padding:8px 12px`、14/22 `#000`、间距 10、hover `#0000000a`
|
||||
- [ ] 推荐区与输入框同宽同左缘(x=360),底对齐输入框上沿,`padding-bottom:16`
|
||||
|
||||
**输入框(重点)**
|
||||
- [ ] 容器:`1000×100`(`min-height:100px`)、`border-radius:24px`、`background:#fff`、`border:1px solid #0000001a`、`box-shadow:0 2px 4px #00000005,0 4px 16px #0000000a,0 8px 32px #00000014`
|
||||
- [ ] 内层 `padding:10px`,编辑区在上、按钮排在下,中间 `gap:14px`
|
||||
- [ ] 编辑区:16/24,文本左缩进再 +10,placeholder `rgba(0,0,0,.3)`,光标 `#0057ff`
|
||||
- [ ] 聚焦:边框 `rgba(0,102,255,.3)`,阴影换成 `0 2px 4px rgba(116,158,243,.02),0 4px 12px rgba(102,188,253,.04),0 8px 24px rgba(95,178,255,.17)`(**不要 ring**)
|
||||
- [ ] 按钮排:高 36,左组 `flex:1`、`overflow:hidden`,组间距 6
|
||||
- [ ] +:36×36 圆、图标 18、hover `#0000000a`
|
||||
- [ ] 竖线:`1×16` `#0000001a`,左右各 8
|
||||
- [ ] 模式按钮:`h32 / 圆角12 / padding 0 8 0 4`,16px 图标 + 14/22 `#000` + 12px `rgba(0,0,0,.2)` 箭头
|
||||
- [ ] 能力按钮:`h32 / 圆角12 / padding 0 8`,16px 图标 + 14/22 `#000`,按钮间 gap 4,hover `#0000000a`
|
||||
- [ ] 右侧模型按钮:14/22 `#000` + 12px 箭头
|
||||
- [ ] 右下按钮 36×36 圆:空态 `#f5f5f5` 底 + 黑图标;有内容 **#06f** 底 + 白箭头(同一个槽位切换)
|
||||
- [ ] 按钮排始终贴输入框内底 10px;编辑区最大高 = `360 - 36(按钮排) - 16 - 14(gap) - 10(padding) = **284px**`(豆包原式:`max-h-[calc(var(--input-guidance-input-container-max-height) - var(--custom-area-height,0px) - 36px - 16px - 14px - 10px)]`)
|
||||
|
||||
**工程**
|
||||
- [ ] 所有过渡统一 150ms + `cubic-bezier(0,0,.2,1)`;侧栏折叠 200ms;分段滑块 150ms `cubic-bezier(.4,0,.2,1)`
|
||||
- [ ] `@media (prefers-reduced-motion:reduce)` 关掉动画
|
||||
- [ ] 亮/暗两套变量按 §6.1 填(暗色值直接抄右列)
|
||||
- [ ] 图标全部用 Material Symbols / 自绘,不引豆包 SVG、不引豆包字体
|
||||
- [ ] 文案全部自己写
|
||||
|
||||
---
|
||||
|
||||
## 13. 附:抓取镜像里可以直接查证的位置
|
||||
|
||||
| 想知道什么 | 看哪儿 |
|
||||
|---|---|
|
||||
| 某个元素的行内 style / 类名 | `dom/page.rendered.html`(搜 `data-testid`) |
|
||||
| 元素层次 + 坐标 + 背景色 | `dom/dom-tree.txt`(25 行,每个节点带 `[x,y wxh]`) |
|
||||
| 关键元素的计算样式 | `styles/metrics.json`、`styles/computed-styles.json` |
|
||||
| 全部 240 个 `--dbx-*` 亮色变量 | `styles/dbx-light-vars.json` |
|
||||
| 亮/暗成对的变量(552 个) | `styles/computed-styles.json → cssVars`(格式 `亮 | 暗`) |
|
||||
| 圆角/阴影/断点/字号阶梯 | 同上 `cssVars` 里的 `--s-radius-* / --s-shadow-* / --dbx-breakpoint-* / --s-font-*` |
|
||||
| 工具类真实取值 | `styles/key-classes.css`、`styles/tokens.txt` |
|
||||
| 字体清单 | `styles/fonts.json` |
|
||||
| 图标形状 | `icons/svg-01..19.svg`(24×24 viewBox,`fill="currentColor"`) |
|
||||
| 想看「活的」页面 | `page.mhtml` 用浏览器打开 |
|
||||
|
||||
---
|
||||
|
||||
**文档版本**:v1(基于 2026-10-17 抓取的镜像 + 1440×900 三张截图逐像素实测)。
|
||||
**只学布局/尺寸/配色,不含豆包任何代码、字体文件、图标资源与文案。**
|
||||
11
package.json
@@ -4,13 +4,16 @@
|
||||
"private": true,
|
||||
"description": "豆包复刻(LynxJS / ReactLynx):Web + Windows(exe) + Android(apk),AI 内核支持火山方舟 / OpenAI + MCP + Python 工具",
|
||||
"scripts": {
|
||||
"install:all": "npm --prefix app install && npm --prefix server install",
|
||||
"build": "npm --prefix app run build",
|
||||
"start": "node server/src/index.mjs",
|
||||
"dev": "npm --prefix app run build && node server/src/index.mjs",
|
||||
"install:all": "npm --prefix desktop install",
|
||||
"start": "node scripts/start-web.mjs",
|
||||
"dev": "node scripts/start-web.mjs",
|
||||
"start:node": "node server/src/index.mjs",
|
||||
"start:legacy-lynx": "npm --prefix app run build && node server/src/index.mjs",
|
||||
"mock": "node scripts/mock-llm.mjs",
|
||||
"rasterize": "node scripts/rasterize-icons.mjs",
|
||||
"exe": "node scripts/build-exe.mjs",
|
||||
"web:scrape": "node scripts/scrape-doubao-web.mjs",
|
||||
"web:shot": "node scripts/screenshot.mjs",
|
||||
"apk": "node scripts/build-apk.mjs",
|
||||
"android:setup": "node scripts/android-setup.mjs",
|
||||
"mcp:smoke": "node scripts/mcp-smoke.mjs",
|
||||
|
||||
73
reference/scripts/extract-css.mjs
Normal file
@@ -0,0 +1,73 @@
|
||||
/** 从抓下来的 CSS 里提取 light 主题变量 + 关键组件类,汇总成一份参考。 */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dirname, 'doubao-web-mirror');
|
||||
const OUT = path.join(ROOT, 'styles');
|
||||
const cssFiles = [];
|
||||
const walk = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name);
|
||||
if (ent.isDirectory()) walk(p);
|
||||
else if (ent.name.endsWith('.css')) cssFiles.push(p);
|
||||
}
|
||||
};
|
||||
walk(path.join(ROOT, 'assets'));
|
||||
console.log('CSS 文件:', cssFiles.length);
|
||||
|
||||
let all = '';
|
||||
for (const f of cssFiles) all += '\n' + fs.readFileSync(f, 'utf8');
|
||||
console.log('CSS 总长:', (all.length / 1048576).toFixed(2), 'MB');
|
||||
|
||||
// 1) light 主题变量块
|
||||
const lightBlocks = [];
|
||||
for (const m of all.matchAll(/([^{}]{0,80})\{([^{}]*--dbx-text-primary:#000[^{}]*)\}/g)) {
|
||||
lightBlocks.push(m[0]);
|
||||
}
|
||||
const vars = {};
|
||||
for (const block of lightBlocks) {
|
||||
for (const m of block.matchAll(/(--dbx-[a-z0-9-]+):([^;{}]+);/g)) {
|
||||
const [, k, v] = m;
|
||||
if (v.includes('var(')) continue;
|
||||
if (!(k in vars)) vars[k] = v.trim();
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'dbx-light-vars.json'), JSON.stringify(vars, null, 2), 'utf8');
|
||||
console.log('light 主题变量:', Object.keys(vars).length, '个 → dbx-light-vars.json');
|
||||
|
||||
// 2) 常用工具类定义(按 DOM 里见到的类名精确找)
|
||||
const wanted = [
|
||||
'w-sidebar-width', 'text-28', 'text-dbx-text-primary', 'text-dbx-text-secondary',
|
||||
'bg-dbx-bg-base-web', 'bg-dbx-bg-body-web', 's-font-small', 's-font-base', 's-font-h1',
|
||||
'rounded-dbx-2xl', 'rounded-dbx-3xl', 'rounded-dbx-4xl', 'rounded-full',
|
||||
'shadow-dbx-drop-shadow-sm', 'shadow-dbx-drop-shadow-xs',
|
||||
];
|
||||
const found = {};
|
||||
for (const cls of wanted) {
|
||||
const re = new RegExp('\\.' + cls.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\{[^}]*\\}', 'g');
|
||||
const hits = [...all.matchAll(re)].map((m) => m[0]);
|
||||
if (hits.length) found[cls] = hits.slice(0, 2).join(' || ');
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'key-classes.css'), Object.entries(found).map(([k, v]) => `/* ${k} */\n${v}`).join('\n\n'), 'utf8');
|
||||
|
||||
// 3) 字体相关的 @font-face(只留 family/src/weight)
|
||||
const fontFaces = [...all.matchAll(/@font-face\{[^}]*\}/g)].map((m) => m[0]);
|
||||
const fontSummary = new Map();
|
||||
for (const face of fontFaces) {
|
||||
const fam = (face.match(/font-family:([^;]+)/) || [])[1];
|
||||
const src = (face.match(/src:url\(([^)]+)\)/) || [])[1];
|
||||
const weight = (face.match(/font-weight:([^;]+)/) || [])[1];
|
||||
if (!fam) continue;
|
||||
const key = fam.replace(/["']/g, '') + '|' + (weight || '');
|
||||
if (!fontSummary.has(key)) fontSummary.set(key, { family: fam.replace(/["']/g, ''), weight: weight || '', src: src || '' });
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'fonts.json'), JSON.stringify([...fontSummary.values()], null, 2), 'utf8');
|
||||
console.log('字体:', [...fontSummary.keys()].join(', '));
|
||||
|
||||
// 4) 滚动条 / 圆角 / 阴影 token 概览
|
||||
const radii = [...new Set([...all.matchAll(/--dbx-radius-[a-z0-9]+:([^;}]+)/g)].map((m) => m[1]))];
|
||||
const shadows = [...new Set([...all.matchAll(/--dbx-drop-shadow-[a-z]+:([^;}]+)/g)].map((m) => m[1]))];
|
||||
fs.writeFileSync(path.join(OUT, 'tokens.txt'), [
|
||||
'# 圆角', ...radii, '', '# 阴影', ...shadows, '',
|
||||
].join('\n'), 'utf8');
|
||||
console.log('done');
|
||||
@@ -1,11 +1,18 @@
|
||||
/**
|
||||
* 打包 Windows 桌面版(Electron)。
|
||||
* 打包 Windows 桌面版(Electron + 网页版界面 + 内嵌 Python 内核)。
|
||||
*
|
||||
* ⚠️ 一个必须知道的坑:Electron 的 exe 放在**非 ASCII 目录**下会在启动时崩溃(0xC0000005),
|
||||
* 所以输出目录固定用纯英文路径,工作区里的中文目录不能直接放 exe。
|
||||
* exe 的**文件名**可以是中文,这个没问题。
|
||||
* 架构(v2,和旧版完全不同):
|
||||
* Electron 主进程 → 起 runtime/python/python.exe 跑 android/kernel(和安卓 App 同一份内核)
|
||||
* → 内核监听 127.0.0.1:<随机端口> 并托管 runtime/web(豆包网页版风格的前端)
|
||||
* → 主进程开窗加载这个地址
|
||||
* 所以 exe / 浏览器 / 手机三端**共用同一个 AI 内核**,功能天然同步。
|
||||
*
|
||||
* 用法: node scripts/build-exe.mjs [--skip-build] [--out D:\some\ascii\dir]
|
||||
* ⚠️ 两个必须知道的坑:
|
||||
* 1. Electron 的 exe 放在**非 ASCII 目录**下会在启动时崩溃(0xC0000005),
|
||||
* 所以输出目录固定用纯英文路径;exe 的**文件名**可以是中文。
|
||||
* 2. 必须带 runtime/python(python.org 的 embeddable zip):用户机器上不一定装了 Python。
|
||||
*
|
||||
* 用法: node scripts/build-exe.mjs [--out D:\some\ascii\dir]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
@@ -18,7 +25,6 @@ const desktopDir = path.join(repo, 'desktop');
|
||||
const staging = path.join(desktopDir, 'dist-staging');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const skipBuild = args.includes('--skip-build');
|
||||
const outIndex = args.indexOf('--out');
|
||||
const OUT_DIR = outIndex >= 0 && args[outIndex + 1]
|
||||
? path.resolve(args[outIndex + 1])
|
||||
@@ -46,10 +52,21 @@ function copy(from, to, filter) {
|
||||
fs.cpSync(from, to, { recursive: true, filter });
|
||||
}
|
||||
|
||||
/* ------------------------------ 1. 构建界面 ------------------------------ */
|
||||
if (!skipBuild) {
|
||||
log('构建 Lynx 界面产物…');
|
||||
run('npm', ['--prefix', 'app', 'run', 'build'], { cwd: repo });
|
||||
/* ------------------------------ 1. 准备嵌入式 Python ------------------------------ */
|
||||
// 为什么用 embeddable:内核是纯标准库(没有 requests/pydantic),
|
||||
// 所以 python.exe + stdlib 就够,解压只有 ~25MB,也不需要用户在电脑上装 Python。
|
||||
const PY_VERSION = '3.13.9';
|
||||
const cacheDir = path.join(desktopDir, 'build-cache');
|
||||
const pyZip = path.join(cacheDir, `python-${PY_VERSION}-embed-amd64.zip`);
|
||||
|
||||
fs.mkdirSync(cacheDir, { recursive: true });
|
||||
if (!fs.existsSync(pyZip)) {
|
||||
const url = `https://www.python.org/ftp/python/${PY_VERSION}/python-${PY_VERSION}-embed-amd64.zip`;
|
||||
log(`下载嵌入式 Python:${url}`);
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(600000) });
|
||||
if (!res.ok) throw new Error(`下载 Python 失败:HTTP ${res.status}`);
|
||||
fs.writeFileSync(pyZip, Buffer.from(await res.arrayBuffer()));
|
||||
log(`已缓存 ${(fs.statSync(pyZip).size / 1024 / 1024).toFixed(1)} MB`);
|
||||
}
|
||||
|
||||
/* ------------------------------ 2. 准备暂存目录 ------------------------------ */
|
||||
@@ -71,7 +88,7 @@ fs.writeFileSync(
|
||||
name: 'doubao-desktop',
|
||||
productName: APP_NAME, // 用 ASCII:%APPDATA% 下的数据目录也跟着是英文,稳妥
|
||||
version,
|
||||
description: '\u8c46\u5305 \u00b7 LynxJS \u590d\u523b\uff08\u684c\u9762\u7248\uff09',
|
||||
description: '\u8c46\u5305 \u00b7 \u7f51\u9875\u7248\u98ce\u683c\u590d\u523b\uff08\u684c\u9762\u7248\uff09',
|
||||
main: 'main.cjs',
|
||||
},
|
||||
null,
|
||||
@@ -80,29 +97,36 @@ fs.writeFileSync(
|
||||
'utf8',
|
||||
);
|
||||
|
||||
// 2.2 AI 内核(源码 + 依赖)
|
||||
log('复制 AI 内核…');
|
||||
fs.mkdirSync(path.join(staging, 'server'), { recursive: true });
|
||||
copy(path.join(repo, 'server', 'src'), path.join(staging, 'server', 'src'));
|
||||
if (fs.existsSync(path.join(repo, 'server', 'config'))) {
|
||||
copy(path.join(repo, 'server', 'config'), path.join(staging, 'server', 'config'));
|
||||
}
|
||||
fs.copyFileSync(path.join(repo, 'server', 'package.json'), path.join(staging, 'server', 'package.json'));
|
||||
copy(path.join(repo, 'server', 'node_modules'), path.join(staging, 'server', 'node_modules'));
|
||||
|
||||
// 2.3 运行时资源:Lynx 产物 / 宿主页 / web-core / python 工具
|
||||
// 2.2 运行时:Python + AI 内核 + 工具 + 网页前端
|
||||
log('复制运行时资源…');
|
||||
const runtime = path.join(staging, 'runtime');
|
||||
fs.mkdirSync(runtime, { recursive: true });
|
||||
copy(path.join(repo, 'app', 'dist'), path.join(runtime, 'app', 'dist'));
|
||||
copy(path.join(repo, 'web'), path.join(runtime, 'web'));
|
||||
copy(
|
||||
path.join(repo, 'app', 'node_modules', '@lynx-js', 'web-core', 'dist', 'client_prod', 'static'),
|
||||
path.join(runtime, 'web-core'),
|
||||
);
|
||||
copy(path.join(repo, 'tools'), path.join(runtime, 'tools'), (src) => !src.includes('__pycache__'));
|
||||
|
||||
// 2.4 打包版 MCP 配置:文件系统服务的目录指向数据目录,用占位符避免写死路径
|
||||
// 嵌入式 Python(解压到 runtime/python)
|
||||
log('解压嵌入式 Python…');
|
||||
run('powershell.exe', ['-NoProfile', '-Command',
|
||||
`Expand-Archive -LiteralPath '${pyZip.replace(/'/g, "''")}' -DestinationPath '${path.join(runtime, 'python').replace(/'/g, "''")}' -Force`]);
|
||||
|
||||
// AI 内核:和安卓 App 同一份 Python 源码(纯标准库,能直接跑在 Windows 上)
|
||||
log('复制 AI 内核…');
|
||||
copy(path.join(repo, 'android', 'kernel'), path.join(runtime, 'kernel'), (src) => {
|
||||
const name = path.basename(src);
|
||||
if (name === '__pycache__') return false;
|
||||
if (name.endsWith('.pyc')) return false;
|
||||
if (name === 'data') return false; // 内核目录下的开发数据不带进包
|
||||
return true;
|
||||
});
|
||||
|
||||
// 工具目录(内置 .py 工具 + MCP 配置)
|
||||
copy(path.join(repo, 'tools'), path.join(runtime, 'tools'), (src) => {
|
||||
const name = path.basename(src);
|
||||
return name !== '__pycache__' && !name.endsWith('.pyc');
|
||||
});
|
||||
|
||||
// 网页前端(纯静态:index.html + assets + js,由内核直接托管)
|
||||
copy(path.join(repo, 'web'), path.join(runtime, 'web'), (src) => !src.includes('__pycache__'));
|
||||
|
||||
// 2.3 打包版 MCP 配置:文件系统服务的目录指向数据目录,用占位符避免写死路径
|
||||
const mcpPath = path.join(runtime, 'tools', 'mcp.servers.json');
|
||||
if (fs.existsSync(mcpPath)) {
|
||||
const conf = JSON.parse(fs.readFileSync(mcpPath, 'utf8'));
|
||||
|
||||
@@ -65,6 +65,7 @@ import agent_context # noqa: E402
|
||||
import agent_tools # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import defaults # noqa: E402
|
||||
import rule_engine # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
@@ -903,6 +904,95 @@ def main():
|
||||
check("app.py 落库时存了它", "'toolTrace': result.get('toolTrace')" in _app2,
|
||||
"engine 收好了但没存 —— 重启照样没")
|
||||
|
||||
# ---------------------------------------------------------------- 26
|
||||
section("26. 状态管理:用户能直接加/清(AI 只有 grant_status,只能加)")
|
||||
#
|
||||
# ★★ 真机/文档里暴露的缺口:AI 手里**没有任何工具能移除状态**,
|
||||
# 于是 `persistent` 状态一旦挂上就永远下不来、`timed` 的也只能干等。
|
||||
# 用户是规则的主人,[状态数值] 页上必须能直接清掉、也能手动挂一个。
|
||||
#
|
||||
# 这里走的是**真实 HTTP 路径**(`h.call` → `agent_api.handle`),
|
||||
# 不是直接调 `rule_engine.drop_status` —— 直接调的话测的是
|
||||
# "函数逻辑对不对",不是"界面上那个按钮能不能用"。
|
||||
pack = store.create_resource("rulepacks", {
|
||||
"name": "状态测试包",
|
||||
"info": {
|
||||
"stats": [{"name": "好感度", "min": 0, "max": 100}],
|
||||
"statuses": [
|
||||
{"name": "中毒", "kind": "timed", "turns": 3},
|
||||
{"name": "庇佑", "kind": "persistent"},
|
||||
],
|
||||
},
|
||||
"scripts": {},
|
||||
})
|
||||
# 挂到 a1 所在的世界观(规则包挂在**世界观**上,不是智能体 —— §3.6)
|
||||
store.update_resource("worldviews", wv["id"], {"rulePackId": pack["id"]})
|
||||
rule_engine.sync_defs(pack["id"])
|
||||
|
||||
st, pl = h.status, None
|
||||
base = h.call("/api/agents/%s/stats" % a1["id"], "GET")
|
||||
check("状态数值接口能读", base.get("rulePackId") == pack["id"], str(base.get("rulePackId")))
|
||||
check("**带了可加的状态定义**(界面的「加一个」靠它)",
|
||||
[d.get("name") for d in (base.get("statusDefs") or [])] == ["中毒", "庇佑"],
|
||||
str([d.get("name") for d in (base.get("statusDefs") or [])]))
|
||||
check("一开始身上没状态", (base.get("statuses") or []) == [], str(base.get("statuses")))
|
||||
|
||||
# 加一个定时状态
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "addStatus", "name": "中毒"})
|
||||
names_now = [x.get("name") for x in (after.get("statuses") or [])]
|
||||
check("**用户能手动挂状态**", names_now == ["中毒"], str(names_now))
|
||||
check("定时状态带剩余轮数",
|
||||
(after["statuses"][0].get("remaining") or 0) >= 1, str(after["statuses"][0]))
|
||||
|
||||
# 加一个持久状态
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "addStatus", "name": "庇佑"})
|
||||
by_name = {x.get("name"): x for x in (after.get("statuses") or [])}
|
||||
check("持久状态也挂上了", "庇佑" in by_name, str(list(by_name)))
|
||||
check("持久状态记 -1(不会自己过期)",
|
||||
int(by_name["庇佑"].get("remaining") or 0) == -1, str(by_name.get("庇佑")))
|
||||
|
||||
# 清掉一个
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "dropStatus", "name": "中毒"})
|
||||
check("**用户能直接清掉状态**(AI 没这个能力)",
|
||||
[x.get("name") for x in (after.get("statuses") or [])] == ["庇佑"],
|
||||
str([x.get("name") for x in (after.get("statuses") or [])]))
|
||||
|
||||
# 清持久状态(这是之前唯一清不掉的那类)
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "dropStatus", "name": "庇佑"})
|
||||
check("**持久状态也能清掉**", (after.get("statuses") or []) == [],
|
||||
str(after.get("statuses")))
|
||||
|
||||
# 不存在 / 没定义的状态名要报错,不能静默成功
|
||||
h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "addStatus", "name": "不存在的状态"})
|
||||
check("加一个没定义的状态 → 404(不是静默成功)", h.status == 404, str(h.status))
|
||||
|
||||
# 老行为不能被破坏:不带 action 时还是改数值
|
||||
old = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"name": "好感度", "value": 42})
|
||||
check("不带 action 仍然是改数值(老客户端不受影响)",
|
||||
int(next(x for x in old["stats"] if x["name"] == "好感度")["value"]) == 42,
|
||||
str(old.get("stats")))
|
||||
|
||||
# ---- 批量接口(智能体卡片要显示数值)----
|
||||
#
|
||||
# ★ 用户要求「数字界面在智能体卡片里展示」。选择页每张卡片都要显示
|
||||
# 数值/状态,所以需要**一次拿全** —— 一个一个拉 N 次会拖垮列表。
|
||||
allst = h.call("/api/agents/stats", "GET")
|
||||
box = allst.get("stats") or {}
|
||||
check("**批量接口能读**(卡片靠它)", isinstance(box, dict) and len(box) > 0, str(len(box)))
|
||||
check("名单里只有**挂了规则包**的智能体",
|
||||
a1["id"] in box, str(list(box))[:120])
|
||||
one = box.get(a1["id"]) or {}
|
||||
check("批量里带着数值", len(one.get("stats") or []) > 0, str(one.get("stats")))
|
||||
check("批量里带着状态", isinstance(one.get("statuses"), list), str(one.get("statuses")))
|
||||
check("**批量不带 statusDefs**(卡片用不上,白传一遍费流量)",
|
||||
"statusDefs" not in one, str(list(one))[:120])
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
155
scripts/probe-doubao-web-metrics.mjs
Normal file
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 精测豆包网页版布局:有效 CSS 变量、组件尺寸/间距、字体。
|
||||
* 结果写到 reference/doubao-web-mirror/styles/metrics.json
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO = path.resolve(HERE, '..');
|
||||
const OUT = path.join(REPO, 'reference', 'doubao-web-mirror');
|
||||
const EDGE = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
|
||||
const PORT = 9613;
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const child = spawn(EDGE, ['--headless=new', '--no-sandbox', '--disable-gpu', '--disable-crash-reporter', '--no-first-run',
|
||||
'--disable-extensions', '--hide-scrollbars', `--remote-debugging-port=${PORT}`,
|
||||
`--user-data-dir=${path.join(os.tmpdir(), 'doubao-scrape-profile')}`, '--window-size=1440,900', 'about:blank'],
|
||||
{ stdio: 'ignore', windowsHide: true });
|
||||
|
||||
async function findPage() {
|
||||
for (let i = 0; i < 80; i += 1) {
|
||||
try {
|
||||
const list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
|
||||
const page = list.find((t) => t.type === 'page');
|
||||
if (page?.webSocketDebuggerUrl) return page;
|
||||
} catch { /* not up */ }
|
||||
await sleep(300);
|
||||
}
|
||||
throw new Error('CDP 连不上');
|
||||
}
|
||||
function connect(wsUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('open', () => resolve({
|
||||
send(method, params = {}) {
|
||||
const msgId = ++id;
|
||||
ws.send(JSON.stringify({ id: msgId, method, params }));
|
||||
return new Promise((res, rej) => pending.set(msgId, { res, rej }));
|
||||
},
|
||||
close() { ws.close(); },
|
||||
}));
|
||||
ws.addEventListener('error', reject);
|
||||
ws.addEventListener('message', (ev) => {
|
||||
const msg = JSON.parse(ev.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { res, rej } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? rej(new Error(JSON.stringify(msg.error))) : res(msg.result);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const page = await findPage();
|
||||
const cdp = await connect(page.webSocketDebuggerUrl);
|
||||
await cdp.send('Page.enable');
|
||||
await cdp.send('Runtime.enable');
|
||||
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
|
||||
await cdp.send('Page.navigate', { url: 'https://www.doubao.com/chat/' });
|
||||
await sleep(15000);
|
||||
|
||||
const expr = `(() => {
|
||||
const pick = (el) => {
|
||||
if (!el) return null;
|
||||
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
|
||||
return {
|
||||
tag: el.tagName, cls: String(el.className).slice(0, 90),
|
||||
text: (el.innerText || '').trim().replace(/\\n/g, ' / ').slice(0, 40),
|
||||
rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
|
||||
bg: s.backgroundColor, color: s.color, fs: s.fontSize, fw: s.fontWeight, lh: s.lineHeight,
|
||||
ls: s.letterSpacing, br: s.borderRadius, border: s.border, shadow: s.boxShadow, pad: s.padding,
|
||||
gap: s.gap, display: s.display, align: s.alignItems, justify: s.justifyContent,
|
||||
};
|
||||
};
|
||||
const q = (sel) => document.querySelector(sel);
|
||||
const byText = (needle, tag) => [...document.querySelectorAll(tag || '*')].reverse()
|
||||
.find((el) => (el.innerText || '').trim() === needle);
|
||||
const root = document.documentElement;
|
||||
const cs = getComputedStyle(root);
|
||||
const names = ['--dbx-text-primary','--dbx-text-secondary','--dbx-text-tertiary','--dbx-text-disable',
|
||||
'--dbx-bg-body-web','--dbx-bg-base-web','--dbx-bg-base-1','--dbx-bg-base-2','--dbx-bg-base-3','--dbx-bg-float',
|
||||
'--dbx-color-blue-100','--dbx-color-blue-400','--dbx-color-blue-500','--dbx-color-blue-600',
|
||||
'--dbx-line-primary','--dbx-line-secondary','--dbx-border-primary','--dbx-static-white',
|
||||
'--dbx-neutral-700','--dbx-neutral-1000-8','--dbx-fill-primary-50','--dbx-function-danger','--dbx-function-success',
|
||||
'--dbx-fill-secondary','--dbx-fill-tertiary','--dbx-fill-quaternary','--dbx-brand-primary','--dbx-brand-blue'];
|
||||
const vars = {};
|
||||
for (const n of names) { const v = cs.getPropertyValue(n).trim(); if (v) vars[n] = v; }
|
||||
const out = { vars, elements: {} };
|
||||
const aside = q('aside') || q('nav');
|
||||
out.elements.sidebar = pick(aside ? aside.parentElement : null);
|
||||
out.elements.sidebarPanel = pick(aside);
|
||||
out.elements.brand = pick(byText('豆包', 'div') || byText('豆包', 'span'));
|
||||
const navTexts = ['新工作任务', '新对话', '项目', 'API 服务', '更多'];
|
||||
out.elements.navItems = {};
|
||||
for (const t of navTexts) {
|
||||
const label = [...document.querySelectorAll('div,span')].find((el) => (el.innerText || '').trim() === t);
|
||||
if (!label) continue;
|
||||
let row = label;
|
||||
for (let i = 0; i < 4 && row.parentElement; i += 1) row = row.parentElement;
|
||||
out.elements.navItems[t] = { label: pick(label), row: pick(row) };
|
||||
}
|
||||
out.elements.greeting = pick(byText('有什么我能帮你的吗?', 'div'));
|
||||
const chips = [...document.querySelectorAll('div')].filter((el) => /一吨100元|一万步|欧元|胃真的/.test(el.innerText || '') );
|
||||
const chip = chips.filter((el) => { const r = el.getBoundingClientRect(); return r.width > 100 && r.height > 20 && r.height < 80; })
|
||||
.sort((a, b) => a.getBoundingClientRect().height - b.getBoundingClientRect().height)[0];
|
||||
out.elements.recommendChip = pick(chip);
|
||||
out.elements.recommendLabel = pick(byText('为你推荐', 'div') || byText('为你推荐', 'span'));
|
||||
const ta = q('textarea');
|
||||
out.elements.textarea = pick(ta);
|
||||
if (ta) {
|
||||
let box = ta;
|
||||
for (let i = 0; i < 6 && box.parentElement; i += 1) box = box.parentElement;
|
||||
out.elements.inputWrap = pick(box);
|
||||
// 输入框最外层:找有较大圆角和边框的祖先
|
||||
let cur = ta; const chain = [];
|
||||
for (let i = 0; i < 10 && cur; i += 1) { chain.push(pick(cur)); cur = cur.parentElement; }
|
||||
out.elements.inputChain = chain;
|
||||
}
|
||||
// 顶部工具条
|
||||
const collapseBtn = [...document.querySelectorAll('button,div')].find((el) => el.getBoundingClientRect().x > 280 && el.getBoundingClientRect().x < 330 && el.getBoundingClientRect().y < 80 && el.getBoundingClientRect().y > 0);
|
||||
out.elements.topCollapseIcon = pick(collapseBtn);
|
||||
const loginBtn = byText('登录', 'button') || byText('登录', 'div');
|
||||
out.elements.loginBtn = pick(loginBtn);
|
||||
// 字体
|
||||
out.fonts = [];
|
||||
for (const sheet of document.styleSheets) {
|
||||
try { for (const rule of sheet.cssRules) if (rule instanceof CSSFontFaceRule) out.fonts.push(rule.cssText.slice(0, 400)); } catch { /* */ }
|
||||
}
|
||||
out.bodyFont = getComputedStyle(document.body).fontFamily.slice(0, 120);
|
||||
out.bodyBg = getComputedStyle(document.body).backgroundColor;
|
||||
out.mainBg = pick(document.querySelector('main'));
|
||||
return JSON.stringify(out);
|
||||
})()`;
|
||||
|
||||
const r = await cdp.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true });
|
||||
const value = r.result?.value || '{}';
|
||||
fs.writeFileSync(path.join(OUT, 'styles', 'metrics.json'), value, 'utf8');
|
||||
try {
|
||||
const j = JSON.parse(value);
|
||||
console.log('vars:', Object.keys(j.vars || {}).length, '| navItems:', Object.keys(j.elements?.navItems || {}).length, '| fonts:', (j.fonts || []).length);
|
||||
console.log(JSON.stringify(j.vars, null, 1));
|
||||
for (const [k, v] of Object.entries(j.elements || {})) {
|
||||
if (k === 'navItems' || k === 'inputChain') continue;
|
||||
console.log(k, JSON.stringify(v));
|
||||
}
|
||||
} catch (e) { console.log('raw:', value.slice(0, 2000)); }
|
||||
cdp.close();
|
||||
child.kill();
|
||||
await sleep(300);
|
||||
process.exit(0);
|
||||
@@ -102,8 +102,14 @@ def main():
|
||||
participants=[a['id']])
|
||||
check("能加成员", G.add_member(c2, b['id']) is True)
|
||||
check("重复加返回 False(不重复不报错)", G.add_member(c2, b['id']) is False)
|
||||
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, a['id']) is False)
|
||||
check("普通成员能移出", G.remove_member(c2, b['id']) is True)
|
||||
# ★ 语义变了(用户要求「群聊去掉主人设定」):现在**谁都能移出**,
|
||||
# 唯一的拒绝条件是"不能删到一个人都不剩"。所以原来那条
|
||||
# "主智能体不能被移出" 已经废了 —— 断言跟着改。
|
||||
check("第一个人也能移出(没有主人这回事了)", G.remove_member(c2, a['id']) is True)
|
||||
check("删到剩一个 → 退回单聊",
|
||||
not G.is_group(c2) and len(G.member_ids(c2)) == 1,
|
||||
f"type={c2.get('type')} participants={G.member_ids(c2)}")
|
||||
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, b['id']) is False)
|
||||
# 单聊拉人 → 转成群聊
|
||||
single = store.create_conversation('单聊', agent_id=a['id'])
|
||||
check("单聊不是群聊", not G.is_group(single))
|
||||
@@ -128,14 +134,18 @@ def main():
|
||||
except ValueError as exc:
|
||||
check("拉自己被拒", '自己' in str(exc), str(exc))
|
||||
# 需确认模式:不直接拉人,让 AI 去问
|
||||
before_ids = sorted(G.member_ids(store.get_conversation(c2['id']) or {}))
|
||||
store.update_agent(a['id'], {'inviteMode': 'confirm'})
|
||||
a2 = store.get_agent(a['id'])
|
||||
tools_runtime.push_context(agentId=a2['id'], conversationId=c2['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("**需确认模式不直接拉人**", r.get('needConfirm') is True, str(r))
|
||||
check("需确认模式下人**没有**进群",
|
||||
b['id'] not in G.member_ids(store.get_conversation(c2['id']) or {}),
|
||||
str(G.member_ids(store.get_conversation(c2['id']) or {})))
|
||||
# ★ 这里**不能**用"仙辰不在群里"来验证:`c2` 经过上面的增删只剩 `b`,
|
||||
# 而"仙辰"就是 `b` —— 他本来就在。改成验证**成员列表一点没变**
|
||||
# (这才是"没直接拉人"的正确判据,对任何初始状态都成立)。
|
||||
check("需确认模式下成员一点没变",
|
||||
sorted(G.member_ids(store.get_conversation(c2['id']) or {})) == sorted(before_ids),
|
||||
f"{before_ids} vs {G.member_ids(store.get_conversation(c2['id']) or {})}")
|
||||
check("提示 AI 去问用户", '问' in str(r.get('note')), str(r.get('note')))
|
||||
# 静默模式:直接拉
|
||||
store.update_agent(a['id'], {'inviteMode': 'silent'})
|
||||
|
||||
325
scripts/scrape-doubao-web.mjs
Normal file
@@ -0,0 +1,325 @@
|
||||
/**
|
||||
* 扒豆包网页版 v2:不靠 CDP 取 body(会被驱逐),改用性能条目列表 + Node fetch 下载。
|
||||
* 产出:截图、渲染后 DOM、离线副本、计算样式、内联 CSS、图标 SVG、全部 CDN 资源、MHTML。
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO = path.resolve(HERE, '..');
|
||||
// 抓下来的参考镜像不入库(第三方资源),见 .gitignore
|
||||
const OUT = path.join(REPO, 'reference', 'doubao-web-mirror');
|
||||
const EDGE = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
|
||||
const PORT = 9612;
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
fs.rmSync(OUT, { recursive: true, force: true });
|
||||
for (const d of ['screenshots', 'dom', 'styles', 'icons', 'assets', 'inline']) {
|
||||
fs.mkdirSync(path.join(OUT, d), { recursive: true });
|
||||
}
|
||||
|
||||
const child = spawn(EDGE, [
|
||||
'--headless=new', '--no-sandbox', '--disable-gpu', '--disable-crash-reporter',
|
||||
'--no-first-run', '--disable-extensions', '--hide-scrollbars',
|
||||
`--remote-debugging-port=${PORT}`,
|
||||
`--user-data-dir=${path.join(os.tmpdir(), 'doubao-scrape-profile')}`,
|
||||
'--window-size=1440,900',
|
||||
'about:blank',
|
||||
], { stdio: 'ignore', windowsHide: true });
|
||||
|
||||
async function findPage() {
|
||||
for (let i = 0; i < 80; i += 1) {
|
||||
try {
|
||||
const list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
|
||||
const page = list.find((t) => t.type === 'page');
|
||||
if (page?.webSocketDebuggerUrl) return page;
|
||||
} catch { /* not up */ }
|
||||
await sleep(300);
|
||||
}
|
||||
throw new Error('CDP 连不上');
|
||||
}
|
||||
|
||||
function connect(wsUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const handlers = [];
|
||||
ws.addEventListener('open', () => resolve({
|
||||
send(method, params = {}) {
|
||||
const msgId = ++id;
|
||||
ws.send(JSON.stringify({ id: msgId, method, params }));
|
||||
return new Promise((res, rej) => pending.set(msgId, { res, rej }));
|
||||
},
|
||||
on(fn) { handlers.push(fn); },
|
||||
close() { ws.close(); },
|
||||
}));
|
||||
ws.addEventListener('error', reject);
|
||||
ws.addEventListener('message', (ev) => {
|
||||
const msg = JSON.parse(ev.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { res, rej } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? rej(new Error(JSON.stringify(msg.error))) : res(msg.result);
|
||||
} else if (msg.method) {
|
||||
for (const fn of handlers) fn(msg);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const evaluate = async (expression) => {
|
||||
const r = await cdp.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
|
||||
return r.result?.value;
|
||||
};
|
||||
const shoot = async (name) => {
|
||||
const shot = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
||||
fs.writeFileSync(path.join(OUT, 'screenshots', name), Buffer.from(shot.data, 'base64'));
|
||||
console.log('[scrape] 截图', name);
|
||||
};
|
||||
const click = async (x, y) => {
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
|
||||
await sleep(70);
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
|
||||
await sleep(700);
|
||||
};
|
||||
|
||||
const page = await findPage();
|
||||
const cdp = await connect(page.webSocketDebuggerUrl);
|
||||
const consoleLines = [];
|
||||
cdp.on((msg) => {
|
||||
if (msg.method === 'Runtime.consoleAPICalled') {
|
||||
consoleLines.push('[console.' + msg.params.type + '] ' + (msg.params.args || []).map((a) => a.value ?? a.description ?? a.type).join(' ').slice(0, 500));
|
||||
}
|
||||
if (msg.method === 'Runtime.exceptionThrown') {
|
||||
consoleLines.push('[exception] ' + JSON.stringify(msg.params.exceptionDetails).slice(0, 800));
|
||||
}
|
||||
});
|
||||
|
||||
await cdp.send('Page.enable');
|
||||
await cdp.send('Runtime.enable');
|
||||
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
|
||||
await cdp.send('Page.navigate', { url: 'https://www.doubao.com/chat/' });
|
||||
console.log('[scrape] 导航完成,等渲染…');
|
||||
await sleep(16000);
|
||||
|
||||
// 1) 关弹窗
|
||||
const dismissed = await evaluate(`(() => {
|
||||
const btns = [...document.querySelectorAll('button,div,span')].filter((el) => {
|
||||
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
|
||||
return r.width > 10 && r.width < 60 && r.height > 10 && r.height < 60 && (s.cursor === 'pointer' || el.tagName === 'BUTTON');
|
||||
});
|
||||
const x = btns.find((el) => { const r = el.getBoundingClientRect(); return r.x > 1000 && r.x < 1200 && r.y > 150 && r.y < 280; });
|
||||
if (x) { x.click(); return 'clicked at ' + Math.round(x.getBoundingClientRect().x) + ',' + Math.round(x.getBoundingClientRect().y); }
|
||||
return 'no-modal';
|
||||
})()`);
|
||||
console.log('[scrape] 弹窗:', dismissed);
|
||||
await sleep(2000);
|
||||
await shoot('01-empty-chat-1440x900.png');
|
||||
|
||||
// 2) 点输入框、输入一句话,看有内容时的发送按钮
|
||||
await click(860, 813);
|
||||
await cdp.send('Input.insertText', { text: '帮我写一段产品介绍' });
|
||||
await sleep(800);
|
||||
await shoot('02-input-filled.png');
|
||||
await evaluate(`(() => { const ta = document.querySelector('textarea'); if (ta) { ta.value=''; ta.dispatchEvent(new Event('input', {bubbles:true})); } document.activeElement && document.activeElement.blur(); return 1; })()`);
|
||||
await sleep(600);
|
||||
|
||||
// 3) 切到「工作」页签看看
|
||||
const seg = await evaluate(`(() => {
|
||||
const els = [...document.querySelectorAll('div,span,button')].filter((el) => (el.innerText||'').trim() === '工作');
|
||||
const el = els[els.length - 1];
|
||||
if (!el) return null;
|
||||
const r = el.getBoundingClientRect();
|
||||
return [Math.round(r.x + r.width/2), Math.round(r.y + r.height/2)];
|
||||
})()`);
|
||||
if (seg) { await click(seg[0], seg[1]); await sleep(1500); await shoot('03-work-tab.png'); }
|
||||
|
||||
// 4) 回「对话」
|
||||
const seg2 = await evaluate(`(() => {
|
||||
const els = [...document.querySelectorAll('div,span,button')].filter((el) => (el.innerText||'').trim() === '对话');
|
||||
const el = els[els.length - 1];
|
||||
if (!el) return null;
|
||||
const r = el.getBoundingClientRect();
|
||||
return [Math.round(r.x + r.width/2), Math.round(r.y + r.height/2)];
|
||||
})()`);
|
||||
if (seg2) { await click(seg2[0], seg2[1]); await sleep(1200); }
|
||||
|
||||
// 5) 收集:DOM / 性能资源 / 计算样式 / 内联 CSS / 图标 SVG / CSS 变量
|
||||
const domHtml = await evaluate(`'<!doctype html>\\n' + document.documentElement.outerHTML`);
|
||||
fs.writeFileSync(path.join(OUT, 'dom', 'page.rendered.html'), domHtml, 'utf8');
|
||||
console.log('[scrape] 渲染后 DOM:', (domHtml.length / 1024).toFixed(0), 'KB');
|
||||
|
||||
const resources = await evaluate(`JSON.stringify(performance.getEntriesByType('resource').map((e) => ({ name: e.name, type: e.initiatorType, size: e.transferSize || 0 })))`);
|
||||
const resList = JSON.parse(resources || '[]');
|
||||
fs.writeFileSync(path.join(OUT, 'styles', 'resource-urls.json'), JSON.stringify(resList, null, 2), 'utf8');
|
||||
console.log('[scrape] 性能条目资源数:', resList.length);
|
||||
|
||||
const computed = await evaluate(`(() => {
|
||||
const pick = (el) => {
|
||||
if (!el) return null;
|
||||
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
|
||||
return {
|
||||
tag: el.tagName, cls: String(el.className).slice(0, 120),
|
||||
text: (el.innerText || '').trim().slice(0, 50),
|
||||
rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
|
||||
bg: s.backgroundColor, color: s.color, fs: s.fontSize, fw: s.fontWeight, lh: s.lineHeight,
|
||||
br: s.borderRadius, border: s.border, shadow: s.boxShadow, pad: s.padding,
|
||||
gap: s.gap, display: s.display, font: s.fontFamily.slice(0, 90),
|
||||
};
|
||||
};
|
||||
const at = (x, y) => document.elementFromPoint(x, y);
|
||||
const byText = (needle, tag = '*') => [...document.querySelectorAll(tag)].reverse().find((el) => (el.innerText || '').trim().includes(needle));
|
||||
const out = {
|
||||
viewport: { w: innerWidth, h: innerHeight, dpr: devicePixelRatio },
|
||||
sidebar: pick(at(10, 300)),
|
||||
sidebarBrand: pick(byText('豆包', 'div')),
|
||||
sidebarNavItem: pick(byText('新对话', 'div')),
|
||||
greeting: pick(byText('有什么我能帮你的吗', 'h1,div,span,p')),
|
||||
segmented: pick(byText('对话', 'div')),
|
||||
inputBox: pick(at(860, 813)),
|
||||
recommendChip: pick(byText('一吨100元', 'div')),
|
||||
sendButton: pick(at(1390, 815)),
|
||||
};
|
||||
const vars = {};
|
||||
for (const sheet of document.styleSheets) {
|
||||
try {
|
||||
for (const rule of sheet.cssRules) {
|
||||
if (rule.style && rule.selectorText && /:root|data-theme/.test(rule.selectorText)) {
|
||||
for (const name of rule.style) {
|
||||
if (name.startsWith('--dbx-') || name.startsWith('--s-') || name.startsWith('--g-')) {
|
||||
const val = rule.style.getPropertyValue(name).trim();
|
||||
if (val) vars[name] = (name in vars ? vars[name] + ' | ' : '') + val;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch { /* 跨域 CSSOM */ }
|
||||
}
|
||||
out.cssVars = vars;
|
||||
return JSON.stringify(out);
|
||||
})()`);
|
||||
fs.writeFileSync(path.join(OUT, 'styles', 'computed-styles.json'), computed || '{}', 'utf8');
|
||||
console.log('[scrape] 计算样式 + CSS 变量已存');
|
||||
|
||||
const tree = await evaluate(`(() => {
|
||||
const lines = [];
|
||||
const walk = (el, depth, maxDepth) => {
|
||||
if (!el || depth > maxDepth) return;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.width < 2 || r.height < 2) return;
|
||||
const s = getComputedStyle(el);
|
||||
const cls = typeof el.className === 'string' ? el.className.trim().split(/\\s+/).slice(0, 3).join('.') : '';
|
||||
const label = (el.innerText || '').trim().split('\\n')[0].slice(0, 34);
|
||||
lines.push(' '.repeat(depth) + el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (cls ? '.' + cls : '')
|
||||
+ ' [' + Math.round(r.x) + ',' + Math.round(r.y) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + ']'
|
||||
+ (s.backgroundColor !== 'rgba(0, 0, 0, 0)' ? ' bg=' + s.backgroundColor : '')
|
||||
+ (s.color !== 'rgb(0, 0, 0)' ? ' c=' + s.color : '')
|
||||
+ (label ? ' «' + label + '»' : ''));
|
||||
if (depth < maxDepth) for (const c of el.children) walk(c, depth + 1, maxDepth);
|
||||
};
|
||||
walk(document.body, 0, 8);
|
||||
return lines.join('\\n');
|
||||
})()`);
|
||||
fs.writeFileSync(path.join(OUT, 'dom', 'dom-tree.txt'), tree || '', 'utf8');
|
||||
|
||||
const inline = await evaluate(`JSON.stringify([...document.querySelectorAll('style')].map((s) => s.textContent))`);
|
||||
fs.writeFileSync(path.join(OUT, 'inline', 'inline-styles.json'), inline || '[]', 'utf8');
|
||||
|
||||
const svgs = await evaluate(`JSON.stringify([...document.querySelectorAll('svg')].map((s) => s.outerHTML))`);
|
||||
const svgList = JSON.parse(svgs || '[]');
|
||||
const seen = new Set();
|
||||
let svgIdx = 0;
|
||||
for (const svg of svgList) {
|
||||
const compact = svg.replace(/\s+/g, ' ').trim();
|
||||
if (seen.has(compact)) continue;
|
||||
seen.add(compact);
|
||||
svgIdx += 1;
|
||||
fs.writeFileSync(path.join(OUT, 'icons', `svg-${String(svgIdx).padStart(2, '0')}.svg`), svg, 'utf8');
|
||||
}
|
||||
console.log('[scrape] 图标 SVG 去重后:', svgIdx, '个');
|
||||
|
||||
// MHTML
|
||||
try {
|
||||
const mhtml = await cdp.send('Page.captureSnapshot', { format: 'mhtml' });
|
||||
fs.writeFileSync(path.join(OUT, 'page.mhtml'), mhtml.data, 'utf8');
|
||||
console.log('[scrape] MHTML 已存:', (fs.statSync(path.join(OUT, 'page.mhtml')).size / 1048576).toFixed(1), 'MB');
|
||||
} catch (err) { console.warn('[scrape] MHTML 失败:', err.message); }
|
||||
|
||||
// 6) 用 Node 拉全部 CDN 资源
|
||||
const safeName = (url) => {
|
||||
const u = new URL(url);
|
||||
let p = decodeURIComponent(u.pathname);
|
||||
if (p.endsWith('/')) p += 'index.html';
|
||||
const base = path.posix.basename(p) || 'file';
|
||||
const dir = path.posix.dirname(p).replace(/(^|\/)\.\.?(\/|$)/g, '/');
|
||||
const hash = Array.from(url).reduce((a, c) => ((a * 31 + c.charCodeAt(0)) | 0), 7).toString(36).slice(-6);
|
||||
return path.posix.join('assets', dir.replace(/^\/+/, ''), `${hash}-${base.includes('.') ? base : base + '.bin'}`);
|
||||
};
|
||||
const localMap = new Map();
|
||||
const manifest = { capturedAt: new Date().toISOString(), pageUrl: 'https://www.doubao.com/chat/', resources: [] };
|
||||
const skipRe = /\/(api|mon|mcs|sami|bym|log|tracker|collect|slardar|apm|webmssdk)\b|\.gif($|\?)|googletagmanager|google-analytics|doubleclick/;
|
||||
for (const res of resList) {
|
||||
const url = res.name;
|
||||
const entry = { url, type: res.type, size: res.size, local: null, error: null };
|
||||
if (!/^https?:/.test(url) || skipRe.test(url)) { manifest.resources.push(entry); continue; }
|
||||
try {
|
||||
const resp = await fetch(url, {
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',
|
||||
Referer: 'https://www.doubao.com/chat/',
|
||||
Origin: 'https://www.doubao.com',
|
||||
},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
if (!resp.ok) throw new Error('HTTP ' + resp.status);
|
||||
const buf = Buffer.from(await resp.arrayBuffer());
|
||||
const rel = safeName(url);
|
||||
fs.mkdirSync(path.dirname(path.join(OUT, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(OUT, rel), buf);
|
||||
localMap.set(url, rel);
|
||||
entry.local = rel;
|
||||
entry.size = buf.length;
|
||||
console.log('[scrape] 下载', (buf.length / 1024).toFixed(0) + 'KB', url.slice(0, 110));
|
||||
} catch (err) {
|
||||
entry.error = String(err.message || err).slice(0, 120);
|
||||
}
|
||||
manifest.resources.push(entry);
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf8');
|
||||
console.log('[scrape] 资源下载完成:', localMap.size, '个');
|
||||
|
||||
// 7) 生成离线副本:绝对 URL → 本地相对路径
|
||||
let offline = domHtml;
|
||||
for (const [url, rel] of localMap) {
|
||||
if (!offline.includes(url)) continue;
|
||||
offline = offline.split(url).join(rel);
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'dom', 'page.offline.html'), offline, 'utf8');
|
||||
// 把 CSS 里的 url() 也换成相对路径
|
||||
let cssFixed = 0;
|
||||
for (const [url, rel] of localMap) {
|
||||
if (!rel.endsWith('.css')) continue;
|
||||
const abs = path.join(OUT, rel);
|
||||
let css = fs.readFileSync(abs, 'utf8');
|
||||
let touched = false;
|
||||
for (const [assetUrl, assetRel] of localMap) {
|
||||
if (!css.includes(assetUrl)) continue;
|
||||
const relFromCss = path.posix.relative(path.posix.dirname(rel), assetRel);
|
||||
css = css.split(assetUrl).join(relFromCss);
|
||||
touched = true;
|
||||
}
|
||||
if (touched) { fs.writeFileSync(abs, css, 'utf8'); cssFixed += 1; }
|
||||
}
|
||||
console.log('[scrape] 离线副本重写完成,CSS 修', cssFixed, '个');
|
||||
fs.writeFileSync(path.join(OUT, 'console.log'), consoleLines.join('\n'), 'utf8');
|
||||
|
||||
console.log('[scrape] ✅ 完成 →', OUT);
|
||||
cdp.close();
|
||||
child.kill();
|
||||
await sleep(500);
|
||||
process.exit(0);
|
||||
60
scripts/start-web.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 本地起网页版(浏览器里用):直接用和安卓 App 同一份 Python 内核托管 web/。
|
||||
*
|
||||
* npm start # http://127.0.0.1:5199/
|
||||
* PORT=5300 npm start # 换端口
|
||||
* DOUBAO_PYTHON=... npm start # 指定 Python 解释器
|
||||
*
|
||||
* 为什么不用 npm 包 / 不引第三方:内核就是纯标准库,起服务 = 跑 main.py。
|
||||
* 唯一的依赖是电脑上有 Python 3.10+(内核用了 `str | None` 语法)。
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repo = path.resolve(here, '..');
|
||||
|
||||
const python = process.env.DOUBAO_PYTHON || 'python';
|
||||
const port = process.env.PORT || process.env.DOUBAO_PORT || '5199';
|
||||
const dataDir = process.env.DOUBAO_DATA || path.join(repo, 'data');
|
||||
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
|
||||
const args = [
|
||||
path.join(repo, 'android', 'kernel', 'main.py'),
|
||||
'--port', String(port),
|
||||
'--data-dir', dataDir,
|
||||
'--tools-dir', path.join(repo, 'tools'),
|
||||
'--web-dir', path.join(repo, 'web'),
|
||||
];
|
||||
|
||||
console.log(`[web] Python: ${python}`);
|
||||
console.log(`[web] 数据目录: ${dataDir}`);
|
||||
console.log(`[web] 启动内核:http://127.0.0.1:${port}/`);
|
||||
console.log('[web] 浏览器打开上面这个地址即可;Ctrl+C 停止。');
|
||||
|
||||
const child = spawn(python, args, {
|
||||
cwd: repo,
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' },
|
||||
});
|
||||
|
||||
child.on('error', (err) => {
|
||||
if (err && err.code === 'ENOENT') {
|
||||
console.error('\n找不到 Python。请安装 Python 3.10+,或用 DOUBAO_PYTHON 指定解释器路径。');
|
||||
console.error('(打包好的 exe 自带 Python,不需要这一步)');
|
||||
} else {
|
||||
console.error('[web] 启动失败:', err);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
child.on('exit', (code) => process.exit(code == null ? 0 : code));
|
||||
|
||||
for (const sig of ['SIGINT', 'SIGTERM']) {
|
||||
process.on(sig, () => {
|
||||
try { child.kill(sig); } catch { /* ignore */ }
|
||||
});
|
||||
}
|
||||
198
scripts/verify-ui-bridge.mjs
Normal file
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* 界面能力通道验收(电脑/网页端):show_ui / ask_user / end_conversation 走
|
||||
* 内核的 HTTP 队列(/api/device/pending + /api/device/answer)能不能跑通。
|
||||
*
|
||||
* node scripts/verify-ui-bridge.mjs
|
||||
*
|
||||
* 它会自己起一个临时内核(独立数据目录、随机端口),不需要浏览器。
|
||||
* 覆盖:
|
||||
* 1. ask_user:工具阻塞 → 网页取请求 → 回答 → 工具拿到 choice
|
||||
* 2. show_ui wait=false:保存到 /api/screens + 通知队列里能拿到界面
|
||||
* 3. show_ui wait=true:阻塞 → 回答 value → 工具拿到 value
|
||||
* 4. end_conversation:会话被落盘标记 ended(不再需要网页参与)
|
||||
* 5. 错误路径:给不存在的请求 id 回答要 404
|
||||
*/
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import path from 'node:path';
|
||||
|
||||
const REPO = path.resolve(import.meta.dirname, '..');
|
||||
const DATA = path.join(REPO, '.tmp-verify-device');
|
||||
const python = process.env.DOUBAO_PYTHON || 'python';
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
let failures = 0;
|
||||
function check(name, ok, extra = '') {
|
||||
console.log(`${ok ? '✅' : '❌'} ${name}${extra ? ` ${extra}` : ''}`);
|
||||
if (!ok) failures += 1;
|
||||
}
|
||||
|
||||
function freePort(start) {
|
||||
return new Promise((resolve) => {
|
||||
const tryPort = (p) => {
|
||||
const srv = net.createServer();
|
||||
srv.once('error', () => tryPort(p + 1));
|
||||
srv.once('listening', () => srv.close(() => resolve(p)));
|
||||
srv.listen(p, '127.0.0.1');
|
||||
};
|
||||
tryPort(start);
|
||||
});
|
||||
}
|
||||
|
||||
async function startKernel() {
|
||||
fs.rmSync(DATA, { recursive: true, force: true });
|
||||
fs.mkdirSync(DATA, { recursive: true });
|
||||
const port = await freePort(5390);
|
||||
const child = spawn(python, [
|
||||
path.join(REPO, 'android', 'kernel', 'main.py'),
|
||||
'--port', String(port),
|
||||
'--data-dir', DATA,
|
||||
'--tools-dir', path.join(REPO, 'tools'),
|
||||
'--web-dir', path.join(REPO, 'web'),
|
||||
'--quiet', '--json', '--no-mcp-autostart',
|
||||
], { cwd: REPO, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });
|
||||
return new Promise((resolve, reject) => {
|
||||
let buf = '';
|
||||
const timer = setTimeout(() => reject(new Error('内核启动超时')), 30000);
|
||||
child.stdout.on('data', (chunk) => {
|
||||
buf += chunk.toString('utf8');
|
||||
for (const line of buf.split('\n')) {
|
||||
if (!line.trim().startsWith('{')) continue;
|
||||
try {
|
||||
const info = JSON.parse(line);
|
||||
if (info.url) { clearTimeout(timer); resolve({ base: info.url.replace(/\/$/, ''), child }); }
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
});
|
||||
child.stderr.on('data', (c) => process.stderr.write(`[kernel] ${c}`));
|
||||
child.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function stopKernel(child) {
|
||||
if (!child) return;
|
||||
try {
|
||||
if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
|
||||
else child.kill('SIGTERM');
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
const j = async (base, method, p, body) => {
|
||||
const res = await fetch(base + p, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const text = await res.text();
|
||||
let json = null;
|
||||
try { json = text ? JSON.parse(text) : null; } catch { /* 非 JSON */ }
|
||||
return { status: res.status, json, text };
|
||||
};
|
||||
|
||||
const waitForRequest = async (base, timeoutMs = 8000) => {
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
const r = await j(base, 'GET', '/api/device/pending');
|
||||
if (r.json && r.json.request) return r.json.request;
|
||||
await sleep(120);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
let kernel = null;
|
||||
try {
|
||||
kernel = await startKernel();
|
||||
const { base } = kernel;
|
||||
console.log(`[verify] 内核:${base}`);
|
||||
|
||||
// 打开界面工具(默认是关的)
|
||||
const st0 = await j(base, 'GET', '/api/state');
|
||||
await j(base, 'PUT', '/api/settings', { uiTools: { ...(st0.json.settings.uiTools || {}), enabled: true } });
|
||||
|
||||
// 建一个会话(end_conversation 要用)
|
||||
const convRes = await j(base, 'POST', '/api/conversations', { title: '界面能力测试' });
|
||||
const convId = convRes.json.conversation.id;
|
||||
|
||||
/* ---------------- 1. ask_user ---------------- */
|
||||
const askPromise = j(base, 'POST', '/api/tools/run', {
|
||||
name: 'ask_user',
|
||||
conversationId: convId,
|
||||
args: { question: '你要选哪个?', options: [{ label: '方案 A', value: 'A' }, { label: '方案 B', value: 'B' }] },
|
||||
});
|
||||
const askReq = await waitForRequest(base);
|
||||
check('ask_user 请求到了网页通道', !!askReq && askReq.action === 'ui_dialog',
|
||||
askReq ? `${askReq.question} / ${(askReq.options || []).length} 个选项` : '没等到请求');
|
||||
if (askReq) {
|
||||
const ans = await j(base, 'POST', '/api/device/answer', {
|
||||
id: askReq.id,
|
||||
result: { choice: 'B', values: ['B'], cancelled: false, multiple: false },
|
||||
});
|
||||
check('ask_user 回答被接收', ans.status === 200 && ans.json.ok === true);
|
||||
}
|
||||
const askOut = await askPromise;
|
||||
check('ask_user 工具拿到用户选择', askOut.json && askOut.json.ok !== false
|
||||
&& askOut.json.result && askOut.json.result.choice === 'B',
|
||||
JSON.stringify((askOut.json && askOut.json.result) || askOut.json).slice(0, 160));
|
||||
|
||||
/* ---------------- 2. show_ui wait=false ---------------- */
|
||||
const screenHtml = '<h2>测试界面</h2><button data-doubao-result="点我">点我</button>';
|
||||
const showOut = await j(base, 'POST', '/api/tools/run', {
|
||||
name: 'show_ui',
|
||||
conversationId: convId,
|
||||
args: { html: screenHtml, title: '测试界面', wait: false },
|
||||
});
|
||||
const shownResult = (showOut.json && showOut.json.result) || {};
|
||||
check('show_ui(wait=false) 立即返回并带 screenId', !!shownResult.screenId, JSON.stringify(shownResult).slice(0, 140));
|
||||
const notifyReq = await waitForRequest(base);
|
||||
check('show_ui(wait=false) 进了通知队列', !!notifyReq && notifyReq.action === 'ui_screen' && notifyReq.notify === true);
|
||||
const screens = await j(base, 'GET', '/api/screens');
|
||||
check('show_ui 的界面落盘了(/api/screens 能列出来)',
|
||||
(screens.json.screens || []).some((s) => s.id === shownResult.screenId));
|
||||
|
||||
/* ---------------- 3. show_ui wait=true ---------------- */
|
||||
const waitPromise = j(base, 'POST', '/api/tools/run', {
|
||||
name: 'show_ui',
|
||||
conversationId: convId,
|
||||
args: { html: '<button data-doubao-result="蓝色">蓝色</button>', title: '等选择', wait: true },
|
||||
});
|
||||
const waitReq = await waitForRequest(base);
|
||||
check('show_ui(wait=true) 请求到了网页通道', !!waitReq && waitReq.action === 'ui_screen' && waitReq.wait === true);
|
||||
if (waitReq) {
|
||||
await j(base, 'POST', '/api/device/answer', {
|
||||
id: waitReq.id, result: { value: '蓝色', closed: false, timeout: false },
|
||||
});
|
||||
}
|
||||
const waitOut = await waitPromise;
|
||||
check('show_ui(wait=true) 工具拿到点选值', (waitOut.json && waitOut.json.result && waitOut.json.result.value) === '蓝色',
|
||||
JSON.stringify((waitOut.json && waitOut.json.result) || waitOut.json).slice(0, 160));
|
||||
|
||||
/* ---------------- 4. end_conversation ---------------- */
|
||||
const endOut = await j(base, 'POST', '/api/tools/run', {
|
||||
name: 'end_conversation',
|
||||
conversationId: convId,
|
||||
args: { reason: '测试结束' },
|
||||
});
|
||||
check('end_conversation 工具返回 ended', (endOut.json && endOut.json.result && endOut.json.result.ended) === true,
|
||||
JSON.stringify((endOut.json && endOut.json.result) || endOut.json).slice(0, 140));
|
||||
const convAfter = await j(base, 'GET', `/api/conversations/${convId}`);
|
||||
const conv = (convAfter.json && convAfter.json.conversation) || {};
|
||||
check('end_conversation 落盘:会话 ended=true', conv.ended === true && conv.endedReason === '测试结束',
|
||||
`ended=${conv.ended} reason=${conv.endedReason}`);
|
||||
|
||||
/* ---------------- 5. 错误路径 ---------------- */
|
||||
const bad = await j(base, 'POST', '/api/device/answer', { id: 'nope', result: { choice: 'x' } });
|
||||
check('给不存在的请求回答要 404', bad.status === 404);
|
||||
} catch (err) {
|
||||
console.error('[verify] 失败:', err);
|
||||
failures += 1;
|
||||
} finally {
|
||||
stopKernel(kernel && kernel.child);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
if (failures) {
|
||||
console.log(`[verify] ❌ ${failures} 项失败`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('[verify] ✅ 界面能力通道全部通过');
|
||||
131
scripts/verify-web-ui.mjs
Normal file
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* 网页版验收:起一个临时内核(独立数据目录),逐页截图 + 收集 JS 报错。
|
||||
*
|
||||
* node scripts/verify-web-ui.mjs # 自己起内核(默认 5199 端口找一个空的)
|
||||
* node scripts/verify-web-ui.mjs --base http://127.0.0.1:5401 # 对着已跑着的内核验
|
||||
*
|
||||
* 产出:.tmp-verify-web/<页面>.png + report.json;有 JS 报错或某页白屏时退出码 1。
|
||||
*/
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import path from 'node:path';
|
||||
|
||||
const REPO = path.resolve(import.meta.dirname, '..');
|
||||
const OUT = path.join(REPO, '.tmp-verify-web');
|
||||
const PORT = 5399;
|
||||
const DATA = path.join(REPO, '.tmp-verify-data');
|
||||
const python = process.env.DOUBAO_PYTHON || 'python';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const baseIndex = args.indexOf('--base');
|
||||
const externalBase = baseIndex >= 0 ? args[baseIndex + 1] : null;
|
||||
|
||||
const routes = [
|
||||
['chat-empty', '/#/chat'],
|
||||
['agents', '/#/agents'],
|
||||
['agent-edit', '/#/agents/a_doubao'],
|
||||
['groups', '/#/groups'],
|
||||
['memories', '/#/agents/a_doubao/memories'],
|
||||
['usage', '/#/agents/a_doubao/usage'],
|
||||
['resources', '/#/resources'],
|
||||
['skills', '/#/skills'],
|
||||
['notes', '/#/notes'],
|
||||
['screens', '/#/screens'],
|
||||
['settings', '/#/settings'],
|
||||
['me', '/#/me'],
|
||||
['about', '/#/about'],
|
||||
['meetings', '/#/meetings'],
|
||||
];
|
||||
|
||||
function freePort(start) {
|
||||
return new Promise((resolve) => {
|
||||
const tryPort = (p) => {
|
||||
const srv = net.createServer();
|
||||
srv.once('error', () => tryPort(p + 1));
|
||||
srv.once('listening', () => srv.close(() => resolve(p)));
|
||||
srv.listen(p, '127.0.0.1');
|
||||
};
|
||||
tryPort(start);
|
||||
});
|
||||
}
|
||||
|
||||
async function startKernel() {
|
||||
if (externalBase) return { base: externalBase.replace(/\/$/, ''), child: null };
|
||||
const port = await freePort(PORT);
|
||||
fs.mkdirSync(DATA, { recursive: true });
|
||||
const child = spawn(python, [
|
||||
path.join(REPO, 'android', 'kernel', 'main.py'),
|
||||
'--port', String(port),
|
||||
'--data-dir', DATA,
|
||||
'--tools-dir', path.join(REPO, 'tools'),
|
||||
'--web-dir', path.join(REPO, 'web'),
|
||||
'--quiet', '--json', '--no-mcp-autostart',
|
||||
], { cwd: REPO, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let buf = '';
|
||||
const timer = setTimeout(() => reject(new Error('内核启动超时')), 30000);
|
||||
child.stdout.on('data', (chunk) => {
|
||||
buf += chunk.toString('utf8');
|
||||
for (const line of buf.split('\n')) {
|
||||
if (!line.trim().startsWith('{')) continue;
|
||||
try {
|
||||
const info = JSON.parse(line);
|
||||
if (info.url) {
|
||||
clearTimeout(timer);
|
||||
resolve({ base: info.url.replace(/\/$/, ''), child });
|
||||
}
|
||||
} catch { /* 不是那行 JSON */ }
|
||||
}
|
||||
});
|
||||
child.stderr.on('data', (chunk) => process.stderr.write(`[kernel] ${chunk}`));
|
||||
child.on('error', reject);
|
||||
child.on('exit', (code) => reject(new Error(`内核退出:${code}`)));
|
||||
});
|
||||
}
|
||||
|
||||
function stopKernel(child) {
|
||||
if (!child) return;
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
|
||||
} else {
|
||||
child.kill('SIGTERM');
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
fs.rmSync(OUT, { recursive: true, force: true });
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
|
||||
let kernel = null;
|
||||
try {
|
||||
kernel = await startKernel();
|
||||
console.log(`[verify] 内核:${kernel.base}`);
|
||||
const report = [];
|
||||
for (const [name, route] of routes) {
|
||||
const shot = path.join(OUT, `${name}.png`);
|
||||
const res = spawnSync('node', ['scripts/screenshot.mjs', kernel.base + route, shot, '5500'], {
|
||||
cwd: REPO,
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, VIEWPORT: '1440x900', SCALE: '1' },
|
||||
timeout: 120000,
|
||||
});
|
||||
const text = `${res.stdout || ''}\n${res.stderr || ''}`;
|
||||
const errors = text.split('\n')
|
||||
.filter((line) => /\[exception\]|\[log\.error\]|\[console\.error\]|\[fatal\]/.test(line))
|
||||
.map((l) => l.slice(0, 300));
|
||||
report.push({ name, route, ok: fs.existsSync(shot) && fs.statSync(shot).size > 10000, errors });
|
||||
console.log(`${report[report.length - 1].ok && !errors.length ? '✅' : '❌'} ${name.padEnd(12)} ${errors[0] || ''}`);
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'report.json'), JSON.stringify(report, null, 2), 'utf8');
|
||||
const bad = report.filter((r) => !r.ok || r.errors.length);
|
||||
console.log(`\n[verify] ${report.length - bad.length}/${report.length} 页通过,截图在 ${path.relative(REPO, OUT)}/`);
|
||||
process.exitCode = bad.length ? 1 : 0;
|
||||
} catch (err) {
|
||||
console.error('[verify] 失败:', err.message);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
stopKernel(kernel && kernel.child);
|
||||
}
|
||||
@@ -6,7 +6,8 @@
|
||||
"e289048324c38899"
|
||||
],
|
||||
"_ui_bridge.py": [
|
||||
"048c7685991715fb"
|
||||
"048c7685991715fb",
|
||||
"4efeaba4272aa679"
|
||||
],
|
||||
"ask_user.py": [
|
||||
"94a9734c8c934db2",
|
||||
|
||||
@@ -17,8 +17,14 @@
|
||||
|
||||
## 电脑端会怎样
|
||||
|
||||
没有 `_android` 桥(桌面版)时,这几个工具都**明确返回不可用**,
|
||||
而不是假装成功 —— 让模型知道"这个端没有界面能力",它就不会反复重试。
|
||||
**v2 起电脑/网页端也有界面能力了,走的是内核自己的 HTTP 队列**:
|
||||
|
||||
· 安卓:`doubao_entry._android.device(json)`(Kotlin NativeBridge,同步阻塞)
|
||||
· 电脑/网页:内核 `app.get_native_device_hook()` 返回 `_web_device` ——
|
||||
请求挂进队列,网页轮询 `/api/device/pending` 弹界面,用户操作后
|
||||
`POST /api/device/answer` 把结果送回来;阻塞语义和安卓一致(工具里不用改一行)。
|
||||
|
||||
两条路返回的 JSON 形状完全一样,所以三个界面工具代码是一份。
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -28,20 +34,44 @@ import sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
class _HookAdapter:
|
||||
"""把内核里的 hook(json字符串)->json字符串 包成和 Kotlin 桥一样的对象。"""
|
||||
|
||||
def __init__(self, hook):
|
||||
self._hook = hook
|
||||
|
||||
def device(self, payload_json: str) -> str:
|
||||
return self._hook(payload_json)
|
||||
|
||||
|
||||
def _bridge():
|
||||
"""
|
||||
拿到安卓原生桥对象;电脑端返回 None。
|
||||
拿到"原生桥"对象:安卓是 `doubao_entry._android`,电脑是内核的网页队列钩子。
|
||||
|
||||
`doubao_entry` 只在安卓上存在(它是 Chaquopy 的入口模块),
|
||||
所以这里用 try/except 而不是判断平台字符串 —— 平台字符串判断错过一次
|
||||
(sys.platform 在 Chaquopy 里也是 'linux',跟桌面 Linux 分不开)。
|
||||
★ 顺序不能反:安卓上也有 app 模块,但 Kotlin 桥是同步的、体验更好,
|
||||
所以先试 doubao_entry;拿不到再退回内核钩子。
|
||||
★ 两种桥都拿不到(比如工具被单独 `python tools/xxx.py` 跑起来)时返回 None,
|
||||
调用方会明确报"没有界面能力",而不是假装成功。
|
||||
"""
|
||||
try:
|
||||
import doubao_entry # noqa: PLC0415 - 电脑端没有这个模块,只能运行时导入
|
||||
|
||||
return getattr(doubao_entry, '_android', None)
|
||||
bridge = getattr(doubao_entry, '_android', None)
|
||||
if bridge is not None:
|
||||
return bridge
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
pass
|
||||
|
||||
try:
|
||||
import app as kernel_app # noqa: PLC0415 - 内核模块,运行时已加载
|
||||
|
||||
hook = kernel_app.get_native_device_hook()
|
||||
if callable(hook):
|
||||
return _HookAdapter(hook)
|
||||
except Exception: # noqa: BLE001 - 单跑工具时没有内核,正常
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def call_device(payload: dict) -> dict:
|
||||
|
||||
1933
web/assets/app.css
Normal file
BIN
web/assets/avatars/agent-analyst.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
web/assets/avatars/agent-cat.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/agent-cloud.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
web/assets/avatars/agent-coder.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
web/assets/avatars/agent-custom.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/agent-robot.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/agent-star.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/agent-writer.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
web/assets/avatars/analyst.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
web/assets/avatars/cat.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/cloud.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
web/assets/avatars/coder.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
web/assets/avatars/custom.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/doubao.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
web/assets/avatars/main.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
web/assets/avatars/robot.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/star.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/assets/avatars/writer.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
245
web/index.html
@@ -1,227 +1,38 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<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" />
|
||||
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>豆包 · 网页版</title>
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='18' fill='%230065fd'/%3E%3Ctext x='32' y='44' font-size='34' font-family='sans-serif' font-weight='700' fill='white' text-anchor='middle'%3E豆%3C/text%3E%3C/svg%3E" />
|
||||
<link rel="stylesheet" href="/assets/app.css" />
|
||||
<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 = '';
|
||||
});
|
||||
}
|
||||
try {
|
||||
var t = localStorage.getItem('doubao.theme') || 'auto';
|
||||
var dark = t === 'dark' || (t === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
<script type="module" src="/static/js/client.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<aside class="sidebar" id="sidebar"></aside>
|
||||
<main class="main">
|
||||
<header class="topbar" id="topbar"></header>
|
||||
<div id="view" class="view"></div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- 首屏骨架:state 还没回来时先亮一下,别是白屏 -->
|
||||
<div id="boot" class="boot">
|
||||
<div class="boot-logo">豆包</div>
|
||||
<div class="boot-status" id="boot-status">正在连接内核…</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="/js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
332
web/js/api.js
Normal file
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* 和后端 Python 内核通信的一层:fetch 封装 + 全局状态(state)+ 聊天轮询。
|
||||
*
|
||||
* 约定(和 Android 端 KernelClient 一致):
|
||||
* - 内核失败也经常返回 HTTP 200 + { ok:false, error:"人话" },所以这里统一 throw ApiError,
|
||||
* 界面层 catch 后直接 toast(error.message) 即可;
|
||||
* - 设置保存只发改动过的字段(内核是浅合并,空字符串会清配置 —— 这是踩过的真 bug)。
|
||||
*/
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message, { status, body, path } = {}) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
this.path = path;
|
||||
}
|
||||
}
|
||||
|
||||
async function request(method, path, body, opts = {}) {
|
||||
const init = {
|
||||
method,
|
||||
headers: { ...(opts.headers || {}) },
|
||||
};
|
||||
if (body !== undefined) {
|
||||
init.headers['Content-Type'] = 'application/json';
|
||||
init.body = JSON.stringify(body);
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(path, init);
|
||||
} catch (err) {
|
||||
throw new ApiError('连不上内核(它可能还没启动好)', { path, body: String(err) });
|
||||
}
|
||||
const text = await res.text();
|
||||
let json = null;
|
||||
try { json = text ? JSON.parse(text) : null; } catch { /* 非 JSON */ }
|
||||
if (!res.ok) {
|
||||
const msg = (json && (json.error || json.message)) || `${res.status} ${res.statusText || '请求失败'}`;
|
||||
throw new ApiError(msg, { status: res.status, body: json || text, path });
|
||||
}
|
||||
if (json && json.ok === false && json.error) {
|
||||
throw new ApiError(json.error, { status: res.status, body: json, path });
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (path, opts) => request('GET', path, undefined, opts),
|
||||
post: (path, body, opts) => request('POST', path, body ?? {}, opts),
|
||||
put: (path, body, opts) => request('PUT', path, body ?? {}, opts),
|
||||
patch: (path, body, opts) => request('PATCH', path, body ?? {}, opts),
|
||||
del: (path, opts) => request('DELETE', path, undefined, opts),
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 全局状态 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const listeners = new Map(); // topic -> Set<fn>
|
||||
|
||||
export const S = {
|
||||
state: null, // 最近一次 /api/state
|
||||
loading: true,
|
||||
error: null,
|
||||
ready: false,
|
||||
route: 'chat',
|
||||
conversationId: null, // 当前打开的会话
|
||||
collapsed: localStorage.getItem('doubao.sidebar') === '1',
|
||||
theme: localStorage.getItem('doubao.theme') || 'auto',
|
||||
};
|
||||
|
||||
export function on(topic, fn) {
|
||||
if (!listeners.has(topic)) listeners.set(topic, new Set());
|
||||
listeners.get(topic).add(fn);
|
||||
return () => listeners.get(topic).delete(fn);
|
||||
}
|
||||
|
||||
export function emit(topic, payload) {
|
||||
const set = listeners.get(topic);
|
||||
if (set) for (const fn of [...set]) { try { fn(payload); } catch (err) { console.error('[emit]', topic, err); } }
|
||||
const all = listeners.get('*');
|
||||
if (all) for (const fn of [...all]) { try { fn(topic, payload); } catch { /* ignore */ } }
|
||||
}
|
||||
|
||||
/** 拉一次全量状态(首屏 / 大改动之后) */
|
||||
export async function loadState({ silent = false } = {}) {
|
||||
try {
|
||||
const state = await api.get('/api/state');
|
||||
if (state && state.error) throw new ApiError(state.error);
|
||||
S.state = state;
|
||||
S.error = null;
|
||||
S.ready = true;
|
||||
if (!silent) S.loading = false;
|
||||
emit('state', state);
|
||||
return state;
|
||||
} catch (err) {
|
||||
S.error = err;
|
||||
S.loading = false;
|
||||
S.ready = true;
|
||||
emit('state-error', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/* 常用派生数据 ------------------------------------------------------ */
|
||||
export const settings = () => (S.state && S.state.settings) || {};
|
||||
export const agents = () => (S.state && S.state.agents) || [];
|
||||
export const conversations = () => (S.state && S.state.conversations) || [];
|
||||
export const providers = () => (S.state && S.state.providers) || {};
|
||||
export const platform = () => (S.state && S.state.platform) || '';
|
||||
export const activeAgent = () => {
|
||||
const list = agents();
|
||||
const id = settings().activeAgentId;
|
||||
return list.find((a) => a.id === id) || list[0] || { id: 'a_doubao', name: '豆包', avatar: 'doubao' };
|
||||
};
|
||||
export const conversationById = (id) => conversations().find((c) => c.id === id) || null;
|
||||
|
||||
/** 只发改动过的字段(内核浅合并;全量下发会把没动过的键清空 —— 真出过这个 bug) */
|
||||
export async function saveSettings(patch) {
|
||||
if (!patch || !Object.keys(patch).length) return;
|
||||
await api.put('/api/settings', patch);
|
||||
await loadState({ silent: true });
|
||||
}
|
||||
|
||||
/** 设置面板草稿 → 只挑和当前不同的键 */
|
||||
export function settingsChanges(draft) {
|
||||
const cur = settings();
|
||||
const changes = {};
|
||||
for (const [k, v] of Object.entries(draft)) {
|
||||
if (JSON.stringify(cur[k]) !== JSON.stringify(v)) changes[k] = v;
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
export async function saveTimeouts(values) {
|
||||
await api.put('/api/timeouts', values);
|
||||
await loadState({ silent: true });
|
||||
}
|
||||
|
||||
/** 本地更新某个会话的概要(标题/预览/时间),避免整份 state 重拉 */
|
||||
export function patchConversation(id, patch) {
|
||||
if (!S.state || !Array.isArray(S.state.conversations)) return;
|
||||
const conv = S.state.conversations.find((c) => c.id === id);
|
||||
if (!conv) return;
|
||||
Object.assign(conv, patch);
|
||||
emit('conversations', S.state.conversations);
|
||||
}
|
||||
|
||||
/** 把会话排到最前(内核在下一轮 state 里也会这么做,这里是本地即时反馈) */
|
||||
export function bumpConversation(id) {
|
||||
if (!S.state || !Array.isArray(S.state.conversations)) return;
|
||||
const list = S.state.conversations;
|
||||
const idx = list.findIndex((c) => c.id === id);
|
||||
if (idx <= 0) return;
|
||||
const [conv] = list.splice(idx, 1);
|
||||
list.unshift(conv);
|
||||
emit('conversations', list);
|
||||
}
|
||||
|
||||
export async function refreshConversations() {
|
||||
const res = await api.get('/api/conversations');
|
||||
if (S.state) S.state.conversations = res.conversations || [];
|
||||
emit('conversations', conversations());
|
||||
return conversations();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 会话相关 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function createConversation({ agentId, title, type = 'single', participants } = {}) {
|
||||
const body = { type };
|
||||
if (agentId) body.agentId = agentId;
|
||||
if (title) body.title = title;
|
||||
if (participants && participants.length) body.participants = participants;
|
||||
const res = await api.post('/api/conversations', body);
|
||||
const conv = res.conversation || res;
|
||||
await refreshConversations();
|
||||
return conv;
|
||||
}
|
||||
|
||||
export async function getConversation(id) {
|
||||
const res = await api.get(`/api/conversations/${encodeURIComponent(id)}`);
|
||||
return res.conversation || res;
|
||||
}
|
||||
|
||||
export async function patchConversationRemote(id, patch) {
|
||||
const res = await api.patch(`/api/conversations/${encodeURIComponent(id)}`, patch);
|
||||
return res.conversation || res;
|
||||
}
|
||||
|
||||
export async function deleteConversation(id) {
|
||||
await api.del(`/api/conversations/${encodeURIComponent(id)}`);
|
||||
await refreshConversations();
|
||||
}
|
||||
|
||||
/** 群聊成员增删:POST/DELETE /api/conversations/<id>/members[/<agentId>] */
|
||||
export async function addMember(conversationId, agentId) {
|
||||
const res = await api.post(`/api/conversations/${encodeURIComponent(conversationId)}/members`, { agentId });
|
||||
return res.conversation;
|
||||
}
|
||||
|
||||
export async function removeMember(conversationId, agentId) {
|
||||
const res = await api.del(`/api/conversations/${encodeURIComponent(conversationId)}/members/${encodeURIComponent(agentId)}`);
|
||||
return res.conversation;
|
||||
}
|
||||
|
||||
/** 标记/取消标记某条消息为「重要」(按内容定位 —— 内核就是这么设计的) */
|
||||
export async function markImportant(conversationId, content, role = '', important = null) {
|
||||
const body = { content, role };
|
||||
if (important != null) body.important = important;
|
||||
return api.post(`/api/conversations/${encodeURIComponent(conversationId)}/important`, body);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 聊天:POST /api/chat → 轮询 /api/chat/poll */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* 发一条消息并消费流式事件。
|
||||
*
|
||||
* 协议(和 Android 端 KernelClient.chat 完全一致):
|
||||
* POST /api/chat body: {conversationId, message, transport:'poll', agentId?, attachments?,
|
||||
* autoContinue?, forceSpeaker?}
|
||||
* → {ok, runId}
|
||||
* GET /api/chat/poll?runId=&cursor= → {ok, events:[…], cursor, done}
|
||||
* 事件类型:start / delta / reasoning / tool_call / tool_result / speaker / handoff /
|
||||
* status / rule_error / ui_results / rebased / saved / error / done
|
||||
*
|
||||
* @param {object} opts
|
||||
* conversationId 会话 id
|
||||
* message 正文(内核字段名就叫 message,不是 text)
|
||||
* agentId 用哪个智能体
|
||||
* attachments 附件数组(/api/upload 的返回)
|
||||
* autoContinue 群聊自动续轮(没有用户消息)
|
||||
* forceSpeaker 指定这一轮谁发言(群聊「让他接着说」)
|
||||
* onEvent(ev) 每个增量事件
|
||||
* signal AbortSignal,用来"停止生成"(只停轮询,服务端这一轮会自然跑完)
|
||||
* @returns {Promise<{runId, aborted}>}
|
||||
*/
|
||||
export async function runChat(opts) {
|
||||
const {
|
||||
conversationId, message, agentId, attachments,
|
||||
autoContinue = false, forceSpeaker = '',
|
||||
onEvent, signal, pollInterval = 200,
|
||||
} = opts || {};
|
||||
const body = {
|
||||
conversationId: conversationId || '',
|
||||
message: message || '',
|
||||
transport: 'poll',
|
||||
};
|
||||
if (agentId) body.agentId = agentId;
|
||||
if (attachments && attachments.length) body.attachments = attachments;
|
||||
if (autoContinue) body.autoContinue = true;
|
||||
if (forceSpeaker) body.forceSpeaker = forceSpeaker;
|
||||
|
||||
const start = await api.post('/api/chat', body);
|
||||
const runId = start && start.runId;
|
||||
if (!runId) throw new ApiError('内核没有返回 runId', { path: '/api/chat', body: start });
|
||||
if (signal && signal.aborted) return { runId, aborted: true };
|
||||
|
||||
let cursor = 0;
|
||||
let idle = 0;
|
||||
let flushing = false; // 拿到 done 之后再补拉一拍(handoff/saved 在 done 之后才发)
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
while (true) {
|
||||
if (signal && signal.aborted) return { runId, aborted: true };
|
||||
let payload;
|
||||
try {
|
||||
payload = await api.get(`/api/chat/poll?runId=${encodeURIComponent(runId)}&cursor=${cursor}`);
|
||||
} catch (err) {
|
||||
// done 之后那一拍如果 run 已经被回收(404),属于正常收尾
|
||||
if (flushing) return { runId, aborted: false };
|
||||
// 内核偶发 500 不该直接毁掉这一轮:等一会儿再试,连续失败太久才抛
|
||||
idle += 1;
|
||||
if (idle > 30) throw err;
|
||||
await sleep(400);
|
||||
continue;
|
||||
}
|
||||
const events = (payload && payload.events) || [];
|
||||
if (typeof payload.cursor === 'number') cursor = payload.cursor;
|
||||
let sawEnd = false;
|
||||
for (const ev of events) {
|
||||
if (!ev) continue;
|
||||
if (ev.type === 'done' || ev.type === 'error') sawEnd = true;
|
||||
if (onEvent) onEvent(ev);
|
||||
}
|
||||
if (payload.done || sawEnd) {
|
||||
// 已经收到结束事件:再补拉一次,把 done 之后才发的 handoff / status / saved 收全
|
||||
if (flushing) return { runId, aborted: false };
|
||||
flushing = true;
|
||||
await sleep(80);
|
||||
continue;
|
||||
}
|
||||
idle = events.length ? 0 : idle + 1;
|
||||
// 3 分钟没有任何新内容 = 上游卡住了(和安卓端一致)
|
||||
if (idle > 900) throw new ApiError('超过 3 分钟没有新内容,已停止等待');
|
||||
await sleep(pollInterval);
|
||||
}
|
||||
}
|
||||
|
||||
/** 让 AI 主动往会话里发一条(send_message 工具/群聊面板用) */
|
||||
export async function sendSessionMessage({ conversationId, text, role, reply, depth }) {
|
||||
return api.post('/api/session-message', { conversationId, text, role, reply, depth });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 附件上传 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function readAsDataUrl(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
export async function uploadFile(file, { pending = false } = {}) {
|
||||
const dataUrl = await readAsDataUrl(file);
|
||||
const res = await api.post('/api/upload', { name: file.name, dataUrl, pending });
|
||||
return res.file;
|
||||
}
|
||||
|
||||
/** 桌面版走内核的原生选文件(Electron 弹系统对话框);浏览器会返回 ok:false */
|
||||
export async function pickFilesNative() {
|
||||
const res = await api.post('/api/pick-file', {});
|
||||
return res;
|
||||
}
|
||||
734
web/js/app.js
Normal file
@@ -0,0 +1,734 @@
|
||||
/**
|
||||
* 网页版入口:侧栏 + 顶栏 + 路由(hash)。
|
||||
*
|
||||
* 页面模块约定:
|
||||
* pages/xxx.js 默认导出 render(container, ctx) → (可选)返回 cleanup 函数
|
||||
* ctx = { params, navigate, onState(fn) },onState 注册的监听在离开页面时自动清掉。
|
||||
*
|
||||
* 路由表:
|
||||
* #/chat 对话(默认)
|
||||
* #/agents 智能体列表
|
||||
* #/agents/:id 智能体编辑
|
||||
* #/agents/:id/memories 记忆
|
||||
* #/agents/:id/usage 用量
|
||||
* #/groups 群聊管理
|
||||
* #/resources 资源(世界观 / Skill / 模型 / 规则包)
|
||||
* #/meetings 会议模式
|
||||
* #/skills 技能 · 连接器
|
||||
* #/notes 笔记
|
||||
* #/screens AI 界面
|
||||
* #/settings 设置
|
||||
* #/me 我的
|
||||
* #/about 关于
|
||||
*/
|
||||
import {
|
||||
S, api, loadState, on, emit, settings, agents, conversations, providers, activeAgent,
|
||||
refreshConversations, createConversation, saveSettings, conversationById,
|
||||
} from './api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, openMenu, openModal, confirmBox, promptBox,
|
||||
fmtRelative, copyText,
|
||||
} from './ui.js';
|
||||
import { startDeviceBridge } from './device.js';
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 侧栏导航表 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const NAV_MAIN = [
|
||||
{ route: 'chat', label: '新对话', icon: 'new-chat', shortcut: 'Ctrl Shift K', action: 'new-chat' },
|
||||
{ route: 'agents', label: '智能体', icon: 'bot' },
|
||||
{ route: 'groups', label: '群聊', icon: 'users' },
|
||||
{ route: 'resources', label: '资源', icon: 'layers' },
|
||||
];
|
||||
|
||||
const NAV_MORE = [
|
||||
{ route: 'meetings', label: '会议模式', icon: 'presentation' },
|
||||
{ route: 'skills', label: '技能 · 连接器', icon: 'plug' },
|
||||
{ route: 'notes', label: '笔记', icon: 'notebook' },
|
||||
{ route: 'screens', label: 'AI 界面', icon: 'scan' },
|
||||
];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 小工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const view = () => document.getElementById('view');
|
||||
const sidebarEl = () => document.getElementById('sidebar');
|
||||
const topbarEl = () => document.getElementById('topbar');
|
||||
const appEl = () => document.getElementById('app');
|
||||
|
||||
/** 按 id 找智能体(找不到返回 null,顶栏用 activeAgent 兜底) */
|
||||
function agentByIdSafe(id) {
|
||||
return agents().find((a) => a.id === id) || null;
|
||||
}
|
||||
|
||||
function setBoot(status) {
|
||||
const boot = document.getElementById('boot');
|
||||
const el = document.getElementById('boot-status');
|
||||
if (!boot) return;
|
||||
if (status === false) {
|
||||
boot.classList.add('hide');
|
||||
setTimeout(() => boot.remove(), 260);
|
||||
return;
|
||||
}
|
||||
if (el) el.textContent = status;
|
||||
}
|
||||
|
||||
export function applyTheme() {
|
||||
const t = S.theme;
|
||||
const dark = t === 'dark'
|
||||
|| (t === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
export function toggleSidebar(force) {
|
||||
const narrow = appEl().classList.contains('narrow');
|
||||
const el = sidebarEl();
|
||||
if (narrow) {
|
||||
el.classList.toggle('open', force == null ? !el.classList.contains('open') : force);
|
||||
renderNarrowMask();
|
||||
return;
|
||||
}
|
||||
S.collapsed = force == null ? !S.collapsed : !force;
|
||||
el.classList.toggle('collapsed', S.collapsed);
|
||||
localStorage.setItem('doubao.sidebar', S.collapsed ? '1' : '0');
|
||||
renderTopbar();
|
||||
}
|
||||
|
||||
function renderNarrowMask() {
|
||||
const existing = document.querySelector('.sidebar-mask');
|
||||
const narrow = appEl().classList.contains('narrow');
|
||||
const open = sidebarEl().classList.contains('open');
|
||||
if (narrow && open) {
|
||||
if (!existing) {
|
||||
appEl().appendChild(h('div.sidebar-mask', { onclick: () => toggleSidebar(false) }));
|
||||
}
|
||||
} else if (existing) {
|
||||
existing.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function applyLayout() {
|
||||
const narrow = window.innerWidth < 900;
|
||||
appEl().classList.toggle('narrow', narrow);
|
||||
if (!narrow) {
|
||||
sidebarEl().classList.remove('open');
|
||||
sidebarEl().classList.toggle('collapsed', S.collapsed);
|
||||
}
|
||||
renderNarrowMask();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 路由 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const ROUTES = [
|
||||
{ re: /^$/, page: 'chat', title: '对话' },
|
||||
{ re: /^chat$/, page: 'chat', title: '对话' },
|
||||
{ re: /^agents$/, page: 'agents', title: '智能体' },
|
||||
{ re: /^agents\/([^/]+)$/, page: 'agent-edit', title: '编辑智能体', keys: ['id'] },
|
||||
{ re: /^agents\/([^/]+)\/memories$/, page: 'memories', title: '记忆', keys: ['id'] },
|
||||
{ re: /^agents\/([^/]+)\/usage$/, page: 'usage', title: '用量', keys: ['id'] },
|
||||
{ re: /^groups$/, page: 'groups', title: '群聊' },
|
||||
{ re: /^resources$/, page: 'resources', title: '资源' },
|
||||
{ re: /^meetings$/, page: 'meetings', title: '会议模式' },
|
||||
{ re: /^skills$/, page: 'skills', title: '技能 · 连接器' },
|
||||
{ re: /^notes$/, page: 'notes', title: '笔记' },
|
||||
{ re: /^screens$/, page: 'screens', title: 'AI 界面' },
|
||||
{ re: /^settings$/, page: 'settings', title: '设置' },
|
||||
{ re: /^me$/, page: 'me', title: '我的' },
|
||||
{ re: /^about$/, page: 'about', title: '关于豆包' },
|
||||
];
|
||||
|
||||
const pageModules = {
|
||||
chat: () => import('./pages/chat.js'),
|
||||
agents: () => import('./pages/agents.js'),
|
||||
'agent-edit': () => import('./pages/agent-edit.js'),
|
||||
memories: () => import('./pages/memories.js'),
|
||||
usage: () => import('./pages/usage.js'),
|
||||
groups: () => import('./pages/groups.js'),
|
||||
resources: () => import('./pages/resources.js'),
|
||||
meetings: () => import('./pages/meetings.js'),
|
||||
skills: () => import('./pages/skills.js'),
|
||||
notes: () => import('./pages/notes.js'),
|
||||
screens: () => import('./pages/screens.js'),
|
||||
settings: () => import('./pages/settings.js'),
|
||||
me: () => import('./pages/me.js'),
|
||||
about: () => import('./pages/about.js'),
|
||||
};
|
||||
|
||||
const pageCache = new Map();
|
||||
let currentCleanup = null;
|
||||
let currentPageKey = null;
|
||||
let navigating = false;
|
||||
|
||||
function parseHash() {
|
||||
let raw = location.hash.replace(/^#\/?/, '');
|
||||
if (!raw) raw = 'chat';
|
||||
const [pathPart, queryPart] = raw.split('?');
|
||||
const params = Object.fromEntries(new URLSearchParams(queryPart || ''));
|
||||
if (S.conversationId) params.conversationId = S.conversationId;
|
||||
return { path: pathPart, params };
|
||||
}
|
||||
|
||||
export function navigate(path, params, { replace = false } = {}) {
|
||||
const qs = new URLSearchParams(params || {}).toString();
|
||||
// conversationId 不进 hash,放在 S 里(新对话会 hash 不变)
|
||||
const target = `#/${path}${qs ? '?' + qs : ''}`;
|
||||
if (replace) {
|
||||
history.replaceState(null, '', target);
|
||||
handleRoute();
|
||||
} else if (location.hash === target) {
|
||||
handleRoute();
|
||||
} else {
|
||||
location.hash = target;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRoute() {
|
||||
if (navigating) return;
|
||||
const { path, params } = parseHash();
|
||||
let matched = null;
|
||||
for (const r of ROUTES) {
|
||||
const m = path.match(r.re);
|
||||
if (m) {
|
||||
matched = { ...r, match: m };
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!matched) { navigate('chat', {}, { replace: true }); return; }
|
||||
const routeParams = { ...params };
|
||||
(matched.keys || []).forEach((k, i) => { routeParams[k] = decodeURIComponent(matched.match[i + 1]); });
|
||||
if (routeParams.conversationId) S.conversationId = routeParams.conversationId;
|
||||
S.route = matched.page;
|
||||
|
||||
const key = matched.page;
|
||||
if (currentCleanup) { try { currentCleanup(); } catch { /* ignore */ } currentCleanup = null; }
|
||||
|
||||
// 每个页面各自滚自己的容器,切换时保留 state(chat 页不销毁:来回切不丢草稿)
|
||||
const container = view();
|
||||
if (key === 'chat') {
|
||||
clear(container);
|
||||
container.className = 'view';
|
||||
} else {
|
||||
clear(container);
|
||||
container.className = 'view page';
|
||||
}
|
||||
renderSidebarActive();
|
||||
renderTopbar();
|
||||
|
||||
navigating = true;
|
||||
try {
|
||||
let mod = pageCache.get(key);
|
||||
if (!mod) {
|
||||
mod = await pageModules[key]();
|
||||
pageCache.set(key, mod);
|
||||
}
|
||||
const cleanups = [];
|
||||
const ctx = {
|
||||
params: routeParams,
|
||||
navigate,
|
||||
onState(fn) { const off = on('state', fn); cleanups.push(off); return off; },
|
||||
setTitle(t) { const title = t ? `${t} · 豆包` : '豆包 · 网页版'; document.title = title; },
|
||||
};
|
||||
document.title = `${matched.title} · 豆包`;
|
||||
const maybeCleanup = mod.default(container, ctx);
|
||||
currentCleanup = () => {
|
||||
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
|
||||
if (typeof maybeCleanup === 'function') maybeCleanup();
|
||||
};
|
||||
currentPageKey = key;
|
||||
} catch (err) {
|
||||
console.error('[route] 页面加载失败', err);
|
||||
container.innerHTML = '';
|
||||
container.classList.add('page');
|
||||
container.appendChild(h('div.page-inner', {},
|
||||
h('div.empty-state', {},
|
||||
h('div.empty-state-title', '这个页面加载失败了'),
|
||||
h('div.empty-state-desc', String(err && err.message || err)),
|
||||
h('div', { style: 'margin-top:16px' },
|
||||
h('button.btn', { onclick: () => location.reload() }, '刷新页面')))));
|
||||
} finally {
|
||||
navigating = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 侧栏 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function renderSidebarActive() {
|
||||
for (const el of sidebarEl().querySelectorAll('.sb-item[data-route]')) {
|
||||
el.classList.toggle('active', el.dataset.route === S.route);
|
||||
}
|
||||
}
|
||||
|
||||
function convTitle(conv) {
|
||||
return conv.title || '新对话';
|
||||
}
|
||||
|
||||
function renderSidebar() {
|
||||
const el = sidebarEl();
|
||||
const scrollTop = (el.querySelector('.sb-convs') || {}).scrollTop || 0;
|
||||
clear(el);
|
||||
el.classList.toggle('collapsed', !appEl().classList.contains('narrow') && S.collapsed);
|
||||
|
||||
const brand = h('div.sb-brand', {},
|
||||
h('div.sb-logo', {}, h('span.logo-dot', '豆'), '豆包'),
|
||||
h('div.sb-brand-actions', {},
|
||||
h('button.icon-btn.sm', {
|
||||
title: '收起侧栏 (Ctrl+B)',
|
||||
onclick: () => toggleSidebar(false),
|
||||
}, icon('panel-left-close', 17)),
|
||||
h('button.icon-btn.sm', { title: '搜索对话', onclick: openSearch }, icon('search', 17))));
|
||||
|
||||
const nav = h('div.sb-nav');
|
||||
for (const item of NAV_MAIN) {
|
||||
nav.appendChild(h('button.sb-item', {
|
||||
'data-route': item.route,
|
||||
class: item.route === 'chat' ? 'main-action' : '',
|
||||
onclick: () => {
|
||||
if (item.action === 'new-chat') { startNewChat(); return; }
|
||||
navigate(item.route);
|
||||
if (appEl().classList.contains('narrow')) toggleSidebar(false);
|
||||
},
|
||||
},
|
||||
icon(item.icon, 18),
|
||||
h('span.sb-label', item.label),
|
||||
item.shortcut ? h('span.kbd', item.shortcut) : null));
|
||||
}
|
||||
// 「更多」= 次级页面(豆包侧栏也是这个结构:主入口 + 更多)
|
||||
const moreActive = NAV_MORE.some((m) => m.route === S.route);
|
||||
nav.appendChild(h('button.sb-item', {
|
||||
class: moreActive ? 'active' : '',
|
||||
onclick: (e) => {
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
openMenu(e.currentTarget, NAV_MORE.map((m) => ({
|
||||
label: m.label,
|
||||
icon: m.icon,
|
||||
onClick: () => { navigate(m.route); if (appEl().classList.contains('narrow')) toggleSidebar(false); },
|
||||
})));
|
||||
},
|
||||
}, icon('more-horizontal', 18), h('span.sb-label', '更多'), h('span.kbd', '›')));
|
||||
|
||||
el.appendChild(brand);
|
||||
el.appendChild(nav);
|
||||
|
||||
// 最近会话
|
||||
el.appendChild(h('div.sb-section', {}, h('span', '最近')));
|
||||
const convs = conversations();
|
||||
const list = h('div.sb-convs');
|
||||
if (!convs.length) {
|
||||
list.appendChild(h('div.sb-empty', '还没有对话,点「新对话」开始。'));
|
||||
}
|
||||
for (const conv of convs) {
|
||||
const isGroup = conv.type === 'group' || conv.kind === 'group' || conv.group;
|
||||
const row = h(`div.sb-conv${isGroup ? '.group' : ''}${conv.id === S.conversationId ? '.active' : ''}${conv.pinned ? '.pinned' : ''}`, {
|
||||
title: convTitle(conv),
|
||||
onclick: () => openConversation(conv.id),
|
||||
oncontextmenu: (e) => { e.preventDefault(); openConvMenu(e.currentTarget, conv); },
|
||||
},
|
||||
isGroup ? icon('users', 14, 'conv-icon') : null,
|
||||
h('span.conv-title', convTitle(conv)),
|
||||
h('button.conv-more', {
|
||||
title: '更多',
|
||||
onclick: (e) => { e.stopPropagation(); openConvMenu(e.currentTarget, conv); },
|
||||
}, icon('more-horizontal', 15)));
|
||||
list.appendChild(row);
|
||||
}
|
||||
el.appendChild(list);
|
||||
|
||||
// 底部
|
||||
const foot = h('div.sb-foot', {},
|
||||
h('button.sb-item', { class: S.route === 'settings' ? 'active' : '', onclick: () => navigate('settings') },
|
||||
icon('settings', 18), h('span.sb-label', '设置')),
|
||||
h('button.sb-item', { class: S.route === 'me' ? 'active' : '', onclick: () => navigate('me') },
|
||||
icon('user', 18), h('span.sb-label', '我的')),
|
||||
h('button.sb-item', { class: S.route === 'about' ? 'active' : '', onclick: () => navigate('about') },
|
||||
icon('info', 18), h('span.sb-label', '关于豆包')));
|
||||
el.appendChild(foot);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const sc = el.querySelector('.sb-convs');
|
||||
if (sc) sc.scrollTop = scrollTop;
|
||||
});
|
||||
}
|
||||
|
||||
function openSearch() {
|
||||
const modal = openModal({
|
||||
title: '搜索对话',
|
||||
width: 560,
|
||||
body: buildSearchBody(),
|
||||
});
|
||||
function buildSearchBody() {
|
||||
const input = h('input.input', { placeholder: '按标题搜索…', autofocus: 'autofocus' });
|
||||
const result = h('div.search-results');
|
||||
const renderResult = () => {
|
||||
const q = input.value.trim().toLowerCase();
|
||||
const list = conversations().filter((c) => !q || convTitle(c).toLowerCase().includes(q));
|
||||
clear(result);
|
||||
if (!list.length) { result.appendChild(h('div.sb-empty', '没有匹配的对话')); return; }
|
||||
for (const conv of list.slice(0, 50)) {
|
||||
result.appendChild(h('div.list-row.clickable', {
|
||||
onclick: () => { modal.close(); openConversation(conv.id); },
|
||||
},
|
||||
h('div.list-main', {},
|
||||
h('div.list-title', convTitle(conv)),
|
||||
h('div.list-desc', `${conv.messageCount || 0} 条 · ${fmtRelative(conv.updatedAt)}`))));
|
||||
}
|
||||
};
|
||||
input.addEventListener('input', renderResult);
|
||||
setTimeout(() => input.focus(), 30);
|
||||
renderResult();
|
||||
return h('div', {}, input, h('div', { style: 'margin-top:8px' }, result));
|
||||
}
|
||||
}
|
||||
|
||||
function openConvMenu(anchor, conv) {
|
||||
openMenu(anchor, [
|
||||
{ label: '打开', icon: 'message-circle', onClick: () => openConversation(conv.id) },
|
||||
{
|
||||
label: conv.pinned ? '取消置顶' : '置顶',
|
||||
icon: 'pin',
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.patch(`/api/conversations/${encodeURIComponent(conv.id)}`, { pinned: !conv.pinned });
|
||||
await refreshConversations();
|
||||
renderSidebar();
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '重命名',
|
||||
icon: 'pencil',
|
||||
onClick: async () => {
|
||||
const title = await promptBox({ title: '重命名对话', value: conv.title || '', okText: '保存' });
|
||||
if (title == null) return;
|
||||
try {
|
||||
await api.patch(`/api/conversations/${encodeURIComponent(conv.id)}`, { title });
|
||||
await refreshConversations();
|
||||
renderSidebar();
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
},
|
||||
'-',
|
||||
{
|
||||
label: '删除对话',
|
||||
icon: 'trash',
|
||||
danger: true,
|
||||
onClick: async () => {
|
||||
const ok = await confirmBox({
|
||||
title: '删除这个对话?',
|
||||
message: `「${convTitle(conv)}」及其消息会被删除,不可恢复。`,
|
||||
danger: true,
|
||||
okText: '删除',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.del(`/api/conversations/${encodeURIComponent(conv.id)}`);
|
||||
if (S.conversationId === conv.id) { S.conversationId = null; startNewChat(); }
|
||||
await refreshConversations();
|
||||
renderSidebar();
|
||||
toast('已删除', { type: 'success' });
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
},
|
||||
], { alignRight: true });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 顶栏 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function providerModelLabel() {
|
||||
const st = settings();
|
||||
const p = providers()[st.provider] || {};
|
||||
const provLabel = p.label || st.provider || '未设置模型';
|
||||
const model = st.model || p.defaultModel || '';
|
||||
return { provLabel, model, hasKey: !!st.hasApiKey };
|
||||
}
|
||||
|
||||
function renderTopbar() {
|
||||
const el = topbarEl();
|
||||
clear(el);
|
||||
const narrow = appEl().classList.contains('narrow');
|
||||
const collapsed = !narrow && S.collapsed;
|
||||
|
||||
const left = h('div.topbar-left', {});
|
||||
left.appendChild(h('button.icon-btn', {
|
||||
title: collapsed ? '展开侧栏 (Ctrl+B)' : '收起侧栏 (Ctrl+B)',
|
||||
onclick: () => toggleSidebar(),
|
||||
}, icon(collapsed || narrow ? 'panel-left-open' : 'panel-left', 19)));
|
||||
|
||||
if (S.route === 'chat') {
|
||||
const conv = S.conversationId ? conversationById(S.conversationId) : null;
|
||||
const isGroup = !!(conv && (conv.type === 'group' || (conv.participants || []).length > 1));
|
||||
if (isGroup) {
|
||||
// 群聊:顶栏显示群名 + 成员头像堆叠(点开去群聊管理)
|
||||
const members = (conv.participants || []).map((id) => agents().find((a) => a.id === id)).filter(Boolean);
|
||||
const stack = h('span.avatar-stack');
|
||||
for (const m of members.slice(0, 4)) stack.appendChild(avatar(m, 22));
|
||||
left.appendChild(h('button.agent-chip', {
|
||||
title: '群聊成员',
|
||||
onclick: () => navigate('groups'),
|
||||
},
|
||||
stack,
|
||||
h('span.agent-name', conv.title || '群聊'),
|
||||
icon('chevron-down', 14, 'chevron')));
|
||||
} else {
|
||||
const agent = (conv && conv.agentId && agentByIdSafe(conv.agentId)) || activeAgent();
|
||||
left.appendChild(h('button.agent-chip', {
|
||||
title: '切换智能体',
|
||||
onclick: (e) => openAgentSwitch(e.currentTarget),
|
||||
},
|
||||
avatar(agent, 24),
|
||||
h('span.agent-name', agent.name || '豆包'),
|
||||
icon('chevron-down', 14, 'chevron')));
|
||||
}
|
||||
} else {
|
||||
const title = (ROUTES.find((r) => r.page === S.route) || {}).title || '';
|
||||
if (title) left.appendChild(h('div.topbar-title', title));
|
||||
}
|
||||
|
||||
const { provLabel, model, hasKey } = providerModelLabel();
|
||||
const right = h('div.topbar-right', {});
|
||||
right.appendChild(h(`button.model-chip${hasKey ? '' : '.warn'}`, {
|
||||
title: hasKey ? `${provLabel} · ${model}` : '还没配置 API Key,点这里去设置',
|
||||
onclick: (e) => openModelMenu(e.currentTarget),
|
||||
},
|
||||
h(`span.model-dot${hasKey ? '' : '.off'}`),
|
||||
h('span.model-name', hasKey ? (model || provLabel) : '未配置模型'),
|
||||
icon('chevron-down', 14)));
|
||||
|
||||
const st = settings();
|
||||
right.appendChild(h('button.icon-btn', {
|
||||
title: st.speech && st.speech.autoRead ? '关闭自动朗读' : '开启自动朗读',
|
||||
class: st.speech && st.speech.autoRead ? 'active' : '',
|
||||
onclick: toggleAutoRead,
|
||||
}, icon('volume', 18)));
|
||||
|
||||
right.appendChild(h('button.icon-btn', {
|
||||
title: '更多',
|
||||
onclick: (e) => openMoreMenu(e.currentTarget),
|
||||
}, icon('more-horizontal', 18)));
|
||||
|
||||
el.appendChild(left);
|
||||
el.appendChild(h('div.topbar-center'));
|
||||
el.appendChild(right);
|
||||
el.classList.toggle('sidebar-collapsed', collapsed);
|
||||
}
|
||||
|
||||
function openAgentSwitch(anchor) {
|
||||
const list = agents();
|
||||
const items = list.map((a) => ({
|
||||
label: a.name + (a.builtin ? '' : ' (自定义)'),
|
||||
icon: 'bot',
|
||||
hint: a.tagline || '',
|
||||
onClick: () => switchAgent(a),
|
||||
}));
|
||||
items.push('-');
|
||||
items.push({ label: '管理智能体…', icon: 'settings', onClick: () => navigate('agents') });
|
||||
openMenu(anchor, items);
|
||||
}
|
||||
|
||||
async function switchAgent(agent) {
|
||||
try {
|
||||
await saveSettings({ activeAgentId: agent.id });
|
||||
toast(`已切换到「${agent.name}」`, { type: 'success' });
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
}
|
||||
|
||||
function openModelMenu(anchor) {
|
||||
const st = settings();
|
||||
const p = providers()[st.provider] || {};
|
||||
const models = (p.models || []).slice(0, 12);
|
||||
const toModelKey = (m) => (m && typeof m === 'object' ? (m.id || m.model || m.name) : m);
|
||||
const items = [];
|
||||
if (!st.hasApiKey) {
|
||||
items.push({ label: '还没配置 API Key → 去设置', icon: 'key', onClick: () => navigate('settings') });
|
||||
items.push('-');
|
||||
}
|
||||
items.push({ label: `提供商:${p.label || st.provider || '未设置'}`, icon: 'cpu', onClick: () => navigate('settings') });
|
||||
if (models.length) {
|
||||
items.push('-');
|
||||
for (const m of models) {
|
||||
const key = toModelKey(m);
|
||||
items.push({
|
||||
label: key,
|
||||
icon: 'check',
|
||||
hint: key === st.model ? '当前' : '',
|
||||
onClick: async () => {
|
||||
try { await saveSettings({ model: key }); toast(`模型:${key}`, { type: 'success' }); } catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
items.push('-');
|
||||
items.push({ label: '全部提供商 / 思考强度…', icon: 'settings', onClick: () => navigate('settings') });
|
||||
openMenu(anchor, items, { alignRight: true });
|
||||
}
|
||||
|
||||
async function toggleAutoRead() {
|
||||
const st = settings();
|
||||
const speech = st.speech || {};
|
||||
try {
|
||||
await saveSettings({ speech: { ...speech, autoRead: !speech.autoRead } });
|
||||
renderTopbar();
|
||||
toast(speech.autoRead ? '已关闭自动朗读' : '已开启自动朗读:回复会自动念出来', { type: 'success' });
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
}
|
||||
|
||||
function openMoreMenu(anchor) {
|
||||
const themeLabel = S.theme === 'auto' ? '主题:跟随系统' : S.theme === 'dark' ? '主题:深色' : '主题:浅色';
|
||||
openMenu(anchor, [
|
||||
{ label: '新对话', icon: 'new-chat', hint: 'Ctrl Shift K', onClick: startNewChat },
|
||||
{ label: '搜索对话', icon: 'search', onClick: openSearch },
|
||||
'-',
|
||||
{ label: '设置', icon: 'settings', onClick: () => navigate('settings') },
|
||||
{ label: '技能 · 连接器', icon: 'plug', onClick: () => navigate('skills') },
|
||||
{ label: '会议模式', icon: 'presentation', onClick: () => navigate('meetings') },
|
||||
'-',
|
||||
{
|
||||
label: themeLabel,
|
||||
icon: 'sun',
|
||||
onClick: () => {
|
||||
S.theme = S.theme === 'auto' ? 'light' : S.theme === 'light' ? 'dark' : 'auto';
|
||||
localStorage.setItem('doubao.theme', S.theme);
|
||||
applyTheme();
|
||||
toast(S.theme === 'auto' ? '主题跟随系统' : S.theme === 'dark' ? '已切到深色' : '已切到浅色');
|
||||
},
|
||||
},
|
||||
{ label: '编辑主题(更多)…', icon: 'moon', onClick: () => navigate('settings') },
|
||||
'-',
|
||||
{ label: '重新加载界面', icon: 'refresh', onClick: () => location.reload() },
|
||||
], { alignRight: true });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 对话切换 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function startNewChat() {
|
||||
S.conversationId = null;
|
||||
if (S.route !== 'chat') navigate('chat');
|
||||
else {
|
||||
// 已经在 chat 页:通知页面重置
|
||||
window.dispatchEvent(new CustomEvent('doubao:new-chat'));
|
||||
}
|
||||
renderSidebar();
|
||||
refreshConversations().then(() => renderSidebar()).catch(() => {});
|
||||
}
|
||||
|
||||
export function openConversation(id) {
|
||||
S.conversationId = id;
|
||||
if (S.route !== 'chat') navigate('chat');
|
||||
else window.dispatchEvent(new CustomEvent('doubao:open-conversation', { detail: id }));
|
||||
renderSidebar();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 全局事件 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function bindGlobalKeys() {
|
||||
document.addEventListener('keydown', (e) => {
|
||||
const mod = e.ctrlKey || e.metaKey;
|
||||
const tag = (e.target && e.target.tagName) || '';
|
||||
const typing = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable);
|
||||
if (mod && e.shiftKey && (e.key === 'K' || e.key === 'k')) {
|
||||
e.preventDefault();
|
||||
startNewChat();
|
||||
} else if (mod && (e.key === 'b' || e.key === 'B')) {
|
||||
e.preventDefault();
|
||||
toggleSidebar();
|
||||
} else if (mod && (e.key === 'k' || e.key === 'K') && !typing) {
|
||||
e.preventDefault();
|
||||
openSearch();
|
||||
} else if (e.key === 'Escape' && !typing) {
|
||||
window.dispatchEvent(new CustomEvent('doubao:escape'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function bindWindow() {
|
||||
let resizeTimer = null;
|
||||
window.addEventListener('resize', () => {
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(() => { applyLayout(); renderNarrowMask(); }, 80);
|
||||
});
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||||
if (S.theme === 'auto') applyTheme();
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 启动 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
async function boot() {
|
||||
S.collapsed = localStorage.getItem('doubao.sidebar') === '1';
|
||||
applyTheme();
|
||||
applyLayout();
|
||||
renderSidebarSkeleton();
|
||||
|
||||
bindGlobalKeys();
|
||||
bindWindow();
|
||||
window.addEventListener('hashchange', handleRoute);
|
||||
// 界面能力通道(show_ui / ask_user):和内核状态无关,越早开始轮询越好
|
||||
startDeviceBridge();
|
||||
|
||||
// 对话切换(聊天页内部触发)→ 顶栏/侧栏跟着刷新(群聊顶栏要显示群名,单聊要显示会话主人)
|
||||
window.addEventListener('doubao:open-conversation', () => {
|
||||
renderTopbar();
|
||||
renderSidebar();
|
||||
});
|
||||
window.addEventListener('doubao:new-chat', () => {
|
||||
renderTopbar();
|
||||
renderSidebar();
|
||||
});
|
||||
|
||||
on('state', () => {
|
||||
renderSidebar();
|
||||
renderTopbar();
|
||||
});
|
||||
// 会话标题/顺序变了(聊天页 saved 事件、重命名、删除)→ 侧栏刷新
|
||||
on('conversations', () => renderSidebar());
|
||||
|
||||
try {
|
||||
setBoot('正在连接内核…');
|
||||
await loadState();
|
||||
setBoot(false);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setBoot(false);
|
||||
showBootError(err);
|
||||
return;
|
||||
}
|
||||
|
||||
renderSidebar();
|
||||
renderTopbar();
|
||||
if (!location.hash) history.replaceState(null, '', '#/chat');
|
||||
handleRoute();
|
||||
}
|
||||
|
||||
function renderSidebarSkeleton() {
|
||||
const el = sidebarEl();
|
||||
clear(el);
|
||||
el.appendChild(h('div.sb-brand', {}, h('div.sb-logo', {}, h('span.logo-dot', '豆'), '豆包')));
|
||||
el.appendChild(h('div.sb-empty', { style: 'padding:16px 8px' }, '正在加载…'));
|
||||
}
|
||||
|
||||
function showBootError(err) {
|
||||
const el = view();
|
||||
el.className = 'view page';
|
||||
mount(el, h('div.page-inner', {},
|
||||
h('div.empty-state', {},
|
||||
h('div.empty-state-icon', {}, icon('alert-triangle', 26)),
|
||||
h('div.empty-state-title', '内核没起来'),
|
||||
h('div.empty-state-desc', String((err && err.message) || err)),
|
||||
h('div', { style: 'margin-top:16px;display:flex;gap:8px;justify-content:center' },
|
||||
h('button.btn.primary', { onclick: () => location.reload() }, '重试')))));
|
||||
}
|
||||
|
||||
boot();
|
||||
366
web/js/device.js
Normal file
@@ -0,0 +1,366 @@
|
||||
/**
|
||||
* 网页端的「界面能力」通道 —— 补上电脑端和 App 之间最后一块功能差距。
|
||||
*
|
||||
* 背景:`show_ui`(AI 自己写 HTML 界面)/ `ask_user`(弹选项等用户选)/ `end_conversation`
|
||||
* 三个工具在安卓上走 Kotlin 的 NativeBridge;电脑端没有原生桥。
|
||||
* 现在内核开了一条 HTTP 队列:
|
||||
*
|
||||
* 内核(工具线程,阻塞等)
|
||||
* → GET /api/device/pending 的响应里带一个请求
|
||||
* 网页(本文件,每 700ms 轮询)
|
||||
* → 弹界面 / 选项弹窗
|
||||
* → 用户操作后 POST /api/device/answer {id, result}
|
||||
* 工具拿到结果继续跑
|
||||
*
|
||||
* 返回形状和安卓 NativeBridge.device() 完全一致,所以内核与工具代码不用区分平台。
|
||||
* 浏览器和 exe(Electron)共用这一条路 —— exe 不需要额外的原生桥。
|
||||
*/
|
||||
import { api } from './api.js';
|
||||
import { h, icon, toast, openModal, clear, injectStyles } from './ui.js';
|
||||
|
||||
injectStyles('device-bridge', `
|
||||
.dialog-question { font-size: 15px; font-weight: 500; line-height: 24px; padding: 2px 0 10px; white-space: pre-wrap; }
|
||||
.dialog-options { display: flex; flex-direction: column; gap: 8px; }
|
||||
.dialog-options .option-row { margin-bottom: 0; align-items: flex-start; }
|
||||
.option-main { flex: 1; min-width: 0; }
|
||||
.dialog-check {
|
||||
width: 20px; height: 20px; border-radius: 50%; flex: none;
|
||||
border: 1px solid var(--line-2); color: transparent;
|
||||
display: inline-flex; align-items: center; justify-content: center; margin-top: 2px;
|
||||
}
|
||||
.dialog-check.on { background: var(--brand); border-color: var(--brand); color: #fff; }
|
||||
.ui-screen-body { margin: 0 -6px 4px; }
|
||||
.ui-iframe {
|
||||
display: block; width: 100%; height: min(70vh, 700px);
|
||||
border: 1px solid var(--line-1); border-radius: 12px; background: var(--bg-body);
|
||||
}
|
||||
.ended-bar {
|
||||
display: flex; align-items: center; gap: 10px; margin-bottom: 8px;
|
||||
padding: 9px 12px; border-radius: var(--r-md);
|
||||
background: var(--bg-sidebar); border: 1px solid var(--line-1);
|
||||
font-size: 13px; color: var(--text-secondary);
|
||||
}
|
||||
.ended-bar .icon { color: var(--text-tertiary); flex: none; }
|
||||
.ended-bar span.ended-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
`);
|
||||
|
||||
const POLL_MS = 700;
|
||||
const WAIT_SCREEN_DEFAULT = '这个界面在等你操作';
|
||||
|
||||
let started = false;
|
||||
let busy = false;
|
||||
let pollTimer = null;
|
||||
|
||||
export function startDeviceBridge() {
|
||||
if (started) return;
|
||||
started = true;
|
||||
const tick = () => {
|
||||
pollOnce().finally(() => {
|
||||
pollTimer = setTimeout(tick, POLL_MS);
|
||||
});
|
||||
};
|
||||
tick();
|
||||
window.addEventListener('beforeunload', () => clearTimeout(pollTimer));
|
||||
}
|
||||
|
||||
async function pollOnce() {
|
||||
if (busy) return; // 正在等用户操作,别叠第二个
|
||||
let res;
|
||||
try {
|
||||
res = await api.get('/api/device/pending');
|
||||
} catch {
|
||||
return; // 内核没起来/重启中,下一拍再试
|
||||
}
|
||||
const req = res && res.request;
|
||||
if (!req || !req.id) return;
|
||||
|
||||
busy = true;
|
||||
try {
|
||||
if (req.notify) await handleNotifyScreen(req);
|
||||
else await handleBlocking(req);
|
||||
} catch (err) {
|
||||
// 本地渲染失败也要给内核一个结果,否则工具线程会白等到超时
|
||||
console.error('[device]', err);
|
||||
try { await answer(req.id, fallbackResult(req)); } catch { /* ignore */ }
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackResult(req) {
|
||||
if (req.action === 'ui_dialog') return { cancelled: true, values: [] };
|
||||
return { closed: true, value: '' };
|
||||
}
|
||||
|
||||
async function answer(id, result) {
|
||||
try {
|
||||
await api.post('/api/device/answer', { id, result });
|
||||
} catch (err) {
|
||||
toast(`界面结果没送出去:${err.message}`, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
function handleBlocking(req) {
|
||||
if (req.action === 'ui_dialog') return handleDialog(req);
|
||||
if (req.action === 'ui_screen') return handleScreen(req, { wait: true });
|
||||
// 不认识的请求:别让工具干等
|
||||
return answer(req.id, fallbackResult(req));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* ask_user:选择弹窗 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function handleDialog(req) {
|
||||
return new Promise((resolve) => {
|
||||
const options = Array.isArray(req.options) ? req.options : [];
|
||||
const multiple = !!req.multiple;
|
||||
const allowCancel = req.allowCancel !== false;
|
||||
const selected = new Set();
|
||||
|
||||
const list = h('div.dialog-options');
|
||||
const paint = () => {
|
||||
clear(list);
|
||||
options.forEach((opt) => {
|
||||
const on = selected.has(opt.value);
|
||||
const row = h(`div.option-row${on ? '.selected' : ''}`, {
|
||||
onclick: () => {
|
||||
if (multiple) {
|
||||
if (on) selected.delete(opt.value); else selected.add(opt.value);
|
||||
paint();
|
||||
return;
|
||||
}
|
||||
// 单选:点一下直接就是答案(少一次点击)
|
||||
finish([opt.value], false);
|
||||
},
|
||||
},
|
||||
h('div.option-main', {},
|
||||
h('div.option-title', opt.label || opt.value || ''),
|
||||
opt.description ? h('div.option-desc', opt.description) : null),
|
||||
h(`span.dialog-check${on ? '.on' : ''}`, {}, icon('check', 14)));
|
||||
list.appendChild(row);
|
||||
});
|
||||
};
|
||||
paint();
|
||||
|
||||
let done = false;
|
||||
let modal = null;
|
||||
const finish = (values, cancelled) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
if (modal) modal.close();
|
||||
answer(req.id, {
|
||||
cancelled: !!cancelled,
|
||||
values: values || [],
|
||||
choice: (values || [])[0] || '',
|
||||
multiple,
|
||||
timeout: false,
|
||||
}).then(() => resolve());
|
||||
};
|
||||
|
||||
const body = h('div', {},
|
||||
req.question ? h('div.dialog-question', String(req.question)) : null,
|
||||
list,
|
||||
multiple ? h('div', { style: 'font-size:12px;color:var(--text-tertiary);margin-top:6px' }, '可以多选,选完点确定') : null);
|
||||
|
||||
modal = openModal({
|
||||
title: '豆包想问你',
|
||||
width: 520,
|
||||
body,
|
||||
persistent: true,
|
||||
footer: h('div.modal-actions', {},
|
||||
allowCancel ? h('button.btn', { onclick: () => finish([], true) }, '取消') : null,
|
||||
multiple ? h('button.btn.primary', {
|
||||
onclick: () => {
|
||||
if (!selected.size) { toast('先选一个吧'); return; }
|
||||
finish([...selected], false);
|
||||
},
|
||||
}, '确定') : h('span', { style: 'font-size:12px;color:var(--text-tertiary)' }, '点一项即可回答')),
|
||||
onClose: () => { if (!done) { done = true; answer(req.id, { cancelled: true, values: [] }); resolve(); } },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* show_ui:AI 写的 HTML 界面 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function handleScreen(req, { wait = false } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const html = String(req.html || '');
|
||||
const title = req.title || 'AI 界面';
|
||||
const fullHtml = !!req.full_html;
|
||||
const conversationId = req.conversationId || '';
|
||||
|
||||
const iframe = h('iframe.ui-iframe', {
|
||||
sandbox: 'allow-scripts allow-forms allow-popups allow-modals allow-popups-to-escape-sandbox',
|
||||
title,
|
||||
});
|
||||
iframe.srcdoc = buildDoc(html, fullHtml, req);
|
||||
|
||||
let done = false;
|
||||
let modal = null;
|
||||
const finish = (result) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
if (modal) modal.close();
|
||||
if (wait) {
|
||||
answer(req.id, result || { closed: true, value: '', timeout: false }).then(() => resolve());
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
// iframe 里的 Doubao.sendToAi / Doubao.close / data-doubao-result 都走 postMessage
|
||||
const onMessage = (event) => {
|
||||
const data = event.data;
|
||||
if (!data || data.__doubao !== true) return;
|
||||
if (event.source !== iframe.contentWindow) return;
|
||||
if (data.kind === 'send') {
|
||||
const value = String(data.value == null ? '' : data.value);
|
||||
if (wait) finish({ value, closed: false, timeout: false });
|
||||
else {
|
||||
// 不等待的界面:用户的选择排进内核"待交付"队列,等他下次说话时带给模型
|
||||
api.post('/api/ui-result', { conversationId, value })
|
||||
.then(() => toast('已记下你的选择,下次说话时 AI 会看到', { type: 'success' }))
|
||||
.catch((err) => toast(err.message, { type: 'error' }));
|
||||
finish(null);
|
||||
}
|
||||
} else if (data.kind === 'close') {
|
||||
finish({ closed: true, value: '', timeout: false });
|
||||
}
|
||||
};
|
||||
window.addEventListener('message', onMessage);
|
||||
|
||||
modal = openModal({
|
||||
title,
|
||||
width: 960,
|
||||
body: h('div.ui-screen-body', {}, iframe),
|
||||
persistent: true,
|
||||
footer: h('div.modal-actions', {},
|
||||
wait
|
||||
? h('span', { style: 'font-size:12px;color:var(--text-tertiary)' }, WAIT_SCREEN_DEFAULT)
|
||||
: h('span', { style: 'font-size:12px;color:var(--text-tertiary)' }, '看完点关闭即可'),
|
||||
h('button.btn', {
|
||||
onclick: () => finish({ closed: true, value: '', timeout: false }),
|
||||
}, '关闭')),
|
||||
onClose: () => {
|
||||
window.removeEventListener('message', onMessage);
|
||||
if (!done) {
|
||||
done = true;
|
||||
if (wait) answer(req.id, { closed: true, value: '', timeout: false }).then(() => resolve());
|
||||
else resolve();
|
||||
}
|
||||
},
|
||||
});
|
||||
// 「关闭」按钮走 finish,不走 onClose,这里补一次监听清理
|
||||
const originalClose = modal.close;
|
||||
modal.close = () => {
|
||||
window.removeEventListener('message', onMessage);
|
||||
originalClose();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function handleNotifyScreen(req) {
|
||||
await handleScreen(req, { wait: false });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* AI 界面的 HTML 骨架(片段自动套样式;完整文档原样渲染) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const BRIDGE_JS = `
|
||||
(function () {
|
||||
var REQ = __REQ_ID__;
|
||||
function post(obj) {
|
||||
obj.__doubao = true;
|
||||
obj.id = REQ;
|
||||
try { parent.postMessage(obj, '*'); } catch (e) {}
|
||||
}
|
||||
function send(v) { post({ kind: 'send', value: v == null ? '' : String(v) }); }
|
||||
function close() { post({ kind: 'close' }); }
|
||||
window.Doubao = { sendToAi: send, pick: send, close: close };
|
||||
document.addEventListener('click', function (e) {
|
||||
var el = e.target && e.target.closest ? e.target.closest('[data-doubao-result]') : null;
|
||||
if (!el) return;
|
||||
e.preventDefault();
|
||||
send(el.getAttribute('data-doubao-result'));
|
||||
}, true);
|
||||
})();
|
||||
`;
|
||||
|
||||
function buildDoc(fragment, fullHtml, req) {
|
||||
const reqId = JSON.stringify(String(req.id || ''));
|
||||
const bridge = BRIDGE_JS.replace('__REQ_ID__', reqId);
|
||||
const inject = (doc) => {
|
||||
if (/<\/body>/i.test(doc)) return doc.replace(/<\/body>/i, `<script>${bridge}</script></body>`);
|
||||
return doc + `<script>${bridge}</script>`;
|
||||
};
|
||||
|
||||
if (fullHtml) {
|
||||
// 完整文档:只塞桥,不套样式(模型要完全控制)
|
||||
return inject(fragment);
|
||||
}
|
||||
|
||||
const dark = document.documentElement.dataset.theme === 'dark';
|
||||
const v = dark
|
||||
? {
|
||||
bg: '#121317', fg: '#e8eaed', code: '#1d1f25', border: '#2c2f36',
|
||||
th: '#1b1d22', quote: '#b9bdc4', link: '#7cb0ff', plain: '#262a31',
|
||||
}
|
||||
: {
|
||||
bg: '#ffffff', fg: '#1a1a1a', code: '#f4f4f6', border: '#e6e6e8',
|
||||
th: '#f7f7f8', quote: '#666', link: '#0066ff', plain: '#f2f3f5',
|
||||
};
|
||||
return `<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: ${dark ? 'dark' : 'light'}; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 18px 20px 40px;
|
||||
background: ${v.bg}; color: ${v.fg};
|
||||
font: 15px/1.7 -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
h1 { font-size: 22px; margin: 4px 0 12px; }
|
||||
h2 { font-size: 18px; margin: 20px 0 8px; }
|
||||
h3 { font-size: 16px; margin: 16px 0 6px; }
|
||||
p { margin: 8px 0; }
|
||||
a { color: ${v.link}; }
|
||||
code, pre {
|
||||
background: ${v.code}; border-radius: 8px;
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px;
|
||||
}
|
||||
code { padding: 2px 5px; }
|
||||
pre { padding: 12px; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||
th, td { border: 1px solid ${v.border}; padding: 8px 10px; text-align: left; }
|
||||
th { background: ${v.th}; font-weight: 600; }
|
||||
blockquote { margin: 12px 0; padding: 8px 14px; border-left: 3px solid ${v.border}; color: ${v.quote}; }
|
||||
img, svg, canvas { max-width: 100%; height: auto; }
|
||||
hr { border: 0; border-top: 1px solid ${v.border}; margin: 18px 0; }
|
||||
|
||||
/* 可点的按钮做得非常显眼(和安卓端 AI 界面同一套约定) */
|
||||
.db-btn, button, [data-doubao-result], [role=button] {
|
||||
display: block !important; width: 100% !important; margin: 10px 0 !important;
|
||||
padding: 14px 18px !important;
|
||||
background: #2b7bff !important; color: #fff !important;
|
||||
text-decoration: none !important; text-align: center !important;
|
||||
border: 0 !important; border-radius: 12px !important;
|
||||
font-size: 16px !important; font-weight: 500 !important; line-height: 1.4 !important;
|
||||
cursor: pointer !important; -webkit-appearance: none; appearance: none;
|
||||
}
|
||||
.db-btn:active, button:active, [data-doubao-result]:active, [role=button]:active {
|
||||
background: #1e63d6 !important; transform: scale(0.985);
|
||||
}
|
||||
.db-plain, button.db-plain { background: ${v.plain} !important; color: ${v.fg} !important; border: 1px solid ${v.border} !important; }
|
||||
.db-row { display: flex; gap: 10px; }
|
||||
.db-row > * { flex: 1; }
|
||||
</style></head>
|
||||
<body>
|
||||
${fragment}
|
||||
</body></html>`;
|
||||
}
|
||||
95
web/js/icons.js
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 图标库 —— 全部是项目自己的手写路径(Lucide 风格,24x24,stroke=2),
|
||||
* 不复制豆包的图标资源,只参考其线条风格。
|
||||
*
|
||||
* 用法:icon('send', 18) → <svg ...>
|
||||
* 也可在 h() 里:h('span.icon', {icon:'send'})
|
||||
*/
|
||||
const P = {
|
||||
// ---- 侧栏 / 导航 ----
|
||||
'panel-left': '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/>',
|
||||
'panel-left-open': '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="m14 9 3 3-3 3"/>',
|
||||
'panel-left-close': '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="m17 9-3 3 3 3"/>',
|
||||
'pen-square': '<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.4 2.6a2.1 2.1 0 0 1 3 3L8 19l-4 1 1-4Z"/>',
|
||||
'new-chat': '<path d="M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.4 2.6a2.1 2.1 0 0 1 3 3L8 19l-4 1 1-4Z"/>',
|
||||
'message-circle': '<path d="M21 11.5a8.4 8.4 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7a8.5 8.5 0 1 1 16.1-3.8Z"/>',
|
||||
'message-square': '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z"/>',
|
||||
'bot': '<rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><path d="M8 16h.01"/><path d="M16 16h.01"/>',
|
||||
'users': '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
|
||||
'layers': '<path d="m12 2 10 5-10 5L2 7Z"/><path d="m2 17 10 5 10-5"/><path d="m2 12 10 5 10-5"/>',
|
||||
'presentation': '<path d="M2 3h20"/><path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"/><path d="m7 21 5-5 5 5"/>',
|
||||
'plug': '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>',
|
||||
'settings': '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/>',
|
||||
'info': '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
|
||||
'download': '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
|
||||
'search': '<circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>',
|
||||
'sun': '<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.9 4.9 1.4 1.4"/><path d="m17.7 17.7 1.4 1.4"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.3 17.7-1.4 1.4"/><path d="m19.1 4.9-1.4 1.4"/>',
|
||||
'moon': '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
|
||||
'user': '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
|
||||
'more-horizontal': '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
|
||||
'chevron-down': '<path d="m6 9 6 6 6-6"/>',
|
||||
'chevron-right': '<path d="m9 18 6-6-6-6"/>',
|
||||
'chevron-left': '<path d="m15 18-6-6 6-6"/>',
|
||||
'arrow-left': '<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>',
|
||||
'arrow-up': '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
|
||||
'plus': '<path d="M12 5v14"/><path d="M5 12h14"/>',
|
||||
'mic': '<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><path d="M12 19v3"/>',
|
||||
'paperclip': '<path d="m21.4 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>',
|
||||
'camera': '<path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3Z"/><circle cx="12" cy="13" r="3"/>',
|
||||
'image': '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/>',
|
||||
'file-text': '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>',
|
||||
'globe': '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
|
||||
'copy': '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>',
|
||||
'thumbs-up': '<path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"/>',
|
||||
'thumbs-down': '<path d="M17 14V2"/><path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"/>',
|
||||
'share': '<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/>',
|
||||
'volume': '<path d="M11 5 6 9H2v6h4l5 4V5Z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>',
|
||||
'volume-x': '<path d="M11 5 6 9H2v6h4l5 4V5Z"/><path d="m22 9-6 6"/><path d="m16 9 6 6"/>',
|
||||
'refresh': '<path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/>',
|
||||
'x': '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
|
||||
'check': '<path d="M20 6 9 17l-5-5"/>',
|
||||
'trash': '<path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>',
|
||||
'pin': '<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1Z"/>',
|
||||
'pencil': '<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>',
|
||||
'sparkles': '<path d="m12 3 1.9 5.8a2 2 0 0 0 1.3 1.3L21 12l-5.8 1.9a2 2 0 0 0-1.3 1.3L12 21l-1.9-5.8a2 2 0 0 0-1.3-1.3L3 12l5.8-1.9a2 2 0 0 0 1.3-1.3Z"/>',
|
||||
'brain': '<path d="M12 5a3 3 0 0 0-5.9 1 3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 5.9 1"/><path d="M12 5a3 3 0 0 1 5.9 1 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-5.9 1"/><path d="M12 5v14"/>',
|
||||
'square': '<rect x="4" y="4" width="16" height="16" rx="3"/>',
|
||||
'clock': '<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>',
|
||||
'notebook': '<path d="M4 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2Z"/><path d="M8 2v20"/><path d="M12 7h5"/><path d="M12 11h5"/><path d="M12 15h5"/>',
|
||||
'terminal': '<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>',
|
||||
'key': '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>',
|
||||
'alert-triangle': '<path d="m21.7 18-8-14a2 2 0 0 0-3.4 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',
|
||||
'folder': '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
|
||||
'external-link': '<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',
|
||||
'list': '<path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/>',
|
||||
'sliders': '<path d="M4 21v-7"/><path d="M4 10V3"/><path d="M12 21v-9"/><path d="M12 8V3"/><path d="M20 21v-5"/><path d="M20 12V3"/><path d="M2 14h4"/><path d="M10 8h4"/><path d="M18 16h4"/>',
|
||||
'cpu': '<rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M9 2v2"/><path d="M15 2v2"/><path d="M9 20v2"/><path d="M15 20v2"/><path d="M2 9h2"/><path d="M2 15h2"/><path d="M20 9h2"/><path d="M20 15h2"/>',
|
||||
'shield': '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/>',
|
||||
'at-sign': '<circle cx="12" cy="12" r="4"/><path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.9 7.9"/>',
|
||||
'hash': '<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',
|
||||
'play': '<path d="m6 3 14 9-14 9V3Z"/>',
|
||||
'pause': '<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>',
|
||||
'arrow-right': '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
|
||||
'arrow-down': '<path d="m7 5 5 5 5-5"/><path d="M12 5v14"/>',
|
||||
'image-plus': '<path d="M21 15V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><path d="M19 22v-6"/><path d="M16 19h6"/>',
|
||||
'database': '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/>',
|
||||
'book': '<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2Z"/>',
|
||||
'history': '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
|
||||
'stop-circle': '<circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/>',
|
||||
'grip-vertical': '<circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/>',
|
||||
'scan': '<path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><path d="M7 12h10"/>',
|
||||
'types': '<path d="M12 4v16"/><path d="M4 7V5h16v2"/><path d="M9 20h6"/>',
|
||||
'heart': '<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',
|
||||
'download-cloud': '<path d="M12 13v8l-4-4"/><path d="m12 21 4-4"/><path d="M4.39 15A7 7 0 1 1 15.7 6.1"/>',
|
||||
};
|
||||
|
||||
/**
|
||||
* 返回图标的 SVG 字符串(由 ui.js 负责塞进 DOM,避免反向依赖)。
|
||||
*/
|
||||
export function iconHtml(name, size = 18) {
|
||||
const body = P[name];
|
||||
if (!body) return '';
|
||||
return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
|
||||
}
|
||||
|
||||
export const ICON_NAMES = Object.keys(P);
|
||||
27
web/js/pages/_stub.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 未完成页面的占位:写明这个页面要做什么 + 需要哪些接口,方便后面接手的人(或 AI)补。
|
||||
* 真正的实现按页面逐个替换掉,不留 TODO 在暗处。
|
||||
*/
|
||||
import { h, icon, mount, emptyState } from '../ui.js';
|
||||
|
||||
export function makeStub({ title, desc, apis = [], plan = [] }) {
|
||||
return function stub(container, ctx) {
|
||||
const el = h('div.page-inner', {},
|
||||
h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', title),
|
||||
h('div.page-sub', desc))),
|
||||
h('div.empty-state', {},
|
||||
h('div.empty-state-icon', {}, icon('layers', 26)),
|
||||
h('div.empty-state-title', '这个页面还没做完'),
|
||||
h('div.empty-state-desc', '页面骨架已经留好,功能实现中。'),
|
||||
apis.length ? h('div', { style: 'margin-top:18px;text-align:left;max-width:560px' },
|
||||
h('div.section-title', {}, '会用到的接口'),
|
||||
h('div.card', {}, apis.map((a) => h('div.kv', {}, h('span.k', a.method || 'GET'), h('span.v', a.path))))) : null,
|
||||
plan.length ? h('div', { style: 'margin-top:14px;text-align:left;max-width:560px' },
|
||||
h('div.section-title', {}, '要做的事'),
|
||||
h('div.card', {}, plan.map((p) => h('div', { style: 'padding:4px 0;font-size:13px;color:var(--text-secondary)' }, `· ${p}`)))) : null));
|
||||
mount(container, el);
|
||||
ctx.setTitle(title);
|
||||
};
|
||||
}
|
||||
79
web/js/pages/about.js
Normal file
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 关于页:项目定位 / 架构 / 快捷键 / 第三方 / 商标声明。
|
||||
* 纯静态,不需要接口。
|
||||
*/
|
||||
import { h, icon, mount, injectStyles } from '../ui.js';
|
||||
import { S, platform } from '../api.js';
|
||||
|
||||
injectStyles('about', `
|
||||
.about-links { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
|
||||
.about-kbd {
|
||||
display: inline-flex; align-items: center; gap: 6px; padding: 2px 8px;
|
||||
border: 1px solid var(--line-2); border-bottom-width: 2px; border-radius: 6px;
|
||||
font-family: var(--font-mono); font-size: 12px; background: var(--bg-sidebar);
|
||||
}
|
||||
.about-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px; }
|
||||
`);
|
||||
|
||||
const SHORTCUTS = [
|
||||
['Ctrl Shift K', '新对话'],
|
||||
['Ctrl B', '收起 / 展开侧栏'],
|
||||
['Ctrl K', '搜索对话'],
|
||||
['Esc', '停止正在生成的回复 / 关闭弹层'],
|
||||
['Enter', '发送(Shift+Enter 换行)'],
|
||||
];
|
||||
|
||||
export default function renderAbout(container, ctx) {
|
||||
const version = 'v2 · 网页版';
|
||||
const page = h('div.page-inner', {},
|
||||
h('div.about-hero', {},
|
||||
h('div.about-icon', '豆'),
|
||||
h('div', {},
|
||||
h('div.page-title', '豆包 · 网页版复刻'),
|
||||
h('div.page-sub', `${version} · 界面参考豆包网页版(www.doubao.com/chat),实现与 Android App 共用同一份 AI 内核`))),
|
||||
|
||||
h('div.card', { style: 'margin-top:18px' },
|
||||
h('div.card-title', {}, icon('info', 17), '这是什么'),
|
||||
h('div.card-desc', { style: 'line-height:24px' },
|
||||
'一个学习目的的界面复刻项目:前端是纯 HTML/CSS/JS(无第三方框架),',
|
||||
'后端是仓库里的纯标准库 Python AI 内核,桌面版用 Electron 打包、内嵌 Python。',
|
||||
'手机上还有一版原生 Kotlin/Compose 的 App,两边共用同一份内核,所以功能天然同步。'),
|
||||
h('div.about-links', {},
|
||||
h('a.btn.sm', { href: 'https://www.doubao.com/chat/', target: '_blank', rel: 'noreferrer' }, icon('external-link', 14), '豆包官网(界面参考)'),
|
||||
h('a.btn.sm', { href: 'https://www.volcengine.com/docs/82379/1298454', target: '_blank', rel: 'noreferrer' }, icon('external-link', 14), '火山方舟文档'))),
|
||||
|
||||
h('div.card', {},
|
||||
h('div.card-title', {}, icon('cpu', 17), '技术架构'),
|
||||
h('div', { style: 'margin-top:10px' },
|
||||
[
|
||||
['网页前端', 'web/ · 纯静态(无构建步骤),由内核直接托管'],
|
||||
['AI 内核', 'android/kernel/ · 纯标准库 Python(HTTP 服务 + 工具 + MCP + 语音)'],
|
||||
['桌面壳', 'desktop/ · Electron,主进程起 Python 子进程并开窗'],
|
||||
['手机 App', 'android/ · Kotlin + Jetpack Compose,内核跑在进程内'],
|
||||
['数据目录', '桌面:%APPDATA%\\Doubao\\data;开发:仓库 data/'],
|
||||
].map(([k, v]) => h('div.kv', {}, h('span.k', k), h('span.v', v))))),
|
||||
|
||||
h('div.about-grid', { style: 'margin-top:12px' },
|
||||
h('div.card', {},
|
||||
h('div.card-title', {}, icon('terminal', 17), '键盘快捷键'),
|
||||
h('div', { style: 'margin-top:10px;display:flex;flex-direction:column;gap:8px' },
|
||||
SHORTCUTS.map(([k, v]) => h('div', { style: 'display:flex;align-items:center;gap:10px;font-size:13px' },
|
||||
h('span.about-kbd', k),
|
||||
h('span', { style: 'color:var(--text-secondary)' }, v))))),
|
||||
h('div.card', {},
|
||||
h('div.card-title', {}, icon('shield', 17), '环境信息'),
|
||||
h('div', { style: 'margin-top:10px' },
|
||||
h('div.kv', {}, h('span.k', '运行平台'), h('span.v', platform() || '—')),
|
||||
h('div.kv', {}, h('span.k', '模型'), h('span.v', (S.state && S.state.settings && S.state.settings.model) || '未配置')),
|
||||
h('div.kv', {}, h('span.k', '界面版本'), h('span.v', version))))),
|
||||
|
||||
h('div.card', { style: 'margin-top:12px' },
|
||||
h('div.card-title', {}, icon('alert-triangle', 17), '声明'),
|
||||
h('div.card-desc', { style: 'font-size:13px;line-height:22px' },
|
||||
'本项目与字节跳动没有任何关系,也不包含任何来自豆包 App / 网页版的代码或素材;',
|
||||
'「豆包」是字节跳动的商标。界面配色与布局参考公开页面,图标全部为本项目手写 SVG。',
|
||||
'项目采用 MIT License(见仓库 LICENSE 文件);Electron / CPython 等第三方组件各自遵循其许可。')));
|
||||
|
||||
mount(container, page);
|
||||
ctx.setTitle('关于豆包');
|
||||
}
|
||||
592
web/js/pages/agent-edit.js
Normal file
@@ -0,0 +1,592 @@
|
||||
/**
|
||||
* 智能体编辑页(#/agents/:id)
|
||||
*
|
||||
* ★ 内核**没有** `GET /api/agents/<id>`(会 404「未知接口」),
|
||||
* 所以这一页的数据全部从 `state.agents` 里按 id 找。
|
||||
*
|
||||
* 保存 = 只发改动过的字段(内核是浅合并,全量下发会把没填的键清空):
|
||||
* PATCH /api/agents/<id> 文本 / 数字 / 布尔字段
|
||||
* PUT /api/agents/<id>/skills {skillIds} —— 数组顺序就是注入顺序
|
||||
*
|
||||
* 技能**必须**走第二个接口:`skillIds` 虽然在 PATCH 的白名单里,但它只改
|
||||
* agents.json 里那条 JSON,真正生效的绑定在 agent.db 的 `agent_skills` 表
|
||||
* (docs/kernel-api-agents.md §2.1、§14 #24 —— 只 PATCH 会出现"勾了保存后又没了")。
|
||||
*
|
||||
* 其它入口:记忆 / 用量 / 导出 / 删除(内置 4 个删不掉,入口直接隐藏)。
|
||||
*/
|
||||
import {
|
||||
api, loadState, agents, settings, providers, S,
|
||||
} from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, confirmBox, spinner,
|
||||
fieldRow, switchEl, injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
/** 内核白名单里的 9 个头像 key(defaults.AVATAR_KEYS) */
|
||||
const AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'cloud', 'robot', 'star', 'custom'];
|
||||
const AVATAR_LABELS = {
|
||||
doubao: '豆包', coder: '代码', writer: '文案', analyst: '数据',
|
||||
cat: '猫', cloud: '云', robot: '机器人', star: '星星', custom: '自定义',
|
||||
};
|
||||
|
||||
/** 文本字段:空串也是合法值(= 继承全局 / 清空人设) */
|
||||
const TEXT_FIELDS = [
|
||||
'name', 'tagline', 'avatar', 'systemPrompt',
|
||||
'provider', 'model', 'baseUrl', 'modelId', 'worldviewId', 'ttsVoice',
|
||||
];
|
||||
/** 数字字段:留空 = 不修改(内核 `float('')` 会抛异常后静默跳过,等于没改) */
|
||||
const NUM_FIELDS = ['tokenLimit', 'contextWindow'];
|
||||
|
||||
const CSS = `
|
||||
.ae-head { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.ae-head .avatar { flex: none; box-shadow: var(--shadow-xs); }
|
||||
.ae-head-main { min-width: 0; }
|
||||
.ae-title-row { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.ae-title { font-size: 22px; line-height: 30px; font-weight: 600; letter-spacing: -0.2px;
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ae-sub { margin-top: 2px; font-size: 13px; line-height: 20px; color: var(--text-secondary);
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ae-sec { margin-top: 12px; padding: 16px 20px 8px; }
|
||||
.ae-sec-head { padding-bottom: 2px; }
|
||||
.ae-sec .field-row:last-child { border-bottom: 0; }
|
||||
.ae-pick { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.ae-pick button { width: 46px; height: 46px; padding: 2px; border: 2px solid transparent;
|
||||
border-radius: var(--r-md); background: var(--bg-base-2); cursor: pointer; line-height: 0;
|
||||
transition: border-color .12s var(--ease), background .12s var(--ease); }
|
||||
.ae-pick button:hover { background: var(--fill-3); }
|
||||
.ae-pick button.on { border-color: var(--brand); background: var(--brand-weak); }
|
||||
.ae-pick img { width: 100%; height: 100%; border-radius: 10px; object-fit: cover; display: block; }
|
||||
.ae-preview-row { display: flex; align-items: center; gap: 10px; }
|
||||
.ae-skills { display: flex; flex-direction: column; gap: 10px; width: 100%; }
|
||||
.ae-skill-group { border: 1px solid var(--line-1); border-radius: var(--r-md); padding: 4px 12px; }
|
||||
.ae-skill-group-title { font-size: 12px; line-height: 18px; color: var(--text-tertiary); padding: 6px 0 2px; }
|
||||
.ae-skill-row { display: flex; align-items: center; gap: 10px; padding: 7px 0; border-top: 1px solid var(--line-1); }
|
||||
.ae-skill-group-title + .ae-skill-row { border-top: 0; }
|
||||
.ae-skill-ord { width: 16px; flex: none; text-align: right; font-size: 12px; color: var(--text-tertiary); }
|
||||
.ae-skill-name { flex: 1; min-width: 0; font-size: 14px; line-height: 22px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ae-skill-side { display: flex; align-items: center; gap: 2px; flex: none; }
|
||||
.ae-hint-box { font-size: 12px; line-height: 18px; color: var(--text-tertiary); padding: 2px 0 6px; }
|
||||
.ae-model-hint { font-size: 12px; line-height: 18px; color: var(--text-tertiary); }
|
||||
.ae-foot { margin-top: 16px; display: flex; align-items: center; gap: 8px; }
|
||||
.ae-foot .spacer { flex: 1; }
|
||||
.ae-num { max-width: 220px; }
|
||||
`;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const listOf = (key) => ((S.state && Array.isArray(S.state[key])) ? S.state[key] : []);
|
||||
|
||||
function avatarImg(key, size = 40) {
|
||||
return h('img', {
|
||||
src: `/assets/avatars/${AVATAR_KEYS.includes(key) ? key : 'custom'}.png`,
|
||||
alt: '',
|
||||
style: `width:${size}px;height:${size}px;border-radius:12px;object-fit:cover;display:block`,
|
||||
onerror: (e) => { e.target.src = '/assets/avatars/custom.png'; },
|
||||
});
|
||||
}
|
||||
|
||||
function downloadBase64(name, base64, mime = 'application/zip') {
|
||||
const bin = atob(String(base64 || ''));
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: mime }));
|
||||
const a = h('a', { href: url, download: name });
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 5000);
|
||||
}
|
||||
|
||||
/** 表单快照:保存时只挑和它不同的字段 */
|
||||
function snapshotOf(agent) {
|
||||
const snap = {};
|
||||
for (const key of TEXT_FIELDS) snap[key] = String(agent[key] == null ? '' : agent[key]);
|
||||
snap.tokenLimit = agent.tokenLimit == null ? '' : String(Number(agent.tokenLimit) || 0);
|
||||
snap.contextWindow = agent.contextWindow == null ? '' : String(Number(agent.contextWindow) || 0);
|
||||
snap.emotionEnabled = !!agent.emotionEnabled;
|
||||
return snap;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 页面 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export default function renderAgentEdit(container, ctx) {
|
||||
injectStyles('page-agent-edit', CSS);
|
||||
|
||||
const root = h('div.page-inner');
|
||||
mount(container, root);
|
||||
|
||||
let agent = agents().find((a) => a.id === ctx.params.id) || null;
|
||||
ctx.setTitle('编辑智能体');
|
||||
|
||||
/* ---------------- 找不到 / 已删除 ---------------- */
|
||||
|
||||
if (!agent) {
|
||||
clear(root);
|
||||
root.appendChild(h('div.page-head', {},
|
||||
h('div.page-head-left.ae-head', {},
|
||||
h('button.icon-btn', { title: '返回智能体列表', onclick: () => ctx.navigate('agents') }, icon('arrow-left', 18)),
|
||||
h('div.ae-head-main', {},
|
||||
h('div.ae-title', '找不到这个智能体'),
|
||||
h('div.ae-sub', `id:${ctx.params.id}`)))));
|
||||
root.appendChild(h('div.card.ae-sec', {},
|
||||
h('div.ae-hint-box', { style: 'font-size:13px;line-height:20px;color:var(--text-secondary)' },
|
||||
'它可能已经被删掉了,或者链接里的 id 不对。内核没有「按 id 读单个智能体」的接口,'
|
||||
+ '这一页的数据只来自 /api/state —— 列表里没有,就是没有了。'),
|
||||
h('div', { style: 'margin-top:10px;display:flex;gap:8px' },
|
||||
h('button.btn.primary', { onclick: () => ctx.navigate('agents') }, '回到智能体列表'),
|
||||
h('button.btn', {
|
||||
onclick: async () => {
|
||||
try {
|
||||
await loadState();
|
||||
toast('状态已刷新,回列表看看', { type: 'success' });
|
||||
ctx.navigate('agents');
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
}, '重新拉状态'))));
|
||||
return undefined;
|
||||
}
|
||||
|
||||
ctx.setTitle(agent.name || '编辑智能体');
|
||||
|
||||
/* ---------------- 本地状态 ---------------- */
|
||||
|
||||
let snapshot = snapshotOf(agent);
|
||||
let skills = Array.isArray(agent.skillIds) ? agent.skillIds.slice() : [];
|
||||
let snapshotSkills = skills.slice();
|
||||
let skillsLoaded = false;
|
||||
let skillsError = '';
|
||||
let saving = false;
|
||||
let currentAvatar = AVATAR_KEYS.includes(agent.avatar) ? agent.avatar : 'custom';
|
||||
|
||||
const skillsBox = h('div.ae-skills');
|
||||
const headAvatar = h('span');
|
||||
const headTitle = h('div.ae-title');
|
||||
const headSub = h('div.ae-sub');
|
||||
|
||||
/* ---------------- 表单控件 ---------------- */
|
||||
|
||||
const nameInput = h('input.input', { value: agent.name || '', maxlength: 24, placeholder: '智能体名字' });
|
||||
const tagInput = h('input.input', { value: agent.tagline || '', maxlength: 40, placeholder: '一句话介绍' });
|
||||
const promptInput = h('textarea.textarea', {
|
||||
rows: 8,
|
||||
placeholder: '人设 / 系统提示词。留空 = 用全局系统提示词。',
|
||||
style: 'min-height:180px;font-size:14px;line-height:22px',
|
||||
});
|
||||
promptInput.value = agent.systemPrompt || '';
|
||||
|
||||
const avatarPick = h('div.ae-pick');
|
||||
const avatarPreview = h('div.ae-preview-row');
|
||||
|
||||
const modelRefSel = h('select.select');
|
||||
const providerSel = h('select.select');
|
||||
const modelInput = h('input.input', {
|
||||
value: agent.model || '',
|
||||
placeholder: '留空 = 跟随全局(例:doubao-seed-2-1-pro-260628)',
|
||||
});
|
||||
const baseUrlInput = h('input.input', {
|
||||
value: agent.baseUrl || '',
|
||||
placeholder: '留空 = 跟随全局(例:https://ark.cn-beijing.volces.com/api/v3)',
|
||||
});
|
||||
const worldSel = h('select.select');
|
||||
const voiceSel = h('select.select');
|
||||
const tokenInput = h('input.input.ae-num', {
|
||||
type: 'number',
|
||||
min: 0,
|
||||
step: 1000,
|
||||
value: agent.tokenLimit == null ? '' : String(Number(agent.tokenLimit) || 0),
|
||||
placeholder: '0 = 不限制',
|
||||
});
|
||||
const ctxInput = h('input.input.ae-num', {
|
||||
type: 'number',
|
||||
min: 0,
|
||||
step: 1,
|
||||
value: agent.contextWindow == null ? '' : String(Number(agent.contextWindow) || 0),
|
||||
placeholder: `留空 = 跟随全局${settings().contextWindow != null ? `(${settings().contextWindow} 轮)` : ''}`,
|
||||
});
|
||||
const emotionSwitch = switchEl({ checked: !!agent.emotionEnabled });
|
||||
const emotionInput = emotionSwitch.querySelector('.switch-input');
|
||||
|
||||
const saveBtn = h('button.btn.primary', { onclick: () => save() }, '保存');
|
||||
const saveBtn2 = h('button.btn.primary', { style: 'min-width:120px', onclick: () => save() }, '保存改动');
|
||||
|
||||
/* ---------------- 各下拉的选项 ---------------- */
|
||||
|
||||
// 引用全局模型
|
||||
modelRefSel.appendChild(h('option', { value: '' }, '不引用(用下面的连接参数)'));
|
||||
for (const entry of listOf('modelEntries')) {
|
||||
modelRefSel.appendChild(h('option', { value: entry.id }, entry.name || entry.model || entry.id));
|
||||
}
|
||||
if (agent.modelId && !listOf('modelEntries').some((m) => m.id === agent.modelId)) {
|
||||
modelRefSel.appendChild(h('option', { value: agent.modelId }, '(已删除的模型)'));
|
||||
}
|
||||
modelRefSel.value = agent.modelId || '';
|
||||
|
||||
// 提供商
|
||||
providerSel.appendChild(h('option', { value: '' }, '跟随全局'));
|
||||
const presets = providers() || {};
|
||||
for (const [key, preset] of Object.entries(presets)) {
|
||||
providerSel.appendChild(h('option', { value: key }, preset && preset.label ? `${preset.label}(${key})` : key));
|
||||
}
|
||||
if (agent.provider && !presets[agent.provider]) {
|
||||
providerSel.appendChild(h('option', { value: agent.provider }, `${agent.provider}(自定义)`));
|
||||
}
|
||||
providerSel.value = agent.provider || '';
|
||||
|
||||
// 世界观
|
||||
worldSel.appendChild(h('option', { value: '' }, '不绑定(记忆只属于自己)'));
|
||||
for (const world of listOf('worldviews')) {
|
||||
worldSel.appendChild(h('option', { value: world.id }, world.name || world.id));
|
||||
}
|
||||
if (agent.worldviewId && !listOf('worldviews').some((w) => w.id === agent.worldviewId)) {
|
||||
worldSel.appendChild(h('option', { value: agent.worldviewId }, '(已删除的世界观)'));
|
||||
}
|
||||
worldSel.value = agent.worldviewId || '';
|
||||
|
||||
// 音色(内核给的是「常用」那一组;留空 = 跟随全局)
|
||||
voiceSel.appendChild(h('option', { value: '' }, '跟随全局音色'));
|
||||
const voices = (S.state && S.state.speechVoices) || {};
|
||||
let voiceFound = !agent.ttsVoice;
|
||||
for (const [key, label] of [['volcv3', '火山引擎 V3(大模型音色)'], ['volc', '火山引擎 V1'], ['openai', 'OpenAI'], ['system', '系统语音']]) {
|
||||
const items = Array.isArray(voices[key]) ? voices[key] : [];
|
||||
if (!items.length) continue;
|
||||
const group = h('optgroup', { label });
|
||||
for (const item of items) {
|
||||
const value = item && (item.value || item.id);
|
||||
if (!value) continue;
|
||||
if (value === agent.ttsVoice) voiceFound = true;
|
||||
group.appendChild(h('option', { value }, item.label || value));
|
||||
}
|
||||
voiceSel.appendChild(group);
|
||||
}
|
||||
if (!voiceFound && agent.ttsVoice) {
|
||||
voiceSel.appendChild(h('option', { value: agent.ttsVoice }, `${agent.ttsVoice}(不在常用列表里)`));
|
||||
}
|
||||
voiceSel.value = agent.ttsVoice || '';
|
||||
|
||||
/* ---------------- 头像 ---------------- */
|
||||
|
||||
function refreshAvatar() {
|
||||
for (const btn of avatarPick.children) btn.classList.toggle('on', btn.dataset.key === currentAvatar);
|
||||
clear(avatarPreview);
|
||||
avatarPreview.appendChild(avatarImg(currentAvatar, 40));
|
||||
avatarPreview.appendChild(h('span.ae-model-hint', AVATAR_LABELS[currentAvatar] || currentAvatar));
|
||||
}
|
||||
for (const key of AVATAR_KEYS) {
|
||||
avatarPick.appendChild(h('button', {
|
||||
type: 'button',
|
||||
title: AVATAR_LABELS[key] || key,
|
||||
dataset: { key },
|
||||
onclick: () => { currentAvatar = key; refreshAvatar(); },
|
||||
}, avatarImg(key, 36)));
|
||||
}
|
||||
refreshAvatar();
|
||||
|
||||
/* ---------------- 技能(顺序 = 注入顺序) ---------------- */
|
||||
|
||||
function skillName(id) {
|
||||
const item = listOf('skills').find((s) => s.id === id);
|
||||
return item ? (item.name || '未命名技能') : '(已删除的技能)';
|
||||
}
|
||||
|
||||
function moveSkill(index, delta) {
|
||||
const next = index + delta;
|
||||
if (next < 0 || next >= skills.length) return;
|
||||
const [id] = skills.splice(index, 1);
|
||||
skills.splice(next, 0, id);
|
||||
renderSkills();
|
||||
}
|
||||
|
||||
function renderSkills() {
|
||||
clear(skillsBox);
|
||||
if (!skillsLoaded) {
|
||||
skillsBox.appendChild(h('div.ae-hint-box', {}, spinner(14), ' 正在读技能绑定…'));
|
||||
return;
|
||||
}
|
||||
if (skillsError) {
|
||||
skillsBox.appendChild(h('div.ae-hint-box', { style: 'color:var(--danger)' }, skillsError));
|
||||
}
|
||||
const all = listOf('skills');
|
||||
if (!all.length) {
|
||||
skillsBox.appendChild(h('div.ae-hint-box', {},
|
||||
'还没有自定义 Skill(「资源」页可以新建)。内置手册每一轮都会注入,不需要在这里勾。',
|
||||
h('div', { style: 'margin-top:8px' },
|
||||
h('button.btn.sm', { onclick: () => ctx.navigate('resources') }, '去资源页新建 Skill'))));
|
||||
return;
|
||||
}
|
||||
|
||||
const chosen = h('div.ae-skill-group', {}, h('div.ae-skill-group-title', '已选(按这个顺序注入)'));
|
||||
if (!skills.length) chosen.appendChild(h('div.ae-hint-box', '还没有勾任何 Skill。'));
|
||||
skills.forEach((id, i) => {
|
||||
chosen.appendChild(h('div.ae-skill-row', {},
|
||||
h('div.ae-skill-ord', String(i + 1)),
|
||||
h('div.ae-skill-name', { title: skillName(id) }, skillName(id)),
|
||||
h('div.ae-skill-side', {},
|
||||
h('button.icon-btn.sm', {
|
||||
title: '上移',
|
||||
disabled: i === 0 ? 'disabled' : null,
|
||||
onclick: () => moveSkill(i, -1),
|
||||
}, icon('arrow-up', 14)),
|
||||
h('button.icon-btn.sm', {
|
||||
title: '下移',
|
||||
disabled: i === skills.length - 1 ? 'disabled' : null,
|
||||
onclick: () => moveSkill(i, 1),
|
||||
}, icon('arrow-down', 14)),
|
||||
h('button.icon-btn.sm', {
|
||||
title: '移出',
|
||||
onclick: () => { skills = skills.filter((x) => x !== id); renderSkills(); },
|
||||
}, icon('x', 14)))));
|
||||
});
|
||||
|
||||
const rest = all.filter((s) => !skills.includes(s.id));
|
||||
const pool = h('div.ae-skill-group', {}, h('div.ae-skill-group-title', '可选的 Skill'));
|
||||
if (!rest.length) pool.appendChild(h('div.ae-hint-box', '全部都已经勾上了。'));
|
||||
for (const item of rest) {
|
||||
pool.appendChild(h('div.ae-skill-row', {},
|
||||
h('div.ae-skill-ord', {}),
|
||||
h('div.ae-skill-name', { title: item.name || '' }, item.name || '未命名技能'),
|
||||
h('div.ae-skill-side', {},
|
||||
h('button.btn.sm', {
|
||||
onclick: () => { skills = [...skills, item.id]; renderSkills(); },
|
||||
}, icon('plus', 14), '加入'))));
|
||||
}
|
||||
|
||||
skillsBox.appendChild(chosen);
|
||||
skillsBox.appendChild(pool);
|
||||
}
|
||||
|
||||
async function loadSkills() {
|
||||
try {
|
||||
const res = await api.get(`/api/agents/${encodeURIComponent(agent.id)}/skills`);
|
||||
skills = res && Array.isArray(res.skillIds) ? res.skillIds.slice() : [];
|
||||
skillsError = '';
|
||||
snapshotSkills = skills.slice();
|
||||
} catch (err) {
|
||||
skills = Array.isArray(agent.skillIds) ? agent.skillIds.slice() : [];
|
||||
snapshotSkills = skills.slice();
|
||||
skillsError = `技能绑定没读到(先用列表里的旧值兜底):${err.message}`;
|
||||
} finally {
|
||||
skillsLoaded = true;
|
||||
renderSkills();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 头部 ---------------- */
|
||||
|
||||
function refreshHead() {
|
||||
clear(headAvatar);
|
||||
headAvatar.appendChild(avatar(agent, 40));
|
||||
clear(headTitle);
|
||||
headTitle.appendChild(document.createTextNode(agent.name || '未命名'));
|
||||
if (agent.builtin) headTitle.appendChild(h('span.tag', '内置'));
|
||||
if (agent.id === settings().activeAgentId) headTitle.appendChild(h('span.tag.blue', '当前'));
|
||||
headSub.textContent = `${agent.tagline || '还没有一句话介绍'} · id ${agent.id}`;
|
||||
document.title = `${agent.name || '编辑智能体'} · 豆包`;
|
||||
}
|
||||
|
||||
/* ---------------- 保存 ---------------- */
|
||||
|
||||
function collect() {
|
||||
return {
|
||||
name: nameInput.value.trim(),
|
||||
tagline: tagInput.value.trim(),
|
||||
avatar: currentAvatar,
|
||||
systemPrompt: promptInput.value,
|
||||
modelId: modelRefSel.value,
|
||||
provider: providerSel.value,
|
||||
model: modelInput.value.trim(),
|
||||
baseUrl: baseUrlInput.value.trim(),
|
||||
worldviewId: worldSel.value,
|
||||
ttsVoice: voiceSel.value,
|
||||
tokenLimit: tokenInput.value.trim(),
|
||||
contextWindow: ctxInput.value.trim(),
|
||||
emotionEnabled: !!emotionInput.checked,
|
||||
};
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (saving) return;
|
||||
const now = collect();
|
||||
if (!now.name) {
|
||||
toast('名字不能为空', { type: 'error' });
|
||||
nameInput.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const patch = {};
|
||||
for (const key of TEXT_FIELDS) {
|
||||
if (String(now[key]) !== String(snapshot[key])) patch[key] = String(now[key]);
|
||||
}
|
||||
for (const key of NUM_FIELDS) {
|
||||
const raw = String(now[key]).trim();
|
||||
if (!raw) continue; // 留空 = 不修改(内核不接受空数字)
|
||||
const num = Number(raw);
|
||||
if (!Number.isFinite(num) || num < 0) {
|
||||
toast(`${key === 'tokenLimit' ? 'Token 限额' : '上下文窗口'}要填 0 或正整数`, { type: 'error' });
|
||||
return;
|
||||
}
|
||||
if (String(num) !== String(snapshot[key])) patch[key] = num;
|
||||
}
|
||||
if (now.emotionEnabled !== snapshot.emotionEnabled) patch.emotionEnabled = now.emotionEnabled;
|
||||
|
||||
const skillsChanged = JSON.stringify(skills) !== JSON.stringify(snapshotSkills);
|
||||
const clearedWindow = !String(now.contextWindow) && !!String(snapshot.contextWindow);
|
||||
if (!Object.keys(patch).length && !skillsChanged) {
|
||||
toast('没有改动');
|
||||
return;
|
||||
}
|
||||
|
||||
saving = true;
|
||||
saveBtn.disabled = true;
|
||||
saveBtn2.disabled = true;
|
||||
saveBtn.textContent = '保存中…';
|
||||
try {
|
||||
if (Object.keys(patch).length) {
|
||||
const res = await api.patch(`/api/agents/${encodeURIComponent(agent.id)}`, patch);
|
||||
if (res && res.ok === false) throw new Error(res.error || '保存失败');
|
||||
}
|
||||
if (skillsChanged) {
|
||||
const res = await api.put(`/api/agents/${encodeURIComponent(agent.id)}/skills`, { skillIds: skills });
|
||||
if (res && res.ok === false) throw new Error(res.error || '技能绑定保存失败');
|
||||
}
|
||||
// 静默重拉 state(portrait / worldview 反查 / emotions 都是派生字段)
|
||||
await loadState({ silent: true });
|
||||
agent = agents().find((a) => a.id === agent.id) || agent;
|
||||
snapshot = snapshotOf(agent);
|
||||
snapshotSkills = skills.slice();
|
||||
refreshHead();
|
||||
toast(skillsChanged ? `已保存${Object.keys(patch).length ? '(含技能绑定)' : ''}` : '已保存', { type: 'success' });
|
||||
if (clearedWindow) {
|
||||
toast('上下文窗口留空不会清空已有值(内核只接受数字),要改请填个数字', { duration: 3600 });
|
||||
}
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
saving = false;
|
||||
saveBtn.disabled = false;
|
||||
saveBtn2.disabled = false;
|
||||
saveBtn.textContent = '保存';
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 删除 ---------------- */
|
||||
|
||||
async function doExport() {
|
||||
if (saving) return;
|
||||
try {
|
||||
const res = await api.get(`/api/agents/${encodeURIComponent(agent.id)}/package`);
|
||||
if (!res || res.ok === false || !res.data) throw new Error((res && res.error) || '内核没有返回包内容');
|
||||
const fileName = res.fileName || `${agent.name || 'agent'}.zip`;
|
||||
downloadBase64(fileName, res.data);
|
||||
toast(`已导出「${fileName}」`, { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(`导出失败:${err.message}`, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function doDelete() {
|
||||
if (saving) return;
|
||||
const ok = await confirmBox({
|
||||
title: `删除「${agent.name}」?`,
|
||||
message: '记忆、用量账单和磁盘上的立绘都会被保留(内核不清理),之后新建一个同名智能体也接不上这些记忆。',
|
||||
okText: '删除',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await api.del(`/api/agents/${encodeURIComponent(agent.id)}`);
|
||||
if (res && res.ok === false) throw new Error(res.error || '删除失败');
|
||||
if (res && res.deleted === false) throw new Error('这个智能体已经不在了');
|
||||
await loadState({ silent: true });
|
||||
toast(`已删除「${agent.name}」`, { type: 'success' });
|
||||
ctx.navigate('agents');
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 组装 ---------------- */
|
||||
|
||||
function section(title, desc, rows) {
|
||||
return h('div.card.ae-sec', {},
|
||||
h('div.ae-sec-head', {},
|
||||
h('div.card-title', title),
|
||||
desc ? h('div.card-desc', desc) : null),
|
||||
h('div.form-grid', {}, rows));
|
||||
}
|
||||
|
||||
clear(root);
|
||||
refreshHead();
|
||||
|
||||
root.appendChild(h('div.page-head', {},
|
||||
h('div.page-head-left.ae-head', {},
|
||||
h('button.icon-btn', {
|
||||
title: '返回智能体列表',
|
||||
onclick: () => ctx.navigate('agents'),
|
||||
}, icon('arrow-left', 18)),
|
||||
headAvatar,
|
||||
h('div.ae-head-main', {}, headTitle, headSub)),
|
||||
h('div.page-actions', {},
|
||||
h('button.btn', {
|
||||
title: '看这个智能体的记忆',
|
||||
onclick: () => ctx.navigate(`agents/${encodeURIComponent(agent.id)}/memories`),
|
||||
}, icon('brain', 16), '记忆'),
|
||||
h('button.btn', {
|
||||
title: '看这个智能体的 Token 用量',
|
||||
onclick: () => ctx.navigate(`agents/${encodeURIComponent(agent.id)}/usage`),
|
||||
}, icon('cpu', 16), '用量'),
|
||||
h('button.icon-btn', { title: '导出智能体包(.zip)', onclick: () => doExport() }, icon('download', 18)),
|
||||
agent.builtin ? null : h('button.icon-btn', { title: '删除智能体', onclick: () => doDelete() }, icon('trash', 18)),
|
||||
saveBtn)));
|
||||
|
||||
root.appendChild(section('基本信息', '名字和一句话介绍会出现在智能体列表、切换菜单和群聊成员里。', [
|
||||
fieldRow('名字', nameInput, '最多 24 个字;可以重名,重名不会共享记忆'),
|
||||
fieldRow('一句话介绍', tagInput, '最多 40 个字,列表里的摘要'),
|
||||
fieldRow('头像', h('div', {}, avatarPick, h('div', { style: 'margin-top:10px' }, avatarPreview)),
|
||||
'内核内置 9 个头像 key,存的就是选中的那个 key'),
|
||||
]));
|
||||
|
||||
root.appendChild(section('人设', '这段文字作为系统提示词的开头注入。留空 = 用全局系统提示词。', [
|
||||
fieldRow('系统提示词', promptInput, '越具体越稳:先说身份,再说输出要求,最后说禁忌'),
|
||||
]));
|
||||
|
||||
root.appendChild(section('模型', '优先级:引用的全局模型 → 智能体自己的配置 → 全局设置 → 提供商预设。', [
|
||||
fieldRow('引用全局模型', modelRefSel,
|
||||
'引用后地址 / Key / 模型标识整组都从那一项来(改 Key 只改一处)。要单独配就选「不引用」。'),
|
||||
fieldRow('提供商', providerSel, '留空跟随全局'),
|
||||
fieldRow('模型标识', modelInput, '留空跟随全局'),
|
||||
fieldRow('接口地址', baseUrlInput, '留空跟随全局;OpenAI 兼容协议,一般以 /v1 或 /api/v3 结尾'),
|
||||
]));
|
||||
|
||||
root.appendChild(section('世界观与技能', '绑定世界观后,这个智能体的记忆会变成同世界观共享的。', [
|
||||
fieldRow('世界观', worldSel, '不同世界观的智能体拉不进同一个群聊(没绑的可以)'),
|
||||
fieldRow('技能 Skill', skillsBox, '勾选顺序就是注入顺序(先注入的在前面);保存时单独 PUT /api/agents/<id>/skills 落库'),
|
||||
]));
|
||||
|
||||
root.appendChild(section('行为', '这些开关只影响这一个智能体。', [
|
||||
fieldRow('情绪感知', emotionSwitch, '打开后能看到同世界观其他人的情绪状态'),
|
||||
fieldRow('Token 限额', tokenInput, '0 = 不限制(不是"限额为 0")'),
|
||||
fieldRow('上下文窗口', ctxInput, '对话轮数,不是记忆条数(记忆条数在记忆页调)'),
|
||||
fieldRow('朗读音色', voiceSel, '留空跟随全局;多人会议靠音色区分谁在说话'),
|
||||
]));
|
||||
|
||||
if (agent.builtin) {
|
||||
root.appendChild(h('div.ae-hint-box', { style: 'margin-top:12px' },
|
||||
'这是内置智能体:可以改人设、头像和模型,但不能删除(内核删了也会自动重建)。'));
|
||||
}
|
||||
|
||||
root.appendChild(h('div.ae-foot', {},
|
||||
saveBtn2,
|
||||
h('button.btn', { onclick: () => ctx.navigate('agents') }, '返回列表'),
|
||||
h('span.spacer'),
|
||||
h('span.ae-model-hint', '只发改动过的字段(PATCH),技能单独落库')));
|
||||
|
||||
renderSkills();
|
||||
loadSkills();
|
||||
return undefined;
|
||||
}
|
||||
411
web/js/pages/agents.js
Normal file
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* 智能体列表页(#/agents)
|
||||
*
|
||||
* 数据全部来自 `/api/state`(`agents` / `worldviews` / `modelEntries`)——
|
||||
* 内核**没有** `GET /api/agents/<id>`,所以这里一次都不单独拉智能体。
|
||||
*
|
||||
* 写操作:
|
||||
* POST /api/agents 新建(然后跳到 #/agents/<id> 继续配)
|
||||
* POST /api/agents/import {data:<zip base64>} 导入
|
||||
* GET /api/agents/<id>/package 导出({fileName, data:<zip base64>})
|
||||
* DELETE /api/agents/<id> 删除(内置 4 个会被内核 400 拒绝,所以入口直接隐藏)
|
||||
* PUT /api/settings {activeAgentId} 设为当前
|
||||
*
|
||||
* 契约要点(docs/kernel-api-agents.md §2.2 / §13 / §14):
|
||||
* - 删除**不会**删掉记忆、Token 账本,也不清磁盘上的立绘 —— 界面不要承诺"删干净";
|
||||
* - 内置智能体删不掉,删了下次也会被 DEFAULT_AGENTS 重建;
|
||||
* - 导出包里没有 id / modelId / worldviewId / tokenLimit / 记忆 / 技能 / API Key。
|
||||
*/
|
||||
import {
|
||||
api, loadState, saveSettings, settings, agents, readAsDataUrl, S,
|
||||
} from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, openModal, confirmBox,
|
||||
emptyState, spinner, injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
/** 内核白名单里的 9 个头像 key(defaults.AVATAR_KEYS) */
|
||||
const AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'cloud', 'robot', 'star', 'custom'];
|
||||
const AVATAR_LABELS = {
|
||||
doubao: '豆包', coder: '代码', writer: '文案', analyst: '数据',
|
||||
cat: '猫', cloud: '云', robot: '机器人', star: '星星', custom: '自定义',
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.ag-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
|
||||
.ag-card {
|
||||
display: flex; flex-direction: column; gap: 0;
|
||||
padding: 16px; border: 1px solid var(--line-1); border-radius: var(--r-lg);
|
||||
background: var(--bg-body); cursor: pointer;
|
||||
transition: border-color .15s var(--ease), box-shadow .15s var(--ease);
|
||||
}
|
||||
.ag-card:hover { border-color: var(--line-2); box-shadow: var(--shadow-sm); }
|
||||
.ag-card.active { border-color: var(--brand); box-shadow: 0 0 0 3px var(--brand-weak-2); }
|
||||
.ag-top { display: flex; align-items: flex-start; gap: 12px; min-height: 44px; }
|
||||
.ag-top .avatar { flex: none; box-shadow: var(--shadow-xs); }
|
||||
.ag-head-main { flex: 1; min-width: 0; }
|
||||
.ag-name-row { display: flex; align-items: center; gap: 8px; }
|
||||
.ag-name { font-size: 16px; line-height: 24px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ag-tagline {
|
||||
margin-top: 4px; font-size: 13px; line-height: 20px; color: var(--text-secondary);
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
|
||||
min-height: 40px;
|
||||
}
|
||||
.ag-meta { margin-top: 12px; display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.ag-foot {
|
||||
margin-top: 14px; padding-top: 10px; border-top: 1px solid var(--line-1);
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 6px;
|
||||
}
|
||||
.ag-cur { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 9px;
|
||||
border-radius: var(--r-full); background: var(--brand-weak); color: var(--brand);
|
||||
font-size: 12px; font-weight: 500; white-space: nowrap; }
|
||||
.ag-acts { display: flex; align-items: center; gap: 2px; flex: none; }
|
||||
.ag-acts .icon-btn { width: 26px; height: 26px; }
|
||||
.ag-acts .icon-btn.danger:hover { background: var(--danger-weak); color: var(--danger); }
|
||||
.ag-empty-tip { padding: 4px 0 0; }
|
||||
.ag-pick { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.ag-pick button {
|
||||
width: 44px; height: 44px; padding: 2px; border: 2px solid transparent; border-radius: var(--r-md);
|
||||
background: var(--bg-base-2); cursor: pointer; line-height: 0;
|
||||
transition: border-color .12s var(--ease), background .12s var(--ease);
|
||||
}
|
||||
.ag-pick button:hover { background: var(--fill-3); }
|
||||
.ag-pick button.on { border-color: var(--brand); background: var(--brand-weak); }
|
||||
.ag-pick img { width: 100%; height: 100%; border-radius: 10px; object-fit: cover; display: block; }
|
||||
.ag-form { display: flex; flex-direction: column; gap: 14px; padding: 6px 0 4px; }
|
||||
.ag-form-label { font-size: 13px; font-weight: 500; margin-bottom: 6px; }
|
||||
.ag-form-hint { margin-top: 4px; font-size: 12px; color: var(--text-tertiary); line-height: 18px; }
|
||||
.ag-form-error { font-size: 12px; color: var(--danger); min-height: 18px; line-height: 18px; }
|
||||
`;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 小工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const listOf = (key) => ((S.state && Array.isArray(S.state[key])) ? S.state[key] : []);
|
||||
|
||||
function avatarImg(key, size = 40) {
|
||||
return h('img', {
|
||||
src: `/assets/avatars/${AVATAR_KEYS.includes(key) ? key : 'custom'}.png`,
|
||||
alt: '',
|
||||
width: size,
|
||||
height: size,
|
||||
style: `width:${size}px;height:${size}px;border-radius:12px;object-fit:cover;display:block`,
|
||||
onerror: (e) => { e.target.src = '/assets/avatars/custom.png'; },
|
||||
});
|
||||
}
|
||||
|
||||
/** 一条模型来源的说明文字(智能体自己的 model → 引用全局模型 → 跟随全局) */
|
||||
function modelLabel(agent) {
|
||||
const modelId = String(agent.modelId || '').trim();
|
||||
if (modelId) {
|
||||
const entry = listOf('modelEntries').find((m) => m.id === modelId);
|
||||
return `引用模型 · ${entry ? (entry.name || entry.model) : '已删除'}`;
|
||||
}
|
||||
const model = String(agent.model || '').trim();
|
||||
if (model) return `模型 · ${model}`;
|
||||
return '跟随全局模型';
|
||||
}
|
||||
|
||||
function worldviewLabel(agent) {
|
||||
const id = String(agent.worldviewId || '').trim();
|
||||
if (!id) return '未绑世界观';
|
||||
const world = listOf('worldviews').find((w) => w.id === id);
|
||||
return `世界观 · ${world ? world.name : '已删除'}`;
|
||||
}
|
||||
|
||||
function downloadBase64(name, base64, mime = 'application/zip') {
|
||||
const bin = atob(String(base64 || ''));
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: mime }));
|
||||
const a = h('a', { href: url, download: name });
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 5000);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 页面 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export default function renderAgents(container, ctx) {
|
||||
injectStyles('page-agents', CSS);
|
||||
|
||||
const root = h('div.page-inner');
|
||||
mount(container, root);
|
||||
ctx.setTitle('智能体');
|
||||
|
||||
let busy = false;
|
||||
const setBusy = (v) => { busy = v; };
|
||||
|
||||
/* ---------------- 写操作 ---------------- */
|
||||
|
||||
async function setActive(agent) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await saveSettings({ activeAgentId: agent.id });
|
||||
toast(`已切换到「${agent.name}」`, { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function exportAgent(agent) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.get(`/api/agents/${encodeURIComponent(agent.id)}/package`);
|
||||
if (!res || res.ok === false || !res.data) {
|
||||
throw new Error((res && res.error) || '内核没有返回包内容');
|
||||
}
|
||||
const name = res.fileName || `${agent.name || 'agent'}.zip`;
|
||||
downloadBase64(name, res.data);
|
||||
toast(`已导出「${name}」`, { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(`导出失败:${err.message}`, { type: 'error' });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeAgent(agent) {
|
||||
if (busy) return;
|
||||
const ok = await confirmBox({
|
||||
title: `删除「${agent.name}」?`,
|
||||
message: '这个智能体会从列表里消失,记忆、用量账单和磁盘上的立绘都会被保留(内核不清理),'
|
||||
+ '之后新建一个同名智能体也接不上这些记忆。',
|
||||
okText: '删除',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.del(`/api/agents/${encodeURIComponent(agent.id)}`);
|
||||
if (res && res.ok === false) throw new Error(res.error || '删除失败');
|
||||
if (res && res.deleted === false) throw new Error('这个智能体已经不在了');
|
||||
await loadState({ silent: true });
|
||||
toast(`已删除「${agent.name}」`, { type: 'success' });
|
||||
} catch (err) {
|
||||
// 内置智能体:内核 400「内置智能体不能删除(删了会被自动重建)」
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 新建 ---------------- */
|
||||
|
||||
function openCreate() {
|
||||
const nameInput = h('input.input', { placeholder: '例如:产品搭档', maxlength: 24 });
|
||||
const tagInput = h('input.input', { placeholder: '一句话介绍,例如:把需求写成评审稿', maxlength: 40 });
|
||||
const errLine = h('div.ag-form-error');
|
||||
let avatarKey = 'custom';
|
||||
|
||||
const pick = h('div.ag-pick');
|
||||
const refreshPick = () => {
|
||||
for (const btn of pick.children) btn.classList.toggle('on', btn.dataset.key === avatarKey);
|
||||
};
|
||||
for (const key of AVATAR_KEYS) {
|
||||
pick.appendChild(h('button', {
|
||||
type: 'button',
|
||||
title: AVATAR_LABELS[key] || key,
|
||||
dataset: { key },
|
||||
onclick: () => { avatarKey = key; refreshPick(); },
|
||||
}, avatarImg(key, 36)));
|
||||
}
|
||||
refreshPick();
|
||||
|
||||
const okBtn = h('button.btn.primary', { onclick: () => submit() }, '创建并编辑');
|
||||
const modal = openModal({
|
||||
title: '新建智能体',
|
||||
width: 520,
|
||||
body: h('div.ag-form', {},
|
||||
h('div', {},
|
||||
h('div.ag-form-label', '名字'),
|
||||
nameInput,
|
||||
h('div.ag-form-hint', '最多 24 个字,可以重名(重名不会共享记忆)。')),
|
||||
h('div', {},
|
||||
h('div.ag-form-label', '一句话介绍'),
|
||||
tagInput,
|
||||
h('div.ag-form-hint', '列表里显示的摘要,最多 40 个字。')),
|
||||
h('div', {},
|
||||
h('div.ag-form-label', '头像'),
|
||||
pick),
|
||||
errLine),
|
||||
footer: h('div.modal-actions', {},
|
||||
h('button.btn', { onclick: () => modal.close() }, '取消'),
|
||||
okBtn),
|
||||
});
|
||||
setTimeout(() => nameInput.focus(), 40);
|
||||
|
||||
async function submit() {
|
||||
const name = nameInput.value.trim();
|
||||
if (!name) { errLine.textContent = '名字不能为空'; nameInput.focus(); return; }
|
||||
okBtn.disabled = true;
|
||||
okBtn.textContent = '创建中…';
|
||||
errLine.textContent = '';
|
||||
try {
|
||||
const res = await api.post('/api/agents', {
|
||||
name,
|
||||
tagline: tagInput.value.trim(),
|
||||
avatar: avatarKey,
|
||||
});
|
||||
if (!res || res.ok === false || !res.agent) throw new Error((res && res.error) || '内核没有返回新智能体');
|
||||
await loadState({ silent: true });
|
||||
modal.close();
|
||||
toast(`已创建「${res.agent.name || name}」`, { type: 'success' });
|
||||
ctx.navigate(`agents/${encodeURIComponent(res.agent.id)}`);
|
||||
} catch (err) {
|
||||
errLine.textContent = err.message;
|
||||
toast(err.message, { type: 'error' });
|
||||
okBtn.disabled = false;
|
||||
okBtn.textContent = '创建并编辑';
|
||||
}
|
||||
}
|
||||
|
||||
nameInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') submit(); });
|
||||
}
|
||||
|
||||
/* ---------------- 导入 ---------------- */
|
||||
|
||||
const fileInput = h('input', {
|
||||
type: 'file',
|
||||
accept: '.zip,application/zip,application/x-zip-compressed',
|
||||
style: 'display:none',
|
||||
});
|
||||
|
||||
fileInput.addEventListener('change', async () => {
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
fileInput.value = '';
|
||||
if (!file) return;
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
toast(`正在导入「${file.name}」…`, { duration: 1600 });
|
||||
try {
|
||||
const dataUrl = await readAsDataUrl(file);
|
||||
const base64 = String(dataUrl || '').split(',')[1] || '';
|
||||
if (!base64) throw new Error('这个文件读不出来');
|
||||
const res = await api.post('/api/agents/import', { data: base64 });
|
||||
if (!res || res.ok === false || !res.agent) throw new Error((res && res.error) || '导入失败');
|
||||
await loadState({ silent: true });
|
||||
const assets = Number(res.assets) || 0;
|
||||
toast(`已导入「${res.agent.name || file.name}」${assets ? `(含 ${assets} 张图)` : ''}`, { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(`导入失败:${err.message}`, { type: 'error' });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
/* ---------------- 卡片 ---------------- */
|
||||
|
||||
function agentCard(agent, isActive) {
|
||||
const edit = () => ctx.navigate(`agents/${encodeURIComponent(agent.id)}`);
|
||||
const act = (iconName, title, onClick, danger) => h(`button.icon-btn${danger ? '.danger' : ''}`, {
|
||||
title,
|
||||
'aria-label': title,
|
||||
onclick: (e) => { e.stopPropagation(); onClick(); },
|
||||
}, icon(iconName, 15));
|
||||
|
||||
const skillCount = Array.isArray(agent.skillIds) ? agent.skillIds.length : 0;
|
||||
|
||||
return h(`div.ag-card${isActive ? '.active' : ''}`, {
|
||||
title: `编辑「${agent.name}」`,
|
||||
onclick: edit,
|
||||
},
|
||||
h('div.ag-top', {},
|
||||
avatar(agent, 44),
|
||||
h('div.ag-head-main', {},
|
||||
h('div.ag-name-row', {},
|
||||
h('div.ag-name', agent.name || '未命名'),
|
||||
agent.builtin ? h('span.tag', '内置') : null,
|
||||
isActive ? h('span.tag.blue', '当前') : null),
|
||||
h('div.ag-tagline', agent.tagline || (agent.builtin ? '(还没有一句话介绍)' : '点卡片进去补一句话介绍'))),
|
||||
h('div.ag-meta', {},
|
||||
h('span.tag', modelLabel(agent)),
|
||||
h('span.tag', worldviewLabel(agent)),
|
||||
h('span.tag', skillCount ? `技能 ${skillCount} 个` : '无技能'),
|
||||
agent.emotionEnabled ? h('span.tag.orange', '情绪开') : null),
|
||||
h('div.ag-foot', {},
|
||||
isActive
|
||||
? h('span.ag-cur', {}, icon('check', 13), '当前使用中')
|
||||
: h('button.btn.sm.primary', {
|
||||
onclick: (e) => { e.stopPropagation(); setActive(agent); },
|
||||
}, '设为当前'),
|
||||
h('div.ag-acts', {},
|
||||
act('pencil', '编辑', edit),
|
||||
act('brain', '记忆', () => ctx.navigate(`agents/${encodeURIComponent(agent.id)}/memories`)),
|
||||
act('cpu', '用量', () => ctx.navigate(`agents/${encodeURIComponent(agent.id)}/usage`)),
|
||||
act('download', '导出智能体包(.zip)', () => exportAgent(agent)),
|
||||
agent.builtin ? null : act('trash', '删除', () => removeAgent(agent), true)))));
|
||||
}
|
||||
|
||||
/* ---------------- 渲染 ---------------- */
|
||||
|
||||
function renderHead() {
|
||||
const total = agents().length;
|
||||
return h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', '智能体'),
|
||||
h('div.page-sub', total
|
||||
? `共 ${total} 个。每个智能体有自己的头像、人设、模型、世界观、记忆和技能;设为当前后,新对话由它回答。`
|
||||
: '每个智能体有自己的头像、人设、模型、世界观、记忆和技能。')),
|
||||
h('div.page-actions', {},
|
||||
h('button.btn', {
|
||||
title: '导入一个 .zip 智能体包',
|
||||
onclick: () => fileInput.click(),
|
||||
}, icon('file-text', 16), '导入'),
|
||||
h('button.btn.primary', { onclick: openCreate }, icon('plus', 16), '新建')));
|
||||
}
|
||||
|
||||
function render() {
|
||||
clear(root);
|
||||
root.appendChild(renderHead());
|
||||
root.appendChild(fileInput);
|
||||
|
||||
if (!S.state) {
|
||||
root.appendChild(h('div', { style: 'display:flex;justify-content:center;padding:80px 0' }, spinner(22)));
|
||||
return;
|
||||
}
|
||||
if (S.error) {
|
||||
root.appendChild(emptyState('alert-triangle', '没读到智能体列表',
|
||||
String(S.error.message || S.error),
|
||||
h('div', { style: 'margin-top:16px' },
|
||||
h('button.btn.primary', {
|
||||
onclick: async () => {
|
||||
try { await loadState(); } catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
}, '重试'))));
|
||||
return;
|
||||
}
|
||||
|
||||
const list = agents();
|
||||
if (!list.length) {
|
||||
root.appendChild(emptyState('bot', '还没有智能体',
|
||||
'新建一个,给它一个头像、一段人设,就能拉进对话里了。',
|
||||
h('div', { style: 'margin-top:16px;display:flex;gap:8px' },
|
||||
h('button.btn.primary', { onclick: openCreate }, icon('plus', 16), '新建智能体'),
|
||||
h('button.btn', { onclick: () => fileInput.click() }, '导入 zip 包'))));
|
||||
return;
|
||||
}
|
||||
|
||||
const activeId = settings().activeAgentId;
|
||||
const grid = h('div.ag-grid');
|
||||
for (const agent of list) grid.appendChild(agentCard(agent, agent.id === activeId));
|
||||
root.appendChild(grid);
|
||||
|
||||
root.appendChild(h('div.ag-empty-tip.page-sub', {
|
||||
style: 'margin-top:16px',
|
||||
}, '提示:内置的 4 个智能体不能删除(删了内核也会自动重建),可以改人设和模型。'));
|
||||
}
|
||||
|
||||
render();
|
||||
// 任何写操作之后内核状态都会变(activeAgentId、新导入的智能体…),跟着重画
|
||||
const off = ctx.onState(() => render());
|
||||
return () => off();
|
||||
}
|
||||
1286
web/js/pages/chat.js
Normal file
487
web/js/pages/groups.js
Normal file
@@ -0,0 +1,487 @@
|
||||
/**
|
||||
* 群聊管理页(#/groups)
|
||||
*
|
||||
* 数据:`state.conversations` 里 `type === 'group'` 的那些会话。
|
||||
* 成员列表**没有** `GET /api/conversations/<id>/members`(405),只能读会话对象的
|
||||
* `participants`(数组顺序有意义:`[0]` 是主智能体 / 无人被 @ 时的兜底发言人)。
|
||||
*
|
||||
* 接口(docs/kernel-api-agents.md §11.2):
|
||||
* POST /api/conversations {type:'group', title, participants, agentId}
|
||||
* PATCH /api/conversations/<id> {title}
|
||||
* DELETE /api/conversations/<id>
|
||||
* POST /api/conversations/<id>/members {agentId}
|
||||
* DELETE /api/conversations/<id>/members/<agentId>
|
||||
*
|
||||
* 内核的两条硬规则(错误信息要如实照转,不要自己编原因):
|
||||
* - 加人:不同世界观的智能体进不来(未绑世界观的放行);
|
||||
* - 移人:谁都能移,但**不能移到一个人都不剩**;剩 1 个时会话自动退回单聊。
|
||||
*/
|
||||
import {
|
||||
S, api, loadState, conversations, agents, refreshConversations,
|
||||
} from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, openModal, openMenu, confirmBox,
|
||||
promptBox, emptyState, spinner, fmtRelative, injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
const CSS = `
|
||||
.gp-how { border: 1px solid var(--line-1); background: var(--bg-sidebar); border-radius: var(--r-md);
|
||||
padding: 12px 14px; font-size: 13px; line-height: 20px; color: var(--text-secondary); margin-bottom: 14px; }
|
||||
.gp-how b { color: var(--text-primary); font-weight: 500; }
|
||||
.gp-list { display: flex; flex-direction: column; gap: 10px; }
|
||||
.gp-card { border: 1px solid var(--line-1); border-radius: var(--r-lg); background: var(--bg-body);
|
||||
transition: border-color .15s var(--ease), box-shadow .15s var(--ease); }
|
||||
.gp-card:hover { border-color: var(--line-2); }
|
||||
.gp-card.open { border-color: var(--line-2); box-shadow: var(--shadow-sm); }
|
||||
.gp-main { display: flex; align-items: center; gap: 14px; padding: 14px 16px; }
|
||||
.gp-stack { display: flex; align-items: center; flex: none; padding-left: 4px; }
|
||||
.gp-stack .avatar, .gp-stack-more { border: 2px solid var(--bg-body); }
|
||||
.gp-stack .avatar + .avatar, .gp-stack-more { margin-left: -10px; }
|
||||
.gp-stack-more { display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: 50%; background: var(--bg-base-2);
|
||||
font-size: 11px; font-weight: 500; color: var(--text-secondary); flex: none; }
|
||||
.gp-info { flex: 1; min-width: 0; }
|
||||
.gp-title { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 600; line-height: 24px; }
|
||||
.gp-title .gp-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.gp-meta { margin-top: 2px; font-size: 12px; line-height: 18px; color: var(--text-tertiary);
|
||||
display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.gp-meta .dot { width: 2px; height: 2px; border-radius: 50%; background: currentColor; display: inline-block; }
|
||||
.gp-acts { flex: none; display: flex; align-items: center; gap: 6px; }
|
||||
.gp-members { border-top: 1px solid var(--line-1); padding: 6px 16px 12px; }
|
||||
.gp-member { display: flex; align-items: center; gap: 10px; padding: 9px 0; border-bottom: 1px solid var(--line-1); }
|
||||
.gp-member:last-of-type { border-bottom: 0; }
|
||||
.gp-member-main { flex: 1; min-width: 0; }
|
||||
.gp-member-name { display: flex; align-items: center; gap: 8px; font-size: 14px; line-height: 22px; font-weight: 500; }
|
||||
.gp-member-desc { margin-top: 1px; font-size: 12px; line-height: 18px; color: var(--text-secondary);
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.gp-member-side { flex: none; display: flex; align-items: center; gap: 6px; }
|
||||
.gp-members-foot { display: flex; align-items: center; gap: 8px; padding-top: 10px; }
|
||||
.gp-members-foot .gp-hint { font-size: 12px; line-height: 18px; color: var(--text-tertiary); }
|
||||
.gp-form { display: flex; flex-direction: column; gap: 14px; padding: 4px 0; }
|
||||
.gp-form-label { font-size: 13px; font-weight: 500; margin-bottom: 6px; display: flex; align-items: center; gap: 8px; }
|
||||
.gp-form-hint { margin-top: 4px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); }
|
||||
.gp-form-error { font-size: 12px; line-height: 18px; color: var(--danger); min-height: 18px; }
|
||||
.gp-pick { display: flex; flex-direction: column; max-height: 240px; overflow-y: auto;
|
||||
border: 1px solid var(--line-1); border-radius: var(--r-md); padding: 4px; }
|
||||
.gp-pick-row { display: flex; align-items: center; gap: 10px; padding: 7px 8px; border-radius: var(--r-sm); cursor: pointer; }
|
||||
.gp-pick-row:hover { background: var(--bg-hover); }
|
||||
.gp-pick-row .gp-pick-main { flex: 1; min-width: 0; }
|
||||
.gp-pick-name { font-size: 14px; line-height: 22px; }
|
||||
.gp-pick-desc { font-size: 12px; line-height: 18px; color: var(--text-tertiary);
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.gp-order { border: 1px solid var(--line-1); border-radius: var(--r-md); padding: 4px 12px; }
|
||||
.gp-order-row { display: flex; align-items: center; gap: 10px; padding: 7px 0; border-top: 1px solid var(--line-1); }
|
||||
.gp-order-row:first-child { border-top: 0; }
|
||||
.gp-order-ord { width: 18px; flex: none; text-align: right; font-size: 12px; color: var(--text-tertiary); }
|
||||
.gp-order-name { flex: 1; min-width: 0; font-size: 14px; line-height: 22px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.gp-empty-tip { margin-top: 14px; }
|
||||
`;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const groupConvs = () => conversations().filter((c) => c.type === 'group');
|
||||
const agentById = (id) => agents().find((a) => a.id === id) || null;
|
||||
|
||||
function memberIds(conv) {
|
||||
return Array.isArray(conv && conv.participants) ? conv.participants : [];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 页面 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export default function renderGroups(container, ctx) {
|
||||
injectStyles('page-groups', CSS);
|
||||
|
||||
const root = h('div.page-inner');
|
||||
mount(container, root);
|
||||
ctx.setTitle('群聊');
|
||||
|
||||
const expanded = new Set(); // 展开成员列表的会话 id
|
||||
let busy = false;
|
||||
|
||||
/* ---------------- 写操作 ---------------- */
|
||||
|
||||
/** 群成员增删后必须重拉 state(会话对象、type 都可能被内核改掉) */
|
||||
async function afterConvChange(message) {
|
||||
await loadState({ silent: true });
|
||||
if (message) toast(message, { type: 'success' });
|
||||
}
|
||||
|
||||
async function addMember(conv, agent) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const res = await api.post(`/api/conversations/${encodeURIComponent(conv.id)}/members`, { agentId: agent.id });
|
||||
if (res && res.ok === false) throw new Error(res.error || '加不进去');
|
||||
await afterConvChange(`已把「${agent.name}」拉进群`);
|
||||
} catch (err) {
|
||||
// 内核原话:「加不进去(人不存在或已经在里面了)」
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMember(conv, agent) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
const res = await api.del(`/api/conversations/${encodeURIComponent(conv.id)}/members/${encodeURIComponent(agent.id)}`);
|
||||
if (res && res.ok === false) throw new Error(res.error || '移不出去');
|
||||
await loadState({ silent: true });
|
||||
const fresh = conversations().find((c) => c.id === conv.id);
|
||||
if (fresh && fresh.type !== 'group') {
|
||||
expanded.delete(conv.id);
|
||||
toast(`已移出「${agent.name}」,只剩 1 个成员,会话退回单聊`, { type: 'success', duration: 3600 });
|
||||
} else {
|
||||
toast(`已移出「${agent.name}」`, { type: 'success' });
|
||||
}
|
||||
} catch (err) {
|
||||
// 内核原话:「移不出去(群里没这个人,或者就剩他一个了)」
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function rename(conv) {
|
||||
const title = await promptBox({
|
||||
title: '重命名群聊',
|
||||
value: conv.title || '',
|
||||
placeholder: '群聊标题',
|
||||
okText: '保存',
|
||||
});
|
||||
if (title == null) return;
|
||||
const next = String(title).trim();
|
||||
if (!next) { toast('标题不能为空', { type: 'error' }); return; }
|
||||
if (next === conv.title) return;
|
||||
busy = true;
|
||||
try {
|
||||
const res = await api.patch(`/api/conversations/${encodeURIComponent(conv.id)}`, { title: next });
|
||||
if (res && res.ok === false) throw new Error(res.error || '重命名失败');
|
||||
await afterConvChange('已重命名');
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeConv(conv) {
|
||||
const ok = await confirmBox({
|
||||
title: `删除群聊「${conv.title || '未命名'}」?`,
|
||||
message: `会话和里面 ${conv.messageCount || 0} 条消息会被删掉,不能恢复。智能体本身不受影响。`,
|
||||
okText: '删除',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
busy = true;
|
||||
try {
|
||||
const res = await api.del(`/api/conversations/${encodeURIComponent(conv.id)}`);
|
||||
if (res && res.ok === false) throw new Error(res.error || '删除失败');
|
||||
if (S.conversationId === conv.id) S.conversationId = null;
|
||||
expanded.delete(conv.id);
|
||||
await afterConvChange('已删除群聊');
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openConversation(conv) {
|
||||
S.conversationId = conv.id;
|
||||
ctx.navigate('chat');
|
||||
}
|
||||
|
||||
/* ---------------- 新建群聊 ---------------- */
|
||||
|
||||
function openCreate() {
|
||||
const list = agents();
|
||||
if (list.length < 2) {
|
||||
toast('至少要有 2 个智能体才能建群(去「智能体」页新建一个)', { type: 'error', duration: 3600 });
|
||||
return;
|
||||
}
|
||||
const titleInput = h('input.input', { placeholder: '例如:周报小组(留空就叫「新群聊」)', maxlength: 40 });
|
||||
const picked = []; // 顺序 = 发言人顺序,第一个是主智能体(兜底)
|
||||
const errLine = h('div.gp-form-error');
|
||||
const pickBox = h('div.gp-pick');
|
||||
const orderBox = h('div.gp-order');
|
||||
|
||||
function renderPick() {
|
||||
clear(pickBox);
|
||||
for (const agent of list) {
|
||||
const on = picked.includes(agent.id);
|
||||
pickBox.appendChild(h('div.gp-pick-row', {
|
||||
onclick: () => {
|
||||
const i = picked.indexOf(agent.id);
|
||||
if (i >= 0) picked.splice(i, 1);
|
||||
else picked.push(agent.id);
|
||||
errLine.textContent = '';
|
||||
renderPick();
|
||||
renderOrder();
|
||||
},
|
||||
},
|
||||
h('input', {
|
||||
type: 'checkbox',
|
||||
checked: on ? 'checked' : null,
|
||||
style: 'width:16px;height:16px;accent-color:var(--brand);flex:none',
|
||||
onclick: (e) => { e.preventDefault(); e.currentTarget.blur(); },
|
||||
}),
|
||||
avatar(agent, 28),
|
||||
h('div.gp-pick-main', {},
|
||||
h('div.gp-pick-name', agent.name || '未命名'),
|
||||
h('div.gp-pick-desc', agent.tagline || '(没有一句话介绍)'))));
|
||||
}
|
||||
}
|
||||
|
||||
function renderOrder() {
|
||||
clear(orderBox);
|
||||
if (!picked.length) {
|
||||
orderBox.appendChild(h('div.gp-form-hint', { style: 'padding:8px 0' }, '还没有选成员。勾 2 个以上。'));
|
||||
return;
|
||||
}
|
||||
picked.forEach((id, i) => {
|
||||
const agent = agentById(id);
|
||||
orderBox.appendChild(h('div.gp-order-row', {},
|
||||
h('div.gp-order-ord', String(i + 1)),
|
||||
h('div.gp-order-name', agent ? agent.name : id),
|
||||
i === 0 ? h('span.tag.blue', '主 · 兜底发言人') : null,
|
||||
i === 0 ? null : h('button.btn.sm.ghost', {
|
||||
title: '把ta换到第一位(没人被 @ 时由第一位兜底)',
|
||||
onclick: () => {
|
||||
picked.splice(i, 1);
|
||||
picked.unshift(id);
|
||||
renderPick();
|
||||
renderOrder();
|
||||
},
|
||||
}, '设为主'),
|
||||
h('button.icon-btn.sm', {
|
||||
title: '移除',
|
||||
onclick: () => {
|
||||
picked.splice(picked.indexOf(id), 1);
|
||||
renderPick();
|
||||
renderOrder();
|
||||
},
|
||||
}, icon('x', 14))));
|
||||
});
|
||||
}
|
||||
|
||||
renderPick();
|
||||
renderOrder();
|
||||
|
||||
const okBtn = h('button.btn.primary', { onclick: () => submit() }, '创建并打开');
|
||||
const modal = openModal({
|
||||
title: '新建群聊',
|
||||
width: 560,
|
||||
body: h('div.gp-form', {},
|
||||
h('div', {},
|
||||
h('div.gp-form-label', '群聊标题'),
|
||||
titleInput),
|
||||
h('div', {},
|
||||
h('div.gp-form-label', '成员', h('span.tag', '至少 2 个')),
|
||||
pickBox,
|
||||
h('div.gp-form-hint', '勾选顺序就是发言人顺序;第一个是主智能体(没人被 @ 时兜底发言)。')),
|
||||
h('div', {},
|
||||
h('div.gp-form-label', '发言人顺序'),
|
||||
orderBox),
|
||||
errLine),
|
||||
footer: h('div.modal-actions', {},
|
||||
h('button.btn', { onclick: () => modal.close() }, '取消'),
|
||||
okBtn),
|
||||
});
|
||||
|
||||
async function submit() {
|
||||
if (picked.length < 2) {
|
||||
errLine.textContent = '至少要勾 2 个智能体(一个群只有一个人是没法聊的)';
|
||||
return;
|
||||
}
|
||||
const title = titleInput.value.trim() || '新群聊';
|
||||
okBtn.disabled = true;
|
||||
okBtn.textContent = '创建中…';
|
||||
errLine.textContent = '';
|
||||
try {
|
||||
const res = await api.post('/api/conversations', {
|
||||
type: 'group',
|
||||
title,
|
||||
participants: picked.slice(),
|
||||
agentId: picked[0],
|
||||
});
|
||||
const conv = (res && (res.conversation || res)) || null;
|
||||
if (!conv || !conv.id) throw new Error((res && res.error) || '内核没有返回新会话');
|
||||
await refreshConversations();
|
||||
modal.close();
|
||||
toast(`已创建「${title}」,正在打开对话…`, { type: 'success' });
|
||||
S.conversationId = conv.id;
|
||||
ctx.navigate('chat');
|
||||
} catch (err) {
|
||||
errLine.textContent = err.message;
|
||||
toast(err.message, { type: 'error' });
|
||||
okBtn.disabled = false;
|
||||
okBtn.textContent = '创建并打开';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 成员区 ---------------- */
|
||||
|
||||
function membersPanel(conv) {
|
||||
const ids = memberIds(conv);
|
||||
const box = h('div.gp-members', {},
|
||||
h('div.gp-form-hint', { style: 'padding:6px 0 2px' },
|
||||
'群里没有「主人」:谁都能移出;不同世界观的智能体不能拉进来(没绑世界观的放行)。'));
|
||||
|
||||
if (!ids.length) {
|
||||
box.appendChild(h('div.gp-form-hint', { style: 'color:var(--danger)' }, '这个群没有成员(数据异常,建议删掉重建)。'));
|
||||
}
|
||||
|
||||
ids.forEach((id, i) => {
|
||||
const agent = agentById(id);
|
||||
box.appendChild(h('div.gp-member', {},
|
||||
agent ? avatar(agent, 28) : h('span.avatar', { style: 'width:28px;height:28px' }, icon('alert-triangle', 14)),
|
||||
h('div.gp-member-main', {},
|
||||
h('div.gp-member-name', {},
|
||||
agent ? (agent.name || '未命名') : `(已删除的智能体 ${id})`,
|
||||
i === 0 ? h('span.tag.blue', '主 · 兜底') : null,
|
||||
agent && agent.builtin ? h('span.tag', '内置') : null),
|
||||
h('div.gp-member-desc', agent ? (agent.tagline || '(没有一句话介绍)') : '它已经从智能体列表里消失了,建议移出')),
|
||||
h('div.gp-member-side', {},
|
||||
h('button.btn.sm.danger', {
|
||||
disabled: ids.length <= 1 ? 'disabled' : null,
|
||||
title: ids.length <= 1 ? '不能移到一个人都不剩' : `把「${agent ? agent.name : id}」移出群`,
|
||||
onclick: () => {
|
||||
if (!agent) {
|
||||
// 智能体已经没了:接口按 id 也能移,构造一个最小对象
|
||||
removeMember(conv, { id, name: id });
|
||||
return;
|
||||
}
|
||||
removeMember(conv, agent);
|
||||
},
|
||||
}, '移出'))));
|
||||
});
|
||||
|
||||
const candidates = agents().filter((a) => !ids.includes(a.id));
|
||||
const addBtn = h('button.btn.sm', {
|
||||
disabled: candidates.length ? null : 'disabled',
|
||||
title: candidates.length ? '加一个智能体进群' : '所有智能体都已在群里',
|
||||
onclick: (e) => {
|
||||
openMenu(e.currentTarget, candidates.map((a) => ({
|
||||
label: a.name || '未命名',
|
||||
icon: 'bot',
|
||||
hint: a.tagline || '',
|
||||
onClick: () => addMember(conv, a),
|
||||
})));
|
||||
},
|
||||
}, icon('plus', 14), '加人');
|
||||
|
||||
box.appendChild(h('div.gp-members-foot', {},
|
||||
addBtn,
|
||||
h('span.gp-hint', `共 ${ids.length} 人 · 第 1 位是没人被 @ 时的兜底发言人`)));
|
||||
return box;
|
||||
}
|
||||
|
||||
/* ---------------- 卡片 ---------------- */
|
||||
|
||||
function groupCard(conv) {
|
||||
const ids = memberIds(conv);
|
||||
const isOpen = expanded.has(conv.id);
|
||||
const current = S.conversationId === conv.id;
|
||||
|
||||
const stack = h('div.gp-stack');
|
||||
const show = ids.slice(0, 3);
|
||||
for (const id of show) {
|
||||
const agent = agentById(id);
|
||||
stack.appendChild(agent
|
||||
? avatar(agent, 30)
|
||||
: h('span.avatar', { style: 'width:30px;height:30px' }, icon('alert-triangle', 13)));
|
||||
}
|
||||
if (ids.length > show.length) {
|
||||
stack.appendChild(h('span.gp-stack-more', `+${ids.length - show.length}`));
|
||||
}
|
||||
if (!ids.length) {
|
||||
stack.appendChild(h('span.gp-stack-more', {}, icon('users', 14)));
|
||||
}
|
||||
|
||||
const card = h(`div.gp-card${isOpen ? '.open' : ''}`, {},
|
||||
h('div.gp-main', {},
|
||||
stack,
|
||||
h('div.gp-info', {},
|
||||
h('div.gp-title', {},
|
||||
h('span.gp-name', { title: conv.title || '未命名群聊' }, conv.title || '未命名群聊'),
|
||||
current ? h('span.tag.blue', '当前会话') : null),
|
||||
h('div.gp-meta', {},
|
||||
h('span', {}, `成员 ${ids.length} 人`),
|
||||
h('span.dot'),
|
||||
h('span', {}, `${conv.messageCount || 0} 条消息`),
|
||||
h('span.dot'),
|
||||
h('span', {}, conv.updatedAt ? `最后更新 ${fmtRelative(conv.updatedAt)}` : '还没有消息'),
|
||||
conv.pinned ? h('span.tag', '置顶') : null)),
|
||||
h('div.gp-acts', {},
|
||||
h('button.btn.sm.primary', { onclick: () => openConversation(conv) }, '打开对话'),
|
||||
h('button.btn.sm', {
|
||||
title: isOpen ? '收起成员' : '成员与加人',
|
||||
onclick: () => {
|
||||
if (isOpen) expanded.delete(conv.id);
|
||||
else expanded.add(conv.id);
|
||||
render();
|
||||
},
|
||||
}, icon('users', 14), '成员'),
|
||||
h('button.icon-btn.sm', { title: '重命名', onclick: () => rename(conv) }, icon('pencil', 15)),
|
||||
h('button.icon-btn.sm', { title: '删除群聊', onclick: () => removeConv(conv) }, icon('trash', 15)))));
|
||||
|
||||
if (isOpen) card.appendChild(membersPanel(conv));
|
||||
return card;
|
||||
}
|
||||
|
||||
/* ---------------- 渲染 ---------------- */
|
||||
|
||||
function render() {
|
||||
clear(root);
|
||||
|
||||
const groups = groupConvs();
|
||||
root.appendChild(h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', '群聊'),
|
||||
h('div.page-sub', groups.length
|
||||
? `共 ${groups.length} 个群。用户 @ 谁就谁答;AI 之间可以把话头移交给别人。`
|
||||
: '把几个智能体拉进同一个会话,用户 @ 谁就谁答,AI 之间也能互相移交话头。')),
|
||||
h('div.page-actions', {},
|
||||
h('button.btn.primary', { onclick: openCreate }, icon('plus', 16), '新建群聊'))));
|
||||
|
||||
root.appendChild(h('div.gp-how', {},
|
||||
h('div', {}, h('b', '怎么用:'), '在对话里 @ 谁就谁回答;没人被 @ 时按成员顺序轮,第一个成员是兜底发言人。'),
|
||||
h('div', { style: 'margin-top:4px' },
|
||||
'AI 之间可以把话头交给别人 —— 交接条会出现在输入框上方,点「让「某某」接着说」就轮到它。'),
|
||||
h('div', { style: 'margin-top:4px' },
|
||||
'成员在这里增删;不同世界观的智能体不能拉进同一个群(内核限制),没绑世界观的可以。')));
|
||||
|
||||
if (!S.state) {
|
||||
root.appendChild(h('div', { style: 'display:flex;justify-content:center;padding:80px 0' }, spinner(22)));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!groups.length) {
|
||||
root.appendChild(emptyState('users', '还没有群聊',
|
||||
'建一个群,把两三个智能体拉进来:可以 @ 指定谁来答,也可以让它们自己交接话头。',
|
||||
h('div', { style: 'margin-top:16px' },
|
||||
h('button.btn.primary', { onclick: openCreate }, icon('plus', 16), '新建群聊'))));
|
||||
return;
|
||||
}
|
||||
|
||||
const list = h('div.gp-list');
|
||||
for (const conv of groups) list.appendChild(groupCard(conv));
|
||||
root.appendChild(list);
|
||||
|
||||
root.appendChild(h('div.gp-empty-tip.page-sub', {},
|
||||
'单聊会话在左侧「最近」里能直接打开;这里只列群聊。'));
|
||||
}
|
||||
|
||||
render();
|
||||
// 成员增删/改名都会让内核状态变(type 甚至可能从 group 变回 single),跟着重画
|
||||
const off = ctx.onState(() => render());
|
||||
return () => off();
|
||||
}
|
||||
362
web/js/pages/me.js
Normal file
@@ -0,0 +1,362 @@
|
||||
/**
|
||||
* 「我的」页(#/me)
|
||||
*
|
||||
* 只读为主:昵称 / Doubao ID 是 settings 里的两个键(内核:nickname 拒收空串、
|
||||
* doubaoId 可改),改的时候**只下发改动过的键** —— 设置接口是浅合并,
|
||||
* 全量下发会把没填的键清空(docs/kernel-api-agents.md §14 第 10 条)。
|
||||
*
|
||||
* 读写:GET /api/state(首屏已拿全)→ PUT /api/settings {nickname} / {doubaoId}
|
||||
* 切换当前智能体 = PUT /api/settings {activeAgentId}
|
||||
*/
|
||||
import { S, agents, settings, providers, activeAgent, saveSettings } from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, openMenu,
|
||||
injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
const CSS = `
|
||||
.me-page .me-hero { display: flex; align-items: center; gap: 16px; }
|
||||
.me-page .me-avatar {
|
||||
width: 64px; height: 64px; border-radius: 20px; flex: none;
|
||||
background: linear-gradient(135deg, #4d8eff, #0065fd);
|
||||
color: #fff; font-size: 26px; font-weight: 700;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
box-shadow: 0 8px 22px rgba(0, 101, 253, 0.24);
|
||||
}
|
||||
.me-page .me-hero-main { flex: 1; min-width: 0; }
|
||||
.me-page .me-hero-name {
|
||||
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
|
||||
font-size: 20px; font-weight: 600; line-height: 28px;
|
||||
}
|
||||
.me-page .me-hero-sub { margin-top: 2px; font-size: 13px; line-height: 20px; color: var(--text-secondary); }
|
||||
.me-page .me-hero-actions { flex: none; display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.me-page .me-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.me-page .me-two-col > .card { margin-top: 0; }
|
||||
.me-page .me-agent {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
}
|
||||
.me-page .me-agent-main { flex: 1; min-width: 0; }
|
||||
.me-page .me-agent-name { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 15px; font-weight: 600; }
|
||||
.me-page .me-agent-tag { margin-top: 4px; font-size: 12px; line-height: 18px; color: var(--text-secondary); }
|
||||
.me-page .me-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(228px, 1fr)); gap: 12px; }
|
||||
.me-page .me-entry {
|
||||
display: flex; align-items: flex-start; gap: 12px; width: 100%;
|
||||
text-align: left; cursor: pointer; font: inherit; color: inherit;
|
||||
}
|
||||
.me-page .me-entry-icon {
|
||||
width: 36px; height: 36px; border-radius: 12px; flex: none;
|
||||
background: var(--bg-base-2); color: var(--text-secondary);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.me-page .me-entry:hover .me-entry-icon { background: var(--brand-weak); color: var(--brand); }
|
||||
.me-page .me-entry-main { min-width: 0; }
|
||||
.me-page .me-entry-title { font-size: 14px; font-weight: 500; line-height: 22px; }
|
||||
.me-page .me-entry-desc {
|
||||
margin-top: 2px; font-size: 12px; line-height: 18px; color: var(--text-secondary);
|
||||
overflow: hidden; text-overflow: ellipsis; display: -webkit-box;
|
||||
-webkit-line-clamp: 2; -webkit-box-orient: vertical;
|
||||
}
|
||||
.me-page .me-mono { font-family: var(--font-mono); font-size: 12px; }
|
||||
.me-page .me-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 14px; }
|
||||
.me-page .me-hint { margin-top: 10px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); }
|
||||
.me-page .me-foot { margin-top: 20px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); text-align: center; }
|
||||
@media (max-width: 760px) {
|
||||
.me-page .me-two-col { grid-template-columns: 1fr; }
|
||||
}
|
||||
`;
|
||||
|
||||
const PLATFORM_LABEL = {
|
||||
win32: 'Windows',
|
||||
darwin: 'macOS',
|
||||
linux: 'Linux',
|
||||
android: 'Android',
|
||||
freebsd: 'FreeBSD',
|
||||
};
|
||||
|
||||
function platformText() {
|
||||
const raw = String((S.state && S.state.platform) || '');
|
||||
if (!raw) return '未知';
|
||||
return PLATFORM_LABEL[raw] ? `${PLATFORM_LABEL[raw]}(${raw})` : raw;
|
||||
}
|
||||
|
||||
function firstChar(text) {
|
||||
const t = String(text || '').trim();
|
||||
return t ? t.slice(0, 1).toUpperCase() : '我';
|
||||
}
|
||||
|
||||
export default function renderMe(container, ctx) {
|
||||
injectStyles('me', CSS);
|
||||
|
||||
const st = {
|
||||
draft: null, // { nickname, doubaoId },跨重渲染保留用户还没保存的输入
|
||||
saving: false,
|
||||
};
|
||||
|
||||
const root = h('div.page-inner.me-page');
|
||||
mount(container, root);
|
||||
ctx.setTitle('我的');
|
||||
|
||||
function syncDraft({ force = false } = {}) {
|
||||
const s = settings();
|
||||
if (!st.draft || force) {
|
||||
st.draft = { nickname: s.nickname || '', doubaoId: s.doubaoId || '' };
|
||||
}
|
||||
return st.draft;
|
||||
}
|
||||
|
||||
/* ---------------- 渲染 ---------------- */
|
||||
|
||||
function render() {
|
||||
syncDraft();
|
||||
clear(root);
|
||||
root.appendChild(renderHead());
|
||||
root.appendChild(renderProfileCard());
|
||||
root.appendChild(renderAgentAndModel());
|
||||
root.appendChild(renderEntries());
|
||||
root.appendChild(renderEnvCard());
|
||||
root.appendChild(h('div.me-foot', {},
|
||||
`数据都在你自己的机器上 · 内核同一份,Android App 也用这份 · v2 网页版`));
|
||||
}
|
||||
|
||||
function renderHead() {
|
||||
const s = settings();
|
||||
const draft = syncDraft();
|
||||
return h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', '我的'),
|
||||
h('div.page-sub', '本地个人资料 · 当前智能体 · 运行环境')),
|
||||
h('div.page-actions', {},
|
||||
h('button.btn', { onclick: () => ctx.navigate('settings') }, icon('settings', 15), '设置'),
|
||||
h('button.btn', { onclick: () => ctx.navigate('about') }, icon('info', 15), '关于豆包')));
|
||||
}
|
||||
|
||||
function renderProfileCard() {
|
||||
const s = settings();
|
||||
const draft = syncDraft();
|
||||
const nick = (draft.nickname || '').trim() || '我';
|
||||
|
||||
const nickInput = h('input.input', {
|
||||
placeholder: '你的昵称(内核拒收空串)',
|
||||
maxlength: 24,
|
||||
oninput: () => { st.draft.nickname = nickInput.value; syncSaveState(); },
|
||||
});
|
||||
nickInput.value = draft.nickname;
|
||||
|
||||
const idInput = h('input.input', {
|
||||
placeholder: 'Doubao ID',
|
||||
maxlength: 32,
|
||||
oninput: () => { st.draft.doubaoId = idInput.value; syncSaveState(); },
|
||||
});
|
||||
idInput.value = draft.doubaoId;
|
||||
|
||||
const saveBtn = h('button.btn.primary', {
|
||||
disabled: st.saving,
|
||||
onclick: (e) => saveProfile(e.currentTarget),
|
||||
}, st.saving ? '保存中…' : '保存资料');
|
||||
const dirtyEl = h('span.me-hint', { style: 'margin:0' });
|
||||
|
||||
function changedPatch() {
|
||||
const patch = {};
|
||||
const nextNick = (st.draft.nickname || '').trim();
|
||||
const nextId = (st.draft.doubaoId || '').trim();
|
||||
const cur = settings();
|
||||
if (nextNick && nextNick !== (cur.nickname || '')) patch.nickname = nextNick;
|
||||
if (nextId !== (cur.doubaoId || '')) patch.doubaoId = nextId;
|
||||
return patch;
|
||||
}
|
||||
function syncSaveState() {
|
||||
const patch = changedPatch();
|
||||
const keys = Object.keys(patch);
|
||||
const dirty = keys.length > 0;
|
||||
const emptyNick = !(st.draft.nickname || '').trim();
|
||||
saveBtn.disabled = st.saving || !dirty || emptyNick;
|
||||
clear(dirtyEl);
|
||||
if (emptyNick) dirtyEl.appendChild(document.createTextNode('昵称不能为空(内核会拒收空串)'));
|
||||
else if (dirty) dirtyEl.appendChild(document.createTextNode(`有未保存的改动:${keys.map((k) => (k === 'nickname' ? '昵称' : 'Doubao ID')).join(' / ')}`));
|
||||
}
|
||||
syncSaveState();
|
||||
|
||||
return h('div.card', {},
|
||||
h('div.me-hero', {},
|
||||
h('div.me-avatar', {}, firstChar(nick)),
|
||||
h('div.me-hero-main', {},
|
||||
h('div.me-hero-name', {},
|
||||
nick,
|
||||
h('span.tag', s.hasApiKey ? '模型已配置' : '模型未配置')),
|
||||
h('div.me-hero-sub', {},
|
||||
`Doubao ID:${draft.doubaoId || '未设置'}`,
|
||||
' · ',
|
||||
s.activeAgentId ? `当前智能体:${(activeAgent() || {}).name || s.activeAgentId}` : '还没有选智能体')),
|
||||
h('div.me-hero-actions', {},
|
||||
h('button.btn', { onclick: () => ctx.navigate('chat') }, icon('message-circle', 15), '去对话'))),
|
||||
h('div.card-body', {},
|
||||
h('div.field-row', {},
|
||||
h('div.field-label', {}, '昵称', h('div.field-hint', {}, '你自己在这些界面上显示的名字')),
|
||||
h('div.field-control', {}, nickInput)),
|
||||
h('div.field-row', {},
|
||||
h('div.field-label', {}, 'Doubao ID', h('div.field-hint', {}, '个人资料里的展示 id,可以随便改')),
|
||||
h('div.field-control', {}, idInput))),
|
||||
h('div.me-actions', {}, saveBtn, dirtyEl));
|
||||
}
|
||||
|
||||
async function saveProfile(btn) {
|
||||
const patch = {};
|
||||
const nextNick = (st.draft.nickname || '').trim();
|
||||
const nextId = (st.draft.doubaoId || '').trim();
|
||||
const cur = settings();
|
||||
if (nextNick && nextNick !== (cur.nickname || '')) patch.nickname = nextNick;
|
||||
if (nextId !== (cur.doubaoId || '')) patch.doubaoId = nextId;
|
||||
if (!Object.keys(patch).length) {
|
||||
toast('没有改动');
|
||||
return;
|
||||
}
|
||||
st.saving = true;
|
||||
render();
|
||||
try {
|
||||
await saveSettings(patch); // 只发改动过的键 —— 浅合并,全量会清空别的设置
|
||||
syncDraft({ force: true });
|
||||
toast('资料已保存', { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
st.saving = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 当前智能体 + 模型 ---------------- */
|
||||
|
||||
function renderAgentAndModel() {
|
||||
return h('div.me-two-col', {}, renderAgentCard(), renderModelCard());
|
||||
}
|
||||
|
||||
function renderAgentCard() {
|
||||
const s = settings();
|
||||
const agent = activeAgent();
|
||||
const wv = (S.state && S.state.worldviews || []).find((w) => w.id === agent.worldviewId);
|
||||
const emo = (S.state && S.state.emotions) || {};
|
||||
const preset = (emo[agent.id] && emo[agent.id].preset) || '平常';
|
||||
const dead = preset === '死亡';
|
||||
|
||||
const tags = h('div.me-agent-name', {},
|
||||
h('span', agent.name || '未选择'),
|
||||
agent.builtin ? h('span.tag', '内置') : h('span.tag.blue', '自定义'),
|
||||
dead ? h('span.tag.red', '已死亡') : null,
|
||||
wv ? h('span.tag.orange', '世界观 · ' + wv.name) : null);
|
||||
|
||||
return h('div.card', {},
|
||||
h('div.card-title', {}, icon('bot', 18), '当前智能体'),
|
||||
h('div.card-body', {},
|
||||
h('div.me-agent', {},
|
||||
avatar(agent, 44),
|
||||
h('div.me-agent-main', {},
|
||||
tags,
|
||||
h('div.me-agent-tag', {}, agent.tagline || '还没有一句话介绍'))),
|
||||
h('div.me-actions', {},
|
||||
h('button.btn.sm', { onclick: (e) => openAgentMenu(e.currentTarget) }, icon('users', 14), '切换'),
|
||||
h('button.btn.sm', { onclick: () => ctx.navigate(`agents/${agent.id}/memories`) }, icon('brain', 14), '记忆'),
|
||||
h('button.btn.sm', { onclick: () => ctx.navigate(`agents/${agent.id}/usage`) }, icon('cpu', 14), '用量'),
|
||||
h('button.btn.sm', { onclick: () => ctx.navigate(`agents/${agent.id}`) }, icon('pencil', 14), '编辑'))),
|
||||
h('div.me-hint', {}, s.activeAgentId
|
||||
? '换人 = 改 settings.activeAgentId;聊天、记忆、用量都跟着这个人走。'
|
||||
: '还没选过智能体(默认用列表里的第一个)。'));
|
||||
}
|
||||
|
||||
function openAgentMenu(anchor) {
|
||||
const cur = (settings().activeAgentId || '') || (activeAgent() || {}).id;
|
||||
const items = agents().map((a) => ({
|
||||
label: a.name,
|
||||
icon: a.id === cur ? 'check' : 'bot',
|
||||
hint: a.tagline || '',
|
||||
onClick: () => switchTo(a),
|
||||
}));
|
||||
items.push('-');
|
||||
items.push({ label: '管理智能体…', icon: 'settings', onClick: () => ctx.navigate('agents') });
|
||||
openMenu(anchor, items, { alignRight: true });
|
||||
}
|
||||
|
||||
async function switchTo(agent) {
|
||||
try {
|
||||
await saveSettings({ activeAgentId: agent.id });
|
||||
toast(`已切换到「${agent.name}」`, { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
function renderModelCard() {
|
||||
const s = settings();
|
||||
const p = providers()[s.provider] || {};
|
||||
const actual = (S.state && S.state.provider) || {};
|
||||
const provLabel = p.label || actual.label || s.provider || '未设置';
|
||||
const model = s.model || actual.model || p.defaultModel || '未设置';
|
||||
const baseUrl = actual.baseUrl || s.baseUrl || '';
|
||||
|
||||
return h('div.card', {},
|
||||
h('div.card-title', {}, icon('cpu', 18), '当前模型',
|
||||
h(`span.tag${s.hasApiKey ? '.green' : '.red'}`, s.hasApiKey ? '已配置' : '未配置')),
|
||||
h('div.card-body', {},
|
||||
h('div.kv', {}, h('span.k', '提供商'), h('span.v', provLabel)),
|
||||
h('div.kv', {}, h('span.k', '模型'), h('span.v', {}),
|
||||
),
|
||||
h('div.kv', {}, h('span.k', '思考强度'), h('span.v', s.thinkingLevel || 'auto')),
|
||||
h('div.kv', {}, h('span.k', '接口地址'),
|
||||
h('span.v.me-mono', { title: baseUrl || '继承提供商预设' }, baseUrl || '继承预设'))),
|
||||
h('div.me-actions', {},
|
||||
h('button.btn.sm', { onclick: () => ctx.navigate('settings') }, icon('key', 14), '填 Key / 换模型'),
|
||||
h('button.btn.sm', { onclick: () => ctx.navigate('skills') }, icon('plug', 14), '连接器')),
|
||||
h('div.me-hint', {}, s.hasApiKey
|
||||
? 'Key 只存在你本机的 settings.json 里,界面只看到掩码。'
|
||||
: '还没配 API Key —— 现在能改设置、看记忆,但对话发不出去。'));
|
||||
}
|
||||
|
||||
/* ---------------- 快捷入口 ---------------- */
|
||||
|
||||
function entry(iconName, title, desc, onclick) {
|
||||
return h('button.card.clickable.me-entry', { onclick },
|
||||
h('div.me-entry-icon', {}, icon(iconName, 18)),
|
||||
h('div.me-entry-main', {},
|
||||
h('div.me-entry-title', {}, title),
|
||||
h('div.me-entry-desc', {}, desc)));
|
||||
}
|
||||
|
||||
function renderEntries() {
|
||||
const agent = activeAgent();
|
||||
const aid = agent.id || '';
|
||||
const grid = h('div.me-grid', {},
|
||||
entry('bot', '智能体', '人设、模型、Token 限额', () => ctx.navigate('agents')),
|
||||
entry('brain', '记忆', `「${agent.name || '当前智能体'}」记得什么`, () => ctx.navigate(`agents/${aid}/memories`)),
|
||||
entry('cpu', '用量', 'Token 统计、额度、清零', () => ctx.navigate(`agents/${aid}/usage`)),
|
||||
entry('layers', '资源', '世界观 / 规则包 / 模型 / 技能', () => ctx.navigate('resources')),
|
||||
entry('plug', '技能 · 连接器', '工具白名单、MCP', () => ctx.navigate('skills')),
|
||||
entry('settings', '设置', 'Key、对话窗口、语音、超时', () => ctx.navigate('settings')),
|
||||
entry('info', '关于豆包', '这是什么、技术架构、快捷键', () => ctx.navigate('about')));
|
||||
return h('div', {},
|
||||
h('div.section-title', {}, h('span', '快捷入口')),
|
||||
grid);
|
||||
}
|
||||
|
||||
/* ---------------- 运行环境 ---------------- */
|
||||
|
||||
function renderEnvCard() {
|
||||
const s = settings();
|
||||
const shellKind = (S.state && S.state.shellKind) || '';
|
||||
const toolsDir = s.toolsDir || '';
|
||||
return h('div', {},
|
||||
h('div.section-title', {}, h('span', '运行环境')),
|
||||
h('div.card', {},
|
||||
h('div.kv', {}, h('span.k', '平台'), h('span.v', platformText())),
|
||||
h('div.kv', {}, h('span.k', '执行外壳'), h('span.v', shellKind || '浏览器 / 桌面壳')),
|
||||
h('div.kv', {}, h('span.k', '工具目录'),
|
||||
h('span.v.me-mono', { title: toolsDir || '内置 tools/' }, toolsDir || '内置 tools/(留空)')),
|
||||
h('div.kv', {}, h('span.k', '记忆注入窗口'), h('span.v', `${s.memoryWindow ?? '—'} 条`)),
|
||||
h('div.kv', {}, h('span.k', '对话上下文窗口'), h('span.v', `${s.contextWindow ?? '—'} 轮`)),
|
||||
h('div.kv', {}, h('span.k', '界面版本'), h('span.v', 'v2 网页版'))));
|
||||
}
|
||||
|
||||
/* ---------------- 启动 ---------------- */
|
||||
|
||||
const off = ctx.onState(() => { render(); });
|
||||
render();
|
||||
return () => { off(); };
|
||||
}
|
||||
432
web/js/pages/meetings.js
Normal file
@@ -0,0 +1,432 @@
|
||||
/**
|
||||
* 会议模式(网页版 · 一期最小实现)
|
||||
*
|
||||
* 一期只做:列表 / 新建 / 重命名 / 删除 / 运行(SSE 实时日志)/ 结果 / 历史。
|
||||
* 节点画布是二期的活(Android 那份画布 7600 行,不硬搬)——先把"跑起来看得到结果"做通。
|
||||
*
|
||||
* 接口:
|
||||
* GET /api/meetings 列表({meetings:[{id,name,nodeCount,edgeCount,updatedAt}]})
|
||||
* POST /api/meetings {name}
|
||||
* GET /api/meetings/<id> 详情(含 nodes/edges)
|
||||
* PUT /api/meetings/<id> {name} 改名(服务端会清洗 nodes/edges,只发改动字段最稳)
|
||||
* DELETE /api/meetings/<id>
|
||||
* POST /api/meetings/<id>/run {input} → SSE
|
||||
* GET /api/meetings/<id>/runs 历史(最新在前,最多 20)
|
||||
* DELETE /api/meetings/<id>/runs 清空历史
|
||||
*/
|
||||
import { api } from '../api.js';
|
||||
import {
|
||||
h, clear, icon, mount, toast, openModal, confirmBox, promptBox,
|
||||
sectionTitle, emptyState, fmtRelative, fmtTime, injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
injectStyles('meetings', `
|
||||
.mt-card { display: flex; gap: 14px; align-items: center; padding: 16px 18px; }
|
||||
.mt-main { flex: 1; min-width: 0; }
|
||||
.mt-name { font-size: 15px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
|
||||
.mt-meta { margin-top: 4px; font-size: 12px; color: var(--text-tertiary); }
|
||||
.mt-actions { display: flex; gap: 6px; flex: none; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.mt-run { margin-top: 16px; }
|
||||
.mt-run-grid { display: grid; grid-template-columns: 260px 1fr; gap: 14px; }
|
||||
@media (max-width: 900px) { .mt-run-grid { grid-template-columns: 1fr; } }
|
||||
.mt-nodes { display: flex; flex-direction: column; gap: 6px; max-height: 420px; overflow-y: auto; }
|
||||
.mt-node {
|
||||
display: flex; align-items: center; gap: 8px; padding: 8px 10px;
|
||||
border: 1px solid var(--line-1); border-radius: var(--r-sm); font-size: 13px;
|
||||
background: var(--bg-body);
|
||||
}
|
||||
.mt-node .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-disable); flex: none; }
|
||||
.mt-node.running .dot { background: var(--brand); animation: mt-pulse 1s infinite; }
|
||||
.mt-node.done .dot { background: var(--success); }
|
||||
.mt-node.error .dot { background: var(--danger); }
|
||||
.mt-node .mt-node-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.mt-node .mt-node-type { font-size: 11px; color: var(--text-tertiary); font-family: var(--font-mono); }
|
||||
@keyframes mt-pulse { 50% { opacity: 0.35; } }
|
||||
.mt-log {
|
||||
border: 1px solid var(--line-1); border-radius: var(--r-md); background: var(--bg-sidebar);
|
||||
height: 420px; overflow-y: auto; padding: 10px 12px;
|
||||
font-family: var(--font-mono); font-size: 12px; line-height: 19px; white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.mt-log .l-start { color: var(--brand); }
|
||||
.mt-log .l-done { color: #1f9f3a; }
|
||||
.mt-log .l-error { color: var(--danger); }
|
||||
.mt-log .l-warn { color: var(--warning); }
|
||||
.mt-log .l-delta { color: var(--text-primary); }
|
||||
.mt-log .l-meta { color: var(--text-tertiary); }
|
||||
.mt-results { margin-top: 14px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.mt-result { border: 1px solid var(--line-1); border-radius: var(--r-md); padding: 10px 12px; }
|
||||
.mt-result .mt-result-title { font-size: 13px; font-weight: 600; display: flex; gap: 8px; align-items: center; }
|
||||
.mt-result pre {
|
||||
margin: 6px 0 0; padding: 8px 10px; background: var(--fill-1); border-radius: var(--r-xs);
|
||||
font-family: var(--font-mono); font-size: 12px; line-height: 18px; white-space: pre-wrap;
|
||||
overflow-wrap: anywhere; max-height: 260px; overflow: auto;
|
||||
}
|
||||
`);
|
||||
|
||||
async function fetchMeetings() {
|
||||
const res = await api.get('/api/meetings');
|
||||
if (Array.isArray(res)) return res;
|
||||
return res.meetings || [];
|
||||
}
|
||||
|
||||
async function fetchMeeting(id) {
|
||||
const res = await api.get(`/api/meetings/${encodeURIComponent(id)}`);
|
||||
return res.meeting || res;
|
||||
}
|
||||
|
||||
export default function renderMeetings(container, ctx) {
|
||||
let meetings = [];
|
||||
let loading = true;
|
||||
let error = null;
|
||||
let running = null;
|
||||
let current = null;
|
||||
|
||||
const pageEl = h('div.page-inner');
|
||||
mount(container, pageEl);
|
||||
|
||||
function header() {
|
||||
return h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', '会议模式'),
|
||||
h('div.page-sub', '把多个智能体按节点编排起来跑一场任务。网页版一期只做「列表 / 运行 / 结果 / 历史」,节点画布是二期(手机端有)。')),
|
||||
h('div.page-actions', {},
|
||||
h('button.btn', { onclick: () => load() }, icon('refresh', 15), '刷新'),
|
||||
h('button.btn.primary', { onclick: createMeeting }, icon('plus', 16), '新建会议')));
|
||||
}
|
||||
|
||||
function render() {
|
||||
clear(pageEl);
|
||||
pageEl.appendChild(header());
|
||||
if (loading) {
|
||||
pageEl.appendChild(h('div', { style: 'display:flex;justify-content:center;padding:60px 0' },
|
||||
h('span.spinner', { style: 'width:22px;height:22px' })));
|
||||
return;
|
||||
}
|
||||
if (error) {
|
||||
pageEl.appendChild(emptyState('alert-triangle', '会议列表加载失败', error, h('button.btn', {
|
||||
onclick: () => load(), style: 'margin-top:12px',
|
||||
}, '重试')));
|
||||
return;
|
||||
}
|
||||
if (!meetings.length) {
|
||||
pageEl.appendChild(emptyState('presentation', '还没有会议',
|
||||
'新建一场会议:服务端会先给一个「初始输入 → 智能体 → 最终输出」的三节点图,可以直接运行。',
|
||||
h('button.btn.primary', { onclick: createMeeting, style: 'margin-top:12px' }, '新建会议')));
|
||||
return;
|
||||
}
|
||||
for (const m of meetings) {
|
||||
pageEl.appendChild(h('div.card.mt-card', {},
|
||||
h('div.mt-main', {},
|
||||
h('div.mt-name', {}, icon('presentation', 16), m.name || '未命名会议'),
|
||||
h('div.mt-meta', {}, `${m.nodeCount ?? 0} 个节点 · ${m.edgeCount ?? 0} 条连线 · 更新于 ${fmtRelative(m.updatedAt)}`)),
|
||||
h('div.mt-actions', {},
|
||||
h('button.btn.sm.primary', { onclick: () => openRun(m) }, icon('play', 14), '运行'),
|
||||
h('button.btn.sm', { onclick: () => openHistory(m) }, icon('history', 14), '历史'),
|
||||
h('button.icon-btn.sm', { title: '重命名', onclick: () => renameMeeting(m) }, icon('pencil', 14)),
|
||||
h('button.icon-btn.sm', { title: '删除', onclick: () => deleteMeeting(m) }, icon('trash', 14)))));
|
||||
}
|
||||
if (current) pageEl.appendChild(renderRunPanel(current));
|
||||
}
|
||||
|
||||
/* ------------------------- 列表操作 ------------------------- */
|
||||
|
||||
async function load() {
|
||||
loading = true; error = null; render();
|
||||
try {
|
||||
meetings = await fetchMeetings();
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
} finally {
|
||||
loading = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
async function createMeeting() {
|
||||
const name = await promptBox({ title: '新建会议', placeholder: '会议名字,例如:周报生成', okText: '新建' });
|
||||
if (!name || !name.trim()) return;
|
||||
try {
|
||||
const res = await api.post('/api/meetings', { name: name.trim() });
|
||||
toast('会议已创建', { type: 'success' });
|
||||
await load();
|
||||
const created = res.meeting;
|
||||
if (created && created.id) openRun(created);
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function renameMeeting(m) {
|
||||
const name = await promptBox({ title: '重命名会议', value: m.name || '', okText: '保存' });
|
||||
if (name == null) return;
|
||||
try {
|
||||
await api.put(`/api/meetings/${encodeURIComponent(m.id)}`, { name: name.trim() || m.name });
|
||||
toast('已保存', { type: 'success' });
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteMeeting(m) {
|
||||
const ok = await confirmBox({
|
||||
title: '删除这场会议?',
|
||||
message: `「${m.name || '未命名会议'}」的节点定义和历史记录都会删除,不可恢复。`,
|
||||
danger: true, okText: '删除',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.del(`/api/meetings/${encodeURIComponent(m.id)}`);
|
||||
toast('已删除', { type: 'success' });
|
||||
if (current && current.id === m.id) current = null;
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------- 运行面板 ------------------------- */
|
||||
|
||||
function openRun(meetingMeta) {
|
||||
current = { ...meetingMeta };
|
||||
render();
|
||||
setTimeout(() => pageEl.querySelector('.mt-run')?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 30);
|
||||
}
|
||||
|
||||
function renderRunPanel(meta) {
|
||||
const wrap = h('div.mt-run');
|
||||
wrap.appendChild(sectionTitle(`运行:${meta.name || ''}`, h('button.btn.sm.ghost', {
|
||||
onclick: () => { current = null; stopRun(); render(); },
|
||||
}, '收起')));
|
||||
|
||||
const input = h('textarea.textarea', { rows: 3, placeholder: '这次会议的初始输入(比如要处理的一段话)' });
|
||||
const runBtn = h('button.btn.primary', { onclick: () => startRun(meta, input.value) }, icon('play', 15), '开始运行');
|
||||
const stopBtn = h('button.btn.danger', { onclick: stopRun, style: 'display:none' }, icon('square', 13), '停止');
|
||||
const nodeList = h('div.mt-nodes');
|
||||
const log = h('div.mt-log');
|
||||
const results = h('div.mt-results');
|
||||
|
||||
wrap.appendChild(h('div.card', { style: 'margin-top:12px' },
|
||||
h('div', { style: 'margin-bottom:10px' }, input),
|
||||
h('div', { style: 'display:flex;gap:8px;margin-bottom:12px' }, runBtn, stopBtn,
|
||||
h('span', { style: 'font-size:12px;color:var(--text-tertiary);align-self:center' },
|
||||
'运行事件会实时打在这里;单个节点报错不会中断整场。')),
|
||||
h('div.mt-run-grid', {},
|
||||
h('div', {}, h('div.section-title', { style: 'padding-top:0' }, '节点'), nodeList),
|
||||
log),
|
||||
results));
|
||||
|
||||
let nodes = [];
|
||||
fetchMeeting(meta.id).then((detail) => {
|
||||
nodes = detail.nodes || [];
|
||||
if (!nodes.length) {
|
||||
nodeList.appendChild(h('div', { style: 'font-size:13px;color:var(--text-tertiary)' }, '这场会议没有节点(定义被清空了?)'));
|
||||
return;
|
||||
}
|
||||
for (const n of nodes) {
|
||||
nodeList.appendChild(h('div.mt-node', { 'data-node-id': n.id },
|
||||
h('span.dot'),
|
||||
h('span.mt-node-title', n.title || n.id),
|
||||
h('span.mt-node-type', n.type || '')));
|
||||
}
|
||||
}).catch((err) => {
|
||||
nodeList.appendChild(h('div', { style: 'font-size:13px;color:var(--danger)' }, `节点加载失败:${err.message}`));
|
||||
});
|
||||
|
||||
const logLine = (cls, text) => {
|
||||
const line = h(`div.l-${cls}`, String(text));
|
||||
log.appendChild(line);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
};
|
||||
// 流式增量要追加到同一个节点的那一行里,不能一个 chunk 一个 div(会变成竖排)
|
||||
const deltaEls = new Map();
|
||||
const appendDelta = (nodeId, text) => {
|
||||
let el = deltaEls.get(nodeId);
|
||||
if (!el) {
|
||||
el = h('div.l-delta');
|
||||
log.appendChild(el);
|
||||
deltaEls.set(nodeId, el);
|
||||
}
|
||||
el.textContent += text || '';
|
||||
log.scrollTop = log.scrollHeight;
|
||||
};
|
||||
const setNodeState = (nodeId, state) => {
|
||||
const el = nodeList.querySelector(`[data-node-id="${CSS.escape(String(nodeId))}"]`);
|
||||
if (!el) return;
|
||||
el.classList.remove('running', 'done', 'error');
|
||||
if (state) el.classList.add(state);
|
||||
if (state === 'done' || state === 'error') deltaEls.delete(nodeId);
|
||||
};
|
||||
|
||||
function startRun(meeting, text) {
|
||||
stopRun();
|
||||
clear(log);
|
||||
clear(results);
|
||||
nodeList.querySelectorAll('.mt-node').forEach((n) => n.classList.remove('running', 'done', 'error'));
|
||||
const controller = new AbortController();
|
||||
running = controller;
|
||||
runBtn.style.display = 'none';
|
||||
stopBtn.style.display = '';
|
||||
logLine('meta', `=== 开始运行「${meeting.name || ''}」 ===`);
|
||||
if (text) logLine('meta', `输入:${text.slice(0, 200)}`);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/meetings/${encodeURIComponent(meeting.id)}/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ input: text || '' }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`;
|
||||
try { const j = await res.json(); msg = j.error || msg; } catch { /* 不是 JSON */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
let buffer = '';
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let idx = buffer.indexOf('\n\n');
|
||||
while (idx >= 0) {
|
||||
const frame = buffer.slice(0, idx);
|
||||
buffer = buffer.slice(idx + 2);
|
||||
idx = buffer.indexOf('\n\n');
|
||||
for (const line of frame.split('\n')) {
|
||||
if (!line.startsWith('data:')) continue;
|
||||
const raw = line.slice(5).trim();
|
||||
if (!raw) continue;
|
||||
let ev = null;
|
||||
try { ev = JSON.parse(raw); } catch { continue; }
|
||||
handleEvent(ev, { logLine, setNodeState, results, appendDelta });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.name === 'AbortError') logLine('warn', '(已手动停止)');
|
||||
else logLine('error', `运行失败:${err.message}`);
|
||||
} finally {
|
||||
running = null;
|
||||
runBtn.style.display = '';
|
||||
stopBtn.style.display = 'none';
|
||||
logLine('meta', '=== 结束 ===');
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function handleEvent(ev, ui) {
|
||||
switch (ev.type) {
|
||||
case 'meeting_start':
|
||||
ui.logLine('meta', `会议开始:${ev.nodes ?? 0} 个节点 / ${ev.edges ?? 0} 条连线`);
|
||||
break;
|
||||
case 'node_start':
|
||||
ui.setNodeState(ev.nodeId, 'running');
|
||||
ui.logLine('start', `▶ ${ev.title || ev.nodeId}${ev.nodeType ? ` [${ev.nodeType}]` : ''}${ev.run > 1 ? ` 第 ${ev.run} 次` : ''}`);
|
||||
break;
|
||||
case 'node_delta':
|
||||
ui.appendDelta(ev.nodeId, ev.text || '');
|
||||
break;
|
||||
case 'node_reasoning':
|
||||
break;
|
||||
case 'node_done':
|
||||
ui.setNodeState(ev.nodeId, 'done');
|
||||
ui.logLine('done', `✓ ${ev.title || ev.nodeId}${ev.note ? ` · ${ev.note}` : ''}${ev.verdict != null ? ` · 判定 ${ev.verdict}` : ''}`);
|
||||
if (ev.output) ui.logLine('meta', `输出:${String(ev.output).slice(0, 300)}`);
|
||||
break;
|
||||
case 'node_warn':
|
||||
ui.logLine('warn', `⚠ ${ev.warn || ev.nodeId}`);
|
||||
break;
|
||||
case 'node_error':
|
||||
ui.setNodeState(ev.nodeId, 'error');
|
||||
ui.logLine('error', `✗ ${ev.title || ev.nodeId || ''}:${ev.error || '节点出错'}`);
|
||||
break;
|
||||
case 'node_vars':
|
||||
ui.logLine('meta', `变量更新:${JSON.stringify(ev.vars || {})}`);
|
||||
break;
|
||||
case 'meeting_done': {
|
||||
if (ev.error) ui.logLine('error', `会议出错:${ev.error}`);
|
||||
if (ev.aborted) ui.logLine('warn', '会议被中止');
|
||||
ui.logLine('done', '=== 会议结束 ===');
|
||||
if (ev.output) ui.logLine('done', ev.output);
|
||||
const box = ui.results;
|
||||
clear(box);
|
||||
(ev.results || []).forEach((r) => {
|
||||
let value = r.value;
|
||||
if (r.type === 'list' && typeof value === 'string') {
|
||||
try { value = JSON.parse(value); } catch { /* 原样 */ }
|
||||
}
|
||||
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
||||
box.appendChild(h('div.mt-result', {},
|
||||
h('div.mt-result-title', {},
|
||||
h('span.tag.blue', r.type || 'str'),
|
||||
r.title || r.nodeId || '输出'),
|
||||
h('pre', {}, text == null ? '(空)' : String(text))));
|
||||
});
|
||||
if (!(ev.results || []).length && ev.output) {
|
||||
box.appendChild(h('div.mt-result', {}, h('div.mt-result-title', {}, '最终输出'), h('pre', {}, String(ev.output))));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
if (ev.type === 'tool_call') ui.logLine('meta', ` ↳ 调用工具 ${ev.name || ''}`);
|
||||
else if (ev.type === 'tool_result') ui.logLine('meta', ` ↳ 工具返回 ${ev.name || ''}${ev.ok ? '' : '(失败)'}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function stopRun() {
|
||||
if (running) {
|
||||
try { running.abort(); } catch { /* */ }
|
||||
running = null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------- 历史 ------------------------- */
|
||||
|
||||
async function openHistory(m) {
|
||||
const modal = openModal({ title: `运行历史 · ${m.name || ''}`, width: 760, body: h('div', {}, '加载中…') });
|
||||
try {
|
||||
const res = await api.get(`/api/meetings/${encodeURIComponent(m.id)}/runs`);
|
||||
const runs = res.runs || [];
|
||||
clear(modal.body);
|
||||
if (!runs.length) {
|
||||
modal.body.appendChild(emptyState('history', '还没有运行记录', '跑一次之后,历史会存在这里(每场最多 20 条)。'));
|
||||
return;
|
||||
}
|
||||
modal.body.appendChild(h('div', { style: 'display:flex;justify-content:flex-end;margin-bottom:8px' },
|
||||
h('button.btn.sm.danger', {
|
||||
onclick: async () => {
|
||||
const ok = await confirmBox({ title: '清空运行历史?', message: '这场会议的所有运行记录会被删除。', danger: true, okText: '清空' });
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.del(`/api/meetings/${encodeURIComponent(m.id)}/runs`);
|
||||
modal.close();
|
||||
toast('已清空', { type: 'success' });
|
||||
} catch (err) { toast(err.message, { type: 'error' }); }
|
||||
},
|
||||
}, '清空历史')));
|
||||
for (const run of runs) {
|
||||
modal.body.appendChild(h('div.card', { style: 'margin-bottom:10px' },
|
||||
h('div', { style: 'display:flex;align-items:center;gap:8px;margin-bottom:6px' },
|
||||
h('span.tag', {}, fmtTime(run.at)),
|
||||
run.error ? h('span.tag.red', '出错') : run.aborted ? h('span.tag.orange', '中止') : h('span.tag.green', '完成'),
|
||||
h('span', { style: 'font-size:12px;color:var(--text-tertiary);flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap' },
|
||||
run.input ? `输入:${run.input}` : '')),
|
||||
h('pre', { style: 'margin:0;padding:8px 10px;background:var(--fill-1);border-radius:8px;font-family:var(--font-mono);font-size:12px;max-height:200px;overflow:auto;white-space:pre-wrap' },
|
||||
String(run.output || run.error || JSON.stringify(run.results || [], null, 2)).slice(0, 4000))));
|
||||
}
|
||||
} catch (err) {
|
||||
clear(modal.body);
|
||||
modal.body.appendChild(h('div', { style: 'color:var(--danger);font-size:13px' }, `加载失败:${err.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
}
|
||||
868
web/js/pages/memories.js
Normal file
@@ -0,0 +1,868 @@
|
||||
/**
|
||||
* 记忆页(#/agents/:id/memories)
|
||||
*
|
||||
* 一条记忆挂在一个「空间」上(docs/kernel-api-agents.md §3.1):
|
||||
* 没绑世界观 → agent:<id>(私有) 绑了 → world:<wid>(同世界观的智能体共用)
|
||||
* 绑定/解绑只换读写空间,记忆一条不迁移、不删除 —— 所以这个页面要交代三件事:
|
||||
* 1. 当前空间里的记忆(可加、可改、可删、可置顶)
|
||||
* 2. 绑定世界观**之前**的私有记忆(?space=own,只读浏览:写入永远进当前空间)
|
||||
* 3. 世界观共享记忆(GET /api/worldviews/<id>/memories,只读,带作者署名)
|
||||
*
|
||||
* 接口:
|
||||
* GET /api/agents/<id>/memories[?space=own]
|
||||
* POST /api/agents/<id>/memories {title, content}
|
||||
* POST /api/agents/<id>/memories/summarize {}
|
||||
* GET /api/agents/<id>/memories/export
|
||||
* POST /api/agents/<id>/memories/import {data, mode:'merge'|'replace'}
|
||||
* PATCH /api/memories/<mid> {title?, content?}
|
||||
* DELETE /api/memories/<mid>
|
||||
* POST /api/memories/<mid>/pin {pinned:true|false}
|
||||
* GET/PUT /api/agents/<id>/emotion {preset, text}
|
||||
* GET /api/worldviews/<id>/memories
|
||||
*
|
||||
* ⚠️ 记忆对象是全 API 里唯一用 snake_case 的:author_agent / created_at / pinned(0|1)。
|
||||
* 别的全是 camelCase —— 拼错不会有报错,只会显示空白。
|
||||
*/
|
||||
import { S, api, agents, loadState } from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, openModal, confirmBox,
|
||||
fmtTime, injectStyles, spinner, emptyState,
|
||||
} from '../ui.js';
|
||||
|
||||
/** 情绪的五个档位(顺序就是界面顺序;内核不校验,前端自己限定) */
|
||||
const PRESETS = ['喜', '怒', '哀', '平常', '死亡'];
|
||||
const DEAD = '死亡';
|
||||
|
||||
const CSS = `
|
||||
.mem-page .mem-head-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.mem-page .mem-head-text { min-width: 0; }
|
||||
.mem-page .mem-head-text .page-title { display: flex; align-items: center; gap: 8px; }
|
||||
.mem-page .mem-loading {
|
||||
display: flex; align-items: center; justify-content: center; gap: 10px;
|
||||
padding: 72px 0; color: var(--text-secondary); font-size: 14px;
|
||||
}
|
||||
.mem-page .mem-banner {
|
||||
display: flex; align-items: flex-start; gap: 10px; margin-bottom: 12px;
|
||||
padding: 12px 14px; border: 1px solid var(--line-1); border-radius: var(--r-md);
|
||||
background: var(--bg-sidebar); font-size: 13px; line-height: 20px; color: var(--text-secondary);
|
||||
}
|
||||
.mem-page .mem-banner .icon { color: var(--text-tertiary); margin-top: 3px; }
|
||||
.mem-page .mem-banner-text { flex: 1; min-width: 0; }
|
||||
.mem-page .mem-banner .btn { flex: none; }
|
||||
.mem-page .mem-card-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.mem-page .mem-card-head .card-title .tag { font-weight: 500; }
|
||||
.mem-page .mem-main { flex: 1; min-width: 0; }
|
||||
.mem-page .mem-title { font-weight: 600; color: var(--text-primary); margin-bottom: 2px; }
|
||||
.mem-page .mem-author { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.mem-page .memory-actions { opacity: 1; align-items: center; }
|
||||
.mem-page .memory-actions .icon-btn { width: 28px; height: 28px; color: var(--text-tertiary); }
|
||||
.mem-page .memory-actions .icon-btn:hover { color: var(--text-primary); }
|
||||
.mem-page .memory-actions .icon-btn.on { color: var(--warning); }
|
||||
.mem-page .memory-actions .icon-btn.danger:hover { color: var(--danger); background: var(--danger-weak); }
|
||||
.mem-page .mem-emotion-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 10px; }
|
||||
.mem-page .mem-emotion-hint { margin-top: 8px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); }
|
||||
.mem-page .mem-dirty { color: var(--warning); font-size: 12px; }
|
||||
.mem-page .mem-form { display: flex; flex-direction: column; gap: 10px; padding: 4px 0 6px; }
|
||||
.mem-page .mem-field { display: flex; flex-direction: column; gap: 4px; font-size: 13px; color: var(--text-secondary); }
|
||||
.mem-page .mem-field .input, .mem-page .mem-field .textarea { color: var(--text-primary); font-family: inherit; }
|
||||
.mem-page .mem-form-err { min-height: 19px; font-size: 13px; line-height: 19px; color: var(--danger); }
|
||||
.mem-page button.option-row {
|
||||
width: 100%; background: transparent; color: inherit; font: inherit; text-align: left;
|
||||
}
|
||||
.mem-page button.option-row:hover { background: var(--bg-hover); }
|
||||
.mem-page .mem-note {
|
||||
display: flex; align-items: flex-start; gap: 8px; margin-top: 10px;
|
||||
font-size: 12px; line-height: 18px; color: var(--text-tertiary);
|
||||
}
|
||||
.mem-page .mem-note .icon { margin-top: 2px; flex: none; }
|
||||
.mem-page .mem-sum-grid { display: flex; align-items: center; gap: 14px; }
|
||||
.mem-page .mem-sum-num { font-size: 26px; font-weight: 600; line-height: 34px; }
|
||||
.mem-page .mem-sum-arrow { color: var(--text-tertiary); margin-top: 12px; }
|
||||
.mem-page .mem-error-line { display: flex; align-items: flex-start; gap: 8px; color: var(--danger); font-size: 14px; }
|
||||
.mem-page .mem-error-line .icon { margin-top: 3px; flex: none; }
|
||||
.mem-page .mem-world-row {
|
||||
display: flex; gap: 12px; padding: 12px 4px; align-items: flex-start;
|
||||
border-bottom: 1px solid var(--line-1);
|
||||
}
|
||||
.mem-page .mem-world-row:last-child { border-bottom: 0; }
|
||||
.mem-page .mem-empty-line { padding: 14px 4px; font-size: 13px; color: var(--text-secondary); }
|
||||
.mem-page .mem-foot { margin-top: 18px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); text-align: center; }
|
||||
`;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 小工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function agentById(id) {
|
||||
return agents().find((a) => a.id === id) || null;
|
||||
}
|
||||
|
||||
function worldviewName(wid) {
|
||||
const list = (S.state && S.state.worldviews) || [];
|
||||
const w = list.find((x) => x.id === wid);
|
||||
return (w && w.name) || '';
|
||||
}
|
||||
|
||||
function truncate(text, n) {
|
||||
const t = String(text || '').replace(/\s+/g, ' ').trim();
|
||||
return t.length > n ? `${t.slice(0, n)}…` : t;
|
||||
}
|
||||
|
||||
/** 按钮忙态:禁用 + 换文案;返回 restore()(连图标一起还原) */
|
||||
function setBusy(btn, label) {
|
||||
if (!btn) return () => {};
|
||||
const html = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.textContent = label;
|
||||
return () => { btn.innerHTML = html; btn.disabled = false; };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 页面 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export default function renderMemories(container, ctx) {
|
||||
const agentId = ctx.params.id || '';
|
||||
injectStyles('memories', CSS);
|
||||
|
||||
const st = {
|
||||
agent: agentById(agentId),
|
||||
data: null, // /memories 的整个 payload
|
||||
space: 'active', // active:当前空间 / own:绑定前的私有空间(只读)
|
||||
loading: true,
|
||||
error: '',
|
||||
emotion: null, // 已保存的情绪(服务端权威值)
|
||||
draft: { preset: '平常', text: '' },
|
||||
draftDirty: false,
|
||||
summarizing: false,
|
||||
world: null, // 世界观共享记忆
|
||||
worldLoading: false,
|
||||
worldError: '',
|
||||
};
|
||||
|
||||
const root = h('div.page-inner.mem-page');
|
||||
const fileInput = h('input', {
|
||||
type: 'file',
|
||||
accept: '.json,application/json',
|
||||
style: 'display:none',
|
||||
onchange: () => onImportFile(),
|
||||
});
|
||||
mount(container, root);
|
||||
ctx.setTitle('记忆');
|
||||
|
||||
/* ---------------- 数据 ---------------- */
|
||||
|
||||
function applyEmotion(emo, { force = false } = {}) {
|
||||
if (!emo || typeof emo !== 'object') return;
|
||||
st.emotion = { preset: emo.preset || '平常', text: emo.text || '' };
|
||||
if (force || !st.draftDirty) {
|
||||
st.draft = { preset: st.emotion.preset, text: st.emotion.text };
|
||||
st.draftDirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function load({ reset = false } = {}) {
|
||||
const scroller = container;
|
||||
const top = reset ? 0 : (scroller ? scroller.scrollTop : 0);
|
||||
if (!st.data) st.loading = true;
|
||||
st.error = '';
|
||||
render();
|
||||
const qs = st.space === 'own' ? '?space=own' : '';
|
||||
try {
|
||||
// 记忆列表里也带了一份 emotion,但 /emotion 才是权威(且保存后要能立刻刷新)
|
||||
const [memRes, emoRes] = await Promise.all([
|
||||
api.get(`/api/agents/${encodeURIComponent(agentId)}/memories${qs}`),
|
||||
api.get(`/api/agents/${encodeURIComponent(agentId)}/emotion`).catch(() => null),
|
||||
]);
|
||||
st.data = memRes;
|
||||
applyEmotion((emoRes && emoRes.emotion) || memRes.emotion);
|
||||
st.agent = agentById(agentId) || st.agent;
|
||||
// 条数/窗口是派生值,本地改完列表要自己重算,否则顶部数字会骗人
|
||||
refreshCounts();
|
||||
} catch (err) {
|
||||
st.error = err.message || String(err);
|
||||
} finally {
|
||||
st.loading = false;
|
||||
render();
|
||||
if (scroller) scroller.scrollTop = top;
|
||||
}
|
||||
if (st.agent && st.agent.worldviewId) loadWorld();
|
||||
}
|
||||
|
||||
async function loadWorld() {
|
||||
const wid = st.agent && st.agent.worldviewId;
|
||||
if (!wid) return;
|
||||
st.worldLoading = true;
|
||||
st.worldError = '';
|
||||
render();
|
||||
try {
|
||||
st.world = await api.get(`/api/worldviews/${encodeURIComponent(wid)}/memories`);
|
||||
} catch (err) {
|
||||
st.worldError = err.message || String(err);
|
||||
st.world = null;
|
||||
} finally {
|
||||
st.worldLoading = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
/** 置顶在前、时间升序(和内核的 `pinned DESC, created_at ASC` 对齐) */
|
||||
function resort() {
|
||||
if (!st.data || !Array.isArray(st.data.memories)) return;
|
||||
st.data.memories.sort((a, b) => (Number(b.pinned) || 0) - (Number(a.pinned) || 0)
|
||||
|| String(a.created_at || '').localeCompare(String(b.created_at || '')));
|
||||
}
|
||||
|
||||
/** pinnedCount / injected 是内核按窗口算的派生值,本地改完要跟着变 */
|
||||
function refreshCounts() {
|
||||
const d = st.data;
|
||||
if (!d || !Array.isArray(d.memories)) return;
|
||||
resort();
|
||||
d.pinnedCount = d.memories.filter((m) => Number(m.pinned)).length;
|
||||
const total = d.memories.length;
|
||||
const win = Number(d.window || 0);
|
||||
if (typeof d.window === 'number') {
|
||||
d.injected = win <= 0 || total <= win ? total : Math.max(win, d.pinnedCount);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 渲染 ---------------- */
|
||||
|
||||
function render() {
|
||||
clear(root);
|
||||
root.appendChild(renderHead());
|
||||
root.appendChild(fileInput);
|
||||
if (st.loading && !st.data) {
|
||||
root.appendChild(h('div.mem-loading', {}, spinner(20), '正在读取记忆…'));
|
||||
return;
|
||||
}
|
||||
if (st.error && !st.data) {
|
||||
root.appendChild(renderLoadError());
|
||||
return;
|
||||
}
|
||||
const banner = renderSpaceBanner();
|
||||
if (banner) root.appendChild(banner);
|
||||
root.appendChild(renderEmotionCard());
|
||||
root.appendChild(renderMemoryCard());
|
||||
if (st.agent && st.agent.worldviewId) root.appendChild(renderWorldCard());
|
||||
root.appendChild(renderFoot());
|
||||
}
|
||||
|
||||
function renderHead() {
|
||||
const agent = st.agent || { id: agentId, name: '未知智能体', avatar: 'custom' };
|
||||
const d = st.data;
|
||||
const total = d && Array.isArray(d.memories) ? d.memories.length : 0;
|
||||
const bits = [];
|
||||
if (d) {
|
||||
bits.push(`共 ${total} 条`);
|
||||
if (d.pinnedCount) bits.push(`置顶 ${d.pinnedCount} 条`);
|
||||
if (typeof d.injected === 'number' && d.injected !== total) bits.push(`这一轮带进 ${d.injected} 条`);
|
||||
} else {
|
||||
bits.push('记忆');
|
||||
}
|
||||
if (st.space === 'own') bits.push('绑定前的私有记忆 · 只读');
|
||||
else if (d && d.shared) bits.push('世界观共享空间');
|
||||
|
||||
const readonly = st.space === 'own';
|
||||
const actions = h('div.page-actions', {},
|
||||
h('button.btn', {
|
||||
title: '让 AI 把零散的记忆合并成更少的几条(置顶的原样保留)',
|
||||
disabled: st.summarizing || readonly || !total,
|
||||
onclick: (e) => runSummarize(e.currentTarget),
|
||||
}, st.summarizing ? spinner(14) : icon('sparkles', 15), st.summarizing ? '整理中…' : 'AI 整理'),
|
||||
h('button.btn', {
|
||||
title: '从 JSON 文件导入记忆',
|
||||
disabled: readonly || st.summarizing,
|
||||
onclick: () => fileInput.click(),
|
||||
}, icon('download-cloud', 15), '导入'),
|
||||
h('button.btn', {
|
||||
title: '把记忆导出成 JSON',
|
||||
disabled: st.summarizing,
|
||||
onclick: (e) => exportMemories(e.currentTarget),
|
||||
}, icon('download', 15), '导出'));
|
||||
|
||||
return h('div.page-head', {},
|
||||
h('div.page-head-left.mem-head-left', {},
|
||||
h('button.icon-btn', { title: '返回智能体', onclick: goBack }, icon('arrow-left', 18)),
|
||||
avatar(agent, 40),
|
||||
h('div.mem-head-text', {},
|
||||
h('div.page-title', agent.name || '未知智能体'),
|
||||
h('div.page-sub', bits.join(' · ')))),
|
||||
actions);
|
||||
}
|
||||
|
||||
function renderLoadError() {
|
||||
return h('div.card', {},
|
||||
h('div.card-title', {}, icon('alert-triangle', 18), '记忆读不出来'),
|
||||
h('div.card-desc', {}, st.error || '未知错误'),
|
||||
h('div.card-actions', {},
|
||||
h('button.btn.primary', { onclick: () => { st.data = null; load(); } }, '重试'),
|
||||
h('button.btn', { onclick: goBack }, '返回')));
|
||||
}
|
||||
|
||||
/** 空间提示条:只在"说清楚会不会误解"的两种情况下出现 */
|
||||
function renderSpaceBanner() {
|
||||
const d = st.data;
|
||||
if (!d) return null;
|
||||
if (st.space === 'own') {
|
||||
return h('div.mem-banner', {},
|
||||
icon('info', 16),
|
||||
h('div.mem-banner-text', {},
|
||||
'正在看绑定世界观之前攒下的私有记忆(只读)。这些记忆一条都没丢,但它们不在当前的共享空间里 —— '
|
||||
+ '新增/编辑永远写进当前空间,所以要改请先解绑世界观。'),
|
||||
h('button.btn.sm', {
|
||||
onclick: () => { st.space = 'active'; st.data = null; load({ reset: true }); },
|
||||
}, '回到共享记忆'));
|
||||
}
|
||||
if (!d.shared) return null;
|
||||
const name = worldviewName(d.worldviewId) || '世界观';
|
||||
return h('div.mem-banner', {},
|
||||
icon('globe', 16),
|
||||
h('div.mem-banner-text', {},
|
||||
`这个智能体绑定了「${name}」:记忆和同一个世界观的智能体共用一份,`
|
||||
+ 'AI 只能改自己写的那几条,你(用户)可以改任何一条。'),
|
||||
d.ownCount ? h('button.btn.sm', {
|
||||
onclick: () => { st.space = 'own'; st.data = null; load({ reset: true }); },
|
||||
}, `绑定前的私有记忆(${d.ownCount} 条)`) : null);
|
||||
}
|
||||
|
||||
/* ---------------- 情绪 ---------------- */
|
||||
|
||||
function renderEmotionCard() {
|
||||
const saved = st.emotion || { preset: '平常', text: '' };
|
||||
const draft = st.draft;
|
||||
const dead = draft.preset === DEAD;
|
||||
|
||||
const tabs = h('div.pill-tabs');
|
||||
for (const p of PRESETS) {
|
||||
const b = h(`button.pill-tab${draft.preset === p ? '.active' : ''}`, {
|
||||
title: p === DEAD ? '死亡:不能对话(改回别的档就是复活)' : `情绪档位:${p}`,
|
||||
onclick: () => pickPreset(p),
|
||||
}, p);
|
||||
b.dataset.preset = p;
|
||||
tabs.appendChild(b);
|
||||
}
|
||||
|
||||
const ta = h('textarea.input.textarea', {
|
||||
rows: 2,
|
||||
maxlength: 200,
|
||||
placeholder: '用一句话写写它现在的心情 / 状态(只管扮演质感,不改变系统行为)',
|
||||
oninput: () => { st.draft.text = ta.value; st.draftDirty = true; syncDirty(); },
|
||||
});
|
||||
ta.value = draft.text;
|
||||
|
||||
const hint = h('div.mem-emotion-hint');
|
||||
const syncHint = () => {
|
||||
clear(hint);
|
||||
hint.appendChild(h('div', {}, dead
|
||||
? '「死亡」档下不能对话(聊天输入条会整条禁用),立绘也走死亡档。把档位改回其它任何一个它就复活了 —— 用户手动改回是兜底主权。'
|
||||
: '情绪永远不会共享,即使绑了这个世界观;它只影响立绘档位和扮演质感。'));
|
||||
hint.appendChild(h('div', {}, '情绪文本最多 200 字,内核会截断。'));
|
||||
};
|
||||
syncHint();
|
||||
|
||||
const dirty = h('span.mem-dirty');
|
||||
const syncDirty = () => {
|
||||
const changed = draft.preset !== saved.preset || draft.text !== saved.text;
|
||||
dirty.textContent = changed ? '有未保存的改动' : '';
|
||||
};
|
||||
syncDirty();
|
||||
|
||||
function pickPreset(p) {
|
||||
st.draft.preset = p;
|
||||
st.draftDirty = true;
|
||||
for (const b of tabs.children) b.classList.toggle('active', b.dataset.preset === p);
|
||||
for (const b of tabs.children) b.setAttribute('aria-pressed', b.dataset.preset === p ? 'true' : 'false');
|
||||
syncHint();
|
||||
syncDirty();
|
||||
}
|
||||
|
||||
const save = h('button.btn.primary.sm', {
|
||||
disabled: st.space === 'own',
|
||||
onclick: (e) => saveEmotion(e.currentTarget),
|
||||
}, '保存情绪');
|
||||
|
||||
const tags = h('div.mem-emotion-row', {},
|
||||
h(`span.tag${dead ? '.red' : '.green'}`, dead ? '已死亡 · 不能对话' : '存活'),
|
||||
h('span.tag', `当前档:${saved.preset}`),
|
||||
dirty,
|
||||
h('span', { style: 'flex:1' }),
|
||||
save);
|
||||
|
||||
return h('div.card', {},
|
||||
h('div.card-title', {}, icon('heart', 18), '情绪',
|
||||
h('span.tag', st.space === 'own' ? '只读' : '私有')),
|
||||
h('div.card-desc', {}, '两个字段:档位(驱动系统行为)和情绪文本(只管扮演质感)。'),
|
||||
h('div.card-body', {},
|
||||
tabs,
|
||||
tags,
|
||||
h('div', { style: 'margin-top:10px' }, ta),
|
||||
hint));
|
||||
}
|
||||
|
||||
async function saveEmotion(btn) {
|
||||
const restore = setBusy(btn, '保存中…');
|
||||
try {
|
||||
const res = await api.put(`/api/agents/${encodeURIComponent(agentId)}/emotion`, {
|
||||
preset: st.draft.preset,
|
||||
text: st.draft.text,
|
||||
});
|
||||
applyEmotion(res.emotion || st.draft, { force: true });
|
||||
toast('情绪已保存', { type: 'success' });
|
||||
render();
|
||||
// 立绘是按情绪算出来的派生值,别的地方要跟上
|
||||
loadState({ silent: true }).catch(() => {});
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
restore();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 记忆列表 ---------------- */
|
||||
|
||||
function renderMemoryCard() {
|
||||
const d = st.data;
|
||||
const items = (d && Array.isArray(d.memories)) ? d.memories : [];
|
||||
const readonly = st.space === 'own';
|
||||
|
||||
const head = h('div.mem-card-head', {},
|
||||
h('div.card-title', {},
|
||||
icon('brain', 18), '记忆',
|
||||
h('span.tag', String(items.length))),
|
||||
h('div', { style: 'display:flex;gap:8px' },
|
||||
h('button.btn.sm', {
|
||||
disabled: readonly || st.summarizing,
|
||||
title: '手动加一条(你自己写的记忆,AI 也会读到)',
|
||||
onclick: openAdd,
|
||||
}, icon('plus', 14), '加一条')));
|
||||
|
||||
const list = h('div.list');
|
||||
if (!items.length) {
|
||||
list.appendChild(emptyState('brain', '还没有记忆',
|
||||
readonly
|
||||
? '绑定世界观之前这里是空的 —— 也就是说那时候它还没记下什么。'
|
||||
: 'AI 在对话里觉得值得记住的事会自动出现在这里;你也可以点右上角「加一条」手动写。',
|
||||
readonly ? null : h('div', { style: 'margin-top:14px' },
|
||||
h('button.btn.primary', { onclick: openAdd }, icon('plus', 15), '手动加一条'))));
|
||||
} else {
|
||||
for (const m of items) list.appendChild(memoryRow(m, readonly));
|
||||
}
|
||||
|
||||
const card = h('div.card', {}, head,
|
||||
h('div.card-desc', {}, '置顶 = 「必须保留」:AI 整理时不参与合并、原样保留,AI 自己也改不动;'
|
||||
+ '它不占记忆注入窗口,每轮都会带进提示词。'));
|
||||
card.appendChild(h('div.card-body', {}, list));
|
||||
return card;
|
||||
}
|
||||
|
||||
function memoryRow(m, readonly) {
|
||||
const pinned = !!Number(m.pinned);
|
||||
const who = String(m.author_agent || '').trim();
|
||||
const mine = !who;
|
||||
const self = who === agentId;
|
||||
const author = mine
|
||||
? { text: '用户手写', icon: 'user' }
|
||||
: self
|
||||
? { text: 'AI 自己记的', icon: 'bot' }
|
||||
: { text: `${(agentById(who) || {}).name || who} 写的`, icon: 'bot' };
|
||||
|
||||
const content = h('div.memory-content');
|
||||
if (m.title) content.appendChild(h('div.mem-title', m.title));
|
||||
content.appendChild(h('div', { style: 'color:var(--text-secondary)' }, m.content || (m.title ? '' : '(空)')));
|
||||
|
||||
const meta = h('div.memory-meta', {},
|
||||
h('span.mem-author', {}, icon(author.icon, 12), author.text),
|
||||
h('span', '·'),
|
||||
h('span', { title: m.created_at || '' }, fmtTime(m.created_at) || '时间未知'),
|
||||
pinned ? h('span.tag.orange', {}, icon('pin', 11), '置顶 · 必须保留') : null,
|
||||
m.scope && String(m.scope).startsWith('world:') ? h('span.tag.blue', '共享空间') : null);
|
||||
|
||||
const actions = h('div.memory-actions', {},
|
||||
h(`button.icon-btn.sm${pinned ? '.on' : ''}`, {
|
||||
title: pinned ? '取消置顶(取消后 AI 整理时可能被合并)' : '置顶 = 必须保留,AI 改不动',
|
||||
disabled: readonly,
|
||||
onclick: () => togglePin(m),
|
||||
}, icon('pin', 15)),
|
||||
h('button.icon-btn.sm', { title: '编辑', disabled: readonly, onclick: () => openEdit(m) }, icon('pencil', 15)),
|
||||
h('button.icon-btn.sm.danger', { title: '删除', disabled: readonly, onclick: () => removeMemory(m) }, icon('trash', 15)));
|
||||
|
||||
return h(`div.memory-row${pinned ? '.pinned' : ''}`, {},
|
||||
h('div.mem-main', {}, content, meta),
|
||||
readonly ? null : actions);
|
||||
}
|
||||
|
||||
async function togglePin(m) {
|
||||
const want = !Number(m.pinned);
|
||||
try {
|
||||
const res = await api.post(`/api/memories/${encodeURIComponent(m.id)}/pin`, { pinned: want });
|
||||
// 这条路由回的是 {"ok": true|false}(找不到那条记忆时 false,不报错)
|
||||
if (res && res.ok === false) throw new Error('内核没有改这条记忆的置顶状态');
|
||||
m.pinned = want ? 1 : 0;
|
||||
refreshCounts();
|
||||
render();
|
||||
toast(want ? '已置顶:AI 整理时原样保留,AI 自己也改不动' : '已取消置顶', { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 加 / 改 ---------------- */
|
||||
|
||||
function memoryForm({ title = '', content = '' } = {}) {
|
||||
const titleInput = h('input.input', { placeholder: '标题(可选;合并导入时按标题去重)' });
|
||||
titleInput.value = title;
|
||||
const contentInput = h('textarea.input.textarea', { rows: 6, placeholder: '要记住什么?越具体越好 —— 名字、数字、日期都写上' });
|
||||
contentInput.value = content;
|
||||
const err = h('div.mem-form-err');
|
||||
const body = h('div.mem-form', {},
|
||||
h('label.mem-field', {}, '标题', titleInput),
|
||||
h('label.mem-field', {}, '内容', contentInput),
|
||||
err);
|
||||
return { body, titleInput, contentInput, err };
|
||||
}
|
||||
|
||||
function openAdd() {
|
||||
const agentName = (st.agent && st.agent.name) || '它';
|
||||
const f = memoryForm();
|
||||
const modal = openModal({
|
||||
title: `给「${agentName}」加一条记忆`,
|
||||
width: 560,
|
||||
body: f.body,
|
||||
footer: h('div.modal-actions', {},
|
||||
h('button.btn', { onclick: () => modal.close() }, '取消'),
|
||||
h('button.btn.primary', { onclick: (e) => submit(e.currentTarget) }, '保存')),
|
||||
});
|
||||
setTimeout(() => f.titleInput.focus(), 30);
|
||||
|
||||
async function submit(btn) {
|
||||
const title = f.titleInput.value.trim();
|
||||
const content = f.contentInput.value.trim();
|
||||
f.err.textContent = '';
|
||||
if (!title && !content) {
|
||||
f.err.textContent = '标题和内容不能都是空的';
|
||||
f.titleInput.focus();
|
||||
return;
|
||||
}
|
||||
const restore = setBusy(btn, '保存中…');
|
||||
try {
|
||||
// author_agent 不传 = 用户手写(空串),界面会署名「用户手写」
|
||||
const res = await api.post(`/api/agents/${encodeURIComponent(agentId)}/memories`, { title, content });
|
||||
if (res && res.memory && st.data) {
|
||||
st.data.memories.push(res.memory);
|
||||
refreshCounts();
|
||||
render();
|
||||
} else {
|
||||
await load();
|
||||
}
|
||||
modal.close();
|
||||
toast('已加一条记忆', { type: 'success' });
|
||||
} catch (err) {
|
||||
f.err.textContent = err.message;
|
||||
restore();
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openEdit(m) {
|
||||
const f = memoryForm({ title: m.title || '', content: m.content || '' });
|
||||
const modal = openModal({
|
||||
title: '编辑这条记忆',
|
||||
width: 560,
|
||||
body: f.body,
|
||||
footer: h('div.modal-actions', {},
|
||||
h('button.btn', { onclick: () => modal.close() }, '取消'),
|
||||
h('button.btn.primary', { onclick: (e) => submit(e.currentTarget) }, '保存')),
|
||||
});
|
||||
setTimeout(() => f.contentInput.focus(), 30);
|
||||
|
||||
async function submit(btn) {
|
||||
const title = f.titleInput.value.trim();
|
||||
const content = f.contentInput.value.trim();
|
||||
f.err.textContent = '';
|
||||
if (!title && !content) {
|
||||
f.err.textContent = '标题和内容不能都是空的';
|
||||
return;
|
||||
}
|
||||
const restore = setBusy(btn, '保存中…');
|
||||
try {
|
||||
const res = await api.patch(`/api/memories/${encodeURIComponent(m.id)}`, { title, content });
|
||||
if (res && res.memory) {
|
||||
m.title = res.memory.title;
|
||||
m.content = res.memory.content;
|
||||
refreshCounts();
|
||||
render();
|
||||
} else {
|
||||
await load();
|
||||
}
|
||||
modal.close();
|
||||
toast('已保存', { type: 'success' });
|
||||
} catch (err) {
|
||||
f.err.textContent = err.message;
|
||||
restore();
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMemory(m) {
|
||||
const ok = await confirmBox({
|
||||
title: '删除这条记忆?',
|
||||
message: `「${m.title || truncate(m.content, 24) || '这条记忆'}」会被永久删除,AI 以后就不记得了。`,
|
||||
hint: '置顶状态也会一起没了;想反悔只能从导出的 JSON 里导回来。',
|
||||
danger: true,
|
||||
okText: '删除',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.del(`/api/memories/${encodeURIComponent(m.id)}`);
|
||||
if (st.data) {
|
||||
st.data.memories = st.data.memories.filter((x) => x.id !== m.id);
|
||||
refreshCounts();
|
||||
render();
|
||||
}
|
||||
toast('已删除', { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- AI 整理 ---------------- */
|
||||
|
||||
async function runSummarize(btn) {
|
||||
if (st.summarizing) return;
|
||||
st.summarizing = true;
|
||||
render();
|
||||
try {
|
||||
const res = await api.post(`/api/agents/${encodeURIComponent(agentId)}/memories/summarize`, {});
|
||||
if (res && res.summarized) {
|
||||
showSummarizeResult(res);
|
||||
await load();
|
||||
} else {
|
||||
const modal = openModal({
|
||||
title: '这次不用整理',
|
||||
width: 460,
|
||||
body: h('div.mem-form', {},
|
||||
h('div', {}, (res && res.reason) || '还没有记忆可以整理。'),
|
||||
h('div.mem-note', {}, icon('info', 14),
|
||||
'先聊几句让它记点东西,或者手动加几条再回来。置顶的条目本来就不参与合并。')),
|
||||
footer: h('div.modal-actions', {}, h('button.btn.primary', { onclick: () => modal.close() }, '好')),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
// 整理要跑一次独立的模型调用:没配 Key、上游报错、模型返回的不是 JSON 数组都会失败。
|
||||
// 失败时内核**不会写回**,记忆还是原样 —— 这句话必须给用户看,否则他不敢再点。
|
||||
const modal = openModal({
|
||||
title: 'AI 整理失败',
|
||||
width: 520,
|
||||
body: h('div.mem-form', {},
|
||||
h('div.mem-error-line', {}, icon('alert-triangle', 16), h('div', {}, err.message || '未知错误')),
|
||||
h('div.mem-note', {}, icon('shield', 14),
|
||||
'失败时内核不会写回任何东西,记忆还是原样。常见原因:没配 API Key、上游报错、模型返回的不是 JSON 列表。'),
|
||||
h('div.mem-note', {}, icon('info', 14),
|
||||
'整理不受 Token 限额约束(额度用完也能整理),但消耗的 Token 会记进这个智能体的用量。')),
|
||||
footer: h('div.modal-actions', {}, h('button.btn.primary', { onclick: () => modal.close() }, '知道了')),
|
||||
});
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
st.summarizing = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
function showSummarizeResult(res) {
|
||||
const modal = openModal({
|
||||
title: '整理完成',
|
||||
width: 480,
|
||||
body: h('div.mem-form', {},
|
||||
h('div.mem-sum-grid', {},
|
||||
h('div', {}, h('div.stat-label', '整理前'), h('div.mem-sum-num', String(res.before ?? '-'))),
|
||||
h('span.mem-sum-arrow', {}, icon('arrow-right', 18)),
|
||||
h('div', {}, h('div.stat-label', '整理后'), h('div.mem-sum-num', String(res.after ?? '-')))),
|
||||
h('div.mem-note', {}, icon('pin', 14),
|
||||
res.keptPinned
|
||||
? `保留了 ${res.keptPinned} 条置顶记忆(置顶 = 必须保留,不参与合并)`
|
||||
: '这次没有置顶的条目要保护 —— 想留住某条,先去标个置顶再整理。'),
|
||||
h('div.mem-note', {}, icon('info', 14), '整理消耗的 Token 已记进这个智能体的用量。')),
|
||||
footer: h('div.modal-actions', {}, h('button.btn.primary', { onclick: () => modal.close() }, '好')),
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 导入 ---------------- */
|
||||
|
||||
async function exportMemories(btn) {
|
||||
const restore = setBusy(btn, '导出中…');
|
||||
try {
|
||||
const res = await api.get(`/api/agents/${encodeURIComponent(agentId)}/memories/export`);
|
||||
const payload = {
|
||||
type: res.type || 'agent-memory',
|
||||
version: res.version || 1,
|
||||
name: res.name || (st.agent && st.agent.name) || '',
|
||||
smartMemory: Array.isArray(res.smartMemory) ? res.smartMemory : [],
|
||||
Emotion: res.Emotion || { preset: '平常', text: '' },
|
||||
};
|
||||
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const safe = String(payload.name || 'agent').replace(/[\\/:*?"<>|\s]+/g, '_');
|
||||
const a = h('a', { href: url, download: `${safe}-记忆-${new Date().toISOString().slice(0, 10)}.json` });
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 3000);
|
||||
toast(`已导出 ${payload.smartMemory.length} 条记忆`, { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
}
|
||||
|
||||
async function onImportFile() {
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
fileInput.value = '';
|
||||
if (!file) return;
|
||||
let data = null;
|
||||
try {
|
||||
const text = await file.text();
|
||||
data = JSON.parse(text);
|
||||
} catch {
|
||||
toast('这个文件不是合法的 JSON', { type: 'error' });
|
||||
return;
|
||||
}
|
||||
const items = data && Array.isArray(data.smartMemory) ? data.smartMemory : null;
|
||||
if (!items) {
|
||||
toast('这不是一个记忆文件(缺少 smartMemory 字段)', { type: 'error' });
|
||||
return;
|
||||
}
|
||||
openImportModal(file.name, items, data);
|
||||
}
|
||||
|
||||
function openImportModal(fileName, items, data) {
|
||||
const modal = openModal({
|
||||
title: '导入记忆',
|
||||
width: 540,
|
||||
body: h('div.mem-form', {},
|
||||
h('div.kv', {}, h('span.k', '文件'), h('span.v', fileName)),
|
||||
h('div.kv', {}, h('span.k', '里面的记忆'), h('span.v', `${items.length} 条`)),
|
||||
h('div', { style: 'margin-top:6px;font-size:13px;color:var(--text-secondary)' }, '怎么合进去?'),
|
||||
h('button.option-row', { onclick: () => doImport('merge') },
|
||||
icon('layers', 18),
|
||||
h('div', {},
|
||||
h('div.option-title', '合并(推荐)'),
|
||||
h('div.option-desc', '按标题去重:标题相同的跳过并保留现有的,只补进来的新条目。'))),
|
||||
h('button.option-row', { onclick: () => doImport('replace') },
|
||||
icon('refresh', 18),
|
||||
h('div', {},
|
||||
h('div.option-title', '覆盖'),
|
||||
h('div.option-desc', '先清空当前空间的记忆再写进去,连情绪一起换掉 —— 不可恢复。')))),
|
||||
footer: h('div.modal-actions', {}, h('button.btn', { onclick: () => modal.close() }, '取消')),
|
||||
});
|
||||
|
||||
async function doImport(mode) {
|
||||
modal.close();
|
||||
if (mode === 'replace') {
|
||||
const ok = await confirmBox({
|
||||
title: '覆盖当前记忆?',
|
||||
message: `当前空间的 ${(st.data && st.data.memories.length) || 0} 条记忆会被清空,换成文件里的 ${items.length} 条。`,
|
||||
hint: '不可恢复。想留一手就先「导出」一份。',
|
||||
danger: true,
|
||||
okText: '覆盖',
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
try {
|
||||
const res = await api.post(`/api/agents/${encodeURIComponent(agentId)}/memories/import`, { data, mode });
|
||||
const detail = mode === 'replace'
|
||||
? `已覆盖:现在 ${res.after} 条`
|
||||
: `已合并:新增 ${res.added} 条,跳过 ${res.skipped} 条(标题重复)`;
|
||||
toast(detail, { type: 'success', duration: 3600 });
|
||||
await load({ reset: true });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 世界观共享记忆(只读) ---------------- */
|
||||
|
||||
function renderWorldCard() {
|
||||
const wid = st.agent.worldviewId;
|
||||
const name = (st.world && st.world.name) || worldviewName(wid) || '世界观';
|
||||
const items = (st.world && Array.isArray(st.world.memories)) ? st.world.memories : [];
|
||||
|
||||
const body = h('div');
|
||||
if (st.worldLoading && !st.world) {
|
||||
body.appendChild(h('div.mem-loading', {}, spinner(18), '正在读取共享记忆…'));
|
||||
} else if (st.worldError) {
|
||||
body.appendChild(h('div.mem-banner', {},
|
||||
icon('alert-triangle', 16),
|
||||
h('div.mem-banner-text', {}, `共享记忆读不出来:${st.worldError}`),
|
||||
h('button.btn.sm', { onclick: loadWorld }, '重试')));
|
||||
} else if (!items.length) {
|
||||
body.appendChild(h('div.mem-empty-line', {}, '这个世界观里还没有共享记忆。'));
|
||||
} else {
|
||||
for (const m of items) body.appendChild(worldRow(m, name));
|
||||
}
|
||||
|
||||
return h('div.card', {},
|
||||
h('div.mem-card-head', {},
|
||||
h('div.card-title', {}, icon('globe', 18), '世界观共享记忆',
|
||||
h('span.tag', String(items.length)),
|
||||
h('span.tag.blue', '只读')),
|
||||
h('button.btn.sm', { title: '重新读一次', onclick: loadWorld }, icon('refresh', 14), '刷新')),
|
||||
h('div.card-desc', {},
|
||||
`绑定同一世界观(「${name}」)的智能体共用这份记忆。这里是全景视角,所以没有"我的"可言 —— `
|
||||
+ '增删改请从各自智能体的记忆页做(AI 只能改自己写的,你可以改任何一条)。'),
|
||||
h('div.card-body', {}, body));
|
||||
}
|
||||
|
||||
function worldRow(m, name) {
|
||||
const who = String(m.authorName || '').trim()
|
||||
|| (String(m.author_agent || '').trim()
|
||||
? ((agentById(m.author_agent) || {}).name || m.author_agent)
|
||||
: '');
|
||||
const content = h('div.memory-content');
|
||||
if (m.title) content.appendChild(h('div.mem-title', m.title));
|
||||
content.appendChild(h('div', { style: 'color:var(--text-secondary)' }, m.content || ''));
|
||||
return h('div.mem-world-row', {},
|
||||
h('div.mem-main', {},
|
||||
content,
|
||||
h('div.memory-meta', {},
|
||||
h('span.mem-author', {}, icon(who ? 'bot' : 'user', 12), who ? `${who} 写的` : '用户手写'),
|
||||
h('span', '·'),
|
||||
h('span', { title: m.created_at || '' }, fmtTime(m.created_at) || '时间未知'),
|
||||
Number(m.pinned) ? h('span.tag.orange', {}, icon('pin', 11), '置顶') : null)),
|
||||
h('span.tag', { title: `增删改请到「${name}」下任意智能体的记忆页` }, '共享'));
|
||||
}
|
||||
|
||||
/* ---------------- 页脚 & 返回 ---------------- */
|
||||
|
||||
function renderFoot() {
|
||||
const d = st.data || {};
|
||||
const bits = [];
|
||||
if (typeof d.window === 'number') {
|
||||
bits.push(d.window > 0 ? `注入窗口 ${d.window} 条` : '注入窗口不限条数');
|
||||
bits.push('置顶不占窗口');
|
||||
}
|
||||
bits.push('导出/导入用的是 JSON,不含作者身份(导入后归当前智能体)');
|
||||
return h('div.mem-foot', {}, bits.join(' · '));
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
ctx.navigate(st.agent ? `agents/${agentId}` : 'agents');
|
||||
}
|
||||
|
||||
/* ---------------- 启动 ---------------- */
|
||||
|
||||
if (!agentId) {
|
||||
root.appendChild(h('div.card', {},
|
||||
h('div.card-title', {}, icon('alert-triangle', 18), '地址里没有智能体 id'),
|
||||
h('div.card-actions', {}, h('button.btn.primary', { onclick: () => ctx.navigate('agents') }, '去智能体列表'))));
|
||||
return undefined;
|
||||
}
|
||||
|
||||
render();
|
||||
load();
|
||||
|
||||
return () => { /* 没有全局监听要摘:所有请求都是本页发起的 */ };
|
||||
}
|
||||
208
web/js/pages/notes.js
Normal file
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* 笔记页(#/notes)
|
||||
*
|
||||
* 接口(docs/kernel-api-misc.md §4):
|
||||
* GET /api/notes → {notes:[{file,title,bytes,at,preview}]}
|
||||
* GET /api/notes/<encodeURIComponent(file)> → {file,title,at,content,bytes}
|
||||
* DELETE /api/notes/<encodeURIComponent(file)> → {ok:true} / 404 {ok:false}
|
||||
*
|
||||
* ★ 内核**没有写接口**(只有 AI 的 notes 工具能写,见 tools/notes.py),
|
||||
* 所以这页只做「看 / 删」:放一个点了必然失败的新建按钮更糟。
|
||||
* ★ 文件名就是 URL 的一段(里面常有中文),必须 encodeURIComponent,
|
||||
* 否则带 # / % 的名字会请求到别的地方去。
|
||||
*/
|
||||
import { api } from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, toast, openModal, confirmBox, spinner,
|
||||
fmtTime, fmtBytes, renderMarkdown, injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
const CSS = `
|
||||
.notes-card { padding: 8px 20px 12px; }
|
||||
.notes-count { font-size: 13px; color: var(--text-tertiary); }
|
||||
|
||||
.note-row { gap: 14px; padding: 12px 10px; margin: 0 -10px; border-radius: 10px; }
|
||||
.note-row:last-child { border-bottom: 0; }
|
||||
.note-main { flex: 1; min-width: 0; }
|
||||
.note-name {
|
||||
font-size: 14px; font-weight: 500; line-height: 22px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.note-preview {
|
||||
margin-top: 2px; font-size: 12.5px; line-height: 18px; color: var(--text-secondary);
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
|
||||
}
|
||||
.note-meta {
|
||||
flex: none; display: flex; flex-direction: column; align-items: flex-end; gap: 2px;
|
||||
font-size: 12px; color: var(--text-tertiary); white-space: nowrap; text-align: right;
|
||||
}
|
||||
.note-actions { flex: none; display: flex; align-items: center; gap: 2px; opacity: 0; transition: opacity .12s; }
|
||||
.note-row:hover .note-actions, .note-row:focus-within .note-actions { opacity: 1; }
|
||||
@media (hover: none) { .note-actions { opacity: 1; } }
|
||||
|
||||
.note-view { max-height: 60vh; overflow: auto; padding-right: 4px; }
|
||||
.note-view .markdown { font-size: 14.5px; line-height: 24px; }
|
||||
.note-view-meta {
|
||||
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
|
||||
padding: 2px 0 12px; margin-bottom: 12px; border-bottom: 1px solid var(--line-1);
|
||||
font-size: 12px; color: var(--text-tertiary);
|
||||
}
|
||||
.note-view-meta .mono { font-family: var(--font-mono); font-size: 11.5px; }
|
||||
|
||||
.loading-line, .error-line {
|
||||
display: flex; align-items: center; gap: 10px; justify-content: center;
|
||||
padding: 36px 16px; font-size: 13px; color: var(--text-secondary);
|
||||
}
|
||||
.error-line { flex-direction: column; gap: 12px; }
|
||||
.error-line .err-text { color: var(--danger); font-size: 13px; line-height: 20px; text-align: center; }
|
||||
`;
|
||||
|
||||
function fileUrl(file) {
|
||||
return `/api/notes/${encodeURIComponent(file)}`;
|
||||
}
|
||||
|
||||
export default function renderNotes(container, ctx) {
|
||||
injectStyles('notes-page', CSS);
|
||||
|
||||
const st = { notes: [], loading: true, error: null };
|
||||
const listBox = h('div.notes-card-host');
|
||||
|
||||
const refreshBtn = h('button.btn.sm', { title: '重新读取笔记列表' }, icon('refresh', 15), h('span', '刷新'));
|
||||
const head = h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', '笔记'),
|
||||
h('div.page-sub', 'AI 用 notes 工具写下的笔记会出现在这里,也可以让 AI 记点什么。')),
|
||||
h('div.page-actions', {}, refreshBtn));
|
||||
|
||||
const page = h('div.page-inner', {}, head, h('div.card.notes-card', {}, listBox));
|
||||
mount(container, page);
|
||||
ctx.setTitle('笔记');
|
||||
|
||||
refreshBtn.addEventListener('click', () => load({ manual: true }));
|
||||
|
||||
function renderLoading() {
|
||||
clear(listBox);
|
||||
listBox.appendChild(h('div.loading-line', {}, spinner(15), '正在读取笔记…'));
|
||||
}
|
||||
|
||||
function renderError(err) {
|
||||
clear(listBox);
|
||||
listBox.appendChild(h('div.error-line', {},
|
||||
h('div.err-text', String((err && err.message) || err)),
|
||||
h('button.btn.sm', { onclick: () => load({ manual: true }) }, '重试')));
|
||||
}
|
||||
|
||||
function renderEmpty() {
|
||||
clear(listBox);
|
||||
listBox.appendChild(h('div.empty-state', {},
|
||||
h('div.empty-state-icon', {}, icon('notebook', 26)),
|
||||
h('div.empty-state-title', '还没有笔记'),
|
||||
h('div.empty-state-desc', 'AI 用 notes 工具写下的笔记会出现在这里,也可以让 AI 记点什么。')));
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
clear(listBox);
|
||||
if (st.loading) { renderLoading(); return; }
|
||||
if (st.error) { renderError(st.error); return; }
|
||||
if (!st.notes.length) { renderEmpty(); return; }
|
||||
|
||||
listBox.appendChild(h('div.notes-count', { style: 'padding:6px 0 2px' },
|
||||
`${st.notes.length} 条笔记 · 点一行看全文,右侧垃圾桶删除`));
|
||||
|
||||
for (const note of st.notes) {
|
||||
const title = note.title || note.file || '未命名笔记';
|
||||
const row = h('div.note-row', {
|
||||
role: 'button',
|
||||
tabindex: '0',
|
||||
title: '点开看全文',
|
||||
onclick: () => openNote(note),
|
||||
onkeydown: (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openNote(note); }
|
||||
},
|
||||
},
|
||||
h('div.note-main', {},
|
||||
h('div.note-name', { title }, title),
|
||||
note.preview ? h('div.note-preview', note.preview) : null),
|
||||
h('div.note-meta', {},
|
||||
h('span', fmtTime(note.at) || note.at || '时间未知'),
|
||||
note.bytes != null ? h('span', fmtBytes(note.bytes)) : null),
|
||||
h('div.note-actions', {},
|
||||
h('button.icon-btn.sm', {
|
||||
title: '删除这条笔记',
|
||||
onclick: (e) => { e.stopPropagation(); deleteNote(note); },
|
||||
}, icon('trash', 15))));
|
||||
listBox.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
async function openNote(note) {
|
||||
const modal = openModal({
|
||||
title: note.title || '笔记',
|
||||
width: 760,
|
||||
body: h('div', {}, h('div.loading-line', {}, spinner(15), '正在读取全文…')),
|
||||
});
|
||||
const body = modal.body;
|
||||
try {
|
||||
const data = await api.get(fileUrl(note.file));
|
||||
clear(body);
|
||||
body.appendChild(h('div.note-view-meta', {},
|
||||
h('span', fmtTime(data.at) || data.at || '时间未知'),
|
||||
data.bytes != null ? h('span', fmtBytes(data.bytes)) : null,
|
||||
h('span', '·'),
|
||||
h('span.mono', data.file || note.file)));
|
||||
const view = h('div.note-view');
|
||||
renderMarkdown(view, data.content || '(这条笔记是空的)');
|
||||
body.appendChild(view);
|
||||
} catch (err) {
|
||||
clear(body);
|
||||
body.appendChild(h('div.error-line', {},
|
||||
h('div.err-text', String(err.message || err)),
|
||||
h('button.btn.sm', { onclick: () => { modal.close(); openNote(note); } }, '重试')));
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteNote(note) {
|
||||
const title = note.title || note.file || '这条笔记';
|
||||
const ok = await confirmBox({
|
||||
title: '删除笔记?',
|
||||
message: `「${title}」会被永久删除,不可恢复。`,
|
||||
hint: '如果只是想让它别再出现,也可以让 AI 另记一条新的。',
|
||||
danger: true,
|
||||
okText: '删除',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.del(fileUrl(note.file));
|
||||
toast('已删除', { type: 'success' });
|
||||
st.notes = st.notes.filter((n) => n.file !== note.file);
|
||||
renderList();
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function load({ manual = false } = {}) {
|
||||
if (manual) st.loading = true;
|
||||
renderList();
|
||||
refreshBtn.disabled = true;
|
||||
try {
|
||||
const res = await api.get('/api/notes');
|
||||
const notes = Array.isArray(res) ? res : (res && res.notes) || [];
|
||||
// 内核已经按时间倒序列出,这里再兜一下(文件名的 YYYYmmdd-HHMMSS 前缀也能比)
|
||||
st.notes = notes.slice().sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')));
|
||||
st.error = null;
|
||||
if (manual) toast(`读到 ${st.notes.length} 条笔记`);
|
||||
} catch (err) {
|
||||
st.error = err;
|
||||
if (manual) toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
st.loading = false;
|
||||
refreshBtn.disabled = false;
|
||||
renderList();
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
|
||||
return () => { /* 没有需要摘掉的监听器 */ };
|
||||
}
|
||||
1609
web/js/pages/resources.js
Normal file
243
web/js/pages/screens.js
Normal file
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* AI 界面页(#/screens)
|
||||
*
|
||||
* 接口(docs/kernel-api-misc.md §5):
|
||||
* GET /api/screens → {screens:[{id,conversationId,title,fullHtml,bytes,preview,at}]}
|
||||
* GET /api/screens/<id> → {id, html}
|
||||
* DELETE /api/screens/<id> → {ok:true} / 404 {ok:false}
|
||||
*
|
||||
* ★ 现状:电脑/网页端的 `show_ui` 现在也能用了 —— 内核的界面能力通道
|
||||
* (/api/device/*)在弹出界面的同时会 `store.save_screen()` 落盘一份,
|
||||
* 所以网页端这个列表里能看到、能再打开。安卓的界面存档在 App 本地
|
||||
* (AiSurface.kt),不进内核,两边互不影响。
|
||||
* ★ 渲染只用 srcdoc + sandbox="allow-scripts allow-forms":
|
||||
* 不加 allow-same-origin,AI 写的 HTML 就不能以同源身份 fetch 内核接口。
|
||||
* 代价是 iframe 里没有 localStorage / cookie,图表类界面不受影响。
|
||||
*/
|
||||
import { api } from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, toast, openModal, confirmBox, spinner,
|
||||
fmtTime, fmtBytes, injectStyles,
|
||||
} from '../ui.js';
|
||||
|
||||
const CSS = `
|
||||
.screens-card { padding: 8px 20px 12px; }
|
||||
.screens-count { font-size: 13px; color: var(--text-tertiary); }
|
||||
|
||||
.screen-row { gap: 14px; }
|
||||
.screen-thumb {
|
||||
flex: none; width: 40px; height: 40px; border-radius: 12px;
|
||||
background: var(--brand-weak); color: var(--brand);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.screen-main { flex: 1; min-width: 0; }
|
||||
.screen-preview {
|
||||
margin-top: 2px; font-size: 12.5px; line-height: 18px; color: var(--text-secondary);
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
|
||||
}
|
||||
.screen-meta { margin-top: 4px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 12px; color: var(--text-tertiary); }
|
||||
.screen-meta .mono { font-family: var(--font-mono); font-size: 11.5px; }
|
||||
.screen-side { flex: none; display: flex; align-items: center; gap: 6px; }
|
||||
|
||||
.screen-frame-wrap { height: 70vh; border-radius: 12px; overflow: hidden; border: 1px solid var(--line-1); background: #fff; }
|
||||
.screen-frame-wrap iframe { display: block; width: 100%; height: 100%; border: 0; background: #fff; }
|
||||
.screen-modal-tip {
|
||||
display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
|
||||
padding: 0 0 10px; font-size: 12px; color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.loading-line, .error-line {
|
||||
display: flex; align-items: center; gap: 10px; justify-content: center;
|
||||
padding: 36px 16px; font-size: 13px; color: var(--text-secondary);
|
||||
}
|
||||
.error-line { flex-direction: column; gap: 12px; }
|
||||
.error-line .err-text { color: var(--danger); font-size: 13px; line-height: 20px; text-align: center; }
|
||||
`;
|
||||
|
||||
/**
|
||||
* 片段模式(fullHtml === false)自己套一层骨架 —— 和安卓 AiSurface.wrapSkeleton 等价:
|
||||
* AI 只给 `<div>…</div>` 这种正文,不套骨架直接塞进 iframe 会顶到边、字号也不对。
|
||||
*/
|
||||
function wrapSkeleton(html) {
|
||||
return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
html, body { margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
font-size: 14px; line-height: 1.65; color: #111;
|
||||
background: #f7f8fa; padding: 16px; box-sizing: border-box;
|
||||
-webkit-text-size-adjust: 100%; overflow-wrap: anywhere;
|
||||
}
|
||||
img, svg, canvas, table { max-width: 100%; }
|
||||
button, a { font: inherit; }
|
||||
pre { overflow: auto; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #17181c; color: rgba(255,255,255,.85); }
|
||||
}
|
||||
</style></head><body>${html}</body></html>`;
|
||||
}
|
||||
|
||||
export default function renderScreens(container, ctx) {
|
||||
injectStyles('screens-page', CSS);
|
||||
|
||||
const st = { screens: [], loading: true, error: null, busy: false };
|
||||
const listBox = h('div.screens-card-host');
|
||||
|
||||
const refreshBtn = h('button.btn.sm', { title: '重新读取界面列表' }, icon('refresh', 15), h('span', '刷新'));
|
||||
const head = h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', 'AI 界面'),
|
||||
h('div.page-sub', 'AI 用 show_ui 弹出来的 HTML 界面。关掉之后还能在这里再打开(手机端的界面存在 App 本地,不进内核)。')),
|
||||
h('div.page-actions', {}, refreshBtn));
|
||||
|
||||
const page = h('div.page-inner', {}, head, h('div.card.screens-card', {}, listBox));
|
||||
mount(container, page);
|
||||
ctx.setTitle('AI 界面');
|
||||
|
||||
refreshBtn.addEventListener('click', () => load({ manual: true }));
|
||||
|
||||
function renderLoading() {
|
||||
clear(listBox);
|
||||
listBox.appendChild(h('div.loading-line', {}, spinner(15), '正在读取界面列表…'));
|
||||
}
|
||||
|
||||
function renderError(err) {
|
||||
clear(listBox);
|
||||
listBox.appendChild(h('div.error-line', {},
|
||||
h('div.err-text', String((err && err.message) || err)),
|
||||
h('button.btn.sm', { onclick: () => load({ manual: true }) }, '重试')));
|
||||
}
|
||||
|
||||
function renderEmpty() {
|
||||
clear(listBox);
|
||||
listBox.appendChild(h('div.empty-state', {},
|
||||
h('div.empty-state-icon', {}, icon('scan', 26)),
|
||||
h('div.empty-state-title', '这里还没有界面'),
|
||||
h('div.empty-state-desc',
|
||||
'AI 用 show_ui 弹出的界面会出现在这里,关掉之后还能再打开。让 AI 试着给你画个图表或排版一张卡片吧。')));
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
clear(listBox);
|
||||
if (st.loading) { renderLoading(); return; }
|
||||
if (st.error) { renderError(st.error); return; }
|
||||
if (!st.screens.length) { renderEmpty(); return; }
|
||||
|
||||
listBox.appendChild(h('div.screens-count', { style: 'padding:6px 0 2px' },
|
||||
`${st.screens.length} 个界面 · 点一行在弹窗里重新渲染`));
|
||||
|
||||
for (const item of st.screens) {
|
||||
const title = item.title || 'AI 界面';
|
||||
const row = h('div.list-row.clickable.screen-row', {
|
||||
role: 'button',
|
||||
tabindex: '0',
|
||||
title: '点开预览这个界面',
|
||||
onclick: () => openScreen(item),
|
||||
onkeydown: (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openScreen(item); }
|
||||
},
|
||||
},
|
||||
h('div.screen-thumb', {}, icon('scan', 18)),
|
||||
h('div.screen-main', {},
|
||||
h('div.list-title', {},
|
||||
h('span', title),
|
||||
item.fullHtml === false ? h('span.tag', '片段') : null),
|
||||
item.preview ? h('div.screen-preview', item.preview) : null,
|
||||
h('div.screen-meta', {},
|
||||
h('span', fmtTime(item.at) || item.at || '时间未知'),
|
||||
item.bytes != null ? h('span', '· ' + fmtBytes(item.bytes)) : null,
|
||||
h('span', '·'),
|
||||
h('span', item.conversationId ? '会话 ' : '未关联会话'),
|
||||
item.conversationId ? h('span.mono', String(item.conversationId)) : null)),
|
||||
h('div.screen-side', {},
|
||||
h('button.btn.sm', { onclick: (e) => { e.stopPropagation(); openScreen(item); } }, '打开'),
|
||||
h('button.icon-btn.sm', {
|
||||
title: '删除这个界面',
|
||||
onclick: (e) => { e.stopPropagation(); deleteScreen(item); },
|
||||
}, icon('trash', 15))));
|
||||
listBox.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
async function openScreen(item) {
|
||||
const modal = openModal({
|
||||
title: item.title || 'AI 界面',
|
||||
width: 900,
|
||||
body: h('div', {}, h('div.loading-line', {}, spinner(15), '正在读取 HTML…')),
|
||||
});
|
||||
const body = modal.body;
|
||||
try {
|
||||
const data = await api.get(`/api/screens/${encodeURIComponent(item.id)}`);
|
||||
const html = String(data.html || '');
|
||||
const doc = item.fullHtml === false ? wrapSkeleton(html) : html;
|
||||
clear(body);
|
||||
body.appendChild(h('div.screen-modal-tip', {},
|
||||
h('span', fmtTime(item.at) || item.at || ''),
|
||||
h('span', '·'),
|
||||
h('span', `${fmtBytes(data.bytes || item.bytes || html.length)}`),
|
||||
h('span', '·'),
|
||||
h('span', item.fullHtml === false ? '片段模式(已套骨架)' : '完整 HTML'),
|
||||
h('span', '·'),
|
||||
h('span', `id ${item.id}`)));
|
||||
const frame = h('iframe', {
|
||||
sandbox: 'allow-scripts allow-forms',
|
||||
srcdoc: doc,
|
||||
title: item.title || 'AI 界面',
|
||||
referrerpolicy: 'no-referrer',
|
||||
});
|
||||
body.appendChild(h('div.screen-frame-wrap', {}, frame));
|
||||
body.appendChild(h('div.screen-modal-tip', { style: 'padding:8px 0 0' },
|
||||
h('span', '界面里的按钮/脚本照常运行,但拿不到内核接口(sandbox 没给 allow-same-origin)。')));
|
||||
} catch (err) {
|
||||
clear(body);
|
||||
body.appendChild(h('div.error-line', {},
|
||||
h('div.err-text', String(err.message || err)),
|
||||
h('button.btn.sm', { onclick: () => { modal.close(); openScreen(item); } }, '重试')));
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteScreen(item) {
|
||||
const ok = await confirmBox({
|
||||
title: '删除这个界面?',
|
||||
message: `「${item.title || item.id}」的 HTML 存档会被删除,不可恢复。`,
|
||||
hint: '删除只影响内核里的存档,不影响聊天记录。',
|
||||
danger: true,
|
||||
okText: '删除',
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.del(`/api/screens/${encodeURIComponent(item.id)}`);
|
||||
st.screens = st.screens.filter((s) => s.id !== item.id);
|
||||
renderList();
|
||||
toast('已删除', { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function load({ manual = false } = {}) {
|
||||
if (manual) st.loading = true;
|
||||
renderList();
|
||||
refreshBtn.disabled = true;
|
||||
try {
|
||||
const res = await api.get('/api/screens');
|
||||
const list = Array.isArray(res) ? res : (res && res.screens) || [];
|
||||
st.screens = list;
|
||||
st.error = null;
|
||||
if (manual) toast(list.length ? `读到 ${list.length} 个界面` : '还是没有界面(电脑端不会写入)');
|
||||
} catch (err) {
|
||||
st.error = err;
|
||||
if (manual) toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
st.loading = false;
|
||||
refreshBtn.disabled = false;
|
||||
renderList();
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
|
||||
return () => { /* 没有需要摘掉的监听器 */ };
|
||||
}
|
||||
1526
web/js/pages/settings.js
Normal file
677
web/js/pages/skills.js
Normal file
@@ -0,0 +1,677 @@
|
||||
/**
|
||||
* 技能 · 连接器页(#/skills)
|
||||
*
|
||||
* 一页四块(都直接打真实接口,不做假按钮):
|
||||
* 1. Python 工具 GET /api/tools → python[],可选「试运行」→ POST /api/tools/run
|
||||
* 2. MCP 服务 GET /api/mcp → servers[](连接/断开/打开配置文件夹)
|
||||
* 3. MCP 原始 JSON 用 /api/mcp 的 **text** 编辑与回写 → PUT /api/mcp/config
|
||||
* 4. AI 界面能力开关 state.settings.uiTools.enabled → PUT /api/settings
|
||||
*
|
||||
* 两个必须踩住的坑(docs/kernel-api-misc.md §2):
|
||||
* ★ 工具数用 `tools.length`,内核**没有** toolCount 字段(安卓那边一直显示 0 就是踩了这个)。
|
||||
* ★ 原始 JSON 只能用 `text`(未展开占位符的原文)。`config` 里的 `${DOUBAO_DATA}`
|
||||
* 已经展开成实路径,拿它回写会把占位符永久写死。
|
||||
*/
|
||||
import { api, settings, saveSettings } from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, toast, openModal, spinner, switchEl, injectStyles, copyText,
|
||||
} from '../ui.js';
|
||||
|
||||
const CSS = `
|
||||
.skills-card { padding: 6px 20px 14px; }
|
||||
.skills-card + .skills-card { margin-top: 12px; }
|
||||
.card-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.card-head-right { flex: none; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.card-title .tag { font-weight: 500; }
|
||||
.mini-note { margin-top: 8px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); }
|
||||
.mini-note code { font-family: var(--font-mono); font-size: 11.5px; background: var(--bg-base-2); padding: 1px 5px; border-radius: 4px; }
|
||||
|
||||
.tool-main { flex: 1; min-width: 0; }
|
||||
.tool-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.tool-title .tag { height: 20px; font-size: 11px; }
|
||||
.tool-desc { font-size: 12px; color: var(--text-secondary); line-height: 18px; margin-top: 3px;
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.tool-side { flex: none; }
|
||||
.tool-row .btn { flex: none; }
|
||||
.tool-more { display: flex; justify-content: center; padding-top: 12px; }
|
||||
|
||||
.py-errors { margin-top: 10px; padding: 10px 12px; border-radius: 10px; background: var(--warning-weak); }
|
||||
.py-errors-title { display: flex; align-items: center; gap: 6px; font-size: 12.5px; font-weight: 500; color: var(--warning); }
|
||||
.py-errors-row { margin-top: 6px; font-size: 12px; line-height: 18px; color: var(--text-secondary); font-family: var(--font-mono); overflow-wrap: anywhere; }
|
||||
|
||||
.mcp-row { display: flex; gap: 12px; padding: 14px 0; border-bottom: 1px solid var(--line-1); align-items: flex-start; }
|
||||
.mcp-row:last-child { border-bottom: 0; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; flex: none; margin-top: 7px; background: var(--text-disable); }
|
||||
.dot.ok { background: var(--success); }
|
||||
.dot.err { background: var(--danger); }
|
||||
.mcp-main { flex: 1; min-width: 0; }
|
||||
.mcp-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 14px; font-weight: 500; }
|
||||
.mcp-status { font-size: 12px; color: var(--text-tertiary); }
|
||||
.mcp-status.ok { color: var(--success); }
|
||||
.mcp-status.err { color: var(--danger); }
|
||||
.mcp-target { margin-top: 4px; font-family: var(--font-mono); font-size: 11.5px; line-height: 17px;
|
||||
color: var(--text-tertiary); overflow-wrap: anywhere;
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.mcp-error { margin-top: 4px; font-size: 12px; line-height: 18px; color: var(--danger); overflow-wrap: anywhere; }
|
||||
.mcp-actions { flex: none; display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; max-width: 260px; }
|
||||
|
||||
.mcp-json { font-family: var(--font-mono); font-size: 12.5px; line-height: 19px;
|
||||
white-space: pre; overflow: auto; tab-size: 2;
|
||||
min-height: 260px; max-height: 54vh; resize: vertical; }
|
||||
.cfg-toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
|
||||
.cfg-status { font-size: 12.5px; color: var(--text-tertiary); }
|
||||
.cfg-results { margin-top: 10px; padding: 8px 12px; border-radius: 10px; background: var(--bg-sidebar); border: 1px solid var(--line-1); }
|
||||
.cfg-results-title { font-size: 12px; font-weight: 500; color: var(--text-secondary); padding-bottom: 4px; }
|
||||
.cfg-result-row { display: flex; align-items: center; gap: 8px; padding: 5px 0; font-size: 12.5px; border-top: 1px dashed var(--line-1); }
|
||||
.cfg-result-row .mono { font-family: var(--font-mono); font-size: 12px; }
|
||||
.cfg-result-row .err { color: var(--danger); overflow-wrap: anywhere; }
|
||||
.cfg-error { margin-top: 10px; padding: 10px 12px; border-radius: 10px; background: var(--danger-weak);
|
||||
color: var(--danger); font-size: 12.5px; line-height: 19px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.placeholder-list { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }
|
||||
.placeholder-chip { font-family: var(--font-mono); font-size: 11.5px; padding: 2px 8px; border-radius: 999px;
|
||||
background: var(--bg-base-2); color: var(--text-secondary); }
|
||||
.path-line { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 12px;
|
||||
color: var(--text-tertiary); flex-wrap: wrap; }
|
||||
.path-line .mono { font-family: var(--font-mono); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
|
||||
.ui-switch-row { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; padding-top: 6px; }
|
||||
.ui-switch-text { font-size: 13px; line-height: 20px; color: var(--text-secondary); max-width: 620px; }
|
||||
|
||||
.tool-args { font-family: var(--font-mono); font-size: 12.5px; line-height: 19px;
|
||||
white-space: pre; overflow: auto; min-height: 110px; }
|
||||
.param-list { max-height: 132px; overflow: auto; font-size: 12px; line-height: 18px; color: var(--text-secondary);
|
||||
border: 1px solid var(--line-1); border-radius: 10px; padding: 8px 10px; }
|
||||
.param-list .mono { font-family: var(--font-mono); font-size: 11.5px; color: var(--text-primary); }
|
||||
.param-list .req { color: var(--danger); }
|
||||
.run-status { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 12.5px; color: var(--text-tertiary); }
|
||||
.run-status.err { color: var(--danger); }
|
||||
.tool-run-desc { font-size: 13px; line-height: 20px; color: var(--text-secondary); margin-bottom: 12px; white-space: pre-wrap; }
|
||||
.tool-run-label { font-size: 12px; font-weight: 500; color: var(--text-secondary); margin: 12px 0 6px; }
|
||||
|
||||
.loading-line, .error-line { display: flex; align-items: center; gap: 10px; justify-content: center;
|
||||
padding: 28px 16px; font-size: 13px; color: var(--text-secondary); }
|
||||
.error-line { flex-direction: column; gap: 12px; }
|
||||
.error-line .err-text { color: var(--danger); font-size: 13px; line-height: 20px; text-align: center; }
|
||||
`;
|
||||
|
||||
/* ---------------- 小工具 ---------------- */
|
||||
|
||||
function scaffoldArgs(tool) {
|
||||
const params = (tool && tool.parameters) || {};
|
||||
const props = params.properties || {};
|
||||
const required = Array.isArray(params.required) ? params.required : [];
|
||||
const pick = required.length ? required : [];
|
||||
const out = {};
|
||||
for (const key of pick) {
|
||||
const spec = props[key] || {};
|
||||
const type = spec.type || 'string';
|
||||
if (type === 'number' || type === 'integer') out[key] = 0;
|
||||
else if (type === 'boolean') out[key] = false;
|
||||
else if (type === 'array') out[key] = [];
|
||||
else if (type === 'object') out[key] = {};
|
||||
else out[key] = '';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function paramSummary(tool) {
|
||||
const params = (tool && tool.parameters) || {};
|
||||
const props = params.properties || {};
|
||||
const keys = Object.keys(props);
|
||||
if (!keys.length) return '';
|
||||
return `${keys.length} 个参数`;
|
||||
}
|
||||
|
||||
function setBtnBusy(btn, busy, text) {
|
||||
if (busy) {
|
||||
if (!btn.dataset.idleHtml) btn.dataset.idleHtml = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '';
|
||||
btn.appendChild(spinner(13));
|
||||
if (text) btn.appendChild(document.createTextNode(' ' + text));
|
||||
} else {
|
||||
btn.disabled = false;
|
||||
if (btn.dataset.idleHtml) { btn.innerHTML = btn.dataset.idleHtml; delete btn.dataset.idleHtml; }
|
||||
}
|
||||
}
|
||||
|
||||
function tag(text, cls) {
|
||||
return h(`span.tag${cls ? '.' + cls : ''}`, String(text));
|
||||
}
|
||||
|
||||
/* ================================================================== */
|
||||
|
||||
export default function renderSkills(container, ctx) {
|
||||
injectStyles('skills-page', CSS);
|
||||
|
||||
const st = {
|
||||
tools: null,
|
||||
toolsError: null,
|
||||
mcp: null,
|
||||
mcpError: null,
|
||||
busy: new Set(),
|
||||
showAllTools: false,
|
||||
cfgDirty: false,
|
||||
cfgResult: null,
|
||||
cfgError: '',
|
||||
cfgSavedAt: '',
|
||||
loading: true,
|
||||
};
|
||||
|
||||
/* ---------------- 骨架:四张卡 ---------------- */
|
||||
|
||||
const pyStateTag = tag('…');
|
||||
const pySwitch = switchEl({ checked: settings().tools ? settings().tools.python !== false : true, onChange: togglePythonTools });
|
||||
const pyCount = h('span.mini-note', { style: 'margin:0' });
|
||||
const pyBody = h('div');
|
||||
const pyErrors = h('div');
|
||||
const pyMore = h('div.tool-more');
|
||||
const pyCard = h('div.card.skills-card', {},
|
||||
h('div.card-head', {},
|
||||
h('div', {},
|
||||
h('div.card-title', {}, 'Python 工具 ', pyStateTag),
|
||||
h('div.card-desc', 'AI 能自己调用的本地能力。工具就是 tools/ 目录下的 .py 文件:删了、或者改坏到导入失败,重启内核会重新播种回默认版本。'),
|
||||
pyCount),
|
||||
h('div.card-head-right', {},
|
||||
h('div', { style: 'display:flex;align-items:center;gap:8px;font-size:13px;color:var(--text-secondary)' },
|
||||
pySwitch, h('span', '启用')))),
|
||||
h('div.card-body', {}, pyBody, pyErrors, pyMore));
|
||||
|
||||
const mcpTag = tag('…');
|
||||
const mcpBody = h('div');
|
||||
const mcpNote = h('div.mini-note');
|
||||
const mcpCard = h('div.card.skills-card', {},
|
||||
h('div.card-head', {},
|
||||
h('div', {},
|
||||
h('div.card-title', {}, 'MCP 服务 ', mcpTag),
|
||||
h('div.card-desc', 'MCP 让 AI 用上外部服务(stdio / http / sse / inproc)。连上之后,它提供的工具会出现在 AI 的工具箱里。'))),
|
||||
h('div.card-body', {}, mcpBody, mcpNote));
|
||||
|
||||
const cfgTa = h('textarea.textarea.mcp-json', {
|
||||
wrap: 'off',
|
||||
spellcheck: 'false',
|
||||
placeholder: '{\n "servers": []\n}',
|
||||
'aria-label': 'MCP 配置文件原文',
|
||||
});
|
||||
cfgTa.addEventListener('input', () => { st.cfgDirty = true; });
|
||||
const cfgSaveBtn = h('button.btn.primary', {}, icon('plug', 15), h('span', '保存并重连'));
|
||||
const cfgResetBtn = h('button.btn', {}, icon('refresh', 15), h('span', '重新读取'));
|
||||
const cfgStatus = h('span.cfg-status');
|
||||
const cfgResults = h('div');
|
||||
const cfgPlaceholders = h('div.placeholder-list');
|
||||
const cfgPath = h('div.path-line');
|
||||
cfgSaveBtn.addEventListener('click', saveConfig);
|
||||
cfgResetBtn.addEventListener('click', () => loadMcp({ manual: true, forceText: true }));
|
||||
|
||||
const cfgCard = h('div.card.skills-card', {},
|
||||
h('div.card-head', {},
|
||||
h('div', {},
|
||||
h('div.card-title', {}, 'MCP 配置(原始 JSON)'),
|
||||
h('div.card-desc', '这里改的是 mcp.servers.json 的原文:${DOUBAO_DATA} 这类占位符会原样保留。保存会先断开全部服务、再按 enabled 重连,所以可能要等几秒(npx 首次下载更久)。'))),
|
||||
h('div.card-body', {},
|
||||
cfgTa,
|
||||
h('div.cfg-toolbar', {}, cfgSaveBtn, cfgResetBtn, cfgStatus),
|
||||
cfgResults,
|
||||
cfgPath,
|
||||
h('div.mini-note', {}, '可用占位符(保存时不会被展开,运行时才替换):'),
|
||||
cfgPlaceholders));
|
||||
|
||||
const uiSwitch = switchEl({
|
||||
checked: !!(settings().uiTools && settings().uiTools.enabled),
|
||||
onChange: toggleUiTools,
|
||||
});
|
||||
const uiStateTag = tag('…');
|
||||
const uiCard = h('div.card.skills-card', {},
|
||||
h('div.card-head', {},
|
||||
h('div', {},
|
||||
h('div.card-title', {}, 'AI 界面能力 ', uiStateTag),
|
||||
h('div.card-desc', '手机上的 AI 可以弹出 HTML 界面(show_ui)、向你提问(ask_user)、结束对话(end_conversation)。桌面 / 网页端这几个工具会降级(没有原生桥),但留着不影响别的功能。'))),
|
||||
h('div.card-body', {},
|
||||
h('div.ui-switch-row', {},
|
||||
h('div.ui-switch-text', {}, '允许 AI 使用界面类工具。关掉之后,这三四个工具不会出现在 AI 的工具清单里。'),
|
||||
uiSwitch)));
|
||||
|
||||
const head = h('div.page-head', {},
|
||||
h('div.page-head-left', {},
|
||||
h('div.page-title', '技能 · 连接器'),
|
||||
h('div.page-sub', '技能页就是「让 AI 多出哪些能力」:本地 Python 工具、外部 MCP 服务、以及手机上能弹的 AI 界面。')),
|
||||
h('div.page-actions', {}, h('button.btn.sm', {
|
||||
title: '重新读取工具列表和 MCP 状态',
|
||||
onclick: () => loadAll({ manual: true }),
|
||||
}, icon('refresh', 15), h('span', '刷新'))));
|
||||
|
||||
const page = h('div.page-inner', {}, head, pyCard, mcpCard, cfgCard, uiCard);
|
||||
mount(container, page);
|
||||
ctx.setTitle('技能 · 连接器');
|
||||
|
||||
/* ---------------- 状态同步 ---------------- */
|
||||
|
||||
function pythonEnabled() {
|
||||
const tools = settings().tools || {};
|
||||
return tools.python !== false;
|
||||
}
|
||||
|
||||
function syncSwitches() {
|
||||
const py = pythonEnabled();
|
||||
pySwitch.querySelector('input').checked = py;
|
||||
pyStateTag.textContent = py ? '已启用' : '已关闭';
|
||||
pyStateTag.className = py ? 'tag green' : 'tag';
|
||||
const ui = !!(settings().uiTools && settings().uiTools.enabled);
|
||||
uiSwitch.querySelector('input').checked = ui;
|
||||
uiStateTag.textContent = ui ? '已开启' : '已关闭';
|
||||
uiStateTag.className = ui ? 'tag green' : 'tag';
|
||||
}
|
||||
|
||||
async function togglePythonTools(checked) {
|
||||
pySwitch.querySelector('input').checked = !checked; // 先回滚,成功后再同步
|
||||
try {
|
||||
await saveSettings({ tools: { python: checked } }); // tools 是深合并,只改这一项
|
||||
toast(checked ? '已启用 Python 工具' : '已关闭 Python 工具:AI 看不到这些工具了', { type: 'success' });
|
||||
syncSwitches();
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
syncSwitches();
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleUiTools(checked) {
|
||||
uiSwitch.querySelector('input').checked = !checked;
|
||||
try {
|
||||
const cur = settings().uiTools || {};
|
||||
// uiTools 在设置里是浅替换,所以整个子对象一起发
|
||||
await saveSettings({ uiTools: { ...cur, enabled: checked } });
|
||||
toast(checked ? '已开启 AI 界面能力' : '已关闭 AI 界面能力', { type: 'success' });
|
||||
syncSwitches();
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
syncSwitches();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- Python 工具 ---------------- */
|
||||
|
||||
function renderPython() {
|
||||
clear(pyBody);
|
||||
clear(pyErrors);
|
||||
clear(pyMore);
|
||||
if (st.loading && !st.tools) {
|
||||
pyBody.appendChild(h('div.loading-line', {}, spinner(15), '正在读取工具…'));
|
||||
return;
|
||||
}
|
||||
if (st.toolsError) {
|
||||
pyBody.appendChild(h('div.error-line', {},
|
||||
h('div.err-text', String(st.toolsError.message || st.toolsError)),
|
||||
h('button.btn.sm', { onclick: () => loadAll({ manual: true }) }, '重试')));
|
||||
return;
|
||||
}
|
||||
const list = (st.tools && st.tools.python) || [];
|
||||
const errors = (st.tools && st.tools.errors) || [];
|
||||
pyCount.textContent = list.length
|
||||
? `${list.length} 个工具 · ${(st.tools && st.tools.toolNames || []).length} 个可用(含 MCP 工具)`
|
||||
: '';
|
||||
|
||||
if (!list.length) {
|
||||
pyBody.appendChild(h('div.empty-state', { style: 'padding:28px 16px' },
|
||||
h('div.empty-state-icon', {}, icon('terminal', 24)),
|
||||
h('div.empty-state-title', '没有 Python 工具'),
|
||||
h('div.empty-state-desc', 'tools/ 目录里没有可用的 .py。放一个进去、或者在设置里确认工具目录,然后重启内核。')));
|
||||
} else {
|
||||
const LIMIT = 8;
|
||||
const shown = st.showAllTools ? list : list.slice(0, LIMIT);
|
||||
for (const tool of shown) pyBody.appendChild(toolRow(tool));
|
||||
if (list.length > LIMIT) {
|
||||
pyMore.appendChild(h('button.btn.sm.ghost', {
|
||||
onclick: () => { st.showAllTools = !st.showAllTools; renderPython(); },
|
||||
}, st.showAllTools ? `收起(只显示前 ${LIMIT} 个)` : `展开全部 ${list.length} 个工具`));
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
pyErrors.appendChild(h('div.py-errors-title', {}, icon('alert-triangle', 14), `有 ${errors.length} 个工具文件导入失败`));
|
||||
for (const err of errors) {
|
||||
pyErrors.appendChild(h('div.py-errors-row', {}, `${err.file || '(未知文件)'} — ${err.error || '导入失败'}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toolRow(tool) {
|
||||
const summary = paramSummary(tool);
|
||||
const runBtn = h('button.btn.sm', { title: `试运行 ${tool.name}` }, icon('play', 13), h('span', '试运行'));
|
||||
runBtn.addEventListener('click', () => openToolRun(tool));
|
||||
return h('div.tool-row', {},
|
||||
h('div.tool-main', {},
|
||||
h('div.tool-title', {},
|
||||
h('span.tool-name', tool.name),
|
||||
tool.file ? tag(tool.file) : null,
|
||||
tool.builtin ? tag('内置', 'blue') : null,
|
||||
summary ? h('span.tool-params', summary) : null),
|
||||
h('div.tool-desc', { title: tool.description || '' }, tool.description || '(没有写说明)')),
|
||||
h('div.tool-side', {}, runBtn));
|
||||
}
|
||||
|
||||
/* ---------------- 工具试运行弹窗 ---------------- */
|
||||
|
||||
function openToolRun(tool) {
|
||||
const params = tool.parameters || {};
|
||||
const props = params.properties || {};
|
||||
const required = Array.isArray(params.required) ? params.required : [];
|
||||
const keys = Object.keys(props);
|
||||
|
||||
const argsTa = h('textarea.textarea.tool-args', {
|
||||
wrap: 'off',
|
||||
spellcheck: 'false',
|
||||
rows: 6,
|
||||
'aria-label': '工具参数(JSON)',
|
||||
});
|
||||
argsTa.value = JSON.stringify(scaffoldArgs(tool), null, 2);
|
||||
|
||||
const out = h('pre.console', { style: 'min-height:96px;max-height:40vh' }, '还没运行。填好参数点「运行」。');
|
||||
const status = h('div.run-status', {}, '参数是一个 JSON 对象;空对象 {} 表示用工具自己的默认值。');
|
||||
|
||||
const runBtn = h('button.btn.sm.primary', {}, icon('play', 13), h('span', '运行'));
|
||||
const resetBtn = h('button.btn.sm', { title: '把参数重置成根据 schema 生成的骨架' }, '重置参数');
|
||||
|
||||
const body = h('div', {},
|
||||
h('div.tool-run-desc', {}, tool.description || '(这个工具没有写说明)'),
|
||||
h('div.tool-run-label', {},
|
||||
'参数(JSON)',
|
||||
required.length ? h('span', { style: 'color:var(--text-tertiary);font-weight:400' }, ` · 必填:${required.join('、')}`) : null),
|
||||
keys.length ? h('details', { style: 'margin-bottom:8px' },
|
||||
h('summary', { style: 'cursor:pointer;font-size:12px;color:var(--text-secondary);padding:2px 0' }, `看参数说明(${keys.length} 项)`),
|
||||
h('div.param-list', { style: 'margin-top:6px' },
|
||||
keys.map((k) => h('div', {},
|
||||
h('span.mono', k),
|
||||
h('span', ` (${(props[k] && props[k].type) || 'any'})`),
|
||||
required.includes(k) ? h('span.req', ' *') : null,
|
||||
props[k] && props[k].description ? h('span', ` — ${props[k].description}`) : null)))) : null,
|
||||
argsTa,
|
||||
h('div.cfg-toolbar', {}, runBtn, resetBtn),
|
||||
status,
|
||||
out);
|
||||
|
||||
const modal = openModal({
|
||||
title: `试运行 · ${tool.name}`,
|
||||
width: 720,
|
||||
body,
|
||||
footer: h('div.modal-actions', {}, h('button.btn', { onclick: () => modal.close() }, '关闭')),
|
||||
});
|
||||
|
||||
resetBtn.addEventListener('click', () => {
|
||||
argsTa.value = JSON.stringify(scaffoldArgs(tool), null, 2);
|
||||
});
|
||||
|
||||
runBtn.addEventListener('click', async () => {
|
||||
let args = {};
|
||||
const raw = argsTa.value.trim();
|
||||
if (raw) {
|
||||
try {
|
||||
args = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
status.className = 'run-status err';
|
||||
status.textContent = `参数不是合法 JSON:${err.message}`;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) {
|
||||
status.className = 'run-status err';
|
||||
status.textContent = '参数必须是一个 JSON 对象,例如 {"expression": "1+1"}';
|
||||
return;
|
||||
}
|
||||
setBtnBusy(runBtn, true, '运行中…');
|
||||
status.className = 'run-status';
|
||||
status.textContent = '正在执行…';
|
||||
out.textContent = '';
|
||||
try {
|
||||
const res = await api.post('/api/tools/run', { name: tool.name, args });
|
||||
status.textContent = '执行成功 · 下面是内核返回的原始 JSON';
|
||||
out.textContent = JSON.stringify(res, null, 2);
|
||||
} catch (err) {
|
||||
// ok:false / 500 都被 api.js 抛出来了,err.message 就是内核的原话
|
||||
status.className = 'run-status err';
|
||||
status.textContent = '执行失败 · 下面是内核的原话';
|
||||
out.textContent = String(err.message || err);
|
||||
} finally {
|
||||
setBtnBusy(runBtn, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------- MCP 服务 ---------------- */
|
||||
|
||||
function serverStatus(server) {
|
||||
if (server.error) return { kind: 'err', text: '连接错误' };
|
||||
if (server.connected) return { kind: 'ok', text: '已连接' };
|
||||
return { kind: 'off', text: '未连接' };
|
||||
}
|
||||
|
||||
async function withServerBusy(key, btn, label, fn) {
|
||||
if (st.busy.has(key)) return;
|
||||
st.busy.add(key);
|
||||
setBtnBusy(btn, true, label);
|
||||
renderMcp();
|
||||
try {
|
||||
await fn();
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
st.busy.delete(key);
|
||||
setBtnBusy(btn, false);
|
||||
renderMcp();
|
||||
}
|
||||
}
|
||||
|
||||
function renderMcp() {
|
||||
clear(mcpBody);
|
||||
clear(mcpNote);
|
||||
if (st.loading && !st.mcp) {
|
||||
mcpBody.appendChild(h('div.loading-line', {}, spinner(15), '正在读取 MCP 状态…'));
|
||||
return;
|
||||
}
|
||||
if (st.mcpError) {
|
||||
mcpBody.appendChild(h('div.error-line', {},
|
||||
h('div.err-text', String(st.mcpError.message || st.mcpError)),
|
||||
h('button.btn.sm', { onclick: () => loadMcp({ manual: true }) }, '重试')));
|
||||
return;
|
||||
}
|
||||
const servers = (st.mcp && st.mcp.servers) || [];
|
||||
const connected = servers.filter((s) => s.connected).length;
|
||||
mcpTag.textContent = servers.length ? `${servers.length} 个服务 · ${connected} 个已连接` : '0 个服务';
|
||||
mcpTag.className = connected ? 'tag green' : 'tag';
|
||||
|
||||
if (!servers.length) {
|
||||
mcpBody.appendChild(h('div.empty-state', { style: 'padding:28px 16px' },
|
||||
h('div.empty-state-icon', {}, icon('plug', 24)),
|
||||
h('div.empty-state-title', '还没有配置 MCP 服务'),
|
||||
h('div.empty-state-desc', '在下面的「MCP 配置(原始 JSON)」里加一个 servers 条目,保存就会按 enabled 自动连接。')));
|
||||
return;
|
||||
}
|
||||
|
||||
for (const server of servers) {
|
||||
const state = serverStatus(server);
|
||||
const toolCount = (server.tools || []).length; // ★ 内核没有 toolCount 字段
|
||||
const busyConnect = st.busy.has(`connect:${server.name}`);
|
||||
const busyDisconnect = st.busy.has(`disconnect:${server.name}`);
|
||||
const busyReveal = st.busy.has(`reveal:${server.name}`);
|
||||
|
||||
const connectBtn = h('button.btn.sm' + (server.connected ? '' : '.outline'), { title: server.connected ? '强制重连一次' : '连接这个服务' },
|
||||
icon('plug', 13), h('span', server.connected ? '重连' : '连接'));
|
||||
const disconnectBtn = h('button.btn.sm', { title: '断开这个服务' }, icon('x', 13), h('span', '断开'));
|
||||
const revealBtn = h('button.btn.sm.ghost', { title: '在系统文件管理器里选中 mcp.servers.json' },
|
||||
icon('folder', 13), h('span', '打开配置文件夹'));
|
||||
|
||||
connectBtn.addEventListener('click', () => withServerBusy(`connect:${server.name}`, connectBtn, '连接中…', async () => {
|
||||
const res = await api.post('/api/mcp/connect', { name: server.name });
|
||||
toast(`「${server.name}」连上了${res.toolCount ? `(${res.toolCount} 个工具)` : ''}`, { type: 'success' });
|
||||
await loadMcp({});
|
||||
}));
|
||||
disconnectBtn.addEventListener('click', () => withServerBusy(`disconnect:${server.name}`, disconnectBtn, '断开中…', async () => {
|
||||
await api.post('/api/mcp/disconnect', { name: server.name });
|
||||
toast(`「${server.name}」已断开`, { type: 'success' });
|
||||
await loadMcp({});
|
||||
}));
|
||||
revealBtn.addEventListener('click', () => withServerBusy(`reveal:${server.name}`, revealBtn, '打开中…', async () => {
|
||||
// 桌面桥没接上时内核会回 ok:false,api.js 会把 error 原话抛出来 —— 照原样 toast
|
||||
const res = await api.post('/api/mcp/reveal');
|
||||
if (res && res.ok === false) throw new Error(res.error || '当前运行方式不支持打开文件夹');
|
||||
toast('已在文件夹里选中配置文件', { type: 'success' });
|
||||
}));
|
||||
|
||||
mcpBody.appendChild(h('div.mcp-row', {},
|
||||
h('span', { class: `dot${state.kind === 'ok' ? ' ok' : state.kind === 'err' ? ' err' : ''}` }),
|
||||
h('div.mcp-main', {},
|
||||
h('div.mcp-title', {},
|
||||
h('span', server.name),
|
||||
tag(server.transport || 'stdio'),
|
||||
server.enabled === false ? tag('未启用') : null,
|
||||
h('span', { class: `mcp-status${state.kind === 'ok' ? ' ok' : state.kind === 'err' ? ' err' : ''}` },
|
||||
`${state.text} · ${toolCount} 个工具`)),
|
||||
server.target ? h('div.mcp-target', { title: server.target }, server.target) : null,
|
||||
server.error ? h('div.mcp-error', {}, server.error) : null,
|
||||
server.enabled === false
|
||||
? h('div.mini-note', { style: 'margin-top:4px' }, '配置文件里 enabled 是 false:改成 true 并保存,内核才会去连它。')
|
||||
: null),
|
||||
h('div.mcp-actions', {}, connectBtn, disconnectBtn, revealBtn)));
|
||||
// 渲染时按钮已经是 busy 状态的要立刻置灰(renderMcp 会重建按钮)
|
||||
if (busyConnect) setBtnBusy(connectBtn, true, '连接中…');
|
||||
if (busyDisconnect) setBtnBusy(disconnectBtn, true, '断开中…');
|
||||
if (busyReveal) setBtnBusy(revealBtn, true, '打开中…');
|
||||
}
|
||||
|
||||
mcpNote.textContent = '连接 / 断开只影响这一次运行:重启内核后,会按配置文件里每个服务的 enabled 重新连。';
|
||||
}
|
||||
|
||||
/* ---------------- MCP 原始 JSON ---------------- */
|
||||
|
||||
function renderConfig() {
|
||||
const mcp = st.mcp;
|
||||
if (mcp) {
|
||||
if (!st.cfgDirty) {
|
||||
cfgTa.value = mcp.text || '';
|
||||
}
|
||||
cfgStatus.textContent = st.cfgDirty ? '有未保存的修改' : (st.cfgSavedAt ? `已保存 ${st.cfgSavedAt}` : '和磁盘上的内容一致');
|
||||
} else if (st.mcpError) {
|
||||
cfgStatus.textContent = '';
|
||||
}
|
||||
|
||||
clear(cfgResults);
|
||||
if (st.cfgError) {
|
||||
cfgResults.appendChild(h('div.cfg-error', {}, st.cfgError));
|
||||
} else if (st.cfgResult) {
|
||||
const results = st.cfgResult.results || [];
|
||||
const box = h('div.cfg-results', {},
|
||||
h('div.cfg-results-title', {}, `${st.cfgResult.count} 个服务写入成功 · 重连结果:`));
|
||||
if (!results.length) {
|
||||
box.appendChild(h('div.cfg-result-row', {}, '没有 enabled 的服务需要连接。'));
|
||||
}
|
||||
for (const r of results) {
|
||||
box.appendChild(h('div.cfg-result-row', {},
|
||||
h('span.mono', r.name),
|
||||
r.ok ? tag('已连接', 'green') : tag('连接失败', 'red'),
|
||||
r.toolCount ? h('span', `${r.toolCount} 个工具`) : null,
|
||||
r.error ? h('span.err', r.error) : null));
|
||||
}
|
||||
cfgResults.appendChild(box);
|
||||
}
|
||||
|
||||
clear(cfgPlaceholders);
|
||||
const ph = (mcp && mcp.placeholders) || {};
|
||||
for (const key of Object.keys(ph)) {
|
||||
cfgPlaceholders.appendChild(h('span.placeholder-chip', {
|
||||
title: ph[key] || '(这个环境里没有这个变量)',
|
||||
}, `\${${key}}`));
|
||||
}
|
||||
|
||||
clear(cfgPath);
|
||||
const path = mcp && mcp.path;
|
||||
if (path) {
|
||||
cfgPath.appendChild(h('span', '配置文件:'));
|
||||
cfgPath.appendChild(h('span.mono', {}, path));
|
||||
cfgPath.appendChild(h('button.btn.sm.ghost', {
|
||||
title: '复制路径',
|
||||
onclick: async () => {
|
||||
const ok = await copyText(path);
|
||||
toast(ok ? '路径已复制' : '复制失败,只能手动选中了', { type: ok ? 'success' : 'error' });
|
||||
},
|
||||
}, icon('copy', 13), h('span', '复制路径')));
|
||||
if (mcp && mcp.canReveal === false) {
|
||||
cfgPath.appendChild(h('span', { style: 'color:var(--text-tertiary)' }, '· 当前运行方式没有接桌面桥,打不开文件夹'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
setBtnBusy(cfgSaveBtn, true, '保存并重连…');
|
||||
cfgSaveBtn.disabled = true;
|
||||
st.cfgError = '';
|
||||
st.cfgResult = null;
|
||||
renderConfig();
|
||||
try {
|
||||
const res = await api.put('/api/mcp/config', { text: cfgTa.value });
|
||||
st.cfgResult = { count: res.count || 0, results: res.results || [] };
|
||||
st.cfgSavedAt = new Date().toLocaleTimeString('zh-CN', { hour12: false });
|
||||
st.cfgDirty = false;
|
||||
const failed = (res.results || []).filter((r) => !r.ok);
|
||||
toast(
|
||||
failed.length
|
||||
? `已保存,但有 ${failed.length} 个服务没连上:${failed[0].error || failed[0].name}`
|
||||
: `已保存并重连(${res.count || 0} 个服务)`,
|
||||
{ type: failed.length ? 'error' : 'success' },
|
||||
);
|
||||
// 重连后 servers 会变,顺手刷新服务状态卡;text 用服务器上的规范文本
|
||||
await loadMcp({ forceText: true });
|
||||
} catch (err) {
|
||||
st.cfgError = String(err.message || err); // 400 的 error 原话
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
cfgSaveBtn.disabled = false;
|
||||
setBtnBusy(cfgSaveBtn, false);
|
||||
renderConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 取数 ---------------- */
|
||||
|
||||
async function loadAll({ manual = false } = {}) {
|
||||
if (manual) st.loading = true;
|
||||
renderPython();
|
||||
await Promise.all([loadTools({ manual }), loadMcp({ manual })]);
|
||||
st.loading = false;
|
||||
renderPython();
|
||||
}
|
||||
|
||||
async function loadTools({ manual = false } = {}) {
|
||||
try {
|
||||
st.tools = await api.get('/api/tools');
|
||||
st.toolsError = null;
|
||||
} catch (err) {
|
||||
st.toolsError = err;
|
||||
if (manual) toast(err.message, { type: 'error' });
|
||||
}
|
||||
renderPython();
|
||||
}
|
||||
|
||||
async function loadMcp({ manual = false, forceText = false } = {}) {
|
||||
try {
|
||||
st.mcp = await api.get('/api/mcp');
|
||||
st.mcpError = null;
|
||||
if (forceText) st.cfgDirty = false;
|
||||
if (manual) toast('已重新读取 MCP 配置');
|
||||
} catch (err) {
|
||||
st.mcpError = err;
|
||||
if (manual) toast(err.message, { type: 'error' });
|
||||
}
|
||||
st.loading = false;
|
||||
renderMcp();
|
||||
renderConfig();
|
||||
}
|
||||
|
||||
syncSwitches();
|
||||
renderPython();
|
||||
renderMcp();
|
||||
renderConfig();
|
||||
loadAll();
|
||||
|
||||
const offState = ctx.onState(() => syncSwitches());
|
||||
|
||||
return () => { offState(); };
|
||||
}
|
||||
365
web/js/pages/usage.js
Normal file
@@ -0,0 +1,365 @@
|
||||
/**
|
||||
* 用量页(#/agents/:id/usage)
|
||||
*
|
||||
* 数据:GET /api/agents/<id>/usage(docs/kernel-api-agents.md §5)
|
||||
* { input, output, total, cacheHit, cacheMiss, byModel:[{model,input,output,cacheHit,cacheMiss}],
|
||||
* limit, remaining, pricePerK, cachePricePerK, cost }
|
||||
*
|
||||
* 两条必须守住的口径:
|
||||
* 1. 输入 / 输出**分开显示**(需求明确说不合并),所以「合计」是第四个数而不是把两列糊成一列。
|
||||
* 2. 缓存命中 / 未命中**两家都没给时是 0/0** —— 此时命中率显示「—」,不能显示 0%(那是误导)。
|
||||
*
|
||||
* 清零:POST /api/agents/<id>/usage(`agent_api.py` 里 len(seg)==4 那条;
|
||||
* 文件头注释写的 /usage/reset 其实**没实现**,所以这里先走 /usage,404 才退到 /usage/reset)。
|
||||
*/
|
||||
import { api, agents } from '../api.js';
|
||||
import {
|
||||
h, mount, clear, icon, avatar, toast, confirmBox,
|
||||
injectStyles, spinner, emptyState,
|
||||
} from '../ui.js';
|
||||
|
||||
const CSS = `
|
||||
.usage-page .usage-head-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.usage-page .usage-head-text { min-width: 0; }
|
||||
.usage-page .usage-loading {
|
||||
display: flex; align-items: center; justify-content: center; gap: 10px;
|
||||
padding: 72px 0; color: var(--text-secondary); font-size: 14px;
|
||||
}
|
||||
.usage-page .stat-card .progress { margin-top: 6px; }
|
||||
.usage-page .stat-value.small { font-size: 18px; line-height: 26px; }
|
||||
.usage-page .usage-card-head {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
|
||||
}
|
||||
.usage-page .usage-card-head .card-title .tag { font-weight: 500; }
|
||||
.usage-page .usage-table { margin-top: 10px; }
|
||||
.usage-page .usage-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 92px 92px 100px 84px;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 4px;
|
||||
border-bottom: 1px solid var(--line-1);
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
}
|
||||
.usage-page .usage-row:last-child { border-bottom: 0; }
|
||||
.usage-page .usage-row.hd {
|
||||
padding: 6px 4px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--text-tertiary);
|
||||
border-bottom: 1px solid var(--line-1);
|
||||
}
|
||||
.usage-page .usage-row.total {
|
||||
font-weight: 600;
|
||||
border-top: 1px solid var(--line-2);
|
||||
border-bottom: 0;
|
||||
}
|
||||
.usage-page .usage-num {
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.usage-page .usage-row.hd .usage-num { font-weight: 400; }
|
||||
.usage-page .usage-model { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.usage-page .usage-model .name {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.usage-page .usage-model .tag { flex: none; }
|
||||
.usage-page .usage-note {
|
||||
display: flex; align-items: flex-start; gap: 8px;
|
||||
margin-top: 12px; font-size: 12px; line-height: 18px; color: var(--text-tertiary);
|
||||
}
|
||||
.usage-page .usage-note .icon { margin-top: 2px; flex: none; }
|
||||
.usage-page .usage-empty { padding: 0; }
|
||||
.usage-page .usage-empty .empty-state { padding: 28px 12px 18px; }
|
||||
.usage-page .usage-foot { margin-top: 18px; font-size: 12px; line-height: 18px; color: var(--text-tertiary); text-align: center; }
|
||||
`;
|
||||
|
||||
function agentById(id) {
|
||||
return agents().find((a) => a.id === id) || null;
|
||||
}
|
||||
|
||||
function num(v) {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
/** Token 数:十万以内原样带千位分隔,再大就换算成「万 / 亿」省地方 */
|
||||
function fmtTok(v) {
|
||||
const n = Math.round(num(v));
|
||||
if (Math.abs(n) < 1e5) return n.toLocaleString('zh-CN');
|
||||
const trim = (s) => s.replace(/\.0+$/, '').replace(/(\.\d)0$/, '$1');
|
||||
if (Math.abs(n) < 1e8) return `${trim((n / 1e4).toFixed(2))}万`;
|
||||
return `${trim((n / 1e8).toFixed(2))}亿`;
|
||||
}
|
||||
|
||||
/** 命中率:两家都没给缓存信息(0/0)时返回 null —— 界面显示「—」而不是 0% */
|
||||
function hitRate(bucket) {
|
||||
const hit = num(bucket.cacheHit);
|
||||
const miss = num(bucket.cacheMiss);
|
||||
const all = hit + miss;
|
||||
return all > 0 ? (hit / all) * 100 : null;
|
||||
}
|
||||
|
||||
function percentText(rate) {
|
||||
if (rate == null) return '—';
|
||||
const v = rate >= 10 ? rate.toFixed(1) : rate.toFixed(2);
|
||||
return `${v.replace(/\.0+$/, '').replace(/(\.\d)0$/, '$1')}%`;
|
||||
}
|
||||
|
||||
export default function renderUsage(container, ctx) {
|
||||
const agentId = ctx.params.id || '';
|
||||
injectStyles('usage', CSS);
|
||||
|
||||
const st = {
|
||||
agent: agentById(agentId),
|
||||
data: null,
|
||||
loading: true,
|
||||
error: '',
|
||||
resetting: false,
|
||||
};
|
||||
|
||||
const root = h('div.page-inner.usage-page');
|
||||
mount(container, root);
|
||||
ctx.setTitle('用量');
|
||||
|
||||
/* ---------------- 数据 ---------------- */
|
||||
|
||||
async function load() {
|
||||
if (!st.data) st.loading = true;
|
||||
st.error = '';
|
||||
render();
|
||||
try {
|
||||
st.data = await api.get(`/api/agents/${encodeURIComponent(agentId)}/usage`);
|
||||
st.agent = agentById(agentId) || st.agent;
|
||||
} catch (err) {
|
||||
st.error = err.message || String(err);
|
||||
} finally {
|
||||
st.loading = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 渲染 ---------------- */
|
||||
|
||||
function render() {
|
||||
clear(root);
|
||||
root.appendChild(renderHead());
|
||||
if (st.loading && !st.data) {
|
||||
root.appendChild(h('div.usage-loading', {}, spinner(20), '正在读取用量…'));
|
||||
return;
|
||||
}
|
||||
if (st.error && !st.data) {
|
||||
root.appendChild(renderLoadError());
|
||||
return;
|
||||
}
|
||||
root.appendChild(renderStats());
|
||||
root.appendChild(renderModelCard());
|
||||
root.appendChild(h('div.usage-foot', {},
|
||||
'输入 / 输出分开记;换模型不会丢历史,桶是查询时按模型名分出来的。'));
|
||||
}
|
||||
|
||||
function renderHead() {
|
||||
const agent = st.agent || { id: agentId, name: '未知智能体', avatar: 'custom' };
|
||||
const d = st.data;
|
||||
const total = d ? num(d.total) : 0;
|
||||
const sub = d
|
||||
? `Token 用量 · 累计 ${fmtTok(total)} · 输入 / 输出分开记`
|
||||
: 'Token 用量';
|
||||
|
||||
return h('div.page-head', {},
|
||||
h('div.page-head-left.usage-head-left', {},
|
||||
h('button.icon-btn', { title: '返回智能体', onclick: goBack }, icon('arrow-left', 18)),
|
||||
avatar(agent, 40),
|
||||
h('div.usage-head-text', {},
|
||||
h('div.page-title', agent.name || '未知智能体'),
|
||||
h('div.page-sub', sub))),
|
||||
h('div.page-actions', {},
|
||||
h('button.btn', {
|
||||
title: '看它的记忆',
|
||||
onclick: () => ctx.navigate(`agents/${agentId}/memories`),
|
||||
}, icon('brain', 15), '记忆'),
|
||||
h('button.btn', {
|
||||
title: '改人设 / 模型 / 限额',
|
||||
onclick: () => ctx.navigate(`agents/${agentId}`),
|
||||
}, icon('pencil', 15), '编辑智能体'),
|
||||
h('button.btn.danger', {
|
||||
title: '把这个智能体的 Token 统计清零(不可恢复)',
|
||||
disabled: st.resetting || !total,
|
||||
onclick: (e) => resetUsage(e.currentTarget),
|
||||
}, icon('trash', 15), st.resetting ? '清零中…' : '清零')));
|
||||
}
|
||||
|
||||
function renderLoadError() {
|
||||
return h('div.card', {},
|
||||
h('div.card-title', {}, icon('alert-triangle', 18), '用量读不出来'),
|
||||
h('div.card-desc', {}, st.error || '未知错误'),
|
||||
h('div.card-actions', {},
|
||||
h('button.btn.primary', { onclick: load }, '重试'),
|
||||
h('button.btn', { onclick: goBack }, '返回')));
|
||||
}
|
||||
|
||||
function renderStats() {
|
||||
const d = st.data;
|
||||
const input = num(d.input);
|
||||
const output = num(d.output);
|
||||
const total = num(d.total) || (input + output);
|
||||
const limit = num(d.limit);
|
||||
const remaining = d.remaining == null ? null : num(d.remaining);
|
||||
const cacheAll = num(d.cacheHit) + num(d.cacheMiss);
|
||||
|
||||
const cards = h('div.usage-grid', {},
|
||||
statCard('总输入', fmtTok(input), 'prompt tokens'),
|
||||
statCard('总输出', fmtTok(output), 'completion tokens'),
|
||||
statCard('合计', fmtTok(total), input + output === total
|
||||
? '输入 + 输出'
|
||||
: `输入 + 输出 = ${fmtTok(input + output)}`),
|
||||
quotaCard(total, limit, remaining));
|
||||
|
||||
if (cacheAll > 0) {
|
||||
cards.appendChild(statCard('缓存命中', fmtTok(num(d.cacheHit)),
|
||||
`命中率 ${percentText(hitRate(d))}`));
|
||||
}
|
||||
if (d.cost != null && num(d.pricePerK) > 0) {
|
||||
cards.appendChild(statCard('预估费用', `¥${Number(d.cost).toFixed(4)}`,
|
||||
`${num(d.pricePerK)} 元 / 千 Token`));
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
function statCard(label, value, sub, extra) {
|
||||
return h('div.stat-card', {},
|
||||
h('div.stat-label', {}, label),
|
||||
h('div.stat-value', {}, String(value)),
|
||||
sub ? h('div.stat-sub', {}, String(sub)) : null,
|
||||
extra || null);
|
||||
}
|
||||
|
||||
function quotaCard(total, limit, remaining) {
|
||||
if (!(limit > 0)) {
|
||||
return statCard('额度', '无限制', '想限额就去「编辑智能体」填 Token 限额');
|
||||
}
|
||||
const used = limit > 0 ? Math.min(100, (total / limit) * 100) : 0;
|
||||
const cls = used >= 90 ? ' danger' : used >= 70 ? ' warn' : '';
|
||||
return h('div.stat-card', {},
|
||||
h('div.stat-label', {}, '额度'),
|
||||
h('div.stat-value.small', {}, `${fmtTok(total)} / ${fmtTok(limit)}`),
|
||||
h('div.progress', { class: cls.trim() }, h('i', { style: `width:${used.toFixed(1)}%` })),
|
||||
h('div.stat-sub', {},
|
||||
`已用 ${used.toFixed(1)}%`,
|
||||
remaining != null ? ` · 还剩 ${fmtTok(remaining)}` : '',
|
||||
used >= 100 ? ' · 额度已用完,聊天会被内核拦下' : ''));
|
||||
}
|
||||
|
||||
function renderModelCard() {
|
||||
const d = st.data;
|
||||
const rows = Array.isArray(d.byModel) ? d.byModel : [];
|
||||
const cacheAll = num(d.cacheHit) + num(d.cacheMiss);
|
||||
|
||||
const head = h('div.usage-card-head', {},
|
||||
h('div.card-title', {},
|
||||
icon('cpu', 18), '按模型分桶',
|
||||
h('span.tag', String(rows.length))),
|
||||
h('button.btn.sm', { title: '重新读一次', onclick: load }, icon('refresh', 14), '刷新'));
|
||||
|
||||
const table = h('div.usage-table');
|
||||
table.appendChild(h('div.usage-row.hd', {},
|
||||
h('span', {}, '模型'),
|
||||
h('span.usage-num', {}, '输入'),
|
||||
h('span.usage-num', {}, '输出'),
|
||||
h('span.usage-num', { title: '缓存命中的输入 token(上游没给就是 0)' }, '缓存命中'),
|
||||
h('span.usage-num', { title: '命中 / (命中 + 未命中)' }, '命中率')));
|
||||
|
||||
if (!rows.length) {
|
||||
table.appendChild(h('div.usage-empty', {},
|
||||
emptyState('cpu', '还没有用量记录',
|
||||
'和它聊几句就会开始统计:输入 / 输出分开记,按模型分桶,额度用完了内核会拦下来。')));
|
||||
} else {
|
||||
for (const b of rows) {
|
||||
const rate = hitRate(b);
|
||||
table.appendChild(h('div.usage-row', {},
|
||||
h('div.usage-model', {},
|
||||
h('span.name', { title: b.model || '' }, b.model || '(未知)')),
|
||||
h('span.usage-num', {}, fmtTok(num(b.input))),
|
||||
h('span.usage-num', {}, fmtTok(num(b.output))),
|
||||
h('span.usage-num', { title: `未命中 ${fmtTok(num(b.cacheMiss))}` },
|
||||
rate == null ? '—' : fmtTok(num(b.cacheHit))),
|
||||
h('span.usage-num', {}, percentText(rate))));
|
||||
}
|
||||
table.appendChild(h('div.usage-row.total', {},
|
||||
h('span', {}, '合计'),
|
||||
h('span.usage-num', {}, fmtTok(num(d.input))),
|
||||
h('span.usage-num', {}, fmtTok(num(d.output))),
|
||||
h('span.usage-num', {}, cacheAll > 0 ? fmtTok(num(d.cacheHit)) : '—'),
|
||||
h('span.usage-num', {}, percentText(hitRate(d)))));
|
||||
}
|
||||
|
||||
const card = h('div.card', {}, head,
|
||||
h('div.card-desc', {}, '一条记忆、一次整理、一轮对话都会记在这里;按模型分桶,按合计倒序。'));
|
||||
card.appendChild(h('div.card-body', {}, table));
|
||||
|
||||
if (!rows.length || cacheAll === 0) {
|
||||
card.appendChild(h('div.usage-note', {},
|
||||
icon('info', 14),
|
||||
h('div', {},
|
||||
rows.length
|
||||
? '上游这次没给缓存信息(命中 / 未命中都是 0),所以命中率显示「—」—— 它不是 0%,是「不知道」。'
|
||||
: '缓存命中 / 未命中两家厂商的字段名都不一样,内核归一化之后才落库;都没给时这里显示「—」。')));
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
/* ---------------- 清零 ---------------- */
|
||||
|
||||
async function resetUsage(btn) {
|
||||
const total = st.data ? num(st.data.total) : 0;
|
||||
const ok = await confirmBox({
|
||||
title: '把这个智能体的用量清零?',
|
||||
message: `当前累计 ${fmtTok(total)} Token(输入 ${fmtTok(num(st.data.input))} / 输出 ${fmtTok(num(st.data.output))})。`,
|
||||
hint: '清零后历史账本不可恢复 —— 额度是按累计算的,清完等于重新开始计数。',
|
||||
danger: true,
|
||||
okText: '清零',
|
||||
});
|
||||
if (!ok) return;
|
||||
st.resetting = true;
|
||||
render();
|
||||
try {
|
||||
let res;
|
||||
try {
|
||||
res = await api.post(`/api/agents/${encodeURIComponent(agentId)}/usage`, {});
|
||||
} catch (err) {
|
||||
// 内核文件头注释里写的是 /usage/reset,实际路由是 /usage —— 老版本可能反过来
|
||||
if (err.status !== 404) throw err;
|
||||
res = await api.post(`/api/agents/${encodeURIComponent(agentId)}/usage/reset`, {});
|
||||
}
|
||||
st.data = res && res.agentId ? res : null;
|
||||
if (!st.data) await load();
|
||||
toast('已清零', { type: 'success' });
|
||||
} catch (err) {
|
||||
toast(err.message, { type: 'error' });
|
||||
} finally {
|
||||
st.resetting = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
ctx.navigate(st.agent ? `agents/${agentId}` : 'agents');
|
||||
}
|
||||
|
||||
if (!agentId) {
|
||||
root.appendChild(h('div.card', {},
|
||||
h('div.card-title', {}, icon('alert-triangle', 18), '地址里没有智能体 id'),
|
||||
h('div.card-actions', {}, h('button.btn.primary', { onclick: () => ctx.navigate('agents') }, '去智能体列表'))));
|
||||
return undefined;
|
||||
}
|
||||
|
||||
render();
|
||||
load();
|
||||
return () => {};
|
||||
}
|
||||
620
web/js/ui.js
Normal file
@@ -0,0 +1,620 @@
|
||||
/**
|
||||
* 网页版基础 UI 库:DOM 构造、Markdown、图标、弹层、Toast、表单小部件。
|
||||
*
|
||||
* 设计目标:不引任何第三方依赖(要能离线装进 exe、也要能被 Python 内核直接托管),
|
||||
* 所以用 200 行左右的 h() + 手写 markdown 渲染,页面全部按"函数返回 DOM"的方式写。
|
||||
*/
|
||||
import { iconHtml } from './icons.js';
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* DOM */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
function classListOf(tag) {
|
||||
let cls = null;
|
||||
// div.foo.bar#id → tag=div, classes=[foo,bar], id=id
|
||||
const hashAt = tag.indexOf('#');
|
||||
let id = null;
|
||||
if (hashAt >= 0) {
|
||||
id = tag.slice(hashAt + 1);
|
||||
tag = tag.slice(0, hashAt);
|
||||
}
|
||||
const dotAt = tag.indexOf('.');
|
||||
if (dotAt >= 0) {
|
||||
cls = tag.slice(dotAt + 1).split('.').filter(Boolean);
|
||||
tag = tag.slice(0, dotAt);
|
||||
}
|
||||
return { tag: tag || 'div', cls, id };
|
||||
}
|
||||
|
||||
function appendChild(node, child) {
|
||||
if (child == null || child === false || child === true) return;
|
||||
if (Array.isArray(child)) {
|
||||
for (const c of child) appendChild(node, c);
|
||||
return;
|
||||
}
|
||||
if (child instanceof Node) {
|
||||
node.appendChild(child);
|
||||
return;
|
||||
}
|
||||
node.appendChild(document.createTextNode(String(child)));
|
||||
}
|
||||
|
||||
/**
|
||||
* h('div.card', {onclick, style:{}, className}, ...children)
|
||||
* style 既可以是对象也可以是字符串。
|
||||
*/
|
||||
export function h(tag, props, ...children) {
|
||||
if (Array.isArray(props) || typeof props === 'string' || typeof props === 'number' || props instanceof Node) {
|
||||
children.unshift(props);
|
||||
props = null;
|
||||
}
|
||||
const { tag: name, cls, id } = classListOf(tag);
|
||||
const node = document.createElement(name);
|
||||
if (id) node.id = id;
|
||||
if (cls && cls.length) node.className = cls.join(' ');
|
||||
|
||||
if (props) {
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (value == null || value === false) continue;
|
||||
if (key === 'style') {
|
||||
if (typeof value === 'string') node.setAttribute('style', value);
|
||||
else for (const [k, v] of Object.entries(value)) { if (v != null && v !== '') node.style.setProperty(k, String(v)); }
|
||||
} else if (key === 'className' || key === 'class') {
|
||||
node.className = node.className ? `${node.className} ${value}` : String(value);
|
||||
} else if (key === 'html') {
|
||||
node.innerHTML = String(value);
|
||||
} else if (key === 'dataset') {
|
||||
for (const [k, v] of Object.entries(value)) node.dataset[k] = String(v);
|
||||
} else if (key.startsWith('on') && typeof value === 'function') {
|
||||
node.addEventListener(key.slice(2).toLowerCase(), value);
|
||||
} else if (key === 'ref' && typeof value === 'function') {
|
||||
value(node);
|
||||
} else if (value === true) {
|
||||
node.setAttribute(key, '');
|
||||
} else {
|
||||
node.setAttribute(key, String(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const child of children) appendChild(node, child);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** HTML 字符串 → 元素(第一个子元素)。 */
|
||||
export function el(html) {
|
||||
const tpl = document.createElement('template');
|
||||
tpl.innerHTML = html.trim();
|
||||
return tpl.content.firstElementChild;
|
||||
}
|
||||
|
||||
export function frag(...children) {
|
||||
const f = document.createDocumentFragment();
|
||||
for (const c of children) appendChild(f, c);
|
||||
return f;
|
||||
}
|
||||
|
||||
export function clear(node) {
|
||||
while (node && node.firstChild) node.removeChild(node.firstChild);
|
||||
}
|
||||
|
||||
export function mount(parent, ...children) {
|
||||
clear(parent);
|
||||
for (const c of children) appendChild(parent, c);
|
||||
return parent;
|
||||
}
|
||||
|
||||
/** 少写点 document.getElementById */
|
||||
export const $ = (sel, root = document) => root.querySelector(sel);
|
||||
export const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
|
||||
|
||||
export function on(target, type, handler, opts) {
|
||||
target.addEventListener(type, handler, opts);
|
||||
return () => target.removeEventListener(type, handler, opts);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 图标 / 头像 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function icon(name, size = 18, extraClass = '') {
|
||||
const span = h(`span.icon${extraClass ? '.' + extraClass : ''}`);
|
||||
span.innerHTML = iconHtml(name, size);
|
||||
return span;
|
||||
}
|
||||
|
||||
/** 头像:优先用立绘/头像图,退回内置 PNG,再退回首字母色块。 */
|
||||
export function avatar(agent, size = 36, extraClass = '') {
|
||||
const name = (agent && agent.name) || 'AI';
|
||||
const key = (agent && (agent.avatar || agent.id) || 'custom').replace(/^a_/, '');
|
||||
const known = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'cloud', 'robot', 'star', 'custom'];
|
||||
const file = known.includes(key) ? key : 'custom';
|
||||
// 智能体包里的自定义头像
|
||||
const custom = agent && agent.image && agent.image.avatar;
|
||||
const src = typeof custom === 'string' && custom ? custom : `/assets/avatars/${file}.png`;
|
||||
const img = h('img.avatar-img', {
|
||||
src,
|
||||
alt: name,
|
||||
onerror: (e) => { e.target.src = '/assets/avatars/custom.png'; },
|
||||
});
|
||||
const span = h(`span.avatar${extraClass ? '.' + extraClass : ''}`, { style: `width:${size}px;height:${size}px` }, img);
|
||||
return span;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 文本工具 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function escapeHtml(s) {
|
||||
return String(s == null ? '' : s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
export function fmtTime(iso) {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const now = new Date();
|
||||
const sameDay = d.toDateString() === now.toDateString();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
if (sameDay) return `${hh}:${mm}`;
|
||||
const y = d.getFullYear() === now.getFullYear() ? '' : `${d.getFullYear()}年`;
|
||||
return `${y}${d.getMonth() + 1}月${d.getDate()}日 ${hh}:${mm}`;
|
||||
}
|
||||
|
||||
export function fmtRelative(iso) {
|
||||
if (!iso) return '';
|
||||
const t = new Date(iso).getTime();
|
||||
if (Number.isNaN(t)) return '';
|
||||
const diff = Date.now() - t;
|
||||
if (diff < 60_000) return '刚刚';
|
||||
if (diff < 3600_000) return `${Math.floor(diff / 60_000)} 分钟前`;
|
||||
if (diff < 86400_000) return `${Math.floor(diff / 3600_000)} 小时前`;
|
||||
return fmtTime(iso);
|
||||
}
|
||||
|
||||
export function fmtNumber(n) {
|
||||
if (n == null || Number.isNaN(Number(n))) return '-';
|
||||
const v = Number(n);
|
||||
if (v >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
|
||||
if (v >= 1e4) return `${(v / 1e4).toFixed(2)}万`;
|
||||
return String(v);
|
||||
}
|
||||
|
||||
export function fmtBytes(n) {
|
||||
if (n == null) return '-';
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let v = Number(n);
|
||||
let i = 0;
|
||||
while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
|
||||
return `${v.toFixed(i ? 1 : 0)} ${units[i]}`;
|
||||
}
|
||||
|
||||
export function sleep(ms) {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面级样式注入:每个页面模块自带一段 CSS,用唯一 id 注入一次。
|
||||
* 这样加页面不用动全局 app.css(多人/多页面并行开发时不会互相踩行)。
|
||||
*/
|
||||
export function injectStyles(id, css) {
|
||||
if (document.getElementById(`style-${id}`)) return;
|
||||
const style = document.createElement('style');
|
||||
style.id = `style-${id}`;
|
||||
style.textContent = css;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
export function debounce(fn, ms = 200) {
|
||||
let timer = null;
|
||||
return (...args) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), ms);
|
||||
};
|
||||
}
|
||||
|
||||
export function uid(prefix = 'x') {
|
||||
return `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Markdown(够用就好:标题/列表/代码块/表格/引用/加粗/链接) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function inlineMd(text) {
|
||||
const codes = [];
|
||||
let s = text.replace(/`([^`\n]+)`/g, (_, c) => {
|
||||
codes.push(c);
|
||||
return `\u0000C${codes.length - 1}\u0000`;
|
||||
});
|
||||
s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_, alt, src) => `<a href="${src}" target="_blank" rel="noreferrer">[图片]${alt ? ' ' + alt : ''}</a>`);
|
||||
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
|
||||
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
s = s.replace(/(^|[\s(])\*([^*\n]+)\*/g, '$1<em>$2</em>');
|
||||
s = s.replace(/~~([^~]+)~~/g, '<del>$1</del>');
|
||||
s = s.replace(/\u0000C(\d+)\u0000/g, (_, i) => `<code>${codes[i]}</code>`);
|
||||
return s;
|
||||
}
|
||||
|
||||
function renderTable(rows) {
|
||||
// rows[0] 表头,rows[1] 是 |---|---| 分隔行
|
||||
const head = rows[0].split('|').map((c) => c.trim()).filter((c, i, a) => !(i === 0 && c === '') && !(i === a.length - 1 && c === ''));
|
||||
const body = rows.slice(2).map((line) => line.split('|').map((c) => c.trim()).filter((c, i, a) => !(i === 0 && c === '') && !(i === a.length - 1 && c === '')));
|
||||
const thead = `<thead><tr>${head.map((c) => `<th>${inlineMd(c)}</th>`).join('')}</tr></thead>`;
|
||||
const tbody = `<tbody>${body.map((r) => `<tr>${r.map((c) => `<td>${inlineMd(c)}</td>`).join('')}</tr>`).join('')}</tbody>`;
|
||||
return `<div class="md-table"><table>${thead}${tbody}</table></div>`;
|
||||
}
|
||||
|
||||
/** markdown → HTML 字符串(内容先转义,代码块单独处理) */
|
||||
export function mdToHtml(src) {
|
||||
const text = String(src == null ? '' : src).replace(/\r\n?/g, '\n');
|
||||
const lines = text.split('\n');
|
||||
const out = [];
|
||||
let i = 0;
|
||||
|
||||
const flushParagraph = (buf) => {
|
||||
if (!buf.length) return;
|
||||
out.push(`<p>${buf.map((l) => inlineMd(escapeHtml(l))).join('<br>')}</p>`);
|
||||
buf.length = 0;
|
||||
};
|
||||
const para = [];
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
// 代码块
|
||||
const fence = line.match(/^\s*```(\w*)\s*$/);
|
||||
if (fence) {
|
||||
flushParagraph(para);
|
||||
const lang = fence[1] || '';
|
||||
const code = [];
|
||||
i += 1;
|
||||
while (i < lines.length && !/^\s*```\s*$/.test(lines[i])) { code.push(lines[i]); i += 1; }
|
||||
i += 1;
|
||||
out.push(
|
||||
`<div class="codeblock"><div class="codeblock-head"><span class="codeblock-lang">${escapeHtml(lang || 'code')}</span>`
|
||||
+ '<button class="codeblock-copy" type="button">复制</button></div>'
|
||||
+ `<pre><code>${escapeHtml(code.join('\n'))}</code></pre></div>`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 表格
|
||||
if (/\|/.test(line) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s:|-]*$/.test(lines[i + 1])) {
|
||||
flushParagraph(para);
|
||||
const rows = [line, lines[i + 1]];
|
||||
i += 2;
|
||||
while (i < lines.length && /\|/.test(lines[i]) && lines[i].trim()) { rows.push(lines[i]); i += 1; }
|
||||
out.push(renderTable(rows));
|
||||
continue;
|
||||
}
|
||||
|
||||
// 标题
|
||||
const heading = line.match(/^(#{1,6})\s+(.*)$/);
|
||||
if (heading) {
|
||||
flushParagraph(para);
|
||||
const level = Math.min(6, heading[1].length + 2); // 聊天里 h1 太重,从 h3 起
|
||||
out.push(`<h${level}>${inlineMd(escapeHtml(heading[2]))}</h${level}>`);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 分隔线
|
||||
if (/^\s*(---|\*\*\*)\s*$/.test(line)) {
|
||||
flushParagraph(para);
|
||||
out.push('<hr>');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 引用
|
||||
if (/^\s*>\s?/.test(line)) {
|
||||
flushParagraph(para);
|
||||
const quote = [];
|
||||
while (i < lines.length && /^\s*>\s?/.test(lines[i])) { quote.push(lines[i].replace(/^\s*>\s?/, '')); i += 1; }
|
||||
out.push(`<blockquote>${quote.map((q) => inlineMd(escapeHtml(q))).join('<br>')}</blockquote>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 无序 / 有序列表
|
||||
if (/^\s*[-*+]\s+/.test(line) || /^\s*\d+\.\s+/.test(line)) {
|
||||
flushParagraph(para);
|
||||
const ordered = /^\s*\d+\.\s+/.test(line);
|
||||
const items = [];
|
||||
while (i < lines.length && (/^\s*[-*+]\s+/.test(lines[i]) || /^\s*\d+\.\s+/.test(lines[i]))) {
|
||||
items.push(lines[i].replace(/^\s*(?:[-*+]|\d+\.)\s+/, ''));
|
||||
i += 1;
|
||||
}
|
||||
out.push(`<${ordered ? 'ol' : 'ul'}>${items.map((it) => `<li>${inlineMd(escapeHtml(it))}</li>`).join('')}</${ordered ? 'ol' : 'ul'}>`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line.trim()) {
|
||||
flushParagraph(para);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
para.push(line);
|
||||
i += 1;
|
||||
}
|
||||
flushParagraph(para);
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
/** 把 markdown 渲染进容器,并给代码块挂上"复制"按钮 */
|
||||
export function renderMarkdown(container, src) {
|
||||
container.innerHTML = mdToHtml(src);
|
||||
container.classList.add('markdown');
|
||||
for (const btn of container.querySelectorAll('.codeblock-copy')) {
|
||||
btn.addEventListener('click', () => {
|
||||
const code = btn.closest('.codeblock')?.querySelector('code');
|
||||
copyText(code ? code.textContent : '').then(() => {
|
||||
btn.textContent = '已复制';
|
||||
setTimeout(() => { btn.textContent = '复制'; }, 1200);
|
||||
});
|
||||
});
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 剪贴板 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function copyText(text) {
|
||||
const value = String(text == null ? '' : text);
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return true;
|
||||
}
|
||||
} catch { /* 落到下面 */ }
|
||||
try {
|
||||
// 非 https / 内核页面里 navigator.clipboard 可能不可用,走内核原生钩子
|
||||
if (location.protocol === 'http:' && location.hostname === '127.0.0.1') {
|
||||
const res = await fetch('/api/clipboard', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: value }),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (json.ok) return true;
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
// 最后的退路:textarea + execCommand
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = value;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
return ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Toast / 弹层 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
let toastRoot = null;
|
||||
export function toast(message, opts = {}) {
|
||||
if (!toastRoot) {
|
||||
toastRoot = h('div.toast-root');
|
||||
document.body.appendChild(toastRoot);
|
||||
}
|
||||
const type = opts.type || 'info';
|
||||
const node = h(`div.toast.toast-${type}`, opts.html ? { html: String(message) } : {}, opts.html ? null : String(message));
|
||||
toastRoot.appendChild(node);
|
||||
requestAnimationFrame(() => node.classList.add('on'));
|
||||
const duration = opts.duration || 2600;
|
||||
setTimeout(() => {
|
||||
node.classList.remove('on');
|
||||
setTimeout(() => node.remove(), 220);
|
||||
}, duration);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** 居中弹窗:返回 { el, close }(打开时自动关掉 Esc) */
|
||||
export function openModal(opts = {}) {
|
||||
const wrap = h('div.modal-mask');
|
||||
const box = h('div.modal', { style: opts.width ? `width:${opts.width}px` : null });
|
||||
const head = h('div.modal-head', {},
|
||||
h('div.modal-title', String(opts.title || '')),
|
||||
h('button.icon-btn.modal-x', { onclick: () => close(), title: '关闭' }, icon('x', 18)));
|
||||
const body = h('div.modal-body');
|
||||
if (opts.body) appendChild(body, opts.body);
|
||||
else if (opts.content != null) body.innerHTML = String(opts.content);
|
||||
box.appendChild(head);
|
||||
box.appendChild(body);
|
||||
if (opts.footer) {
|
||||
const foot = h('div.modal-foot');
|
||||
appendChild(foot, opts.footer);
|
||||
box.appendChild(foot);
|
||||
}
|
||||
wrap.appendChild(box);
|
||||
document.body.appendChild(wrap);
|
||||
requestAnimationFrame(() => wrap.classList.add('on'));
|
||||
|
||||
function onKey(e) {
|
||||
if (e.key === 'Escape') { e.stopPropagation(); close(); }
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
wrap.addEventListener('mousedown', (e) => { if (e.target === wrap && !opts.persistent) close(); });
|
||||
|
||||
let closed = false;
|
||||
function close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
wrap.classList.remove('on');
|
||||
setTimeout(() => wrap.remove(), 180);
|
||||
if (opts.onClose) opts.onClose();
|
||||
}
|
||||
return { el: box, body, close };
|
||||
}
|
||||
|
||||
export function confirmBox(opts = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const finish = (v) => { if (done) return; done = true; modal.close(); resolve(v); };
|
||||
const modal = openModal({
|
||||
title: opts.title || '确认',
|
||||
width: opts.width || 420,
|
||||
body: h('div.confirm-body', {},
|
||||
h('div.confirm-text', String(opts.message || '')),
|
||||
opts.hint ? h('div.confirm-hint', String(opts.hint)) : null),
|
||||
footer: h('div.modal-actions', {},
|
||||
h('button.btn', { onclick: () => finish(false) }, opts.cancelText || '取消'),
|
||||
h(`button.btn.primary${opts.danger ? '.danger' : ''}`, { onclick: () => finish(true) }, opts.okText || '确定')),
|
||||
onClose: () => finish(false),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function promptBox(opts = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const input = opts.multiline
|
||||
? h('textarea.input.textarea', { rows: 5, placeholder: opts.placeholder || '' })
|
||||
: h('input.input', { placeholder: opts.placeholder || '', value: opts.value || '' });
|
||||
if (opts.multiline) input.value = opts.value || '';
|
||||
const finish = (v) => { if (done) return; done = true; modal.close(); resolve(v); };
|
||||
const modal = openModal({
|
||||
title: opts.title || '输入',
|
||||
width: opts.width || 480,
|
||||
body: h('div.prompt-body', {}, input),
|
||||
footer: h('div.modal-actions', {},
|
||||
h('button.btn', { onclick: () => finish(null) }, '取消'),
|
||||
h('button.btn.primary', { onclick: () => finish(input.value) }, opts.okText || '确定')),
|
||||
onClose: () => finish(null),
|
||||
});
|
||||
setTimeout(() => input.focus(), 30);
|
||||
if (!opts.multiline) {
|
||||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') finish(input.value); });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 下拉菜单:items = [{label, icon, danger, disabled, hint, onClick}] */
|
||||
export function openMenu(anchor, items, opts = {}) {
|
||||
closeAllMenus();
|
||||
const menu = h('div.menu');
|
||||
for (const item of items) {
|
||||
if (item === '-') { menu.appendChild(h('div.menu-sep')); continue; }
|
||||
menu.appendChild(h(`button.menu-item${item.danger ? '.danger' : ''}`, {
|
||||
disabled: item.disabled ? 'disabled' : null,
|
||||
onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (item.disabled) return;
|
||||
closeMenu();
|
||||
item.onClick && item.onClick();
|
||||
},
|
||||
}, item.icon ? icon(item.icon, 16) : null, h('span.menu-label', String(item.label || '')), item.hint ? h('span.menu-hint', String(item.hint)) : null));
|
||||
}
|
||||
document.body.appendChild(menu);
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const mw = menu.offsetWidth;
|
||||
const mh = menu.offsetHeight;
|
||||
let x = opts.alignRight ? rect.right - mw : rect.left;
|
||||
let y = rect.bottom + 6;
|
||||
x = Math.max(8, Math.min(x, window.innerWidth - mw - 8));
|
||||
if (y + mh > window.innerHeight - 8) y = Math.max(8, rect.top - mh - 6);
|
||||
menu.style.left = `${x}px`;
|
||||
menu.style.top = `${y}px`;
|
||||
requestAnimationFrame(() => menu.classList.add('on'));
|
||||
|
||||
let closed = false;
|
||||
function closeMenu() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
document.removeEventListener('mousedown', onDoc, true);
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
menu.remove();
|
||||
}
|
||||
function onDoc(e) { if (!menu.contains(e.target)) closeMenu(); }
|
||||
function onKey(e) { if (e.key === 'Escape') closeMenu(); }
|
||||
document.addEventListener('mousedown', onDoc, true);
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
|
||||
return { el: menu, close: closeMenu };
|
||||
}
|
||||
|
||||
function closeAllMenus() {
|
||||
for (const m of document.querySelectorAll('.menu')) m.remove();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 表单小部件 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function switchEl(opts = {}) {
|
||||
const input = h('input.switch-input', { type: 'checkbox' });
|
||||
input.checked = !!opts.checked;
|
||||
if (opts.onChange) input.addEventListener('change', () => opts.onChange(input.checked));
|
||||
const label = h('label.switch', {}, input, h('span.switch-track', {}, h('span.switch-thumb')));
|
||||
if (opts.disabled) { input.disabled = true; label.classList.add('disabled'); }
|
||||
return label;
|
||||
}
|
||||
|
||||
export function fieldRow(label, control, hint) {
|
||||
return h('div.field-row', {},
|
||||
h('div.field-label', {},
|
||||
h('div', String(label)),
|
||||
hint ? h('div.field-hint', String(hint)) : null),
|
||||
h('div.field-control', {}, control));
|
||||
}
|
||||
|
||||
export function sectionTitle(text, extra) {
|
||||
return h('div.section-title', {}, h('span', String(text)), extra || null);
|
||||
}
|
||||
|
||||
export function spinner(size = 16) {
|
||||
return h('span.spinner', { style: `width:${size}px;height:${size}px` });
|
||||
}
|
||||
|
||||
export function typingDots() {
|
||||
return h('span.typing-dots', {}, h('i'), h('i'), h('i'));
|
||||
}
|
||||
|
||||
export function emptyState(iconName, title, desc, action) {
|
||||
return h('div.empty-state', {},
|
||||
h('div.empty-state-icon', {}, icon(iconName, 26)),
|
||||
h('div.empty-state-title', String(title || '')),
|
||||
desc ? h('div.empty-state-desc', String(desc)) : null,
|
||||
action || null);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 滚动 / 输入框 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function scrollToBottom(container, smooth = false) {
|
||||
if (!container) return;
|
||||
container.scrollTo({ top: container.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
|
||||
}
|
||||
|
||||
export function autoGrow(textarea, maxHeight = 200) {
|
||||
const resize = () => {
|
||||
textarea.style.height = 'auto';
|
||||
const next = Math.min(maxHeight, textarea.scrollHeight);
|
||||
textarea.style.height = `${next}px`;
|
||||
textarea.style.overflowY = textarea.scrollHeight > maxHeight ? 'auto' : 'hidden';
|
||||
};
|
||||
textarea.addEventListener('input', resize);
|
||||
resize();
|
||||
return resize;
|
||||
}
|
||||