Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 182c0005a4 | |||
| 9ff60e684b | |||
| f8ab075f5e | |||
| 56b15f1d19 | |||
| d3a327da26 |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 248
|
||||
versionName = "2.0.48"
|
||||
versionCode = 253
|
||||
versionName = "2.0.53"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -229,8 +229,23 @@ fun AgentEditScreen(
|
||||
)
|
||||
if (draft.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// ★ 选世界观的时候就要看到"已经有谁在"(用户问的"哪些智能体绑了它")。
|
||||
// 这是**决策依据**:如果里面已经有三个角色,加进去意味着
|
||||
// 四份记忆混在一个空间里;如果只有它一个,那基本等于私有。
|
||||
val wv = vm.state.worldviews.firstOrNull { it.id == draft.worldviewId }
|
||||
val others = (wv?.agents ?: emptyList()).filter { it.id != draft.id }
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定,而且记忆会和同世界观的其他智能体共享。\n" +
|
||||
if (others.isEmpty()) "目前只有它用这个世界观(记忆实际上还是自己一份)"
|
||||
else "已经有 ${others.size} 个智能体在用:${others.joinToString("、") { it.name }}",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (others.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定," +
|
||||
"而且记忆会和上面这些智能体共享(它们也能看到并写入同一个空间," +
|
||||
"但只能改自己写的那几条)。\n" +
|
||||
"情绪仍然是私有的(不会共享)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
@@ -314,6 +329,25 @@ fun AgentEditScreen(
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
BigAction("看它记住了什么") { vm.openMemories(draft.id) }
|
||||
BigAction("看它用了多少") { vm.openTokenUsage(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp)) {
|
||||
Hint(
|
||||
"记忆是 AI 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 删除 ---------------- */
|
||||
if (!isNew) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
@@ -376,6 +410,21 @@ private fun Hint(text: String) {
|
||||
Text(text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
private fun BigAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LabeledField(
|
||||
label: String,
|
||||
|
||||
@@ -125,6 +125,8 @@ fun AgentSelectScreen(
|
||||
onEnter: (Agent) -> Unit,
|
||||
/** 「更多」→ Token 用量详情(需求 2.4) */
|
||||
onMore: (Agent) -> Unit,
|
||||
/** 「记忆」→ 看它记住了什么(记忆管理界面的主入口) */
|
||||
onMemories: (Agent) -> Unit,
|
||||
/** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */
|
||||
onManage: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
@@ -295,14 +297,27 @@ fun AgentSelectScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 底部:进入对话 ----------------
|
||||
// ---------------- 底部:进对话 / 看记忆 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(12.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★「记忆」和「开始对话」并排:进对话之前顺手看一眼它记住了什么。
|
||||
// 记忆是这个功能里最需要"用户能看见"的东西 —— AI 会记错
|
||||
// (把"喜欢猫"记成"讨厌猫"很常见),看见了才能改。
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { onMemories(pickedAgent) }
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("记忆", fontSize = 15.sp, color = doubaoText())
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(
|
||||
Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
@@ -122,7 +123,10 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
active = agent.id == activeId,
|
||||
onUse = { vm.useAgent(agent.id) },
|
||||
onEdit = { vm.openAgentEdit(agent) },
|
||||
onMemories = { vm.openMemories(agent.id) },
|
||||
onDelete = { confirmDelete = agent },
|
||||
worldName = vm.state.worldviews
|
||||
.firstOrNull { it.id == agent.worldviewId }?.name.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -185,7 +189,11 @@ private fun AgentRow(
|
||||
active: Boolean,
|
||||
onUse: () -> Unit,
|
||||
onEdit: () -> Unit,
|
||||
/** 看这个智能体记住了什么(记忆管理界面的入口之一) */
|
||||
onMemories: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
/** 它绑的世界观叫什么(空 = 没绑)。交互是双向的,这边也要看得见 */
|
||||
worldName: String = "",
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||
@@ -221,7 +229,23 @@ private fun AgentRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
// ★ 绑了哪个世界观(用户要求"互通")——
|
||||
// 重点不是"它有个世界观",而是**它和谁共用记忆**。
|
||||
// 所以文案直接写"共用记忆",而不是干巴巴一个名字。
|
||||
if (agent.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"世界观「${worldName.ifBlank { "已失效" }}」· 记忆与同世界的智能体共用",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★「记忆」放在「编辑」**左边**:它是"看它记住了什么",
|
||||
// 属于日常动作;编辑是配置动作,用得少。
|
||||
TextButton(onClick = onMemories) { Text("记忆", fontSize = 12.sp) }
|
||||
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
|
||||
if (!agent.builtin) {
|
||||
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
@@ -150,6 +150,7 @@ fun AppRoot(
|
||||
activeId = vm.state.settings.activeAgentId,
|
||||
onEnter = { vm.enterAgent(it.id) },
|
||||
onMore = { vm.openTokenUsage(it.id) },
|
||||
onMemories = { vm.openMemories(it.id) },
|
||||
onManage = { vm.screen = Screen.Agents },
|
||||
onBack = { vm.screen = Screen.Chat },
|
||||
)
|
||||
@@ -243,6 +244,41 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 世界观的**共享记忆**(从「资源 → 世界观 → 记忆」进来)。
|
||||
//
|
||||
// ★ 它和上面那个是同一个空间(world:<uuid>)的**另一个视角**:
|
||||
// 那边问"玄辰记住了什么",这边问"这个世界里大家共同记得什么"。
|
||||
// 纯只读 —— 写入限权是按 author 判的,而这个视角没有"我"。
|
||||
AnimatedVisibility(
|
||||
visible = vm.worldMemoryId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.worldMemorySpace,
|
||||
agentName = vm.state.worldviews.firstOrNull { it.id == vm.worldMemoryId }?.name
|
||||
?: "世界观",
|
||||
agentId = "",
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
worldMode = true,
|
||||
loading = false,
|
||||
hint = "",
|
||||
onSetEmotion = {},
|
||||
onAdd = { _, _ -> },
|
||||
onUpdate = { _, _, _ -> },
|
||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||
onDelete = { vm.deleteWorldMemory(it) },
|
||||
onTogglePin = { _, _ -> },
|
||||
onSummarize = {},
|
||||
onExport = {},
|
||||
onSetWindow = {},
|
||||
onImportClick = {},
|
||||
onOpenOwn = {},
|
||||
onBackToActive = {},
|
||||
onBack = { vm.closeWorldMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「智能体编辑」—— 全屏界面(字段二十多个,弹窗装不下,见 AGENTS.md 那张表)
|
||||
AnimatedVisibility(
|
||||
visible = vm.agentEditOpen,
|
||||
@@ -289,6 +325,7 @@ fun AppRoot(
|
||||
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
||||
onSummarize = { vm.summarizeMemories() },
|
||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||
onSetWindow = { vm.setMemoryWindow(it) },
|
||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
||||
onBackToActive = { vm.openMemories(vm.memoryAgentId, own = false) },
|
||||
@@ -463,6 +500,13 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
|
||||
vm.screen = Screen.AgentSelect; vm.drawerOpen = false
|
||||
}
|
||||
// ★「记忆」:当前这个智能体记住了什么。
|
||||
// 给它一个抽屉直达入口,因为这是**日常要看**的东西 ——
|
||||
// 你得知道它记对没记错(AI 记反了"喜欢猫/讨厌猫"这种事很常见)。
|
||||
DrawerItem(Icons.Filled.Psychology, "记忆") {
|
||||
vm.drawerOpen = false
|
||||
vm.activeAgent?.id?.let { vm.openMemories(it) }
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
|
||||
@@ -463,6 +463,62 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
memorySpace = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 世界观的**共享记忆**("这个世界里大家共同记得什么")。
|
||||
*
|
||||
* ★ 和智能体的记忆是同一个空间、不同的视角,所以用**独立的状态**:
|
||||
* 共用一个 `memorySpace` 的话,从世界观进去看完再回智能体那边,
|
||||
* 会看到上一个视角留下的数据(界面上表现为"名字和内容对不上")。
|
||||
*/
|
||||
var worldMemoryId by mutableStateOf("")
|
||||
private set
|
||||
var worldMemorySpace by mutableStateOf<com.doubao.lynxclone.data.MemorySpace?>(null)
|
||||
private set
|
||||
|
||||
fun openWorldMemories(worldviewId: String) {
|
||||
worldMemoryId = worldviewId
|
||||
worldMemorySpace = null
|
||||
viewModelScope.launch {
|
||||
worldMemorySpace = runCatching {
|
||||
withContext(Dispatchers.IO) { client.worldMemories(worldviewId) }
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
fun closeWorldMemories() {
|
||||
worldMemoryId = ""
|
||||
worldMemorySpace = null
|
||||
}
|
||||
|
||||
/** 世界观视角下删一条(用户有权删任何人的 —— 限权只约束 AI) */
|
||||
fun deleteWorldMemory(mid: String) {
|
||||
val wid = worldMemoryId
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.deleteMemory(mid) } }
|
||||
if (wid.isNotBlank()) openWorldMemories(wid)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调**注入窗口**:每轮最多把多少条记忆放进提示词(0 = 不限)。
|
||||
*
|
||||
* ★ 这是全局设置(不是每个智能体一份):它防的是"提示词被记忆撑爆",
|
||||
* 而那是个和上下文长度有关的问题,跟具体哪个角色无关。
|
||||
* 放在记忆页顶部就地调,是因为**你看到"300 条里只进去 50 条"的那一刻
|
||||
* 才是你想改它的时候** —— 让用户去设置页翻三层,他就不改了。
|
||||
*/
|
||||
fun setMemoryWindow(n: Int) {
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
client.saveSettings(JSONObject().put("memoryWindow", n))
|
||||
}
|
||||
}
|
||||
refresh()
|
||||
if (memoryAgentId.isNotBlank()) refreshMemories()
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshMemories() {
|
||||
val id = memoryAgentId
|
||||
if (id.isBlank()) return
|
||||
@@ -807,7 +863,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
urlPickerOpen = true
|
||||
}
|
||||
|
||||
/** 用户自己输了一个网址(或从列表里挑了一个) */
|
||||
/**
|
||||
* 用户自己输了一个网址(或从列表里挑了一个)。
|
||||
*
|
||||
* ★ 它**取代**了原来的 `openWebPage(url)` —— 那个是"只负责打开、不补协议",
|
||||
* 和这个除了补 https 之外一模一样,等于同一逻辑两份。
|
||||
* 删掉的那个审计脚本抓出来的(`openWebPage` 没有任何调用点)。
|
||||
*/
|
||||
fun openTypedUrl(text: String) {
|
||||
val t = text.trim()
|
||||
if (t.isEmpty()) return
|
||||
@@ -823,14 +885,6 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
urlPickerOpen = false
|
||||
}
|
||||
|
||||
/** 打开一个网页(全屏界面) */
|
||||
fun openWebPage(url: String) {
|
||||
val u = url.trim()
|
||||
if (u.isEmpty()) return
|
||||
pickUrlFrom = emptyList() // 进网页界面时把"选哪个"收掉
|
||||
webPage = u
|
||||
}
|
||||
|
||||
fun closeWebPage() {
|
||||
webPage = null
|
||||
}
|
||||
@@ -993,7 +1047,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
fun newTopic() {
|
||||
viewModelScope.launch {
|
||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||
val conv = runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
// ★ 新会话记住它属于哪个智能体 —— 会话隔离的依据就是它
|
||||
client.newConversation(agentId = activeAgent?.id.orEmpty())
|
||||
}
|
||||
}.getOrNull()
|
||||
refresh()
|
||||
if (conv != null) {
|
||||
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
||||
@@ -1120,6 +1179,11 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
})
|
||||
}
|
||||
// ★ 内核说"这个会话不是当前智能体的,我另起了一个"(兜底路径)。
|
||||
// 界面必须跟着切,否则会继续往老会话上追加 —— 还是串味。
|
||||
is StreamEvent.Rebased -> {
|
||||
if (event.conversationId.isNotBlank()) openConversation(event.conversationId)
|
||||
}
|
||||
is StreamEvent.Failure -> {
|
||||
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:
|
||||
// 清零 / 调大限额 / 改成无限制。所以单独记一个标记,
|
||||
@@ -1360,7 +1424,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
|
||||
fun useAgent(id: String) {
|
||||
val changed = id != state.settings.activeAgentId
|
||||
saveSettings(mapOf("activeAgentId" to id))
|
||||
// ★★ 换人就**换会话**(用户报的"串味")。
|
||||
//
|
||||
// 会话是属于某个智能体的:里面的历史消息是**上一个角色**说的。
|
||||
// 只换 system prompt 不换会话的话,新角色会看到一堆"自己说过的话",
|
||||
// 把它们当成自己的经历接着聊 —— 表现就是"智能体串味了"。
|
||||
//
|
||||
// 会话还是空的时候不用换(那是"刚点进来还没聊")。
|
||||
if (changed && messages.isNotEmpty()) newTopic()
|
||||
}
|
||||
|
||||
/* ------------------------------ 附件 ------------------------------ */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
@@ -30,6 +31,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.MemoryItem
|
||||
@@ -64,6 +66,15 @@ fun MemoryScreen(
|
||||
agentId: String,
|
||||
/** 所有智能体的 id → 名字(共享记忆里显示"由某某写入") */
|
||||
agentNames: Map<String, String>,
|
||||
/**
|
||||
* **世界观视角**("这个世界里大家共同记得什么")。
|
||||
*
|
||||
* ★ 只读:增删改仍从智能体那边做。世界观视角没有"我",
|
||||
* 而共享空间的写入限权是按 author 判的(需求 3.6)——
|
||||
* 硬做一个权限含义不明的界面,只会让人误操作。
|
||||
* 情绪也藏起来:情绪是**智能体私有**的,不属于这个空间。
|
||||
*/
|
||||
worldMode: Boolean = false,
|
||||
loading: Boolean,
|
||||
hint: String,
|
||||
onSetEmotion: (String) -> Unit,
|
||||
@@ -73,6 +84,8 @@ fun MemoryScreen(
|
||||
onTogglePin: (String, Boolean) -> Unit,
|
||||
onSummarize: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
/** 调注入窗口(条数,0 = 不限) */
|
||||
onSetWindow: (Int) -> Unit,
|
||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||
onImportClick: () -> Unit,
|
||||
/** 去看绑定世界观**之前**攒的私有记忆 */
|
||||
@@ -86,6 +99,9 @@ fun MemoryScreen(
|
||||
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
|
||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||
var confirmSummarize by remember { mutableStateOf(false) }
|
||||
/** 调注入窗口(输入条数,0 = 不限) */
|
||||
var editWindow by remember { mutableStateOf(false) }
|
||||
var windowDraft by remember(space?.window) { mutableStateOf((space?.window ?: 0).toString()) }
|
||||
val readingOwn = space?.own == true
|
||||
|
||||
FullScreen(
|
||||
@@ -94,6 +110,7 @@ fun MemoryScreen(
|
||||
append(agentName.ifBlank { "智能体" })
|
||||
append(" · ")
|
||||
when {
|
||||
worldMode -> append("世界观共享记忆")
|
||||
readingOwn -> append("绑定前的私有记忆")
|
||||
space == null -> append("读取中")
|
||||
space.shared -> append("世界观共享记忆")
|
||||
@@ -104,7 +121,9 @@ fun MemoryScreen(
|
||||
},
|
||||
onBack = { if (readingOwn) onBackToActive() else onBack() },
|
||||
actions = {
|
||||
if (!readingOwn) TopTextAction("导入", onClick = onImportClick)
|
||||
// 世界观视角是纯只读(导入/导出都以"某个智能体的记忆"为单位,
|
||||
// 而这里没有"我")—— 不给按钮,而不是给一个点了没反应的按钮
|
||||
if (!worldMode && !readingOwn) TopTextAction("导入", onClick = onImportClick)
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
@@ -152,8 +171,75 @@ fun MemoryScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口(一遍看不出来"哪些真的进去了",所以直接写清)----
|
||||
if (!readingOwn && !worldMode && space != null) {
|
||||
val total = space.memories.size
|
||||
val win = space.window
|
||||
val injected = space.injected
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { windowDraft = win.toString(); editWindow = true }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
// ★ "列表里有 300 条"和"带进去 50 条"是完全不同的两件事。
|
||||
// 不写清楚的话,用户会以为记忆全都在提示词里。
|
||||
"这一轮会带进去 $injected / $total 条",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
buildString {
|
||||
append("窗口:")
|
||||
append(if (win <= 0) "不限(全部都带)" else "最近 $win 条")
|
||||
append("。")
|
||||
// ★ "能置顶几条"必须在界面上说清:不说的话用户会默认
|
||||
// "只能有一条"(很自然的假设),而实际上标几条都行,
|
||||
// 而且它们**永远**带进去、不受窗口限制。
|
||||
append(
|
||||
if (space.pinnedCount > 0) "已置顶 ${space.pinnedCount} 条"
|
||||
else "可以置顶任意多条"
|
||||
)
|
||||
append(",置顶的永远带、不受窗口限制")
|
||||
if (injected < total) {
|
||||
append(";没带进去的没丢,AI 用 memory_search 还能搜到")
|
||||
}
|
||||
append("。 点这里调 ›")
|
||||
},
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
|
||||
if (space?.shared == true) {
|
||||
if (worldMode) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是这个世界观里所有人共同记得的 —— 绑定了它的智能体共用这一份。\n" +
|
||||
"这里只供查看(改和删请从各自的智能体进去,那边才知道「我」是谁);" +
|
||||
"每条都标了是谁写的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if (space?.shared == true) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -210,7 +296,8 @@ fun MemoryScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 情绪 ----
|
||||
// ---- 情绪(世界观视角没有"自己的情绪",隐藏)----
|
||||
if (!worldMode) {
|
||||
SectionLabel("情绪")
|
||||
Column(
|
||||
Modifier
|
||||
@@ -242,6 +329,7 @@ fun MemoryScreen(
|
||||
) { Text("保存情绪", fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 操作条 ----
|
||||
SectionLabel("记忆(按时间排,最新的在下面)")
|
||||
@@ -249,8 +337,8 @@ fun MemoryScreen(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!readingOwn) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingOwn) {
|
||||
if (!readingOwn && !worldMode) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingOwn && !worldMode) {
|
||||
SmallAction(if (loading) "整理中…" else "AI 整理") {
|
||||
// ★ 先确认再调(复查报告 4.2.1):整理是**一次真的 LLM 调用**、
|
||||
// 会改掉现有记忆,而且用户可能刚标好了「必须保留」——
|
||||
@@ -295,6 +383,46 @@ fun MemoryScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口的调整(A 方案)----
|
||||
if (editWindow) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { editWindow = false },
|
||||
title = { Text("注入窗口", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"每轮最多把多少条记忆放进提示词。\n\n" +
|
||||
"置顶的永远带,不受这个数限制 —— 而且可以置顶任意多条" +
|
||||
"(标几条都行,它们一定都在)。\n" +
|
||||
"其余按时间取最近的。没带进去的不会丢," +
|
||||
"AI 用 memory_search 还能搜到。\n\n" +
|
||||
"填 0 = 不限(全量注入)。记忆攒到几百条时提示词会很贵," +
|
||||
"而且早期的会挤掉最近的对话上下文。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = windowDraft,
|
||||
onValueChange = { s -> windowDraft = s.filter { it.isDigit() }.take(5) },
|
||||
label = { Text("条数(0 = 不限)", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
editWindow = false
|
||||
onSetWindow(windowDraft.toIntOrNull() ?: 0)
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editWindow = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- AI 整理的确认(复查报告 4.2.1)----
|
||||
if (confirmSummarize) {
|
||||
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
||||
@@ -306,10 +434,10 @@ fun MemoryScreen(
|
||||
buildString {
|
||||
append("这会把现在这 ${space?.memories?.size ?: 0} 条零散、重复的记忆")
|
||||
append("压缩成更少、更完整的几条。\n\n")
|
||||
append("· 标了「必须保留」的(现在有 $pinnedCount 条)**原样不动**,不参与合并\n")
|
||||
append("· 它会**只做合并改写**,不许编造新的事实\n")
|
||||
append("· 标了「置顶」的(现在有 $pinnedCount 条)原样不动,不参与合并\n")
|
||||
append("· 它只做合并改写,不许编造新的事实\n")
|
||||
append("· 这是一次真实的模型调用,会花 Token(但不受额度限制)\n\n")
|
||||
append("想保住哪几条,先取消对话框去标上「必须保留」。")
|
||||
append("想保住哪几条,先取消对话框去标上「置顶」。")
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
@@ -381,7 +509,7 @@ private fun MemoryRow(
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (item.pinned) {
|
||||
Text(
|
||||
"必须保留",
|
||||
"置顶",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier
|
||||
@@ -438,7 +566,7 @@ private fun MemoryRow(
|
||||
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
||||
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
||||
// 但文案要写成"取消保留",不能只显示当前状态)
|
||||
RowAction(if (item.pinned) "取消保留" else "必须保留", onClick = onTogglePin)
|
||||
RowAction(if (item.pinned) "取消置顶" else "置顶", onClick = onTogglePin)
|
||||
RowAction("编辑", onClick = onEdit)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
}
|
||||
|
||||
@@ -283,6 +283,26 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
// ★ 谁绑了它(用户要求)—— 反过来也得看得见:
|
||||
// 绑之前你要知道"这个世界观已经有谁在用了",
|
||||
// 空的则说明没人用它、共享记忆也没人在读写。
|
||||
if (kind.id == "worldviews") {
|
||||
val users = vm.state.worldviews.firstOrNull { it.id == id }?.agents ?: emptyList()
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
if (users.isEmpty()) "还没有智能体用它"
|
||||
else "${users.size} 个智能体在用:${users.joinToString("、") { it.name }}",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = if (users.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
RowAction("记忆") {
|
||||
// ★ 世界观的**共享记忆**("大家共同记得什么")——
|
||||
// 和从智能体进去看的是同一个空间、不同的视角
|
||||
vm.openWorldMemories(id)
|
||||
}
|
||||
RowAction("导出") {
|
||||
vm.exportPackage(kind.id, id) { content, ext ->
|
||||
|
||||
@@ -214,6 +214,38 @@ def _extract_json(text: str):
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _world_memories(handler, wid: str, err) -> bool:
|
||||
"""
|
||||
一个世界观的共享记忆(只读快照)。
|
||||
|
||||
★ 为什么世界观也要有这个入口:记忆挂在**空间**上,而空间是世界观定义的
|
||||
(`world:<uuid>`)。从智能体进去看到的是"这个空间里的记忆",
|
||||
但从世界观进去问的是另一个问题 —— "这个世界里大家共同记得什么"。
|
||||
有五个智能体共用同一个世界观时,后者才是你要看的那个视角。
|
||||
|
||||
★ 只读:增删改仍然从智能体那边做。世界观视角没有"我",
|
||||
而共享空间的写入限权是**按 author 判的**(需求 3.6),
|
||||
这里没有一个"我"可以拿来判 —— 硬做只会做出一个权限含义不明的界面。
|
||||
"""
|
||||
world = store.get_resource('worldviews', wid)
|
||||
if not world:
|
||||
err(404, '没有这个世界观')
|
||||
return True
|
||||
scope = agentdb.world_scope(wid)
|
||||
items = agentdb.memory_list(scope)
|
||||
names = {a.get('id'): (a.get('name') or '某人') for a in store.list_agents()}
|
||||
for m in items:
|
||||
m['authorName'] = names.get((m.get('author_agent') or '').strip(), '')
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True,
|
||||
'worldviewId': wid,
|
||||
'name': world.get('name') or '',
|
||||
'shared': True,
|
||||
'memories': items,
|
||||
'count': len(items),
|
||||
})
|
||||
|
||||
|
||||
def _memory_space(agent: dict) -> str:
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
@@ -240,6 +272,15 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
'suggestion': '',
|
||||
}
|
||||
items = agentdb.memory_list(scope)
|
||||
# 注入窗口(条数):界面要显示"这一轮实际会带多少条进去",
|
||||
# 而"列表里有 300 条"和"带进去 50 条"是完全不同的两件事 ——
|
||||
# 不显示的话用户会以为全都在提示词里。
|
||||
try:
|
||||
window = int((store.read_settings() or {}).get('memoryWindow') or 0)
|
||||
except (TypeError, ValueError):
|
||||
window = 0
|
||||
pinned_count = sum(1 for m in items if m.get('pinned'))
|
||||
injected = len(items) if window <= 0 or len(items) <= window else max(window, pinned_count)
|
||||
return {
|
||||
'ok': True,
|
||||
'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示)
|
||||
@@ -250,6 +291,9 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
# ★ 绑定世界观之后,私有空间里可能还留着以前攒的记忆 ——
|
||||
# 条数一并告诉界面,它才知道要不要显示"以前那些在这"这个入口
|
||||
'ownCount': 0 if scope == own else len(agentdb.memory_list(own)),
|
||||
'window': window,
|
||||
'pinnedCount': pinned_count,
|
||||
'injected': injected,
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||
}
|
||||
@@ -659,6 +703,34 @@ _RES_PATH = {
|
||||
}
|
||||
|
||||
|
||||
def _tag_world_agents(items: list) -> list:
|
||||
"""
|
||||
给每个世界观补一个 `agents: [{id, name}]` —— "谁绑了它"。
|
||||
|
||||
★ 为什么在**列表接口**里一起给,而不是开一个 `/worldviews/<id>/agents`:
|
||||
界面本来就要拉这个列表(进资源页就拉),多一个子路由只换来
|
||||
"多一次请求 + 一个可能和列表不同步的缓存"。这个数据量很小
|
||||
(智能体通常几个到几十个),一起算的成本可以忽略。
|
||||
|
||||
★ 顺便能看出**没绑的**(`agents` 为空)—— 那意味着这个世界观
|
||||
目前没人用,它的共享记忆也没有人在读写。
|
||||
"""
|
||||
by_world = {}
|
||||
for a in store.list_agents():
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if wid:
|
||||
by_world.setdefault(wid, []).append({
|
||||
'id': a.get('id') or '',
|
||||
'name': a.get('name') or '未命名',
|
||||
})
|
||||
out = []
|
||||
for it in items or []:
|
||||
it = dict(it)
|
||||
it['agents'] = by_world.get((it.get('id') or '').strip(), [])
|
||||
out.append(it)
|
||||
return out
|
||||
|
||||
|
||||
def _resource_route(handler, seg: list, method: str, body, err):
|
||||
if seg[1] not in _RES_PATH:
|
||||
return None
|
||||
@@ -670,6 +742,9 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
# 世界观的外观图(需求 3.6:沿用同一套四件套)
|
||||
return _set_asset(handler, 'worldviews', seg[2], body(), err)
|
||||
if len(seg) == 4 and seg[3] == 'memories' and method == 'GET':
|
||||
# 世界观的**共享记忆**(大家共同记得什么)—— 只读视角
|
||||
return _world_memories(handler, seg[2], err)
|
||||
if len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||||
return _resource_export(handler, name, seg[2], err)
|
||||
if len(seg) == 4 and seg[3] == 'export' and method == 'GET':
|
||||
@@ -677,7 +752,15 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
|
||||
if len(seg) == 2:
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'items': store.list_resource(name)})
|
||||
items = store.list_resource(name)
|
||||
if name == 'worldviews':
|
||||
# ★ 给世界观补上"哪些智能体绑了它"(用户要求)。
|
||||
# 没有这个的话,你在绑之前想知道"这个世界观已经有谁在用了",
|
||||
# 只能回智能体列表一个个翻 —— 而那正是"互通"该解决的问题。
|
||||
# 在**列表接口里一起给**,而不是再开一个 `/agents` 子路由:
|
||||
# 界面本来就要拉列表,多一次请求只是多一次等待。
|
||||
items = _tag_world_agents(items)
|
||||
handler.send_json(200, {'ok': True, 'items': items})
|
||||
return True
|
||||
if method == 'POST':
|
||||
handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())})
|
||||
|
||||
@@ -103,22 +103,65 @@ def build_emotion(agent: dict) -> str:
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
"""
|
||||
`<memory>` 段:那个记忆空间的**全部条目**(标题 + 正文,需求 3.2 的"全量注入")。
|
||||
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||||
|
||||
★★ 共享空间里的条目**带作者署名**(复查报告第 5 条)。
|
||||
## 注入窗口 + 置顶保护
|
||||
|
||||
为什么必须带:共享记忆是几个人往同一个本子上写。没有署名的时候,
|
||||
别人写的"我小时候住在海边"在模型眼里就是**它自己的经历** ——
|
||||
它会当成自己的过去来讲,甚至在用户问起时说"我不记得有这事"。
|
||||
署名之后它才知道"这条是仙辰写的,不是我的"(需求 3.6 的
|
||||
"交模型调和矛盾记忆"也才有前提:得先分得清谁写的)。
|
||||
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||||
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
|
||||
早期记忆反而挤掉了最近的对话上下文**。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
所以这里按**窗口**裁:
|
||||
|
||||
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
|
||||
· 其余按时间取**最近**的,凑够窗口
|
||||
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
|
||||
不是用来否决用户明确置顶的东西)
|
||||
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
|
||||
也就是"降级为仅可检索"
|
||||
|
||||
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
|
||||
|
||||
## 共享记忆带作者署名
|
||||
|
||||
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
|
||||
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
|
||||
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
|
||||
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
|
||||
得先分得清谁写的)。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
"""
|
||||
scope = memory_scope(agent)
|
||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||
if not items:
|
||||
return ''
|
||||
|
||||
# ---- 窗口裁剪 ----
|
||||
settings = _safe(store.read_settings, {}) or {}
|
||||
try:
|
||||
window = int(settings.get('memoryWindow') or 0)
|
||||
except (TypeError, ValueError):
|
||||
window = 0
|
||||
total = len(items)
|
||||
trimmed = 0
|
||||
if window > 0 and total > window:
|
||||
pinned = [m for m in items if m.get('pinned')]
|
||||
rest = [m for m in items if not m.get('pinned')]
|
||||
room = max(0, window - len(pinned))
|
||||
keep = pinned + (rest[-room:] if room else [])
|
||||
# 顺序:置顶的在前(用户明确要的),其余保持时间顺序
|
||||
items = keep
|
||||
trimmed = total - len(keep)
|
||||
parts = []
|
||||
if pinned:
|
||||
parts.append(f'置顶 {len(pinned)} 条')
|
||||
if trimmed:
|
||||
parts.append(f'另有 {trimmed} 条较早的没放进来(用 memory_search 还能搜到)')
|
||||
note = '(' + ';'.join(parts) + ')' if parts else ''
|
||||
else:
|
||||
note = ''
|
||||
|
||||
tmpl = _safe(
|
||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||
DEFAULT_MEMORY_LINE,
|
||||
@@ -133,15 +176,20 @@ def build_memory(agent: dict) -> str:
|
||||
title = (it.get('title') or '').strip()
|
||||
content = (it.get('content') or '').strip()
|
||||
author = (it.get('author_agent') or '').strip()
|
||||
tags = []
|
||||
if it.get('pinned'):
|
||||
tags.append('置顶')
|
||||
if shared and author:
|
||||
# 自己写的也标出来("(你记的)")—— 一眼能分清哪些是自己的立场
|
||||
who = '你记的' if author == me else f'{names.get(author) or "某人"}记的'
|
||||
title = f'{title}({who})'
|
||||
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||||
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
|
||||
if tags:
|
||||
title = f'{title}({",".join(tags)})'
|
||||
try:
|
||||
lines.append(tmpl.format(title=title, content=content))
|
||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
||||
return '\n'.join(lines)
|
||||
body = '\n'.join(lines)
|
||||
return f'{body}\n{note}' if note else body
|
||||
|
||||
|
||||
def build_peer_emotions(agent: dict) -> str:
|
||||
|
||||
@@ -207,10 +207,16 @@ def memory_get(memory_id: str) -> dict | None:
|
||||
|
||||
|
||||
def memory_list(scope: str) -> list:
|
||||
"""一个记忆空间的全部条目(**注入 system prompt 用的就是它**)"""
|
||||
"""
|
||||
一个记忆空间的全部条目(**注入 system prompt 用的就是它**)。
|
||||
|
||||
★ 顺序是**置顶的排最前**,其余按时间。
|
||||
界面和提示词注入用**同一个顺序** —— 两处各排一次的话,很容易出现
|
||||
"界面上看着在第一条、实际没进提示词"这种对不上的情况。
|
||||
"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? ORDER BY created_at ASC', (scope,),
|
||||
'SELECT * FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
@@ -928,7 +928,13 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
|
||||
self.send_json(200, {'conversation': store.create_conversation(
|
||||
body.get('title') or '新对话',
|
||||
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
|
||||
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
|
||||
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
|
||||
agent_id=(body.get('agentId') or '').strip(),
|
||||
)})
|
||||
return True
|
||||
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||
if conv_id is not None:
|
||||
@@ -1661,6 +1667,27 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
|
||||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||
#
|
||||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||
# 还在同一个会话里接着聊 —— 历史消息是上一个角色说的,
|
||||
# 而 system prompt 已经换成新角色的了。新角色**会把别人的话
|
||||
# 当成自己说的**(用户的原话:"智能体怎么串味了")。
|
||||
#
|
||||
# 处理:主人不一致就**另起一个会话**,并通知界面换 id。
|
||||
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||||
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||||
owner = (existing.get('agentId') or '').strip()
|
||||
if existing and agent_id:
|
||||
if not owner:
|
||||
store.set_conversation_agent(conversation_id, agent_id)
|
||||
elif owner != agent_id:
|
||||
conversation_id = store.create_conversation(agent_id=agent_id)['id']
|
||||
existing = store.get_conversation(conversation_id) or {}
|
||||
# 界面据此把当前会话切过去(不然它会往老 id 上继续追加)
|
||||
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||||
'reason': 'agent_changed'})
|
||||
|
||||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
|
||||
@@ -166,6 +166,15 @@ for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
# 记忆注入窗口(条数):每轮最多把多少条记忆放进提示词。
|
||||
#
|
||||
# ★ "记忆无上限"和"每轮全量注入"这两条长期是矛盾的 —— 攒到几百上千条时
|
||||
# 提示词会被记忆撑爆(一千条 × 几十字 ≈ 几万 token),而且**越靠后的
|
||||
# 记忆越贵、反而把最近的对话上下文挤掉**。
|
||||
# 所以给一个窗口:置顶的永远注入,其余取最近的。
|
||||
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||
# 0 = 不限(退回全量注入)。
|
||||
'memoryWindow': 50,
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
|
||||
@@ -932,6 +932,26 @@ def delete_conversation(conv_id: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def set_conversation_agent(conv_id: str, agent_id: str) -> None:
|
||||
"""
|
||||
把会话**认领**给一个智能体(只用于没有主人的老会话)。
|
||||
|
||||
★ 只认领、不"改嫁":已经在别人名下的会话不由这里动 ——
|
||||
那会让历史消息和提示词对不上(用户报的"串味"就是这么来的)。
|
||||
★ 走 `_load_conversations` / `_persist_conversations` 这一对,
|
||||
不要自己 `_read_json`+`_write_json`:会话有一份**内存缓存**,
|
||||
绕过它写文件的话,紧接着的 `get_conversation` 读到的还是旧的缓存
|
||||
(这个错误在探针里被抓到过)。
|
||||
"""
|
||||
with _lock:
|
||||
data = _load_conversations()
|
||||
for c in data.get('conversations') or []:
|
||||
if c.get('id') == conv_id and not (c.get('agentId') or '').strip():
|
||||
c['agentId'] = agent_id
|
||||
_persist_conversations()
|
||||
return
|
||||
|
||||
|
||||
def append_messages(conv_id: str, messages: list):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
|
||||
BIN
docs/screenshots/agent-memory.png
Normal file
BIN
docs/screenshots/agent-memory.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
146
scripts/audit-ui-entries.py
Normal file
146
scripts/audit-ui-entries.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""审计:**做好了但没有入口的界面**。
|
||||
|
||||
## 为什么要有这个脚本
|
||||
|
||||
记忆管理界面做完、内核接口全通、探针 80 多项全绿 —— 但**没有任何地方能打开它**。
|
||||
是用户问"记忆管理在哪"才发现的。
|
||||
|
||||
这类漏**探针抓不到**(它测的是内核和数据,不测界面有没有入口),
|
||||
**编译也抓不到**(Kotlin 允许一个 public 方法没人调用),
|
||||
**截图也抓不到**(你只会去截你已经知道怎么进去的那几个页面)。
|
||||
|
||||
能抓到的只有"机器扫一遍:这个打开方法,除了定义之外还有人用吗"。
|
||||
|
||||
## 查什么
|
||||
|
||||
1. `AppViewModel` 里所有 `fun openXxx` / `fun closeXxx` —— 谁在调?
|
||||
2. `Screen` 枚举的每个值 —— 有 `when` 分支吗?有地方 `= Screen.X` 跳过去吗?
|
||||
3. `mutableStateOf` 的 `*Open` / `*Id` 状态 —— 有地方把它设成"打开"吗?
|
||||
|
||||
## 怎么判"没入口"
|
||||
|
||||
- 打开类方法:**除定义和内部自查外**没有调用点
|
||||
- Screen 值:没有 `Screen.X ->` 分支(会编译失败,Compiler 已覆盖)**或者**
|
||||
没有 `= Screen.X` 赋值(这个编译不管,就是死页面)
|
||||
- 状态:没有任何地方把它设成 true / 非空(只有读没有写)
|
||||
|
||||
用法:
|
||||
python scripts/audit-ui-entries.py # 有问题时退出码 1
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
UI = os.path.join(
|
||||
HERE, "..", "android", "app", "src", "main", "java", "com", "doubao", "lynxclone", "ui",
|
||||
)
|
||||
VM = os.path.join(UI, "AppViewModel.kt")
|
||||
|
||||
#: 这些**故意**不在这里判:它们是 ViewModel 内部用的,或者由别处(Activity/Service)触发
|
||||
ALLOW_NO_CALLER = {
|
||||
# close 类方法经常只在自己的界面里用,正常
|
||||
"closeTimeouts", "closeTokenUsage", "closeMemories", "closeAgentEdit",
|
||||
}
|
||||
|
||||
|
||||
def read(path):
|
||||
with io.open(path, encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def main():
|
||||
files = {}
|
||||
for name in os.listdir(UI):
|
||||
if name.endswith(".kt"):
|
||||
files[name] = read(os.path.join(UI, name))
|
||||
|
||||
vm_src = files.get("AppViewModel.kt", "")
|
||||
problems = []
|
||||
|
||||
print("=" * 66)
|
||||
print("1. 打开类方法:除了定义,有没有人调?")
|
||||
print("=" * 66)
|
||||
# 定义:fun openXxx( / fun closeXxx(
|
||||
defined = re.findall(r"^\s*fun ((?:open|close|toggle)[A-Za-z0-9_]*)\s*\(", vm_src, re.M)
|
||||
for fn in sorted(set(defined)):
|
||||
if fn in ALLOW_NO_CALLER:
|
||||
print(f" · {fn}(白名单:可能只在自身界面里用)")
|
||||
continue
|
||||
# 调用点:在**别的**文件里出现 fn(,或者在 AppViewModel 里出现第二次以上
|
||||
callers = []
|
||||
for name, src in files.items():
|
||||
n = len(re.findall(rf"\b{re.escape(fn)}\s*\(", src))
|
||||
if name == "AppViewModel.kt":
|
||||
n -= 1 # 减掉定义那一处
|
||||
if n > 0:
|
||||
callers.append(f"{name}×{n}")
|
||||
if callers:
|
||||
print(f" ✓ {fn} ← {', '.join(callers)}")
|
||||
else:
|
||||
print(f" ✗ {fn} **没有任何地方调用** —— 界面做好了但进不去")
|
||||
problems.append(f"{fn} 没有入口")
|
||||
|
||||
print()
|
||||
print("=" * 66)
|
||||
print("2. Screen 枚举:每个值都有人跳过去吗?")
|
||||
print("=" * 66)
|
||||
m = re.search(r"enum class Screen \{([^}]*)\}", vm_src)
|
||||
if not m:
|
||||
print(" !! 找不到 Screen 枚举")
|
||||
return 1
|
||||
values = [v.strip() for v in m.group(1).split(",") if v.strip()]
|
||||
for v in values:
|
||||
# 跳过去的地方:= Screen.X(赋值),排除 when 分支和枚举定义
|
||||
jump = 0
|
||||
for name, src in files.items():
|
||||
jump += len(re.findall(rf"=\s*Screen\.{re.escape(v)}\b", src))
|
||||
branch = sum(len(re.findall(rf"Screen\.{re.escape(v)}\s*->", src)) for src in files.values())
|
||||
if jump == 0:
|
||||
print(f" ✗ Screen.{v} 有 {branch} 个 when 分支,但**没有任何地方跳过去**")
|
||||
problems.append(f"Screen.{v} 是死页面")
|
||||
elif branch == 0:
|
||||
print(f" ✗ Screen.{v} 有 {jump} 处跳转,但**没有 when 分支**(会渲染不出东西)")
|
||||
problems.append(f"Screen.{v} 没有渲染分支")
|
||||
else:
|
||||
print(f" ✓ Screen.{v} ({jump} 处跳转 / {branch} 个分支)")
|
||||
|
||||
print()
|
||||
print("=" * 66)
|
||||
print("3. 打开状态:有没有地方把它打开?")
|
||||
print("=" * 66)
|
||||
states = re.findall(r"var (\w*(?:Open|Id|Hit|Editing))\s+by\s+mutableStateOf", vm_src)
|
||||
for st in sorted(set(states)):
|
||||
# ★ 两种写法都要数,否则全是误报:
|
||||
# ① 外部 `vm.xxx = true`(界面直接设)
|
||||
# ② ViewModel **内部** `xxx = true`(openXxx() 里设)—— 最常见的那种
|
||||
external = sum(len(re.findall(rf"\.{re.escape(st)}\s*=", src)) for src in files.values())
|
||||
inner = len(re.findall(rf"^\s*{re.escape(st)}\s*=", vm_src, re.M))
|
||||
writes = external + inner
|
||||
reads = sum(len(re.findall(rf"\bvm\.{re.escape(st)}\b", src)) for src in files.values())
|
||||
# `private set` 的状态只能内部写 —— 那正是第 ② 种
|
||||
if writes <= 0:
|
||||
print(f" ✗ {st} 只被读 {reads} 次、**没有地方写** —— 这个界面永远打不开")
|
||||
problems.append(f"{st} 永远打不开")
|
||||
else:
|
||||
print(f" ✓ {st} (写 {writes} 次:内部 {inner} / 外部 {external};读 {reads} 次)")
|
||||
|
||||
print()
|
||||
if problems:
|
||||
print(f"❌ {len(problems)} 个问题:")
|
||||
for p in problems:
|
||||
print(" -", p)
|
||||
return 1
|
||||
print("✅ 所有界面都有入口")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
108
scripts/demo-peer-visibility.py
Normal file
108
scripts/demo-peer-visibility.py
Normal file
@@ -0,0 +1,108 @@
|
||||
"""演示:智能体在提示词里**实际能看到什么**(同世界观的伙伴)。
|
||||
|
||||
用户问"智能体能看哪些智能体绑了它吗" —— 这件事光说"能"没意义,
|
||||
跑一下把**真实注入的那段文字**打出来看。
|
||||
|
||||
python scripts/demo-peer-visibility.py
|
||||
|
||||
它造一个世界观 + 三个智能体(两个绑上、一个不绑),然后把三个智能体
|
||||
各自收到的 `<peer_emotions>` 段原样打印。
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
DATA = tempfile.mkdtemp(prefix="doubao-demo-peer-")
|
||||
os.environ["DOUBAO_DATA"] = DATA
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
import agent_context # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
def seg(prompt: str, name: str) -> str:
|
||||
"""把某一段从拼好的提示词里抠出来(看不到就是空)"""
|
||||
a = prompt.find(f'<{name}>')
|
||||
if a < 0:
|
||||
return '(整段没有)'
|
||||
b = prompt.find(f'</{name}>', a)
|
||||
return prompt[a:b + len(name) + 3]
|
||||
|
||||
|
||||
def main():
|
||||
world = store.create_resource('worldviews', {
|
||||
'name': '九州', 'setting': '一个仙侠世界,灵气复苏。',
|
||||
})
|
||||
xc = store.create_agent({'name': '玄辰', 'systemPrompt': '你是玄辰,仙门大师兄。'})
|
||||
xc = store.update_agent(xc['id'], {'worldviewId': world['id']}) or xc
|
||||
xc2 = store.create_agent({'name': '仙辰', 'systemPrompt': '你是仙辰。'})
|
||||
xc2 = store.update_agent(xc2['id'], {'worldviewId': world['id']}) or xc2
|
||||
lone = store.create_agent({'name': '独行侠', 'systemPrompt': '你谁也不认识。'})
|
||||
|
||||
agentdb.emotion_set(xc['id'], '刚被师父训了一顿,有点闷')
|
||||
agentdb.emotion_set(xc2['id'], '刚赢了比试,得意')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('① 玄辰(绑了九州)· 情绪感知**关着**(默认)')
|
||||
print('=' * 70)
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 知道「有谁」,但看不到他们的情绪。')
|
||||
print(' 为什么关着也要给名单:共享记忆是共用的,它一定会看到别人写的条目。')
|
||||
print(' 不知道有别人,它就会把别人的经历当成自己的过去。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('② 玄辰 · 情绪感知**打开**(编辑界面 → 能力 → 情绪感知)')
|
||||
print('=' * 70)
|
||||
store.update_agent(xc['id'], {'emotionEnabled': True})
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 名单 + 各自当前的情绪。情绪仍然是**单向只读**的:')
|
||||
print(' 玄辰能看到仙辰的情绪,但改不了;仙辰那边看到的是玄辰的。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('③ 独行侠(没绑世界观)')
|
||||
print('=' * 70)
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(lone['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 没有这段。它没有世界观,也就没有"伙伴"这回事。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('④ 共享记忆里别人写的条目(署名)')
|
||||
print('=' * 70)
|
||||
scope = agentdb.world_scope(world['id'])
|
||||
agentdb.memory_add(scope, '师父的忌讳', '提到"剑冢"他会翻脸', author_agent=xc2['id'])
|
||||
agentdb.memory_add(scope, '我的佩剑', '叫"霜落",是师父给的', author_agent=xc['id'])
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'memory'))
|
||||
print()
|
||||
print(' → 玄辰看到的是:仙辰记的那条**标了「仙辰记的」**,')
|
||||
print(' 自己记的那条标「你记的」。不标的话,')
|
||||
print(' "我小时候住在海边"这种别人写的经历,在它眼里就是它自己的过去。')
|
||||
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
code = main()
|
||||
finally:
|
||||
shutil.rmtree(DATA, ignore_errors=True)
|
||||
sys.exit(code)
|
||||
@@ -350,6 +350,105 @@ def main():
|
||||
r = h.call(f"/api/skills/{sid}", "DELETE")
|
||||
check("删 skill", r.get("deleted") is True)
|
||||
|
||||
# ---------------------------------------------------------------- 13
|
||||
section("13. 世界观的引用列表(谁绑了它)")
|
||||
lonely = store.create_resource("worldviews", {"name": "没人用的世界", "setting": "空"})
|
||||
r = h.call("/api/worldviews", "GET")
|
||||
items = r.get("items") or []
|
||||
check("列表每一项都带 agents 字段", items and all("agents" in it for it in items))
|
||||
mine = next((it for it in items if it.get("id") == wv["id"]), None)
|
||||
check("绑了它的两个智能体都在", mine is not None and len(mine.get("agents") or []) == 2,
|
||||
str(mine and mine.get("agents")))
|
||||
check("给的是名字而不是只有 id",
|
||||
bool(mine) and all(a.get("name") for a in mine.get("agents") or []),
|
||||
str(mine and mine.get("agents")))
|
||||
empty = next((it for it in items if it.get("id") == lonely["id"]), None)
|
||||
check("没人绑的世界观 agents 为空(能看出没人用)",
|
||||
empty is not None and empty.get("agents") == [], str(empty and empty.get("agents")))
|
||||
# 解绑之后要跟着变(缓存住了的话这里会露馅)
|
||||
store.update_agent(a2["id"], {"worldviewId": ""})
|
||||
again = next((it for it in (h.call("/api/worldviews", "GET").get("items") or [])
|
||||
if it.get("id") == wv["id"]), None)
|
||||
check("解绑之后列表跟着少一个", again is not None and len(again.get("agents") or []) == 1,
|
||||
str(again and again.get("agents")))
|
||||
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
|
||||
|
||||
# ---------------------------------------------------------------- 14
|
||||
section("14. 会话隔离:一个会话属于一个智能体(用户报的「串味」)")
|
||||
# 场景:跟「豆包」聊了半天 → 切到「代码搭子」→ 接着聊。
|
||||
# 以前 system prompt 换了、历史消息没换,新角色会把上一个角色说过的话
|
||||
# 当成自己的经历 —— 用户的原话是"智能体怎么串味了"。
|
||||
conv_a = store.create_conversation("A 的对话", agent_id=a1["id"])
|
||||
check("新会话记住了主人", (store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"])
|
||||
legacy = store.create_conversation("老会话")
|
||||
check("不传主人时是空(老数据的样子)",
|
||||
not (store.get_conversation(legacy["id"]) or {}).get("agentId"))
|
||||
store.set_conversation_agent(legacy["id"], a2["id"])
|
||||
check("没主人的老会话能被认领",
|
||||
(store.get_conversation(legacy["id"]) or {}).get("agentId") == a2["id"])
|
||||
# ★★ 这条是关键:有主人的会话**不许改嫁** —— 改名换姓就等于串味
|
||||
store.set_conversation_agent(conv_a["id"], a2["id"])
|
||||
check("已经有主人的不会被改嫁(那正是串味的来源)",
|
||||
(store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"],
|
||||
str((store.get_conversation(conv_a["id"]) or {}).get("agentId")))
|
||||
|
||||
# ---------------------------------------------------------------- 15
|
||||
section("15. 记忆注入窗口 + 置顶保护(本次新增)")
|
||||
w = store.create_agent({"name": "窗口测试"})
|
||||
sc = agentdb.scope_of(w["id"])
|
||||
for i in range(1, 11):
|
||||
agentdb.memory_add(sc, f"第{i}条", f"内容{i}", author_agent=w["id"])
|
||||
ids = agentdb.memory_list(sc)
|
||||
agentdb.memory_set_pinned(ids[0]["id"], True) # 把**最旧**的一条置顶
|
||||
# ★ SQLite 里的布尔是 0/1 整数,`is True` 永远是 False(这个坑探针自己踩了)
|
||||
check("置顶的排在列表最前", bool(agentdb.memory_list(sc)[0]["pinned"]))
|
||||
# 窗口设成 4:置顶的必须在,其余取最近的
|
||||
store.write_settings({"memoryWindow": 4})
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
seg = p[p.find("<memory>"):p.find("</memory>")]
|
||||
check("置顶的那条**在**(不受窗口限制)", "第1条" in seg, seg[-200:])
|
||||
check("最近的在", "第10条" in seg and "第9条" in seg, seg[-200:])
|
||||
check("中间的被裁掉了", "第5条" not in seg, seg[-200:])
|
||||
check("裁掉多少写清楚了(告知可检索)", "memory_search" in seg, seg[-200:])
|
||||
# 0 = 不限
|
||||
store.write_settings({"memoryWindow": 0})
|
||||
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
check("窗口 = 0 时全部注入", all(f"第{i}条" in p2 for i in range(1, 11)))
|
||||
# 接口把窗口信息带给界面
|
||||
mp = h.call(f"/api/agents/{w['id']}/memories", "GET")
|
||||
check("界面拿得到窗口/置顶数/实际注入数",
|
||||
all(k in mp for k in ("window", "pinnedCount", "injected")), str(sorted(mp)[:8]))
|
||||
check("injected 算得对(先恢复窗口=4)",
|
||||
(store.write_settings({"memoryWindow": 4}),
|
||||
(h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected") == 4)[1],
|
||||
str((h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected")))
|
||||
|
||||
# ---- ★ 可以**多个**置顶(用户明确要求)----
|
||||
#
|
||||
# 单条置顶是最容易蒙混过关的:只测一条的话,"置顶逻辑写成只能有一个"
|
||||
# 也能通过。所以这里标**三条**,而且专挑**最早**的三条 ——
|
||||
# 窗口只留最近的话它们本来就该被裁掉,只有置顶真的生效才会留下。
|
||||
ids2 = agentdb.memory_list(sc)
|
||||
for k in (0, 2, 4):
|
||||
agentdb.memory_set_pinned(ids2[k]["id"], True)
|
||||
store.write_settings({"memoryWindow": 5})
|
||||
p3 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
seg3 = p3[p3.find("<memory>"):p3.find("</memory>")]
|
||||
check("**多个置顶**都能留(标了三条最早的)",
|
||||
all(f"第{i}条" in seg3 for i in (1, 3, 5)), seg3[-260:])
|
||||
check("窗口剩下的名额给最近的", "第10条" in seg3, seg3[-260:])
|
||||
check("置顶在正文里被标出来", seg3.count("置顶") >= 3, str(seg3.count("置顶")))
|
||||
# 置顶比窗口还多的时候:置顶**全部**保留(窗口是给普通记忆设的,
|
||||
# 不是用来否决用户明确置顶的东西)
|
||||
for k in (6, 8, 9):
|
||||
agentdb.memory_set_pinned(ids2[k]["id"], True)
|
||||
store.write_settings({"memoryWindow": 2})
|
||||
p4 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
seg4 = p4[p4.find("<memory>"):p4.find("</memory>")]
|
||||
kept = sum(1 for i in range(1, 11) if f"第{i}条" in seg4)
|
||||
check("置顶数超过窗口时,置顶的全部保留(6 条)", kept == 6, f"实际 {kept} 条:{seg4[-200:]}")
|
||||
store.write_settings({"memoryWindow": 50})
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
Reference in New Issue
Block a user