diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a5594bb..5001494 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 272 - versionName = "2.0.72" + versionCode = 273 + versionName = "2.0.73" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt b/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt index b412024..907a6ac 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt @@ -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) } /** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */ diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index 52608b5..8e1965a 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -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( diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index 9fe6f10..90c1b00 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -1399,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 -> @@ -1630,10 +1650,38 @@ class AppViewModel(val client: KernelClient) : ViewModel() { runChat(t, emptyList()) } - private fun runChat(text: String, files: List) { - 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, 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 @@ -1647,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}" }) } @@ -1657,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) + } } } } @@ -1718,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 -> { // ★ 额度用完不是"出错了",是**一个需要你决定的状态**: diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index 912b5f9..ad63bb3 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -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) diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt index b58ebfd..956516a 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt @@ -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 diff --git a/android/kernel/app.py b/android/kernel/app.py index 64d7ef7..cc8f8c6 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -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, diff --git a/android/kernel/store.py b/android/kernel/store.py index 18decc0..a201b16 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -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 diff --git a/docs/screenshots/chat-backdrop.png b/docs/screenshots/chat-backdrop.png new file mode 100644 index 0000000..e299d40 Binary files /dev/null and b/docs/screenshots/chat-backdrop.png differ diff --git a/docs/screenshots/drawer-split.png b/docs/screenshots/drawer-split.png new file mode 100644 index 0000000..c8041bf Binary files /dev/null and b/docs/screenshots/drawer-split.png differ diff --git a/docs/screenshots/group-after.png b/docs/screenshots/group-after.png new file mode 100644 index 0000000..4bab4ca Binary files /dev/null and b/docs/screenshots/group-after.png differ diff --git a/docs/screenshots/group-before.png b/docs/screenshots/group-before.png new file mode 100644 index 0000000..3e00ab6 Binary files /dev/null and b/docs/screenshots/group-before.png differ diff --git a/docs/screenshots/now1.png b/docs/screenshots/now1.png new file mode 100644 index 0000000..9120caf Binary files /dev/null and b/docs/screenshots/now1.png differ diff --git a/docs/screenshots/now2.png b/docs/screenshots/now2.png new file mode 100644 index 0000000..d60020f Binary files /dev/null and b/docs/screenshots/now2.png differ diff --git a/docs/screenshots/now3.png b/docs/screenshots/now3.png new file mode 100644 index 0000000..2ad1d8a Binary files /dev/null and b/docs/screenshots/now3.png differ diff --git a/docs/智能体系统.md b/docs/智能体系统.md index 4913395..52dc8fd 100644 --- a/docs/智能体系统.md +++ b/docs/智能体系统.md @@ -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`(聊天页整屏立绘/背景层,跟着说话者换) | ### 两份"窗口"的命名纪律(需求点名要求,别混) @@ -47,6 +47,7 @@ v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿, | **请求体上限按最小的调用方给** | 手机照片 28.9MB → base64 38MB,撞上 `read_json_body` 默认的 4MB;异常又被吞成空 dict,最后报的是**「不认识的外观槽位」** | 上限按**最大**的用;吞异常等于把原因丢掉 | | **探针绕过了真正出问题的那一层** | 第 22 节直接调 `_set_asset`,而卡住的是 `handle()` 里的 `body()` → 探针全绿,真机全挂 | 探针**必须走生产同一条调用路径** | | **换图时"自己删自己"** | 落盘名是 `<槽位>-<原始文件名>`;同一张图传第二次时新旧同路径 → 写完新的立刻被当旧的删掉,`image` 里留下**指向不存在文件**的路径,目录空着界面回退默认图 | 删旧文件前先比路径;"先写后删"的顺序里藏着这个坑 | +| **两条各自正确的逻辑叠在一起** | 群聊仲裁把 `agentId` 换成「本轮发言人」,紧接着的会话隔离又拿它比「会话主人」→ 群里每换一个人说话就**另起一个会话**,用户 @ 谁就跳到谁的对话去 | 一条规则搬到新场景时要重问一遍"它还成立吗"——群聊里 `agentId` 根本不是主人 | 这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。 diff --git a/scripts/probe-group-chat.py b/scripts/probe-group-chat.py index bd39d2e..86d82b3 100644 --- a/scripts/probe-group-chat.py +++ b/scripts/probe-group-chat.py @@ -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)} 项不合格:")