diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 5001494..4869b39 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 273 - versionName = "2.0.73" + versionCode = 274 + versionName = "2.0.74" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 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 90c1b00..afe0d4e 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 @@ -1402,11 +1402,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() { /** * 这一轮 AI 是不是用 `pass_turn` 把话交给了别人(群聊才有)→ 跑完自动替他续一轮。 * + * ★ 用 [AtomicBoolean] 而不是普通 `var`:置位发生在 + * `client.chat` 的**回调线程**(IO)上,读取发生在 `finally`(协程)里 —— + * 两边不是一个线程。用普通变量的话,这个"续不续轮"的判断就是在赌调度, + * 表现是"有时候能聊起来、有时候不能"(比稳定不工作更难查)。 + * * ★ 没有它的话,群聊里的"AI 互相说话"就只是**半截**: * A 把话让给 B,然后这一轮就结束了,B 永远没开口 —— - * 用户得再发一条消息才看得到 B 说话(用户要的是"他们自己聊起来")。 + * 用户得再发一条消息才看得到 B 说话。 */ - private var handoffPending = false + private val handoffDone = AtomicBoolean(false) /** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */ private var autoRounds = 0 @@ -1673,15 +1678,91 @@ class AppViewModel(val client: KernelClient) : ViewModel() { showHint("已停止") } - private fun runChat(text: String, files: List, auto: Boolean = false) { + /** + * 让群里的成员**轮流对话**(用户要的「智能体可以和群聊中另外一个智能体对话」)。 + * + * ★★ 为什么不是"等 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 = emptyList() + + private fun runChat(text: String, files: List, 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 - handoffPending = false + handoffDone.set(false) val cancel = AtomicBoolean(false) chatJob = cancel @@ -1698,6 +1779,8 @@ class AppViewModel(val client: KernelClient) : ViewModel() { onEvent = { event -> onStreamEvent(event) }, // 自动续的那几轮不带用户消息(内核据此不追加) autoContinue = auto, + // 「让他们聊」时**直接指定**这一轮谁说话,不指望 AI 自己移交 + forceSpeaker = forceSpeaker, ) } } catch (e: Exception) { @@ -1716,12 +1799,26 @@ class AppViewModel(val client: KernelClient) : ViewModel() { // 用户随时可以点「停止」打断(`cancel.get()`), // 也随时可以直接发消息把话题拉回来。 val conv = state.conversations.firstOrNull { it.id == activeConversationId } - if (handoffPending && conv?.isGroup == true && - !cancel.get() && autoRounds < autoRoundCap - ) { - handoffPending = false + 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() } } } @@ -1729,6 +1826,14 @@ class AppViewModel(val client: KernelClient) : ViewModel() { /** 事件回调可能在 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) } @@ -1784,11 +1889,17 @@ 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 + } + // ★ 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 -> { // ★ 额度用完不是"出错了",是**一个需要你决定的状态**: 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 ad63bb3..7967f72 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 @@ -613,35 +613,37 @@ private fun HeroText(greeting: String) { * 两处各写一个数字的话,将来改一处必漏另一处。) */ /** - * 当前该显示**谁**的图。 + * 聊天页整屏背景/立绘的**主人**。 * - * 跟随开着 **且**是群聊 → 用内核仲裁出来的那一位(`currentSpeakerId`); - * 否则就是当前智能体。 + * ★★ 就是**当前这条对话的智能体**(`activeAgent`)—— 用户的原话: + * 「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。 * - * ★ 「谁在说话」只能有**一份**判断,背景层从这里取。 + * 我一开始做成了"跟着当前发言者换",那是错的: + * 聊天页的背景表达的是**这个场景是谁的**(和顶栏那个名字是一回事), + * 而**不是**"这一轮谁在开口"。群里两个人一来一回时背景跟着闪, + * 既晃眼又和顶栏的名字对不上。 * - * ★ 顶栏那个 24dp 头像**故意不用它**:顶栏回答的是"这个对话属于谁", - * 不是"这一轮谁在说" —— 群聊里这两件事不是一回事,混了就会出现 - * "名字是小黑、头像是寐眠"。 + * "谁在说话"是**每条消息**自己的事 —— 那个用 `msg.agentId` + * (见 [SpeakerTag] 和朗读挑音色那两处),和背景不是一回事。 + * + * ★ 所以这里和顶栏用的是同一个来源,天然一致,不会再出现 + * "名字是小黑、背景是寐眠"。 */ -private fun speakerAgent(vm: AppViewModel): Agent? { - val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId } - 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 - } -} +private fun backdropAgent(vm: AppViewModel): Agent? = vm.activeAgent /** * 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。 * - * ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆(见 [ChatPortrait]), + * ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆, * 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」, * 而他要的是整个背景都是这个角色。 * + * ★★ 显示的是**当前对话的智能体**(`activeAgent`),不是"这一轮谁在说"。 + * 用户澄清过:「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。 + * 背景表达的是**这个场景是谁的**(和顶栏那个名字同一件事); + * 群聊里两个人一来一回时背景跟着闪,既晃眼又和顶栏对不上。 + * "谁在说话"是**每条消息**自己的事,用 `msg.agentId`(见 [SpeakerTag])。 + * * ★ 两条硬约束: * · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住; * · **图要实心、气泡要半透明** —— 这是用户点名要的一对 @@ -654,7 +656,7 @@ private fun speakerAgent(vm: AppViewModel): Agent? { */ @Composable private fun ChatBackdrop(vm: AppViewModel) { - val who = speakerAgent(vm) + val who = backdropAgent(vm) val back = who?.image?.back.orEmpty() val art = who?.image?.portrait.orEmpty() if (back.isBlank() && art.isBlank()) return @@ -688,7 +690,7 @@ private fun ChatBackdrop(vm: AppViewModel) { */ @Composable private fun PortraitHint(vm: AppViewModel) { - val who = speakerAgent(vm) ?: return + val who = backdropAgent(vm) ?: return if (who.image.portrait.isNotBlank()) return Text( "还没有立绘 · 点这里去传一张", @@ -700,6 +702,41 @@ private fun PortraitHint(vm: AppViewModel) { /* ------------------------------ 消息 ------------------------------ */ +/** + * 气泡上方那行**小字:这条是谁说的**。 + * + * ★ 只在**群聊**显示(用户要求:「对话前面写明是谁在说话」)。 + * 单聊里只有一个人,每条都标一遍就是噪音 —— 那个名字顶栏已经有了。 + * + * ★ 名字从 `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) { @@ -743,6 +780,7 @@ 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 @@ -792,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() @@ -1360,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,界面以前收了但从不显示 —— diff --git a/android/kernel/agent_tools.py b/android/kernel/agent_tools.py index 0c94687..76d98da 100644 --- a/android/kernel/agent_tools.py +++ b/android/kernel/agent_tools.py @@ -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}, } diff --git a/android/kernel/app.py b/android/kernel/app.py index cc8f8c6..6bfd854 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -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')) @@ -1931,7 +1955,10 @@ class KernelHandler(BaseHTTPRequestHandler): # 而且模型会以为用户又说话了。移交状态本来就从 # `tools_runtime.handoff_state()` 里读(上一轮留下的), # 所以下一轮的发言人自然是接得上的。 - auto_continue = bool(body.get('autoContinue')) + # ★ 判据必须和 `_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', @@ -1978,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): diff --git a/android/kernel/group_chat.py b/android/kernel/group_chat.py index 8f713fb..3ce8dc7 100644 --- a/android/kernel/group_chat.py +++ b/android/kernel/group_chat.py @@ -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', diff --git a/docs/screenshots/ai-talk.png b/docs/screenshots/ai-talk.png new file mode 100644 index 0000000..9879270 Binary files /dev/null and b/docs/screenshots/ai-talk.png differ diff --git a/docs/screenshots/group-ai-chat.png b/docs/screenshots/group-ai-chat.png new file mode 100644 index 0000000..c6542b2 Binary files /dev/null and b/docs/screenshots/group-ai-chat.png differ diff --git a/docs/screenshots/mention-switch.png b/docs/screenshots/mention-switch.png new file mode 100644 index 0000000..3c4011b Binary files /dev/null and b/docs/screenshots/mention-switch.png differ diff --git a/docs/智能体系统.md b/docs/智能体系统.md index 8abde3a..d6762d1 100644 --- a/docs/智能体系统.md +++ b/docs/智能体系统.md @@ -49,6 +49,7 @@ v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿, | **换图时"自己删自己"** | 落盘名是 `<槽位>-<原始文件名>`;同一张图传第二次时新旧同路径 → 写完新的立刻被当旧的删掉,`image` 里留下**指向不存在文件**的路径,目录空着界面回退默认图 | 删旧文件前先比路径;"先写后删"的顺序里藏着这个坑 | | **两条各自正确的逻辑叠在一起** | 群聊仲裁把 `agentId` 换成「本轮发言人」,紧接着的会话隔离又拿它比「会话主人」→ 群里每换一个人说话就**另起一个会话**,用户 @ 谁就跳到谁的对话去 | 一条规则搬到新场景时要重问一遍"它还成立吗"——群聊里 `agentId` 根本不是主人 | | **能力全都在,缺最后一个按钮** | `chatJob`(取消句柄)建好了、内核从 HTTP 到 `agent_loop` 一路支持 `cancelled`、ViewModel 也把 `AtomicBoolean` 传下去了 —— 但**没有任何界面调它**,用户只能干等它说完 | 一条链路要数**两端**:内核发得出 + 界面点得到。只做前半截,测的时候还全是绿的 | +| **顺序错了:先仲裁、后落库** | 群聊仲裁要读「用户这一轮 @ 了谁」,而本次消息**还没写进库** → 读到的是**上一次**的话 → 我 @ 寐眠,回答的却是小黑(背景/标签/音色三处全对不上) | 读「刚刚发生的事」之前先问:**它现在在库里了吗** | 这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。 diff --git a/scripts/probe-group-chat.py b/scripts/probe-group-chat.py index 86d82b3..dc302d7 100644 --- a/scripts/probe-group-chat.py +++ b/scripts/probe-group-chat.py @@ -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(旧探针是假通过)===") @@ -373,6 +375,133 @@ def main(): "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)} 项不合格:")