Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 31c62fafc2 | |||
| 7498810c70 | |||
| 57a9ff4ea1 | |||
| ab063d0674 | |||
| 3d5c02e7a9 |
@@ -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 = 274
|
||||
versionName = "2.0.74"
|
||||
versionCode = 280
|
||||
versionName = "2.0.80"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -29,6 +29,7 @@ import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应;AgentSelect 是需求 v1.1 新增的选择页) */
|
||||
enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Resources, Terminal, Meetings }
|
||||
@@ -1413,9 +1414,84 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
*/
|
||||
private val handoffDone = AtomicBoolean(false)
|
||||
|
||||
/**
|
||||
* 这一轮 AI 把话交给了**谁**(id / 名字)。
|
||||
*
|
||||
* ★ 用 `AtomicReference` 的理由和 [handoffDone] 一样:写在 `client.chat`
|
||||
* 的**回调线程**(IO)上,而 `runChat` 的 `finally` 紧接着就要读它 ——
|
||||
* 普通 `var` 的话,"交给谁"会随调度时有时无,表现是手动模式那个
|
||||
* 「让他说」按钮**有时候不出来**。
|
||||
*/
|
||||
private val handoffToRef = AtomicReference("")
|
||||
private val handoffFromRef = AtomicReference("")
|
||||
|
||||
/**
|
||||
* 这一轮 AI 把话交给了**一串人**(`talk_to` 多目标)。
|
||||
*
|
||||
* ★ 用 `AtomicReference` 的理由同 [handoffDone]:写在 IO 回调线程上、
|
||||
* `finally` 里马上要读。
|
||||
*/
|
||||
private val handoffQueueRef = AtomicReference<List<String>>(emptyList())
|
||||
|
||||
/**
|
||||
* 待接话的人(队列)。
|
||||
*
|
||||
* ★★ 用户要求:「talk_to 支持多个目标(目标智能体挨个回话)」。
|
||||
* 所以一轮跑完如果还有没接过话的人,就摆出"下一个是他",
|
||||
* 自动模式直接接着跑、手动模式把按钮摆出来等用户点。
|
||||
*/
|
||||
private val handoffQueue = ArrayDeque<String>()
|
||||
|
||||
/** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */
|
||||
private var autoRounds = 0
|
||||
|
||||
/**
|
||||
* 待用户决定的移交:AI 把话交给了谁。
|
||||
*
|
||||
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
|
||||
*
|
||||
* 所以默认**不自动续** —— 一轮跑完如果 AI 交了话,
|
||||
* 聊天页底下出现一条「X 把话交给了 Y」+「让他说」「停在这」,
|
||||
* **由用户决定**。设置里开了「AI 对聊自动模式」才跳过这一步。
|
||||
*
|
||||
* 这也顺带解决了烧钱:默认不会自己一直聊下去。
|
||||
*/
|
||||
var pendingHandoffName by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 是谁交出去的(显示用) */
|
||||
var pendingHandoffFromName by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 交给的那个人(点「让他说」时用) */
|
||||
private var pendingHandoffTo = ""
|
||||
|
||||
/** 用户点「让他说」—— 接着让下一个人开口 */
|
||||
fun continueHandoff() {
|
||||
val to = pendingHandoffTo
|
||||
if (to.isBlank()) return
|
||||
pendingHandoffTo = ""
|
||||
pendingHandoffName = ""
|
||||
pendingHandoffFromName = ""
|
||||
autoRounds++
|
||||
runChat("", emptyList(), auto = true, forceSpeaker = to)
|
||||
}
|
||||
|
||||
/** 用户点「停在这」—— 到此为止,不再往下递 */
|
||||
fun stopHandoff() {
|
||||
val who = pendingHandoffName
|
||||
pendingHandoffTo = ""
|
||||
pendingHandoffName = ""
|
||||
pendingHandoffFromName = ""
|
||||
// ★ 队列也一起清掉:用户说停就是停,别过一会儿又冒出来一个"下一个"
|
||||
handoffQueue.clear()
|
||||
handoffDone.set(false)
|
||||
if (who.isNotBlank()) showHint("停在这里了($who 没接)")
|
||||
}
|
||||
|
||||
/** AI 对聊的自动模式(不用用户确认)。设置里那个开关 */
|
||||
fun setAiTalkAuto(on: Boolean) = saveSettings(mapOf("aiTalkAuto" to on))
|
||||
|
||||
/**
|
||||
* 一次自动对聊最多续几轮。
|
||||
*
|
||||
@@ -1560,10 +1636,36 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
/* ------------------------------ 会话 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 重新拉当前会话的消息列表(只重载消息,不切屏、不动别的状态)。
|
||||
*
|
||||
* ★★ 为什么需要它(用户报的「talk_to 看不到智能体说啥」):
|
||||
* 工具是在**轮中**往对话里写东西的 —— `talk_to` 就是:它把
|
||||
* 「我对你说的话」直接落库了。而本地这份 `messages` 只在流式里追增量,
|
||||
* 根本不知道库里多了几条,于是**那句话说出去就看不见**,
|
||||
* 要退出去重进这条对话才看得到。
|
||||
*
|
||||
* ★ 不用 `openConversation`:它会切屏、清空、还重读一次 meta ——
|
||||
* 刚跑完一轮就调它太重,屏幕上还会闪一下。
|
||||
*/
|
||||
private suspend fun reloadMessages() {
|
||||
val id = activeConversationId.ifBlank { "c_main" }
|
||||
val list = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversation(id) }
|
||||
}.getOrNull() ?: return
|
||||
// 流式期间本地插的那条 pending 占位不在库里,重载正好换成落库的版本
|
||||
messages.clear()
|
||||
messages.addAll(list)
|
||||
}
|
||||
|
||||
fun openConversation(id: String) {
|
||||
activeConversationId = id
|
||||
drawerOpen = false
|
||||
screen = Screen.Chat
|
||||
// ★ 换会话就把「上一轮谁在说」清掉 —— 不清的话,从群 A 切到群 B,
|
||||
// B 的顶栏和背景会显示**A 那个发言人**(用户报的"对不上"里就有这一种)。
|
||||
currentSpeakerId = ""
|
||||
speakerNote = ""
|
||||
viewModelScope.launch {
|
||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||
messages.clear()
|
||||
@@ -1695,20 +1797,24 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
/**
|
||||
* 点名(点群聊底部的 `@某人`)。
|
||||
*
|
||||
* ★ 除了把 `@名字 ` 插进草稿,还要**立即把展示切到那个人** ——
|
||||
* 用户的要求原话是「@ 的时候立即切换」:
|
||||
* 点了谁,立绘/背景马上就是他,而不是等到回复回来才换
|
||||
* (等内核跑完那一轮再换,中间那段空白看着像"点了没反应")。
|
||||
* ★ 只做两件事:把 `@名字 ` 插进草稿、把「让他们聊」掐掉
|
||||
* (用户点了名 = 他要接管发言权了)。
|
||||
*
|
||||
* ★ 顺手把「让他们聊」掐掉:用户点名 = 他要接管发言权了。
|
||||
* ★★ **不碰 `currentSpeakerId`** —— 这是上一版踩的坑。
|
||||
* 用户的原话:「背景是根据当前对话来的,**不是让你 @ 谁就换哪个背景**」。
|
||||
* 点一下按钮就把顶栏和背景切成那个人,但消息根本没发出去、
|
||||
* 对方也还没开口,于是屏幕上出现"顶栏是寐眠、最后一条消息是小黑"——
|
||||
* 正是他截图里指出来的那种不对。
|
||||
*
|
||||
* 现在改成:**发出去、内核仲裁完、`speaker` 事件回来才切**。
|
||||
* 那个事件是轮前的,所以观感上依然是"一点就换",但换的是
|
||||
* **真正要开口的那个人**,名副其实。
|
||||
*/
|
||||
fun mentionAgent(agentId: String, name: String) {
|
||||
fun mentionAgent(name: String) {
|
||||
aiTalkLeft = 0
|
||||
aiTalkTurn = 0
|
||||
aiTalkPair = emptyList()
|
||||
draft = draft + "@$name "
|
||||
currentSpeakerId = agentId
|
||||
speakerNote = ""
|
||||
}
|
||||
|
||||
fun startAiTalk(rounds: Int = 4) {
|
||||
@@ -1763,6 +1869,14 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||
streaming = true
|
||||
handoffDone.set(false)
|
||||
handoffToRef.set("")
|
||||
handoffFromRef.set("")
|
||||
// 用户自己发消息 = 他要接手了,把待决的那个"要不要让他说"收起来
|
||||
if (!auto) {
|
||||
pendingHandoffTo = ""
|
||||
pendingHandoffName = ""
|
||||
pendingHandoffFromName = ""
|
||||
}
|
||||
|
||||
val cancel = AtomicBoolean(false)
|
||||
chatJob = cancel
|
||||
@@ -1791,6 +1905,9 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
chatJob = null
|
||||
patchLast { it.copy(pending = false) }
|
||||
refresh()
|
||||
// ★ 重载消息:工具可能在**轮中**往对话里写过东西
|
||||
// (`talk_to` 就是)—— 不重载的话那句话根本看不见
|
||||
reloadMessages()
|
||||
|
||||
// ★★ 群聊里 AI 把话交给了别人 → 自动替他续一轮。
|
||||
//
|
||||
@@ -1802,23 +1919,54 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
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` 交的话 —— 也接着让它说出来
|
||||
} else if (canContinue && handoffDone.get()) {
|
||||
// ② AI 自己用 talk_to / pass_turn 把话交给了别人
|
||||
handoffDone.set(false)
|
||||
autoRounds++
|
||||
runChat("", emptyList(), auto = true)
|
||||
if (state.settings.aiTalkAuto) {
|
||||
// 自动模式:不用用户确认,直接接着让他说
|
||||
if (autoRounds < autoRoundCap) {
|
||||
autoRounds++
|
||||
// ★ 把多目标的队列也带上:下一轮跑完 `finally` 会继续消费
|
||||
handoffQueue.clear()
|
||||
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
|
||||
runChat("", emptyList(), auto = true)
|
||||
}
|
||||
} else {
|
||||
// ★ 手动模式(默认):**摆出两个按钮等用户决定**
|
||||
// —— 用户要求「可以选择传递和停止」
|
||||
pendingHandoffTo = handoffToRef.get()
|
||||
pendingHandoffName = state.agents
|
||||
.firstOrNull { it.id == handoffToRef.get() }?.name.orEmpty()
|
||||
pendingHandoffFromName = handoffFromRef.get()
|
||||
// ★ 多目标:剩下的排进队列,`continueHandoff` 之后由
|
||||
// 这次 `runChat` 的 finally 接着摆出来("挨个回话")
|
||||
handoffQueue.clear()
|
||||
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
|
||||
}
|
||||
} else if (canContinue && handoffQueue.isNotEmpty()) {
|
||||
// ★★ 队列里还有没接过话的人(`talk_to` 多目标)——
|
||||
// 用户要求「目标智能体挨个回话」,所以接着摆下一个。
|
||||
val next = handoffQueue.removeFirst()
|
||||
val nextName = state.agents.firstOrNull { it.id == next }?.name.orEmpty()
|
||||
if (state.settings.aiTalkAuto) {
|
||||
runChat("", emptyList(), auto = true, forceSpeaker = next)
|
||||
} else {
|
||||
pendingHandoffTo = next
|
||||
pendingHandoffName = nextName
|
||||
pendingHandoffFromName = handoffFromRef.get()
|
||||
}
|
||||
} else {
|
||||
// 收尾:清掉自动对聊的计数,免得下次发消息又自己续上
|
||||
aiTalkLeft = 0
|
||||
aiTalkTurn = 0
|
||||
aiTalkPair = emptyList()
|
||||
handoffQueue.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1832,7 +1980,15 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
// `finally` 紧接着就要读这个标志来决定续不续轮。
|
||||
// 放进 launch 里就变成异步 —— 会和 finally 抢,抢输了那一轮就不续,
|
||||
// 表现是"两个 AI 有时候能聊、有时候聊不起来"。
|
||||
if (event is StreamEvent.Handoff) handoffDone.set(true)
|
||||
if (event is StreamEvent.Handoff) {
|
||||
handoffDone.set(true)
|
||||
handoffToRef.set(event.to)
|
||||
// 多目标:剩下的那些也记下来,`finally` 里逐个消费
|
||||
handoffQueueRef.set(event.queue)
|
||||
handoffFromRef.set(
|
||||
state.agents.firstOrNull { it.id == event.from }?.name.orEmpty()
|
||||
)
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
when (event) {
|
||||
@@ -1889,6 +2045,21 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
is StreamEvent.Speaker -> {
|
||||
currentSpeakerId = event.agentId
|
||||
speakerNote = event.note
|
||||
// ★★ 把发言人写进**这一条正在生成的消息**。
|
||||
//
|
||||
// 这条消息是流式期间客户端**自己建的**
|
||||
// (`runChat` 里 `ChatMessage(role="assistant", pending=true)`),
|
||||
// 当时还不知道谁会说,所以 `agentId` 是空的 ——
|
||||
// 而它**不会**跟着 `refresh()` 更新(那个只换 `state`,
|
||||
// 不动本地的 `messages`)。
|
||||
//
|
||||
// 于是:内核库里存的 `agentId` 明明是对的(寐眠),
|
||||
// 界面上这条的却是空 → 名字标签退回"当前对话的主人"
|
||||
// (小黑)、朗读也退回全局音色(还是小黑)。
|
||||
// 用户看到的就是「@ 了寐眠、标签和声音却都是小黑」。
|
||||
if (event.agentId.isNotBlank()) {
|
||||
patchLast { if (it.agentId.isBlank()) it.copy(agentId = event.agentId) else it }
|
||||
}
|
||||
}
|
||||
// ★ AI 轮中把话交给了别人 → 这一轮跑完要**自动替他续一轮**,
|
||||
// 不然就是"用户说一句 → A 让给 B → B 永远没开口"
|
||||
|
||||
@@ -267,7 +267,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||
// ★ 顶栏的名字和**背景用的是同一个人**(`backdropAgent`)——
|
||||
// 用户的原话是「还是没换标题和背景呀」:寐眠在说话,
|
||||
// 顶栏和背景就该都是寐眠。两处各取各的必然对不上。
|
||||
val shown = backdropAgent(vm)
|
||||
ChatHeader(vm, shown?.name ?: (agent?.name ?: "豆包"), speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
|
||||
@@ -373,6 +377,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
}
|
||||
}
|
||||
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
|
||||
//
|
||||
// ★★ 顺序:先「要不要让他接着说」,再点名条 ——
|
||||
// 前者的决策更靠前(它决定这一轮还继不继续),
|
||||
// 而且它只在有待决移交时才出现。
|
||||
HandoffBar(vm)
|
||||
GroupQuickBar(vm)
|
||||
SessionUsageBar(vm)
|
||||
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
|
||||
@@ -415,8 +424,18 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
// 内核那道拦截是权威,但**界面上也要拦一道** ——
|
||||
// 让用户敲完一整句话、点发送、再被拒绝,是最差的体验。
|
||||
// 提示条点一下直达记忆页的情绪区(那就是复活入口)。
|
||||
//
|
||||
// ★★ 但**群聊不锁输入框**:死了一个,群里还有别人能接话
|
||||
// (内核的 `group_chat.resolve` 会把死人跳过、换下一个人)。
|
||||
// 整条锁掉的话,用户只能干看着一个群不能用 ——
|
||||
// 用户报的「角色死亡输入框怎么不能用了」就是这个。
|
||||
// 群聊里只留一条提示,输入框照给。
|
||||
val deadAgent = vm.activeAgent
|
||||
if (deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true) {
|
||||
val dead = deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true
|
||||
val convNow = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
val groupNow = convNow?.isGroup == true
|
||||
if (dead && !groupNow) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -427,7 +446,7 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"「${deadAgent.name}」已经死亡,不能对话。",
|
||||
"「${deadAgent?.name}」已经死亡,不能对话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier.weight(1f),
|
||||
@@ -439,11 +458,23 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { vm.openMemories(deadAgent.id) }
|
||||
.clickable { deadAgent?.let { vm.openMemories(it.id) } }
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if (dead && groupNow) {
|
||||
// 群聊:只提示,**不拦**。被点名的人死了的话,
|
||||
// 内核会换下一个人接(不再"回主智能体",群里没有主人)
|
||||
Text(
|
||||
"「${deadAgent?.name}」已经死亡 —— 群里其他人还能接话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 14.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
@@ -496,7 +527,8 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
) {
|
||||
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
|
||||
// 这里 path 为空就还是原来的图标)
|
||||
val art = vm.activeAgent?.image?.portrait.orEmpty()
|
||||
// ★ 跟**同一个人**:名字是寐眠、头像却是小黑,用户一眼就看出不对
|
||||
val art = backdropAgent(vm)?.image?.portrait.orEmpty()
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
@@ -613,23 +645,31 @@ private fun HeroText(greeting: String) {
|
||||
* 两处各写一个数字的话,将来改一处必漏另一处。)
|
||||
*/
|
||||
/**
|
||||
* 聊天页整屏背景/立绘的**主人**。
|
||||
* 顶栏和背景该显示**谁** —— **当前正在说话的那个人**。
|
||||
*
|
||||
* ★★ 就是**当前这条对话的智能体**(`activeAgent`)—— 用户的原话:
|
||||
* 「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
|
||||
* ★★ 用户的原话:「还是没换标题和背景呀」。
|
||||
*
|
||||
* 我一开始做成了"跟着当前发言者换",那是错的:
|
||||
* 聊天页的背景表达的是**这个场景是谁的**(和顶栏那个名字是一回事),
|
||||
* 而**不是**"这一轮谁在开口"。群里两个人一来一回时背景跟着闪,
|
||||
* 既晃眼又和顶栏的名字对不上。
|
||||
* 我上一版理解成「跟当前对话的主人走」,那是错的 ——
|
||||
* 他要的是**寐眠说话时,顶栏和背景都是寐眠**。
|
||||
*
|
||||
* "谁在说话"是**每条消息**自己的事 —— 那个用 `msg.agentId`
|
||||
* (见 [SpeakerTag] 和朗读挑音色那两处),和背景不是一回事。
|
||||
* 「不是让你 @ 谁就换哪个背景」那句,意思是**不要光点一下 @ 按钮
|
||||
* 就提前换**;要跟着**真实的发言者**。内核每轮都 emit 一个
|
||||
* `speaker` 事件(群聊里就是仲裁结果),跟着它走既"立即"又"名副其实"。
|
||||
*
|
||||
* ★ 所以这里和顶栏用的是同一个来源,天然一致,不会再出现
|
||||
* "名字是小黑、背景是寐眠"。
|
||||
* ★ 只在**群聊**里用 `currentSpeakerId`:单聊时它可能还是上一轮群里
|
||||
* 留下的值,会把单聊的顶栏带跑偏。单聊就认会话主人。
|
||||
*
|
||||
* ★ 顶栏、背景、【朗读音色】三处都从这里/`msg.agentId` 取,
|
||||
* 保证同一条消息上的名字、图、声音是**同一个人**。
|
||||
*/
|
||||
private fun backdropAgent(vm: AppViewModel): Agent? = vm.activeAgent
|
||||
private fun backdropAgent(vm: AppViewModel): Agent? {
|
||||
val convId = vm.activeConversationId.ifBlank { "c_main" }
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == convId }
|
||||
if (conv?.isGroup == true && vm.currentSpeakerId.isNotBlank()) {
|
||||
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId }?.let { return it }
|
||||
}
|
||||
return vm.state.agents.firstOrNull { it.id == conv?.agentId.orEmpty() } ?: vm.activeAgent
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
|
||||
@@ -1373,6 +1413,44 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「要不要让他接着说」——
|
||||
* AI 用 `talk_to` / `pass_turn` 把话交给别人之后,这里摆两个按钮。
|
||||
*
|
||||
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
|
||||
*
|
||||
* 所以默认(手动)就**停在这儿等用户点**:
|
||||
* · 「让他说」= 继续把这一轮交出去;
|
||||
* · 「停在这」= 到此为止。
|
||||
* 设置里开了「AI 对聊自动模式」就不出现这条,直接接着跑。
|
||||
*
|
||||
* ★ 顺带解决了烧钱:默认不会自己一直聊下去。
|
||||
* ★ 位置在输入框正上方、点名条**上面**:这是"接着聊还是打住"的决策现场。
|
||||
*/
|
||||
@Composable
|
||||
private fun HandoffBar(vm: AppViewModel) {
|
||||
if (vm.pendingHandoffName.isBlank()) return
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"${vm.pendingHandoffFromName.ifBlank { "它" }} 把话交给了 ${vm.pendingHandoffName}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DoubaoPill(text = "让他说", onClick = { vm.continueHandoff() })
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("停在这") { vm.stopHandoff() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 群聊的成员快捷条(v1.2 §3.9)。
|
||||
*
|
||||
@@ -1398,12 +1476,12 @@ private fun GroupQuickBar(vm: AppViewModel) {
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// 主智能体标一下:没人被 @ 时由它接话,用户得知道"不点名也有话说"
|
||||
for ((i, pair) in members.withIndex()) {
|
||||
val label = if (i == 0) "${pair.second}(主)" else pair.second
|
||||
// 点名除了插草稿,还要**立即**把立绘/背景切过去
|
||||
// (用户要求:「@ 的时候立即切换」)
|
||||
DoubaoPill(text = "@$label", onClick = { vm.mentionAgent(pair.first, pair.second) })
|
||||
// 点名条:**不标"(主)"** —— 用户要求「群聊去掉主人设定」,
|
||||
// 群里没有老大,没人被 @ 时按顺序轮(kernel 的 group_chat.rotate_next)
|
||||
for (pair in members) {
|
||||
// 只插草稿 —— **不碰顶栏/背景**。那两处等内核仲裁完
|
||||
// (`speaker` 事件)才切,不然会"点了还没发就换了人"
|
||||
DoubaoPill(text = "@${pair.second}", onClick = { vm.mentionAgent(pair.second) })
|
||||
}
|
||||
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
|
||||
//
|
||||
|
||||
@@ -57,7 +57,6 @@ fun GroupMembersScreen(
|
||||
) {
|
||||
val conv: Conversation? = vm.state.conversations.firstOrNull { it.id == conversationId }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
val hostId = conv?.participants?.firstOrNull().orEmpty()
|
||||
|
||||
FullScreen(
|
||||
title = "群成员",
|
||||
@@ -70,11 +69,29 @@ fun GroupMembersScreen(
|
||||
// ---- 加人(就地展开,不再弹一层 —— 弹窗压弹窗是手机上的灾难)----
|
||||
if (adding) {
|
||||
val inGroup = conv?.participants?.toSet() ?: emptySet()
|
||||
val candidates = vm.state.agents.filter { it.id !in inGroup }
|
||||
// ★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
//
|
||||
// 群聊上下文里有 <worldview> 段、共享记忆也按世界观分空间 ——
|
||||
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
|
||||
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
|
||||
// 让人点了才被告知"加不进去"是最差的体验。
|
||||
//
|
||||
// ★ **未绑世界观的放行**:它没有设定会串,和谁都合得来
|
||||
// (用户报的「还是加不了人」,其中"黑化豆包"就是未绑的)。
|
||||
val hostWorldview = vm.state.agents
|
||||
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
|
||||
val sameWorldview = vm.state.agents.filter {
|
||||
it.worldviewId.orEmpty().isBlank() || it.worldviewId.orEmpty() == hostWorldview
|
||||
}
|
||||
val candidates = sameWorldview.filter { it.id !in inGroup }
|
||||
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
|
||||
SectionLabel("拉谁进来")
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint("所有智能体都在群里了。")
|
||||
Hint(
|
||||
if (blocked > 0) "没有可以拉的人了。"
|
||||
else "所有能拉的人都在群里了。",
|
||||
)
|
||||
} else {
|
||||
for (a in candidates) {
|
||||
Row(
|
||||
@@ -83,7 +100,10 @@ fun GroupMembersScreen(
|
||||
// 用的(会新建群聊);已经有成员了就走 `addMember`,
|
||||
// 不能混 —— 混了会把当前会话换掉,用户会一头雾水。
|
||||
if (inGroup.isEmpty()) vm.makeGroup(a.id) else vm.addMember(a.id)
|
||||
adding = false
|
||||
// ★★ 加完**不收起**(原来这里 `adding = false`)。
|
||||
// 收起的话,用户加了一个就得再点一次「加人」才能加下一个,
|
||||
// 体感就是"群聊只能拉两个"(真机反馈)。
|
||||
// 刷新后 `candidates` 会少一个,接着点就行。
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -92,7 +112,32 @@ fun GroupMembersScreen(
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Hint("拉人无条件:会话是你的,想拉谁就拉谁。只能拉同世界观的。")
|
||||
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
|
||||
}
|
||||
// ★★ 被世界观挡下的**也列出来**,并说清原因。
|
||||
//
|
||||
// 不列的话用户只看到"某些智能体不见了",以为功能坏了 ——
|
||||
// 他报的「还是加不了人」有一半是这种感觉。
|
||||
val blockedAgents = vm.state.agents.filter { it.id !in inGroup && it !in sameWorldview }
|
||||
if (blockedAgents.isNotEmpty()) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"这些绑的是别的世界观,拉进来会串设定(两套背景、共享记忆也会混):",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
for (a in blockedAgents) {
|
||||
Text(
|
||||
"· ${a.name}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(start = 6.dp, top = 2.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("想拉它们:先去它们的编辑页绑成这个世界观(或者另开一个群)。")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
@@ -107,7 +152,6 @@ fun GroupMembersScreen(
|
||||
Card {
|
||||
for ((i, id) in conv.participants.withIndex()) {
|
||||
val a: Agent? = vm.state.agents.firstOrNull { it.id == id }
|
||||
val isHost = id == hostId
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -115,31 +159,26 @@ fun GroupMembersScreen(
|
||||
AgentFace(a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (isHost) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
HostBadge()
|
||||
}
|
||||
}
|
||||
Text(
|
||||
if (isHost) "没人被 @ 的时候由它接话"
|
||||
else "第 ${i + 1} 个进群的",
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
// ★ 这里原来标了「主」徽章 + "没人被 @ 的时候由它接话"。
|
||||
// 用户要求「群聊去掉主人设定」—— 群里没有老大,
|
||||
// 没人被 @ 时**按顺序轮**(见 kernel/group_chat.rotate_next)。
|
||||
Text(
|
||||
"第 ${i + 1} 个进群的",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
if (!isHost) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 主智能体走不到这里(上面那个 if)—— 它是兜底发言的人
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
|
||||
// 就没有"动不了"的那一个。内核那边会拦住"最后一个"
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,7 +186,7 @@ fun GroupMembersScreen(
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时由主智能体兜底,不会冷场。",
|
||||
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
|
||||
)
|
||||
|
||||
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
|
||||
@@ -203,20 +242,6 @@ fun GroupMembersScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/** 「主智能体」小标签(它和普通成员的区别只在兜底发言,用个浅色标签就够) */
|
||||
@Composable
|
||||
private fun HostBadge() {
|
||||
Text(
|
||||
"主智能体",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@Composable
|
||||
private fun AgentFace(agent: Agent?, size: Int) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
@@ -551,6 +551,18 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
value = vm.state.settings.privateChatRounds,
|
||||
onChange = { vm.setPrivateChatRounds(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★★ 用户要求:「talk_to 是用户可以选择传递和停止,有自动模式
|
||||
// (不用用户确认)」—— 所以默认是**手动**(关),
|
||||
// 群聊里 AI 交了话就停下来等你点;开了这个才是自动接着跑。
|
||||
FormSwitch(
|
||||
title = "AI 对聊自动模式",
|
||||
sub = "关(默认):群里 AI 把话交给别人时,底下会出现" +
|
||||
"「让他说 / 停在这」两个按钮,由你决定要不要接着聊。" +
|
||||
"开:不用确认,自动一轮轮接着跑(最多几轮)。",
|
||||
checked = vm.state.settings.aiTalkAuto,
|
||||
onChange = { vm.setAiTalkAuto(it) },
|
||||
)
|
||||
}
|
||||
|
||||
SettingsCard("个人资料") {
|
||||
|
||||
@@ -428,6 +428,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
# ★ 工具调用的**明细**(不只次数)。
|
||||
#
|
||||
# 界面上的"工具卡片"(调了什么、成没成、返回了什么)以前只有流式那一刻
|
||||
# 能看到 —— 因为这份明细**从来没落过库**,重启 App 就全没了。
|
||||
# 用户的原话:「工具怎么重启就不显示了」。
|
||||
#
|
||||
# 只留 id/name/ok/result 四样:args 可能很长(贴进去的代码),
|
||||
# 而用户真正想回看的是"它做了什么、拿到什么"。result 也截断,
|
||||
# 不然一条消息能撑爆会话 JSON。
|
||||
tool_trace = []
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
@@ -494,6 +504,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': final, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
@@ -549,6 +560,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
# ★ 记明细(落库用,见上面 tool_trace 的注释)
|
||||
tool_trace.append({
|
||||
'id': tc.get('id') or '',
|
||||
'name': tc.get('name') or '',
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': str(payload)[:800],
|
||||
})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
@@ -563,4 +581,5 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
@@ -654,39 +654,58 @@ def pass_turn(args: dict) -> dict:
|
||||
TALK_TO = {
|
||||
'name': 'talk_to',
|
||||
'description': (
|
||||
'在群聊里**主动对另一个智能体说一句话**。\n'
|
||||
'在群聊里**主动对一个或多个智能体说话**。\n'
|
||||
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
|
||||
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
|
||||
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
|
||||
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
|
||||
'★ 一次可以找**好几个人**(`agents` 列表),他们会**挨个**回应。\n'
|
||||
'★ `private=true` 时这条只有**目标**看得到,群里其他智能体看不到 ——\n'
|
||||
' 用户能看到(他是观察者),但别的 AI 不会知道你们说了什么。\n'
|
||||
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 单聊里没有"别人",调了会报错。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'agent': {'type': 'string', 'description': '对方的名字或 id'},
|
||||
'content': {'type': 'string', 'description': '你要对他说的话'},
|
||||
'agents': {
|
||||
'type': 'array',
|
||||
'items': {'type': 'string'},
|
||||
'description': '对方的名字列表(只找一个人也可以只写一个)。他们会按顺序挨个回应。',
|
||||
},
|
||||
'agent': {
|
||||
'type': 'string',
|
||||
'description': '老写法:只找一个人时可以直接写名字(等价于 agents=[名字])。',
|
||||
},
|
||||
'content': {'type': 'string', 'description': '你要对他们说的话'},
|
||||
'private': {
|
||||
'type': 'boolean',
|
||||
'description': '私聊模式:只有目标能看到这条,群里其他智能体看不到(默认 false)。',
|
||||
},
|
||||
},
|
||||
'required': ['agent', 'content'],
|
||||
'required': ['content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def talk_to(args: dict) -> dict:
|
||||
"""
|
||||
主动找群里的另一个智能体说话。
|
||||
主动找群里的一个或多个智能体说话。
|
||||
|
||||
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
|
||||
「工具定义 / 智能体加上内容」):
|
||||
★★ 三个能力都是用户点名要的:
|
||||
|
||||
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
|
||||
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
|
||||
而且那句话要**落进对话**,对方下一轮才看得到。
|
||||
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
|
||||
① **能说具体的话**(`content`)
|
||||
`pass_turn` 只交发言权、不带内容 —— 对方接到一片空白,聊不起来。
|
||||
|
||||
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
|
||||
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
|
||||
② **一次找多个人**(`agents`)—— 他们**挨个**回话。
|
||||
发言权排成队列交给 `tools_runtime`,界面逐个接下去。
|
||||
|
||||
③ **私聊模式**(`private=true`)—— 这条只有目标看得到,
|
||||
群里其他人(包括别的 AI)都不知道你们说了什么。
|
||||
落库时打在消息的 `privateTo` 上;`app.py` 组装 history 时
|
||||
会按"是不是给我的"过滤掉,所以别的 AI 真的看不到。
|
||||
|
||||
★ 说完之后把发言权交出去(`note_handoff`,多目标时排队)——
|
||||
界面据此逐个让他们回应;他们也可以反过来再 `talk_to` 回来。
|
||||
"""
|
||||
import group_chat
|
||||
import tools_runtime
|
||||
@@ -705,30 +724,70 @@ def talk_to(args: dict) -> dict:
|
||||
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
|
||||
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")}」不在这个群里,先把他拉进来')
|
||||
# ★ 目标名单:`agents` 列表优先,兼容老的单数 `agent`
|
||||
raw = args.get('agents')
|
||||
wanted = []
|
||||
if isinstance(raw, list):
|
||||
wanted = [str(x or '').strip() for x in raw]
|
||||
elif raw:
|
||||
wanted = [str(raw or '').strip()]
|
||||
if not wanted:
|
||||
single = str(args.get('agent') or '').strip()
|
||||
if single:
|
||||
wanted = [single]
|
||||
wanted = [x for x in wanted if x]
|
||||
if not wanted:
|
||||
raise ValueError('要跟谁说?写 agent 或 agents')
|
||||
|
||||
targets, missing = [], []
|
||||
for name in wanted:
|
||||
t = _find_agent(name)
|
||||
if not t:
|
||||
missing.append(name)
|
||||
continue
|
||||
if t.get('id') == me.get('id'):
|
||||
continue # 自己跳过(一次找多人时很常见)
|
||||
if t['id'] not in group_chat.member_ids(conv):
|
||||
missing.append(f'{t.get("name")}(不在群里)')
|
||||
continue
|
||||
if all(t['id'] != x['id'] for x in targets):
|
||||
targets.append(t)
|
||||
if not targets:
|
||||
raise ValueError(f'一个都没找到:{"、".join(missing) or "(空的)"}')
|
||||
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not content:
|
||||
raise ValueError('要说什么?content 不能是空的')
|
||||
|
||||
# ① 这句话以**我**的名义落进对话 —— 对方下一轮就看得到
|
||||
store.append_messages(conv_id, [{
|
||||
is_private = bool(args.get('private'))
|
||||
msg = {
|
||||
'role': 'assistant',
|
||||
'content': content,
|
||||
'agentId': me.get('id'),
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
# ② 把发言权交给他 —— 界面据此自动续一轮,让他真的回应
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
}
|
||||
if is_private:
|
||||
# ★ 私聊:只给这几个目标看(`app.py` 组装 history 时按这个过滤)
|
||||
msg['privateTo'] = [t['id'] for t in targets]
|
||||
|
||||
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
store.append_messages(conv_id, [msg])
|
||||
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} private={is_private} '
|
||||
f'targets={[t.get("name") for t in targets]} 内容={content[:20]!r}', file=sys.stderr)
|
||||
|
||||
# ★ 发言权:多目标排成队列,界面逐个接着让他们回应
|
||||
names_out = '、'.join(t.get('name') or '?' for t in targets)
|
||||
tools_runtime.note_handoff(targets[0]['id'], queue=[t['id'] for t in targets])
|
||||
return {
|
||||
'said_to': target.get('name'),
|
||||
'note': f'你已经对「{target.get("name")}」说了这句话,接下来由他回应。',
|
||||
'said_to': [t.get('name') for t in targets],
|
||||
'content': content,
|
||||
'private': is_private,
|
||||
'note': (
|
||||
f'已把「{content}」{"(私下)" if is_private else ""}说给「{names_out}」,'
|
||||
'这句话已经写进对话,他们会挨个回应。别再重复调这个工具。'
|
||||
+ (f'(没找到:{"、".join(missing)})' if missing else '')
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -976,8 +976,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
|
||||
# 限制 —— 会话是用户的,他想拉谁就拉谁。
|
||||
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
|
||||
member_id = self._match_id(pathname, '/api/conversations/')
|
||||
if member_id is not None and '/members' in pathname:
|
||||
#
|
||||
# ★★ 这里**绝不能用 `_match_id`**:它要求"id 后面没有斜杠",
|
||||
# 而这条路是 `/api/conversations/<id>/members` —— `rest` 里带 `/`,
|
||||
# 它直接返回 None,**整个分支永远进不去**。
|
||||
# 真机表现就是「点加人没反应、人也加不上」,接口回的是
|
||||
# **404 未知接口**(看着像路由没写,其实写了、被这个门槛拦住了)。
|
||||
if pathname.startswith('/api/conversations/') and '/members' in pathname:
|
||||
head, _, tail = pathname.partition('/members')
|
||||
member_id = unquote(head[len('/api/conversations/'):].strip('/'))
|
||||
conv = store.get_conversation(member_id)
|
||||
if not conv:
|
||||
self.send_json(404, {'error': '会话不存在'})
|
||||
@@ -1806,24 +1813,22 @@ 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]
|
||||
# ★★ 用户这一轮 @ 了谁 —— **必须看这一条消息,不是历史里的上一条**。
|
||||
# ★★ 用户这一轮 @ 了谁 —— **只看这一条消息**。
|
||||
#
|
||||
# 这个顺序很容易写错:本函数是「先仲裁、后落库」,
|
||||
# 所以 `raw_history` 里**根本没有本次这条用户消息**。
|
||||
# 拿它去找"最后一条 user",找到的是**上一次**用户说的话,
|
||||
# 于是出现:用户打 `@寐眠 在吗` → 仲裁按上一条(没点名)→
|
||||
# 兜底给主智能体 → **小黑替寐眠答了**。
|
||||
# 拿它去找"最后一条 user",找到的是**上一次**用户说的话。
|
||||
#
|
||||
# 用户看到的是「@ 的时候没立即切换」「背景和智能体对不上」
|
||||
# (背景跟着 @ 切到了寐眠,说话的却是小黑,两边对不上)。
|
||||
# 踩过两次:
|
||||
# ① 用户打 `@寐眠 在吗` → 按上一条(没点名)仲裁 → 小黑替寐眠答
|
||||
# ② **自动续轮时又从历史回退** → 把上一轮的 `@寐眠` 又拿来用,
|
||||
# 于是 `talk_to` 明明把话交给了别人,仲裁还是给寐眠 ——
|
||||
# 表现是"下回还是 A 说话"(真机反馈)。
|
||||
#
|
||||
# `autoContinue` 那几轮**本来就没有**新用户消息,那时才回退到历史。
|
||||
# ★ 续轮(`autoContinue`)**本来就没有新用户消息**,
|
||||
# 那一轮该由 `forced` / `passed` / 轮流来定,
|
||||
# 绝不能去翻历史里的 `@` —— 那是上一件事了。
|
||||
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=want,
|
||||
@@ -1863,6 +1868,40 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if window.get('reason'):
|
||||
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
|
||||
|
||||
# ★★ 群聊:给送进模型的每条消息标上**是谁说的**,并过滤私聊消息。
|
||||
#
|
||||
# ① 以前 history 里只有 role/content —— 群里**别人说的话**
|
||||
# 模型根本分不清是谁,只能当成自己说过/用户说过。
|
||||
# 用户的原话:「智能体可以读取群聊所有智能体的对话信息」。
|
||||
# 这里在内容的**前面**加 `[名字] `,只改"送给模型的这份",
|
||||
# 落库的正文保持干净(界面显示不受影响)。
|
||||
#
|
||||
# ② `talk_to` 的私聊模式(`privateTo`):那条消息只有**目标智能体**
|
||||
# 和**用户**看得到,别人(包括模型)都不该有。所以在送进模型之前
|
||||
# 就把"不是给我的私聊"剔掉 —— 在窗口裁剪之后剔除,
|
||||
# 这样裁剪的"轮数"还是按全群算的,不会因为私聊把窗口算歪。
|
||||
_is_group = group_chat.is_group(existing)
|
||||
if _is_group:
|
||||
_name_of = {x['id']: (x.get('name') or '') for x in store.list_agents()}
|
||||
_filtered = []
|
||||
for _m in history:
|
||||
_to = _m.get('privateTo')
|
||||
if isinstance(_to, list) and _to and agent_id not in _to:
|
||||
# 这条是别人之间的私聊 —— 你看不到(用户能看到,那是用户的事)
|
||||
continue
|
||||
_who = ''
|
||||
if _m.get('role') == 'assistant':
|
||||
_who = _name_of.get(str(_m.get('agentId') or ''), '')
|
||||
elif _m.get('role') == 'user':
|
||||
_who = '用户'
|
||||
if _who:
|
||||
_m = dict(_m)
|
||||
_content = _m.get('content')
|
||||
if isinstance(_content, str):
|
||||
_m['content'] = f'[{_who}] {_content}'
|
||||
_filtered.append(_m)
|
||||
history = _filtered
|
||||
|
||||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||
#
|
||||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||
@@ -1969,10 +2008,33 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
|
||||
# ★★ 自动续轮(`autoContinue`)**不能再追加一条空的 user 消息**。
|
||||
#
|
||||
# 以前不管是不是续轮都拼一条 `{'role':'user','content':user_content}`,
|
||||
# 而续轮没有用户输入 → `user_content` 是空串。
|
||||
# 模型看到的是"用户刚发了一条空消息",于是它自己都懵了 ——
|
||||
# 真机上的原话是:「这条又是空的,我这边没收到内容。猜两种可能:…」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
#
|
||||
# 而 `talk_to` 说的那句话**就在历史里**(落库了),
|
||||
# 不追加空消息它自然就看到了。
|
||||
msgs_for_model = list(history)
|
||||
if not auto_continue:
|
||||
msgs_for_model.append({'role': 'user', 'content': user_content})
|
||||
else:
|
||||
# 续轮补一句**极短的指令**而不是空消息:模型需要知道
|
||||
# "现在轮到你接话",但不该以为用户说了什么。
|
||||
# 这条**不落库**(只进这一轮给模型的 messages),
|
||||
# 所以用户在聊天记录里看不到它。
|
||||
msgs_for_model.append({
|
||||
'role': 'user',
|
||||
'content': '(系统:现在轮到你接着说,不用等用户输入。直接接着上面的内容回应。)',
|
||||
})
|
||||
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
agent=agent,
|
||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||
messages=msgs_for_model,
|
||||
emit=emit,
|
||||
should_stop=cancelled,
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
@@ -2003,6 +2065,10 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
int(result.get('toolCalls') or 0),
|
||||
bool((settings.get('tools') or {}).get('python', True)),
|
||||
),
|
||||
# ★ 工具调用明细要落库 —— 不落的话界面上那些"工具卡片"
|
||||
# 只有流式那一刻能看到,**重启 App 就全没了**
|
||||
# (用户报的「工具怎么重启就不显示了」)。
|
||||
'toolTrace': result.get('toolTrace') or [],
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
@@ -2020,7 +2086,11 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# 这个坑在 `pass_turn` 上已经踩过一次了。
|
||||
hs = tools_runtime.handoff_state()
|
||||
if hs.get('used') and hs.get('to'):
|
||||
emit({'type': 'handoff', 'to': hs['to'], 'from': agent_id})
|
||||
emit({'type': 'handoff', 'to': hs['to'],
|
||||
# ★ `talk_to` 一次找多个人时,剩下的人在这里 ——
|
||||
# 界面逐个接下去让他们回应(用户要求"目标智能体挨个回话")
|
||||
'queue': hs.get('queue') or [],
|
||||
'from': agent_id})
|
||||
|
||||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
|
||||
@@ -269,6 +269,26 @@ BUILTIN_SKILL = '\n'.join([
|
||||
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
|
||||
'',
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
'',
|
||||
# ★★ 群聊的用法(用户反馈「智能体好像不怎么会用」)。
|
||||
#
|
||||
# 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
|
||||
'【群聊】你可能在一个群里(群里有别人)。',
|
||||
'· 你能**看到群里所有人的发言**(送进上下文的每条都有 `[名字]` 前缀,'
|
||||
'「[用户]」是你对面那个人说的)。别把别人说的话当成自己说过。',
|
||||
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
|
||||
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
|
||||
'· 一次想找**好几个人**:talk_to(agents=["甲","乙"], content=...),他们会**挨个**回应。',
|
||||
'· 想**私下**跟某人说(只有他知道、群里其他 AI 看不到):加 `private=true`。'
|
||||
' 用户还是看得到(他是观察者)—— 所以别以为私聊就可以说见不得人的话。',
|
||||
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
|
||||
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
|
||||
' pass_turn 只在"我没什么可说了,换你"的时候用。',
|
||||
'· 一轮最多一次:talk_to 和 pass_turn 二选一,别两个都调。',
|
||||
'· 单聊里没有"别人",talk_to 会报错 —— 想跟某个人单独聊,让用户去建群或者私聊。',
|
||||
'· 别为了"显得在忙"反复调 talk_to:一轮一次,说人话就行。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
## 死亡的人不能接
|
||||
|
||||
> 死亡智能体被点名时移交无效,发言权回主智能体。
|
||||
> 死亡智能体被点名时移交无效,换下一个人接。
|
||||
|
||||
这条单独写出来,是因为"移交无效"有三种可能的处置:
|
||||
报错、随机选一个、回主智能体 —— 需求选了第三种。
|
||||
@@ -32,6 +32,8 @@
|
||||
#: 一轮最多移交一次。需求明文,所以做成一个常量而不是散在代码里的布尔。
|
||||
MAX_HANDOFF_PER_ROUND = 1
|
||||
|
||||
import store # noqa: E402 —— 加成员时要查世界观(只读,不参与仲裁)
|
||||
|
||||
|
||||
def member_ids(conv: dict) -> list:
|
||||
"""群聊的成员 id 列表(顺序就是加入顺序,**第 0 个是主智能体**)"""
|
||||
@@ -47,11 +49,44 @@ def is_group(conv: dict) -> bool:
|
||||
|
||||
|
||||
def host_id(conv: dict) -> str:
|
||||
"""主智能体 = 会话发起者 = 成员列表的第一个(需求:"发起者")"""
|
||||
"""
|
||||
⚠️ **不再用于"决定谁发言"** —— 用户明确要求「群聊去掉主人设定」。
|
||||
|
||||
它现在只剩一个用途:`remove_member` 里判断"不能把最后一个人踢走"。
|
||||
决定发言的那条路走 [rotate_next](轮流),不再有"老大"。
|
||||
"""
|
||||
ids = member_ids(conv)
|
||||
return ids[0] if ids else (conv or {}).get('agentId') or ''
|
||||
|
||||
|
||||
def rotate_next(conv: dict, ids: list = None) -> str:
|
||||
"""
|
||||
没人被点名时该谁说 —— **按成员顺序轮**,不设主人。
|
||||
|
||||
★★ 用户原话:「群聊去掉主人设定」。
|
||||
|
||||
原来兜底永远是"会话发起者"(成员列表第一个)——
|
||||
那等于群里有个老大:其他人不 @ 就不开口,@ 了才有台词。
|
||||
现在看**最近一条 AI 消息是谁说的**,下一个人接上,谁都不欠谁。
|
||||
|
||||
★ 找不到上一条(新群、或者老消息没有 agentId)就从第一个开始。
|
||||
"""
|
||||
ids = list(ids if ids is not None else member_ids(conv))
|
||||
if not ids:
|
||||
return ''
|
||||
last = ''
|
||||
for m in reversed((conv or {}).get('messages') or []):
|
||||
if m.get('role') != 'assistant':
|
||||
continue
|
||||
aid = str(m.get('agentId') or '')
|
||||
if aid in ids:
|
||||
last = aid
|
||||
break
|
||||
if not last:
|
||||
return ids[0]
|
||||
return ids[(ids.index(last) + 1) % len(ids)]
|
||||
|
||||
|
||||
def mention_in(text: str, names: list) -> str:
|
||||
"""
|
||||
从用户输入里找出被 @ 的人(返回 id,没有就空串)。
|
||||
@@ -83,7 +118,7 @@ def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
[handoffs] 这一轮已经移交过几次(用于"一轮最多一次")
|
||||
[forced] 界面点「让他们聊」时**指定**的发言者,优先级最高
|
||||
|
||||
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'host'|'handoff_denied'|'forced', 'note': ''}`。
|
||||
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'rotate'|'handoff_denied'|'forced', 'note': ''}`。
|
||||
|
||||
★★ 为什么要有 [forced](真机反馈「还是不能互相对话」):
|
||||
下面三条路都要求**用户点名**或者**AI 自己愿意移交**。
|
||||
@@ -96,7 +131,8 @@ def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
conv = conv or {}
|
||||
alive = alive or {}
|
||||
ids = member_ids(conv)
|
||||
host = host_id(conv)
|
||||
# ★ 兜底**不再是主人**,是轮流(用户要求「群聊去掉主人设定」)
|
||||
nxt = rotate_next(conv, ids)
|
||||
|
||||
def ok(aid: str) -> bool:
|
||||
return bool(aid) and aid in ids and alive.get(aid, True)
|
||||
@@ -115,8 +151,8 @@ def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
if ok(want):
|
||||
return {'speaker': want, 'reason': 'mention', 'note': ''}
|
||||
# 被 @ 的人死了或不在场:回主智能体,而不是报错
|
||||
return {'speaker': host, 'reason': 'host',
|
||||
'note': '被点的人不在场或已死亡,发言权回主智能体'}
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '被点的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ② 界面指定的(「让他们聊」)—— 用户没点名时才轮到它
|
||||
#
|
||||
@@ -124,27 +160,27 @@ def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
if forced:
|
||||
if ok(forced):
|
||||
return {'speaker': forced, 'reason': 'forced', 'note': ''}
|
||||
return {'speaker': host, 'reason': 'host',
|
||||
'note': '指定的人不在场或已死亡,发言权回主智能体'}
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '指定的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ③ AI 的移交(一轮最多一次)
|
||||
if passed:
|
||||
if handoffs >= MAX_HANDOFF_PER_ROUND:
|
||||
return {'speaker': host, 'reason': 'handoff_denied',
|
||||
return {'speaker': nxt, 'reason': 'handoff_denied',
|
||||
'note': '这一轮已经移交过了,不再移交'}
|
||||
if ok(passed):
|
||||
return {'speaker': passed, 'reason': 'handoff', 'note': ''}
|
||||
# ★ 死亡的人被点名时**移交无效**,发言权回主智能体(需求明文)
|
||||
return {'speaker': host, 'reason': 'host',
|
||||
'note': f'「{passed}」已死亡或不在场,移交无效,发言权回主智能体'}
|
||||
# ★ 死亡的人被点名时**移交无效**,换下一个人接(需求明文)
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': f'「{passed}」已死亡或不在场,移交无效,换下一个人接'}
|
||||
|
||||
# ③ 兜底:永不冷场
|
||||
return {'speaker': host, 'reason': 'host', 'note': ''}
|
||||
return {'speaker': nxt, 'reason': 'rotate', 'note': ''}
|
||||
|
||||
|
||||
def add_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
加一个成员(用户手动增删**无条件允许** —— 用户主权)。
|
||||
加一个成员(用户手动增删基本无条件 —— 用户主权)。
|
||||
|
||||
★ 加完**自动升级成 group**:成员超过一个时 `type` 必须是 `group`,
|
||||
不然成员列表里有人、仲裁逻辑还按单聊跑 ——
|
||||
@@ -154,6 +190,12 @@ def add_member(conv: dict, agent_id: str) -> bool:
|
||||
|
||||
★ 单聊要拉人 → 那个会话**就地转成群聊**,而不是偷偷往
|
||||
`participants` 里塞一个 id 却把 `type` 留着。
|
||||
|
||||
★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
理由不是洁癖:群聊的上下文里有 `<worldview>` 段,视野不同的两个人
|
||||
看到的是两套设定 —— 同一个群里会出现"这是哪、我们是谁"对不上的情况,
|
||||
而且记忆空间也是按世界观分的(共享记忆会串)。
|
||||
判定以**群主**(`agentId`)的世界观为准;空对空(都没绑)也算同。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
@@ -162,6 +204,19 @@ def add_member(conv: dict, agent_id: str) -> bool:
|
||||
ids = member_ids(c)
|
||||
if aid in ids:
|
||||
return False
|
||||
|
||||
# ★ 世界观一致才让进 —— 但**未绑世界观的放行**。
|
||||
#
|
||||
# 未绑 = 这个智能体没有世界观设定,和谁都合得来,拉进来不会串。
|
||||
# 一开始我写成"必须相等",于是没绑世界观的智能体也进不来 ——
|
||||
# 用户报的「还是加不了人」,其中那个"黑化豆包"就是未绑的。
|
||||
target = store.get_agent(aid) or {}
|
||||
if target:
|
||||
mine = (store.get_agent(str(c.get('agentId') or '')) or {}).get('worldviewId') or ''
|
||||
theirs = target.get('worldviewId') or ''
|
||||
if theirs and theirs != mine:
|
||||
return False
|
||||
|
||||
ids.append(aid)
|
||||
c['participants'] = ids
|
||||
if len(ids) > 1 and (c.get('type') or 'single') != 'group':
|
||||
|
||||
@@ -182,24 +182,36 @@ def current_context() -> dict:
|
||||
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
|
||||
#
|
||||
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
|
||||
_handoff = {'to': '', 'used': False}
|
||||
_handoff = {'to': '', 'used': False, 'queue': []}
|
||||
|
||||
|
||||
def begin_round() -> None:
|
||||
"""一轮对话开始时调用(agent_loop 在生成前调)"""
|
||||
_handoff['to'] = ''
|
||||
_handoff['used'] = False
|
||||
_handoff['queue'] = []
|
||||
|
||||
|
||||
def note_handoff(agent_id: str) -> None:
|
||||
"""`pass_turn` 记下"这一轮移交给了谁" """
|
||||
_handoff['to'] = str(agent_id or '')
|
||||
def note_handoff(agent_id: str, queue: list = None) -> None:
|
||||
"""
|
||||
记下"这一轮把话交给了谁"。
|
||||
|
||||
[queue] 是**多目标**时的完整名单(`talk_to` 支持一次找好几个人,
|
||||
他们挨个回话)。`to` 始终是**第一个**,保持老调用方不用改。
|
||||
"""
|
||||
ids = [str(x) for x in (queue or []) if str(x or '').strip()]
|
||||
if not ids and str(agent_id or '').strip():
|
||||
ids = [str(agent_id)]
|
||||
_handoff['to'] = ids[0] if ids else str(agent_id or '')
|
||||
_handoff['used'] = True
|
||||
# 剩下的排进队列(`to` 已经算第一个了)
|
||||
_handoff['queue'] = ids[1:]
|
||||
|
||||
|
||||
def handoff_state() -> dict:
|
||||
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`)"""
|
||||
return dict(_handoff)
|
||||
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`,界面要用 `queue`)"""
|
||||
return {'to': _handoff['to'], 'used': _handoff['used'],
|
||||
'queue': list(_handoff.get('queue') or [])}
|
||||
|
||||
|
||||
def ui_tools_enabled(settings: dict) -> bool:
|
||||
|
||||
BIN
docs/screenshots/no-premature-switch.png
Normal file
BIN
docs/screenshots/no-premature-switch.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/speaker-tag-fixed.png
Normal file
BIN
docs/screenshots/speaker-tag-fixed.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.5 MiB |
BIN
docs/screenshots/switch-on-speak.png
Normal file
BIN
docs/screenshots/switch-on-speak.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
BIN
docs/screenshots/title-backdrop-switch.png
Normal file
BIN
docs/screenshots/title-backdrop-switch.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 885 KiB |
@@ -882,6 +882,27 @@ def main():
|
||||
check("换不同名的新图:新文件在", bool(path3) and os.path.isfile(path3), path3)
|
||||
check("换不同名的新图:**旧文件被清掉了**", not os.path.isfile(path2), f"{path2} 还在")
|
||||
|
||||
# ---------------------------------------------------------------- 25
|
||||
section("25. 工具调用明细要落库(真机反馈「工具怎么重启就不显示了」)")
|
||||
#
|
||||
# ★ 界面上那些"工具卡片"(调了什么、成没成、返回什么)以前只有**流式那一刻**
|
||||
# 看得到 —— 因为这份明细从来没落过库,重启 App 就全没了。
|
||||
# 现在 `agent_loop` 收集 → `app.py` 落进消息 → 客户端解析。
|
||||
# 三处缺一处都白搭,所以逐处断言(这是"改一半"的高发区)。
|
||||
_kd = os.path.dirname(os.path.abspath(__file__))
|
||||
_loop = open(os.path.join(_kd, '..', 'android', 'kernel', 'agent_loop.py'),
|
||||
encoding='utf-8').read()
|
||||
_app2 = open(os.path.join(_kd, '..', 'android', 'kernel', 'app.py'),
|
||||
encoding='utf-8').read()
|
||||
check("agent_loop 收集了明细",
|
||||
'tool_trace = []' in _loop and 'tool_trace.append(' in _loop,
|
||||
"没有 tool_trace —— 工具卡片只在流式那一刻存在")
|
||||
check("agent_loop 把它放进了**两条** return(正常收尾 + 轮次用尽)",
|
||||
_loop.count("'toolTrace': tool_trace") >= 2,
|
||||
f"只有 {_loop.count(chr(39) + 'toolTrace' + chr(39) + ': tool_trace')} 处")
|
||||
check("app.py 落库时存了它", "'toolTrace': result.get('toolTrace')" in _app2,
|
||||
"engine 收好了但没存 —— 重启照样没")
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
@@ -52,7 +52,10 @@ def main():
|
||||
participants=[a['id'], b['id']])
|
||||
check("type 存下来了", conv.get('type') == 'group', str(conv.get('type')))
|
||||
check("participants 存下来了", len(G.member_ids(conv)) == 2, str(G.member_ids(conv)))
|
||||
check("主智能体 = 成员列表第一个", G.host_id(conv) == a['id'], G.host_id(conv))
|
||||
# ⚠️ `host_id` 现在**不再用于决定谁发言**(用户要求「群聊去掉主人设定」),
|
||||
# 只剩 remove_member 里「不能把最后一个人踢走」这一个用途。
|
||||
check("host_id 还在(但只表示「列表第一个」,不是发言优先级)",
|
||||
G.host_id(conv) == a['id'], G.host_id(conv))
|
||||
old = store.create_conversation('老会话')
|
||||
check("老会话默认是 single", (old.get('type') or 'single') == 'single')
|
||||
check("非法 type 会被规整成 single",
|
||||
@@ -68,18 +71,18 @@ def main():
|
||||
# ② AI 移交
|
||||
r = G.resolve(conv, passed=b['id'], handoffs=0)
|
||||
check("② AI 移交的人发言", r['speaker'] == b['id'] and r['reason'] == 'handoff', str(r))
|
||||
# ③ 兜底
|
||||
# ③ 兜底:**按顺序轮,不设主人**(用户要求「群聊去掉主人设定」)
|
||||
r = G.resolve(conv)
|
||||
check("③ 没人点名时主智能体兜底(永不冷场)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
|
||||
check("③ 没人点名时按顺序轮(新群从第一个开始)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
# ④ 被点的人死亡
|
||||
r = G.resolve(conv, passed=b['id'], alive={b['id']: False})
|
||||
check("④ **死亡的人接不了,回主智能体**",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
|
||||
check("④ **死亡的人接不了,换下一个人**",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
check("④ 而且说明了原因(界面/日志能看懂)", '死亡' in str(r.get('note')), str(r.get('note')))
|
||||
# ⑤ 一轮内重复移交
|
||||
r = G.resolve(conv, passed=b['id'], handoffs=G.MAX_HANDOFF_PER_ROUND)
|
||||
check("⑤ 一轮内第二次移交被拒(回主智能体)",
|
||||
check("⑤ 一轮内第二次移交被拒(换下一个人)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'handoff_denied', str(r))
|
||||
# 用户 @ 不受"一轮一次"约束(那条只管 AI 的移交)
|
||||
r = G.resolve(conv, want=b['id'], handoffs=99)
|
||||
@@ -99,7 +102,7 @@ def main():
|
||||
participants=[a['id']])
|
||||
check("能加成员", G.add_member(c2, b['id']) is True)
|
||||
check("重复加返回 False(不重复不报错)", G.add_member(c2, b['id']) is False)
|
||||
check("**主智能体不能被移出**(移掉就没兜底了)", G.remove_member(c2, a['id']) is False)
|
||||
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, a['id']) is False)
|
||||
check("普通成员能移出", G.remove_member(c2, b['id']) is True)
|
||||
# 单聊拉人 → 转成群聊
|
||||
single = store.create_conversation('单聊', agent_id=a['id'])
|
||||
@@ -236,7 +239,8 @@ def main():
|
||||
# 新一轮开始要重置
|
||||
tools_runtime.begin_round()
|
||||
check("新一轮开始后重置(可以再移交)",
|
||||
tools_runtime.handoff_state() == {'to': '', 'used': False},
|
||||
tools_runtime.handoff_state().get('to') == ''
|
||||
and tools_runtime.handoff_state().get('used') is False,
|
||||
str(tools_runtime.handoff_state()))
|
||||
r3 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("新一轮里又能移交了", r3.get('ok') is True, str(r3))
|
||||
@@ -411,14 +415,14 @@ def main():
|
||||
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))
|
||||
check("forced 指定的人不在场 → 换下一个人(不抛异常)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
r = G.resolve(gconv, want=b['id'])
|
||||
check("不传 forced 时用户 @ 仍然优先(原有行为没被改坏)",
|
||||
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
r = G.resolve(gconv)
|
||||
check("什么都不传 → 兜底主智能体(永不冷场)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'host', str(r))
|
||||
check("什么都不传 → 按顺序轮(永不冷场,但没主人)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
|
||||
# ★★ 自动续轮**没有用户消息**,所以 `_handle_chat` 开头那条"消息为空"
|
||||
# 的校验必须给它放行 —— 否则每一轮都被打回 400,
|
||||
@@ -445,9 +449,12 @@ def main():
|
||||
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'},
|
||||
# ★ 参数演化过:最早是「agent + 内容」,后来加了多目标(agents)
|
||||
# 和私聊(private),所以必填只剩 content —— 目标二选一。
|
||||
check("参数含「目标 + 内容」",
|
||||
{'agent', 'agents', 'content'} <= set(props), str(list(props)))
|
||||
check("只要求 content 必填(agent/agents 二选一)",
|
||||
list(entry['spec']['parameters'].get('required') or []) == ['content'],
|
||||
str(entry['spec']['parameters'].get('required')))
|
||||
# ★ 模型要能看见它 —— AGENT_TOOLS 会被合并进 BUILTIN_TOOLS 才是真注册
|
||||
import builtin_tools
|
||||
@@ -502,6 +509,85 @@ def main():
|
||||
r.get('ok') is False and ('content' in str(r.get('error')) or '什么' in str(r.get('error'))),
|
||||
str(r))
|
||||
|
||||
print("\n=== 18. 群聊去掉主人设定:没人点名时按顺序轮 ===")
|
||||
#
|
||||
# ★★ 用户原话:「群聊去掉主人设定」。
|
||||
#
|
||||
# 原来兜底永远是"会话发起者"(成员列表第一个)—— 等于群里有个老大:
|
||||
# 其他人不 @ 就不开口。现在看**最近一条 AI 消息是谁说的**,
|
||||
# 下一个人接上,谁都不欠谁。
|
||||
rconv = store.create_conversation(title='轮', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
r = G.resolve(rconv)
|
||||
check("新群没人说过时从第一个开始",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'x', 'agentId': a['id']}])
|
||||
r = G.resolve(store.get_conversation(rconv['id']))
|
||||
check("a 说过了 → 下一个是 b(不是永远 a)", r['speaker'] == b['id'], str(r))
|
||||
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'y', 'agentId': b['id']}])
|
||||
r = G.resolve(store.get_conversation(rconv['id']))
|
||||
check("b 说过了 → 又轮回到 a", r['speaker'] == a['id'], str(r))
|
||||
check("理由统一是 rotate(界面上不再有「主」这个身份)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
|
||||
print("\n=== 19. 提示词要教模型怎么用 talk_to(真机反馈「智能体不怎么会用」)===")
|
||||
#
|
||||
# ★★ 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。
|
||||
import defaults
|
||||
_skill = defaults.BUILTIN_SKILL
|
||||
check("skill 里提到了 talk_to", 'talk_to' in _skill, "提示词没教这个工具")
|
||||
check("说清了它和 pass_turn 的区别",
|
||||
'pass_turn' in _skill and ('空白' in _skill or '不带内容' in _skill),
|
||||
"没讲清区别 —— 模型会继续拿 pass_turn 当说话用")
|
||||
check("写明了「一轮最多一次」", '一轮最多一次' in _skill, "模型会一轮调好几次")
|
||||
|
||||
print("\n=== 20. 加人接口必须真的进得去(真机反馈「点加人没反应」)===")
|
||||
#
|
||||
# ★★ 真机现场:点「加人」→ 选人 → 没反应、人也没加到,接口回 **404 未知接口**。
|
||||
#
|
||||
# 原因不是路由没写,而是它用 `_match_id(pathname, '/api/conversations/')`
|
||||
# 去解析 id —— 那个函数要求「id 后面没有斜杠」,而这条路是
|
||||
# `/api/conversations/<id>/members`,`rest` 里带 `/` 直接返回 None,
|
||||
# **整个分支永远进不去**。
|
||||
#
|
||||
# 这条断言守的就是"别再退回去用 _match_id"。
|
||||
check("成员增删路由自己解析 id(不能用 _match_id)",
|
||||
"if pathname.startswith('/api/conversations/') and '/members' in pathname:" in _app,
|
||||
"又用回 _match_id 了 —— 加人会 404")
|
||||
|
||||
print("\n=== 21. talk_to 多目标 / 私聊 + 群聊里能看到谁说的 ===")
|
||||
#
|
||||
# 用户的三个要求:
|
||||
# ① 智能体能读到群里**所有人**的发言(不是只看到自己的)
|
||||
# ② talk_to 加私聊:只有目标知道
|
||||
# ③ talk_to 支持多目标:目标挨个回话
|
||||
spec2 = agent_tools.AGENT_TOOLS['talk_to']['spec']['parameters']
|
||||
props2 = spec2.get('properties', {})
|
||||
check("talk_to 支持 `agents` 多目标", 'agents' in props2, str(list(props2)))
|
||||
check("`agents` 是数组", props2.get('agents', {}).get('type') == 'array', str(props2.get('agents')))
|
||||
check("talk_to 支持 `private` 私聊", 'private' in props2, str(list(props2)))
|
||||
check("只要求 content 必填(agent/agents 二选一)",
|
||||
spec2.get('required') == ['content'], str(spec2.get('required')))
|
||||
|
||||
# 移交状态要能带队列(多目标挨个回话靠它)
|
||||
import tools_runtime as _tr
|
||||
_tr.begin_round()
|
||||
_tr.note_handoff('a', queue=['a', 'b', 'c'])
|
||||
_st = _tr.handoff_state()
|
||||
check("移交状态带队列(多目标挨个回)",
|
||||
_st.get('to') == 'a' and _st.get('queue') == ['b', 'c'], str(_st))
|
||||
_tr.begin_round()
|
||||
check("新一轮把队列也清掉", _tr.handoff_state().get('queue') == [], str(_tr.handoff_state()))
|
||||
|
||||
# 群聊里送进模型的历史要标发言人 + 过滤别人的私聊
|
||||
check("送进模型的历史标了发言人(`[名字] ` 前缀)",
|
||||
'_[who]' in _app.replace('[', '_[', 1) or 'f\'[{_who}] {_content}\'' in _app,
|
||||
"没标发言人 —— 模型分不清哪句是别人说的")
|
||||
check("别人的私聊消息会被过滤掉(`privateTo`)",
|
||||
"m.get('privateTo')" in _app, "没过滤 —— 私聊会被全群看到")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
|
||||
Reference in New Issue
Block a user