feat(agent-v1.1): 智能体系统第一阶段 —— 数据层 + 7 个工具 + 选择界面

按《智能体系统需求文档 v1.1》实现。这一阶段打通了"内核数据 → 接口 → 界面"整条链路。

## 内核

- 新增 agentdb.py:智能体系统的 SQLite 层(记忆 / 情绪 / Token 统计 / Skill 绑定)。
  **为什么这次用 SQLite 而别处还是 JSON**(store.py 顶上写着 JSON 的理由):
  记忆是"条目无上限 + 每轮全量注入 + 要 LIKE 检索 + 要行级改删",
  那三条都指向 SQLite;而设置/会话/智能体的量级仍然是"几个到几十个"、
  且要人肉可读,继续留在 JSON。分界线写在 agentdb.py 的文件头。
- 新增 agent_context.py:按需求附录 C 拼 system prompt
  (人设 → skills → worldview → emotion → memory → peer_emotions,**空段整段删掉**,每轮重拼)。
- 新增 agent_tools.py:7 个内置工具(memory_add/update/forget/search、
  memory_suggest_summary、emotion_set、get_token_usage)。
  走进程内实现是因为它们要读写 agent.db,而电脑端的文件工具是子进程。
  共享记忆的写入限权(只能改自己写的)+ pinned 保护都在这里。
- 新增 agent_api.py:20+ 个 HTTP 接口(记忆 CRUD/导出导入/整理、情绪、
  Token 用量、世界观/模型列表/Skill 的 CRUD 与包导入导出)。
  app.py 的老 /api/agents 三个路由删掉,统一由它处理(顺便补上"内置不能删")。
- store.py:Agent 字段按类型分开的 _apply_agent_patch(create/update 共用)、
  三种资源的通用 CRUD、create_agent 改用 **UUID**(需求附录 A)、
  delete_agent 清理绑定关系但**不删记忆**。
- Token:usage 从"只留最后一轮"改成**累加**(多轮工具调用的消耗是大头,
  以前全丢);落库时按轮记在消息上(会话级 = 加起来,重新生成不会虚高)
  + 计入智能体累计(按模型分桶、输入输出分开);超限时**发起前**拦住,
  附一条带语气的告别消息并给界面明确的 token_limit 错误(需求 3.1)。
- 会议节点的 system prompt 也改用 agent_context(以前是自己拼的,
  同一个智能体在会议里没有记忆/情绪/世界观)。
- doubao_entry:web_search.py 补进 BUNDLED_TOOL_FILES(对拍脚本抓出的清单不一致)。

## 安卓

- AgentSelectScreen:智能体选择界面(需求第二章)——
  左列表 + 右侧四层叠加(背景/主体边框/角色图/介绍边框),
  1.5s 四阶段切换动画(0.3 出 / 0.5 间隔 / 0.4 边框 / 0.3 入,方向按列表顺序,
  连点立即打断并从当前视觉状态续走),圆形「更多」按钮,默认资源回退。
- AssetImage:本地图片显示。**不引 Coil/Glide**(项目零第三方依赖)——
  PNG/JPG 走 BitmapFactory,GIF 走 ImageDecoder(API28+ 能播动图,以下退化成首帧),
  SVG 走 WebView(原生解不了)。
- TokenUsageScreen / MemoryScreen:用量详情(输入输出分列、按模型分行、
  限额进度、配了单价才估费用)+ 记忆管理(情绪编辑、整理、导入导出、
  pinned 开关、共享记忆提示)。
- Models.kt / KernelClient.kt / AppViewModel.kt:全部新字段与新接口。
- 入口:抽屉「智能体」→ 选择界面;聊天页顶栏点名字 → 选择界面
  (以前点开的是「模型」面板 —— 那是"换脑子"不是"换人")。
- 需求文档给的两张默认资源图进 res/drawable(2.3MB)。

## 验证

- 新增 scripts/probe-agent-system.py:11 节 60+ 项断言,**不装机**跑完整链路
  (临时数据目录 + 假 Handler)。覆盖:UUID 主键、记忆增删改查检索、
  pinned 保护、共享记忆与写入限权、system prompt 五段注入与顺序、
  20 多个接口、包的导出导入边界(模型引用/世界观/限额**不进包**)、
  记忆导入的合并去重、资源 CRUD。全绿。
- 装机验证:选择界面四层叠加、默认资源回退、切换动画与高亮。

## 还没做(下一阶段)

世界观/Skill/模型列表的管理界面、对话页会话级用量显示、智能体编辑界面扩展
(介绍/外观/模型引用/世界观/限额/技能绑定)、包的导入导出界面、
幻觉调用检测、不支持 function calling 的兼容降级、Node 端跟上。
This commit is contained in:
l
2026-10-16 12:36:55 +08:00
parent 2a25cf623f
commit fd72ad06a1
21 changed files with 4189 additions and 45 deletions

View File

@@ -0,0 +1,460 @@
package com.doubao.lynxclone.ui
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.doubao.lynxclone.R
import com.doubao.lynxclone.data.AgentImage
import com.doubao.lynxclone.data.Agent
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/*
* 智能体选择界面(需求第二章)。
*
* ## 布局(需求 2.1)
*
* 左侧:智能体列表(纵向、当前项高亮)
* 右侧:角色展示区,**四层叠加**:
* ① 背景图(铺满)② 主体边框(框住展示区)③ 角色图(居中)④ 介绍边框(围住介绍文本)
*
* ## 切换动画(需求 2.3,定稿参数)
*
* ① 旧角色图渐出 + 侧移 0.3s ease-in
* ② 间隔 0.5s
* ③ 边框/背景/介绍 滑出滑入 0.4s ease-in-out
* ④ 新角色图渐入 + 侧移到位 0.3s ease-out
* 合计约 1.5s。
*
* **方向**:目标在当前**之下**(列表靠后)→ 向左切换;**之上** → 向右。
*
* **连续快速切换立即打断**:靠 `LaunchedEffect(选中的 id)` —— 换目标时
* 上一个协程直接被取消,而 `Animatable` 会**停在当前值**,所以新动画
* 是从眼前的画面接着走的,不会闪回。这正是需求要的"从当前视觉状态
* 直接过渡到最新目标,不做排队"。
*
* ## ★ 默认资源回退(需求 2.6)
*
* 角色图缺 → 内置默认人物;背景缺 → 内置默认背景;边框缺 → **简单方框**。
* 回退优先级:`smartInfo.json 指定 → 包内同名 → 内置默认`。
* 前两级在内核导入时就落定了(存的是绝对路径),所以这里只做最后一级。
*
* ★ "任何智能体至少能以「默认人物 + 默认背景 + 方框边框」正常展示" ——
* 所以**每个槽位都必须有兜底**,不能出现空白展示区。
*/
/* -------------------------------------------------------------------------- */
/* 动画参数(需求 2.3 说"收进全局配置") */
/* -------------------------------------------------------------------------- */
private const val T_FRONT_OUT = 300 // ① 旧角色图出
private const val T_GAP = 500 // ② 间隔
private const val T_FRAME = 400 // ③ 边框/背景/介绍(滑出 + 滑入各一半)
private const val T_FRONT_IN = 300 // ④ 新角色图进
/** 侧移幅度占展示区宽度的比例。需求只说"侧移",幅度大了像翻页、小了看不出来 */
private const val SHIFT = 0.10f
@Composable
fun AgentSelectScreen(
agents: List<Agent>,
activeId: String,
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
onEnter: (Agent) -> Unit,
/** 「更多」→ Token 用量详情(需求 2.4) */
onMore: (Agent) -> Unit,
/** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */
onManage: () -> Unit,
onBack: () -> Unit,
) {
if (agents.isEmpty()) {
Column(Modifier.fillMaxSize().background(doubaoBg()), verticalArrangement = Arrangement.Center) {
Text("还没有智能体", Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = doubaoText())
Spacer(Modifier.height(12.dp))
Text("点右上角「管理」新建或导入一个", Modifier.fillMaxWidth(),
textAlign = TextAlign.Center, fontSize = 12.sp, color = doubaoTextSecondary())
Spacer(Modifier.height(20.dp))
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
TopAction("去管理", onClick = onManage)
}
}
return
}
val startIndex = agents.indexOfFirst { it.id == activeId }.coerceAtLeast(0)
var picked by remember(agents.size) { mutableStateOf(startIndex) }
// `shown` 是**画面上正在显示**的那个;picked 变了之后要等动画走到第③阶段才换它
var shown by remember(agents.size) { mutableStateOf(startIndex) }
val shownAgent = agents.getOrNull(shown) ?: agents.first()
val pickedAgent = agents.getOrNull(picked) ?: agents.first()
val frontAlpha = remember { Animatable(1f) }
val frontShift = remember { Animatable(0f) }
val frameAlpha = remember { Animatable(1f) }
val frameShift = remember { Animatable(0f) }
val listState = rememberLazyListState()
LaunchedEffect(picked, agents.size) {
if (picked == shown) return@LaunchedEffect
// 目标在列表靠后 = 向左切换(新内容从右边进来)
val dir = if (picked > shown) 1f else -1f
// ① 旧角色图渐出 + 侧移
launch { frontAlpha.animateTo(0f, tween(T_FRONT_OUT, easing = FastOutSlowInEasing)) }
frontShift.animateTo(-dir * SHIFT, tween(T_FRONT_OUT, easing = FastOutSlowInEasing))
// ② 间隔(需求明确定义了这一段留白)
delay(T_GAP.toLong())
// ③ 边框 / 背景 / 介绍:滑出 → 换数据 → 滑入
val half = T_FRAME / 2
launch { frameAlpha.animateTo(0f, tween(half, easing = FastOutSlowInEasing)) }
frameShift.animateTo(-dir * SHIFT, tween(half, easing = FastOutSlowInEasing))
shown = picked
launch { frameAlpha.animateTo(1f, tween(half, easing = LinearOutSlowInEasing)) }
frameShift.animateTo(0f, tween(half, easing = LinearOutSlowInEasing))
// ④ 新角色图渐入 + 侧移到位
frontShift.snapTo(dir * SHIFT)
launch { frontAlpha.animateTo(1f, tween(T_FRONT_IN, easing = LinearOutSlowInEasing)) }
frontShift.animateTo(0f, tween(T_FRONT_IN, easing = LinearOutSlowInEasing))
}
// 选中的那项滚进视野(列表长了之后不滚的话用户看不到自己选了谁)
LaunchedEffect(picked) {
runCatching { listState.animateScrollToItem(picked) }
}
Column(Modifier.fillMaxSize().background(doubaoBg())) {
// ---------------- 顶栏 ----------------
Row(
Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"← 返回",
fontSize = 14.sp,
color = Doubao.Blue,
modifier = Modifier.clip(RoundedCornerShape(8.dp))
.clickable { onBack() }.padding(horizontal = 10.dp, vertical = 8.dp),
)
Spacer(Modifier.weight(1f))
Text(
"选择智能体",
fontSize = 17.sp,
fontWeight = FontWeight.Medium,
color = doubaoText(),
)
Spacer(Modifier.weight(1f))
TopTextAction("管理", onClick = onManage)
}
// ---------------- 展示区 ----------------
Box(
Modifier
.fillMaxWidth()
.weight(1f)
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(18.dp)),
) {
// ① 背景图(最底层,铺满)—— 缺就用内置默认背景
ArtworkFill(shownAgent.image.back, R.drawable.agent_default_background)
// ② 左侧列表(浮在背景上)
AgentList(
agents = agents,
picked = picked,
onPick = { picked = it },
state = listState,
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
)
// ③ 角色图(居中)。★ 它和右侧的边框/介绍一起跟着 frameShift 动
Box(
Modifier
.fillMaxSize()
.padding(start = 96.dp, end = 10.dp, top = 10.dp, bottom = 10.dp),
) {
Box(
Modifier
.fillMaxSize()
.offset(x = (frameShift.value * 180).dp)
.alpha(frameAlpha.value),
) {
// ③-1 角色图
Box(
Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp),
) {
ArtworkFill(
shownAgent.image.front,
R.drawable.agent_default_character,
alpha = frontAlpha.value,
scale = ContentScale.Fit,
)
}
// ③-2 介绍边框 + 介绍文本(需求 2.1 的第 4 层)
IntroCard(
agent = shownAgent,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(end = 6.dp, bottom = 10.dp)
.width(200.dp),
)
// ③-3 主体边框(画在最上层,纯装饰)
MainBorder(shownAgent.image.borderMain)
}
}
// ④ 「更多」按钮(需求 2.4:圆形、竖排三点、在角色图附近)→ Token 用量
Box(
Modifier
.align(Alignment.TopEnd)
.padding(top = 10.dp, end = 12.dp)
.size(34.dp)
.clip(CircleShape)
.background(Color(0xCC1B2430))
.clickable { onMore(shownAgent) },
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.MoreVert,
contentDescription = "用量详情",
tint = Color(0xFFE8EAED),
modifier = Modifier.size(20.dp),
)
}
}
// ---------------- 底部:进入对话 ----------------
Row(
Modifier.fillMaxWidth().padding(12.dp),
horizontalArrangement = Arrangement.Center,
) {
Box(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(26.dp))
.background(
Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))),
)
.clickable { onEnter(pickedAgent) }
.padding(vertical = 14.dp),
contentAlignment = Alignment.Center,
) {
Text(
"开始对话",
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
color = Color.White,
)
}
}
}
}
/* -------------------------------------------------------------------------- */
/* 四层的具体画法 */
/* -------------------------------------------------------------------------- */
/** 铺满一层图;没有就用内置默认(需求 2.6 的最后一级回退) */
@Composable
private fun ArtworkFill(
path: String,
fallbackRes: Int,
alpha: Float = 1f,
scale: ContentScale = ContentScale.Crop,
) {
Box(Modifier.fillMaxSize().alpha(alpha)) {
AssetImage(
path = path,
modifier = Modifier.fillMaxSize(),
contentScale = scale,
fallback = {
// ★ 内置默认图:**必须画出来**,不能是空白 ——
// 需求原话"任何智能体至少能以默认人物+默认背景+方框边框正常展示"
Image(
painter = painterResource(fallbackRes),
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = scale,
)
},
)
}
}
/** 主体边框。缺的时候用**简单方框**(纯色细线矩形)兜底 */
@Composable
private fun MainBorder(path: String) {
val shape = RoundedCornerShape(18.dp)
if (canShowImage(path)) {
AssetImage(
path = path,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds,
fallback = { SimpleFrame(shape) },
)
} else {
SimpleFrame(shape)
}
}
@Composable
private fun SimpleFrame(shape: RoundedCornerShape) {
Box(
Modifier
.fillMaxSize()
.border(1.dp, Doubao.Blue.copy(alpha = 0.45f), shape),
)
}
/**
* 介绍卡片(需求 2.1 的"介绍边框 + 介绍文本")。
*
* 文本来自 `description`;缺失时**只显示智能体名**(需求原文)。
*/
@Composable
private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
Column(
modifier
.clip(RoundedCornerShape(14.dp))
.background(Color(0xE6FFFDF5))
.border(1.dp, Color(0x66B9A46A), RoundedCornerShape(14.dp))
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Text(
agent.name,
fontSize = 15.sp,
fontWeight = FontWeight.Medium,
color = Color(0xFF2A2419),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val desc = agent.description.trim().ifBlank { agent.greeting.trim() }
if (desc.isNotBlank()) {
Spacer(Modifier.height(6.dp))
Text(
desc,
fontSize = 11.sp,
lineHeight = 16.sp,
color = Color(0xFF4A4232),
maxLines = 6,
overflow = TextOverflow.Ellipsis,
)
}
}
}
/** 左侧列表:一张卡片 = 缩略图 + 名字;当前项高亮 */
@Composable
private fun AgentList(
agents: List<Agent>,
picked: Int,
onPick: (Int) -> Unit,
state: androidx.compose.foundation.lazy.LazyListState,
modifier: Modifier = Modifier,
) {
LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) {
itemsIndexed(agents) { index, agent ->
val on = index == picked
Column(
Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.background(if (on) Color(0xCC2B7BFF) else Color(0x99101820))
.border(
width = if (on) 1.5.dp else 0.5.dp,
color = if (on) Color(0xFFFFE08A) else Color(0x33FFFFFF),
shape = RoundedCornerShape(12.dp),
)
.clickable { onPick(index) }
.padding(4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(
Modifier
.fillMaxWidth()
.height(52.dp)
.clip(RoundedCornerShape(9.dp))
.background(Color(0x33FFFFFF)),
) {
// 缩略图:也用角色图(缺就默认人物)—— 和右侧是同一套回退。
// ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会
// 裁出"腰到大腿",一排缩略图全是裤子
AssetImage(
path = agent.image.front,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter,
fallback = {
Image(
painter = painterResource(R.drawable.agent_default_character),
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter,
)
},
)
}
Spacer(Modifier.height(3.dp))
Text(
agent.name.ifBlank { "未命名" },
fontSize = 11.sp,
color = Color.White,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
)
}
}
}
}

View File

@@ -72,6 +72,43 @@ fun AppRoot(
val vm = rememberAppViewModel(client)
LaunchedEffect(Unit) { vm.refresh() }
/* ---------------- 记忆的导入 / 导出(SAF)----------------
*
* ★ 为什么用系统的文件选择器而不是自己写路径:安卓 11+ 已经不给
* App 随便写公共目录了,SAF 是唯一"用户想存哪就存哪"的正路
* (会议导出、节点导出都是这条路,见 MeetingsScreen)。
* ★ 编码固定 UTF-8:记忆里有中文,用默认编码在别的机器上会变乱码。
*/
val ctx = androidx.compose.ui.platform.LocalContext.current
var pendingExport by remember { mutableStateOf<String?>(null) }
val createMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json"),
) { uri ->
val text = pendingExport
pendingExport = null
if (uri != null && text != null) {
runCatching {
ctx.contentResolver.openOutputStream(uri)?.use { it.write(text.toByteArray(Charsets.UTF_8)) }
}.onFailure { vm.showHint("导出失败:${it.message ?: "写不进去"}") }
.onSuccess { vm.showHint("记忆已导出") }
}
}
val importMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
) { uri ->
if (uri != null) {
runCatching {
ctx.contentResolver.openInputStream(uri)?.use { input ->
input.readBytes().toString(Charsets.UTF_8)
} ?: ""
}.onSuccess { text ->
// ★ 默认**合并**(需求 3.4 定的默认值):按标题去重、保留现有。
// 覆盖是破坏性的,不该是默认 —— 用户点错一次就全没了。
if (text.isNotBlank()) vm.importMemories(text, "merge")
}.onFailure { vm.showHint("读不出这个文件") }
}
}
// 提示条 2.5 秒后自动消失
LaunchedEffect(vm.hint) {
if (vm.hint.isNotBlank()) {
@@ -104,6 +141,15 @@ fun AppRoot(
Screen.Settings -> SettingsScreen(vm)
Screen.Skills -> SkillsScreen(vm)
Screen.Agents -> AgentsScreen(vm)
// 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画
Screen.AgentSelect -> AgentSelectScreen(
agents = vm.agents,
activeId = vm.state.settings.activeAgentId,
onEnter = { vm.enterAgent(it.id) },
onMore = { vm.openTokenUsage(it.id) },
onManage = { vm.screen = Screen.Agents },
onBack = { vm.screen = Screen.Chat },
)
Screen.Meetings -> MeetingsScreen(vm)
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
}
@@ -188,6 +234,54 @@ fun AppRoot(
)
}
// 「用量」详情 —— 选择界面上的「更多」按钮(需求 2.4 / 3.1)
AnimatedVisibility(
visible = vm.tokenUsageOpen,
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
) {
TokenUsageScreen(
usage = vm.tokenUsage,
onReset = { vm.tokenUsage?.agentId?.takeIf { it.isNotBlank() }?.let { vm.resetTokenUsage(it) } },
onBack = { vm.closeTokenUsage() },
)
}
// 「记忆」管理(需求 3.2 的"用户手动编辑兜底")
AnimatedVisibility(
visible = vm.memoryAgentId.isNotBlank(),
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
) {
MemoryScreen(
space = vm.memorySpace,
agentName = vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "",
loading = vm.memoryLoading,
hint = vm.memoryHint,
onSetEmotion = { vm.setEmotion(it) },
onAdd = { t, c -> vm.addMemory(t, c) },
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
onDelete = { vm.deleteMemory(it) },
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
onSummarize = { vm.summarizeMemories() },
onExport = { vm.exportMemories { text -> pendingExport = text } },
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
onBack = { vm.closeMemories() },
)
}
// 拿到 JSON 之后再弹存盘对话框(先有内容才能给文件名,顺序不能反)
LaunchedEffect(pendingExport) {
val text = pendingExport ?: return@LaunchedEffect
if (text.isNotBlank()) {
runCatching {
createMemoryDoc.launch(
"${vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "agent"}-记忆.json",
)
}
}
}
// 「超时」—— 所有超时都能调(入口在设置页)
AnimatedVisibility(
visible = vm.timeoutsOpen,
@@ -305,7 +399,9 @@ private fun DrawerOverlay(vm: AppViewModel) {
SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
vm.screen = Screen.Agents; vm.drawerOpen = false
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
vm.screen = Screen.AgentSelect; vm.drawerOpen = false
}
// 「笔记」—— 用户要能查看 AI 替他记了什么
DrawerItem(Icons.Filled.EditNote, "笔记") {

View File

@@ -27,8 +27,8 @@ import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */
enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal, Meetings }
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应;AgentSelect 是需求 v1.1 新增的选择页) */
enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Terminal, Meetings }
/**
* 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。
@@ -138,8 +138,184 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
}
}
/* -------------------- 超时(全部可调)-------------------- */
/* -------------------- 智能体系统(需求 v1.1)-------------------- */
/**
* 选择界面上"开始对话":把这个人设为当前,然后回聊天页。
*
* ★ 需求 2.1 的定位是"选择智能体的入口页,**完成选择后进入对话界面**"——
* 所以这里既切人设也切页面,用户不用自己再点一次返回。
*/
fun enterAgent(agentId: String) {
useAgent(agentId)
screen = Screen.Chat
}
/** 用量详情(选择界面「更多」按钮,需求 3.1) */
var tokenUsage by mutableStateOf<com.doubao.lynxclone.data.TokenUsage?>(null)
private set
var tokenUsageOpen by mutableStateOf(false)
private set
fun openTokenUsage(agentId: String) {
tokenUsageOpen = true
tokenUsage = null
viewModelScope.launch {
tokenUsage = runCatching {
withContext(Dispatchers.IO) { client.tokenUsage(agentId) }
}.getOrNull()
}
}
fun closeTokenUsage() {
tokenUsageOpen = false
}
/** 清零(需求 3.1 的"管理操作",界面会先弹一次确认) */
fun resetTokenUsage(agentId: String) {
viewModelScope.launch {
tokenUsage = runCatching {
withContext(Dispatchers.IO) { client.resetTokenUsage(agentId) }
}.getOrNull() ?: tokenUsage
}
}
/** 记忆空间(列表 + 情绪 + AI 的建议) */
var memorySpace by mutableStateOf<com.doubao.lynxclone.data.MemorySpace?>(null)
private set
/** 正在看谁的记忆(null = 没打开) */
var memoryAgentId by mutableStateOf("")
private set
var memoryLoading by mutableStateOf(false)
private set
/** AI 整理记忆的结果提示("12 条 → 7 条"这种) */
var memoryHint by mutableStateOf("")
private set
fun openMemories(agentId: String) {
memoryAgentId = agentId
memoryHint = ""
refreshMemories()
}
fun closeMemories() {
memoryAgentId = ""
memorySpace = null
}
fun refreshMemories() {
val id = memoryAgentId
if (id.isBlank()) return
memoryLoading = true
viewModelScope.launch {
memorySpace = runCatching {
withContext(Dispatchers.IO) { client.memories(id) }
}.getOrNull()
memoryLoading = false
}
}
fun setEmotion(text: String) {
val id = memoryAgentId
if (id.isBlank()) return
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.setEmotion(id, text) } }
refreshMemories()
}
}
fun addMemory(title: String, content: String) {
val id = memoryAgentId
if (id.isBlank()) return
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.addMemory(id, title, content) } }
refreshMemories()
}
}
fun updateMemory(mid: String, title: String?, content: String?) {
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.updateMemory(mid, title, content) } }
refreshMemories()
}
}
fun deleteMemory(mid: String) {
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.deleteMemory(mid) } }
refreshMemories()
}
}
fun toggleMemoryPin(mid: String, pinned: Boolean) {
viewModelScope.launch {
runCatching { withContext(Dispatchers.IO) { client.pinMemory(mid, pinned) } }
refreshMemories()
}
}
/**
* 让 AI 整理一次记忆(需求 3.2)。
*
* ★ 这是**一次真的 LLM 调用**(会花 Token、要等几秒),所以界面上要给人反馈 ——
* 按钮按下之后显示"整理中…",回来之后报"12 条 → 7 条"。
*/
fun summarizeMemories() {
val id = memoryAgentId
if (id.isBlank()) return
memoryLoading = true
memoryHint = ""
viewModelScope.launch {
val res = runCatching {
withContext(Dispatchers.IO) { client.summarizeMemories(id) }
}.getOrNull()
memoryHint = when {
res == null -> "整理失败(看内核日志)"
res.optBoolean("summarized") ->
"整理好了:${res.optInt("before")} 条 → ${res.optInt("after")} 条" +
if (res.optInt("keptPinned") > 0) "(保留了 ${res.optInt("keptPinned")} 条「必须保留」)" else ""
else -> res.optString("error").ifBlank { res.optString("reason").ifBlank { "没有可整理的记忆" } }
}
memoryLoading = false
refreshMemories()
refresh() // 用量变了,「更多」里要跟着变
}
}
fun exportMemories(onDone: (String) -> Unit) {
val id = memoryAgentId
if (id.isBlank()) return
viewModelScope.launch {
val text = runCatching {
withContext(Dispatchers.IO) { client.exportMemories(id) }
}.getOrNull()
if (text.isNullOrBlank()) showHint("导出失败") else onDone(text)
}
}
fun importMemories(json: String, mode: String) {
val id = memoryAgentId
if (id.isBlank()) return
memoryLoading = true
viewModelScope.launch {
val res = runCatching {
withContext(Dispatchers.IO) { client.importMemories(id, json, mode) }
}.getOrNull()
memoryHint = if (res == null) "导入失败" else {
val err = res.optString("error")
if (err.isNotBlank()) err
else "导入完成:新增 ${res.optInt("added")} 条,跳过重名 ${res.optInt("skipped")} 条"
}
memoryLoading = false
refreshMemories()
}
}
/* -------------------- 超时(全部可调)-------------------- */
/**
* 超时清单 + 当前值。
*

View File

@@ -0,0 +1,226 @@
package com.doubao.lynxclone.ui
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Log
import android.widget.ImageView
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import java.io.File
/*
* 显示智能体/世界观包里的图片资源。
*
* ## ★ 为什么不用 Coil / Glide
*
* 项目一直坚持**零第三方依赖**(安卓端构建要能离线完成、APK 也不要多几百 KB)。
* 而这里要的东西其实很窄:显示一个已知路径的本地图片。
* Android 原生的三套 API 正好够:
*
* · PNG / JPG → `BitmapFactory.decodeFile`(所有版本)
* · GIF 动图 → `ImageDecoder.decodeDrawable`(API 28+,低版本退化成静态第一帧)
* · SVG → 原生**解不了**,走 WebView(项目里已经大量在用 WebView)
*
* ## 为什么静态图不统一走 ImageView
*
* 因为 Compose 的 `Image(bitmap)` 在裁剪/圆角/缩放上比 `AndroidView` 包一层
* 可控得多(`Modifier.clip` / `ContentScale` 直接生效),而 GIF 又必须用
* `Drawable`(Compose 没有原生的动图 Painter,accompanist 是第三方)。
* 所以按扩展名分流:常见的静态图走低成本那条,动图才付出 AndroidView 的代价。
*
* ## 缺失资源的回退(需求 2.6)
*
* 回退是**调用方**的事(`AgentArtwork` 里判的),这里只负责"路径给了就画"。
* 给空路径、文件不存在,这里返回 false 让调用方决定显示什么。
*/
private const val TAG = "DoubaoImage"
/** 这个文件是哪种图(按扩展名,和内核 uploads.py 一个思路) */
private enum class ImageKind { Static, Gif, Svg, Unknown }
private fun kindOf(path: String): ImageKind = when (File(path).extension.lowercase()) {
"gif" -> ImageKind.Gif
"svg" -> ImageKind.Svg
"png", "jpg", "jpeg", "webp", "bmp" -> ImageKind.Static
else -> ImageKind.Unknown
}
/**
* 画一张本地图片。
*
* @param path 绝对路径(内核给的就是绝对路径)
* @param fallback 画不出来时显示什么(通常是默认图或一个占位框)
*/
@Composable
fun AssetImage(
path: String,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
/**
* 裁剪时对齐哪儿。
*
* ★ 缩略图必须给 `TopCenter`:角色图是**竖长**的(头在上半部分),
* 居中对齐裁出来的是"腰到大腿"——列表里一排裤子,谁也认不出是谁。
*/
alignment: Alignment = Alignment.Center,
fallback: @Composable () -> Unit = {},
) {
val file = remember(path) { if (path.isBlank()) null else File(path) }
if (file == null || !file.isFile) {
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
return
}
when (kindOf(path)) {
ImageKind.Svg -> SvgImage(file, modifier)
ImageKind.Gif -> DrawableImage(file, modifier, contentScale, alignment, fallback)
else -> StaticImage(file, modifier, contentScale, alignment, fallback)
}
}
@Composable
private fun StaticImage(
file: File,
modifier: Modifier,
contentScale: ContentScale,
alignment: Alignment,
fallback: @Composable () -> Unit,
) {
// ★ remember(file.path):同一张图不重复解码。列表里滚动时这一下省很多。
val bitmap = remember(file.path) {
runCatching { BitmapFactory.decodeFile(file.path) }.getOrNull()
}
if (bitmap == null) {
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
return
}
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = null,
modifier = modifier,
contentScale = contentScale,
alignment = alignment,
)
}
/**
* 动图(GIF)。
*
* ★ API 28 以下 `ImageDecoder` 不存在 —— 退回 `BitmapFactory` 拿第一帧,
* 至少不是空白。项目 minSdk 是 24,所以这条分支真的会走到。
*/
@Composable
private fun DrawableImage(
file: File,
modifier: Modifier,
contentScale: ContentScale,
alignment: Alignment,
fallback: @Composable () -> Unit,
) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
StaticImage(file, modifier, contentScale, alignment, fallback)
return
}
val drawable: Drawable? = remember(file.path) {
runCatching {
// ★ 宽度在 `info` 上(`ImageDecoder` 自己只有 setTargetSampleSize)——
// 写成 `decoder.width` 是编译不过的
ImageDecoder.decodeDrawable(ImageDecoder.createSource(file)) { decoder, info, _ ->
// 缩到 1024 以内:包里的图可能很大,全尺寸解码在低端机上会 OOM
val w = info.size.width
if (w > 1024) decoder.setTargetSampleSize(kotlin.math.round(w / 1024f).coerceAtLeast(1f).toInt())
}
}.getOrNull()
}
if (drawable == null) {
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
return
}
AndroidView(
modifier = modifier,
factory = { ctx ->
ImageView(ctx).apply {
setImageDrawable(drawable)
scaleType = when (contentScale) {
ContentScale.Crop -> ImageView.ScaleType.CENTER_CROP
ContentScale.FillBounds -> ImageView.ScaleType.FIT_XY
else -> ImageView.ScaleType.FIT_CENTER
}
}
},
// 动图由 Drawable 自己驱动,不需要在 update 里做任何事;
// 但路径变了要换图 —— 这个 composable 的 key 已经是路径,重建即可。
)
}
/**
* SVG。
*
* ★ 原生解不了 SVG(`BitmapFactory` 直接返回 null),而引一个 SVG 库
* 就破了"零第三方依赖"。项目里已经有成熟的 WebView 通道
* (AI 界面就全靠它),所以这里用 WebView 单图显示。
*
* ★ 关掉一切交互:它是**背景/装饰**,不能抢走列表的滑动和点击。
*/
@Composable
private fun SvgImage(file: File, modifier: Modifier) {
AndroidView(
modifier = modifier,
factory = { ctx ->
android.webkit.WebView(ctx).apply {
setBackgroundColor(android.graphics.Color.TRANSPARENT)
settings.javaScriptEnabled = false
settings.allowFileAccess = true
isClickable = false
isFocusable = false
// 让触摸穿透到下面的列表(不然在列表里滑动会被 WebView 吃掉)
setOnTouchListener { _, _ -> false }
loadDataWithBaseURL(
"file://" + file.parent + "/",
"""<html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<style>html,body{margin:0;padding:0;background:transparent;height:100%}
img{width:100%;height:100%;object-fit:contain}</style></head>
<body><img src="${file.name}"></body></html>""",
"text/html", "UTF-8", null,
)
}
},
)
}
/** 占位:没有图时显示一个淡淡的灰框 + 可选文字(需求 2.6 的"简单方框") */
@Composable
fun ImagePlaceholder(modifier: Modifier = Modifier, text: String = "") {
Box(
modifier.then(Modifier.fillMaxSize()),
contentAlignment = Alignment.Center,
) {
if (text.isNotBlank()) {
Text(text, fontSize = 10.sp, color = doubaoTextSecondary())
}
}
}
/** 图片能不能画出来(调用方据此决定要不要回退到默认资源) */
fun canShowImage(path: String): Boolean {
if (path.isBlank()) return false
val f = File(path)
if (!f.isFile) {
Log.w(TAG, "图片不存在:$path")
return false
}
return true
}

View File

@@ -43,6 +43,7 @@ import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
@@ -361,11 +362,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
Spacer(Modifier.weight(1f))
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
// 中间这块点开是**智能体选择界面**(需求 2.1:它是"选择智能体的入口页")。
//
// ★ 以前点这里是「模型」面板 —— 但用户想"换个人聊"时点的是名字,
// 而模型是"换脑子"、不是"换人",两者混在一个入口里说不清。
// 模型仍然在抽屉里有独立入口(那才是它该在的地方)。
Row(
Modifier
.clip(RoundedCornerShape(16.dp))
.clickable { vm.modelPickerOpen = true }
.clickable { vm.screen = Screen.AgentSelect }
.padding(horizontal = 8.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
@@ -373,7 +378,21 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
// 这里 path 为空就还是原来的图标)
val art = vm.activeAgent?.image?.front ?: ""
if (art.isNotBlank()) {
AssetImage(
path = art,
modifier = Modifier.fillMaxSize().clip(CircleShape),
contentScale = ContentScale.Crop,
fallback = {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
},
)
} else {
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
}
}
Spacer(Modifier.width(6.dp))
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())

View File

@@ -0,0 +1,348 @@
package com.doubao.lynxclone.ui
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
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.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.doubao.lynxclone.data.MemoryItem
import com.doubao.lynxclone.data.MemorySpace
/*
* 记忆管理(需求 3.2 / 3.5)。
*
* ## 这个界面存在的理由
*
* 需求里记忆是"**混合制**":AI 通过工具自主读写,**用户手动编辑兜底**。
* 没有这个界面,"兜底"就是空话 —— AI 记错了东西,用户只能干看着
* (而他会记错:模型把"他喜欢猫"记成"他讨厌猫"这种事很常见)。
*
* 顺带把三样东西一起放进来,因为它们都是"这个智能体的内在状态":
* · 情绪(需求 3.5:用户可手动编辑)
* · AI 提的"该整理记忆了"建议(需求 3.2:仅提示,用户确认才执行)
* · 导入 / 导出(需求 3.4)
*
* ## 共享记忆要**显式说明**
*
* 绑了世界观的智能体,记忆是和同世界观其他智能体**共用**的。
* 界面上不写清楚的话,用户会以为"我给 A 记的东西怎么 B 也知道" ——
* 所以顶部有一条明显的提示。
*/
@Composable
fun MemoryScreen(
space: MemorySpace?,
agentName: String,
loading: Boolean,
hint: String,
onSetEmotion: (String) -> Unit,
onAdd: (String, String) -> Unit,
onUpdate: (String, String?, String?) -> Unit,
onDelete: (String) -> Unit,
onTogglePin: (String, Boolean) -> Unit,
onSummarize: () -> Unit,
onExport: () -> Unit,
onImportClick: () -> Unit,
onBack: () -> Unit,
) {
var editing by remember { mutableStateOf<MemoryItem?>(null) }
var adding by remember { mutableStateOf(false) }
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
FullScreen(
title = "记忆",
subtitle = buildString {
append(agentName.ifBlank { "智能体" })
space?.let {
append(" · ")
append(if (it.shared) "世界观共享记忆" else "私有记忆")
append(" ${it.memories.size} 条")
}
if (loading) append(" · 处理中…")
},
onBack = onBack,
actions = {
TopTextAction("导入", onClick = onImportClick)
},
) {
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
if (space?.shared == true) {
Row(
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),
)
}
}
// ---- AI 的建议(需求 3.2:仅提示,用户确认才执行)----
if (!space?.suggestion.isNullOrBlank()) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp)
.clip(RoundedCornerShape(10.dp))
.background(Doubao.Blue.copy(alpha = 0.08f))
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("AI 觉得记忆该整理一下了", fontSize = 12.sp, color = Doubao.Blue)
Spacer(Modifier.height(2.dp))
Text(space?.suggestion ?: "", fontSize = 11.sp, color = doubaoTextSecondary())
}
Text(
"整理",
fontSize = 13.sp,
color = Color.White,
modifier = Modifier
.clip(RoundedCornerShape(14.dp))
.background(Doubao.Blue)
.clickable(enabled = !loading) { onSummarize() }
.padding(horizontal = 12.dp, vertical = 6.dp),
)
}
}
if (hint.isNotBlank()) {
Text(
hint,
fontSize = 12.sp,
color = Doubao.Blue,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 6.dp),
)
}
// ---- 情绪 ----
SectionLabel("情绪")
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.clip(RoundedCornerShape(14.dp))
.background(doubaoSurface())
.padding(12.dp),
) {
Text(
"AI 自己能改(emotion_set),你也可以在这里改。它每次对话都会被带进提示词。",
fontSize = 11.sp,
lineHeight = 16.sp,
color = doubaoTextSecondary(),
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = emotionDraft,
onValueChange = { emotionDraft = it },
placeholder = { Text("比如:刚被夸了,有点得意", fontSize = 13.sp) },
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
)
Spacer(Modifier.height(6.dp))
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
TextButton(
onClick = { onSetEmotion(emotionDraft.trim()) },
enabled = emotionDraft.trim() != (space?.emotion ?: ""),
) { Text("保存情绪", fontSize = 13.sp) }
}
}
// ---- 操作条 ----
SectionLabel("记忆(按时间排,最新的在下面)")
Row(
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
SmallAction("+ 加一条") { adding = true }
SmallAction(if (loading) "整理中…" else "AI 整理") { if (!loading) onSummarize() }
SmallAction("导出文件", onClick = onExport)
}
Spacer(Modifier.height(8.dp))
// ---- 列表 ----
val items = space?.memories ?: emptyList()
if (items.isEmpty()) {
Text(
if (loading) "读取中…" else "还没有记忆。AI 觉得有值得记住的事时会自己记下来。",
fontSize = 12.sp,
color = doubaoTextSecondary(),
modifier = Modifier.padding(horizontal = 14.dp, vertical = 16.dp),
)
}
for (m in items) {
MemoryRow(
item = m,
onEdit = { editing = m },
onDelete = { onDelete(m.id) },
onTogglePin = { onTogglePin(m.id, !m.pinned) },
)
}
Spacer(Modifier.height(28.dp))
}
}
// ---- 编辑 / 新增 ----
val target = editing
if (target != null || adding) {
MemoryEditDialog(
initial = target,
onDismiss = { editing = null; adding = false },
onSave = { title, content ->
if (target == null) onAdd(title, content) else onUpdate(target.id, title, content)
editing = null
adding = false
},
)
}
}
@Composable
private fun SmallAction(label: String, onClick: () -> Unit) {
Text(
label,
fontSize = 12.sp,
color = Doubao.Blue,
modifier = Modifier
.clip(RoundedCornerShape(14.dp))
.background(Doubao.Blue.copy(alpha = 0.10f))
.clickable { onClick() }
.padding(horizontal = 12.dp, vertical = 7.dp),
)
}
@Composable
private fun MemoryRow(
item: MemoryItem,
onEdit: () -> Unit,
onDelete: () -> Unit,
onTogglePin: () -> Unit,
) {
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 4.dp)
.clip(RoundedCornerShape(12.dp))
.background(doubaoSurface())
.border(
width = if (item.pinned) 1.dp else 0.dp,
color = if (item.pinned) Color(0x66F29900) else Color.Transparent,
shape = RoundedCornerShape(12.dp),
)
.padding(12.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (item.pinned) {
Text(
"必须保留",
fontSize = 9.sp,
color = Color(0xFF8A6100),
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.background(Color(0x22F29900))
.padding(horizontal = 5.dp, vertical = 2.dp),
)
Spacer(Modifier.width(6.dp))
}
Text(
item.title.ifBlank { "(无标题)" },
fontSize = 13.sp,
fontWeight = FontWeight.Medium,
color = doubaoText(),
modifier = Modifier.weight(1f),
)
}
if (item.content.isNotBlank()) {
Spacer(Modifier.height(4.dp))
Text(item.content, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary())
}
Spacer(Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
// ★「必须保留」是**用户**的权利(需求 3.2):标上之后 AI 总结时
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给
RowAction(if (item.pinned) "取消保留" else "必须保留", onClick = onTogglePin)
RowAction("编辑", onClick = onEdit)
RowAction("删除", danger = true, onClick = onDelete)
}
}
}
@Composable
private fun MemoryEditDialog(
initial: MemoryItem?,
onDismiss: () -> Unit,
onSave: (String, String) -> Unit,
) {
var title by remember { mutableStateOf(initial?.title ?: "") }
var content by remember { mutableStateOf(initial?.content ?: "") }
// ★ 单条记忆的编辑用弹窗是合适的(内容量小、就是两个输入框);
// 而"列表 / 多组配置"一律全屏 —— 见 AGENTS.md 那张表
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(if (initial == null) "加一条记忆" else "编辑记忆", fontSize = 16.sp) },
text = {
Column {
OutlinedTextField(
value = title,
onValueChange = { title = it },
label = { Text("标题", fontSize = 12.sp) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = content,
onValueChange = { content = it },
label = { Text("内容", fontSize = 12.sp) },
modifier = Modifier.fillMaxWidth().heightIn(min = 90.dp, max = 220.dp),
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
)
}
},
confirmButton = {
TextButton(
onClick = { onSave(title.trim(), content.trim()) },
enabled = title.isNotBlank() || content.isNotBlank(),
) { Text("保存") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
)
}

View File

@@ -0,0 +1,212 @@
package com.doubao.lynxclone.ui
import androidx.compose.foundation.background
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.fillMaxWidth
import androidx.compose.foundation.layout.height
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.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.doubao.lynxclone.data.TokenUsage
/*
* Token 用量详情(需求 3.1 的展示入口:选择界面「更多」按钮)。
*
* ## 展示什么
*
* · 累计用量(**输入 / 输出分列**,需求明确要求不合并)
* · 限额进度(没限额就显示"无限制")
* · **按模型分行**(需求 3.1 的"按模型分桶",可看总数也可展开)
* · 配了单价才显示估算费用 —— 没配就只显示 Token 数,不瞎估
*
* ## 不做历史曲线
*
* 需求原话"当前不做曲线"(时间戳只是为将来预留)。
*
* ## 做全屏而不是弹窗
*
* 见 AGENTS.md「少用弹窗」。这里要放三四行数字 + 一张可能十几行的模型表,
* 弹窗装不下。
*/
@Composable
fun TokenUsageScreen(
usage: TokenUsage?,
onReset: () -> Unit,
onBack: () -> Unit,
) {
FullScreen(
title = "用量",
subtitle = usage?.name?.takeIf { it.isNotBlank() }?.let { "$it · 累计" } ?: "正在读取…",
onBack = onBack,
actions = {
if (usage != null && usage.total > 0) TopTextAction("清零", danger = true, onClick = onReset)
},
) {
if (usage == null) {
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
Text("正在读取…", fontSize = 13.sp, color = doubaoTextSecondary())
}
return@FullScreen
}
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
// ---- 总览 ----
Card {
Text("累计消耗", fontSize = 12.sp, color = doubaoTextSecondary())
Spacer(Modifier.height(6.dp))
Text(
fmtTokens(usage.total),
fontSize = 30.sp,
fontWeight = FontWeight.Medium,
color = doubaoText(),
)
Spacer(Modifier.height(10.dp))
Row {
Metric("输入", usage.input)
Spacer(Modifier.width(24.dp))
Metric("输出", usage.output)
}
if (usage.pricePerK > 0 && usage.cost != null) {
Spacer(Modifier.height(10.dp))
Text(
"估算费用 ¥${"%.2f".format(usage.cost)}(按 ¥${usage.pricePerK}/千 Token)",
fontSize = 11.sp,
color = doubaoTextSecondary(),
)
}
}
// ---- 限额 ----
Card {
if (usage.unlimited) {
Text("额度:无限制", fontSize = 14.sp, color = doubaoText())
Spacer(Modifier.height(4.dp))
Text(
"想限制他?在「管理 → 编辑」里填一个 Token 上限就行。",
fontSize = 11.sp,
color = doubaoTextSecondary(),
)
} else {
Text("额度", fontSize = 12.sp, color = doubaoTextSecondary())
Spacer(Modifier.height(6.dp))
Row(verticalAlignment = Alignment.Bottom) {
Text(
fmtTokens(usage.remaining ?: 0),
fontSize = 22.sp,
fontWeight = FontWeight.Medium,
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoText(),
)
Text(
" / ${fmtTokens(usage.limit)} 剩余",
fontSize = 12.sp,
color = doubaoTextSecondary(),
modifier = Modifier.padding(bottom = 3.dp),
)
}
Spacer(Modifier.height(8.dp))
// 进度条自己画(项目没有 material 的 LinearProgressIndicator 用法先例,
// 一条圆角 Box 更可控)
Box(
Modifier
.fillMaxWidth()
.height(6.dp)
.clip(RoundedCornerShape(3.dp))
.background(Doubao.Border),
) {
Box(
Modifier
.fillMaxWidth(usage.percent.toFloat().coerceIn(0f, 1f))
.height(6.dp)
.clip(RoundedCornerShape(3.dp))
.background(if (usage.percent >= 1f) Color(0xFFD93025) else Doubao.Blue),
)
}
Spacer(Modifier.height(6.dp))
Text(
if (usage.percent >= 1f)
"已经用完了 —— 下一轮会被拦住,并附一句告别。可以清零、调大限额或改成无限制。"
else "用满之后会拦住发送(记忆整理这类操作不受影响)。",
fontSize = 11.sp,
lineHeight = 16.sp,
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoTextSecondary(),
)
}
}
// ---- 按模型分桶 ----
Card {
Text("按模型", fontSize = 12.sp, color = doubaoTextSecondary())
Spacer(Modifier.height(8.dp))
if (usage.byModel.isEmpty()) {
Text("还没用过", fontSize = 13.sp, color = doubaoTextSecondary())
} else {
for ((i, m) in usage.byModel.withIndex()) {
if (i > 0) Spacer(Modifier.height(8.dp))
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(
m.model,
fontSize = 13.sp,
color = doubaoText(),
modifier = Modifier.weight(1f),
)
Text(
"入 ${fmtTokens(m.input)} · 出 ${fmtTokens(m.output)}",
fontSize = 12.sp,
color = doubaoTextSecondary(),
)
}
}
}
}
Spacer(Modifier.height(24.dp))
}
}
}
@Composable
private fun Card(content: @Composable () -> Unit) {
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp)
.clip(RoundedCornerShape(14.dp))
.background(doubaoSurface())
.padding(14.dp),
) { content() }
}
@Composable
private fun Metric(label: String, value: Long) {
Column {
Text(label, fontSize = 11.sp, color = doubaoTextSecondary())
Text(fmtTokens(value), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
}
}
/** 大数字加千分位:`12345` → `12,345`。Token 数动辄五六位,不加看不清量级 */
fun fmtTokens(n: Long): String {
val s = n.toString()
if (s.length <= 3) return s
val sb = StringBuilder()
for ((i, c) in s.withIndex()) {
if (i > 0 && (s.length - i) % 3 == 0) sb.append(',')
sb.append(c)
}
return sb.toString()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 669 KiB