Compare commits

...

2 Commits

Author SHA1 Message Date
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
25 changed files with 765 additions and 106 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 = 273
versionName = "2.0.73"
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,26 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
private var chatJob: AtomicBoolean? = null
/**
* 这一轮 AI 是不是用 `pass_turn` 把话交给了别人(群聊才有)→ 跑完自动替他续一轮。
*
* ★ 没有它的话,群聊里的"AI 互相说话"就只是**半截**:
* A 把话让给 B,然后这一轮就结束了,B 永远没开口 ——
* 用户得再发一条消息才看得到 B 说话(用户要的是"他们自己聊起来")。
*/
private var handoffPending = false
/** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */
private var autoRounds = 0
/**
* 一次自动对聊最多续几轮。
*
* 3 是个保守值:够看出"他们真的在对话",又不至于用户一转头回来
* 发现 Token 少了一大截。想聊更久,用户再发一句就是了。
*/
private val autoRoundCap = 3
init {
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
AiSurface.subscribe { kind ->
@@ -1580,10 +1650,38 @@ 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("已停止")
}
private fun runChat(text: String, files: List<Attachment>, auto: Boolean = false) {
if (!auto) {
// 用户自己开的头:把自动续轮的计数清零
autoRounds = 0
messages.add(ChatMessage(role = "user", content = text, attachments = files))
}
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
streaming = true
handoffPending = false
val cancel = AtomicBoolean(false)
chatJob = cancel
@@ -1597,7 +1695,10 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
attachments = files,
agentId = activeAgent?.id,
cancelled = cancel,
) { event -> onStreamEvent(event) }
onEvent = { event -> onStreamEvent(event) },
// 自动续的那几轮不带用户消息(内核据此不追加)
autoContinue = auto,
)
}
} catch (e: Exception) {
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
@@ -1607,6 +1708,21 @@ 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 }
if (handoffPending && conv?.isGroup == true &&
!cancel.get() && autoRounds < autoRoundCap
) {
handoffPending = false
autoRounds++
runChat("", emptyList(), auto = true)
}
}
}
}
@@ -1668,6 +1784,11 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
is StreamEvent.Speaker -> {
currentSpeakerId = event.agentId
speakerNote = event.note
// ★ AI 用 `pass_turn` 把话交给了别人(reason == "handoff")。
// 记下来:这一轮跑完后要**自动替它续一轮**,
// 不然就变成"用户说一句 → A 把话让给 B → B 永远没开口"
// (用户要的「智能体可以和群聊中另外一个智能体对话」)。
if (event.reason == "handoff") handoffPending = true
}
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,50 +612,90 @@ private fun HeroText(greeting: String) {
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
* 两处各写一个数字的话,将来改一处必漏另一处。)
*/
@Composable
private fun ChatPortrait(vm: AppViewModel) {
/**
* 当前该显示**谁**的图。
*
* 跟随开着 **且**是群聊 → 用内核仲裁出来的那一位(`currentSpeakerId`);
* 否则就是当前智能体。
*
* ★ 「谁在说话」只能有**一份**判断,背景层从这里取。
*
* ★ 顶栏那个 24dp 头像**故意不用它**:顶栏回答的是"这个对话属于谁",
* 不是"这一轮谁在说" —— 群聊里这两件事不是一回事,混了就会出现
* "名字是小黑、头像是寐眠"。
*/
private fun speakerAgent(vm: AppViewModel): Agent? {
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
// 谁在说话:跟随开着 && 是群聊 → 用**内核仲裁出来的**那一位;否则当前智能体
val who = if (vm.state.settings.followSpeaker && conv?.isGroup == true &&
return if (vm.state.settings.followSpeaker && conv?.isGroup == true &&
vm.currentSpeakerId.isNotBlank()
) {
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId } ?: vm.activeAgent
} else {
vm.activeAgent
}
}
/**
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
*
* ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆(见 [ChatPortrait]),
* 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」,
* 而他要的是整个背景都是这个角色。
*
* ★ 两条硬约束:
* · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住;
* · **图要实心、气泡要半透明** —— 这是用户点名要的一对
* (「立绘不要透明的」+「聊天框半透明」)。反过来做(图淡化、气泡实心)
* 等于两头都不讨好:立绘看不清,气泡也白透。
* 所以可读性交给气泡那边([doubaoBubbleVeil]),这里不淡化。
*
* ★ 立绘用 `ContentScale.Fit` 而不是 `Crop`:角色不能被裁掉半个身子。
* 背景图反过来,必须 `Crop` —— `Fit` 会留出底色,铺不满。
*/
@Composable
private fun ChatBackdrop(vm: AppViewModel) {
val who = speakerAgent(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 = speakerAgent(vm) ?: return
if (who.image.portrait.isNotBlank()) return
Text(
"还没有立绘 · 点这里去传一张",
fontSize = 11.sp,
color = Doubao.Blue,
modifier = Modifier.clickable { vm.openAgentEdit(who) },
)
}
/* ------------------------------ 消息 ------------------------------ */
@@ -698,7 +747,7 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
Box(
Modifier
.clip(RoundedCornerShape(12.dp))
.background(doubaoBubble())
.background(doubaoBubbleMine())
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -717,7 +766,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 },
@@ -827,7 +876,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 +1000,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 +1224,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)

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 @@
"""
"""
HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上。
用的是 http.server.ThreadingHTTPServer + BaseHTTPRequestHandler:
@@ -1850,7 +1850,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 +1921,26 @@ 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()` 里读(上一轮留下的),
# 所以下一轮的发言人自然是接得上的。
auto_continue = bool(body.get('autoContinue'))
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,

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: 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: 453 KiB

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,20 @@ 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` 根本不是主人 |
这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。
> 最后一条是 v2.0.72 修「背景图设置不了」时补上的:用户选的是手机相册里的照片
> (30~55MB),这条链路上有三堵墙,**每一堵单独看都合理**:
> 前端把 55MB 原样 `readBytes` + base64;内核每条接口卡 4MB;异常被 `body()` 吞掉。
> 现在的分工是:前端**先把位图压到 3MB 以内**(`ui/ImagePick.kt`,GIF/SVG 不压,
> 因为缩放会丢动画、栅格化会毁矢量),内核把**上传类**接口的上限统一放到
> `UPLOAD_BODY_LIMIT`(图片 + 四种包导入),并且读不出来时**如实报原因**。
---
## 1. 需求 → 实现对照
@@ -237,14 +248,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 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交),
每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是
@@ -336,6 +336,43 @@ 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()
if fails:
print(f"❌ {len(fails)} 项不合格:")