diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt new file mode 100644 index 0000000..208c44c --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentEditScreen.kt @@ -0,0 +1,468 @@ +package com.doubao.lynxclone.ui + +import android.util.Base64 +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +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.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +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.R +import com.doubao.lynxclone.data.Agent +import com.doubao.lynxclone.data.AgentImage +import androidx.compose.ui.res.painterResource +import androidx.compose.foundation.Image + +/* + * 智能体的完整编辑界面(需求 2.5 / 3.1 / 3.3 / 3.5 / 3.6 / 3.7)。 + * + * ## ★ 为什么是全屏,而不是沿用那个弹窗 + * + * 字段从 8 个涨到了二十多个(外观四件套、模型引用、世界观、限额、技能……)。 + * AGENTS.md 里那张表写得很清楚:「**列表 / 多组配置 / 任何要滚动的 → 独立全屏界面**」, + * 而"节点配置 NodeConfigDialog → 全屏(字段很多)"到现在还挂在待办清单上 —— + * 这次不再欠新账。 + * + * ## 三处会让人困惑的地方,界面上直接说清 + * + * ① **介绍(description)和一句话介绍(tagline)不是一回事**: + * 前者只在选择界面的介绍框里显示,后者是列表里的摘要。 + * ② **绑了世界观 = 记忆变成共享的**(需求 3.6)—— 不写清楚, + * 用户会以为"我给 A 记的东西怎么 B 也知道"。 + * ③ **限额 0 就是无限制**,不是"限额为 0"。 + */ + +/** 外观四件套在界面上的顺序和文案 */ +private val ASSET_SLOTS = listOf( + Triple("front", "角色图", "展示区中间的主体形象;缺了用内置默认人物"), + Triple("back", "背景图", "铺在展示区最底层;缺了用内置默认背景"), + Triple("border-main", "主体边框", "框住整个展示区;缺了用简单方框"), + Triple("border-info", "介绍边框", "围住介绍文本;缺了跟主体边框一个样式"), +) + +@Composable +fun AgentEditScreen( + vm: AppViewModel, + initial: Agent?, + onDone: () -> Unit, +) { + val isNew = initial == null + var draft by remember { mutableStateOf(initial ?: Agent(avatar = "custom")) } + var saving by remember { mutableStateOf(false) } + var promptDraft by remember { mutableStateOf(draft.systemPrompt) } + var limitDraft by remember { mutableStateOf( + if (draft.tokenLimit > 0) draft.tokenLimit.toInt().toString() else "" + ) } + val ctx = LocalContext.current + + // 选一张外观图 → 读字节 → base64 → 立刻上传 + // ★ 不等"保存":图片可能好几 MB,混在保存里用户会以为卡死了 + var pendingSlot by remember { mutableStateOf("") } + val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + val slot = pendingSlot + pendingSlot = "" + if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult + runCatching { + val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) + val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/') + val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP) + vm.uploadAgentAsset(draft.id, slot, name, b64) + }.onFailure { vm.showHint("读不出这张图") } + } + + FullScreen( + title = if (isNew) "新建智能体" else "编辑智能体", + subtitle = if (isNew) "保存后可以加外观图片" else draft.name, + onBack = onDone, + actions = { + TopAction("保存", enabled = !saving) { + saving = true + vm.saveAgentFull( + draft.copy(systemPrompt = promptDraft, tokenLimit = limitDraft.toDoubleOrNull() ?: 0.0), + isNew, + ) { saving = false; onDone() } + } + }, + ) { + // 编辑中的智能体可能是**别处刚改过**的(比如刚上传完图片)—— + // vm.agents 里的那份才是最新的,这里同步一下,否则预览是旧的 + val fresh = vm.agents.firstOrNull { it.id == draft.id } + if (!isNew && fresh != null && fresh.image != draft.image) { + draft = draft.copy(image = fresh.image) + } + + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { + + /* ---------------- 基本信息 ---------------- */ + SectionLabel("基本信息") + Card { + LabeledField("名字", draft.name, "比如:玄辰") { draft = draft.copy(name = it) } + Spacer(Modifier.height(10.dp)) + LabeledField("一句话介绍", draft.greeting, "列表里的摘要,比如:仙门大师兄") { + draft = draft.copy(greeting = it) + } + Spacer(Modifier.height(4.dp)) + Hint("显示在智能体列表里。") + Spacer(Modifier.height(12.dp)) + LabeledField("介绍文案", draft.description, "选择界面右边那个介绍框里显示的话") { + draft = draft.copy(description = it) + } + Spacer(Modifier.height(4.dp)) + Hint("★ 和上面那条不一样:这条只在选择智能体时的介绍框里显示。留空就只显示名字。") + } + + /* ---------------- 外观 ---------------- */ + SectionLabel("外观") + Card { + if (isNew) { + // ★ 图片要落到"这个智能体的资源目录"里,所以必须先在库里有一条记录 + Text( + "先点右上角「保存」把智能体建出来,再回来加外观图片。", + fontSize = 12.sp, + lineHeight = 17.sp, + color = doubaoTextSecondary(), + ) + } else { + for ((key, title, desc) in ASSET_SLOTS) { + AssetRow( + title = title, + desc = desc, + path = draft.image.pathOf(key), + onPick = { pendingSlot = key; pickImage.launch(arrayOf("image/*")) }, + onClear = { vm.uploadAgentAsset(draft.id, key, "", "") }, + ) + Spacer(Modifier.height(6.dp)) + } + Hint("支持 PNG / JPG / GIF(动图会动)。SVG 也能显示。缺哪张就用内置默认。") + } + } + + /* ---------------- 人设 ---------------- */ + SectionLabel("人设(系统提示词)") + Card { + OutlinedTextField( + value = promptDraft, + onValueChange = { promptDraft = it }, + placeholder = { Text("你是一个……", fontSize = 13.sp) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp), + textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp), + ) + Spacer(Modifier.height(6.dp)) + Hint("留空就用全局系统提示词。记忆、情绪、世界观、技能会自动拼在这后面,不用你自己写。") + } + + /* ---------------- 模型 ---------------- */ + SectionLabel("模型") + Card { + val entries = vm.state.modelEntries + if (entries.isEmpty()) { + Hint("还没有全局模型。去「设置 → 超时」上面的「全局模型」里加一个,就能在这里引用它。") + } else { + ChipRow( + options = listOf("" to "跟随全局") + entries.map { it.id to it.name }, + active = draft.modelId, + onPick = { draft = draft.copy(modelId = it) }, + ) + Spacer(Modifier.height(6.dp)) + Hint("选了它就固定用那个模型;「跟随全局」= 用设置里当前选的那个。") + } + } + + /* ---------------- 世界观 ---------------- */ + SectionLabel("世界观") + Card { + val worlds = vm.state.worldviews + ChipRow( + options = listOf("" to "不绑定") + worlds.map { it.id to it.name }, + active = draft.worldviewId, + onPick = { draft = draft.copy(worldviewId = it) }, + ) + if (draft.worldviewId.isNotBlank()) { + Spacer(Modifier.height(8.dp)) + Text( + "★ 绑定之后:提示词里会多一段世界观设定,而且记忆会和同世界观的其他智能体共享。\n" + + "情绪仍然是私有的(不会共享)。", + fontSize = 11.sp, + lineHeight = 16.sp, + color = Color(0xFF8A6100), + ) + } + if (worlds.isEmpty()) { + Spacer(Modifier.height(6.dp)) + Hint("还没有世界观。在「更多功能 → 世界观」里新建或导入一个。") + } + } + + /* ---------------- 能力 ---------------- */ + SectionLabel("能力") + Card { + ToggleRow( + title = "情绪感知", + sub = "能看到同世界观其他智能体当前的情绪(只读,单向)", + checked = draft.emotionEnabled, + onChange = { draft = draft.copy(emotionEnabled = it) }, + ) + Spacer(Modifier.height(12.dp)) + Text("Token 限额", fontSize = 13.sp, color = doubaoText()) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = limitDraft, + onValueChange = { s -> limitDraft = s.filter { it.isDigit() }.take(9) }, + placeholder = { Text("留空 = 无限制", fontSize = 13.sp) }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp), + ) + Spacer(Modifier.height(4.dp)) + Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。") + } + + /* ---------------- 技能 ---------------- */ + SectionLabel("技能(Skill)") + Card { + val all = vm.state.skills + if (all.isEmpty()) { + Hint("还没有自定义 Skill。内置的记忆/情绪/用量手册默认就生效,不用在这里选。") + } else { + for (s in all) { + val on = s.id in draft.skillIds + ToggleRow( + title = s.name.ifBlank { "未命名 Skill" }, + sub = s.content.lineSequence().firstOrNull()?.take(60) ?: "", + checked = on, + onChange = { v -> + draft = draft.copy( + // ★ 按**勾选顺序**排:需求 3.7 说"按绑定顺序拼接注入", + // 顺序会影响模型读到的先后,所以不能是 Set + skillIds = if (v) draft.skillIds + s.id + else draft.skillIds.filter { it != s.id }, + ) + }, + ) + Spacer(Modifier.height(6.dp)) + } + Hint("勾选顺序就是注入顺序(先勾的在前)。") + } + } + + /* ---------------- 语音 ---------------- */ + SectionLabel("语音") + Card { + // ★ 这里**只选音色**,不选引擎 —— 引擎是"用哪套语音服务", + // 属于全局设置(换引擎时音色名整套都不一样,混在一个界面里 + // 必然出现"选了引擎、音色还是上一家的"这种状态)。 + Hint("引擎跟随全局(在「设置 → 语音」里换)。想给这个智能体一个不同的嗓音,就在下面选音色。") + Spacer(Modifier.height(10.dp)) + val engine = vm.state.speech.ttsEngine + VoicePickerInline( + engine = engine, + voices = vm.state.speechVoices[engine] ?: emptyList(), + voicesAll = vm.state.speechVoicesAll[engine] ?: emptyList(), + value = draft.ttsVoice, + onValue = { draft = draft.copy(ttsVoice = it) }, + ) + } + + /* ---------------- 删除 ---------------- */ + if (!isNew && !draft.builtin) { + Spacer(Modifier.height(10.dp)) + Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) { + RowAction("删除这个智能体", danger = true) { + vm.deleteAgentFull(draft.id) { onDone() } + } + } + } + Spacer(Modifier.height(30.dp)) + } + } +} + +/* -------------------------------------------------------------------------- */ + +private fun AgentImage.pathOf(key: String): String = when (key) { + "front" -> front + "back" -> back + "border-main" -> borderMain + else -> borderInfo +} + +@Composable +private fun Card(content: @Composable () -> Unit) { + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp) + .clip(RoundedCornerShape(14.dp)) + .background(doubaoSurface()) + .padding(14.dp), + ) { content() } +} + +@Composable +private fun Hint(text: String) { + Text(text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary()) +} + +@Composable +private fun LabeledField( + label: String, + value: String, + placeholder: String, + onChange: (String) -> Unit, +) { + Text(label, fontSize = 13.sp, color = doubaoText()) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = value, + onValueChange = onChange, + placeholder = { Text(placeholder, fontSize = 13.sp) }, + modifier = Modifier.fillMaxWidth(), + textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp), + ) +} + +@Composable +private fun ChipRow( + options: List>, + active: String, + onPick: (String) -> Unit, +) { + Column { + for (row in options.chunked(3)) { + Row( + Modifier.fillMaxWidth().padding(vertical = 3.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + for ((key, label) in row) { + val on = key == active + Text( + label, + fontSize = 12.sp, + color = if (on) Color.White else doubaoText(), + maxLines = 1, + modifier = Modifier + .clip(RoundedCornerShape(16.dp)) + .background(if (on) Doubao.Blue else doubaoCard()) + .clickable { onPick(key) } + .padding(horizontal = 12.dp, vertical = 7.dp), + ) + } + } + } + } +} + +@Composable +private fun ToggleRow( + title: String, + sub: String, + checked: Boolean, + onChange: (Boolean) -> Unit, +) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(title, fontSize = 14.sp, color = doubaoText()) + if (sub.isNotBlank()) { + Text(sub, fontSize = 11.sp, lineHeight = 15.sp, color = doubaoTextSecondary()) + } + } + Spacer(Modifier.width(10.dp)) + Box( + Modifier + .size(width = 44.dp, height = 26.dp) + .clip(RoundedCornerShape(13.dp)) + .background(if (checked) Doubao.Blue else Doubao.Border) + .clickable { onChange(!checked) }, + contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart, + ) { + Box( + Modifier + .padding(horizontal = 3.dp) + .size(20.dp) + .clip(RoundedCornerShape(10.dp)) + .background(Color.White), + ) + } + } +} + +/** 一个外观槽位:小预览 + 标题说明 + 选图 / 清除 */ +@Composable +private fun AssetRow( + title: String, + desc: String, + path: String, + onPick: () -> Unit, + onClear: () -> Unit, +) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Box( + Modifier + .size(52.dp) + .clip(RoundedCornerShape(8.dp)) + .background(doubaoCard()) + .border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)), + contentAlignment = Alignment.Center, + ) { + if (path.isBlank()) { + Image( + painter = painterResource(R.drawable.agent_default_character), + contentDescription = null, + modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)), + contentScale = ContentScale.Crop, + alignment = Alignment.TopCenter, + alpha = 0.35f, + ) + } else { + AssetImage( + path = path, + modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)), + contentScale = ContentScale.Crop, + alignment = Alignment.TopCenter, + ) + } + } + Spacer(Modifier.width(10.dp)) + Column(Modifier.weight(1f)) { + Text(title, fontSize = 13.sp, color = doubaoText()) + Text(desc, fontSize = 10.sp, lineHeight = 14.sp, color = doubaoTextSecondary()) + } + Column(horizontalAlignment = Alignment.End) { + RowAction("选择") { onPick() } + if (path.isNotBlank()) RowAction("清除", danger = true) { onClear() } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt index 6b68362..0ef8630 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt @@ -1,4 +1,4 @@ -package com.doubao.lynxclone.ui +package com.doubao.lynxclone.ui import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background @@ -72,15 +72,13 @@ import com.doubao.lynxclone.data.VoiceOption */ @Composable fun AgentsScreen(vm: AppViewModel) { - var editing by remember { mutableStateOf(null) } - var creating by remember { mutableStateOf(false) } var confirmDelete by remember { mutableStateOf(null) } val activeId = vm.state.activeAgent?.id.orEmpty() Column(Modifier.fillMaxSize()) { ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) { - TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) } + TextButton(onClick = { vm.openAgentEdit(null) }) { Text("新建", fontSize = 13.sp) } } Column( @@ -103,7 +101,7 @@ fun AgentsScreen(vm: AppViewModel) { agent = agent, active = agent.id == activeId, onUse = { vm.useAgent(agent.id) }, - onEdit = { editing = agent }, + onEdit = { vm.openAgentEdit(agent) }, onDelete = { confirmDelete = agent }, ) } @@ -113,7 +111,7 @@ fun AgentsScreen(vm: AppViewModel) { } Button( - onClick = { creating = true }, + onClick = { vm.openAgentEdit(null) }, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(24.dp), contentPadding = PaddingValues(vertical = 12.dp), @@ -129,41 +127,29 @@ fun AgentsScreen(vm: AppViewModel) { } /* ---------------- 新建 / 编辑 ---------------- */ - if (creating || editing != null) { - val target = editing - AgentEditDialog( - agent = target, - providers = vm.state.providers.values.toList(), - voices = vm.state.speechVoices, - voicesAll = vm.state.speechVoicesAll, - globalTtsEngine = vm.state.speech.ttsEngine, - onDismiss = { creating = false; editing = null }, - onSave = { draft -> - vm.saveAgent(target?.id, draft) { - creating = false - editing = null - } - }, - onDelete = if (target != null && !target.builtin) { - { confirmDelete = target } - } else { - null - }, - ) - } + // + // ★ 编辑走的是 **AgentEditScreen(全屏)**,不是这里原来那个弹窗。 + // 字段从 8 个涨到二十多个(外观四件套 / 模型引用 / 世界观 / 限额 / 技能……), + // 弹窗装不下 —— AGENTS.md 那张表写得很清楚。 + // 删除确认**仍然是弹窗**:它就是"一次确认",正好是弹窗该用的地方。 /* ---------------- 删除确认 ---------------- */ confirmDelete?.let { agent -> AlertDialog( onDismissRequest = { confirmDelete = null }, title = { Text("删除智能体", fontSize = 16.sp) }, - text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) }, + text = { + Text( + "确定删除「${agent.name}」吗?\n\n" + + "它的系统提示词和外观会一起删掉,不能撤销。\n" + + "**记忆会保留**(那是你攒下来的东西,删之前建议先导出)。", + fontSize = 13.sp, + ) + }, confirmButton = { TextButton(onClick = { vm.deleteAgent(agent.id) confirmDelete = null - // 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404 - if (editing?.id == agent.id) editing = null }) { Text("删除") } }, dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } }, @@ -255,185 +241,6 @@ private fun ActiveBadge() { */ @OptIn(ExperimentalLayoutApi::class) @Composable -private fun AgentEditDialog( - agent: Agent?, - providers: List, - voices: Map>, - voicesAll: Map>, - /** 全局当前的朗读引擎:智能体没选引擎时,音色列表要按它来给 */ - globalTtsEngine: String, - onDismiss: () -> Unit, - onSave: (Agent) -> Unit, - onDelete: (() -> Unit)?, -) { - // 整份草稿:加字段时只要往 Agent 里加,不用再改一遍这里的所有 var - var draft by remember { - mutableStateOf( - agent ?: Agent(avatar = "doubao"), - ) - } - var error by remember { mutableStateOf("") } - val name = draft.name - val avatar = draft.avatar - val prompt = draft.systemPrompt - val greeting = draft.greeting - - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) }, - text = { - Column(Modifier.verticalScroll(rememberScrollState())) { - FormLabel("头像") - FlowRow( - modifier = Modifier.fillMaxWidth().padding(top = 6.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - AvatarKeys.forEach { key -> - Box(Modifier.clickable { draft = draft.copy(avatar = key) }) { - // 选中态画在 AvatarCircle 的外圈上,不改变尺寸 - AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key) - } - } - } - - Spacer(Modifier.height(10.dp)) - FormLabel("名称") - OutlinedTextField( - value = name, - onValueChange = { draft = draft.copy(name = it) }, - modifier = Modifier.fillMaxWidth().padding(top = 6.dp), - placeholder = { Text("例如:翻译官", fontSize = 13.sp) }, - singleLine = true, - textStyle = TextStyle(fontSize = 14.sp), - ) - - Spacer(Modifier.height(10.dp)) - FormLabel("问候语 / 一句话介绍") - OutlinedTextField( - value = greeting, - onValueChange = { draft = draft.copy(greeting = it) }, - modifier = Modifier.fillMaxWidth().padding(top = 6.dp), - placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) }, - singleLine = true, - textStyle = TextStyle(fontSize = 14.sp), - ) - Text( - "列表摘要会显示这句;新会话首屏也用它打招呼。", - fontSize = 11.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Spacer(Modifier.height(10.dp)) - FormLabel("系统提示词") - OutlinedTextField( - value = prompt, - onValueChange = { draft = draft.copy(systemPrompt = it) }, - modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp), - placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) }, - textStyle = TextStyle(fontSize = 13.sp), - ) - Text( - "和它聊天时,这段提示词会覆盖全局系统提示词。", - fontSize = 11.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - /* ---------------- 模型(留空 = 跟随全局) ---------------- */ - Spacer(Modifier.height(14.dp)) - FormLabel("模型") - Text( - "不选就跟随「设置 → 连接与模型」里的全局配置。", - fontSize = 11.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(6.dp)) - WrapChips( - options = listOf("" to "跟随全局") + - providers.map { it.key to it.label }, - active = draft.provider, - ) { draft = draft.copy(provider = it) } - Spacer(Modifier.height(6.dp)) - // ★ 别把 `ifBlank{…} == "x" ? a : b` 写成一整行:Kotlin 会把那个 `?` - // 当成安全调用开始解析,报一堆看不懂的语法错。拆成变量最稳。 - val followGlobalModel = draft.provider.isBlank() - OutlinedTextField( - value = draft.model, - onValueChange = { draft = draft.copy(model = it) }, - modifier = Modifier.fillMaxWidth(), - placeholder = { - Text( - if (followGlobalModel) "留空 = 用全局模型" else "留空 = 用这家的默认模型", - fontSize = 13.sp, - ) - }, - singleLine = true, - textStyle = TextStyle(fontSize = 14.sp), - ) - - /* ---------------- 语音(留空 = 跟随全局) ---------------- */ - Spacer(Modifier.height(14.dp)) - FormLabel("语音") - Text( - "多人会议里靠它区分谁在说话 —— 几个智能体一个嗓子的话根本听不出谁在讲。", - fontSize = 11.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(6.dp)) - WrapChips( - options = listOf("" to "跟随全局") + TtsEngineChoices, - active = draft.ttsEngine, - ) { engine -> - // 换引擎顺手清掉音色:音色是按引擎命名的(BVxxx / zh_xxx_bigtts), - // 留着上一家的值一定会被判非法 - draft = draft.copy(ttsEngine = engine, ttsVoice = "") - } - val voiceEngine = draft.ttsEngine.ifBlank { globalTtsEngine } - if (voiceEngine != "" && voiceEngine != "system") { - Spacer(Modifier.height(6.dp)) - VoicePickerInline( - engine = voiceEngine, - voices = voices[voiceEngine].orEmpty(), - voicesAll = voicesAll[voiceEngine].orEmpty(), - value = draft.ttsVoice, - onValue = { draft = draft.copy(ttsVoice = it) }, - ) - } - - if (error.isNotBlank()) { - Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error) - } - } - }, - confirmButton = { - TextButton(onClick = { - if (draft.name.isBlank()) { - error = "名称不能为空" - } else { - onSave(draft.copy(name = draft.name.trim(), greeting = draft.greeting.trim())) - } - }) { Text("保存") } - }, - dismissButton = { - Row { - if (onDelete != null) { - TextButton(onClick = onDelete) { - Icon( - Icons.Filled.DeleteOutline, - null, - modifier = Modifier.size(16.dp), - tint = MaterialTheme.colorScheme.error, - ) - Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp) - } - } - TextButton(onClick = onDismiss) { Text("取消") } - } - }, - ) -} - -/** 列表里那一行摘要文案 */ private fun agentSummary(agent: Agent): String = when { agent.greeting.isNotBlank() -> agent.greeting agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手" @@ -495,7 +302,7 @@ internal fun WrapChips( * 拽进智能体页 —— 真要统一的话应该把它提成公共组件,那是另一件事。 */ @Composable -private fun VoicePickerInline( +internal fun VoicePickerInline( engine: String, voices: List, voicesAll: List, diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index 7c687ab..6c15a33 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -234,6 +234,19 @@ fun AppRoot( ) } + // 「智能体编辑」—— 全屏界面(字段二十多个,弹窗装不下,见 AGENTS.md 那张表) + AnimatedVisibility( + visible = vm.agentEditOpen, + enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)), + exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)), + ) { + AgentEditScreen( + vm = vm, + initial = vm.agentEditing, + onDone = { vm.closeAgentEdit() }, + ) + } + // 「用量」详情 —— 选择界面上的「更多」按钮(需求 2.4 / 3.1) AnimatedVisibility( visible = vm.tokenUsageOpen, diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index 6c43d29..b77cfd1 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -16,6 +16,7 @@ import com.doubao.lynxclone.data.MeetingEvent import com.doubao.lynxclone.data.MeetingMeta import com.doubao.lynxclone.data.StreamEvent import com.doubao.lynxclone.data.ToolTrace +import com.doubao.lynxclone.data.toJson import com.doubao.lynxclone.termux.AiSurface import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -140,6 +141,105 @@ class AppViewModel(val client: KernelClient) : ViewModel() { /* -------------------- 智能体系统(需求 v1.1)-------------------- */ + /** + * 智能体编辑界面(全屏)。 + * + * [agentEditing] 为 null = 新建。 + * + * ★ 用浮层状态而不是 `Screen` 枚举:这样「返回」是回到**智能体列表**, + * 而不是一路弹回聊天页(用 Screen 的话返回目标写死在 AppRoot 的路由里)。 + */ + var agentEditOpen by mutableStateOf(false) + private set + var agentEditing by mutableStateOf(null) + private set + + fun openAgentEdit(agent: com.doubao.lynxclone.data.Agent?) { + agentEditing = agent + agentEditOpen = true + } + + fun closeAgentEdit() { + agentEditOpen = false + agentEditing = null + } + + /** + * 保存一个智能体(全屏编辑界面用,需求 2.5 / 3.1 / 3.3 / 3.5 / 3.6 / 3.7)。 + * + * ★ 这一份**取代**了老的 `saveAgent(id, draft)`:那次只发 8 个字段, + * 加字段就得改一处、漏一处。现在一次把**全部字段**发过去, + * 内核的 `_apply_agent_patch` 按类型规整(两边都只有一份字段表)。 + * + * ★ 三件事的**顺序**有讲究: + * ① 先建/改智能体本身(拿到 id) + * ② 再写 Skill 绑定(它要 agentId,而且存在另一张表里) + * ③ 图片是**选的时候就已经单独上传**了(见 uploadAgentAsset)—— + * 不放在保存里,是因为字节大、传得慢,用户会以为"保存卡住了" + */ + fun saveAgentFull(agent: com.doubao.lynxclone.data.Agent, isNew: Boolean, onDone: (Boolean) -> Unit) { + viewModelScope.launch { + val body = JSONObject() + .put("name", agent.name) + .put("description", agent.description) + .put("tagline", agent.greeting) + .put("systemPrompt", agent.systemPrompt) + .put("avatar", agent.avatar) + .put("provider", agent.provider) + .put("model", agent.model) + .put("baseUrl", agent.baseUrl) + .put("ttsEngine", agent.ttsEngine) + .put("ttsVoice", agent.ttsVoice) + .put("modelId", agent.modelId) + .put("worldviewId", agent.worldviewId) + .put("emotionEnabled", agent.emotionEnabled) + .put("tokenLimit", agent.tokenLimit) + // ★ 外观四件套:键名带连字符(需求 2.5 定的包格式), + // 转换只有 AgentImage.toJson() 这一处 + .put("image", agent.image.toJson()) + val ok = runCatching { + withContext(Dispatchers.IO) { + val saved = if (isNew) client.createAgent(body) else client.updateAgent(agent.id, body) + // ② Skill 绑定(需求 3.7:一个智能体可绑多个,**按绑定顺序**注入) + if (saved.id.isNotBlank()) { + client.bindSkills(saved.id, agent.skillIds) + } + saved + } + }.isSuccess + refresh() + if (!ok) showHint("保存失败") + onDone(ok) + } + } + + /** + * 上传一张外观图(需求 2.5)。**选完立刻传**,不等保存。 + * + * ★ 只对已存在的智能体可用 —— 新建时还没有 id,没法落到它的资源目录。 + * 界面在"新建"模式下把外观区藏起来并说明原因(比报一个错友好)。 + */ + fun uploadAgentAsset(agentId: String, key: String, name: String, base64: String) { + viewModelScope.launch { + val saved = runCatching { + withContext(Dispatchers.IO) { client.setAgentAsset(agentId, key, name, base64) } + }.getOrNull() + if (saved == null) showHint("这张图没传上去") else refresh() + } + } + + /** 删除一个智能体(内核会拒绝删内置的,这里把原因显示出来) */ + fun deleteAgentFull(agentId: String, onDone: () -> Unit) { + viewModelScope.launch { + val err = runCatching { + withContext(Dispatchers.IO) { client.deleteAgent(agentId) } + }.exceptionOrNull() + if (err != null) showHint(err.message ?: "删不掉") + refresh() + onDone() + } + } + /** * 选择界面上"开始对话":把这个人设为当前,然后回聊天页。 * diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index e9fafa7..9514f68 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -329,6 +329,9 @@ fun ChatScreen(vm: AppViewModel) { ) } } else { + // 本次对话的用量(需求 4.1)跟着输入条一起显示 —— + // 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口 + SessionUsageBar(vm) InputBar(vm, onPickFile, onMic, speech) } } @@ -758,6 +761,51 @@ private fun AttachmentStrip(vm: AppViewModel) { } } +/** + * 本次对话的 Token 用量(需求 4.1)。 + * + * ## 为什么按消息加起来,而不是问内核要一个"会话总数" + * + * 因为用量是**按轮记在消息上的**(内核落库时就这么存的)。加起来算有两个好处: + * · "重新生成"把上一条替换掉时,它的消耗自动消失,不会虚高 + * · 删掉某条消息、切换会话、界面刷新,都不需要额外请求 + * + * ## 为什么没有用量时**整行不显示** + * + * 一条消息都还没发(或者老数据里没记用量)时显示"入 0 · 出 0"是纯噪音。 + * 需求要的是"能看到用了多少",不要求一直占一行。 + */ +@Composable +private fun SessionUsageBar(vm: AppViewModel) { + val inTok = vm.messages.sumOf { it.usage?.first ?: 0L } + val outTok = vm.messages.sumOf { it.usage?.second ?: 0L } + if (inTok == 0L && outTok == 0L) return + + Row( + Modifier + .fillMaxWidth() + .padding(start = 20.dp, end = 20.dp, bottom = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text("本次对话", fontSize = 10.sp, color = Doubao.TextTertiary) + Spacer(Modifier.width(8.dp)) + Text("输入 ${fmtTokens(inTok)}", fontSize = 10.sp, color = Doubao.TextTertiary) + Spacer(Modifier.width(8.dp)) + Text("输出 ${fmtTokens(outTok)}", fontSize = 10.sp, color = Doubao.TextTertiary) + Spacer(Modifier.weight(1f)) + // 点一下看智能体的**累计**用量(那个在「更多」里,需求 3.1) + Text( + "累计 ›", + fontSize = 10.sp, + color = Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { vm.activeAgent?.id?.let { vm.openTokenUsage(it) } } + .padding(horizontal = 4.dp, vertical = 2.dp), + ) + } +} + @Composable private fun InputBar( vm: AppViewModel, diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt index a229b13..da55cdc 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt @@ -1,4 +1,4 @@ -package com.doubao.lynxclone.ui +package com.doubao.lynxclone.ui import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -104,7 +104,7 @@ fun MemoryScreen( .padding(10.dp), ) { Text( - "这个智能体绑定了世界观,记忆是**和同世界观的其他智能体共用**的。\n" + + "这个智能体绑定了世界观,记忆是和同世界观的其他智能体共用的。\n" + "它能改自己写的条目;改别人的(或删)需要你在这里手动操作。", fontSize = 11.sp, lineHeight = 16.sp, diff --git a/android/kernel/agent_api.py b/android/kernel/agent_api.py index 6b9cb5e..c08b747 100644 --- a/android/kernel/agent_api.py +++ b/android/kernel/agent_api.py @@ -371,6 +371,10 @@ def handle(handler, pathname: str, method: str) -> bool: if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'package' and method == 'GET': return _export_agent(handler, seg[2], err) + # ---------------- 外观图片(四件套)---------------- + if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST': + return _set_asset(handler, seg[2], body(), err) + # ---------------- 单条记忆 ---------------- if seg[1] == 'memories' and len(seg) == 3: mid = seg[2] @@ -727,6 +731,62 @@ def _export_agent(handler, agent_id: str, err) -> bool: }) +#: 外观四件套的槽位名(和需求 2.5 的 smartInfo.json 一一对应) +ASSET_KEYS = ('front', 'back', 'border-main', 'border-info') + + +def _set_asset(handler, agent_id: str, body: dict, err) -> bool: + """ + 设置外观四件套里的**一个槽位**(需求 2.5)。 + + 界面把图片读成 base64 发过来,这里落盘到 `agent-assets//`, + 再把**路径**写进 `agent.image`。 + + ★ 存路径不存字节:展示区和列表每次都要显示它,每次从 base64 解一遍太贵。 + ★ `data` 传空 = **清掉这个槽位**(回到内置默认 / 方框)—— + 这是"我不想要这张图了"的唯一出口,不给的话用户只能换、不能删。 + """ + agent = store.get_agent(agent_id) + if not agent: + err(404, '没有这个智能体') + return True + key = str(body.get('key') or '').strip() + if key not in ASSET_KEYS: + err(400, f'不认识的外观槽位:{key}(可选:{"、".join(ASSET_KEYS)})') + return True + + image = dict(agent.get('image') or {}) + raw = body.get('data') or body.get('base64') or '' + if not raw: + old = image.pop(key, '') + if old and os.path.isfile(old): + try: + os.remove(old) + except OSError: + pass + return _send_json_ok(handler, {'agent': store.update_agent(agent_id, {'image': image}), 'cleared': True}) + + try: + blob = base64.b64decode(raw) + except Exception as exc: # noqa: BLE001 + err(400, f'图片数据解不开:{exc}') + return True + if len(blob) > 20 * 1024 * 1024: + err(400, '图片太大了(上限 20MB)') + return True + + name = _safe_segment(str(body.get('name') or f'{key}.png')) + dest = os.path.join(_asset_dir(agent_id), f'{key}-{name}') + with open(dest, 'wb') as fh: + fh.write(blob) + image[key] = dest + return _send_json_ok(handler, { + 'agent': store.update_agent(agent_id, {'image': image}), + 'path': dest, + 'bytes': len(blob), + }) + + def _import_agent(handler, body, err) -> bool: """ 导入智能体包(需求 2.5)。 diff --git a/scripts/build-apk.mjs b/scripts/build-apk.mjs index 672f50d..99e830e 100644 --- a/scripts/build-apk.mjs +++ b/scripts/build-apk.mjs @@ -49,6 +49,37 @@ if (!skipBuild) { log('界面是原生 Compose,无需构建前端产物'); } +/* ---------------- 1.5 Python 内核的语法自检 ---------------- */ +// +// ★★ 为什么构建脚本要管这件事:内核是 Python,而**构建阶段根本不编译它** —— +// Chaquopy 只是把 .py 打进 APK,语法错误要等手机上"启动内核"那一刻才炸。 +// +// 实测漏过一次:`agent_api.py` 里有个 IndentationError, +// Gradle 报 BUILD SUCCESSFUL、APK 也正常产出,装到手机上打开就是 +// 「本地内核启动失败:IndentationError」—— 整机不可用。 +// 而 Kotlin 那边一个类型不对就编不过,落差太大了。 +// +// 所以这里用**和 Chaquopy 同一个 Python** 先编译一遍:几秒钟的事, +// 把"打包成功但装上打不开"这类问题挡在构建阶段。 +const pyBin = process.env.DOUBAO_PYTHON313 || 'C:\\Python313\\python.exe'; +const kernelDir = path.join(repo, 'android', 'kernel'); +if (!fs.existsSync(kernelDir)) { + throw new Error(`找不到内核目录:${kernelDir}`); +} +const pyFiles = fs.readdirSync(kernelDir).filter((f) => f.endsWith('.py')); +const pyBad = []; +for (const f of pyFiles) { + const r = spawnSync(pyBin, ['-m', 'py_compile', path.join(kernelDir, f)], { encoding: 'utf8' }); + if (r.status !== 0) { + const msg = String(r.stderr || r.stdout || '').trim().split('\n').filter(Boolean).pop() || '未知错误'; + pyBad.push(`${f}: ${msg}`); + } +} +if (pyBad.length) { + throw new Error(`Python 内核有语法错误,先修好再打包:\n ${pyBad.join('\n ')}`); +} +log(`Python 语法自检通过(${pyFiles.length} 个文件)`); + /* ---------------- 2. 同步工程到 ASCII 路径 ---------------- */ /** 手写递归拷贝:fs.cpSync 带 filter 时在这套环境下会把 Node 直接搞崩(0xC0000409) */ function copyTree(from, to, skipDirs) { diff --git a/scripts/migrate-drop-agent-dialog.py b/scripts/migrate-drop-agent-dialog.py new file mode 100644 index 0000000..02f4cc9 --- /dev/null +++ b/scripts/migrate-drop-agent-dialog.py @@ -0,0 +1,77 @@ +"""删掉 AgentsScreen 里那个被全屏界面取代的 AgentEditDialog。 + +★ 带断言:首尾内容对不上就整个中止,一个字节都不写。 + 这个仓库里"按行号剪贴算错下标"的坑踩过(把整个文件追加过一遍), + 所以任何批量删除都必须先断言。 + +用法: + python scripts/migrate-drop-agent-dialog.py # 预演 + python scripts/migrate-drop-agent-dialog.py --write +""" +import io +import os +import sys + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +HERE = os.path.dirname(os.path.abspath(__file__)) +KT = os.path.join( + HERE, "..", "android", "app", "src", "main", "java", + "com", "doubao", "lynxclone", "ui", "AgentsScreen.kt", +) + + +def main(): + write = "--write" in sys.argv + with io.open(KT, encoding="utf-8") as fh: + lines = fh.read().split("\n") + + start = None + for i, line in enumerate(lines): + if line.startswith("private fun AgentEditDialog("): + # 连它上面的 @Composable 一起删 + start = i - 3 if i >= 3 and lines[i - 3].strip() == "@Composable" else i + break + if start is None: + print("找不到 AgentEditDialog —— 可能已经删过了") + return 1 + + # 结束:下一个顶层 private fun / @Composable 之前 + end = None + for j in range(start + 1, len(lines)): + s = lines[j] + if s.startswith("private fun ") or s.startswith("fun ") or s.startswith("internal fun "): + end = j + break + if end is None: + print("找不到下一个顶层函数,无法确定结束位置") + return 1 + + print(f"将删除第 {start + 1} 行到第 {end} 行(共 {end - start} 行)") + print(f" 起始:{lines[start].strip()[:70]}") + print(f" 末行:{lines[end - 1].strip()[:70]}") + print(f" 下一段:{lines[end].strip()[:70]}") + + # 断言:这段里必须有 AgentEditDialog 的特征 + body = "\n".join(lines[start:end]) + for must in ("AgentEditDialog", "AlertDialog", "onSave", "systemPrompt"): + if must not in body: + print(f"!! 断言失败:待删段落里没有 {must}") + return 1 + + if not write: + print("(预演模式,没有写文件。加 --write 才真写)") + return 0 + + del lines[start:end] + with io.open(KT, "w", encoding="utf-8", newline="") as fh: + fh.write("\n".join(lines)) + print(f"已写入,剩 {len(lines)} 行") + return 0 + + +if __name__ == "__main__": + sys.exit(main())