Compare commits

...

23 Commits

Author SHA1 Message Date
l
91a4ba2ab4 v2.0.83 —— 数值和状态直接显示在智能体卡片上
## 卡片上现在长这样

```
┌──────────┐
│  缩略图   │
│  豆包     │
│ 好感度 72 │   ← 第一条数值
│ ▓▓▓▓▓▓░░ │   ← 迷你进度条(3dp,一眼看出比例)
│ 庇佑·中毒 │   ← 身上挂着的状态
└──────────┘
```

不用点进去,看列表就知道每个角色现在什么情况。

## 几个设计取舍

**只显示第一条数值**。卡片只有 96dp 宽,把整个数值表塞进去等于把
[状态数值] 页压成邮票——谁也看不清。卡片要回答的只是"这个角色现在什么情况",
想细看就点进去。

**没挂规则包的智能体不显示任何东西**。不显示一个空的"数值"标题——
那只会让人以为坏了。

**状态用绿色、数值用金色**,和状态数值页的视觉对得上。

## 为此加的批量接口

卡片要显示数值,就得**一次拿到所有智能体**的。原来只有单个接口
(`GET /api/agents/<id>/stats`),N 个智能体就是 N 次往返,而每次都重算
区间、查状态表——列表会被拖垮。

新增 `GET /api/agents/stats`:

- 只返回**挂了规则包**的智能体
- **不带 `statusDefs`**(那是"能加哪些状态",只有点进状态数值页才需要,
  卡片用不上,白传一遍)
- 按 `worldviewId` 缓存包查询——同一世界观下的智能体共用一个包,
  不该为 N 个智能体把同一个世界观查 N 遍

## 验证

**模拟器实测**(`emulator-5558`)截图见
`docs/screenshots/agent-card-stats.png`:豆包卡片显示「好感度 72 + 进度条 +
庇佑 · 中毒」,其他三张卡片干净。

**探针**加了 5 条断言:批量接口能读、只含挂了规则包的、带数值、带状态、
**不带 statusDefs**。八个探针全绿。
2026-10-17 17:40:39 +08:00
l
5a65320a5d feat(web): 电脑端补齐 AI 界面能力(show_ui / ask_user / end_conversation)+ 收尾
背景:这三个工具以前只有安卓能用(走 Kotlin NativeBridge),电脑/网页端
一律回"当前环境没有界面能力",是 Web 端和 App 之间最后一块功能差距。
(核心实现已随 946bf8b 那批一起入库,这里补的是收尾与文档/截图。)

## 做法:内核开一条 HTTP 界面队列(浏览器与 exe 共用,不需要原生桥)
- 内核(工具线程阻塞)→ GET /api/device/pending → 网页 700ms 轮询
- 网页弹界面(ask_user=选择弹窗;show_ui=iframe 渲染 AI 写的 HTML)
- POST /api/device/answer → 用户操作送回内核 → 工具继续跑(wait 语义完整保留)
- FIFO 队列(上限 8),不再"新请求顶掉旧请求"
- show_ui 同时 store.save_screen() 落盘 → /api/screens 在电脑端也有数据,可重新打开
- end_conversation 由内核直接落盘(会话 ended + 原因),网页显示"这次对话已结束"并锁输入框
- iframe 用 sandbox + 注入 Doubao.sendToAi/close 桥(postMessage),AI 的 HTML 拿不到内核接口

## 顺手修的
- kernel:对浏览器关连接(WinError 10054)不再刷一屏 traceback
- 聊天页:toolTrace 里看到 end_conversation 成功后重新拉会话,显示结束提示
- 「AI 界面」页文案更新(电脑端现在也有写入方了)

## 验收
- node scripts/verify-ui-bridge.mjs → 11/11(ask_user/show_ui wait 两态/end_conversation/404)
- node scripts/verify-web-ui.mjs → 14/14 页
- exe 真窗口实测:ask_user 弹窗正常(docs/screenshots/exe2-ai.png)
- docs/网页版.md 新增 §5.1 通道说明与 3 条踩坑;docs/kernel-api-misc.md §5 加更新说明
2026-10-17 17:36:08 +08:00
l
946bf8bc55 v2.0.82 —— 界面加状态管理:能看、能清、能手动挂
## 你说「界面加个状态管理」,做出来是这样

进 **[状态数值]** 页(三个入口任一),状态那一节现在是可操作的:

```
状态
  中毒   剩 3 轮                    [清掉]
  庇佑   持久                        [清掉]

加一个
  中毒   定时 · 3 轮后消失           [挂上]
```

- **清掉**:每条状态一个按钮
- **加一个**:包里有还没挂上的状态时自动出现,点一下直接挂

## 为什么这个必须做

AI 手里**只有 `grant_status`(只能加)**,**没有任何工具能移除状态**。
所以之前:

- `persistent` 状态一旦挂上,**永远下不来**
- `timed` 的状态想立刻清掉,只能干等它自己轮完

用户是规则的主人,这说明不过去。现在补上了 —— 内核加两个动作
(`addStatus` / `dropStatus`),界面给了出口。

**兼容性**:`action` 缺省时保持老行为(改数值),老客户端不受影响。

## 顺手补的第三个入口

`AgentStatsScreen` 的注释一直写着「三个入口:聊天页状态栏 / 智能体编辑的
它的状态 / 群成员的状态」,但**中间那个从来没做出来**:

智能体编辑页的「它的状态」标题下面只有**记忆**和**用量**两个按钮,
状态数值那个按钮压根没加 —— 用户在群里能点到「状态」,在编辑页点不到。

现在加了「看它的数值和状态」。

## 验证

**接口层**(探针第 26 节,11 条断言,走真实 HTTP 路径):
手动挂状态、持久状态记 -1、清定时状态、**清持久状态**、
加没定义的状态报 404、不带 action 仍改数值。

**界面层**(模拟器 `emulator-5558`,真点):
```
点「清掉」→ 中毒消失,「加一个」区块自动出现并列出「中毒」
点「挂上」→ 中毒回来,「加一个」自动消失
```

八个探针全绿。
2026-10-17 17:29:01 +08:00
l
050a3b2385 feat(web): 网页版 v2 —— 豆包网页端风格 + 与 App 共用同一份 Python 内核
## 一、界面:从 Lynx 手机壳换成豆包网页版风格的真 Web 前端
- web/ 重写为纯静态 HTML/CSS/JS(无构建步骤):侧栏 280(#f9f9f9) + 内容列 1000 居中、
  空态问候语 28/600、输入框 1000x100/圆角 24/聚焦细蓝边、品牌蓝 #06f、暗色 token 全套
- 尺寸/配色是对着真实豆包网页版(www.doubao.com/chat 1440x900)抓取镜像逐像素量的,
  规范见 docs/豆包网页版-风格规范.md;图标全部本项目手写 SVG(web/js/icons.js,74 个)

## 二、内核:不再维护第二套,Web/exe 直接跑 android/kernel
- 桌面 exe 内嵌 python.org embeddable Python 3.13(runtime/python),起 Python 子进程
- Electron 主进程 + 原生能力桥(选文件/剪贴板/在资源管理器显示),对应内核 --desktop-bridge
- 新增内核静态路由:web/ 下的 /assets /js 等由内核直接托管
- 旧 Lynx 版(app/ + server/)保留为历史存档,命令见 README §9

## 三、功能同步(与安卓 App 同一份后端)
对话流式/思考/工具轨迹/附件/朗读/语音输入/群聊与交接条、智能体增删改与导入导出、
记忆与情绪、Token 用量、世界观/Skill/全局模型/规则包、Python 工具与 MCP、笔记、
AI 界面、会议模式(一期:列表/运行/结果/历史)、设置(10 家提供商/22 项超时)、我的/关于

## 四、文档与验收
- docs/网页版.md:架构、功能对照矩阵、已知差距、踩坑
- docs/kernel-api-chat.md / agents.md / misc.md:接口契约(按真实内核探测写出)
- scripts/verify-web-ui.mjs:起临时内核逐页截图 + 收集 JS 报错 → 14/14 页通过
- scripts/build-exe.mjs:自动下载嵌入式 Python、组装 runtime、electron-packager 打包(390MB)
- scripts/scrape-doubao-web.mjs:豆包网页版抓取可复现(reference/ 不入库)
2026-10-17 17:02:57 +08:00
l
ab8296901d v2.0.81 —— 修「群聊删不了人」+ 世界观能挂数值状态包了(附教程)
## 一、群聊删不了人:两处都修了

**① 内核还留着"主智能体不能移出"**

你早就要求「群聊去掉主人设定」,界面上也写了「谁都能移出」——
但内核 `remove_member` 里还留着 `aid == host_id(c)` 的拦截,
于是**第一个进群的人删不掉**(点了没反应)。

现在唯一的拒绝条件是"不能删到一个人不剩";删到剩 1 个会**退回单聊**
(`type` 一起改回去,不然界面还按群聊渲染、仲裁还按群聊跑)。

**② `invite_agent` 的「需确认」被绕过**

它排在"单聊 → 转群聊"那个分支**后面**,所以单聊里拉人时
直接把人拉进来了,配置的"拉起需要确认"完全没生效。现在排到最前面。

**③ 顺便**:删除失败时的提示还是"主智能体不能被移出",
那条规则已经废了,改成如实说「群里没这个人,或者就剩他一个了」。

## 二、世界观能挂数值状态包了(之前整条链路是断的)

规则包挂在**世界观**上(`world.rulePackId`),内核那条链路一直是通的,
但**世界观编辑界面没有这个入口** —— 也就是说:

> 你在「资源 → 规则包」里辛苦写完数值和状态,回来发现**没有任何地方能启用它**。

现在世界观编辑页加了「数值状态包」选择器(列出所有包 + 各自有几条数值/状态/
带不带脚本 + 「不挂」选项)。链路终于闭环:

```
资源 → 规则包(建包)→ 世界观挂上它 → 智能体绑这个世界观 → 有数值了
```

## 三、新增两个文档

- **`docs/Python脚本.md`** —— 六处跑 Python 的地方和它们的权限边界
- **`docs/数值状态系统-教程.md`** —— 手把手跑通「好感度 + 中毒」:
  链路、字段含义、脚本三个入口、常见问题,以及**最快四步清单**

教程里如实标注了一个已知缺口:**AI 只有「加状态」没有「移除状态」**
(`persistent` 状态挂上后界面上没有一键清掉的地方)。

## 四、测试

这次按你说的**用模拟器测**(`emulator-5558`,Android 14 / x86_64),
在真实数据上验证删人:

```
群成员: ['豆包', '文案师']
删第一个人 豆包(以前删不掉的那位)
  HTTP 200  → 剩: ['文案师']  type= single
删最后一个(应被拒绝)
  HTTP 400  移不出去(群里没这个人,或者就剩他一个了)
```

界面上也确认了:点「移出」→ **2 个人在群里 → 1 个人在群里**。

八个探针全绿(`probe-group-chat` 里三条过期断言已按新语义更新)。
2026-10-17 16:25:20 +08:00
l
c09df1d0a2 docs: 新增《Python 脚本》—— 六处跑 Python 的地方和它们的权限边界
这个仓库有六类地方会跑 Python:AI 的 python_run / shell、规则脚本、
会议 Python 节点、自定义节点、内置 Termux。它们的权限和兜底手段完全不同,
混着看会出事(以为规则脚本能读文件、或者以为 python_run 有沙箱)。

文档把每处的:谁能写 / 能做什么 / 兜底手段 / 超时键 / 安全边界 列成表,
并给了规则脚本三个入口的签名和示例、自定义节点的声明格式和三条语义。

结论一句话:只有规则脚本有沙箱,而它挡得住手滑、挡不住有意。
2026-10-17 16:02:28 +08:00
l
31c62fafc2 v2.0.80 —— 群聊里 AI 能看到谁说的 + talk_to 多目标 + 私聊
## 一、智能体能读到群里所有人的发言了

以前送进模型的 `history` 只有 `role` / `content` —— 群里**别人说的话**,
模型根本分不清是谁说的,只能当成自己说过或用户说过。

现在群聊时,送给模型的每条消息前面都标上发言人:

```
[用户] @寐眠 你们聊聊
[小黑] 我哪句是打岔,哪句是问号,哪句是逗号——我记性好
[寐眠] 你打的是「你们」。我知道,你打的时候大概是想把两个都算进去
```

(只在**送给模型的那份**上加,落库的正文和界面显示都还是干净的。)
顺带在 skill 里写清楚:「你能看到群里所有人的发言,别把别人的话当成自己说过。」

## 二、talk_to 一次可以找好几个人

```
talk_to(agents=["小黑", "寐眠"], content="你们都说说")
```

目标会**挨个**回话 —— 移交状态带队列,界面逐个接下去(自动模式直接跑,
手动模式每轮都出「让他说 / 停在这」)。

为了兼容老写法,`agent="名字"` 仍然能用,等价于只找一个人。

## 三、talk_to 加私聊:只有目标知道

```
talk_to(agent="寐眠", content="别告诉小黑", private=true)
```

- 这条消息**只有目标智能体**能看到;
- 内核组装 history 时按「是不是给我的」过滤掉,所以**别的 AI 真的看不到**;
- **你(用户)照样看得到** —— 你是观察者,不能连自己都瞒着。
  skill 里也这么写了:「别以为私聊就可以说见不得人的话」。

## 四、顺手

- 探针里三条**旧断言**过期了(`talk_to` 参数从「agent+content」扩成
  `agents`/`agent`/`content`/`private`;移交状态多了 `queue`)—— 已更新,
  不是放宽标准,是接口真的变了。

## 验证

八个探针全绿;`probe-group-chat` 新增第 21 节共 8 条断言,
覆盖:多目标参数、私聊参数、移交队列、新一轮清队列、
送模型的历史带发言人、别人的私聊被过滤。
2026-10-17 14:46:49 +08:00
l
7498810c70 v2.0.79 —— 修「加人没反应」:那个接口一直是 404
## 根因:路由被自己的解析函数挡住了

你说「加人界面点了没反应,人也没加到」。查下来是**接口根本没通**:

```
POST /api/conversations/<id>/members  →  404 {"error": "未知接口 ..."}
```

不是路由没写 —— 是它用 `_match_id(pathname, '/api/conversations/')` 去解析 id,
而那个函数的规则是**「id 后面不能有斜杠」**:

```python
rest = pathname[len(prefix):]
if not rest or '/' in rest:
    return None          #  ← /api/conversations/<id>/members 的 rest 是 "<id>/members"
```

所以 `member_id` 永远是 `None`,**整个成员分支永远进不去**,落到最后就是 404。
界面拿到失败,表现就是"点了没反应、人也加不上"。

修:这个分支自己解析 id,不碰 `_match_id`。

**实测**(直接打接口,不经界面):
```
群里现有: ['数据分析', '豆包', '代码搭子', '文案师']
要加:     黑化豆包
HTTP 200 -> 现在成员: [... , '黑化豆包']
```

## 顺便修好的两件(上一版没生效的)

- **未绑世界观的智能体可以拉**:它没有设定会串,和谁都合得来。
  上一版我写成"世界观必须相等",于是「黑化豆包」这种没绑的也进不来。
- **被世界观挡下的人会列出来**并说明原因,不再"凭空消失"。

另外界面那个「加人」面板确实会展开(点了变「取消」+「拉谁进来」),
之前看不到候选就是因为上面的接口 404 + 过滤条件太严。

## 验证

八个探针全绿;`probe-group-chat` 新增第 20 节,
专门守「成员增删路由不能用 `_match_id`」—— 别再退回去。
2026-10-17 14:26:42 +08:00
l
57a9ff4ea1 v2.0.78 —— talk_to 说得出话、群聊能拉更多人、只能拉同世界观
## 一、talk_to 那句「话」现在真的说出来了

你报「talk_to 没有内容呀」—— 我查了库,那句话**其实一直在**,
但有**两处**让它显得像空的:

1. **`talk_to` 的返回值没回显说了什么**。模型只看到
   「你已经对他说了这句话」,看不到自己的正文落在哪儿,
   于是它自己在回复里写「这条是空的,我猜是想看我把 talk_to 真跑一遍」,
   然后反复重试。现在返回值里带上 `content`。
2. **更根本的一处**:自动续轮时界面传的 `message` 是空串,
   而内核**还是给模型追加了一条空的 user 消息** ——
   模型看到的是"用户刚发了一条空消息",当然会说「我这边没收到内容」。
   真机原话就是这么写的。

   现在续轮不再追加空消息,改成一句**不落库**的极短指令
   (「现在轮到你接着说」),模型就知道该接话、而不是以为用户发了空。

真机实测:`talk_to` 落的那句已经明明白白出现在对话里 ——
`[数据分析] 在的话回一句「文案师收到」,顺便报一下你现在什么状态。`

## 二、群聊能拉更多人了

你说「群聊只能拉两个」。内核和 `add_member` **都没有人数上限**,
是**界面每加一个人就自动收起**(`adding = false`)——
你得再点一次「加人」才能加下一个,体感就是只能拉两个。

现在加完**保持展开**,点一个加一个。

## 三、确实只能拉同世界观的

你说得对,这条规则是对的,我之前把提示删掉是错的 —— 现在**内核和界面都管**:

- 内核 `group_chat.add_member` 直接拒(不是只有界面拦)
- 界面**先把不同世界观的筛掉**,并说明为什么("拉进来会串设定")

理由不只是洁癖:群聊上下文里有 `<worldview>` 段、共享记忆也按世界观分空间,
世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。

## 四、更新了 skill(提示词)

你说「智能体好像不怎么会用」—— 工具描述只讲"怎么调",
而模型最容易错的是"**什么时候该用哪个**"。所以在内置 skill 里加了一段:

- 想主动对某个智能体说一句**具体的话** → `talk_to(agent, content)`
- **不要**拿 `pass_turn` 当"跟他说话"(它只交发言权、不带内容,对方接到一片空白)
- 一轮最多一次,两个工具二选一
- 单聊里没有"别人"

## 验证

八个探针全绿(新增第 19 节,专门守「提示词里必须教 talk_to 怎么用」)。
真机(Android 16 / arm64)实测群聊 4 人(同世界观)能正常接话。
2026-10-17 12:20:51 +08:00
l
ab063d0674 v2.0.77 —— AI 对聊由你决定传递或停止 + 工具记录不再丢 + 死亡不锁输入框
## 一、talk_to 改成「你选择传递或停止」,另有自动模式

你的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。

以前 AI 交了话界面**自动**就往下续,你插不上手。现在:

- **默认(手动)**:群里 AI 用 `talk_to` / `pass_turn` 把话交给别人后,
  输入框上方出现一条

  > 小黑 把话交给了 寐眠    [让他说] [停在这]

  由你决定接着聊还是打住。
- **自动模式**:设置 →「对话」→「AI 对聊自动模式」打开,
  不用确认,自动一轮轮接着跑(最多几轮)。

顺带把「烧钱」这件事堵上了:默认不会自己一直聊下去。

## 二、工具记录不再重启就丢

界面上那些工具卡片(调了什么、成没成、返回什么)以前**只有流式那一刻**
能看到 —— 因为这份明细从来没落过库。你说的「工具怎么重启就不显示了」就是这个。

现在三层都补上了:

- `agent_loop` 收集 `tool_trace`(只留 id / name / ok / result,result 截断 800 字,
  不然一条消息能撑爆会话 JSON)
- `app.py` 落进消息
- 客户端 `toMessage()` 解析(`ok` 保留三态,别把"没值"读成失败)

## 三、角色死亡不再锁死整个群聊的输入框

原来只要**对话主人**死了,输入框整条被换成「已经死亡,不能对话」——
可群里还有别人能接话(内核的 `resolve` 会把死人跳过、换下一个人)。

现在:

- **单聊**:照旧拦住 + 给「去复活」(主人没了就是没了)
- **群聊**:只留一行提示「小黑已经死亡 —— 群里其他人还能接话」,**输入框照给**

## 四、顺带

`speaker` 事件到达时把发言人补进**正在生成的这条消息** ——
它是流式期间客户端自己建的、`agentId` 是空的,不补的话消息标签和朗读音色
会一起退回「对话主人」(上一版报的「还是没换」)。

## 验证

- 真机(Android 16 / arm64)实测:点 `@寐眠` 不发送 → 顶栏仍是小黑;
  发送后内核仲裁 → 顶栏、头像、背景一起变寐眠。
- 八个探针全绿;`probe-agent-system` 新增第 25 节专门守「工具明细要落库」
  (三处缺一处都算失败)。
2026-10-17 02:06:17 +08:00
l
3d5c02e7a9 v2.0.75 —— 群聊去掉主人 + 背景跟对话走 + @ 谁就该谁答
## 一、群聊去掉主人设定

你说得对,群里不该有老大。

**内核**:兜底发言从「永远是会话发起者」改成**按顺序轮** ——
看最近一条 AI 消息是谁说的,下一个人接上(`group_chat.rotate_next`)。
被 @ 的人不在场、移交目标已死亡,也都是"换下一个人",不再"回主智能体"。

**界面**:

- 点名条不再标「(主)」
- 成员页去掉了「主智能体」徽章和"没人被 @ 的时候由它接话"那句
- 谁都能移出(原来主智能体移不掉)—— 既然没有主人,就没有动不了的那一个

## 二、背景跟「当前对话」走(这次是真换过来了)

上一版我用了 `vm.activeAgent`,那玩意儿其实来自内核 `/api/state` 的
`settings.activeAgentId` —— **全局设置**,默认 `a_doubao`,
意思是"用户最后一次选了哪个智能体",**不是**这条对话的主人。
所以切到别的对话,背景还是上一个的。

现在改成读**会话自己的 `agentId`**(为此给客户端 `Conversation` 补了这个字段,
内核一直在返回它)。

## 三、@ 谁就该谁答(上两版修的是两个不同的原因)

- **原因一**:群聊仲裁要读「用户这一轮 @ 了谁」,但代码是**先仲裁、后落库**,
  本次消息还没进库 → 读到的是**上一次**的话。(改用本条消息)
- **原因二**:那条回复是**流式期间客户端自己建的**,`agentId` 是空的,
  而它不会跟着 `refresh()` 更新 → 名字标签和朗读音色一起退回"当前对话的主人"。
  (`speaker` 事件到达时把发言人补进这一条)

内核里那条消息的 `agentId` 一直是**对的**(寐眠),错的是界面这一侧 ——
所以你怎么看都不对。两个都修完,真机实测 `@寐眠` → 标签、音色都是寐眠。

## 四、踩到的两个自己的坑

- **构建早于编辑**:我改完代码没重新构建就装机,验证时"改了没生效",
  查了半天代码 —— 源文件时间 1:22、APK 时间 1:17,一眼就能看出来。
- 探针里两处**半角引号**写进中文字符串,把字符串截断了(SyntaxError)。

## 验证

八个探针全绿(群聊那节 24 条断言,新增第 18 节「按顺序轮」)。
真机(Android 16 / arm64)实测:点名条已是 `@小黑` `@寐眠`(无「(主)」)。
2026-10-17 01:31:15 +08:00
l
4ed6c6a4ee fix(group): @ 谁就该谁答 + 背景跟对话走 + talk_to 工具(v2.0.74)
用户连着报了五条,其实根子集中在两处:

1. 「@ 的时候立即切换」「背景和智能体对不上」「声音对不上」
   —— 三个症状,一个根因:**仲裁在前、落库在后**。
   群聊仲裁要读「用户这一轮 @ 了谁」,但本次这条消息还没写进库,
   于是拿 raw_history 里最后一条 user(= **上一次**说的话)去匹配,
   没匹配到就兜底给主智能体 → 我 @ 寐眠,回答的却是小黑。
   消息的 agentId 是小黑 → 名字标签是小黑、朗读音色也是小黑,
   而 AI 自述是寐眠、背景又跟着 @ 切了 → 三处全对不上。
   修:仲裁用**本条**消息(autoContinue 那几轮没有新消息,才回退历史)。

2. 「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」
   背景层原来跟 currentSpeakerId 走,是我理解反了。
   背景表达的是「这个场景是谁的」(和顶栏同一个来源),
   改成 activeAgent —— 和顶栏天然一致。
   「谁在说话」是**每条消息**自己的事(msg.agentId),两者不是一回事。

3. 新增 talk_to 工具(用户要求:智能体主动调用工具和别的智能体聊,
   参数就是「智能体 + 内容」)
   pass_turn 只交发言权、**不带内容** —— 对方接到一片空白,聊不起来。
   talk_to 把话落进对话(发言者是本人)再把发言权交出去,
   界面据此自动续一轮让对方回应。单聊/空内容/一轮两次都会被拒。

顺带:_handle_chat 给自动续轮放行空消息(原来每一轮都被打回 400,
界面上是一屏「出错了:消息为空」)。

探针:group-chat 加了第 14~17 节共 20 条断言。八个探针全绿。
2026-10-17 01:10:33 +08:00
l
f665b83b34 docs: 坑表补「能力全都在,缺最后一个按钮」 2026-10-17 00:16:04 +08:00
l
1c07e37932 feat(chat): 整屏立绘背景 + 群聊四项(v2.0.73)
用户一次报了五件事,逐条对照:

1. 整个背景都是角色卡 / 就头像是立绘
   以前立绘只在空对话时露一个 168dp 的圆,一开聊就只剩顶栏 24dp 头像。
   新增 ChatBackdrop:背景图 + 立绘铺在消息下面,群聊跟着说话者换。
   空对话那个圆形立绘去掉(重复,且圆形 Crop 会裁到腰上)。

2. 立绘不要透明的 + 聊天框半透明
   这一对是配套的:立绘实心(可读性交给气泡),气泡半透明
   (新增 doubaoBubbleVeil / doubaoBubbleMine)。

3. 群聊和对话要分开
   抽屉里按 isGroup 分两组,单聊那组空时给一句引导。

4. 群聊时不同智能体的语音不会切换
   内核一直在消息里存 agentId(群聊仲裁后的发言者),客户端从来没读。
   ChatMessage 加 agentId + toMessage 解析;SpeakController 的 speak /
   maybeAutoRead 按这条消息的发言者挑音色。顺手补上 store.append_message
   漏掉的 agentId(AI 主动发的那条)。

5. 智能体可以和群聊中另一个智能体对话 + 可中断
   · 群聊里 A pass_turn 给 B 之后,界面自动续一轮(autoContinue,
     内核据此不追加用户消息),最多 3 轮
   · chatJob 这个取消句柄一直存在、内核也一路支持 cancelled,
     但没有任何界面调它 —— 现在生成中右侧圆钮变「停止」

探针:group-chat 加第 13、14 节,并验证过撤掉修复会变红。八个探针全绿。
2026-10-17 00:15:02 +08:00
l
daccc3fd10 fix(assets): 手机大图传不上去(请求体上限 4MB + 错误信息误导 + 换图自删)
真机报「背景图设置不了」——选相册里的照片,那行还是显示「空」。
三个原因叠在一起:

1. 照片 30~55MB,base64 后 38~73MB,撞上 read_json_body 的默认 4MB 上限
2. 异常被 body() 吞成空 dict,报出来的是「不认识的外观槽位」
3. 失败只闪一句「这张图没传上去」

修:
- 新增 ui/ImagePick.kt:位图按最长边 1600 采样(28.9MB → 774KB),
  GIF/SVG 不压(丢动画 / 毁矢量);读图整体挪进 ViewModel 的 IO 线程
- agent_api:上传类接口统一 UPLOAD_BODY_LIMIT(图片 + 四种包导入)
- body() 失败时把原因挂到 handler,_set_asset 如实报,不再伪装成槽位错
- _drop_replaced:换图时新旧同路径不删(否则同一张图传第二次会把自己删掉)
- AppViewModel:两个 upload 都把服务端原因显示出来
  (世界观那个原来把 runCatching 结果整个丢掉了)

探针加第 23、24 节共 19 条断言,并验证过撤掉修复会变红。八个探针全绿。
真机(Android 16/arm64)实测:28.9MB → 774KB,连传两次文件都在。
2026-10-16 22:53:49 +08:00
l
e62dd7b87b fix(ui): 上传成功但页面没变化 + 回话消失(v2.0.71)
用户连报三个现象,根因是两个,都找到了。

## ① 上传成功但页面没变化

图**确实存下来了**(用户截图里编辑页五档显示了不同的图就是证据),
问题在**界面读不到**:

    /api/state 的形状:  { id, name, image: {...}, portrait: "路径" }
                                                  ↑ **顶层**
    Kotlin 却在这里读:  optJSONObject("image").toAgentImage().portrait
                                                          ↑ 从 image 里面读

`portrait` 是内核在顶层拼上去的,`image` 对象里没有这个键 →
永远解析成空 → 界面一直回退到内置默认人物。

**编辑页为什么能显示**:它读 `image.front`(五档表本身),那条路是对的。
"编辑页有图、列表和聊天页没图"这个矛盾就是这么来的。

**修**:`toAgent()` 把顶层的 `portrait` 补进 `AgentImage`。

★ 真机验证:传一张红色测试图给豆包 → **列表缩略图变成红色** ✓

## ② 回话直接消失

    is StreamEvent.Rebased -> { openConversation(event.conversationId) }

`openConversation` 先 `messages.clear()` 再拉服务端 —— 可这时候**回复还没落盘**,
拉回来是空的;流还在继续往 `messages` 追加,**清空就再也回不来了**。

表现:发一句 → 看到回复 → **它自己没了**。

**修**:只换 id,不调 `openConversation`。顺带加一行提示 + 「知道了」。

## ③ 顺带:背景/边框位置显示人物照

`AssetRow` 空时统一显示 `agent_default_character`。立绘显示它是对的,
但背景图/边框为空时显示人物照是误导(用户截图里那三行都有人物照)。
**修**:只有立绘显示,那三个写「空」字。

## 验证

真机:豆包缩略图 = 传入的图;未传图的仍默认。八个探针全绿。
2026-10-16 21:42:40 +08:00
l
8ccf009958 fix(v1.2): 立绘传不上去(500)+ 已设的图丢失(v2.0.70)
用户报的两个问题都是真的,而且都是**上次改五档立绘时引入的**。

## ① 角色图设置不了 —— 接口直接 500

真机实测 `POST /api/agents/<id>/asset` → 500。本地复现拿到 traceback:

    File "agent_api.py", line 1213, in _set_asset
        base, _, slot = key.partition(':')
    NameError: name 'key' is not defined

改五档槽位(`front:喜`)时**把 `key = str(body.get('key')...)` 删掉了**。
所以**任何**立绘/背景/边框都传不上去。

## ② 已设的图丢失 —— 值被字符串化

同一个改动漏了另一半:`_apply_agent_patch` 对 `image` 的**每个值**调 `_as_text`。
`image` 以前只有字符串(文件名),但 v1.2 的立绘是**五档字典**,于是磁盘上变成:

    "front": {"平常": "{'平常': 'C:\\...\\a.png'}"}

· 回退链读不到(档位取不出来)
· **每读写一次多包一层**,最后 `os.path.isfile` 失败

★ 上次只改了 `_apply_resource_patch`(规则包 `info` 踩过同一个坑),
  **漏了这个姐妹函数** —— 两处同一段逻辑抄了两份。现在都用 `_json_safe`。

## 老数据能救回来

`normalize_image` 会**解套**:字符串化的字典用 `ast.literal_eval` 解回
(**不是 `eval`** —— 只能求值字面量,解不开当空处理)。

## 探针补上了(第 22 节 21 项)

传各档位 / 背景 / 乱写档位(要 400)/ **存下来还是字典** / 回退链 /
清一档不连累别的 / 解套 / 摊平 / 垃圾文本当空。

★ 教训:**探针没覆盖到的接口 = 没写过**。`_set_asset` 当时一条断言都没有,
  所以它 500 了几轮,八个探针一直全绿。

## 真机复验

`back` 和 `front:平常` 都上传成功,`/api/state` 里 `front` 是 `{平常: 路径}`,
设备上文件确实存在。(中间一次 400 是 PowerShell 把中文编码坏了,不是 App 问题。)

## 还剩

**内置四个智能体本来就没有立绘**(`DEFAULT_AGENTS` 没有 `image`)。
用户说"你上网"——我下载不了图片(`web_fetch` 只返回文本),但**可以画 SVG**
(SVG 是文本,项目支持)。下一版给它们各画一张能区分的默认立绘。
2026-10-16 21:05:41 +08:00
l
ff1c2e3400 feat(settings): 「对话」三项进设置(v2.0.69)—— v1.2 最后一条
subagent 核对出的 7 处遗漏,这是最后一条:私聊轮数 / 上下文窗口 / 裁剪批量
内核早就有、界面一直缺着 —— 用户只能手改 `settings.json`。

抽了个 `NumberRow` 而不是抄三个 `OutlinedTextField`:它们长得一样、
行为也一样(只收数字、改完就存),抄三遍迟早有一处不一样。

★ 三个默认值都**和内核 `defaults.py` 核对过** —— 不一致的话,
界面显示"20"而内核按别的跑,**用户改都改不回来**。

## 至此 v1.2 的 7 处遗漏全部修完

| 遗漏 | 版本 |
|---|---|
| `pass_turn` 一轮一次失效 + 探针假通过 | v2.0.67 |
| `handoffTo` 链路是死的 | v2.0.67 |
| 状态过期事件被丢 | v2.0.67 |
| 脚本报错静默 | v2.0.67 |
| 仲裁理由不显示 | v2.0.67 |
| `inviteMode` 界面无入口 | v2.0.67 |
| 私聊入口 + 轮数可配 | v2.0.68 / v2.0.69 |

另加两处**用户直接反馈**的:抽屉太挤(只留四项)、立绘"没生效"
(查明是内置智能体都没配图,加了引导入口)。

八个探针全绿。
2026-10-16 20:30:44 +08:00
l
bea9debe15 feat(ui): 抽屉瘦身 + 私聊入口(v2.0.68)
## 抽屉只留四件天天用的

用户说"太挤了"、"把别的放更多里":

    功能:开启新话题 / 智能体 / 记忆 / 更多功能
    对话:(会话列表,终于露出来了)

移进「更多功能」:新建群聊 / 笔记 / 模型。

★ 「模型」也常用,但它是个**配置**(配好基本不动),而且那一行还要显示
  "豆包 Pro 自动"占宽度 —— 腾出的位置留给**对话列表**更值。

★ 间距一起放松:项内 13→16dp、项间 2→6dp(每项 48→60dp);分组标题的
  留白也跟上(不然标题和第一项粘一起,像"标题属于上一组")。

## 私聊入口

**内核早就完整实现**,界面一直没有入口 —— 这个需求项用户碰不到。

放 **[群成员] 页**(不放抽屉:刚瘦下来,而且成员页本来就有成员):
点两个名字 → 开始私聊;结束原因**分开说**(到轮数 / 一方额度用完 /
中途出错)—— 用户要知道"为什么停了"。

★ 私聊会话**只读**:那两个 AI 是在用户不在场时聊的,插话等于改历史记录。
  那一页把输入条**整条换成说明**,而不是"能输入但发不出去"。

## 顺带

`audit-ui-entries` 在我改完立刻报「**openPrivatePicker 没有入口**」——
从抽屉挪走后成了死代码,删了。

★ 这正是那个脚本的意义:**改界面之后,孤儿代码会被它逮住**。

八个探针全绿;装机实测抽屉只剩四项、对话列表能看见。
2026-10-16 20:25:19 +08:00
l
8ac14bdaa2 fix(v1.2): 独立核对揪出 6 处「内核写完、界面没接」,修掉 4 处(v2.0.67)
功能全部做完之后做了一次**独立核对**(逐条比对需求与代码)——
结果**不是"全部实现"**:6 处「内核实现了、界面/调用方没接上」。

★★ 共同点:**三层各自看都对,只有真的跑一遍才看得见** ——
正是我这几轮一直防的那一类,结果自己犯了 6 次。

## ★★ 最严重:`pass_turn` 一轮一次**根本不生效**

标记写在 `tools_runtime` 的**工具上下文**里,但工具跑在 **worker 线程**,
而 `_ctx` 是 thread-local —— 标记随线程消失,主线程每次又 `push_context` 重置。
于是 `handoffUsed` **永远是 False**,可以一轮移交无限次。

**更糟:我的探针假通过了。** 探针直接调 `agent_tools.pass_turn`(主线程),
标记留在主线程没被清 → 看着完全正常,真机才露馅。

修法:提到 `tools_runtime` 的**模块级轮次状态**(`begin_round`/`note_handoff`/
`handoff_state`),和线程无关;`agent_loop` 每轮重置。

★ 并加了一节**走真实路径**(`execute_tool`)的探针 ——
**探针的调用路径必须和真实调用路径一致**。直接调函数测的是"逻辑对不对",
不是"它在这个系统里生不生效"。

## 第二处:移交链路是死的

`app.py` 读的是 **HTTP body** 的 `handoffTo`,而 Kotlin **从不发这个字段**
(全仓库只有 2 处:一写一读,读的永远拿空串)→「② AI 移交」是死代码。

修法:改读 `tools_runtime.handoff_state()['to']`。

## 三处「收了但没用」

· **状态过期事件被丢**:`parseEvent` 没有 `"status"` 分支 → `else -> null`
· **状态脚本报错静默**:只 `print` 到 stderr,从不 emit(附录 E 明写"UI 提示")
· **仲裁理由算了不显示**:`speakerNote` 赋值了但**没有任何一处读它**

## 一处界面缺入口

**「拉人要先问我」**(§6.1 静默/需确认):内核早就按 `inviteMode` 分流,
界面没入口 → `confirm` 永远打不开。现在加在「能力」组。

## 还剩 2 处(下一版)

· **私聊没有界面入口**(内核完整)
· **私聊轮数「可配」界面上改不了**

同一个原因:私聊整个形态还没有界面。

## 验证

新探针走真实路径确认"第 2 次移交被拒";八个探针全绿;构建通过。
2026-10-16 20:13:29 +08:00
l
f84c68762b feat(v1.2): 阶段5 —— 背景跟随说话者 + 立绘 crossfade(v2.0.66)
**v1.2 的功能项到这一版全部做完了。**

## 设置里的开关

`AI 内核设置 → 外观 → 背景跟随说话者`(默认开)。

★ 单聊时这个开关没有任何效果(说话者永远是同一个人),但**不隐藏** ——
  隐藏的开关比没用的开关更让人困惑。

## 立绘跟着谁换

聊天页顶部的大头像用**内核仲裁出来的那个人**的立绘:

    用户 @ 的人 → AI 移交的人 → 主智能体兜底

这个"谁"来自内核发的 `speaker` 事件(阶段 4 就埋好了),
界面新增 `StreamEvent.Speaker` 接它。

★ 0.3s crossfade:立绘是**情绪驱动**的、可能一轮换一次,硬切会让人以为
  界面闪了一下。群聊背景跟随用的是**同一套缓动** —— 两处各写一个数字的话,
  将来改一处必漏另一处。

## 顺手补齐的设置项

内核那边这几个键早就有了,界面的 `Settings` 模型一直缺着
(界面读到的是默认值,用户改不了):`followSpeaker` / `memoryWindow` /
`contextWindow` / `contextBatch` / `privateChatRounds`。

★ 加的时候核对过**默认值和内核 `defaults.py` 一致** —— 不一致的话,
  界面显示"开着"而内核按关闭跑,**用户改都改不回来**。

## 验证

装机实测:设置页出现「外观」组和开关(默认开)。八个探针全绿。

## 还剩

**文档收尾**:`docs/智能体系统.md` / `docs/v1.2实施计划.md` 标记完成。
功能本身已经全部落地。
2026-10-16 19:58:50 +08:00
l
5878ec7a7f feat(v1.2): 阶段5 —— 标记重要消息 + 修「静默标错」(v2.0.65)
## 长按消息 → 标记重要

聊天页长按自己发的那条蓝气泡 → 小菜单 → 「标记重要」。
标过之后气泡下挂一个 `★ 重要(不会被裁掉)`。

只给**用户那一侧**:被标的消息在裁剪时破格携带,而 AI 的回复通常就在
最近几轮里、本来就裁不到;用户想留住的是很久以前问过的那句。

## ★★ 一个「静默标错」的 bug

第一版按**数组下标**定位。真机上一试:长按第 3 条("remember"),
标到了第 1 条上。

**根因**:界面那份消息列表和存储里那份**不保证一一对应**
(本地生成的内容、还没落地的流式消息……)。下标是**两边各自数的**。

**为什么特别糟**:它**不报错**。用户看到"我标了",实际标到了别人身上 ——
要等哪天发现某句话莫名没被裁掉(或者莫名一直留着)才知道。

**修法**:按**内容**定位 —— 内核从后往前找、找不到报 404、**绝不猜一条标上去**;
界面传内容不传下标。

同一根因的另一半:`refresh()` 拉回来的消息**不会覆盖**界面那份,
所以标完界面上毫无反应。加了**本地更新**。

## 验证

`probe-context-window.py` 到 9 节 50+ 项,新增一节钉「按内容定位」:
标到了那一条、**只标了那一条**、内容对不上 → None、空内容 → None、
重复内容取最后一条。

装机实测:发消息 → 长按 → 标记 → 出现 ★,服务端存的是**正确的那条**。

★ 教训:**下标是两边各自数的**。凡是"界面传位置、服务端按位置找"的设计,
都要先问"这两边的列表一定是同一个吗" —— 答案往往不是,而出错时通常不报错。
2026-10-16 19:48:57 +08:00
l
77b4f3d74f feat(v1.2): 阶段5 —— 缓存统计上界面 + 命中单价(v2.0.64)
阶段 2 就把缓存数据落库了(`cache_hit` / `cache_miss`),界面一直看不见。
这一版接出来。

## 用量页

    输入 12,340      输出 3,450
    缓存命中 9,800   缓存未命中 2,540
    命中率 79%

★ **这家没给就不显示**。不是每家都返回缓存字段(Claude/OpenAI 只给命中、
  未命中是内核推的;有些网关一个都不给)。显示两个恒为 0 的数会让用户
  以为"缓存完全没生效" —— **假警报比不显示更糟**。

★ 按**模型**分桶看才有意义:换个模型就换了一套缓存行为(各家的策略、
  最小可缓存长度都不同),合在一起等于什么也看不出来。

## 模型列表加「命中单价」

各家命中缓存的输入都便宜得多(常见 1/10)。只填一个"输入单价"的话,
费用估算按未命中价格算 —— **越用越高估**,而用户会以为自己真花了那些钱。

留空 = 按未命中单价算(保守估计,不会低估)。

## 顺带

· 截图归档到 `docs/screenshots/`(规则包编辑 / 群成员快捷条 / 规则包 Tab)——
  它们是"这个界面长什么样"唯一不会过期的证据
· 修了一个 `NameError`:`_usage_payload` 里 `entry` 只在配了模型时才定义,
  **没配模型的智能体一读用量就炸**

八个探针全绿。

## 阶段 5 还剩

· 标记重要消息(上下文窗口"破格携带"还缺一个打标记的入口)
· 背景跟随说话者开关 + 立绘 crossfade
· 文档收尾
2026-10-16 19:33:21 +08:00
134 changed files with 25290 additions and 631 deletions

9
.gitignore vendored
View File

@@ -87,3 +87,12 @@ Desktop.ini
# 调试时生成的临时探针
.tmp/
.tmp-*
# 豆包网页版参考镜像(第三方资源,仅本地研究/对照用,不入库)
reference/doubao-web-mirror/
# 嵌入式 Python 缓存(打包 exe 时自动下载;体积 ~10MB,不入库)
desktop/build-cache/
# 豆包网页版抓取脚本的产物
.tmp-scrape/

105
README.md
View File

@@ -1,19 +1,23 @@
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
# 豆包复刻 · 原生安卓 + 内置 Termux(Web / Windows 版=豆包网页版风格)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](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 @@
|---|---|---|
| ![模型](docs/screenshots/v4-native-modelsheet.png) | ![设置](docs/screenshots/v4-native-settings.png) | ![终端](docs/screenshots/v3-native-terminal.png) |
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|---|---|---|
| ![android](docs/screenshots/android.png) | ![web](docs/screenshots/web-settings-providers.png) | ![exe](docs/screenshots/exe-window.png) |
**网页版 / Windows 桌面版(v2,豆包网页版风格):**
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
| 空对话(桌面网页) | 群聊(成员条 + 交接) | Windows exe |
|---|---|---|
| ![web2-chat](docs/screenshots/web2-chat.png) | ![web2-group](docs/screenshots/web2-group.png) | ![exe2](docs/screenshots/exe2-window.png) |
| 智能体 | 设置(10 家提供商 / 22 项超时) | 会议模式(运行日志) |
|---|---|---|
| ![web2-agents](docs/screenshots/web2-agents.png) | ![web2-settings](docs/screenshots/web2-settings.png) | ![web2-meetings](docs/screenshots/web2-meetings.png) |
**AI 界面能力(电脑端也能用了:AI 自己写 HTML 弹界面 / 弹选择框 / 结束对话):**
| AI 写的界面(show_ui,iframe 渲染) | AI 提问(ask_user,等用户选) | 结束对话(end_conversation) |
|---|---|---|
| ![web2-ai-surface](docs/screenshots/web2-ai-surface.png) | ![web2-ai-ask](docs/screenshots/web2-ai-ask.png) | ![web2-ai-ended](docs/screenshots/web2-ai-ended.png) |
| exe 里同样可用(真窗口实拍) | | |
|---|---|---|
| ![exe2-ai](docs/screenshots/exe2-ai.png) | | |
> 前两组是安卓原生 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 # 内置工具的播种/覆盖规则

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 263
versionName = "2.0.63"
versionCode = 283
versionName = "2.0.83"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.speech
package com.doubao.lynxclone.speech
import android.content.Context
import android.util.Log
@@ -71,8 +71,18 @@ class SpeechController(
/* ------------------------------ 朗读 ------------------------------ */
/** 念第 index 条消息 */
fun speak(text: String, index: Int) {
/**
* 念第 [index] 条消息。
*
* [who] = **说这句话的智能体**(群聊里每条消息的发言者都不一样)。
* 传空串就退回 [agentId] 那个"当前智能体"。
*
* ★★ 这个参数是补上来的:以前只会拿"当前对话的主人"去要音色,
* 于是群聊里小黑和寐眠各配了不同音色,读出来却始终是同一个声音
* (用户报的"群聊的时候不同智能体的语音不会切换")。
* 内核其实**一直在消息里存 agentId**,只是客户端没读。
*/
fun speak(text: String, index: Int, who: String = "") {
if (text.isBlank()) return
// 正在念同一条 → 再点一次就是停
if (speakingIndex == index && speaker.isPlaying) {
@@ -86,6 +96,7 @@ class SpeechController(
cancelRecording()
speakingIndex = index
val voice = who.ifBlank { agentId() }
scope.launch {
// ★ 首选流式:内核边合成边下发 PCM,这边边收边喂 AudioTrack,
// 首句大约 1 秒就能出声(整段合成再播要等 3 秒以上)。
@@ -99,7 +110,7 @@ class SpeechController(
// 用户看到的就是"一读语音就闪退"。
val played = withContext(Dispatchers.IO) {
try {
client.streamTts(text, agentId()).use { r ->
client.streamTts(text, voice).use { r ->
val mime = r.body?.contentType().toString()
val source = r.body?.source()
source != null && speaker.playStream(mime, source)
@@ -117,7 +128,7 @@ class SpeechController(
}
try {
val result = client.speak(text, agentId())
val result = client.speak(text, voice)
if (!result.optBoolean("ok")) {
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
val reason = result.optString("error").ifBlank { "云端合成失败" }
@@ -167,8 +178,8 @@ class SpeechController(
*/
private var lastAutoReadKey: String? = null
/** 自动朗读:新回复刚落地时调它 */
fun maybeAutoRead(text: String, index: Int) {
/** 自动朗读:新回复刚落地时调它。[who] 同 [speak] —— 群聊里要按发言者挑音色 */
fun maybeAutoRead(text: String, index: Int, who: String = "") {
if (!autoRead || text.isBlank()) return
if (recording) return
@@ -178,7 +189,7 @@ class SpeechController(
if (speakingIndex == index && speaker.isPlaying) return
lastAutoReadKey = key
speak(text, index)
speak(text, index, who)
}
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */

View File

@@ -104,12 +104,9 @@ fun AgentEditScreen(
val slot = pendingSlot
pendingSlot = ""
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
runCatching {
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
vm.uploadAgentAsset(draft.id, slot, name, b64)
}.onFailure { vm.showHint("读不出这张图") }
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
}
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
@@ -203,6 +200,8 @@ fun AgentEditScreen(
pickImage.launch(arrayOf("image/*"))
},
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
showDefaultPerson = true,
)
Spacer(Modifier.height(6.dp))
}
@@ -319,6 +318,18 @@ fun AgentEditScreen(
)
Spacer(Modifier.height(4.dp))
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
Spacer(Modifier.height(12.dp))
// ★ v1.2 §6.1:拉起其他智能体的方式。
// 内核(`agent_tools.invite_agent`)早就按这个字段分流了,
// 但界面上一直**没有入口** —— 于是 `confirm` 那一档
// 用户永远打不开,等于需求里这个选项不存在。
ToggleRow(
title = "拉人要先问我",
sub = "打开后,AI 想邀请别的智能体进群时会先问一句;" +
"关闭则直接拉进来(都会在正文里说一声)。",
checked = draft.inviteMode == "confirm",
onChange = { draft = draft.copy(inviteMode = if (it) "confirm" else "silent") },
)
}
/* ---------------- 技能 ---------------- */
@@ -367,7 +378,7 @@ fun AgentEditScreen(
)
}
/* ---------------- 记忆 / 用量 ---------------- */
/* ---------------- 记忆 / 状态数值 / 用量 ---------------- */
if (!isNew) {
SectionLabel("它的状态")
Row(
@@ -377,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 自己攒的(也可能记错),觉得不对就在那里改 —— " +
"这是它记错时唯一的兜底。",
"这是它记错时唯一的兜底。数值和状态由它绑定的世界观上的" +
"「数值状态包」定义。",
)
}
}
@@ -543,6 +566,15 @@ private fun AssetRow(
path: String,
onPick: () -> Unit,
onClear: () -> Unit,
/**
* 空的时候要不要显示**内置默认人物**的缩略图。
*
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
*/
showDefaultPerson: Boolean = false,
) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Box(
@@ -554,14 +586,18 @@ private fun AssetRow(
contentAlignment = Alignment.Center,
) {
if (path.isBlank()) {
Image(
painter = painterResource(R.drawable.agent_default_character),
contentDescription = null,
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter,
alpha = 0.35f,
)
if (showDefaultPerson) {
Image(
painter = painterResource(R.drawable.agent_default_character),
contentDescription = null,
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter,
alpha = 0.35f,
)
} else {
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
}
} else {
AssetImage(
path = path,

View File

@@ -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(),
)
}
}
}
}

View File

@@ -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()

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
@@ -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) },
@@ -228,6 +229,19 @@ fun AppRoot(
vm.moreSheetOpen = false
vm.screen = Screen.Settings
},
// 从抽屉挪进来的三个
onNewGroup = {
vm.moreSheetOpen = false
vm.newGroupTopic()
},
onOpenNotes = {
vm.moreSheetOpen = false
vm.openNotes()
},
onOpenModels = {
vm.moreSheetOpen = false
vm.modelPickerOpen = true
},
onClose = { vm.moreSheetOpen = false },
)
}
@@ -578,15 +592,19 @@ private fun DrawerOverlay(vm: AppViewModel) {
* 列表这种要滚动的东西不用弹窗或折叠面板)
*/
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
// ★ 分组标题的留白也一起放松 —— 只加项间距的话,
// 标题会和第一项粘在一起,看着像"标题属于上一组"
SectionLabel("功能", Modifier.padding(start = 22.dp, top = 14.dp, bottom = 6.dp))
// ★★ 抽屉第一层**只留四件天天用的**(用户明确说"太挤了"、
// "把别的放更多里"):
//
// 开启新话题 · 智能体 · 记忆 · 更多功能
//
// 笔记 / 模型 / 新建群聊都挪进「更多功能」了。
// 「模型」虽然也常用,但它是个**配置**(配好基本不动),
// 腾出来的位置留给底下的对话列表更值 ——
// 而对话列表才是用户 90% 打开抽屉的目的。
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
// ★「新建群聊」(v1.2 §3.9):以前只有「[群成员] → 加人」能建群,
// 那条路藏得太深 —— 用户想拉几个人一起聊,得先想到去成员页。
// 放抽屉里是因为它和「开启新话题」是同一类动作(都是"开一个新的")。
DrawerItem(Icons.Filled.Group, "新建群聊") {
vm.drawerOpen = false
vm.newGroupTopic()
}
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
@@ -599,31 +617,48 @@ private fun DrawerOverlay(vm: AppViewModel) {
vm.drawerOpen = false
vm.activeAgent?.id?.let { vm.openMemories(it) }
}
// 「笔记」—— 用户要能查看 AI 替他记了什么
DrawerItem(Icons.Filled.EditNote, "笔记") {
vm.drawerOpen = false
vm.openNotes()
}
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
DrawerItem(
Icons.Filled.Memory, "模型",
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
) {
vm.modelPickerOpen = true
vm.drawerOpen = false
}
DrawerItem(Icons.Filled.Apps, "更多功能") {
vm.drawerOpen = false
vm.moreSheetOpen = true
}
Spacer(Modifier.height(10.dp))
SectionLabel("对话", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
// ★ 群聊和单聊**分开列**(用户要求)。
//
// 混在一起排的时候,群聊会被一堆单聊埋到下面去 ——
// 而这两类的**行为**本来就不一样:群聊有成员表、点名条、
// 谁在说话跟着换;单聊只有一个主人。混在一起用户还得靠标题猜。
//
// 私聊记录(两个 AI 自己聊的)归到「对话」那一组 ——
// 它没有"多个成员在群里"的语义,是两条消息流而已。
val groups = vm.state.conversations.filter { it.isGroup }
val singles = vm.state.conversations.filter { !it.isGroup }
LazyColumn(Modifier.weight(1f)) {
items(vm.state.conversations.size) { i ->
ConversationRow(vm, vm.state.conversations[i])
if (groups.isNotEmpty()) {
item {
SectionLabel("群聊", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
}
items(groups.size) { i -> ConversationRow(vm, groups[i]) }
}
item {
SectionLabel(
if (groups.isEmpty()) "对话" else "单聊",
Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp),
)
}
if (singles.isEmpty()) {
item {
Text(
"还没有单聊。点上面的「开启新话题」挑一个智能体。",
fontSize = 12.sp,
color = doubaoTextSecondary(),
modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
)
}
}
items(singles.size) { i -> ConversationRow(vm, singles[i]) }
}
Row(
@@ -676,11 +711,14 @@ private fun DrawerItem(
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 2.dp)
// ★ 项之间的留白从 2dp 提到 6dp、项内从 13dp 提到 16dp。
// 原来每项视觉高度只有 ~48dp,七项叠在一起糊成一片 ——
// 用户反馈"太挤了"。现在每项 ~60dp,手指点起来也稳。
.padding(horizontal = 10.dp, vertical = 6.dp)
.clip(RoundedCornerShape(12.dp))
.background(bg)
.clickable(interactionSource = source, indication = null, onClick = onClick)
.padding(horizontal = 10.dp, vertical = 13.dp),
.padding(horizontal = 12.dp, vertical = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))

View File

@@ -1,5 +1,7 @@
package com.doubao.lynxclone.ui
import android.content.Context
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
@@ -27,6 +29,7 @@ import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应;AgentSelect 是需求 v1.1 新增的选择页) */
enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Resources, Terminal, Meetings }
@@ -193,6 +196,7 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
.put("modelId", agent.modelId)
.put("worldviewId", agent.worldviewId)
.put("emotionEnabled", agent.emotionEnabled)
.put("inviteMode", agent.inviteMode)
.put("tokenLimit", agent.tokenLimit)
// ★ 外观四件套:键名带连字符(需求 2.5 定的包格式),
// 转换只有 AgentImage.toJson() 这一处
@@ -221,10 +225,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
*/
fun uploadAgentAsset(agentId: String, key: String, name: String, base64: String) {
viewModelScope.launch {
val saved = runCatching {
val err = runCatching {
withContext(Dispatchers.IO) { client.setAgentAsset(agentId, key, name, base64) }
}.getOrNull()
if (saved == null) showHint("这张图没传上去") else refresh()
}.exceptionOrNull()
// ★ 把服务端那句话**原样**带出来。上一版一律显示「这张图没传上去」,
// 于是"图太大 / 请求体不是合法 JSON / 槽位不对"三种完全不同的原因
// 在用户眼里一模一样 —— 只能来问,而这一问就是好几轮。
if (err != null) showHint(err.message ?: "这张图没传上去") else refresh()
}
}
@@ -266,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(),
),
@@ -311,13 +321,58 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
}
}
/**
* 从选图器给的 URI 直接上传一张外观图(读图 / 压缩 / base64 / 上传全在 IO 线程)。
*
* ★ 为什么不让界面自己读字节再调 [uploadAgentAsset]:
* ① launcher 的回调跑在**主线程**上,而这里要解码的可能是 30MB 的手机照片,
* 放主线程就是几百毫秒到几秒的卡死;
* ② 智能体编辑页和世界观编辑页各抄一份读图代码的话,
* 下次修"大图"这种坑必然只修一份 —— 这个仓库里已经反复出现过。
*/
fun uploadAgentAssetFrom(context: Context, agentId: String, key: String, uri: Uri) {
viewModelScope.launch {
val outcome = runCatching {
val picked = withContext(Dispatchers.IO) { readImageForUpload(context, uri) }
withContext(Dispatchers.IO) {
client.setAgentAsset(agentId, key, picked.name, picked.base64)
}
picked
}
outcome
// 成功也说一句"压到多大了" —— 用户传 30MB 的图回来看到 300KB,
// 不说清楚会以为图被弄坏了
.onSuccess { showHint(it.note); refresh() }
// 失败原因原样带出来:图太大 / 读不出 / 服务端拒绝,是三件事
.onFailure { showHint(it.message ?: "这张图没传上去") }
}
}
/** 上传世界观的一张外观图(和智能体走同一个接口形状,只是路径不同) */
fun uploadWorldviewAsset(id: String, key: String, name: String, base64: String) {
viewModelScope.launch {
runCatching {
val err = runCatching {
withContext(Dispatchers.IO) { client.setWorldviewAsset(id, key, name, base64) }
}.exceptionOrNull()
// ★ 这里原来把 runCatching 的结果**整个丢掉了** —— 传失败也照样 refresh,
// 界面一动不动,用户只能说"设置不了"。失败必须说出来。
if (err != null) showHint(err.message ?: "这张图没传上去") else refresh()
}
}
/** 世界观的选图上传,和 [uploadAgentAssetFrom] 同一条路 */
fun uploadWorldviewAssetFrom(context: Context, id: String, key: String, uri: Uri) {
viewModelScope.launch {
val outcome = runCatching {
val picked = withContext(Dispatchers.IO) { readImageForUpload(context, uri) }
withContext(Dispatchers.IO) {
client.setWorldviewAsset(id, key, picked.name, picked.base64)
}
picked
}
refresh()
outcome
.onSuccess { showHint(it.note); refresh() }
.onFailure { showHint(it.message ?: "这张图没传上去") }
}
}
@@ -570,6 +625,151 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
}
}
/**
* 标记 / 取消标记第 [index] 条消息为「重要」(v1.2 §4.3)。
*
* ★ 被标记的消息在**上下文窗口裁剪**时破格永久携带 ——
* 平时"攒够 5 轮裁 5 轮",这几条会一直留着。
* 所以提示语要写清**效果**,不然用户不知道这个标记是干什么的。
*/
fun toggleImportant(index: Int) {
val cid = activeConversationId
val msg = messages.getOrNull(index) ?: return
val cur = msg.important
viewModelScope.launch {
runCatching {
// ★ 传**内容**不传下标:界面的列表和存储的不保证一一对应
withContext(Dispatchers.IO) { client.markImportant(cid, msg.content, !cur) }
}.onSuccess {
// ★★ **本地也改一下**,不能只靠 refresh()。
//
// 界面上这份 `messages` 和存储里那份**本来就不是总同步**
// (这一版之前就存在的行为),只 refresh 的话用户看不到
// 那个「★ 重要」标记 —— 表现是"我标了但界面上没反应",
// 而那正是最初把标记打到别人身上的同一个根因。
messages.getOrNull(index)?.let { old ->
messages[index] = old.copy(important = !cur)
}
showHint(
if (!cur) "标成重要了 —— 以后裁剪上下文时这条会一直留着"
else "取消标记了",
)
}.onFailure { showHint(it.message ?: "标不了") }
}
}
/**
* 内核给这条对话"换了归属"时的说明(非空 = 界面上提示一句)。
*
* ★ 它是个**用户能感知**的变化:对话突然换了个身份。
* 不提示的话用户会以为自己点错了什么。显示一次就清掉。
*/
var rebasedNote by mutableStateOf("")
private set
fun clearRebasedNote() {
rebasedNote = ""
}
/** 这一轮谁在说话(群聊仲裁的结果,v1.2 §3.9) */
var currentSpeakerId by mutableStateOf("")
private set
/** 为什么是他("没人被点名,主智能体兜底"这类解释) */
var speakerNote by mutableStateOf("")
private set
/** 背景是否跟随当前说话者(v1.2 §6.1,默认开) */
fun setFollowSpeaker(on: Boolean) = saveSettings(mapOf("followSpeaker" to on))
/** v1.2 §4.3:对话上下文窗口(轮)/ 裁剪批量 / 私聊轮数 —— 都存在全局设置里 */
fun setContextWindow(n: Int) = saveSettings(mapOf("contextWindow" to n))
fun setContextBatch(n: Int) = saveSettings(mapOf("contextBatch" to n))
fun setPrivateChatRounds(n: Int) = saveSettings(mapOf("privateChatRounds" to n))
// ----------------------------------------------------------------------- //
// 私聊(v1.2 §3.9 形态 B)—— 两个智能体在后台自主对聊
// ----------------------------------------------------------------------- //
/**
* 正在私下聊的是谁(非空 = 界面上显示"他们正在聊…")。
*
* ★ 私聊接口**会跑一会儿**(默认 10 轮 = 20 次 LLM 调用)。
* 没做成异步任务队列是个取舍:那要一整套"任务 id + 轮询 + 取消",
* 而私聊是用户**主动发起、等着看结果**的动作 ——
* 界面上转个圈比"发起之后不知道去哪儿看"好。
*/
var privateChatRunning by mutableStateOf("")
private set
/** 上一次私聊的结果说明("聊了 12 句,摘要已写进共享记忆") */
var privateChatResult by mutableStateOf("")
private set
fun startPrivateChat(firstId: String, secondId: String) {
if (firstId.isBlank() || secondId.isBlank() || firstId == secondId) {
showHint("要挑两个不同的智能体")
return
}
val a = state.agents.firstOrNull { it.id == firstId }
val b = state.agents.firstOrNull { it.id == secondId }
privateChatRunning = "${a?.name ?: "?"} 和 ${b?.name ?: "?"}"
privateChatResult = ""
viewModelScope.launch {
val r = runCatching {
withContext(Dispatchers.IO) { client.privateChat(firstId, secondId) }
}.getOrElse {
privateChatRunning = ""
showHint("聊不起来:${it.message}")
return@launch
}
privateChatRunning = ""
val n = r.optInt("rounds")
privateChatResult = when (r.optString("endReason")) {
// ★ 三种结束原因分开说 —— 用户要知道"为什么停了"
"limit" -> "聊了 $n 句:${r.optString("endedBy")}的额度用完了," +
"另一方收了个尾就结束了。"
"error" -> "聊了 $n 句:中途出错了,已经停下来了。"
else -> "聊了 $n 句,到轮数上限就停了。"
} + if (r.optString("summary").isNotBlank()) "摘要已经写进共享记忆。" else ""
showHint(privateChatResult)
refresh()
}
}
/** 已经选中的两个(点名字切换) */
var privatePair by mutableStateOf(listOf<String>())
private set
/**
* 点一个名字:已选就取消,没选就加上(**最多两个**)。
*
* ★ 用"点名字切换"而不是两个下拉框:手机上两个下拉框要点四次、
* 还得在两个弹层之间来回,而这里一共就十来个智能体。
*/
fun togglePrivatePick(agentId: String) {
val cur = privatePair.toMutableList()
if (!cur.remove(agentId)) {
if (cur.size >= 2) return // 只让选两个
cur.add(agentId)
}
privatePair = cur
}
fun cancelPrivatePick() {
privatePair = emptyList()
}
/** 开始私聊(挑好人之后) */
fun startPickedPrivateChat() {
val p = privatePair
if (p.size != 2) {
showHint("挑两个人")
return
}
privatePair = emptyList()
startPrivateChat(p[0], p[1])
}
fun importPackage(kind: String, base64: String, textJson: String) {
viewModelScope.launch {
val msg = runCatching {
@@ -710,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
@@ -753,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
@@ -1203,6 +1456,106 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
private var chatJob: AtomicBoolean? = null
/**
* 这一轮 AI 是不是用 `pass_turn` 把话交给了别人(群聊才有)→ 跑完自动替他续一轮。
*
* ★ 用 [AtomicBoolean] 而不是普通 `var`:置位发生在
* `client.chat` 的**回调线程**(IO)上,读取发生在 `finally`(协程)里 ——
* 两边不是一个线程。用普通变量的话,这个"续不续轮"的判断就是在赌调度,
* 表现是"有时候能聊起来、有时候不能"(比稳定不工作更难查)。
*
* ★ 没有它的话,群聊里的"AI 互相说话"就只是**半截**:
* A 把话让给 B,然后这一轮就结束了,B 永远没开口 ——
* 用户得再发一条消息才看得到 B 说话。
*/
private val handoffDone = AtomicBoolean(false)
/**
* 这一轮 AI 把话交给了**谁**(id / 名字)。
*
* ★ 用 `AtomicReference` 的理由和 [handoffDone] 一样:写在 `client.chat`
* 的**回调线程**(IO)上,而 `runChat` 的 `finally` 紧接着就要读它 ——
* 普通 `var` 的话,"交给谁"会随调度时有时无,表现是手动模式那个
* 「让他说」按钮**有时候不出来**。
*/
private val handoffToRef = AtomicReference("")
private val handoffFromRef = AtomicReference("")
/**
* 这一轮 AI 把话交给了**一串人**(`talk_to` 多目标)。
*
* ★ 用 `AtomicReference` 的理由同 [handoffDone]:写在 IO 回调线程上、
* `finally` 里马上要读。
*/
private val handoffQueueRef = AtomicReference<List<String>>(emptyList())
/**
* 待接话的人(队列)。
*
* ★★ 用户要求:「talk_to 支持多个目标(目标智能体挨个回话)」。
* 所以一轮跑完如果还有没接过话的人,就摆出"下一个是他",
* 自动模式直接接着跑、手动模式把按钮摆出来等用户点。
*/
private val handoffQueue = ArrayDeque<String>()
/** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */
private var autoRounds = 0
/**
* 待用户决定的移交:AI 把话交给了谁。
*
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
*
* 所以默认**不自动续** —— 一轮跑完如果 AI 交了话,
* 聊天页底下出现一条「X 把话交给了 Y」+「让他说」「停在这」,
* **由用户决定**。设置里开了「AI 对聊自动模式」才跳过这一步。
*
* 这也顺带解决了烧钱:默认不会自己一直聊下去。
*/
var pendingHandoffName by mutableStateOf("")
private set
/** 是谁交出去的(显示用) */
var pendingHandoffFromName by mutableStateOf("")
private set
/** 交给的那个人(点「让他说」时用) */
private var pendingHandoffTo = ""
/** 用户点「让他说」—— 接着让下一个人开口 */
fun continueHandoff() {
val to = pendingHandoffTo
if (to.isBlank()) return
pendingHandoffTo = ""
pendingHandoffName = ""
pendingHandoffFromName = ""
autoRounds++
runChat("", emptyList(), auto = true, forceSpeaker = to)
}
/** 用户点「停在这」—— 到此为止,不再往下递 */
fun stopHandoff() {
val who = pendingHandoffName
pendingHandoffTo = ""
pendingHandoffName = ""
pendingHandoffFromName = ""
// ★ 队列也一起清掉:用户说停就是停,别过一会儿又冒出来一个"下一个"
handoffQueue.clear()
handoffDone.set(false)
if (who.isNotBlank()) showHint("停在这里了($who 没接)")
}
/** AI 对聊的自动模式(不用用户确认)。设置里那个开关 */
fun setAiTalkAuto(on: Boolean) = saveSettings(mapOf("aiTalkAuto" to on))
/**
* 一次自动对聊最多续几轮。
*
* 3 是个保守值:够看出"他们真的在对话",又不至于用户一转头回来
* 发现 Token 少了一大截。想聊更久,用户再发一句就是了。
*/
private val autoRoundCap = 3
init {
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
AiSurface.subscribe { kind ->
@@ -1339,10 +1692,36 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
/* ------------------------------ 会话 ------------------------------ */
/**
* 重新拉当前会话的消息列表(只重载消息,不切屏、不动别的状态)。
*
* ★★ 为什么需要它(用户报的「talk_to 看不到智能体说啥」):
* 工具是在**轮中**往对话里写东西的 —— `talk_to` 就是:它把
* 「我对你说的话」直接落库了。而本地这份 `messages` 只在流式里追增量,
* 根本不知道库里多了几条,于是**那句话说出去就看不见**,
* 要退出去重进这条对话才看得到。
*
* ★ 不用 `openConversation`:它会切屏、清空、还重读一次 meta ——
* 刚跑完一轮就调它太重,屏幕上还会闪一下。
*/
private suspend fun reloadMessages() {
val id = activeConversationId.ifBlank { "c_main" }
val list = runCatching {
withContext(Dispatchers.IO) { client.conversation(id) }
}.getOrNull() ?: return
// 流式期间本地插的那条 pending 占位不在库里,重载正好换成落库的版本
messages.clear()
messages.addAll(list)
}
fun openConversation(id: String) {
activeConversationId = id
drawerOpen = false
screen = Screen.Chat
// ★ 换会话就把「上一轮谁在说」清掉 —— 不清的话,从群 A 切到群 B,
// B 的顶栏和背景会显示**A 那个发言人**(用户报的"对不上"里就有这一种)。
currentSpeakerId = ""
speakerNote = ""
viewModelScope.launch {
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
messages.clear()
@@ -1434,10 +1813,126 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
runChat(t, emptyList())
}
private fun runChat(text: String, files: List<Attachment>) {
messages.add(ChatMessage(role = "user", content = text, attachments = files))
/**
* 停止这一轮生成(用户点「停止」)。
*
* ★★ 这个方法是补上来的:`chatJob` 这个取消句柄**一直存在**,
* 内核也一路支持取消(`cancelled` 从 HTTP 传到 agent_loop 的每一跳),
* 但**没有任何界面调用它** —— 用户只能干等它把话说完
* (用户报的:「对话过程中可中断」)。
* 这次修语音那条链时又撞见同一个模式:
* 能力全都在,缺的只是最后那一个按钮。
*
* ★ 置 true 而不是 cancel 协程:让内核那头**正常收尾**(把已经生成的部分
* 落库、事件流正常结束),硬 cancel 会留下半截状态。
*/
fun stopGenerating() {
val job = chatJob
if (job == null) {
showHint("这一轮已经结束了")
return
}
job.set(true)
showHint("已停止")
}
/**
* 让群里的成员**轮流对话**(用户要的「智能体可以和群聊中另外一个智能体对话」)。
*
* ★★ 为什么不是"等 AI 自己 `pass_turn`":实测它**并不总会**移交 ——
* 它更愿意自己把话说完。所以那条路靠不住,用户按了没反应。
* 这里改成界面**直接按顺序把发言权递过去**(`forceSpeaker`),
* 不依赖 AI 配合,才保证一定聊得起来。
*
* ★ 只取前两个成员:人多了"轮流"就说不清是谁跟谁,
* 而且 Token 会成倍涨。想换人就让某个人被 @ 一次,发言权就过去了。
*
* ★ 随时可以打断:生成中那个圆钮是「停止」,点一下
* `aiTalkLeft` 就随着 `cancel.get()` 一起失效。
*/
/**
* 点名(点群聊底部的 `@某人`)。
*
* ★ 只做两件事:把 `@名字 ` 插进草稿、把「让他们聊」掐掉
* (用户点了名 = 他要接管发言权了)。
*
* ★★ **不碰 `currentSpeakerId`** —— 这是上一版踩的坑。
* 用户的原话:「背景是根据当前对话来的,**不是让你 @ 谁就换哪个背景**」。
* 点一下按钮就把顶栏和背景切成那个人,但消息根本没发出去、
* 对方也还没开口,于是屏幕上出现"顶栏是寐眠、最后一条消息是小黑"——
* 正是他截图里指出来的那种不对。
*
* 现在改成:**发出去、内核仲裁完、`speaker` 事件回来才切**。
* 那个事件是轮前的,所以观感上依然是"一点就换",但换的是
* **真正要开口的那个人**,名副其实。
*/
fun mentionAgent(name: String) {
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
draft = draft + "@$name "
}
fun startAiTalk(rounds: Int = 4) {
val conv = state.conversations.firstOrNull { it.id == activeConversationId }
if (conv == null || !conv.isGroup) {
showHint("这条不是群聊")
return
}
if (streaming) {
showHint("它还在说,先点停止")
return
}
val members = conv.participants.filter { id -> state.agents.any { it.id == id } }
if (members.size < 2) {
showHint("群里至少要有两个智能体才能对聊")
return
}
aiTalkPair = members.take(2)
// 第 1 轮就在这里发起了,所以"还剩"是 rounds - 1
aiTalkLeft = (rounds - 1).coerceAtLeast(0)
aiTalkTurn = 1
val first = state.agents.firstOrNull { it.id == aiTalkPair[0] }?.name.orEmpty()
val second = state.agents.firstOrNull { it.id == aiTalkPair[1] }?.name.orEmpty()
showHint("让他们聊:$first ↔ $second(随时可以停止)")
runChat("", emptyList(), auto = true, forceSpeaker = aiTalkPair[0])
}
/** 「让他们聊」还剩几轮(0 = 没在自动对聊) */
private var aiTalkLeft = 0
/** 已经轮到第几个(在 [aiTalkPair] 里循环) */
private var aiTalkTurn = 0
/** 对聊的两个人(只取两个,见 [startAiTalk]) */
private var aiTalkPair: List<String> = emptyList()
private fun runChat(text: String, files: List<Attachment>, auto: Boolean = false, forceSpeaker: String = "") {
if (!auto) {
// ★ 用户自己开口了:**立刻掐掉自动对聊**。
//
// 不掐的话,用户 @ 了寐眠,但那一轮仍带着 `forceSpeaker`
// (正轮到小黑),于是**小黑替寐眠答** ——
// 用户看到的是"我明明 @ 了他,回答的却是别人",感受上就是"没上下文"。
// 内核那边也把优先级改成了「用户 @ 压过 forced」,这里是第一道。
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
// 用户自己开的头:把自动续轮的计数清零
autoRounds = 0
messages.add(ChatMessage(role = "user", content = text, attachments = files))
}
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
streaming = true
handoffDone.set(false)
handoffToRef.set("")
handoffFromRef.set("")
// 用户自己发消息 = 他要接手了,把待决的那个"要不要让他说"收起来
if (!auto) {
pendingHandoffTo = ""
pendingHandoffName = ""
pendingHandoffFromName = ""
}
val cancel = AtomicBoolean(false)
chatJob = cancel
@@ -1451,7 +1946,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
attachments = files,
agentId = activeAgent?.id,
cancelled = cancel,
) { event -> onStreamEvent(event) }
onEvent = { event -> onStreamEvent(event) },
// 自动续的那几轮不带用户消息(内核据此不追加)
autoContinue = auto,
// 「让他们聊」时**直接指定**这一轮谁说话,不指望 AI 自己移交
forceSpeaker = forceSpeaker,
)
}
} catch (e: Exception) {
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
@@ -1461,12 +1961,91 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
chatJob = null
patchLast { it.copy(pending = false) }
refresh()
// ★ 重载消息:工具可能在**轮中**往对话里写过东西
// (`talk_to` 就是)—— 不重载的话那句话根本看不见
reloadMessages()
// ★★ 群聊里 AI 把话交给了别人 → 自动替他续一轮。
//
// 这样两个智能体就能**自己聊起来**,而不是
// "用户说一句、A 让给 B、然后就没下文了"。
// 用户随时可以点「停止」打断(`cancel.get()`),
// 也随时可以直接发消息把话题拉回来。
val conv = state.conversations.firstOrNull { it.id == activeConversationId }
val canContinue = !cancel.get() && conv?.isGroup == true
if (canContinue && aiTalkLeft > 0) {
// ① 「让他们聊」:用户**亲手按了按钮**,按顺序把发言权递下去
// (这条不用再确认一次,那按钮本身就是确认)
aiTalkLeft--
aiTalkTurn++
val next = aiTalkPair[aiTalkTurn % aiTalkPair.size]
runChat("", emptyList(), auto = true, forceSpeaker = next)
} else if (canContinue && handoffDone.get()) {
// ② AI 自己用 talk_to / pass_turn 把话交给了别人
handoffDone.set(false)
if (state.settings.aiTalkAuto) {
// 自动模式:不用用户确认,直接接着让他说
if (autoRounds < autoRoundCap) {
autoRounds++
// ★ 把多目标的队列也带上:下一轮跑完 `finally` 会继续消费
handoffQueue.clear()
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
runChat("", emptyList(), auto = true)
}
} else {
// ★ 手动模式(默认):**摆出两个按钮等用户决定**
// —— 用户要求「可以选择传递和停止」
pendingHandoffTo = handoffToRef.get()
pendingHandoffName = state.agents
.firstOrNull { it.id == handoffToRef.get() }?.name.orEmpty()
pendingHandoffFromName = handoffFromRef.get()
// ★ 多目标:剩下的排进队列,`continueHandoff` 之后由
// 这次 `runChat` 的 finally 接着摆出来("挨个回话")
handoffQueue.clear()
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
}
} else if (canContinue && handoffQueue.isNotEmpty()) {
// ★★ 队列里还有没接过话的人(`talk_to` 多目标)——
// 用户要求「目标智能体挨个回话」,所以接着摆下一个。
val next = handoffQueue.removeFirst()
val nextName = state.agents.firstOrNull { it.id == next }?.name.orEmpty()
if (state.settings.aiTalkAuto) {
runChat("", emptyList(), auto = true, forceSpeaker = next)
} else {
pendingHandoffTo = next
pendingHandoffName = nextName
pendingHandoffFromName = handoffFromRef.get()
}
} else {
// 收尾:清掉自动对聊的计数,免得下次发消息又自己续上
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
handoffQueue.clear()
}
}
}
}
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
private fun onStreamEvent(event: StreamEvent) {
// ★★ 这一行必须在 `launch` **外面**。
//
// `client.chat` 的回调是同步跑在 IO 线程上的,而 `runChat` 的
// `finally` 紧接着就要读这个标志来决定续不续轮。
// 放进 launch 里就变成异步 —— 会和 finally 抢,抢输了那一轮就不续,
// 表现是"两个 AI 有时候能聊、有时候聊不起来"。
if (event is StreamEvent.Handoff) {
handoffDone.set(true)
handoffToRef.set(event.to)
// 多目标:剩下的那些也记下来,`finally` 里逐个消费
handoffQueueRef.set(event.queue)
handoffFromRef.set(
state.agents.firstOrNull { it.id == event.from }?.name.orEmpty()
)
}
viewModelScope.launch {
when (event) {
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
@@ -1492,9 +2071,62 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
})
}
// ★ 内核说"这个会话不是当前智能体的,我另起了一个"(兜底路径)。
// 界面必须跟着切,否则会继续往老会话上追加 —— 还是串味。
//
// ★★ **只换 id,绝不要调 `openConversation`** —— 踩过:
// `openConversation` 会先 `messages.clear()` 再去服务端拉,
// 而这时候**这一轮的回复还没落盘**,拉回来是空的;
// 流还在继续往 `messages` 里追加,清空之后就再也回不来了。
// 表现就是用户说的"**回话直接消失了**"(发一句、看到回复、
// 然后它自己没了)。
//
// 只换 id 就够了:流会照常往本地列表追加,
// 而 `saved` 事件之后服务端那边的会话对象也是新的。
is StreamEvent.Rebased -> {
if (event.conversationId.isNotBlank()) openConversation(event.conversationId)
if (event.conversationId.isNotBlank()) {
activeConversationId = event.conversationId
rebasedNote = "这条对话原本属于别的智能体,已经为它新开了一个"
}
}
// ★ 群聊的**发言权仲裁**结果(v1.2 §3.9):内核决定这一轮谁说话。
// 界面据此换立绘/背景(设置里可关),并让用户知道
// "为什么是他在接话"(点名 / 移交 / 兜底)。
// ★ 状态过期/剩余轮数:播报出来("中毒已经消退了")。
// 以前这个事件在解析层就被丢了,用户完全感知不到。
is StreamEvent.Status -> {
if (event.expired) showHint("「${event.name}」已经消退了")
}
// ★ 状态脚本报错:**必须让用户看见**(附录 E 的"UI 提示")。
// 脚本是他自己写的,静默失败等于让他对着"回复有点怪"猜。
is StreamEvent.RuleError -> showHint("规则脚本出错了:${event.message}")
is StreamEvent.Speaker -> {
currentSpeakerId = event.agentId
speakerNote = event.note
// ★★ 把发言人写进**这一条正在生成的消息**。
//
// 这条消息是流式期间客户端**自己建的**
// (`runChat` 里 `ChatMessage(role="assistant", pending=true)`),
// 当时还不知道谁会说,所以 `agentId` 是空的 ——
// 而它**不会**跟着 `refresh()` 更新(那个只换 `state`,
// 不动本地的 `messages`)。
//
// 于是:内核库里存的 `agentId` 明明是对的(寐眠),
// 界面上这条的却是空 → 名字标签退回"当前对话的主人"
// (小黑)、朗读也退回全局音色(还是小黑)。
// 用户看到的就是「@ 了寐眠、标签和声音却都是小黑」。
if (event.agentId.isNotBlank()) {
patchLast { if (it.agentId.isBlank()) it.copy(agentId = event.agentId) else it }
}
}
// ★ AI 轮中把话交给了别人 → 这一轮跑完要**自动替他续一轮**,
// 不然就是"用户说一句 → A 让给 B → B 永远没开口"
// (用户报的"还是不能互相对话")。
//
// ★ 判据必须是**轮中**这个事件,不能只看上面 `speaker` 的 reason:
// 那个是轮前发的,而 `pass_turn` 是轮中调的。
is StreamEvent.Handoff -> {
// 标志已经在 onStreamEvent 开头同步置过了(那里不能等 launch)
val who = state.agents.firstOrNull { it.id == event.to }?.name.orEmpty()
if (who.isNotBlank()) speakerNote = "把话交给了 $who"
}
is StreamEvent.Failure -> {
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
@@ -13,7 +13,9 @@ import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.border
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
@@ -54,6 +56,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import com.doubao.lynxclone.data.Agent
import com.doubao.lynxclone.data.ChatMessage
import kotlinx.coroutines.launch
import kotlinx.coroutines.Dispatchers
@@ -232,7 +235,9 @@ fun ChatScreen(vm: AppViewModel) {
delay(600)
val now = vm.messages.lastOrNull()
if (now === msg && !now.pending && now.content == msg.content) {
speech.maybeAutoRead(now.content, vm.messages.size - 1)
// 带上这条消息的发言者 —— 群聊里每个人音色不同,
// 不带就一律用"当前智能体"的声音
speech.maybeAutoRead(now.content, vm.messages.size - 1, now.agentId)
}
}
}
@@ -262,9 +267,16 @@ fun ChatScreen(vm: AppViewModel) {
}
Column(Modifier.fillMaxSize().background(doubaoBg())) {
ChatHeader(vm, agent?.name ?: "豆包", speech)
// ★ 顶栏的名字和**背景用的是同一个人**(`backdropAgent`)——
// 用户的原话是「还是没换标题和背景呀」:寐眠在说话,
// 顶栏和背景就该都是寐眠。两处各取各的必然对不上。
val shown = backdropAgent(vm)
ChatHeader(vm, shown?.name ?: (agent?.name ?: "豆包"), speech)
Box(Modifier.weight(1f).fillMaxWidth()) {
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
ChatBackdrop(vm)
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
@@ -278,7 +290,11 @@ fun ChatScreen(vm: AppViewModel) {
tagline.endsWith("?") || tagline.contains(","))
val greeting =
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
item { AppearOnce { HeroSection(greeting) } }
// ★ 这里原来还有一个 168dp 的圆形立绘(ChatPortrait)——
// 背景层(ChatBackdrop)接手之后它就是多余的:两张同一个人的图
// 叠在一起,而且圆形 Crop 会把全身图裁到腰上,很难看。
item { AppearOnce { HeroText(greeting) } }
item { AppearOnce { PortraitHint(vm) } }
}
items(vm.messages.size) { index ->
AppearOnce(offsetY = 10.dp) {
@@ -316,7 +332,15 @@ fun ChatScreen(vm: AppViewModel) {
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
if (vm.conversationEnded) {
// ★ 私聊记录是**只读**的(v1.2 §3.9 形态 B)——那两个 AI 是
// 在你不在场的时候聊的,往里插话等于改历史记录。
// 这里把输入条整条换掉,而不是"能输入但发不出去"。
val privateConv = vm.state.conversations
.firstOrNull { it.id == vm.activeConversationId }?.isPrivate == true
if (privateConv) {
Box(Modifier.weight(1f))
Hint("这是两个智能体的私聊记录,只读。想让他们再聊一次,去「群成员」页。")
} else if (vm.conversationEnded) {
/**
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
*
@@ -337,7 +361,27 @@ fun ChatScreen(vm: AppViewModel) {
} else {
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
// ★ 对话被换了归属时的提示(见 AppViewModel 的 rebasedNote)
if (vm.rebasedNote.isNotBlank()) {
Row(
Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
vm.rebasedNote,
fontSize = 11.sp,
color = doubaoTextSecondary(),
modifier = Modifier.weight(1f),
)
RowAction("知道了") { vm.clearRebasedNote() }
}
}
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
//
// ★★ 顺序:先「要不要让他接着说」,再点名条 ——
// 前者的决策更靠前(它决定这一轮还继不继续),
// 而且它只在有待决移交时才出现。
HandoffBar(vm)
GroupQuickBar(vm)
SessionUsageBar(vm)
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
@@ -380,8 +424,18 @@ fun ChatScreen(vm: AppViewModel) {
// 内核那道拦截是权威,但**界面上也要拦一道** ——
// 让用户敲完一整句话、点发送、再被拒绝,是最差的体验。
// 提示条点一下直达记忆页的情绪区(那就是复活入口)。
//
// ★★ 但**群聊不锁输入框**:死了一个,群里还有别人能接话
// (内核的 `group_chat.resolve` 会把死人跳过、换下一个人)。
// 整条锁掉的话,用户只能干看着一个群不能用 ——
// 用户报的「角色死亡输入框怎么不能用了」就是这个。
// 群聊里只留一条提示,输入框照给。
val deadAgent = vm.activeAgent
if (deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true) {
val dead = deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true
val convNow = vm.state.conversations
.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
val groupNow = convNow?.isGroup == true
if (dead && !groupNow) {
Row(
Modifier
.fillMaxWidth()
@@ -392,7 +446,7 @@ fun ChatScreen(vm: AppViewModel) {
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"「${deadAgent.name}」已经死亡,不能对话。",
"「${deadAgent?.name}」已经死亡,不能对话。",
fontSize = 11.sp,
color = Color(0xFFB3261E),
modifier = Modifier.weight(1f),
@@ -404,11 +458,23 @@ fun ChatScreen(vm: AppViewModel) {
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.background(Color(0xFFB3261E))
.clickable { vm.openMemories(deadAgent.id) }
.clickable { deadAgent?.let { vm.openMemories(it.id) } }
.padding(horizontal = 10.dp, vertical = 5.dp),
)
}
} else {
if (dead && groupNow) {
// 群聊:只提示,**不拦**。被点名的人死了的话,
// 内核会换下一个人接(不再"回主智能体",群里没有主人)
Text(
"「${deadAgent?.name}」已经死亡 —— 群里其他人还能接话。",
fontSize = 11.sp,
color = Color(0xFFB3261E),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 14.dp, vertical = 4.dp),
)
}
InputBar(vm, onPickFile, onMic, speech)
}
}
@@ -461,7 +527,8 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
) {
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
// 这里 path 为空就还是原来的图标)
val art = vm.activeAgent?.image?.portrait.orEmpty()
// ★ 跟**同一个人**:名字是寐眠、头像却是小黑,用户一眼就看出不对
val art = backdropAgent(vm)?.image?.portrait.orEmpty()
if (art.isNotBlank()) {
AssetImage(
path = art,
@@ -550,22 +617,15 @@ private fun HeaderIcon(
/* ------------------------------ 空态大头像 ------------------------------ */
@Composable
private fun HeroSection(greeting: String) {
private fun HeroText(greeting: String) {
Column(
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
Modifier.fillMaxWidth().padding(bottom = 18.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
}
Spacer(Modifier.height(20.dp))
Box(
Modifier
.clip(RoundedCornerShape(16.dp))
.background(doubaoBubble())
.background(doubaoBubbleVeil())
.padding(horizontal = 16.dp, vertical = 14.dp),
) {
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
@@ -573,21 +633,199 @@ private fun HeroSection(greeting: String) {
}
}
/**
* 聊天页顶部的立绘(v1.2 §6.1)。
*
* ★ **跟随说话者**(设置里可关,默认开):群聊时谁发言就换成谁的立绘 ——
* 一眼看出"这句是谁说的"。关掉时固定用主智能体(成员列表第一个)。
*
* ★ 0.3 秒的 crossfade:立绘是**情绪驱动**的,可能一轮换一次;
* 硬切会让人以为界面闪了一下。0.3s 刚好够看出"换了",又不拖沓。
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
* 两处各写一个数字的话,将来改一处必漏另一处。)
*/
/**
* 顶栏和背景该显示**谁** —— **当前正在说话的那个人**。
*
* ★★ 用户的原话:「还是没换标题和背景呀」。
*
* 我上一版理解成「跟当前对话的主人走」,那是错的 ——
* 他要的是**寐眠说话时,顶栏和背景都是寐眠**。
*
* 「不是让你 @ 谁就换哪个背景」那句,意思是**不要光点一下 @ 按钮
* 就提前换**;要跟着**真实的发言者**。内核每轮都 emit 一个
* `speaker` 事件(群聊里就是仲裁结果),跟着它走既"立即"又"名副其实"。
*
* ★ 只在**群聊**里用 `currentSpeakerId`:单聊时它可能还是上一轮群里
* 留下的值,会把单聊的顶栏带跑偏。单聊就认会话主人。
*
* ★ 顶栏、背景、【朗读音色】三处都从这里/`msg.agentId` 取,
* 保证同一条消息上的名字、图、声音是**同一个人**。
*/
private fun backdropAgent(vm: AppViewModel): Agent? {
val convId = vm.activeConversationId.ifBlank { "c_main" }
val conv = vm.state.conversations.firstOrNull { it.id == convId }
if (conv?.isGroup == true && vm.currentSpeakerId.isNotBlank()) {
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId }?.let { return it }
}
return vm.state.agents.firstOrNull { it.id == conv?.agentId.orEmpty() } ?: vm.activeAgent
}
/**
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
*
* ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆,
* 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」,
* 而他要的是整个背景都是这个角色。
*
* ★★ 显示的是**当前对话的智能体**(`activeAgent`),不是"这一轮谁在说"。
* 用户澄清过:「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
* 背景表达的是**这个场景是谁的**(和顶栏那个名字同一件事);
* 群聊里两个人一来一回时背景跟着闪,既晃眼又和顶栏对不上。
* "谁在说话"是**每条消息**自己的事,用 `msg.agentId`(见 [SpeakerTag])。
*
* ★ 两条硬约束:
* · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住;
* · **图要实心、气泡要半透明** —— 这是用户点名要的一对
* (「立绘不要透明的」+「聊天框半透明」)。反过来做(图淡化、气泡实心)
* 等于两头都不讨好:立绘看不清,气泡也白透。
* 所以可读性交给气泡那边([doubaoBubbleVeil]),这里不淡化。
*
* ★ 立绘用 `ContentScale.Fit` 而不是 `Crop`:角色不能被裁掉半个身子。
* 背景图反过来,必须 `Crop` —— `Fit` 会留出底色,铺不满。
*/
@Composable
private fun ChatBackdrop(vm: AppViewModel) {
val who = backdropAgent(vm)
val back = who?.image?.back.orEmpty()
val art = who?.image?.portrait.orEmpty()
if (back.isBlank() && art.isBlank()) return
Box(Modifier.fillMaxSize()) {
if (back.isNotBlank()) {
AssetImage(
path = back,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
}
if (art.isNotBlank()) {
AssetImage(
path = art,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Fit,
)
}
}
}
/**
* 没配立绘时**说清楚 + 给入口**。
*
* ★ 回退链最后一级就是「内置默认人物」(需求 §2.6),所以背景层显示那张图**没错** ——
* 但界面上一个字都不说的话,用户只会觉得"立绘功能没生效",
* 而不知道**得自己去传**(内置那四个示例智能体默认都没有图)。
*
* ★ 它原来长在一个 168dp 圆形立绘(`ChatPortrait`)底下,和背景层重复,
* 已经拆开:图归背景层,这句话单独留着。
*/
@Composable
private fun PortraitHint(vm: AppViewModel) {
val who = backdropAgent(vm) ?: return
if (who.image.portrait.isNotBlank()) return
Text(
"还没有立绘 · 点这里去传一张",
fontSize = 11.sp,
color = Doubao.Blue,
modifier = Modifier.clickable { vm.openAgentEdit(who) },
)
}
/* ------------------------------ 消息 ------------------------------ */
/**
* 气泡上方那行**小字:这条是谁说的**。
*
* ★ 只在**群聊**显示(用户要求:「对话前面写明是谁在说话」)。
* 单聊里只有一个人,每条都标一遍就是噪音 —— 那个名字顶栏已经有了。
*
* ★ 名字从 `msg.agentId` 查(内核一直在消息里存群聊仲裁后的发言者)。
* 老消息没这个字段 → 退回当前智能体;群聊里退错了也只是名字不对,
* 不影响别的(比不显示强,因为不显示就完全分不清谁是谁)。
*
* ★ 自己那侧写「你」而不是昵称:翻记录时"哪句是我说的"要一眼看出来,
* 用昵称反而要在脑子里做一次映射。
*/
@Composable
private fun SpeakerTag(vm: AppViewModel, msg: ChatMessage, mine: Boolean) {
// ★ 会话 id 可能是空串(内核用 "c_main" 兜底)
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
// 单聊只有一个人,每条都标一遍是噪音;群聊和私聊记录(两个 AI 自己聊的)
// 都是"多人在场",不标就完全分不清谁是谁
if (conv == null || (!conv.isGroup && !conv.isPrivate)) return
val name = if (mine) {
"你"
} else {
vm.state.agents.firstOrNull { it.id == msg.agentId }?.name.orEmpty()
.ifBlank { vm.activeAgent?.name.orEmpty() }
}
if (name.isBlank()) return
Text(
name,
fontSize = 11.sp,
color = if (mine) doubaoTextSecondary() else Doubao.Blue,
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = 3.dp),
)
}
@Composable
@OptIn(ExperimentalFoundationApi::class)
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
val clipboard = LocalClipboardManager.current
val speaking = speech.speakingIndex == index
// 长按气泡 → 这个菜单(v1.2 §4.3 的「标记重要」)
var importantMenu by remember { mutableStateOf(false) }
if (msg.role == "user") {
// ★ 长按**用户**消息才能标重要。需求说的是"消息操作栏加标记重要",
// 这里只做用户那一侧,理由是**效果差异**:
// 被标的消息在上下文窗口裁剪时破格携带,而 AI 的回复通常就在
// 最近几轮里、本来就裁不到;用户想留住的是**很久以前问过的那句**。
if (importantMenu) {
androidx.compose.material3.AlertDialog(
onDismissRequest = { importantMenu = false },
title = { Text(if (msg.important) "这条标过了" else "这条消息") },
text = {
Text(
if (msg.important) {
"取消之后它就按普通消息处理了 —— 攒够一批会被裁掉。"
} else {
"标成重要之后,以后裁剪上下文时这条会一直留着," +
"不管过了多少轮。"
},
fontSize = 13.sp,
lineHeight = 19.sp,
)
},
confirmButton = {
androidx.compose.material3.TextButton(
onClick = { vm.toggleImportant(index); importantMenu = false },
) { Text(if (msg.important) "取消标记" else "标记重要", color = Doubao.Blue) }
},
dismissButton = {
androidx.compose.material3.TextButton(
onClick = { importantMenu = false },
) { Text("算了") }
},
)
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
Column(horizontalAlignment = Alignment.End) {
SpeakerTag(vm, msg, mine = true)
msg.attachments.forEach { file ->
Box(
Modifier
.clip(RoundedCornerShape(12.dp))
.background(doubaoBubble())
.background(doubaoBubbleMine())
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -606,18 +844,35 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
Modifier
.widthIn(max = 288.dp)
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
.background(Doubao.Blue)
.background(doubaoBubbleMine())
.combinedClickable(
onClick = { clipboard.setText(AnnotatedString(msg.content)) },
onLongClick = { importantMenu = true },
)
.padding(horizontal = 14.dp, vertical = 11.dp),
) {
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
}
}
// 标过的给一个小标记 —— 不然用户忘了自己标过哪几条,
// 而"这条会不会被裁掉"是他自己决定的
if (msg.important) {
Spacer(Modifier.height(3.dp))
Text(
"★ 重要(不会被裁掉)",
fontSize = 10.sp,
color = Doubao.Blue,
)
}
}
}
return
}
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
// 群聊里标出**这条是谁说的**(用户要求:「对话前面写明是谁在说话」)
SpeakerTag(vm, msg, mine = false)
val hasReasoning = msg.reasoning.isNotBlank()
val hasTrace = msg.toolTrace.isNotEmpty()
@@ -702,7 +957,7 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
Modifier
.widthIn(max = 300.dp)
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
.background(if (msg.error) Doubao.ErrorBg else doubaoBubbleVeil())
.padding(horizontal = 14.dp, vertical = 12.dp),
) {
when {
@@ -826,7 +1081,8 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
// 手动点朗读时清掉"自动朗读念过了"的记录:
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
speech.forgetAutoRead()
speech.speak(msg.content, index)
// 用**这条消息**的发言者挑音色(群聊里每个人不一样)
speech.speak(msg.content, index, msg.agentId)
}
}
Spacer(Modifier.width(10.dp))
@@ -1049,7 +1305,25 @@ private fun InputBar(
Spacer(Modifier.width(8.dp))
if (canSend) {
// ★★ 正在生成时,右边那个圆钮变成「停止」。
//
// 取消能力**一直都有**:内核从 HTTP 到 agent_loop 一路支持 `cancelled`,
// ViewModel 里也建好了 `chatJob`(AtomicBoolean)——
// 但没有任何界面调它,用户只能干等它把话说完。
// 用户的原话就是「对话过程中可中断」。
if (vm.streaming) {
Box(
Modifier
.size(40.dp)
.clip(CircleShape)
.background(doubaoSurface())
.border(1.dp, doubaoBorder(), CircleShape)
.clickable(onClick = { vm.stopGenerating() }),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Stop, "停止生成", tint = Doubao.Blue, modifier = Modifier.size(20.dp))
}
} else if (canSend) {
Box(
Modifier
.size(40.dp)
@@ -1139,6 +1413,44 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
}
}
/**
* 「要不要让他接着说」——
* AI 用 `talk_to` / `pass_turn` 把话交给别人之后,这里摆两个按钮。
*
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
*
* 所以默认(手动)就**停在这儿等用户点**:
* · 「让他说」= 继续把这一轮交出去;
* · 「停在这」= 到此为止。
* 设置里开了「AI 对聊自动模式」就不出现这条,直接接着跑。
*
* ★ 顺带解决了烧钱:默认不会自己一直聊下去。
* ★ 位置在输入框正上方、点名条**上面**:这是"接着聊还是打住"的决策现场。
*/
@Composable
private fun HandoffBar(vm: AppViewModel) {
if (vm.pendingHandoffName.isBlank()) return
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp)
.clip(RoundedCornerShape(12.dp))
.background(doubaoCard())
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"${vm.pendingHandoffFromName.ifBlank { "它" }} 把话交给了 ${vm.pendingHandoffName}",
fontSize = 12.sp,
color = doubaoTextSecondary(),
modifier = Modifier.weight(1f),
)
DoubaoPill(text = "让他说", onClick = { vm.continueHandoff() })
Spacer(Modifier.width(6.dp))
RowAction("停在这") { vm.stopHandoff() }
}
}
/**
* 群聊的成员快捷条(v1.2 §3.9)。
*
@@ -1164,11 +1476,31 @@ private fun GroupQuickBar(vm: AppViewModel) {
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
// 主智能体标一下:没人被 @ 时由它接话,用户得知道"不点名也有话说"
for ((i, pair) in members.withIndex()) {
val label = if (i == 0) "${pair.second}(主)" else pair.second
DoubaoPill(text = "@$label", onClick = { vm.draft = vm.draft + "@${pair.second} " })
// 点名条:**不标"(主)"** —— 用户要求「群聊去掉主人设定」,
// 群里没有老大,没人被 @ 时按顺序轮(kernel 的 group_chat.rotate_next)
for (pair in members) {
// 只插草稿 —— **不碰顶栏/背景**。那两处等内核仲裁完
// (`speaker` 事件)才切,不然会"点了还没发就换了人"
DoubaoPill(text = "@${pair.second}", onClick = { vm.mentionAgent(pair.second) })
}
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
//
// 为什么需要这个按钮:光靠 AI 自己 `pass_turn` 是靠不住的 ——
// 实测它更愿意把话说完,于是"两个智能体对话"永远发生不了
// (用户报的「还是不能互相对话」)。
// 这个按钮不依赖 AI 配合,界面直接按顺序把发言权递过去。
DoubaoPill(text = "让他们聊", onClick = { vm.startAiTalk() })
RowAction("成员") { vm.openMembers(conv.id) }
}
// ★ 仲裁**理由**(v1.2 §3.9):内核发了 note,界面以前收了但从不显示 ——
// 于是"被点的人已死亡,发言权回主智能体"这种事用户只能自己猜。
// 只在有话说时占一行,平时不显示。
if (vm.speakerNote.isNotBlank()) {
Text(
vm.speakerNote,
fontSize = 11.sp,
color = doubaoTextSecondary(),
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
)
}
}

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
@@ -70,6 +70,24 @@ fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
@Composable
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
/**
* 聊天气泡的底色(**半透明**)。
*
* ★ 聊天页现在有一层**实心**的立绘(`ChatScreen.ChatBackdrop`)垫在下面,
* 气泡要是也不透明,那张立绘就白铺了 —— 用户要的正是
* 「立绘看得见、字也读得清」这一对。
*
* ★ 0.78 是这两条的交点:再透字就开始糊在图上,再实立绘就等于没有。
* 别的页面(卡片、弹窗)继续用不透明的 [doubaoBubble],
* 它们底下没有图,半透明只会显脏。
*/
@Composable
fun doubaoBubbleVeil() = doubaoBubble().copy(alpha = 0.78f)
/** 用户自己那侧的气泡(蓝色),同样要半透明 —— 理由同 [doubaoBubbleVeil] */
@Composable
fun doubaoBubbleMine() = Doubao.Blue.copy(alpha = 0.82f)
@Composable
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
@Composable

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
@@ -57,7 +57,6 @@ fun GroupMembersScreen(
) {
val conv: Conversation? = vm.state.conversations.firstOrNull { it.id == conversationId }
var adding by remember { mutableStateOf(false) }
val hostId = conv?.participants?.firstOrNull().orEmpty()
FullScreen(
title = "群成员",
@@ -70,11 +69,29 @@ fun GroupMembersScreen(
// ---- 加人(就地展开,不再弹一层 —— 弹窗压弹窗是手机上的灾难)----
if (adding) {
val inGroup = conv?.participants?.toSet() ?: emptySet()
val candidates = vm.state.agents.filter { it.id !in inGroup }
// ★★ **只能拉同世界观的**(用户确认过这条规则)。
//
// 群聊上下文里有 <worldview> 段、共享记忆也按世界观分空间 ——
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
// 让人点了才被告知"加不进去"是最差的体验。
//
// ★ **未绑世界观的放行**:它没有设定会串,和谁都合得来
// (用户报的「还是加不了人」,其中"黑化豆包"就是未绑的)。
val hostWorldview = vm.state.agents
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
val sameWorldview = vm.state.agents.filter {
it.worldviewId.orEmpty().isBlank() || it.worldviewId.orEmpty() == hostWorldview
}
val candidates = sameWorldview.filter { it.id !in inGroup }
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
SectionLabel("拉谁进来")
Card {
if (candidates.isEmpty()) {
Hint("所有智能体都在群里了。")
Hint(
if (blocked > 0) "没有可以拉的人了。"
else "所有能拉的人都在群里了。",
)
} else {
for (a in candidates) {
Row(
@@ -83,7 +100,10 @@ fun GroupMembersScreen(
// 用的(会新建群聊);已经有成员了就走 `addMember`,
// 不能混 —— 混了会把当前会话换掉,用户会一头雾水。
if (inGroup.isEmpty()) vm.makeGroup(a.id) else vm.addMember(a.id)
adding = false
// ★★ 加完**不收起**(原来这里 `adding = false`)。
// 收起的话,用户加了一个就得再点一次「加人」才能加下一个,
// 体感就是"群聊只能拉两个"(真机反馈)。
// 刷新后 `candidates` 会少一个,接着点就行。
}.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
@@ -92,7 +112,32 @@ fun GroupMembersScreen(
Text(a.name, fontSize = 14.sp, color = doubaoText())
}
}
Hint("拉人无条件:会话是你的,想拉谁就拉谁。只能拉同世界观的。")
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
}
// ★★ 被世界观挡下的**也列出来**,并说清原因。
//
// 不列的话用户只看到"某些智能体不见了",以为功能坏了 ——
// 他报的「还是加不了人」有一半是这种感觉。
val blockedAgents = vm.state.agents.filter { it.id !in inGroup && it !in sameWorldview }
if (blockedAgents.isNotEmpty()) {
Spacer(Modifier.height(10.dp))
Text(
"这些绑的是别的世界观,拉进来会串设定(两套背景、共享记忆也会混):",
fontSize = 11.sp,
lineHeight = 16.sp,
color = doubaoTextSecondary(),
)
Spacer(Modifier.height(4.dp))
for (a in blockedAgents) {
Text(
"· ${a.name}",
fontSize = 12.sp,
color = doubaoTextSecondary(),
modifier = Modifier.padding(start = 6.dp, top = 2.dp),
)
}
Spacer(Modifier.height(4.dp))
Hint("想拉它们:先去它们的编辑页绑成这个世界观(或者另开一个群)。")
}
}
Spacer(Modifier.height(10.dp))
@@ -107,7 +152,6 @@ fun GroupMembersScreen(
Card {
for ((i, id) in conv.participants.withIndex()) {
val a: Agent? = vm.state.agents.firstOrNull { it.id == id }
val isHost = id == hostId
Row(
Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -115,31 +159,26 @@ fun GroupMembersScreen(
AgentFace(a, 40)
Spacer(Modifier.width(10.dp))
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
a?.name ?: "(已删除)",
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
color = doubaoText(),
)
if (isHost) {
Spacer(Modifier.width(6.dp))
HostBadge()
}
}
Text(
if (isHost) "没人被 @ 的时候由它接话"
else "第 ${i + 1} 个进群的",
a?.name ?: "(已删除)",
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
color = doubaoText(),
)
// ★ 这里原来标了「主」徽章 + "没人被 @ 的时候由它接话"。
// 用户要求「群聊去掉主人设定」—— 群里没有老大,
// 没人被 @ 时**按顺序轮**(见 kernel/group_chat.rotate_next)。
Text(
"第 ${i + 1} 个进群的",
fontSize = 11.sp,
color = doubaoTextSecondary(),
)
}
RowAction("状态") { onOpenStats(id) }
if (!isHost) {
Spacer(Modifier.width(6.dp))
// ★ 主智能体走不到这里(上面那个 if)—— 它是兜底发言的人
RowAction("移出") { vm.removeMember(id) }
}
Spacer(Modifier.width(6.dp))
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
// 就没有"动不了"的那一个。内核那边会拦住"最后一个"
RowAction("移出") { vm.removeMember(id) }
}
}
}
@@ -147,23 +186,60 @@ fun GroupMembersScreen(
Spacer(Modifier.height(6.dp))
Hint(
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
"被点的人这一轮一定发言。没人被点时由主智能体兜底,不会冷场。",
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
)
}
}
/** 「主智能体」小标签(它和普通成员的区别只在兜底发言,用个浅色标签就够) */
@Composable
private fun HostBadge() {
Text(
"主智能体",
fontSize = 10.sp,
color = Doubao.Blue,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.background(Doubao.Blue.copy(alpha = 0.12f))
.padding(horizontal = 6.dp, vertical = 2.dp),
)
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
//
// 放这儿而不是抽屉里:抽屉已经有七项了(用户刚说过"太挤了"),
// 而**群成员页本来就有成员** —— 从这儿点两个人比在抽屉里
// 再开一个挑人对话框顺得多。
//
// 内核早就完整实现了(10 轮安全网、一方触顶另一方单方面收尾、
// 摘要进共享记忆),但界面上一直没有入口 —— 这个需求项碰不到。
Spacer(Modifier.height(12.dp))
SectionLabel("私下聊聊")
Card {
Hint(
"点两个名字,让他们在后台自主对聊 —— 你不在场。" +
"聊完的摘要会写进共享记忆,完整记录在会话列表里能翻。",
)
Spacer(Modifier.height(8.dp))
for (id in conv.participants) {
val a = vm.state.agents.firstOrNull { it.id == id }
val picked = id in vm.privatePair
Row(
Modifier.fillMaxWidth().clickable { vm.togglePrivatePick(id) }
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
if (picked) "✓" else "○",
fontSize = 15.sp,
color = if (picked) Doubao.Blue else doubaoTextSecondary(),
)
Spacer(Modifier.width(10.dp))
Text(a?.name ?: "(已删除)", fontSize = 14.sp, color = doubaoText())
}
}
Spacer(Modifier.height(6.dp))
Row {
RowAction("开始私聊") { vm.startPickedPrivateChat() }
if (vm.privatePair.isNotEmpty()) {
Spacer(Modifier.width(12.dp))
RowAction("清空选择") { vm.cancelPrivatePick() }
}
}
if (vm.privateChatRunning.isNotBlank()) {
Spacer(Modifier.height(6.dp))
Hint("${vm.privateChatRunning} 正在聊……(要跑一会儿,别退出去)")
}
if (vm.privateChatResult.isNotBlank()) {
Spacer(Modifier.height(6.dp))
Hint(vm.privateChatResult)
}
}
}
}
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */

View File

@@ -0,0 +1,139 @@
package com.doubao.lynxclone.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Base64
import java.io.ByteArrayOutputStream
/**
* 选图 → 读成能上传的 base64。
*
* ## 为什么必须在这里压缩(这是真机上报回来的 bug)
*
* 用户选的是**手机相册里的照片**,现在动辄 30~55MB(一亿像素)。
* 原样读进来会连撞三堵墙:
*
* ① `readBytes()` 把 55MB 全读进内存,`Base64` 再翻 4/3 倍 → 低端机直接 OOM;
* ② 内核 `read_json_body()` 每条接口有自己的上限,图片这条路走的是小上限,
* 38MB 的请求体一进去就被判「请求体过大」;
* ③ 更糟的是那个异常被上层吞掉,最后报出来的是
* **「不认识的外观槽位」** —— 一个和真实原因毫无关系的错误,
* 用户只看到"设置不了",查代码的人也会往槽位名上去找。
*
* 所以压缩不是优化,是**这条链路能不能用**的前提:
* 一张 4000×3000 的照片按最长边 1600 采样后大约是 200~400KB,
* 比原来小两个数量级,上面三堵墙一次全绕过。
*
* ## 两种图**不能**压
*
* - **GIF**:缩放会丢动画(这个 App 明确支持动图,"动图会动"是写在界面上的);
* - **SVG**:本来就是矢量,栅格化等于自毁。
*
* 这两种原样传,只在超过内核 20MB 上限时明确报错 —— 让用户换个文件,
* 而不是静默失败。
*/
/** 压缩后最长边不超过它。1600 在手机上看立绘/背景已经够清楚 */
private const val MAX_EDGE = 1600
/** 压到这么大就收手。经验值:1600 边长的 JPEG 通常在 200~400KB */
private const val TARGET_BYTES = 3 * 1024 * 1024
/** 内核 `_set_asset` 的硬上限,超过它一定传不上去,这里提前拦下来把话说清楚 */
private const val MAX_BYTES = 20 * 1024 * 1024
/** 一张选好的图。[note] 是给用户看的一句话,说明这张图被怎么处理了 */
data class PickedImage(val name: String, val base64: String, val note: String)
private fun mb(n: Int): String = String.format("%.1f", n / 1048576.0)
/**
* 读一张图并压到能传的大小。
*
* 失败时抛 [IllegalStateException],**消息是可以直接显示给用户的中文** ——
* 调用方 `catch` 之后原样 `showHint(e.message)` 就行,
* 不要再包一层"上传失败",那样又把原因盖掉了。
*/
fun readImageForUpload(ctx: Context, uri: Uri): PickedImage {
val resolver = ctx.contentResolver
val rawName = (uri.lastPathSegment ?: "image").substringAfterLast('/').ifBlank { "image" }
// ★ 名字靠不住:SAF 给的常常是 `image_1000018030` 这种没有扩展名的。
// MIME 才是可信的(getType 对 content:// 会去查 provider)。
val mime = (resolver.getType(uri) ?: "").lowercase()
val isGif = mime.contains("gif")
val isSvg = mime.contains("svg")
if (isGif || isSvg) {
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
?: throw IllegalStateException("读不出这个文件")
if (bytes.isEmpty()) throw IllegalStateException("这个文件是空的")
if (bytes.size > MAX_BYTES) {
throw IllegalStateException("这张图 ${mb(bytes.size)}MB,超过 20MB 上限了,换一张吧")
}
return PickedImage(
name = rawName,
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
note = if (isGif) "动图原样上传(压缩会丢动画)" else "SVG 原样上传",
)
}
// ---- 位图:先只问尺寸,不解码像素 ----
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
throw IllegalStateException("这不是一张能识别的图片")
}
// 压不下来就一轮轮降:边长 ×3/4、质量 ×4/5。四轮足够把任何照片压进 3MB
var edge = MAX_EDGE
var quality = 88
var last = 0
repeat(4) {
val opts = BitmapFactory.Options().apply { inSampleSize = sampleFor(bounds, edge) }
val bmp = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) }
?: throw IllegalStateException("读不出这张图")
val hasAlpha = bmp.hasAlpha()
val out = ByteArrayOutputStream()
bmp.compress(if (hasAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, quality, out)
val w = bmp.width
val h = bmp.height
bmp.recycle()
val bytes = out.toByteArray()
last = bytes.size
if (bytes.size <= TARGET_BYTES) {
return PickedImage(
// ★ 扩展名要跟着真实格式走:压成 JPEG 却叫 .png,虽然解码器看魔数也能认,
// 但导出的包里会留下一个名不副实的文件
name = "${rawName.substringBeforeLast('.')}.${if (hasAlpha) "png" else "jpg"}",
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
note = "已压到 ${w}×${h}、${bytes.size / 1024}KB 再上传",
)
}
edge = edge * 3 / 4
quality = (quality * 4) / 5
}
throw IllegalStateException("这张图压到 ${mb(last)}MB 还是太大,换一张吧")
}
/**
* 采样率(2 的幂,`BitmapFactory` 只认这个)。
*
* ★ 判据是**最长边**(写成 `||`),不是"宽高都超"。
* 写成 `&&` 的话 4000×3000 一张只缩到 4000(短边 3000 没到阈值就停了),
* JPEG 出来还有 2.2MB;按长边缩一档到 2000×1500 就只有它的三分之一。
*
* 取**解码后仍然 ≥ maxEdge** 的那一档 —— 宁可多留一点,
* 后面还有缩小/降质的循环兜着;反过来取小了就再也补不回清晰度。
*/
private fun sampleFor(bounds: BitmapFactory.Options, maxEdge: Int): Int {
var sample = 1
while (bounds.outWidth / (sample * 2) >= maxEdge ||
bounds.outHeight / (sample * 2) >= maxEdge
) {
sample *= 2
}
return sample
}

View File

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
@@ -21,6 +21,9 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Dashboard
import androidx.compose.material.icons.filled.EditNote
import androidx.compose.material.icons.filled.Group
import androidx.compose.material.icons.filled.Memory
import androidx.compose.material.icons.filled.Layers
import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.Settings
@@ -44,8 +47,11 @@ import androidx.compose.ui.unit.sp
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
*
* 现在抽屉第一层只留天天用的(新话题 / 智能体 / 笔记 / 模型),
* 其余收进这里。
* ★★ 后来又收了一次(用户第二次说"太挤了"、"把别的放更多里"):
* 抽屉第一层现在只剩**四件天天用的**:新话题 / 智能体 / 记忆 / 更多功能。
* 笔记、模型、新建群聊都挪进来了 ——
* 「模型」虽然也常用,但它是个**配置**,配好基本不动;
* 抽屉里腾出来的位置留给对话列表更值。
*
* ## 按项目约定:独立全屏界面
*
@@ -60,6 +66,9 @@ fun MoreSheetScreen(
onOpenMeetings: () -> Unit,
onOpenTerminal: () -> Unit,
onOpenSettings: () -> Unit,
onNewGroup: () -> Unit,
onOpenNotes: () -> Unit,
onOpenModels: () -> Unit,
onClose: () -> Unit,
) {
BackHandler(enabled = true) { onClose() }
@@ -76,6 +85,28 @@ fun MoreSheetScreen(
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
item {
// 从抽屉挪进来的三个(都是"偶尔用一次"那一档)
MoreRow(
icon = Icons.Filled.Group,
title = "新建群聊",
subtitle = "拉几个智能体到一个会话里,可以 @ 点名",
) { onNewGroup() }
}
item {
MoreRow(
icon = Icons.Filled.EditNote,
title = "笔记",
subtitle = "AI 替你记下来的东西",
) { onOpenNotes() }
}
item {
MoreRow(
icon = Icons.Filled.Memory,
title = "模型",
subtitle = "换模型 / 思考强度(配好基本不用动)",
) { onOpenModels() }
}
item {
MoreRow(
icon = Icons.Filled.Dashboard,

View File

@@ -102,6 +102,10 @@ private val MODEL_FIELDS = listOf(
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
// ★ v1.2:命中缓存的单价单独填。各家命中都比未命中便宜得多(常见 1/10),
// 不填的话费用按未命中的价格算 —— **越用越高估**,而用户会以为
// 自己真花了那些钱。留空 = 按未命中单价算(保守估计,不会低估)。
Field("cachePricePerK", "命中单价(元/千 Token)", "留空 = 按上面的单价算(偏保守)", number = true),
Field(
"noTools", "不支持工具调用",
"这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," +
@@ -416,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)
@@ -443,11 +453,9 @@ private fun ResourceEditScreen(
val slot = pendingSlot
pendingSlot = ""
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
runCatching {
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
vm.uploadWorldviewAsset(id, slot, name, Base64.encodeToString(bytes, Base64.NO_WRAP))
}.onFailure { vm.showHint("读不出这张图") }
// 和智能体编辑页**同一份实现** —— 这条链路的坑(大图、GIF、SAF 没扩展名)
// 两边一模一样,抄两份迟早只修一份
vm.uploadWorldviewAssetFrom(ctx.applicationContext, id, slot, uri)
}
// 上传完 image 会变,跟着刷新预览
vm.state.worldviews.firstOrNull { it.id == id }?.let {
@@ -473,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() }
}
},
@@ -548,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("外观(四件套)")

View File

@@ -512,6 +512,59 @@ fun SettingsScreen(vm: AppViewModel) {
}
/* ---------------- 个人资料 ---------------- */
// 外观(v1.2 §6.1)
SettingsCard("外观") {
FormSwitch(
title = "背景跟随说话者",
sub = "群聊时,展示区的立绘和背景跟着当前发言的人换 —— " +
"一眼就能看出这句话是谁说的。关掉的话固定用主智能体的。",
checked = vm.state.settings.followSpeaker,
onChange = { vm.setFollowSpeaker(it) },
)
}
// 对话(v1.2 §3.9 / §4.3)
//
// ★★ 这几个数字内核早就有、界面一直缺着 —— 用户只能手改 settings.json。
// 而它们**都要和内核的默认值一致**,不然界面显示"20"而内核按别的跑。
SettingsCard("对话") {
NumberRow(
title = "对话上下文窗口",
sub = "每轮最多带最近多少轮对话进模型。超出的直接丢掉(不摘要)—— " +
"该记住的走记忆系统。攒够几轮才裁一次,见下一项。",
value = vm.state.settings.contextWindow,
onChange = { vm.setContextWindow(it) },
)
Spacer(Modifier.height(10.dp))
NumberRow(
title = "攒够几轮裁一次",
sub = "不是「超一点就裁」,而是攒够这个数才裁一批 —— " +
"每轮都裁的话前缀缓存每轮都失效,比多带几轮贵得多。",
value = vm.state.settings.contextBatch,
onChange = { vm.setContextBatch(it) },
)
Spacer(Modifier.height(10.dp))
NumberRow(
title = "私聊最多几轮",
sub = "两个智能体后台对聊时的上限(一轮 = 双方各说一次)。" +
"这是安全网 —— 它们没有「该结束了」的内在信号。",
value = vm.state.settings.privateChatRounds,
onChange = { vm.setPrivateChatRounds(it) },
)
Spacer(Modifier.height(10.dp))
// ★★ 用户要求:「talk_to 是用户可以选择传递和停止,有自动模式
// (不用用户确认)」—— 所以默认是**手动**(关),
// 群聊里 AI 交了话就停下来等你点;开了这个才是自动接着跑。
FormSwitch(
title = "AI 对聊自动模式",
sub = "关(默认):群里 AI 把话交给别人时,底下会出现" +
"「让他说 / 停在这」两个按钮,由你决定要不要接着聊。" +
"开:不用确认,自动一轮轮接着跑(最多几轮)。",
checked = vm.state.settings.aiTalkAuto,
onChange = { vm.setAiTalkAuto(it) },
)
}
SettingsCard("个人资料") {
FormLabel("昵称")
FormField(
@@ -1270,3 +1323,41 @@ private fun secretOrNull(raw: String): String? {
if (v.all { it == '•' }) return null
return v
}
/**
* 一行数字设置(v1.2 的上下文窗口 / 裁剪批量 / 私聊轮数)。
*
* ★ 独立一个组件而不是塞三个 `OutlinedTextField`:它们长得一样、
* 行为也一样(只收数字、失焦/改完就存),抄三遍迟早有一处不一样。
*/
@Composable
private fun NumberRow(
title: String,
sub: String,
value: Int,
onChange: (Int) -> Unit,
) {
var draft by remember(value) { mutableStateOf(value.toString()) }
Column(Modifier.fillMaxWidth()) {
Text(title, fontSize = 14.sp, color = doubaoText())
Spacer(Modifier.height(4.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
value = draft,
onValueChange = { s ->
val digits = s.filter { it.isDigit() }.take(4)
draft = digits
digits.toIntOrNull()?.takeIf { it > 0 }?.let(onChange)
},
singleLine = true,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
),
modifier = Modifier.width(100.dp),
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
)
}
Spacer(Modifier.height(4.dp))
Text(sub, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
}
}

View File

@@ -91,6 +91,24 @@ fun TokenUsageScreen(
Spacer(Modifier.width(24.dp))
Metric("输出", usage.output)
}
// ★ 缓存统计(v1.2):**这家没给就不显示**。
// 不是每家都返回缓存字段,显示两个恒为 0 的数会让用户
// 以为"缓存完全没生效" —— 那是假警报,比不显示更糟。
if (usage.hasCacheInfo) {
Spacer(Modifier.height(10.dp))
Row {
Metric("缓存命中", usage.cacheHit)
Spacer(Modifier.width(24.dp))
Metric("缓存未命中", usage.cacheMiss)
}
Spacer(Modifier.height(4.dp))
Text(
"命中率 ${(usage.hitRate * 100).toInt()}% —— " +
"命中缓存的输入便宜得多,这一段没白存",
fontSize = 11.sp,
color = Doubao.Blue,
)
}
if (usage.pricePerK > 0 && usage.cost != null) {
Spacer(Modifier.height(10.dp))
Text(
@@ -180,6 +198,18 @@ fun TokenUsageScreen(
color = doubaoTextSecondary(),
)
}
// ★ 缓存命中/未命中(v1.2)。**这家没给就不显示这一行** ——
// 不是每家都返回缓存字段,显示一个恒为 0 的"命中率"
// 会让用户以为"缓存完全没生效"(那是个假警报)
if (m.hasCacheInfo) {
Spacer(Modifier.height(2.dp))
Text(
"命中 ${fmtTokens(m.cacheHit)} · 未命中 ${fmtTokens(m.cacheMiss)}" +
" · 命中率 ${(m.hitRate * 100).toInt()}%",
fontSize = 11.sp,
color = Doubao.Blue,
)
}
}
}
}

View File

@@ -362,7 +362,7 @@ def handle(handler, pathname: str, method: str) -> bool:
if len(seg) < 2 or seg[0] != 'api':
return False
def body():
def body(limit: int = 0):
"""
解析请求体。
@@ -370,10 +370,22 @@ def handle(handler, pathname: str, method: str) -> bool:
★ 但注意:往下传的时候必须**调用它**(`body()`)——
直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`,
而那个错看起来像"字段名写错了"。这里踩过一次。
★ [limit] 给了就用它,不给就走 `read_json_body` 的默认小上限 ——
图片那条路是唯一的例外,见 `ASSET_BODY_LIMIT`。
★★ 失败时**不能只 `return {}`**:那样"请求体太大 / 不是合法 JSON"
会在下游表现成"某个字段是空的",于是报出牛头不对马嘴的错误
(真机上就是大图报「不认识的外观槽位」)。原因挂到 handler 上,
需要的地方用 `body_error(handler)` 取出来。
"""
# 每次进来先清掉上一次的残留,否则一次失败会永远跟着后面所有请求
handler.body_error = ''
try:
if limit:
return handler.read_json_body(limit)
return handler.read_json_body()
except Exception: # noqa: BLE001
except Exception as exc: # noqa: BLE001
handler.body_error = str(exc)
return {}
def err(code: int, msg: str):
@@ -390,7 +402,7 @@ def handle(handler, pathname: str, method: str) -> bool:
return True
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST':
return _import_agent(handler, body(), err)
return _import_agent(handler, body(UPLOAD_BODY_LIMIT), err)
if seg[1] == 'agents' and len(seg) == 3:
aid = seg[2]
@@ -480,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:
@@ -492,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}」的数值')
@@ -547,7 +613,7 @@ def handle(handler, pathname: str, method: str) -> bool:
# ---------------- 外观图片(四件套)----------------
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
return _set_asset(handler, 'agents', seg[2], body(), err)
return _set_asset(handler, 'agents', seg[2], body(UPLOAD_BODY_LIMIT), err)
# ---------------- 单条记忆 ----------------
if seg[1] == 'memories' and len(seg) == 3:
@@ -636,7 +702,7 @@ def _memories(handler, method: str, seg: list, body, err) -> bool:
# /memories/import
if tail == ['import'] and method == 'POST':
return _memory_import(handler, agent, body(), err)
return _memory_import(handler, agent, body(UPLOAD_BODY_LIMIT), err)
return False
@@ -933,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 "",
}
@@ -979,12 +1052,12 @@ def _resource_route(handler, seg: list, method: str, body, err):
if len(seg) == 4 and seg[3] in ('package', 'export') and method == 'GET':
return _export_rulepack(handler, seg[2], err)
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
return _import_rulepack(handler, body(), err)
return _import_rulepack(handler, body(UPLOAD_BODY_LIMIT), err)
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
return _resource_import(handler, name, body(), err)
return _resource_import(handler, name, body(UPLOAD_BODY_LIMIT), err)
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
# 世界观的外观图(需求 3.6:沿用同一套四件套)
return _set_asset(handler, 'worldviews', seg[2], body(), err)
return _set_asset(handler, 'worldviews', seg[2], body(UPLOAD_BODY_LIMIT), err)
if len(seg) == 4 and seg[3] == 'memories' and method == 'GET':
# 世界观的**共享记忆**(大家共同记得什么)—— 只读视角
return _world_memories(handler, seg[2], err)
@@ -1074,6 +1147,9 @@ def _usage_payload(agent: dict) -> dict:
used = usage['total']['input'] + usage['total']['output']
# 单价(元/千 Token):在**全局模型列表**里配,填了才估费用
price = 0.0
cache_price = 0.0
entry = {} # ★ 先给个空 dict:下面只有 mid 非空才会填它,
# 而返回时无条件读 `entry` —— 不初始化会 NameError
mid = agent.get('modelId') or ''
if mid:
entry = store.get_resource('models', mid) or {}
@@ -1081,6 +1157,10 @@ def _usage_payload(agent: dict) -> dict:
price = float(entry.get('pricePerK') or 0)
except (TypeError, ValueError):
price = 0.0
try:
cache_price = float(entry.get('cachePricePerK') or 0)
except (TypeError, ValueError):
cache_price = 0.0
return {
'agentId': agent.get('id') or '',
'name': agent.get('name') or '',
@@ -1089,6 +1169,10 @@ def _usage_payload(agent: dict) -> dict:
# v1.2 缓存统计:两家都没给时是 0/0,界面据此不显示那一列
'cacheHit': usage['total'].get('cacheHit', 0),
'cacheMiss': usage['total'].get('cacheMiss', 0),
# ★ 命中缓存的单价(v1.2)。各家命中都比未命中便宜得多(常见 1/10),
# 只按未命中单价算的话费用会**越用越高估** —— 而用户会以为
# 自己真花了那些钱。
'cachePricePerK': cache_price,
'total': used,
'byModel': usage['byModel'],
'limit': limit,
@@ -1133,6 +1217,24 @@ def _export_agent(handler, agent_id: str, err) -> bool:
#: 外观四件套的槽位名(和需求 2.5 的 smartInfo.json 一一对应)
ASSET_KEYS = ('front', 'back', 'border-main', 'border-info')
#: **上传类**接口单独给的请求体上限(图片槽位 + 四种包导入)。
#:
#: ★ 为什么别的接口 4MB、这里要 48MB:这些东西进 JSON 之前都要 base64,
#: 体积是原件的 4/3 还要加转义。
#: - 图片:真机上用户选的是**手机相册的照片**(30~55MB 很常见),
#: base64 之后 38~73MB。默认那 4MB 一进去就被 read_json_body 判
#: 「请求体过大」,而上层那个 `except` 把异常吞成空 dict,
#: 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
#: 用户只看到"设置不了"。(这就是真机上报回来的那个 bug。)
#: - 包导入:带外观图片的智能体包,zip 上到十几 MB,base64 之后还要再大。
#:
#: 现在前端会先把位图压到 3MB 以内(见 ImagePick.kt),走这里的常态是几百 KB;
#: 这个上限留给**不压缩的 GIF/SVG** 和包导入兜底。
#:
#: ★ 别把这个上限按"最小的那个调用方"给 —— 这个仓库里已经出现过一次
#: 「内核说这图可以(20MB),通道却说请求体太大(4MB)」的自相矛盾。
UPLOAD_BODY_LIMIT = 48 * 1024 * 1024
#: v1.2 立绘表支持的五档(和情绪 preset 对齐,需求 2.5)
PORTRAIT_PRESETS = ('喜', '怒', '哀', '平常', '死亡')
@@ -1197,13 +1299,26 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
err(404, '没有这一项')
return True
# ★★ `key` 必须在这里读出来 —— 我改五档槽位时**把这行删掉了**,
# 于是下面 `key.partition(':')` 直接 NameError → 整个接口 500。
# 表现是"角色图设置不了"(任何图都传不上去)。
# 而当时的探针**没测这个接口**,所以一路绿着过去了。
key = str(body.get('key') or '').strip()
# ★ v1.2:立绘是**五档**,所以槽位名允许带档位 —— `front:喜`。
# 不带档位的 `front` 视为「平常」档(兼容旧界面和旧调用)。
base, _, slot = key.partition(':')
base = base.strip()
slot = slot.strip()
if base not in ASSET_KEYS:
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
# ★ 先看请求体是不是根本没读进来(太大 / 不是合法 JSON)。
# 那种情况下 `key` 必然是空的,报"槽位不认识"等于把人往完全错误的
# 方向带 —— 真机上就是这么发生的:30MB 的照片 → 请求体超上限 →
# 报的却是「不认识的外观槽位」,查了半天槽位名。
why = getattr(handler, 'body_error', '')
if why:
err(400, f'上传内容没收全:{why}')
else:
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
return True
if base == 'front':
slot = slot or '平常'
@@ -1238,7 +1353,7 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
dest = os.path.join(_asset_dir(owner_id), f'front-{_safe_segment(slot)}-{name}')
with open(dest, 'wb') as fh:
fh.write(blob)
_drop_file(fronts.get(slot)) # 换图时把旧的那张删掉,不然越攒越多
_drop_replaced(fronts.get(slot), dest) # 换图时删旧的那张,不然越攒越多
fronts[slot] = dest
image['front'] = fronts
return _send_json_ok(handler, {
@@ -1263,7 +1378,7 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
dest = os.path.join(_asset_dir(owner_id), f'{base}-{name}')
with open(dest, 'wb') as fh:
fh.write(blob)
_drop_file(image.get(base))
_drop_replaced(image.get(base), dest)
image[base] = dest
return _send_json_ok(handler, {
'item': save(image),
@@ -1283,6 +1398,33 @@ def _drop_file(path) -> None:
pass
def _drop_replaced(old, keep: str) -> None:
"""
换图时删掉旧的那张 —— 但**新旧是同一个文件时,千万不能删**。
★★ 这个 bug 是真机上踩出来的(而且随手试一次碰不到):
落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**,
于是这段顺序出问题:
open(dest,'wb') 写新内容
_drop_file(旧路径) ← 旧路径 == dest,刚写的那张被自己删了
image[base] = dest ← 留下一个指向**不存在文件**的引用
结果:资源目录空着,state 里却指着一个幽灵路径,界面回退到默认图。
表现是"同一张图传第二次就没了"。
第一次传时用的是 SAF 给的 `image_1000018033` 这种 segment,名字不一样,
所以只有"第二次"才触发 —— 用户报的"设置不了"里就混着这一种。
"""
p = str(old or '').strip()
if not p:
return
try:
if os.path.abspath(p) == os.path.abspath(str(keep or '')):
return
except (OSError, ValueError):
pass
_drop_file(p)
def _import_agent(handler, body, err) -> bool:
"""
导入智能体包(需求 2.5)。

View File

@@ -329,6 +329,10 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
# 按开关动态追加,两边永远一致。
#
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
# ★ 新一轮开始:清掉上一轮的发言权移交(v1.2 §3.9 的"一轮最多一次")。
# 放这儿是因为它必须**每轮**重置,而且和线程无关(工具跑在 worker 线程里)
tools_runtime.begin_round()
if tools_runtime.ui_tools_enabled(settings):
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
@@ -352,6 +356,10 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
system_prompt = (system_prompt + '\n\n【当前状况】\n'
+ '\n'.join(_turn['narration'])).strip()
for _e in _turn.get('errors') or []:
# ★ 异常要**让用户看见**(需求附录 E:"异常归零 + UI 提示")。
# 只 print 到 stderr 的话,用户看到的只是"这轮回复有点怪",
# 而完全不知道是脚本报错了 —— 而脚本是他自己写的。
emit({'type': 'rule_error', 'message': _e})
print(f'[rule] {_e}', file=sys.stderr)
except Exception as _exc: # noqa: BLE001 - 规则引擎坏了不该让对话发不出去
print(f'[rule] 状态脚本执行失败:{_exc}', file=sys.stderr)
@@ -420,6 +428,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
answer = ''
reasoning_all = ''
tool_call_count = 0
# ★ 工具调用的**明细**(不只次数)。
#
# 界面上的"工具卡片"(调了什么、成没成、返回了什么)以前只有流式那一刻
# 能看到 —— 因为这份明细**从来没落过库**,重启 App 就全没了。
# 用户的原话:「工具怎么重启就不显示了」。
#
# 只留 id/name/ok/result 四样:args 可能很长(贴进去的代码),
# 而用户真正想回看的是"它做了什么、拿到什么"。result 也截断,
# 不然一条消息能撑爆会话 JSON。
tool_trace = []
usage = None
for round_index in range(max_rounds):
@@ -486,6 +504,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
return {
'content': final, 'reasoning': reasoning_all,
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
'toolTrace': tool_trace,
}
convo.append({
@@ -541,6 +560,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
'result': payload,
})
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
# ★ 记明细(落库用,见上面 tool_trace 的注释)
tool_trace.append({
'id': tc.get('id') or '',
'name': tc.get('name') or '',
'ok': bool(result.get('ok')),
'result': str(payload)[:800],
})
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
emit({
@@ -555,4 +581,5 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
return {
'content': answer, 'reasoning': reasoning_all,
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
'toolTrace': tool_trace,
}

View File

@@ -1,4 +1,4 @@
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
## 为什么是"内置工具"而不是 `tools/*.py`
@@ -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'])
@@ -630,8 +637,10 @@ def pass_turn(args: dict) -> dict:
me = _me()
if not me:
raise ValueError('拿不到当前智能体')
ctx = tools_runtime.current_context()
if ctx.get('handoffUsed'):
# ★★ 用 tools_runtime 的**轮次级状态**,不能用工具上下文 ——
# 工具跑在 worker 线程里,写进 thread-local 的标记会随线程消失,
# 于是"一轮最多一次"永远不生效(踩过,见 tools_runtime.begin_round 的注释)
if tools_runtime.handoff_state().get('used'):
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
# 不然模型会以为是"对方有问题",而不是"规则不允许"
raise ValueError('这一轮你已经移交过发言权了(一轮最多一次),直接回复就行')
@@ -644,13 +653,151 @@ def pass_turn(args: dict) -> dict:
# ★ 需求明文:死亡目标移交无效。这里**如实告诉模型**,
# 它就会自己在正文里圆过去(而不是干等着对方开口)
raise ValueError(f'「{target.get("name")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
# ★ 用 update_context 而不是 push_context —— 后者是**替换**语义,
# 会把 agentId / conversationId 一起冲掉,接着这个工具里的 _me() 就炸了
tools_runtime.update_context(handoffTo=target['id'], handoffUsed=True)
tools_runtime.note_handoff(target['id'])
return {'handed_to': target.get('name'),
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
TALK_TO = {
'name': 'talk_to',
'description': (
'在群聊里**主动对一个或多个智能体说话**。\n'
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
'★ 一次可以找**好几个人**(`agents` 列表),他们会**挨个**回应。\n'
'★ `private=true` 时这条只有**目标**看得到,群里其他智能体看不到 ——\n'
' 用户能看到(他是观察者),但别的 AI 不会知道你们说了什么。\n'
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
'★ 单聊里没有"别人",调了会报错。'
),
'parameters': {
'type': 'object',
'properties': {
'agents': {
'type': 'array',
'items': {'type': 'string'},
'description': '对方的名字列表(只找一个人也可以只写一个)。他们会按顺序挨个回应。',
},
'agent': {
'type': 'string',
'description': '老写法:只找一个人时可以直接写名字(等价于 agents=[名字])。',
},
'content': {'type': 'string', 'description': '你要对他们说的话'},
'private': {
'type': 'boolean',
'description': '私聊模式:只有目标能看到这条,群里其他智能体看不到(默认 false)。',
},
},
'required': ['content'],
},
}
def talk_to(args: dict) -> dict:
"""
主动找群里的一个或多个智能体说话。
★★ 三个能力都是用户点名要的:
① **能说具体的话**(`content`)
`pass_turn` 只交发言权、不带内容 —— 对方接到一片空白,聊不起来。
② **一次找多个人**(`agents`)—— 他们**挨个**回话。
发言权排成队列交给 `tools_runtime`,界面逐个接下去。
③ **私聊模式**(`private=true`)—— 这条只有目标看得到,
群里其他人(包括别的 AI)都不知道你们说了什么。
落库时打在消息的 `privateTo` 上;`app.py` 组装 history 时
会按"是不是给我的"过滤掉,所以别的 AI 真的看不到。
★ 说完之后把发言权交出去(`note_handoff`,多目标时排队)——
界面据此逐个让他们回应;他们也可以反过来再 `talk_to` 回来。
"""
import group_chat
import tools_runtime
me = _me()
if not me:
raise ValueError('拿不到当前智能体')
ctx = _ctx()
conv_id = str(ctx.get('conversationId') or '')
conv = store.get_conversation(conv_id) or {}
if not group_chat.is_group(conv):
raise ValueError('这条不是群聊 —— 只有群里有「别人」可以聊')
if tools_runtime.handoff_state().get('used'):
# 和 pass_turn 共用"一轮最多一次"那个标记:要么移交、要么找人说,
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
# ★ 目标名单:`agents` 列表优先,兼容老的单数 `agent`
raw = args.get('agents')
wanted = []
if isinstance(raw, list):
wanted = [str(x or '').strip() for x in raw]
elif raw:
wanted = [str(raw or '').strip()]
if not wanted:
single = str(args.get('agent') or '').strip()
if single:
wanted = [single]
wanted = [x for x in wanted if x]
if not wanted:
raise ValueError('要跟谁说?写 agent 或 agents')
targets, missing = [], []
for name in wanted:
t = _find_agent(name)
if not t:
missing.append(name)
continue
if t.get('id') == me.get('id'):
continue # 自己跳过(一次找多人时很常见)
if t['id'] not in group_chat.member_ids(conv):
missing.append(f'{t.get("name")}(不在群里)')
continue
if all(t['id'] != x['id'] for x in targets):
targets.append(t)
if not targets:
raise ValueError(f'一个都没找到:{"、".join(missing) or "(空的)"}')
content = str(args.get('content') or '').strip()
if not content:
raise ValueError('要说什么?content 不能是空的')
is_private = bool(args.get('private'))
msg = {
'role': 'assistant',
'content': content,
'agentId': me.get('id'),
'at': store.now_iso(),
}
if is_private:
# ★ 私聊:只给这几个目标看(`app.py` 组装 history 时按这个过滤)
msg['privateTo'] = [t['id'] for t in targets]
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
store.append_messages(conv_id, [msg])
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} private={is_private} '
f'targets={[t.get("name") for t in targets]} 内容={content[:20]!r}', file=sys.stderr)
# ★ 发言权:多目标排成队列,界面逐个接着让他们回应
names_out = '、'.join(t.get('name') or '?' for t in targets)
tools_runtime.note_handoff(targets[0]['id'], queue=[t['id'] for t in targets])
return {
'said_to': [t.get('name') for t in targets],
'content': content,
'private': is_private,
'note': (
f'已把「{content}」{"(私下)" if is_private else ""}说给「{names_out}」,'
'这句话已经写进对话,他们会挨个回应。别再重复调这个工具。'
+ (f'(没找到:{"、".join(missing)})' if missing else '')
),
}
# --------------------------------------------------------------------------- #
# 注册
# --------------------------------------------------------------------------- #
@@ -670,6 +817,9 @@ AGENT_TOOLS = {
# v1.2 多智能体对话(附录 B 的 invite_agent / pass_turn)
'invite_agent': {'spec': INVITE_AGENT, 'run': invite_agent},
'pass_turn': {'spec': PASS_TURN, 'run': pass_turn},
# ★ 主动找另一个智能体说话(用户要求:参数是「智能体 + 内容」)。
# `pass_turn` 只交发言权、不带内容,所以那个聊不起来。
'talk_to': {'spec': TALK_TO, 'run': talk_to},
}

View File

@@ -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 自己写进网页里的接口"的落点。
@@ -976,8 +1207,15 @@ class KernelHandler(BaseHTTPRequestHandler):
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
# 限制 —— 会话是用户的,他想拉谁就拉谁。
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
member_id = self._match_id(pathname, '/api/conversations/')
if member_id is not None and '/members' in pathname:
#
# ★★ 这里**绝不能用 `_match_id`**:它要求"id 后面没有斜杠",
# 而这条路是 `/api/conversations/<id>/members` —— `rest` 里带 `/`,
# 它直接返回 None,**整个分支永远进不去**。
# 真机表现就是「点加人没反应、人也加不上」,接口回的是
# **404 未知接口**(看着像路由没写,其实写了、被这个门槛拦住了)。
if pathname.startswith('/api/conversations/') and '/members' in pathname:
head, _, tail = pathname.partition('/members')
member_id = unquote(head[len('/api/conversations/'):].strip('/'))
conv = store.get_conversation(member_id)
if not conv:
self.send_json(404, {'error': '会话不存在'})
@@ -995,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': '不支持的操作'})
@@ -1030,6 +1271,51 @@ class KernelHandler(BaseHTTPRequestHandler):
self.send_json(200 if ok else 404, {'ok': ok})
return True
# 标记某条消息为「重要」(v1.2 §4.3)
#
# 路径:/api/conversations/<convId>/important,body: {content, role?, important?}
#
# ★ 只有**用户**能打这个标记(需求原话"仅用户可标")——
# AI 那边没有对应的工具,它有 `memory_add` 去记该记的东西。
# 被标记的消息在**上下文窗口裁剪**时"破格永久携带"。
#
# ★★ 按**内容**定位而不是下标(踩过):
# 界面上那份消息列表和存储里的**不保证一一对应**(本地生成的内容、
# 还没落地的流式消息……),按下标"长按第 3 条"会把标记打到第 1 条上,
# 而且**静默标错** —— 用户要等哪天发现某句话莫名没被裁掉才知道。
# 找不到就报 404,绝不猜一条标上去。
if pathname.startswith('/api/conversations/') and pathname.endswith('/important') \
and method == 'POST':
cid = pathname[len('/api/conversations/'):-len('/important')].strip('/')
if cid and '/' not in cid:
try:
body = self.read_json_body()
except ValueError:
body = {}
content = body.get('content')
if content is None:
self.send_json(400, {'error': '要带上 content(按内容定位那条消息)'})
return True
want = body.get('important')
if want is None:
# 不传就取反:界面上是个开关,点一下切一次。
# ★ 用**存储里**那条的当前状态取反(不是界面传来的),
# 免得界面和服务端状态不一致时越切越乱
conv = store.get_conversation(cid) or {}
cur = False
for m in reversed(conv.get('messages') or []):
if str(m.get('content') or '') == str(content):
cur = bool(m.get('important'))
break
want = not cur
msg = store.mark_important_by_content(
cid, content, str(body.get('role') or ''), bool(want))
if msg is None:
self.send_json(404, {'error': '没找到这条消息(内容对不上)'})
else:
self.send_json(200, {'ok': True, 'important': bool(want)})
return True
# 会议模式
if pathname == '/api/meetings' and method == 'GET':
self.send_json(200, {'meetings': meeting.list_meetings()})
@@ -1656,7 +1942,15 @@ class KernelHandler(BaseHTTPRequestHandler):
conversation_id = body.get('conversationId') or 'c_main'
text = str(body.get('message') or '').strip()
attachments = body.get('attachments') if isinstance(body.get('attachments'), list) else []
if not text and not attachments:
# ★★ 自动续的那几轮(`autoContinue` / `forceSpeaker`)**本来就没有用户消息** ——
# 那是让群里下一个人接着说话,不是用户在打字。
#
# 不放行的话,每一轮都会被这条校验打回 400,
# 用户在界面上看到的是**一屏「出错了:消息为空」**,
# 而"两个智能体对话"永远发生不了(真机反馈「还是不能互相对话」,
# 现场就是六条这个错误)。
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
if not text and not attachments and not auto_continue:
self.send_json(400, {'error': '消息为空'})
return
@@ -1753,16 +2047,34 @@ class KernelHandler(BaseHTTPRequestHandler):
if group_chat.is_group(conv0):
all_agents = store.list_agents()
names = [(x['id'], x.get('name') or '') for x in all_agents]
# 用户这一轮 @ 了谁:从**最后一条用户消息**里找
last_user = ''
for m in reversed(raw_history):
if m.get('role') == 'user':
last_user = str(m.get('content') or '')
break
# ★★ 用户这一轮 @ 了谁 —— **只看这一条消息**。
#
# 这个顺序很容易写错:本函数是「先仲裁、后落库」,
# 所以 `raw_history` 里**根本没有本次这条用户消息**。
# 拿它去找"最后一条 user",找到的是**上一次**用户说的话。
#
# 踩过两次:
# ① 用户打 `@寐眠 在吗` → 按上一条(没点名)仲裁 → 小黑替寐眠答
# ② **自动续轮时又从历史回退** → 把上一轮的 `@寐眠` 又拿来用,
# 于是 `talk_to` 明明把话交给了别人,仲裁还是给寐眠 ——
# 表现是"下回还是 A 说话"(真机反馈)。
#
# ★ 续轮(`autoContinue`)**本来就没有新用户消息**,
# 那一轮该由 `forced` / `passed` / 轮流来定,
# 绝不能去翻历史里的 `@` —— 那是上一件事了。
want = group_chat.mention_in(text or '', names)
pick = group_chat.resolve(
conv0,
want=group_chat.mention_in(last_user, names),
passed=str(body.get('handoffTo') or ''),
want=want,
# ★★ 从**上一轮**的移交状态取,**不是**从 HTTP body ——
# 界面(Kotlin)从来不发 handoffTo 这个字段,
# 以前读 body 等于永远拿到空串,② AI 移交那条分支是**死代码**。
# 现在 pass_turn 写在 tools_runtime 的轮次状态里,这里读它。
passed=str(tools_runtime.handoff_state().get('to') or ''),
# ★ 界面点「让他们聊」时指定的人(优先级最高)。
# 不这样做的话,"两个 AI 对话"就得指望 AI 自己愿意 pass_turn ——
# 实测它并不总会,用户按了也没反应。
forced=str(body.get('forceSpeaker') or ''),
alive={x['id']: not agentdb.is_dead(x['id']) for x in all_agents},
)
speaker = store.get_agent(pick.get('speaker'))
@@ -1790,6 +2102,40 @@ class KernelHandler(BaseHTTPRequestHandler):
if window.get('reason'):
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
# ★★ 群聊:给送进模型的每条消息标上**是谁说的**,并过滤私聊消息。
#
# ① 以前 history 里只有 role/content —— 群里**别人说的话**
# 模型根本分不清是谁,只能当成自己说过/用户说过。
# 用户的原话:「智能体可以读取群聊所有智能体的对话信息」。
# 这里在内容的**前面**加 `[名字] `,只改"送给模型的这份",
# 落库的正文保持干净(界面显示不受影响)。
#
# ② `talk_to` 的私聊模式(`privateTo`):那条消息只有**目标智能体**
# 和**用户**看得到,别人(包括模型)都不该有。所以在送进模型之前
# 就把"不是给我的私聊"剔掉 —— 在窗口裁剪之后剔除,
# 这样裁剪的"轮数"还是按全群算的,不会因为私聊把窗口算歪。
_is_group = group_chat.is_group(existing)
if _is_group:
_name_of = {x['id']: (x.get('name') or '') for x in store.list_agents()}
_filtered = []
for _m in history:
_to = _m.get('privateTo')
if isinstance(_to, list) and _to and agent_id not in _to:
# 这条是别人之间的私聊 —— 你看不到(用户能看到,那是用户的事)
continue
_who = ''
if _m.get('role') == 'assistant':
_who = _name_of.get(str(_m.get('agentId') or ''), '')
elif _m.get('role') == 'user':
_who = '用户'
if _who:
_m = dict(_m)
_content = _m.get('content')
if isinstance(_content, str):
_m['content'] = f'[{_who}] {_content}'
_filtered.append(_m)
history = _filtered
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
#
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
@@ -1801,7 +2147,13 @@ class KernelHandler(BaseHTTPRequestHandler):
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
owner = (existing.get('agentId') or '').strip()
if existing and agent_id:
# ★★ **群聊不做这个隔离**:群聊本来就是多智能体的,上面
# `group_chat.resolve` 刚把 `agent_id` 定成「本轮的发言人」,
# 它不是「会话的主人」。照单聊这样比一下,群里每换一个人说话
# 就会另起一个会话 —— 用户 @ 谁,界面就跳到谁的对话去
# (真机反馈原话:「群聊一@就跑到别的对话去了」)。
# `is_group` 既认 `type` 也认 `participants`,老会话也吃得住。
if existing and agent_id and not group_chat.is_group(existing):
if not owner:
store.set_conversation_agent(conversation_id, agent_id)
elif owner != agent_id:
@@ -1866,19 +2218,57 @@ class KernelHandler(BaseHTTPRequestHandler):
})
return
store.append_messages(conversation_id, [{
'role': 'user',
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
'attachments': attachment_meta,
'at': store.now_iso(),
}])
if text:
store.auto_title(conversation_id, text)
# ★★ `autoContinue`:这一轮是**界面替 AI 自动续的**,不是用户说的话。
#
# 群聊里 AI 用 `pass_turn` 把话交给另一个人时,界面会接着再发一次
# (不带用户消息)—— 这样两个人就能真的聊起来,而不是
# "用户说一句、AI 移交一次、然后就没下文了"。
#
# ★ 不追加用户消息:追加的话对话里会冒出一堆空消息,
# 而且模型会以为用户又说话了。移交状态本来就从
# `tools_runtime.handoff_state()` 里读(上一轮留下的),
# 所以下一轮的发言人自然是接得上的。
# ★ 判据必须和 `_handle_chat` 开头那条校验**完全一致**
# (`autoContinue` 或 `forceSpeaker`)—— 两处不一致的话,
# 一边放行一边往里塞空用户消息,对话里就会冒出一堆空条目。
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
if not auto_continue:
store.append_messages(conversation_id, [{
'role': 'user',
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
'attachments': attachment_meta,
'at': store.now_iso(),
}])
if text:
store.auto_title(conversation_id, text)
# ★★ 自动续轮(`autoContinue`)**不能再追加一条空的 user 消息**。
#
# 以前不管是不是续轮都拼一条 `{'role':'user','content':user_content}`,
# 而续轮没有用户输入 → `user_content` 是空串。
# 模型看到的是"用户刚发了一条空消息",于是它自己都懵了 ——
# 真机上的原话是:「这条又是空的,我这边没收到内容。猜两种可能:…」
# (用户报的「talk_to 没有内容呀」)。
#
# 而 `talk_to` 说的那句话**就在历史里**(落库了),
# 不追加空消息它自然就看到了。
msgs_for_model = list(history)
if not auto_continue:
msgs_for_model.append({'role': 'user', 'content': user_content})
else:
# 续轮补一句**极短的指令**而不是空消息:模型需要知道
# "现在轮到你接话",但不该以为用户说了什么。
# 这条**不落库**(只进这一轮给模型的 messages),
# 所以用户在聊天记录里看不到它。
msgs_for_model.append({
'role': 'user',
'content': '(系统:现在轮到你接着说,不用等用户输入。直接接着上面的内容回应。)',
})
result = agent_loop.run_agent(
settings=settings,
agent=agent,
messages=[*history, {'role': 'user', 'content': user_content}],
messages=msgs_for_model,
emit=emit,
should_stop=cancelled,
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
@@ -1909,8 +2299,33 @@ class KernelHandler(BaseHTTPRequestHandler):
int(result.get('toolCalls') or 0),
bool((settings.get('tools') or {}).get('python', True)),
),
# ★ 工具调用明细要落库 —— 不落的话界面上那些"工具卡片"
# 只有流式那一刻能看到,**重启 App 就全没了**
# (用户报的「工具怎么重启就不显示了」)。
'toolTrace': result.get('toolTrace') or [],
'at': store.now_iso(),
}])
# ★★ 这一轮 AI 用 `pass_turn` 把话交给了别人吗?交了就**告诉界面**。
#
# 光靠上面那个 `speaker` 事件不够 —— 它是在**轮前**发的,
# 而 `pass_turn` 是**轮中**才调用的。于是最常见的那个剧本:
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
# ② 主智能体说完话,轮中调 `pass_turn` 让给另一个人
# 界面看到的 reason 是 "host",以为没人移交,就**不再续轮** ——
# 被让的那个人永远开不了口(用户报的"还是不能互相对话")。
#
# ★ 判据用 `tools_runtime.handoff_state()`(模块级轮次状态),
# 不是线程局部变量 —— 工具跑在 worker 线程上,
# 这个坑在 `pass_turn` 上已经踩过一次了。
hs = tools_runtime.handoff_state()
if hs.get('used') and hs.get('to'):
emit({'type': 'handoff', 'to': hs['to'],
# ★ `talk_to` 一次找多个人时,剩下的人在这里 ——
# 界面逐个接下去让他们回应(用户要求"目标智能体挨个回话")
'queue': hs.get('queue') or [],
'from': agent_id})
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
if agent_id and (in_tok or out_tok):
@@ -2003,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)))

View File

@@ -175,6 +175,20 @@ DEFAULT_SETTINGS = {
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
# 0 = 不限(退回全量注入)。
'memoryWindow': 50,
# 背景(立绘 + 背景图)**跟随当前说话者**(v1.2 §6.1,默认开)。
#
# ★ 群聊里才有区别:关掉时展示区一直用**主智能体**的立绘,
# 打开时谁发言就换成谁的 —— 后者能让用户一眼看出"这句是谁说的",
# 所以默认开。做成开关是因为**有人就是想要固定的主视觉**。
# ★ 单聊时这个开关没有任何效果(说话者永远是同一个人),
# 但设置项不隐藏 —— 隐藏的开关比没用的开关更让人困惑。
'followSpeaker': True,
# 对话上下文窗口(轮,v1.2 §4.3):每轮最多带最近多少轮对话。
# 攒够 `contextBatch` 轮才裁一次(摊薄前缀缓存失效),见 context_window。
'contextWindow': 20,
'contextBatch': 5,
# 私聊(幕后对聊)最多几轮,v1.2 §3.9。一轮 = 双方各说一次。
'privateChatRounds': 10,
'provider': 'ark',
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
'model': PROVIDER_PRESETS['ark']['defaultModel'],
@@ -255,6 +269,26 @@ BUILTIN_SKILL = '\n'.join([
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
'',
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
'',
# ★★ 群聊的用法(用户反馈「智能体好像不怎么会用」)。
#
# 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
'【群聊】你可能在一个群里(群里有别人)。',
'· 你能**看到群里所有人的发言**(送进上下文的每条都有 `[名字]` 前缀,'
'「[用户]」是你对面那个人说的)。别把别人说的话当成自己说过。',
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
'· 一次想找**好几个人**:talk_to(agents=["甲","乙"], content=...),他们会**挨个**回应。',
'· 想**私下**跟某人说(只有他知道、群里其他 AI 看不到):加 `private=true`。'
' 用户还是看得到(他是观察者)—— 所以别以为私聊就可以说见不得人的话。',
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
' pass_turn 只在"我没什么可说了,换你"的时候用。',
'· 一轮最多一次:talk_to 和 pass_turn 二选一,别两个都调。',
'· 单聊里没有"别人",talk_to 会报错 —— 想跟某个人单独聊,让用户去建群或者私聊。',
'· 别为了"显得在忙"反复调 talk_to:一轮一次,说人话就行。',
])
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。

View File

@@ -16,7 +16,7 @@
## 死亡的人不能接
> 死亡智能体被点名时移交无效,发言权回主智能体。
> 死亡智能体被点名时移交无效,换下一个人接。
这条单独写出来,是因为"移交无效"有三种可能的处置:
报错、随机选一个、回主智能体 —— 需求选了第三种。
@@ -32,6 +32,8 @@
#: 一轮最多移交一次。需求明文,所以做成一个常量而不是散在代码里的布尔。
MAX_HANDOFF_PER_ROUND = 1
import store # noqa: E402 —— 加成员时要查世界观(只读,不参与仲裁)
def member_ids(conv: dict) -> list:
"""群聊的成员 id 列表(顺序就是加入顺序,**第 0 个是主智能体**)"""
@@ -47,11 +49,44 @@ def is_group(conv: dict) -> bool:
def host_id(conv: dict) -> str:
"""主智能体 = 会话发起者 = 成员列表的第一个(需求:"发起者")"""
"""
⚠️ **不再用于"决定谁发言"** —— 用户明确要求「群聊去掉主人设定」。
它现在只剩一个用途:`remove_member` 里判断"不能把最后一个人踢走"。
决定发言的那条路走 [rotate_next](轮流),不再有"老大"。
"""
ids = member_ids(conv)
return ids[0] if ids else (conv or {}).get('agentId') or ''
def rotate_next(conv: dict, ids: list = None) -> str:
"""
没人被点名时该谁说 —— **按成员顺序轮**,不设主人。
★★ 用户原话:「群聊去掉主人设定」。
原来兜底永远是"会话发起者"(成员列表第一个)——
那等于群里有个老大:其他人不 @ 就不开口,@ 了才有台词。
现在看**最近一条 AI 消息是谁说的**,下一个人接上,谁都不欠谁。
★ 找不到上一条(新群、或者老消息没有 agentId)就从第一个开始。
"""
ids = list(ids if ids is not None else member_ids(conv))
if not ids:
return ''
last = ''
for m in reversed((conv or {}).get('messages') or []):
if m.get('role') != 'assistant':
continue
aid = str(m.get('agentId') or '')
if aid in ids:
last = aid
break
if not last:
return ids[0]
return ids[(ids.index(last) + 1) % len(ids)]
def mention_in(text: str, names: list) -> str:
"""
从用户输入里找出被 @ 的人(返回 id,没有就空串)。
@@ -73,7 +108,7 @@ def mention_in(text: str, names: list) -> str:
def resolve(conv: dict, want: str = '', passed: str = '',
alive: dict = None, handoffs: int = 0) -> dict:
alive: dict = None, handoffs: int = 0, forced: str = '') -> dict:
"""
决定这一轮谁发言。
@@ -81,43 +116,71 @@ def resolve(conv: dict, want: str = '', passed: str = '',
[passed] AI 上一轮 `pass_turn` 指定的人
[alive] `{agent_id: bool}`,缺省视为活着
[handoffs] 这一轮已经移交过几次(用于"一轮最多一次")
[forced] 界面点「让他们聊」时**指定**的发言者,优先级最高
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'host'|'handoff_denied', 'note': ''}`。
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'rotate'|'handoff_denied'|'forced', 'note': ''}`。
★★ 为什么要有 [forced](真机反馈「还是不能互相对话」):
下面三条路都要求**用户点名**或者**AI 自己愿意移交**。
实测下来 AI 并不总会调 `pass_turn` —— 它更愿意自己把话说完,
于是"两个智能体对话"这件事就永远发生不了。
用户要的是一个**明确能按下去的入口**:点「让他们聊」,
界面就一轮一轮地把发言权在两个人之间递过去,不需要 AI 配合。
这是唯一能保证"一定聊得起来"的做法。
"""
conv = conv or {}
alive = alive or {}
ids = member_ids(conv)
host = host_id(conv)
# ★ 兜底**不再是主人**,是轮流(用户要求「群聊去掉主人设定」)
nxt = rotate_next(conv, ids)
def ok(aid: str) -> bool:
return bool(aid) and aid in ids and alive.get(aid, True)
# ① 用户 @ 的人(用户主权,不受"一轮一次"约束 —— 那条只管 AI 的移交)
# ① 用户 @ 的人 —— **压过 forced**。
#
# ★★ 顺序不能反(真机反馈:「@ 的时候立即切换」「对话时没上下文」)。
# 现场是这样的:用户点了「让他们聊」,那几轮还在跑;
# 这时用户打了一句 `@寐眠 别` —— 界面那一轮仍然带着 `forceSpeaker`
# (正轮到小黑),于是**小黑替寐眠答了**。
# 用户看到的是"我明明 @ 了他,回答的却是别人",感受上就是"没上下文"。
#
# 用户的手是最后发言权:他一旦点名,自动对聊必须让位。
# (界面那边也会在用户发消息时把自动对聊直接掐掉,这里是第二道。)
if want:
if ok(want):
return {'speaker': want, 'reason': 'mention', 'note': ''}
# 被 @ 的人死了或不在场:回主智能体,而不是报错
return {'speaker': host, 'reason': 'host',
'note': '被点的人不在场或已死亡,发言权回主智能体'}
return {'speaker': nxt, 'reason': 'rotate',
'note': '被点的人不在场或已死亡,换下一个人接'}
# ② AI 的移交(一轮最多一次)
# ② 界面指定的(「让他们聊」)—— 用户没点名时才轮到它
#
# 它只出现在界面的自动续轮里;用户手打消息时不会带上。
if forced:
if ok(forced):
return {'speaker': forced, 'reason': 'forced', 'note': ''}
return {'speaker': nxt, 'reason': 'rotate',
'note': '指定的人不在场或已死亡,换下一个人接'}
# ③ AI 的移交(一轮最多一次)
if passed:
if handoffs >= MAX_HANDOFF_PER_ROUND:
return {'speaker': host, 'reason': 'handoff_denied',
return {'speaker': nxt, 'reason': 'handoff_denied',
'note': '这一轮已经移交过了,不再移交'}
if ok(passed):
return {'speaker': passed, 'reason': 'handoff', 'note': ''}
# ★ 死亡的人被点名时**移交无效**,发言权回主智能体(需求明文)
return {'speaker': host, 'reason': 'host',
'note': f'「{passed}」已死亡或不在场,移交无效,发言权回主智能体'}
# ★ 死亡的人被点名时**移交无效**,换下一个人接(需求明文)
return {'speaker': nxt, 'reason': 'rotate',
'note': f'「{passed}」已死亡或不在场,移交无效,换下一个人接'}
# ③ 兜底:永不冷场
return {'speaker': host, 'reason': 'host', 'note': ''}
return {'speaker': nxt, 'reason': 'rotate', 'note': ''}
def add_member(conv: dict, agent_id: str) -> bool:
"""
加一个成员(用户手动增删**无条件允许** —— 用户主权)。
加一个成员(用户手动增删基本无条件 —— 用户主权)。
★ 加完**自动升级成 group**:成员超过一个时 `type` 必须是 `group`,
不然成员列表里有人、仲裁逻辑还按单聊跑 ——
@@ -127,6 +190,12 @@ def add_member(conv: dict, agent_id: str) -> bool:
★ 单聊要拉人 → 那个会话**就地转成群聊**,而不是偷偷往
`participants` 里塞一个 id 却把 `type` 留着。
★★ **只能拉同世界观的**(用户确认过这条规则)。
理由不是洁癖:群聊的上下文里有 `<worldview>` 段,视野不同的两个人
看到的是两套设定 —— 同一个群里会出现"这是哪、我们是谁"对不上的情况,
而且记忆空间也是按世界观分的(共享记忆会串)。
判定以**群主**(`agentId`)的世界观为准;空对空(都没绑)也算同。
"""
c = conv or {}
aid = str(agent_id or '').strip()
@@ -135,6 +204,19 @@ def add_member(conv: dict, agent_id: str) -> bool:
ids = member_ids(c)
if aid in ids:
return False
# ★ 世界观一致才让进 —— 但**未绑世界观的放行**。
#
# 未绑 = 这个智能体没有世界观设定,和谁都合得来,拉进来不会串。
# 一开始我写成"必须相等",于是没绑世界观的智能体也进不来 ——
# 用户报的「还是加不了人」,其中那个"黑化豆包"就是未绑的。
target = store.get_agent(aid) or {}
if target:
mine = (store.get_agent(str(c.get('agentId') or '')) or {}).get('worldviewId') or ''
theirs = target.get('worldviewId') or ''
if theirs and theirs != mine:
return False
ids.append(aid)
c['participants'] = ids
if len(ids) > 1 and (c.get('type') or 'single') != 'group':
@@ -144,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

View File

@@ -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 - 信号回调签名固定

View File

@@ -59,17 +59,34 @@ def normalize_image(image) -> dict:
"用户手改过 agents.json" 这种情况也不会被冲掉。
归一化**不丢信息**:字典里多出来的档位原样保留(用户可能自己加了「醉」这种)。
★★ 还要**解套**:有一版把 `front` 的字典值也 `_as_text` 了一遍,于是磁盘上
存成了 `"{'平常': 'C:\\...\\a.png'}"`(**字符串化的字典**)。
那种数据要能救回来 —— 不然用户看到的就是"**我设的图不见了**":
档位读不出来(是个字符串不是字典),而且每读写一次还多包一层,
最后连 `os.path.isfile` 都失败。
"""
img = dict(image or {})
front = img.get('front')
if isinstance(front, str):
# v1.1 的单文件名 → 只有「平常」档
img['front'] = {'平常': front} if front.strip() else {}
if isinstance(front, str) and front.strip().startswith('{'):
# ② 字符串化的字典 → 解回真字典
img['front'] = _unshell_dict(front)
elif isinstance(front, str):
# ① v1.1 的单文件名 → 只有「平常」档
img['front'] = {'平常': front.strip()} if front.strip() else {}
elif isinstance(front, dict):
img['front'] = {
str(k): str(v) for k, v in front.items()
if str(v or '').strip()
}
fixed = {}
for k, v in front.items():
key = str(k)
if isinstance(v, str) and v.strip().startswith('{'):
# 值本身又被包成了字典 → 摊平(旧数据里反复读写会这样)
for ik, iv in _unshell_dict(v).items():
if isinstance(iv, str) and iv.strip():
fixed[str(ik)] = iv.strip()
continue
if str(v or '').strip():
fixed[key] = str(v).strip()
img['front'] = fixed
else:
img['front'] = {}
for key in ('back', 'border-main', 'border-info'):
@@ -77,6 +94,25 @@ def normalize_image(image) -> dict:
return img
def _unshell_dict(text: str) -> dict:
"""
把**字符串化的字典**解回 dict(解不开就给空字典)。
★ 用 `ast.literal_eval` 而不是 `eval`:它只能求值**字面量**
(数字、字符串、列表、字典……),遇到函数调用直接报错。
就算那段文本被谁改过,也执行不了任何东西。
"""
import ast
try:
got = ast.literal_eval(str(text or ''))
except (ValueError, SyntaxError):
return {}
if not isinstance(got, dict):
return {}
return {str(k): v for k, v in got.items()}
def _read_json(file_path: str):
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
if not os.path.isfile(file_path):
@@ -608,13 +644,18 @@ def session_message_count(conv_id: str) -> int:
return sum(1 for m in (conv.get('messages') or []) if m.get('aiSent'))
def append_message(conv_id: str, role: str, content: str) -> dict:
def append_message(conv_id: str, role: str, content: str, agent_id: str = '') -> dict:
"""
往会话里追加一条消息(AI 主动发的)。
★ 走 `update_conversation` 而不是自己写文件:会话的落盘、时间戳、
标题自动生成那些逻辑都在那儿,这里再写一份就会不一致
(这个仓库里"同一段逻辑两份、加功能只改一份"的坑踩过好几次)。
★ [agent_id] 是**说这句话的是谁**。群聊里每条消息的发言者都不一样,
界面朗读时要按它挑音色 —— 不记的话只能一律用"当前对话的主人",
表现就是"群聊时不同智能体的语音不会切换"(真机反馈)。
`/api/chat` 那条路一直在写这个字段,只有这里漏了。
"""
item = get_conversation(conv_id)
if not item:
@@ -628,6 +669,8 @@ def append_message(conv_id: str, role: str, content: str) -> dict:
# 用来算"这个会话还能主动发几条",界面上不显示、也不给模型看。
'aiSent': True,
}
if agent_id:
msg['agentId'] = str(agent_id)
msgs.append(msg)
update_conversation(conv_id, {'messages': msgs})
return msg
@@ -1015,6 +1058,72 @@ def append_messages(conv_id: str, messages: list):
return item
def mark_important(conv_id: str, index: int, important: bool):
"""
给第 [index] 条消息打/取消「重要」标记(v1.2 §4.3)。
★ 需求原话:"**仅用户可标**;被标记消息破格永久携带、按原始时间序插入"。
所以这个函数**只由界面调**,AI 那边没有对应的工具 ——
它有 `memory_add` 去记该记的东西,标记是用户的主权。
★★ 按**下标**定位是**不安全**的,已经踩过:界面上那份消息列表可能和
存储里的**不是一一对应**(本地生成的内容、还没落地的流式消息……),
于是"长按第 3 条"会把标记打到第 1 条上 —— **静默标错**,
而用户完全看不出来(要等哪天发现某句话莫名没被裁掉)。
所以界面走的是 `mark_important_by_content`,这个按下标的老函数
只留给内部/测试用。
"""
item = get_conversation(conv_id)
if not item:
return None
msgs = item.get('messages') or []
if not (0 <= index < len(msgs)):
return None
with _lock:
# ★ 只改这一个字段,**不动 content** —— 需求把"历史消息字节冻结"
# 写成了内核纪律:改一个字,从那儿往后的前缀缓存全废。
# 标一个 `important` 是**新增键**,不影响 content 的字节。
msgs[index]['important'] = bool(important)
item['updatedAt'] = now_iso()
_persist_conversations()
return msgs[index]
def mark_important_by_content(conv_id: str, content: str, role: str = '',
important: bool = True):
"""
按**内容**找那条消息来打标记(界面的长按走这条路)。
★ 为什么不用下标:见 `mark_important` 的说明 —— 界面的列表和存储的
列表**不保证一一对应**,下标会静默标错。
★ 从**后往前**找:同一个内容可能重复出现(用户把一句话发了两遍),
而他长按的通常是比较靠后的那条。
★ 找不到就返回 None,让调用方**报错** —— 绝不"猜一条"标上去。
标错了用户看不出来,而那比报错糟得多。
"""
item = get_conversation(conv_id)
if not item:
return None
want = _as_text(content)
if not want:
return None
msgs = item.get('messages') or []
hit = -1
for i in range(len(msgs) - 1, -1, -1):
m = msgs[i]
if _as_text(m.get('content')) != want:
continue
if role and m.get('role') != role:
continue
hit = i
break
if hit < 0:
return None
return mark_important(conv_id, hit, important)
def auto_title(conv_id: str, text: str) -> None:
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
item = get_conversation(conv_id)
@@ -1114,10 +1223,18 @@ def _apply_agent_patch(agent: dict, patch: dict) -> dict:
for key in AGENT_DICT_FIELDS:
if patch.get(key) is not None:
raw = patch[key]
agent[key] = (
{str(k): _as_text(v) for k, v in raw.items()}
if isinstance(raw, dict) else {}
)
# ★★ 和 `_apply_resource_patch` 一样:**不能对每个值调 `_as_text`**。
#
# 智能体的 `image` 以前只有字符串(文件名),转一下无妨;
# 但 v1.2 的立绘是**五档字典**(`front: {'喜': 路径, ...}`)——
# 转成字符串之后,那个键就变成了 `"{'喜': 'C:\\...'}"` 这种
# 字符串化的字典:
# · 回退链按档位找不到(`front['喜']` 从字典里读不到)
# · 而且**每读写一次就多包一层**,最后 `os.path.isfile` 失败
# —— 表现就是用户说的"**之前设置的图像也没了**"
#
# 改成 `_json_safe`:保留嵌套结构,只把 JSON 存不下的转字符串。
agent[key] = _json_safe(raw) if isinstance(raw, dict) else {}
return agent
@@ -1242,7 +1359,11 @@ RESOURCES = {
'file': lambda: paths.get().models_file,
'key': 'models',
'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'),
'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算
# 元/千 Token,0 = 不显示费用估算。
# ★ cachePricePerK 是**命中缓存**的单价(v1.2):各家命中都比未命中
# 便宜得多(常见 1/10)。只填一个输入单价的话,费用估算会按未命中
# 的价格算 —— 用得越多、高估得越离谱,而用户会以为自己真花了那些钱。
'num': ('pricePerK', 'cachePricePerK'),
# ★ noTools:这个模型不支持 function calling(需求 3.3 的兼容降级)。
# 打开之后不传 tools、改成正文内的调用约定 —— 见 agent_loop.DEGRADED_HINT。
'bool': ('noTools',),

View File

@@ -165,6 +165,55 @@ def current_context() -> dict:
return dict(getattr(_ctx, 'value', None) or {})
# --------------------------------------------------------------------------- #
# 轮次级状态(发言权移交)
# --------------------------------------------------------------------------- #
#
# ★★ 为什么**不能**用工具上下文(`update_context`)来记这个 —— 踩过:
#
# 工具跑在 **worker 线程**里(`builtin_tools.run_with_timeout` 起线程),
# 而 `_ctx` 是 `threading.local()`。工具在里面写 `update_context(...)`,
# 写的是**那个 worker 线程**的副本;线程一结束、`finally` 里把值置 None,
# 标记就没了。而主线程每次调用前又 `push_context(...)`(替换语义)——
# 于是"这一轮已经移交过"**永远是 False**,`pass_turn` 可以一轮交无限次。
#
# ★ 更麻烦的是:探针当时是**直接调 `agent_tools.pass_turn`**(主线程),
# 标记留在主线程里没被清 → 探针**假通过**。真机上才会露馅。
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
#
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
_handoff = {'to': '', 'used': False, 'queue': []}
def begin_round() -> None:
"""一轮对话开始时调用(agent_loop 在生成前调)"""
_handoff['to'] = ''
_handoff['used'] = False
_handoff['queue'] = []
def note_handoff(agent_id: str, queue: list = None) -> None:
"""
记下"这一轮把话交给了谁"。
[queue] 是**多目标**时的完整名单(`talk_to` 支持一次找好几个人,
他们挨个回话)。`to` 始终是**第一个**,保持老调用方不用改。
"""
ids = [str(x) for x in (queue or []) if str(x or '').strip()]
if not ids and str(agent_id or '').strip():
ids = [str(agent_id)]
_handoff['to'] = ids[0] if ids else str(agent_id or '')
_handoff['used'] = True
# 剩下的排进队列(`to` 已经算第一个了)
_handoff['queue'] = ids[1:]
def handoff_state() -> dict:
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`,界面要用 `queue`)"""
return {'to': _handoff['to'], 'used': _handoff['used'],
'queue': list(_handoff.get('queue') or [])}
def ui_tools_enabled(settings: dict) -> bool:
"""
界面工具开了没有。

View 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.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,5 @@
python313.zip
.
# Uncomment to run site.main() automatically
#import site

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -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());
}

View File

@@ -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
View 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

File diff suppressed because it is too large Load Diff

1211
docs/kernel-api-chat.md Normal file

File diff suppressed because it is too large Load Diff

1290
docs/kernel-api-misc.md Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 668 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

BIN
docs/screenshots/now1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 436 KiB

BIN
docs/screenshots/now2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

BIN
docs/screenshots/now3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 509 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 885 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

@@ -5,9 +5,30 @@
---
## ✅ 全部完成(v2.0.47 → v2.0.66)
| 阶段 | 内容 | 完成版本 | 主要落点 |
|---|---|---|---|
| **0** | 情绪双字段(地基) | v2.0.55 | `agentdb.py` / `agent_tools.py` / `agent_context.py` / `MemoryScreen.kt` |
| **1** | 立绘表 + 回退链 | v2.0.56 | `store.normalize_image` / `agent_api.portrait_of` / `AgentEditScreen.kt` |
| **2** | 缓存统计 + 段序 + 上下文窗口 | v2.0.57 / v2.0.58 / v2.0.64 | `agent_loop.cache_pair` / `defaults.DEFAULT_PROMPT_TEMPLATE` / **新建 `kernel/context_window.py`** |
| **3** | 规则引擎(数值 + 状态 + 沙箱 + 规则包) | v2.0.59 | **新建 `kernel/rule_engine.py`** / `agent_tools.change_stat`·`grant_status` / `ResourcesScreen.kt` / **新建 `RulePackEditScreen.kt`** |
| **4** | 多智能体对话(群聊 + 私聊) | v2.0.60 / v2.0.61 | **新建 `kernel/group_chat.py`**·`private_chat.py` / `agent_tools.invite_agent`·`pass_turn` / **新建 `GroupMembersScreen.kt`** |
| **5** | 收尾(三个新界面 + @ 快捷条 + 标记重要 + 背景跟随) | v2.0.62 → v2.0.66 | **新建 `AgentStatsScreen.kt`** / `ChatScreen.kt` / `SettingsScreen.kt` |
**八个探针全绿**(每一阶段都构建 + 探针验证过):
probe-agent-system probe-degraded probe-rule-sandbox
probe-rule-engine probe-context-window probe-group-chat
audit-ui-tree audit-ui-entries
`audit-ui-tree.py` 的 `PLANNED` 已**清空** —— 三个"计划中"的界面全部落地。
---
## 阶段划分(每一阶段都能单独发版)
### 阶段 0 · 情绪双字段(**地基**)
### ✅ 阶段 0 · 情绪双字段(**地基**)
**为什么必须第一个做**:v1.2 有三处依赖它 —— 立绘联动(按 preset 切图)、
`peer_emotions`(注入的是 preset 不是 text)、`on_turn` 脚本(能改情绪)。
@@ -23,7 +44,7 @@
**注意**:`get_token_usage` 之外的旧工具签名一个字都不能变。
### 阶段 1 · 立绘表 + 回退链(依赖阶段 0)
### ✅ 阶段 1 · 立绘表 + 回退链(依赖阶段 0)
| 做什么 | 落在哪 |
|---|---|
@@ -32,7 +53,7 @@
| 智能体编辑外观组:角色图拆成五档,各带选图/清除 | `AgentEditScreen.kt` |
| 选择界面立绘随 preset 切换 | `AgentSelectScreen.kt` |
### 阶段 2 · 缓存统计 + 段序(**独立,可以并行**)
### ✅ 阶段 2 · 缓存统计 + 段序(**独立,可以并行**)
| 做什么 | 落在哪 |
|---|---|
@@ -46,7 +67,7 @@
把最易变的 `<emotion>` 放在 `<memory>` 前面 —— 情绪一变,后面整段缓存全废。
挪到最后,长前缀(prompt/skills/worldview/memory)能一直命中。
### 阶段 3 · 规则引擎(数值 + 状态,**最大的一块**)
### ✅ 阶段 3 · 规则引擎(数值 + 状态,**最大的一块**)
| 做什么 | 落在哪 |
|---|---|
@@ -60,7 +81,7 @@
| `[规则包编辑]` 全屏界面(脚本编辑复用节点代码那个组件) | 新建 |
| `[状态数值]` 浮层 + 三个入口 | 新建 |
### 阶段 4 · 多智能体对话(**依赖阶段 0 和 3**)
### ✅ 阶段 4 · 多智能体对话(**依赖阶段 0 和 3**)
| 做什么 | 落在哪 |
|---|---|
@@ -73,7 +94,7 @@
| 群聊背景跟随发言者(crossfade 0.3s) | `ChatScreen.kt` |
| 死亡规则:禁言 + 不冻结状态机 + 复活双通道 | `app.py` + `agent_tools.py` |
### 阶段 5 · 收尾
### ✅ 阶段 5 · 收尾
- 文档:`docs/智能体系统.md` 补 v1.2 各节
- `docs/界面总览.md` 里三个"计划中"的界面标成已落地
@@ -102,9 +123,30 @@
**§3.10 的脚本沙箱能做到什么程度**。~~需求说"仅暴露三个 API,无文件、网络访问"。
安卓上的内核是 CPython(Chaquopy),Python 的沙箱天生关不严,三条路……~~
### ✅ 已定:子进程 + 资源限制(2026-10-16 你选的)
### ✅ 已定:**限制 import(builtins 白名单)**(2026-10-16 你选的,已实现)
但查了一遍代码,**安卓上不能直接起 Python 子进程**,方案要绕一下:
最终做的是 `kernel/rule_sandbox.py` 的三层:
1. **静态扫描**:`__\w+__`、`import`、`open|eval|exec|getattr|...` 一律拒绝
2. **受限 `SAFE_BUILTINS`**:脚本的全局命名空间里只有白名单里的内置函数
3. **硬超时**:跑不动就放弃等待(线程杀不掉,如实写进提示)
★★ 而且**如实标注了能力边界** —— 模块里写着"**挡手滑,挡不住有意**":
· 文本级扫描可以绕过(`"_" * 2 + "import__"` 这类拼接)
· 没有资源限制(内存 / CPU)
· 安卓上起不了真子进程(Chaquopy 嵌的 CPython 没有独立解释器,
证据是现有 `python_run` 工具用的就是进程内 `exec`)
`scripts/probe-rule-sandbox.py` 里专门有一节**测试它挡不住什么** ——
一个只测"能挡住什么"的沙箱测试,会给人虚假的安全感。
**下面这段是当初的调研记录**,保留下来是因为"安卓上为什么起不了 Python
子进程"这个结论以后还会有人问:
> ~~需求说"仅暴露三个 API,无文件、网络访问"。三条路……~~
>
> 但查了一遍代码,**安卓上不能直接起 Python 子进程**,方案要绕一下:
**问题**:安卓内核是 Chaquopy 嵌的 CPython —— 它**没有独立的解释器可执行文件**,
`sys.executable` 指向的东西起不来。证据在仓库里:现有的 `python_run` 工具

View 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. 发一句话,问它"你现在对我什么感觉"
脚本可以先完全不管 —— 没有脚本,数值和状态照样工作。

View File

@@ -1,8 +1,64 @@
# 智能体系统(需求 v1.1)
# 智能体系统(需求 v1.1 + v1.2)
这份文档对应《智能体系统需求文档 v1.1》。它不讲"应该怎么做"(那在需求里),
只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、当时为什么这么选、
出了问题去哪儿看。
这份文档对应《智能体系统需求文档 v1.1》**和 v1.2**。它不讲"应该怎么做"
(那在需求里),只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、
当时为什么这么选、出了问题去哪儿看。
---
## 0. v1.2 增补(v2.0.47 → v2.0.66 全部落地)
v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿,
因为它们的落点大多是**新文件**,和 v1.1 那批不是一回事。
| 需求 | 实现位置 |
|---|---|
| §3.5 情绪双字段(preset + text) | `kernel/agentdb.py`(`emotions` 表加 `preset`)+ `MemoryScreen.kt` |
| §2.5 立绘五档 + §2.6 回退链 | `kernel/store.py: normalize_image` + `kernel/agent_api.py: portrait_of` + `AgentEditScreen.kt` |
| §3.1 缓存统计归一化 | `kernel/agent_loop.py: cache_pair`(三家字段名不同)+ `agentdb.py` 的 `cache_hit/miss` |
| 附录 C 缓存友好段序 | `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` + `agent_context.SECTIONS` |
| §4.3 对话上下文窗口 | **`kernel/context_window.py`**(成批对齐裁剪 + 重要标记破格携带) |
| §3.10 数值系统 | **`kernel/rule_engine.py`** + `agent_tools.change_stat` |
| §3.11 状态系统 | 同上 + `agent_tools.grant_status` + `agent_loop` 的 `on_turn` 调用点 |
| 附录 E 脚本沙箱 | **`kernel/rule_sandbox.py`**(如实标注"挡手滑挡不住有意") |
| 附录 D 数值状态包 | `agent_api._export_rulepack` / `_import_rulepack` + `ui/RulePackEditScreen.kt` |
| §3.9 群聊 | **`kernel/group_chat.py`**(点名制仲裁)+ `agent_tools.invite_agent`·`pass_turn` + `ui/GroupMembersScreen.kt` |
| §3.9 私聊 | **`kernel/private_chat.py`**(10 轮安全网 + 一方触顶单方面收尾) |
| §3.10/3.11 状态数值界面 | `ui/AgentStatsScreen.kt`(三个入口共用) |
| §6.1 背景跟随说话者 | `SettingsScreen.kt` 的「外观」组 + `ChatScreen.ChatBackdrop`(聊天页整屏立绘/背景层,跟着说话者换) |
### 两份"窗口"的命名纪律(需求点名要求,别混)
· 「记忆注入窗口」 memoryWindow —— 每轮塞多少条**记忆**,超出部分**降级为可检索**
· 「上下文窗口」 contextWindow —— 送多少轮**对话**,超出部分**直接丢弃、不做摘要**
两个像但完全不同。混着叫的话,用户问"我调窗口怎么没用"时你都不知道说的是哪个。
### v1.2 踩过、值得记住的几类坑
| 坑 | 表现 | 教训 |
|---|---|---|
| **字段表缺项** | `rulePackId` / `inviteMode` / `contextWindow` 不在白名单里 → "界面里配了、读出来没有" | 加字段时先看字段表 |
| **`push_context` 是替换语义** | 工具里拿它记标记,冲掉了 `agentId` → "拿不到当前智能体" | 要合并用 `update_context` |
| **`GET /api/<res>/<id>` 缺分支** | 编辑页拿到空包,界面显示"0 条数值"而包其实建出来了 | 只有真点一遍才看得见 |
| **`Text` 不渲染 Markdown** | `Text("**粗体**")` 把星号原样显示 | 不报错、不警告,只有截图能发现 |
| **按下标定位消息** | 界面和存储的列表不一一对应 → **静默标错**到别的消息上 | 下标是两边各自数的;改成按内容定位 |
| **`dict` 字段被 `_as_text` 压平** | 规则包的 `info` 里嵌套 list 变成字符串 → 整个规则引擎静默失效 | 嵌套结构要 `_json_safe` |
| **请求体上限按最小的调用方给** | 手机照片 28.9MB → base64 38MB,撞上 `read_json_body` 默认的 4MB;异常又被吞成空 dict,最后报的是**「不认识的外观槽位」** | 上限按**最大**的用;吞异常等于把原因丢掉 |
| **探针绕过了真正出问题的那一层** | 第 22 节直接调 `_set_asset`,而卡住的是 `handle()` 里的 `body()` → 探针全绿,真机全挂 | 探针**必须走生产同一条调用路径** |
| **换图时"自己删自己"** | 落盘名是 `<槽位>-<原始文件名>`;同一张图传第二次时新旧同路径 → 写完新的立刻被当旧的删掉,`image` 里留下**指向不存在文件**的路径,目录空着界面回退默认图 | 删旧文件前先比路径;"先写后删"的顺序里藏着这个坑 |
| **两条各自正确的逻辑叠在一起** | 群聊仲裁把 `agentId` 换成「本轮发言人」,紧接着的会话隔离又拿它比「会话主人」→ 群里每换一个人说话就**另起一个会话**,用户 @ 谁就跳到谁的对话去 | 一条规则搬到新场景时要重问一遍"它还成立吗"——群聊里 `agentId` 根本不是主人 |
| **能力全都在,缺最后一个按钮** | `chatJob`(取消句柄)建好了、内核从 HTTP 到 `agent_loop` 一路支持 `cancelled`、ViewModel 也把 `AtomicBoolean` 传下去了 —— 但**没有任何界面调它**,用户只能干等它说完 | 一条链路要数**两端**:内核发得出 + 界面点得到。只做前半截,测的时候还全是绿的 |
| **顺序错了:先仲裁、后落库** | 群聊仲裁要读「用户这一轮 @ 了谁」,而本次消息**还没写进库** → 读到的是**上一次**的话 → 我 @ 寐眠,回答的却是小黑(背景/标签/音色三处全对不上) | 读「刚刚发生的事」之前先问:**它现在在库里了吗** |
这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。
> 最后一条是 v2.0.72 修「背景图设置不了」时补上的:用户选的是手机相册里的照片
> (30~55MB),这条链路上有三堵墙,**每一堵单独看都合理**:
> 前端把 55MB 原样 `readBytes` + base64;内核每条接口卡 4MB;异常被 `body()` 吞掉。
> 现在的分工是:前端**先把位图压到 3MB 以内**(`ui/ImagePick.kt`,GIF/SVG 不压,
> 因为缩放会丢动画、栅格化会毁矢量),内核把**上传类**接口的上限统一放到
> `UPLOAD_BODY_LIMIT`(图片 + 四种包导入),并且读不出来时**如实报原因**。
---
@@ -27,7 +83,7 @@
| 3.7 幻觉调用检测 | `kernel/agent_loop.py: check_hallucinated_memory` + 对话页警示条 |
| 4.1 本次对话用量 | `ui/ChatScreen.kt: SessionUsageBar` |
| 附录 A UUID 主键 | `kernel/store.py: create_agent` / `create_resource` |
| 附录 B 六个工具 | `kernel/agent_tools.py: AGENT_TOOLS` |
| 附录 B 工具清单 | `kernel/agent_tools.py: AGENT_TOOLS`(v1.2 后共 11 个:v1.1 的 7 个 + `change_stat` / `grant_status` / `invite_agent` / `pass_turn`) |
| 附录 C 提示词模板 | `kernel/agent_context.py` + `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` |
| 附录 D 包格式 | `kernel/agent_api.py` + `docs/智能体系统.md` 第 4 节 |
@@ -194,14 +250,28 @@ assets/… # 四件套图片(front / back / border-main / border-in
| 脚本 | 验什么 |
|---|---|
| `python scripts/probe-agent-system.py` | 12 节 70+ 项:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析 |
| `python scripts/probe-agent-system.py` | 23 节:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析、数值/状态、外观槽位、**上传请求体上限和错误信息** |
| `python scripts/probe-degraded.py` | 幻觉检测(该报的报、不该报的不报)+ 降级调用的解析/执行/剥离/坏输入 |
| `python scripts/probe-rule-engine.py` | 数值/状态的定义、钳制、脚本、状态过期 |
| `python scripts/probe-rule-sandbox.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` 指到一个临时目录,
八个都不需要装机、不需要网络:把 `DOUBAO_DATA` 指到一个临时目录,
内核的存储层是无状态的,整条链路就能在一个进程里跑完。
**比装机验证快得多,而且能断言具体字段**(截图只能看个大概)。
### 写探针的一条硬纪律:走**生产同一条**调用路径
第 22 节直接调 `_set_asset(...)`,于是它**永远测不到**卡住真机的那一层 ——
上限是在 `handle()` 里的 `body()` 卡的。结果:探针全绿,真机选一张照片就挂。
所以第 23 节改成 `h.call('/api/agents/<id>/asset', 'POST', {...})`,
从 HTTP 路径进去,一路走到存储。**能绕过的那一层,就是下次会出问题的那一层。**
### 改内核之后必须做的一件事
```bash

261
docs/网页版.md Normal file
View 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 探测写的(不是凭记忆),加接口时先更新它们。

View 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 三张截图逐像素实测)。
**只学布局/尺寸/配色,不含豆包任何代码、字体文件、图标资源与文案。**

View File

@@ -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",

View 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');

View File

@@ -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'));

View File

@@ -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
@@ -74,12 +75,19 @@ class FakeHandler:
def __init__(self):
self.status = 200
self.payload = None
#: 设一个消息就模拟"请求体读不出来"(太大 / 不是合法 JSON)
self.body_error_exc = None
#: 记下这次收到的 limit —— 用来断言"图片这条路真的被单独放行了"
self.last_limit = None
def send_json(self, code, payload):
self.status = code
self.payload = payload
def read_json_body(self, *a, **k):
self.last_limit = a[0] if a else k.get('limit')
if self.body_error_exc is not None:
raise ValueError(self.body_error_exc)
return self._body
def call(self, pathname, method, body=None):
@@ -678,6 +686,313 @@ def main():
check("老库的 token_usage 能加上缓存两列", {"cache_hit", "cache_miss"} <= tcols, str(sorted(tcols)))
conn_old_tu.close()
# ---------------------------------------------------------------- 22
section("22. 外观槽位接口(真机上报过 500 / 图不见了)")
#
# ★★ 这一节是**真机反馈**倒逼出来的,两个 bug 都在这里:
# ① `_set_asset` 里 `key` 变量被删了 → NameError → 接口 500
# → 表现"角色图设置不了"(任何图都传不上去)
# ② `_apply_agent_patch` 对 image 的每个值调 `_as_text`
# → `front`(字典)被存成字符串化的字典
# → 表现"之前设置的图像也没了"(档位读不出来 + 每读写一次多包一层)
#
# 教训:**探针没覆盖到的接口 = 没写过**。这个接口当时一条断言都没有。
import agent_api as _api
class _H:
def __init__(self):
self.status = 200
self.payload = None
def send_json(self, code, payload):
self.status, self.payload = code, payload
hh = _H()
def _err(code, msg):
hh.status, hh.payload = code, {'error': msg}
art_agent = store.create_agent({'name': '外观测试'})
aid = art_agent['id']
_small = ('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8'
'z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==')
def put(key, data=_small, name='t.png'):
hh.status, hh.payload = 200, None
_api._set_asset(hh, 'agents', aid, {'key': key, 'name': name, 'data': data}, _err)
return hh.status, hh.payload or {}
st, pl = put('front:喜')
check("① 传「喜」档不再 500(真机就是这里挂的)", st == 200, f"{st} {pl}")
check("返回里带 slot", pl.get('slot') == '喜', str(pl.get('slot')))
st, pl = put('front')
check("不带档位的 front 视为「平常」(兼容旧界面)", pl.get('slot') == '平常', str(pl.get('slot')))
st, pl = put('front:死亡')
check("「死亡」档也能传", st == 200 and pl.get('slot') == '死亡', f"{st} {pl}")
st, pl = put('back')
check("背景图能传", st == 200, f"{st} {pl}")
st, pl = put('front:乱写')
check("乱写的档位被拒(400 不是 500)", st == 400, f"{st} {pl}")
# ★★ 存下来的形状必须是**字典**,不是字符串化的字典
img = (store.get_agent(aid) or {}).get('image') or {}
front = img.get('front')
check("**front 存下来还是字典**(不是字符串化)", isinstance(front, dict), str(type(front)))
check("三个档位都在", set(front or {}) >= {'喜', '平常', '死亡'}, str(front))
for k, v in (front or {}).items():
check(f"档位「{k}」的值是**路径字符串**不是嵌套字典",
isinstance(v, str) and not v.strip().startswith('{'), str(v)[:40])
# 回退链要能用
check("回退链:preset=喜 命中自己的档", bool(_api.portrait_of(img, '喜')))
check("回退链:preset=怒 退到平常", bool(_api.portrait_of(img, '怒')))
# 清空一个档
st, pl = put('front:喜', data='')
check("传空 data = 清掉那一档", st == 200 and pl.get('cleared') is True, f"{st} {pl}")
img2 = (store.get_agent(aid) or {}).get('image') or {}
check("清掉之后「喜」不在字典里了", '喜' not in (img2.get('front') or {}), str(img2.get('front')))
check("别的档**没被连累**", '平常' in (img2.get('front') or {}), str(img2.get('front')))
# ★★ 老脏数据要能救回来(用户磁盘上可能真的有)
shelled = store.normalize_image({'front': "{'平常': 'C:/x/a.png'}"})
check("字符串化的字典能解套", shelled.get('front') == {'平常': 'C:/x/a.png'}, str(shelled.get('front')))
nested = store.normalize_image({'front': {'平常': "{'平常': 'C:/y/b.png'}"}})
check("嵌套一层也能摊平", nested.get('front') == {'平常': 'C:/y/b.png'}, str(nested.get('front')))
check("解不开的垃圾文本当空处理(不抛异常)",
store.normalize_image({'front': '{不是字典}'}).get('front') == {},
str(store.normalize_image({'front': '{不是字典}'}).get('front')))
check("老格式(单个文件名)还是认",
store.normalize_image({'front': 'old.png'}).get('front') == {'平常': 'old.png'})
# ---------------------------------------------------------------- 23
section("23. 大图上传:请求体上限 + 错误信息(真机上报过「背景图设置不了」)")
#
# ★★ 真机现场:用户选的是**手机相册里的照片**(30~55MB),base64 之后
# 38~73MB。read_json_body 的默认上限是 4MB,于是请求体一进去就被判
# 「请求体过大」;而那个异常被 body() 吞成空 dict,
# 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
# 用户只看到"设置不了",查的人也会往槽位名上去找。
#
# ★ 这一节**必须走 handle()**,不能像上一节那样直接调 _set_asset:
# 上限是在 handle 里的 `body()` 那一层卡的,绕过它就等于没测。
# (第 22 节正是直接调 _set_asset 的 —— 所以它一直没盖到这条路径。)
big = store.create_agent({'name': '大图测试'})
big_id = big['id']
h.body_error_exc = None
h.last_limit = None
pl = h.call(f'/api/agents/{big_id}/asset', 'POST',
{'key': 'back', 'name': 'bg.png', 'data': _small})
check("图片上传正常返回", h.status == 200 and bool(pl.get('path')), f"{h.status} {pl}")
check("图片这条路的请求体上限被单独放行(不是默认的 4MB)",
h.last_limit == _api.UPLOAD_BODY_LIMIT,
f"实际收到 {h.last_limit},期望 {_api.UPLOAD_BODY_LIMIT}")
# 两个上限必须自洽:内核允许单张图到 20MB,base64 之后是 4/3 倍。
# 请求体上限比它小的话,就会出现"内核说这图可以,通道却传不进来"
need = 20 * 1024 * 1024 * 4 // 3
check("请求体上限装得下内核允许的最大图(20MB → base64 约 27MB)",
_api.UPLOAD_BODY_LIMIT > need,
f"{_api.UPLOAD_BODY_LIMIT} 要 > {need}")
# ★★ 请求体读失败时,必须报真正的原因
h.body_error_exc = '请求体过大'
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
check("请求体读不出来时报的是真原因",
h.status == 400 and '请求体过大' in str(pl.get('error', '')),
f"{h.status} {pl}")
check("不再把「请求体过大」伪装成「不认识的外观槽位」",
'不认识的外观槽位' not in str(pl.get('error', '')),
str(pl.get('error')))
h.body_error_exc = None
# 正常的参数错误不能被这次改动带坏
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': '乱写的槽位', 'data': _small})
check("槽位名写错仍然报「不认识的外观槽位」",
h.status == 400 and '不认识的外观槽位' in str(pl.get('error', '')),
f"{h.status} {pl}")
# 上一次的失败不能跟着到下一个请求上(body_error 是挂在 handler 上的)
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
check("上一次失败不污染下一次请求", h.status == 200 and 'error' not in pl, f"{h.status} {pl}")
# 世界观走的是同一个 _set_asset —— 上限也得跟上,别只改一边
world = store.create_resource('worldviews', {'name': '大图世界观', 'setting': ''}) or {}
world_id = world.get('id')
if world_id:
h.last_limit = None
pl = h.call(f'/api/worldviews/{world_id}/asset', 'POST', {'key': 'back', 'data': _small})
check("世界观那条路也放行了(同一个 _set_asset,别只改一边)",
h.status == 200 and h.last_limit == _api.UPLOAD_BODY_LIMIT,
f"{h.status} limit={h.last_limit} {pl}")
# ★ 同一类坑还有四处:四种**包导入**也是 base64 进 JSON。
# 带外观图片的智能体包 zip 上到十几 MB,走默认的 4MB 一样进不来。
# 这里不要求导入成功(空包必然失败),只要求**上限确实传下去了**。
for path in ('/api/agents/import', '/api/worldviews/import', '/api/rulepacks/import'):
h.last_limit = None
h.call(path, 'POST', {})
check(f"{path} 也放行了(包里有图片时才不会卡在 4MB)",
h.last_limit == _api.UPLOAD_BODY_LIMIT,
f"limit={h.last_limit}")
# ---------------------------------------------------------------- 24
section("24. 换图时新旧同名(真机上报过「同一张图传第二次就没了」)")
#
# ★★ 落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**。
# 原来的顺序是"写新的 → 删旧的",而旧路径正好就是新路径 ——
# 刚写的那张被自己删掉,image 里留下一个指向不存在文件的路径:
# 资源目录空着,界面回退到默认图。表现是"第二次传同一张图就没了"。
#
# 第一次传时名字来自 SAF 的 segment(`image_1000018033` 这种),
# 和第二次不同名,所以随手试一次碰不到 —— 必须**故意传两次同名**才复现。
twice = store.create_agent({'name': '重传测试'})
tid = twice['id']
def put_named(key, name):
return h.call(f'/api/agents/{tid}/asset', 'POST',
{'key': key, 'name': name, 'data': _small})
pl1 = put_named('back', 'same.png')
path1 = pl1.get('path') or ''
check("第一次传:文件确实落了盘", bool(path1) and os.path.isfile(path1), path1)
pl2 = put_named('back', 'same.png')
path2 = pl2.get('path') or ''
check("第二次传同名文件:路径不变(本来就是同一个文件)", path1 == path2, f"{path1} vs {path2}")
check("**第二次传完文件还在**(旧版在这里把它自己删了)",
bool(path2) and os.path.isfile(path2),
f"{path2} 存在={os.path.isfile(path2) if path2 else None}")
img = (store.get_agent(tid) or {}).get('image') or {}
check("image 里指的是一个真实存在的文件",
bool(img.get('back')) and os.path.isfile(img['back']), str(img.get('back')))
# 立绘那条分支是同一份逻辑,也要过一遍 —— 别只修一边
pf1 = put_named('front:喜', 'same.png')
pf2 = put_named('front:喜', 'same.png')
fpath = pf2.get('path') or ''
check("立绘连传两次同名文件也还在", bool(fpath) and os.path.isfile(fpath),
f"{fpath} 存在={os.path.isfile(fpath) if fpath else None}")
check("立绘两次的路径相同", (pf1.get('path') or '') == fpath, f"{pf1.get('path')} vs {fpath}")
# ★ 反向:换一张**不同名**的图时,旧文件必须真的被清掉
# (别为了修上面的问题,把"不然越攒越多"的清理一起弄没了)
pl3 = put_named('back', 'other.png')
path3 = pl3.get('path') or ''
check("换不同名的新图:新文件在", bool(path3) and os.path.isfile(path3), path3)
check("换不同名的新图:**旧文件被清掉了**", not os.path.isfile(path2), f"{path2} 还在")
# ---------------------------------------------------------------- 25
section("25. 工具调用明细要落库(真机反馈「工具怎么重启就不显示了」)")
#
# ★ 界面上那些"工具卡片"(调了什么、成没成、返回什么)以前只有**流式那一刻**
# 看得到 —— 因为这份明细从来没落过库,重启 App 就全没了。
# 现在 `agent_loop` 收集 → `app.py` 落进消息 → 客户端解析。
# 三处缺一处都白搭,所以逐处断言(这是"改一半"的高发区)。
_kd = os.path.dirname(os.path.abspath(__file__))
_loop = open(os.path.join(_kd, '..', 'android', 'kernel', 'agent_loop.py'),
encoding='utf-8').read()
_app2 = open(os.path.join(_kd, '..', 'android', 'kernel', 'app.py'),
encoding='utf-8').read()
check("agent_loop 收集了明细",
'tool_trace = []' in _loop and 'tool_trace.append(' in _loop,
"没有 tool_trace —— 工具卡片只在流式那一刻存在")
check("agent_loop 把它放进了**两条** return(正常收尾 + 轮次用尽)",
_loop.count("'toolTrace': tool_trace") >= 2,
f"只有 {_loop.count(chr(39) + 'toolTrace' + chr(39) + ': tool_trace')} 处")
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:

View File

@@ -132,6 +132,67 @@ def main():
check("非 dict 的东西被跳过", W.trim([{'role': 'user'}, 'noise', None], 20)['kept'] == 1)
check("describe 不炸", isinstance(W.describe(W.trim(convo(30), 20, 5)), str))
print("\n=== 8. 标记重要:从存储到裁剪的整条路 ===")
#
# 这一节测的是**端到端**:界面调接口 → 存库 → 裁剪时读它。
# 中间任何一环断了,用户看到的现象都是"我标了,但它还是被裁掉了"。
import store
conv = store.create_conversation('测试', agent_id='A')
store.append_messages(conv['id'], [
{'role': 'user', 'content': '记住这句'},
{'role': 'assistant', 'content': '好的'},
])
check("新消息默认没标记", not (store.get_conversation(conv['id'])['messages'][0].get('important')))
m = store.mark_important(conv['id'], 0, True)
check("标记上了", m and m.get('important') is True, str(m))
# ★ 关键:标记**不能动 content**(需求 4.3 的"字节冻结")
check("**content 一个字节都没动**(字节冻结)", m.get('content') == '记住这句', str(m))
check("越界下标返回 None(不抛异常)", store.mark_important(conv['id'], 99, True) is None)
check("不存在的会话返回 None", store.mark_important('nope', 0, True) is None)
check("能取消标记", store.mark_important(conv['id'], 0, False).get('important') is False)
# 端到端:标过的消息在裁剪时被捞回
msgs = []
for i in range(30):
msgs.append({'role': 'user', 'content': f'问{i}', 'important': i == 0})
msgs.append({'role': 'assistant', 'content': f'答{i}'})
r = W.trim(msgs, 20, 5)
check("端到端:标记过的老消息**没被裁掉**",
any(m['content'] == '问0' for m in r['messages']), str(r.get('rescued')))
check("没标记的老消息被裁掉了", not any(m['content'] == '问5' for m in r['messages']))
print("\n=== 9. ★★ 按内容定位(下标定位踩过的坑)===")
#
# 界面上那份消息列表和存储里那份**不保证一一对应**(本地生成的内容、
# 还没落地的流式消息……)。按下标"长按第 3 条"会把标记打到第 1 条上,
# 而且**静默标错** —— 真机上就是这么错的。
c3 = store.create_conversation('定位', agent_id='A')
store.append_messages(c3['id'], [
{'role': 'user', 'content': '第一句'},
{'role': 'assistant', 'content': '回一句'},
{'role': 'user', 'content': '第三句'},
])
m = store.mark_important_by_content(c3['id'], '第三句', 'user', True)
check("按内容标到了**那一条**", m and m.get('content') == '第三句', str(m))
flags = [(x['content'], bool(x.get('important')))
for x in store.get_conversation(c3['id'])['messages']]
check("**只标了那一条**(别的没被误标)",
flags == [('第一句', False), ('回一句', False), ('第三句', True)], str(flags))
check("内容对不上 → None(**绝不猜一条标上去**)",
store.mark_important_by_content(c3['id'], '没有这句话', 'user', True) is None)
check("空内容 → None", store.mark_important_by_content(c3['id'], '', 'user', True) is None)
check("不存在的会话 → None", store.mark_important_by_content('nope', '第一句', 'user', True) is None)
# 重复内容:从后往前找(用户长按的通常是靠后那条)
c4 = store.create_conversation('重复', agent_id='A')
store.append_messages(c4['id'], [
{'role': 'user', 'content': '一样'},
{'role': 'user', 'content': '别的'},
{'role': 'user', 'content': '一样'},
])
store.mark_important_by_content(c4['id'], '一样', 'user', True)
flags4 = [bool(x.get('important')) for x in store.get_conversation(c4['id'])['messages']]
check("重复内容标**最后**一条(从后往前找)", flags4 == [False, False, True], str(flags4))
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")

View 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);

View File

@@ -52,7 +52,10 @@ def main():
participants=[a['id'], b['id']])
check("type 存下来了", conv.get('type') == 'group', str(conv.get('type')))
check("participants 存下来了", len(G.member_ids(conv)) == 2, str(G.member_ids(conv)))
check("主智能体 = 成员列表第一个", G.host_id(conv) == a['id'], G.host_id(conv))
# ⚠️ `host_id` 现在**不再用于决定谁发言**(用户要求「群聊去掉主人设定」),
# 只剩 remove_member 里「不能把最后一个人踢走」这一个用途。
check("host_id 还在(但只表示「列表第一个」,不是发言优先级)",
G.host_id(conv) == a['id'], G.host_id(conv))
old = store.create_conversation('老会话')
check("老会话默认是 single", (old.get('type') or 'single') == 'single')
check("非法 type 会被规整成 single",
@@ -68,18 +71,18 @@ def main():
# ② AI 移交
r = G.resolve(conv, passed=b['id'], handoffs=0)
check("② AI 移交的人发言", r['speaker'] == b['id'] and r['reason'] == 'handoff', str(r))
# ③ 兜底
# ③ 兜底:**按顺序轮,不设主人**(用户要求「群聊去掉主人设定」)
r = G.resolve(conv)
check("③ 没人点名时主智能体兜底(永不冷场)",
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
check("③ 没人点名时按顺序轮(新群从第一个开始)",
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
# ④ 被点的人死亡
r = G.resolve(conv, passed=b['id'], alive={b['id']: False})
check("④ **死亡的人接不了,回主智能体**",
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
check("④ **死亡的人接不了,换下一个人**",
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
check("④ 而且说明了原因(界面/日志能看懂)", '死亡' in str(r.get('note')), str(r.get('note')))
# ⑤ 一轮内重复移交
r = G.resolve(conv, passed=b['id'], handoffs=G.MAX_HANDOFF_PER_ROUND)
check("⑤ 一轮内第二次移交被拒(回主智能体)",
check("⑤ 一轮内第二次移交被拒(换下一个人)",
r['speaker'] == a['id'] and r['reason'] == 'handoff_denied', str(r))
# 用户 @ 不受"一轮一次"约束(那条只管 AI 的移交)
r = G.resolve(conv, want=b['id'], handoffs=99)
@@ -99,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))
@@ -125,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'})
@@ -144,13 +157,18 @@ def main():
b['id'] in G.member_ids(store.get_conversation(c2['id']) or {}))
print("\n=== 6. pass_turn 工具 ===")
# ★ 每次都 push 完整上下文 —— `push_context` 是**替换**语义,
# 只补一个键会把 agentId / conversationId 冲掉(这个坑踩过)
# ★ 每次 `begin_round()` —— agent_loop 每轮开头会调它。
# 不调的话上一节留下的 `used=True` 会让这里全变成"已经移交过"。
tools_runtime.begin_round()
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
r = agent_tools.pass_turn({'target': '仙辰'})
check("移交成功", r.get('handed_to') == '仙辰', str(r))
check("上下文里记了移交标记", tools_runtime.current_context().get('handoffUsed') is True)
check("也记了交给谁", tools_runtime.current_context().get('handoffTo') == b['id'])
# ★ 读**轮次状态**,不是工具上下文 —— 上下文是 thread-local,
# 工具跑在 worker 线程里写的东西回不来(这就是当初失效的原因)
check("轮次状态里记了移交标记", tools_runtime.handoff_state().get('used') is True,
str(tools_runtime.handoff_state()))
check("也记了交给谁", tools_runtime.handoff_state().get('to') == b['id'],
str(tools_runtime.handoff_state()))
# 一轮内第二次:拒
try:
agent_tools.pass_turn({'target': '仙辰'})
@@ -162,6 +180,7 @@ def main():
dead = store.create_agent({'name': '死者'})
store.update_agent(dead['id'], {'worldviewId': world['id']})
agentdb.emotion_set(dead['id'], preset='死亡')
tools_runtime.begin_round() # 开新一轮,否则先撞上"已经移交过"
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
try:
agent_tools.pass_turn({'target': '死者'})
@@ -169,22 +188,75 @@ def main():
except ValueError as exc:
check("**死亡目标移交无效**", '死亡' in str(exc), str(exc))
check("理由说的是死亡,不是别的", '已经移交过' not in str(exc), str(exc))
tools_runtime.begin_round()
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
try:
agent_tools.pass_turn({'target': '玄辰'})
check("交给自己被拒", False, "居然允许了")
except ValueError as exc:
check("交给自己被拒", '自己' in str(exc), str(exc))
tools_runtime.begin_round()
print("\n=== 7. 附录 B 的工具清单齐了吗 ===")
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status',
'invite_agent', 'pass_turn'):
'invite_agent', 'pass_turn', 'talk_to'):
check(f"有 {want}", want in agent_tools.AGENT_TOOLS)
# 附录 B 列了 10 个工具,外加"建议机制"(memory_suggest_summary)= 11
check("一共 11 个(附录 B 的 10 个 + 建议机制)", len(agent_tools.AGENT_TOOLS) == 11,
# 附录 B 列了 10 个,外加"建议机制"(memory_suggest_summary)
# 和新增的 talk_to(用户要求:智能体主动找另一个智能体说话)= 12
check("一共 12 个(附录 B 的 10 个 + 建议机制 + talk_to)",
len(agent_tools.AGENT_TOOLS) == 12,
str(sorted(agent_tools.AGENT_TOOLS)))
print("\n=== 8. 私聊:轮数解析与额度判据 ===")
print("\n=== 8. ★★ 走真实路径测 pass_turn(旧探针是假通过)===")
#
# ★★ 这一节**必须**走 `tools_runtime.execute_tool`。
#
# 它会把上下文复制到 **worker 线程** 去执行(`run_with_timeout` 起线程),
# 而 `_ctx` 是 thread-local —— 工具在 worker 里写的东西**回不到主线程**。
#
# 旧探针直接调 `agent_tools.pass_turn`(主线程),标记留在主线程里
# 没被清,于是"一轮最多一次"看着是好的 —— **假通过**,
# 而真机上每一轮都能无限次移交(`handoffUsed` 永远是 False)。
#
# 教训:**探针的调用路径必须和真实调用路径一致**。
# 直接调函数测的是"函数逻辑对不对",不是"它在这个系统里生不生效"。
settings = store.read_settings()
c2 = store.create_conversation('群2', agent_id=a['id'], kind='group',
participants=[a['id'], b['id']])
def real_call(name: str, args: dict):
"""走真实的工具调用路径(含 worker 线程 + 上下文重置)"""
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'], toolName=name)
try:
return tools_runtime.execute_tool(name, args, settings)
finally:
tools_runtime.clear_context()
tools_runtime.begin_round() # agent_loop 每轮开头会调这个
r1 = real_call('pass_turn', {'target': '仙辰'})
check("真实路径:第 1 次移交成功", r1.get('ok') is True, str(r1))
st = tools_runtime.handoff_state()
check("**移交目标跨线程保住了**(这是旧实现丢掉的那个)",
st.get('to') == b['id'], str(st))
check("状态标成 used", st.get('used') is True, str(st))
r2 = real_call('pass_turn', {'target': '仙辰'})
check("真实路径:**第 2 次被拒**(一轮最多一次真的生效了)",
r2.get('ok') is False and '已经移交过' in str(r2.get('error')), str(r2))
# app.py 从轮次状态取(不是从 HTTP body —— 界面根本不发那个字段)
check("移交目标能被 app.py 读到(仲裁的 ② 分支不再是死代码)",
tools_runtime.handoff_state().get('to') == b['id'], str(tools_runtime.handoff_state()))
# 新一轮开始要重置
tools_runtime.begin_round()
check("新一轮开始后重置(可以再移交)",
tools_runtime.handoff_state().get('to') == ''
and tools_runtime.handoff_state().get('used') is False,
str(tools_runtime.handoff_state()))
r3 = real_call('pass_turn', {'target': '仙辰'})
check("新一轮里又能移交了", r3.get('ok') is True, str(r3))
tools_runtime.begin_round()
print("\n=== 9. 私聊:轮数解析与额度判据 ===")
import private_chat as P
check("默认 10 轮(需求定的)", P.resolve_rounds({}) == 10, str(P.resolve_rounds({})))
@@ -202,7 +274,7 @@ def main():
check("没超限额时 false", P.limit_hit({**a, 'tokenLimit': 1000}) is False)
check("超了才是 true", P.limit_hit({**a, 'tokenLimit': 100}) is True)
print("\n=== 9. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
print("\n=== 10. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
turns = [
{'agentId': a['id'], 'name': '玄辰', 'content': '你来了。'},
{'agentId': b['id'], 'name': '仙辰', 'content': '嗯,路上耽搁了。'},
@@ -214,7 +286,7 @@ def main():
check("对 B 来说正好反过来",
hb[0]['role'] == 'user' and hb[1]['role'] == 'assistant', str(hb))
print("\n=== 10. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
print("\n=== 11. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
#
# 这两个是需求里私聊唯一的硬约束,也是最该测的 ——
# 两个 AI 互相对话最大的风险就是**停不下来**(用户不在场,没人喊停)。
@@ -273,13 +345,259 @@ def main():
finally:
agent_loop.run_agent = real_run_agent
print("\n=== 11. 私聊的边界 ===")
print("\n=== 12. 私聊的边界 ===")
check("没有共同世界观时不写记忆(不替人记他没参与的事)",
P.summarize_to_memory(a, {'id': 'x', 'worldviewId': ''}, turns) == '')
check("没说话时不写摘要", P.summarize_to_memory(a, b, []) == '')
check("缺参数时返回错误而不是抛异常",
P.run_pair(store.read_settings(), {}, {}, max_rounds=1).get('ok') is False)
print("\n=== 13. 群聊不能被「会话隔离」当成换人设(真机反馈)===")
#
# ★★ 真机原话:「群聊一@就跑到别的对话去了」。
#
# app.py 里有两条挨着的逻辑,各自都对,叠在一起就出事:
# ① 群聊仲裁把 `agent_id` 换成**本轮的发言人**(@谁就是谁)
# ② 紧接着的「一个会话属于一个智能体」隔离拿它跟会话主人比,
# 不等就**另起一个会话**并通知界面切过去
# 于是群里每换一个人说话就跳一次对话。
#
# 修法是让隔离**跳过群聊**(群聊本来就是多智能体的,`agentId` 在那儿是发言人
# 不是主人)。这条没法在本进程里跑(要真的走 /api/chat),
# 所以直接对源码做断言 —— 和 audit-ui-tree 一个路子:
# 它防的是"以后有人把 is_group 那半句删掉",而不是算法本身。
_app = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
'..', 'android', 'kernel', 'app.py'), encoding='utf-8').read()
check("会话隔离对群聊免疫(`not group_chat.is_group(...)` 还在)",
'not group_chat.is_group(existing)' in _app,
"app.py 里那句群聊豁免被删了 —— 群聊 @ 谁就会跳到谁的对话")
check("单聊的隔离没被一起删掉(换智能体仍然另起会话)",
"elif owner != agent_id:" in _app and 'set_conversation_agent' in _app,
"隔离整段没了 —— 换智能体会串味")
print("\n=== 14. 自动续轮(AI 互相说话不能只有半截)===")
#
# ★ 群聊里 A 用 `pass_turn` 把话让给 B 之后,界面会**自动再发一次**
# (`autoContinue: true`)让 B 真的开口 —— 不然就是
# "用户说一句 → A 让给 B → 没下文了",用户得自己再发一条才看得到 B 说话。
#
# 这条路要真的调模型,本进程里跑不了,所以同样对源码断言。
check("内核认 `autoContinue`(界面替 AI 续的那一轮)",
"body.get('autoContinue')" in _app,
"autoContinue 没被读 —— 自动续轮会变成往对话里塞空消息")
check("续轮时**不追加用户消息**(否则对话里会冒出一堆空消息)",
"if not auto_continue:" in _app,
"append_messages 没被 auto_continue 包住")
print("\n=== 15. 轮中移交要告诉界面(否则两个 AI 永远聊不起来)===")
#
# ★★ 真机反馈第二版:「还是不能互相对话」。
#
# 第一版是靠 `speaker` 事件的 `reason == 'handoff'` 判断的 —— 但那个
# 事件是**轮前**发的,而 `pass_turn` 是**轮中**才调的。最常见的剧本是:
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
# ② 主智能体说完话,轮中调 `pass_turn` 让给别人
# 界面看到的 reason 是 "host",就以为没人移交,**不再续轮** ——
# 被让的那个人永远开不了口。
#
# 所以轮末必须补一个 `handoff` 事件。这条同样对源码断言(要真跑模型)。
check("轮末会 emit `handoff`(判据是**轮中**的移交状态,不是轮前的 reason)",
"'type': 'handoff'" in _app,
"缺这个事件 → 界面不知道 AI 中途交了话 → 两个 AI 永远聊不起来")
check("判据取自 tools_runtime 的轮次状态(不是线程局部变量)",
"tools_runtime.handoff_state()" in _app,
"handoff_state 没被读 —— pass_turn 那条链路是断的")
print("\n=== 16. 「让他们聊」:界面直接指定发言者 ===")
#
# ★★ 真机反馈第三版:还是聊不起来。
#
# 原因很实在:**AI 并不总会调 `pass_turn`** —— 它更愿意自己把话说完。
# 所以"等它自觉移交"这条路靠不住。用户要的是一个能按下去的入口:
# 点「让他们聊」,界面就一轮一轮把发言权在两个人之间递过去
# (`forceSpeaker`),完全不依赖 AI 配合。
gconv = store.create_conversation(
title='对聊测试', agent_id=a['id'], kind='group', participants=[a['id'], b['id']],
)
r = G.resolve(gconv, forced=b['id'])
check("forced 直接生效(用户没点名时)", r['speaker'] == b['id'] and r['reason'] == 'forced', str(r))
r = G.resolve(gconv, want=b['id'], forced=a['id'])
check("**用户 @ 压过 forced**(「@ 的时候立即切换」——自动对聊必须让位)",
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
r = G.resolve(gconv, forced='不存在的人')
check("forced 指定的人不在场 → 换下一个人(不抛异常)",
r['reason'] == 'rotate', str(r))
r = G.resolve(gconv, want=b['id'])
check("不传 forced 时用户 @ 仍然优先(原有行为没被改坏)",
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
r = G.resolve(gconv)
check("什么都不传 → 按顺序轮(永不冷场,但没主人)",
r['reason'] == 'rotate', str(r))
# ★★ 自动续轮**没有用户消息**,所以 `_handle_chat` 开头那条"消息为空"
# 的校验必须给它放行 —— 否则每一轮都被打回 400,
# 界面上是一屏「出错了:消息为空」,用户看到的就是"还是不能互相对话"。
# (真机现场截图就是这么六条错误。)
check("`_handle_chat` 给自动续轮放行空消息",
"not auto_continue" in _app and "bool(body.get('forceSpeaker'))" in _app,
"空消息校验没放行 autoContinue/forceSpeaker")
# 两边判据必须一致,不然一边放行一边往里塞空用户消息
check("两处判据一致(校验处 与 追加消息处 用同一个条件)",
_app.count("bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))") >= 2,
"两处条件不一致 —— 对话里会冒出一堆空条目")
print("\n=== 17. talk_to:智能体主动找另一个智能体说话 ===")
#
# ★★ 用户的原话:「不是这样聊是智能体主动调用工具和别的智能体聊」
# 「工具定义 / 智能体加上内容」。
#
# 所以这个工具的**参数就是那两样**:跟谁说 + 说什么。
# 它和 `pass_turn` 的分工是关键:那个只交发言权、**不带内容** ——
# 对方接到的是一片空白,只能凭上下文猜,聊不起来。
entry = agent_tools.AGENT_TOOLS.get('talk_to')
check("工具注册了(AGENT_TOOLS 里能找到)", entry is not None,
str(sorted(agent_tools.AGENT_TOOLS)))
if entry:
props = entry['spec'].get('parameters', {}).get('properties', {})
# ★ 参数演化过:最早是「agent + 内容」,后来加了多目标(agents)
# 和私聊(private),所以必填只剩 content —— 目标二选一。
check("参数含「目标 + 内容」",
{'agent', 'agents', 'content'} <= set(props), str(list(props)))
check("只要求 content 必填(agent/agents 二选一)",
list(entry['spec']['parameters'].get('required') or []) == ['content'],
str(entry['spec']['parameters'].get('required')))
# ★ 模型要能看见它 —— AGENT_TOOLS 会被合并进 BUILTIN_TOOLS 才是真注册
import builtin_tools
check("模型真的能看到它(合并进了 BUILTIN_TOOLS)",
'talk_to' in builtin_tools.BUILTIN_TOOLS, "没合并进工具表")
# 单聊里没有"别人"可聊。
# ★ 断言看**返回值**,不是等它抛 —— `real_call` 走 `execute_tool`,
# 那一层会把工具抛的异常捕获成 `{'ok': False, 'error': ...}`。
# (直接调 `agent_tools.talk_to` 才会抛,但那样测的就不是真实路径了。)
#
# ★★ 必须**新建**一条:上面第 5 节测 `invite_agent` 时把原来的
# `single` 拉人拉成了群聊(`invite_agent` 会把 type 改成 group)——
# 拿它当"单聊"用,断言必然失败。这种"用例被前面的测试改脏了"
# 很隐蔽:断言的错看着像代码的错。
lonely = store.create_conversation('真的单聊', agent_id=a['id'])
tools_runtime.push_context(agentId=a['id'], conversationId=lonely['id'], toolName='talk_to')
try:
r = tools_runtime.execute_tool('talk_to', {'agent': '仙辰', 'content': '在吗'},
store.read_settings())
finally:
tools_runtime.clear_context()
check("单聊里会被拒(没有别人可以聊)",
r.get('ok') is False and '不是群聊' in str(r.get('error')), str(r))
# 群聊里:话要落进对话 + 发言权交给对方
tools_runtime.begin_round()
before = len((store.get_conversation(c2['id']) or {}).get('messages') or [])
r = real_call('talk_to', {'agent': '仙辰', 'content': '你刚才那句话是什么意思?'})
check("群聊里调用成功", r.get('ok') is True, str(r))
msgs = (store.get_conversation(c2['id']) or {}).get('messages') or []
check("**说的话真的进了对话**(`pass_turn` 就没有这一步)",
len(msgs) == before + 1 and '什么意思' in (msgs[-1].get('content') or ''),
str([m.get('content') for m in msgs[-2:]]))
check("那条消息的发言者**是我**", msgs[-1].get('agentId') == a['id'],
str(msgs[-1].get('agentId')))
check("**发言权交给了对方**(界面据此自动续一轮让他回应)",
tools_runtime.handoff_state().get('to') == b['id'],
str(tools_runtime.handoff_state()))
# 一轮最多一次:既 pass_turn 又 talk_to 要被拦住
tools_runtime.begin_round()
real_call('pass_turn', {'target': '仙辰'})
r = real_call('talk_to', {'agent': '仙辰', 'content': '再说一句'})
check("一轮里不能又移交又找人聊",
r.get('ok') is False and '已经' in str(r.get('error')), str(r))
# 内容不能为空
tools_runtime.begin_round()
r = real_call('talk_to', {'agent': '仙辰', 'content': ' '})
check("空内容会被拒(内容是必填的)",
r.get('ok') is False and ('content' in str(r.get('error')) or '什么' in str(r.get('error'))),
str(r))
print("\n=== 18. 群聊去掉主人设定:没人点名时按顺序轮 ===")
#
# ★★ 用户原话:「群聊去掉主人设定」。
#
# 原来兜底永远是"会话发起者"(成员列表第一个)—— 等于群里有个老大:
# 其他人不 @ 就不开口。现在看**最近一条 AI 消息是谁说的**,
# 下一个人接上,谁都不欠谁。
rconv = store.create_conversation(title='轮', agent_id=a['id'], kind='group',
participants=[a['id'], b['id']])
r = G.resolve(rconv)
check("新群没人说过时从第一个开始",
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'x', 'agentId': a['id']}])
r = G.resolve(store.get_conversation(rconv['id']))
check("a 说过了 → 下一个是 b(不是永远 a)", r['speaker'] == b['id'], str(r))
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'y', 'agentId': b['id']}])
r = G.resolve(store.get_conversation(rconv['id']))
check("b 说过了 → 又轮回到 a", r['speaker'] == a['id'], str(r))
check("理由统一是 rotate(界面上不再有「主」这个身份)",
r['reason'] == 'rotate', str(r))
print("\n=== 19. 提示词要教模型怎么用 talk_to(真机反馈「智能体不怎么会用」)===")
#
# ★★ 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
# 于是对方接到一片空白,两个人永远聊不起来。
import defaults
_skill = defaults.BUILTIN_SKILL
check("skill 里提到了 talk_to", 'talk_to' in _skill, "提示词没教这个工具")
check("说清了它和 pass_turn 的区别",
'pass_turn' in _skill and ('空白' in _skill or '不带内容' in _skill),
"没讲清区别 —— 模型会继续拿 pass_turn 当说话用")
check("写明了「一轮最多一次」", '一轮最多一次' in _skill, "模型会一轮调好几次")
print("\n=== 20. 加人接口必须真的进得去(真机反馈「点加人没反应」)===")
#
# ★★ 真机现场:点「加人」→ 选人 → 没反应、人也没加到,接口回 **404 未知接口**。
#
# 原因不是路由没写,而是它用 `_match_id(pathname, '/api/conversations/')`
# 去解析 id —— 那个函数要求「id 后面没有斜杠」,而这条路是
# `/api/conversations/<id>/members`,`rest` 里带 `/` 直接返回 None,
# **整个分支永远进不去**。
#
# 这条断言守的就是"别再退回去用 _match_id"。
check("成员增删路由自己解析 id(不能用 _match_id)",
"if pathname.startswith('/api/conversations/') and '/members' in pathname:" in _app,
"又用回 _match_id 了 —— 加人会 404")
print("\n=== 21. talk_to 多目标 / 私聊 + 群聊里能看到谁说的 ===")
#
# 用户的三个要求:
# ① 智能体能读到群里**所有人**的发言(不是只看到自己的)
# ② talk_to 加私聊:只有目标知道
# ③ talk_to 支持多目标:目标挨个回话
spec2 = agent_tools.AGENT_TOOLS['talk_to']['spec']['parameters']
props2 = spec2.get('properties', {})
check("talk_to 支持 `agents` 多目标", 'agents' in props2, str(list(props2)))
check("`agents` 是数组", props2.get('agents', {}).get('type') == 'array', str(props2.get('agents')))
check("talk_to 支持 `private` 私聊", 'private' in props2, str(list(props2)))
check("只要求 content 必填(agent/agents 二选一)",
spec2.get('required') == ['content'], str(spec2.get('required')))
# 移交状态要能带队列(多目标挨个回话靠它)
import tools_runtime as _tr
_tr.begin_round()
_tr.note_handoff('a', queue=['a', 'b', 'c'])
_st = _tr.handoff_state()
check("移交状态带队列(多目标挨个回)",
_st.get('to') == 'a' and _st.get('queue') == ['b', 'c'], str(_st))
_tr.begin_round()
check("新一轮把队列也清掉", _tr.handoff_state().get('queue') == [], str(_tr.handoff_state()))
# 群聊里送进模型的历史要标发言人 + 过滤别人的私聊
check("送进模型的历史标了发言人(`[名字] ` 前缀)",
'_[who]' in _app.replace('[', '_[', 1) or 'f\'[{_who}] {_content}\'' in _app,
"没标发言人 —— 模型分不清哪句是别人说的")
check("别人的私聊消息会被过滤掉(`privateTo`)",
"m.get('privateTo')" in _app, "没过滤 —— 私聊会被全群看到")
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")

View 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
View 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 */ }
});
}

View 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
View 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);
}

View File

@@ -6,7 +6,8 @@
"e289048324c38899"
],
"_ui_bridge.py": [
"048c7685991715fb"
"048c7685991715fb",
"4efeaba4272aa679"
],
"ask_user.py": [
"94a9734c8c934db2",

View File

@@ -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

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Some files were not shown because too many files have changed in this diff Show More