feat(agent-v1.1): 第二阶段 —— 全屏编辑界面 + 会话用量显示 + 构建期 Python 自检

## 界面

- 新增 AgentEditScreen:智能体的**全屏**编辑界面。字段从 8 个涨到二十多个
  (基本信息 / 外观四件套 / 人设 / 模型引用 / 世界观绑定 / 情绪开关 / Token 限额 /
  技能多选 / 音色),弹窗装不下 —— AGENTS.md 那张表写得很清楚。
  三处容易困惑的地方在界面上直接说清:介绍文案 vs 一句话介绍、
  绑世界观 = 记忆变共享、限额留空 = 无限制。
- 新增 Provider「设置外观图片」接口(/api/agents/<id>/asset):
  选图 → 读字节 → base64 → **立刻上传**(不等保存,图可能好几 MB)。
  传空 data = 清除该槽位(回到内置默认),这是"我不想要这张图了"的唯一出口。
- 会话级 Token 用量(需求 4.1):输入框上方一行小字(输入/输出分列),
  点「累计 ›」进智能体累计用量页。**按消息加起来算**,所以"重新生成"
  替换上一条时消耗自动消失,不会虚高。
- 删掉 AgentsScreen 里那个被取代的 AgentEditDialog(179 行)——
  用带断言的脚本删(scripts/migrate-drop-agent-dialog.py),
  不留死代码,也不冒"按行号剪贴算错下标"的险。

## ★★ 一个必须记下来的教训:Python 语法错误构建阶段不报

加 /api/agents/<id>/asset 时手滑把函数签名和 docstring 挤到了一行
(上一个"删空行"的 edit 把换行吃掉了),结果:

    Gradle: BUILD SUCCESSFUL          ← 完全看不出来
    APK: 正常产出、正常安装
    打开 App:「本地内核启动失败:IndentationError (agent_api.py, line 797)」

**Gradle 不编译 Python**(Chaquopy 只是把 .py 打进 APK),所以这类错误
一路畅通到手机上才炸,而且炸的是整个内核 —— App 直接不可用。
Kotlin 那边一个类型不对就编不过,落差太大。

修法:scripts/build-apk.mjs 里加一道 **Python 语法自检**(用和 Chaquopy
同一个解释器 py_compile 一遍内核里所有 .py,几秒钟),有错直接中止构建。
以后不用靠人记得跑。

顺带:我自己那次也是"改完没跑 py_compile 就构建"——探针脚本能覆盖运行时,
但覆盖不了"根本 import 不进来",所以语法检查必须在构建这一层。

## 其它

- VoicePickerInline 从 private 改 internal(编辑界面要复用;它是既有的
  音色选择器,这里只选音色不选引擎 —— 引擎属于全局设置,
  混在一起必然出现"换了引擎、音色还是上一家的")。
- 用户可见文案里的字面 `**` 去掉(普通 Text 不渲染 Markdown)。

验证:探针 11 节 60+ 项全绿;装机确认内核恢复、管理列表、全屏编辑界面
(基本信息 + 外观槽位带预览与清除)。
This commit is contained in:
l
2026-10-16 12:59:54 +08:00
parent a87eca329a
commit ef42aa70ca
9 changed files with 817 additions and 213 deletions

View File

@@ -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<Pair<String, String>>,
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() }
}
}
}

View File

@@ -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<Agent?>(null) }
var creating by remember { mutableStateOf(false) }
var confirmDelete by remember { mutableStateOf<Agent?>(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<ProviderPreset>,
voices: Map<String, List<VoiceOption>>,
voicesAll: Map<String, List<VoiceOption>>,
/** 全局当前的朗读引擎:智能体没选引擎时,音色列表要按它来给 */
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<VoiceOption>,
voicesAll: List<VoiceOption>,

View File

@@ -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,

View File

@@ -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<com.doubao.lynxclone.data.Agent?>(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()
}
}
/**
* 选择界面上"开始对话":把这个人设为当前,然后回聊天页。
*

View File

@@ -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,

View File

@@ -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,