Compare commits

...

4 Commits

Author SHA1 Message Date
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
30 changed files with 1235 additions and 129 deletions

View File

@@ -1,4 +1,4 @@
plugins {
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 271
versionName = "2.0.71"
versionCode = 274
versionName = "2.0.74"
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

@@ -1,4 +1,4 @@
package com.doubao.lynxclone.ui
package com.doubao.lynxclone.ui
import android.util.Base64
import androidx.activity.compose.rememberLauncherForActivityResult
@@ -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 → 这里落盘。

View File

@@ -622,12 +622,42 @@ private fun DrawerOverlay(vm: AppViewModel) {
}
Spacer(Modifier.height(10.dp))
SectionLabel("对话", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.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(

View File

@@ -1,5 +1,7 @@
package com.doubao.lynxclone.ui
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
@@ -222,10 +224,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()
}
}
@@ -312,13 +317,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 ?: "这张图没传上去") }
}
}
@@ -1349,6 +1399,31 @@ 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 你一句我一句停不下来(那是烧钱) */
private var autoRounds = 0
/**
* 一次自动对聊最多续几轮。
*
* 3 是个保守值:够看出"他们真的在对话",又不至于用户一转头回来
* 发现 Token 少了一大截。想聊更久,用户再发一句就是了。
*/
private val autoRoundCap = 3
init {
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
AiSurface.subscribe { kind ->
@@ -1580,10 +1655,114 @@ 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()` 一起失效。
*/
/**
* 点名(点群聊底部的 `@某人`)。
*
* ★ 除了把 `@名字 ` 插进草稿,还要**立即把展示切到那个人** ——
* 用户的要求原话是「@ 的时候立即切换」:
* 点了谁,立绘/背景马上就是他,而不是等到回复回来才换
* (等内核跑完那一轮再换,中间那段空白看着像"点了没反应")。
*
* ★ 顺手把「让他们聊」掐掉:用户点名 = 他要接管发言权了。
*/
fun mentionAgent(agentId: String, name: String) {
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
draft = draft + "@$name "
currentSpeakerId = agentId
speakerNote = ""
}
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)
val cancel = AtomicBoolean(false)
chatJob = cancel
@@ -1597,7 +1776,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}" }) }
@@ -1607,12 +1791,49 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
chatJob = null
patchLast { it.copy(pending = false) }
refresh()
// ★★ 群聊里 AI 把话交给了别人 → 自动替他续一轮。
//
// 这样两个智能体就能**自己聊起来**,而不是
// "用户说一句、A 让给 B、然后就没下文了"。
// 用户随时可以点「停止」打断(`cancel.get()`),
// 也随时可以直接发消息把话题拉回来。
val conv = state.conversations.firstOrNull { it.id == activeConversationId }
val canContinue = !cancel.get() && conv?.isGroup == true
if (canContinue && aiTalkLeft > 0) {
// ★ ① 「让他们聊」:按顺序把发言权递给下一个人。
// 这条路**不依赖 AI 配合** —— 实测 AI 并不总会 pass_turn,
// 所以"等它自觉移交"是靠不住的。
aiTalkLeft--
aiTalkTurn++
val next = aiTalkPair[aiTalkTurn % aiTalkPair.size]
runChat("", emptyList(), auto = true, forceSpeaker = next)
} else if (canContinue && handoffDone.get() && autoRounds < autoRoundCap) {
// ② AI 自己 `pass_turn` 交的话 —— 也接着让它说出来
handoffDone.set(false)
autoRounds++
runChat("", emptyList(), auto = true)
} else {
// 收尾:清掉自动对聊的计数,免得下次发消息又自己续上
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
}
}
}
}
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
private fun onStreamEvent(event: StreamEvent) {
// ★★ 这一行必须在 `launch` **外面**。
//
// `client.chat` 的回调是同步跑在 IO 线程上的,而 `runChat` 的
// `finally` 紧接着就要读这个标志来决定续不续轮。
// 放进 launch 里就变成异步 —— 会和 finally 抢,抢输了那一轮就不续,
// 表现是"两个 AI 有时候能聊、有时候聊不起来"。
if (event is StreamEvent.Handoff) handoffDone.set(true)
viewModelScope.launch {
when (event) {
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
@@ -1669,6 +1890,17 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
currentSpeakerId = event.agentId
speakerNote = event.note
}
// ★ 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
@@ -56,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
@@ -234,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)
}
}
}
@@ -267,6 +270,9 @@ fun ChatScreen(vm: AppViewModel) {
ChatHeader(vm, agent?.name ?: "豆包", speech)
Box(Modifier.weight(1f).fillMaxWidth()) {
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
ChatBackdrop(vm)
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
@@ -280,8 +286,11 @@ fun ChatScreen(vm: AppViewModel) {
tagline.endsWith("?") || tagline.contains(","))
val greeting =
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
item { AppearOnce { ChatPortrait(vm) } }
// ★ 这里原来还有一个 168dp 的圆形立绘(ChatPortrait)——
// 背景层(ChatBackdrop)接手之后它就是多余的:两张同一个人的图
// 叠在一起,而且圆形 Crop 会把全身图裁到腰上,很难看。
item { AppearOnce { HeroText(greeting) } }
item { AppearOnce { PortraitHint(vm) } }
}
items(vm.messages.size) { index ->
AppearOnce(offsetY = 10.dp) {
@@ -584,7 +593,7 @@ private fun HeroText(greeting: String) {
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())
@@ -603,54 +612,131 @@ private fun HeroText(greeting: String) {
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
* 两处各写一个数字的话,将来改一处必漏另一处。)
*/
/**
* 聊天页整屏背景/立绘的**主人**。
*
* ★★ 就是**当前这条对话的智能体**(`activeAgent`)—— 用户的原话:
* 「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
*
* 我一开始做成了"跟着当前发言者换",那是错的:
* 聊天页的背景表达的是**这个场景是谁的**(和顶栏那个名字是一回事),
* 而**不是**"这一轮谁在开口"。群里两个人一来一回时背景跟着闪,
* 既晃眼又和顶栏的名字对不上。
*
* "谁在说话"是**每条消息**自己的事 —— 那个用 `msg.agentId`
* (见 [SpeakerTag] 和朗读挑音色那两处),和背景不是一回事。
*
* ★ 所以这里和顶栏用的是同一个来源,天然一致,不会再出现
* "名字是小黑、背景是寐眠"。
*/
private fun backdropAgent(vm: AppViewModel): Agent? = vm.activeAgent
/**
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
*
* ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆,
* 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」,
* 而他要的是整个背景都是这个角色。
*
* ★★ 显示的是**当前对话的智能体**(`activeAgent`),不是"这一轮谁在说"。
* 用户澄清过:「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
* 背景表达的是**这个场景是谁的**(和顶栏那个名字同一件事);
* 群聊里两个人一来一回时背景跟着闪,既晃眼又和顶栏对不上。
* "谁在说话"是**每条消息**自己的事,用 `msg.agentId`(见 [SpeakerTag])。
*
* ★ 两条硬约束:
* · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住;
* · **图要实心、气泡要半透明** —— 这是用户点名要的一对
* (「立绘不要透明的」+「聊天框半透明」)。反过来做(图淡化、气泡实心)
* 等于两头都不讨好:立绘看不清,气泡也白透。
* 所以可读性交给气泡那边([doubaoBubbleVeil]),这里不淡化。
*
* ★ 立绘用 `ContentScale.Fit` 而不是 `Crop`:角色不能被裁掉半个身子。
* 背景图反过来,必须 `Crop` —— `Fit` 会留出底色,铺不满。
*/
@Composable
private fun ChatPortrait(vm: AppViewModel) {
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
// 谁在说话:跟随开着 && 是群聊 → 用**内核仲裁出来的**那一位;否则当前智能体
val who = if (vm.state.settings.followSpeaker && conv?.isGroup == true &&
vm.currentSpeakerId.isNotBlank()
) {
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId } ?: vm.activeAgent
} else {
vm.activeAgent
}
private fun ChatBackdrop(vm: AppViewModel) {
val who = backdropAgent(vm)
val back = who?.image?.back.orEmpty()
val art = who?.image?.portrait.orEmpty()
// ★ 用 key(art) + AnimatedContent:图变了才做过渡,
// 没变时(比如只是又聊了一句)不该白做一次动画
androidx.compose.animation.Crossfade(
targetState = art,
animationSpec = androidx.compose.animation.core.tween(300),
label = "portrait",
) { path ->
Box(
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
contentAlignment = Alignment.Center,
) {
if (path.isNotBlank()) {
AssetImage(path, Modifier.size(168.dp), contentScale = ContentScale.Crop)
} else {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
}
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),所以显示这张图**没错** ——
// 但界面上一个字都不说的话,用户只会觉得"立绘功能没生效",
// 而不知道**得自己去传**(内置那四个示例智能体默认都没有图)。
if (art.isBlank() && who != null) {
Spacer(Modifier.height(8.dp))
Text(
"还没有立绘 · 点这里去传一张",
fontSize = 11.sp,
color = Doubao.Blue,
modifier = Modifier.clickable { vm.openAgentEdit(who) },
)
}
}
/**
* 没配立绘时**说清楚 + 给入口**。
*
* ★ 回退链最后一级就是「内置默认人物」(需求 §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) {
@@ -694,11 +780,12 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
}
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) {
@@ -717,7 +804,7 @@ 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 },
@@ -743,6 +830,9 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
}
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
// 群聊里标出**这条是谁说的**(用户要求:「对话前面写明是谁在说话」)
SpeakerTag(vm, msg, mine = false)
val hasReasoning = msg.reasoning.isNotBlank()
val hasTrace = msg.toolTrace.isNotEmpty()
@@ -827,7 +917,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 {
@@ -951,7 +1041,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))
@@ -1174,7 +1265,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)
@@ -1292,8 +1401,17 @@ private fun GroupQuickBar(vm: AppViewModel) {
// 主智能体标一下:没人被 @ 时由它接话,用户得知道"不点名也有话说"
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} " })
// 点名除了插草稿,还要**立即**把立绘/背景切过去
// (用户要求:「@ 的时候立即切换」)
DoubaoPill(text = "@$label", onClick = { vm.mentionAgent(pair.first, pair.second) })
}
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
//
// 为什么需要这个按钮:光靠 AI 自己 `pass_turn` 是靠不住的 ——
// 实测它更愿意把话说完,于是"两个智能体对话"永远发生不了
// (用户报的「还是不能互相对话」)。
// 这个按钮不依赖 AI 配合,界面直接按顺序把发言权递过去。
DoubaoPill(text = "让他们聊", onClick = { vm.startAiTalk() })
RowAction("成员") { vm.openMembers(conv.id) }
}
// ★ 仲裁**理由**(v1.2 §3.9):内核发了 note,界面以前收了但从不显示 ——

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

@@ -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 android.util.Base64
import androidx.activity.compose.rememberLauncherForActivityResult
@@ -447,11 +447,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 {

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]
@@ -547,7 +559,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 +648,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
@@ -979,12 +991,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)
@@ -1144,6 +1156,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 = ('喜', '怒', '哀', '平常', '死亡')
@@ -1219,7 +1249,15 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
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 '平常'
@@ -1254,7 +1292,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, {
@@ -1279,7 +1317,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),
@@ -1299,6 +1337,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

@@ -1,4 +1,4 @@
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
## 为什么是"内置工具"而不是 `tools/*.py`
@@ -651,6 +651,87 @@ def pass_turn(args: dict) -> dict:
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
TALK_TO = {
'name': 'talk_to',
'description': (
'在群聊里**主动对另一个智能体说一句话**。\n'
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
'★ 单聊里没有"别人",调了会报错。'
),
'parameters': {
'type': 'object',
'properties': {
'agent': {'type': 'string', 'description': '对方的名字或 id'},
'content': {'type': 'string', 'description': '你要对他说的话'},
},
'required': ['agent', 'content'],
},
}
def talk_to(args: dict) -> dict:
"""
主动找群里的另一个智能体说话。
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
「工具定义 / 智能体加上内容」):
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
而且那句话要**落进对话**,对方下一轮才看得到。
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
"""
import group_chat
import tools_runtime
me = _me()
if not me:
raise ValueError('拿不到当前智能体')
ctx = _ctx()
conv_id = str(ctx.get('conversationId') or '')
conv = store.get_conversation(conv_id) or {}
if not group_chat.is_group(conv):
raise ValueError('这条不是群聊 —— 只有群里有「别人」可以聊')
if tools_runtime.handoff_state().get('used'):
# 和 pass_turn 共用"一轮最多一次"那个标记:要么移交、要么找人说,
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
target = _find_agent(str(args.get('agent') or '').strip())
if not target:
raise ValueError(f'找不到叫「{args.get("agent")}」的智能体')
if target.get('id') == me.get('id'):
raise ValueError('不能对自己说 —— 直接说就行')
if target['id'] not in group_chat.member_ids(conv):
raise ValueError(f'「{target.get("name")}」不在这个群里,先把他拉进来')
content = str(args.get('content') or '').strip()
if not content:
raise ValueError('要说什么?content 不能是空的')
# ① 这句话以**我**的名义落进对话 —— 对方下一轮就看得到
store.append_messages(conv_id, [{
'role': 'assistant',
'content': content,
'agentId': me.get('id'),
'at': store.now_iso(),
}])
# ② 把发言权交给他 —— 界面据此自动续一轮,让他真的回应
tools_runtime.note_handoff(target['id'])
return {
'said_to': target.get('name'),
'note': f'你已经对「{target.get("name")}」说了这句话,接下来由他回应。',
}
# --------------------------------------------------------------------------- #
# 注册
# --------------------------------------------------------------------------- #
@@ -670,6 +751,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

@@ -1,4 +1,4 @@
"""
"""
HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上。
用的是 http.server.ThreadingHTTPServer + BaseHTTPRequestHandler:
@@ -1701,7 +1701,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
@@ -1798,20 +1806,36 @@ 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",找到的是**上一次**用户说的话,
# 于是出现:用户打 `@寐眠 在吗` → 仲裁按上一条(没点名)→
# 兜底给主智能体 → **小黑替寐眠答了**。
#
# 用户看到的是「@ 的时候没立即切换」「背景和智能体对不上」
# (背景跟着 @ 切到了寐眠,说话的却是小黑,两边对不上)。
#
# `autoContinue` 那几轮**本来就没有**新用户消息,那时才回退到历史。
want = group_chat.mention_in(text or '', names)
if not want and not text:
for m in reversed(raw_history):
if m.get('role') == 'user':
want = group_chat.mention_in(str(m.get('content') or ''), names)
break
pick = group_chat.resolve(
conv0,
want=group_chat.mention_in(last_user, names),
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'))
@@ -1850,7 +1874,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:
@@ -1915,14 +1945,29 @@ 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)
result = agent_loop.run_agent(
settings=settings,
@@ -1960,6 +2005,23 @@ class KernelHandler(BaseHTTPRequestHandler):
),
'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'], 'from': agent_id})
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
if agent_id and (in_tok or out_tok):

View File

@@ -73,7 +73,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,8 +81,17 @@ 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'|'host'|'handoff_denied'|'forced', 'note': ''}`。
★★ 为什么要有 [forced](真机反馈「还是不能互相对话」):
下面三条路都要求**用户点名**或者**AI 自己愿意移交**。
实测下来 AI 并不总会调 `pass_turn` —— 它更愿意自己把话说完,
于是"两个智能体对话"这件事就永远发生不了。
用户要的是一个**明确能按下去的入口**:点「让他们聊」,
界面就一轮一轮地把发言权在两个人之间递过去,不需要 AI 配合。
这是唯一能保证"一定聊得起来"的做法。
"""
conv = conv or {}
alive = alive or {}
@@ -92,7 +101,16 @@ def resolve(conv: dict, want: str = '', passed: str = '',
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': ''}
@@ -100,7 +118,16 @@ def resolve(conv: dict, want: str = '', passed: str = '',
return {'speaker': host, 'reason': 'host',
'note': '被点的人不在场或已死亡,发言权回主智能体'}
# ② AI 的移交(一轮最多一次)
# ② 界面指定的(「让他们聊」)—— 用户没点名时才轮到它
#
# 它只出现在界面的自动续轮里;用户手打消息时不会带上。
if forced:
if ok(forced):
return {'speaker': forced, 'reason': 'forced', 'note': ''}
return {'speaker': host, 'reason': 'host',
'note': '指定的人不在场或已死亡,发言权回主智能体'}
# ③ AI 的移交(一轮最多一次)
if passed:
if handoffs >= MAX_HANDOFF_PER_ROUND:
return {'speaker': host, 'reason': 'handoff_denied',

View File

@@ -644,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:
@@ -664,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

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: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 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

View File

@@ -25,7 +25,7 @@ v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿,
| §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.ChatPortrait`(crossfade 0.3s) |
| §6.1 背景跟随说话者 | `SettingsScreen.kt` 的「外观」组 + `ChatScreen.ChatBackdrop`(聊天页整屏立绘/背景层,跟着说话者换) |
### 两份"窗口"的命名纪律(需求点名要求,别混)
@@ -44,9 +44,22 @@ v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿,
| **`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`(图片 + 四种包导入),并且读不出来时**如实报原因**。
---
## 1. 需求 → 实现对照
@@ -237,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

View File

@@ -74,12 +74,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):
@@ -757,6 +764,124 @@ def main():
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} 还在")
# ---------------------------------------------------------------- 汇总
print()
if fails:

View File

@@ -1,4 +1,4 @@
"""群聊仲裁的探针(v1.2 §3.9)。
"""群聊仲裁的探针(v1.2 §3.9)。
点名制的分支有五种(用户 @ / AI 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交),
每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是
@@ -187,10 +187,12 @@ def main():
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. ★★ 走真实路径测 pass_turn(旧探针是假通过)===")
@@ -336,6 +338,170 @@ def main():
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['speaker'] == a['id'], 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['speaker'] == a['id'] and r['reason'] == 'host', 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', {})
check("参数就是「智能体 + 内容」", set(props) == {'agent', 'content'}, str(list(props)))
check("两个都是必填",
set(entry['spec']['parameters'].get('required') or []) == {'agent', '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()
if fails:
print(f"❌ {len(fails)} 项不合格:")