diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index c821e7c..414720d 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 206 - versionName = "2.0.6" + versionCode = 207 + versionName = "2.0.7" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt index f989ade..8aa67b2 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt @@ -1,4222 +1,8485 @@ package com.doubao.lynxclone.ui + + import androidx.compose.foundation.Canvas + import androidx.compose.foundation.background + import androidx.compose.foundation.border + import androidx.compose.foundation.clickable + import androidx.compose.foundation.gestures.awaitEachGesture + import androidx.compose.foundation.gestures.awaitFirstDown + import androidx.compose.foundation.gestures.detectDragGestures + import androidx.compose.foundation.horizontalScroll + import androidx.compose.foundation.layout.Arrangement + import androidx.compose.foundation.layout.Box + import androidx.compose.foundation.layout.ExperimentalLayoutApi + import androidx.compose.foundation.layout.FlowRow + 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.offset + 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.CircleShape + import androidx.compose.foundation.shape.RoundedCornerShape + import androidx.compose.foundation.verticalScroll + import androidx.compose.material.icons.Icons + import androidx.compose.material.icons.automirrored.filled.ArrowBack + import androidx.compose.material.icons.filled.Add + import androidx.compose.material.icons.filled.Delete + import androidx.compose.material.icons.filled.PlayArrow + import androidx.compose.material3.AlertDialog + import androidx.compose.material3.Icon + import androidx.compose.material3.IconButton + import androidx.compose.material3.HorizontalDivider + import androidx.compose.material3.MaterialTheme + import androidx.compose.material3.OutlinedTextField + import androidx.compose.material3.Surface + import androidx.compose.material3.Text + import androidx.compose.material3.TextButton + import androidx.compose.foundation.layout.heightIn + import androidx.compose.material3.Card + import androidx.compose.material3.CardDefaults + import androidx.compose.animation.core.LinearEasing + import androidx.compose.animation.core.RepeatMode + import androidx.compose.animation.core.animateFloat + import androidx.compose.animation.core.infiniteRepeatable + import androidx.compose.animation.core.rememberInfiniteTransition + import androidx.compose.animation.core.tween + import androidx.compose.material3.Slider + import org.json.JSONObject + import org.json.JSONArray + import com.doubao.lynxclone.data.toJson + import com.doubao.lynxclone.data.toMeeting + import com.doubao.lynxclone.data.MeetingResult + import androidx.compose.foundation.BorderStroke + import androidx.activity.compose.rememberLauncherForActivityResult + import androidx.activity.result.contract.ActivityResultContracts + import com.doubao.lynxclone.data.toMeeting + import androidx.compose.runtime.Composable + import androidx.compose.runtime.LaunchedEffect + import androidx.compose.runtime.getValue + import androidx.compose.runtime.mutableStateListOf + import androidx.compose.runtime.mutableStateMapOf + import androidx.compose.runtime.mutableStateOf + import androidx.compose.runtime.remember + import androidx.compose.runtime.rememberUpdatedState + 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.geometry.Offset + +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.Color + import androidx.compose.ui.graphics.TransformOrigin + import androidx.compose.ui.graphics.graphicsLayer + import androidx.compose.ui.graphics.Path + import androidx.compose.ui.graphics.StrokeCap + import androidx.compose.ui.graphics.PathEffect + import androidx.compose.ui.graphics.drawscope.Stroke + import androidx.compose.ui.input.pointer.pointerInput + import androidx.compose.ui.text.TextStyle + import androidx.compose.ui.text.font.FontWeight + import androidx.compose.ui.text.style.TextOverflow + import androidx.compose.ui.unit.dp + import androidx.compose.ui.unit.sp + import com.doubao.lynxclone.data.Meeting + import com.doubao.lynxclone.data.MeetingEdge + import com.doubao.lynxclone.data.MeetingMeta + import com.doubao.lynxclone.data.MeetingNode + import com.doubao.lynxclone.data.MeetingRun + import com.doubao.lynxclone.data.MeetingStep + import com.doubao.lynxclone.data.MeetingSummary + + /** + * 会议模式:用「节点 + 连线」编排多个智能体。 + * + * --------------------------------------------------------------------------- + * 交互设计:为什么连线是"点选"而不是"拖拽拉线" + * --------------------------------------------------------------------------- + * 桌面上的节点编辑器都是从一个锚点拖出一条线到另一个节点。手机上行不通: + * 手指挡住目标、画布还在滚动、拖拽和滚动手势互相抢 —— 实测很容易连错或者 + * 变成滚屏。所以这里改成**两步点选**:点节点上的「连线」→ 再点目标节点。 + * 慢一点,但不会错,也不用跟手势打架。 + * + * 拖动节点本身还是用拖拽(这个在手机上很自然)。 + * + * --------------------------------------------------------------------------- + * 画布坐标系 + * --------------------------------------------------------------------------- + * 节点位置就是内核里的 x / y(同一份数据,不做转换)。画布是一块固定大小的 + * 可滚动画布,节点用 offset 摆上去,连线用 Canvas 画在底下。 + * 不用可缩放画布:手机上缩放 + 拖拽 + 滚动三套手势叠一起必然打架。 + */ + @Composable + fun MeetingsScreen(vm: AppViewModel) { + var editing by remember { mutableStateOf(null) } + // 节点类型 / 判断条件 / 可用智能体:进页面拉一次就够 + LaunchedEffect(Unit) { vm.ensureMeetingMeta() } + val current = editing + if (current == null) { + MeetingListScreen(vm) { editing = it } + } else { + MeetingEditorScreen(vm, current) { editing = null } + } + } -/* ====================================================================== */ -/* 列表 */ + + /* ====================================================================== */ +/* 列表 */ + +/* ====================================================================== */ + + + @Composable + private fun MeetingListScreen(vm: AppViewModel, onOpen: (Meeting) -> Unit) { + var items by remember { mutableStateOf>(emptyList()) } + var name by remember { mutableStateOf("") } + var creating by remember { mutableStateOf(false) } + var error by remember { mutableStateOf("") } + var reload by remember { mutableStateOf(0) } + + LaunchedEffect(reload) { + try { + items = vm.client.meetings() + error = "" + } catch (e: Exception) { + error = e.message ?: "读取失败" + } + } + + Column(Modifier.fillMaxSize().background(doubaoBg())) { + ScreenHeader("会议模式", onBack = { vm.screen = com.doubao.lynxclone.ui.Screen.Chat }) + + Column(Modifier.padding(horizontal = 16.dp)) { + Text( + "把多个智能体用节点和连线串起来:初始输入 → 各司其职 → 按条件分叉 → 最终输出。", + fontSize = 13.sp, + color = doubaoTextSecondary(), + lineHeight = 19.sp, + ) + Spacer(Modifier.height(12.dp)) + } + + if (error.isNotBlank()) { + Text( + "读取失败:$error", + color = MaterialTheme.colorScheme.error, + fontSize = 13.sp, + modifier = Modifier.padding(horizontal = 16.dp), + ) + Spacer(Modifier.height(8.dp)) + } + + Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp)) { + items.forEach { item -> + Surface( + shape = RoundedCornerShape(14.dp), + color = doubaoSurface(), + modifier = Modifier.fillMaxWidth().padding(vertical = 5.dp) + .clickable { + // 列表只有摘要,打开时再取整份图 + vm.launch { + try { + onOpen(vm.client.meeting(item.id)) + } catch (e: Exception) { + error = e.message ?: "打开失败" + } + } + }, + ) { + Row( + Modifier.padding(14.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(item.name, fontSize = 16.sp, color = doubaoText(), fontWeight = FontWeight.Medium) + Spacer(Modifier.height(2.dp)) + Text( + "${item.nodeCount} 个节点 · ${item.edgeCount} 条连线", + fontSize = 12.sp, + color = doubaoTextSecondary(), + ) + } + IconButton(onClick = { + vm.launch { + try { + vm.client.deleteMeeting(item.id) + reload += 1 + } catch (e: Exception) { + error = e.message ?: "删除失败" + } + } + }) { Icon(Icons.Filled.Delete, "删除", tint = doubaoTextSecondary(), modifier = Modifier.size(18.dp)) } + } + } + } + Spacer(Modifier.height(10.dp)) + } + + Row(Modifier.padding(16.dp)) { + PrimaryButton("新建会议") { creating = true } + } + } + + if (creating) { + AlertDialog( + onDismissRequest = { creating = false }, + title = { Text("新建会议", fontSize = 16.sp) }, + text = { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + modifier = Modifier.fillMaxWidth(), + placeholder = { Text("例如:选题评审会", fontSize = 13.sp) }, + singleLine = true, + textStyle = TextStyle(fontSize = 14.sp), + ) + }, + confirmButton = { + TextButton(onClick = { + vm.launch { + try { + onOpen(vm.client.createMeeting(name.ifBlank { "新会议" })) + creating = false + name = "" + } catch (e: Exception) { + error = e.message ?: "创建失败" + creating = false + } + } + }) { Text("创建") } + }, + dismissButton = { TextButton(onClick = { creating = false }) { Text("取消") } }, + ) + } + } -/* ====================================================================== */ -/* 编辑器 */ + + /* ====================================================================== */ +/* 编辑器 */ + +/* ====================================================================== */ + + + /** + * 节点的显示尺寸。 + * + * 116dp 是权衡出来的:手机竖屏约 360dp 宽,三个节点 + 两条连线要能一屏看全 + * (12 + 116 → 132 + 116 → 252 + 116 = 368,会稍微超一点点但主体都在)。 + * 再宽就放不下,再窄节点标题就全折行了。 + * + * ★ 高度 88 是算出来的,不是拍的:上下 padding 16 + 标题 18 + 间隔 3 + + * 描述两行 24 + 「连线」14 = 75,留点余量。原来给 72 装不下, + * 「连线」两个字被 size() 压成了半截(截图上看像被划掉了)。 + */ + private const val NODE_W = 116f + private const val NODE_H = 88f + + /** 画布比屏幕大,可以滚;节点坐标落在这个范围内 */ + private const val CANVAS_W = 900f + private const val CANVAS_H = 800f + + @Composable + private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -> Unit) { + var meeting by remember { mutableStateOf(initial) } + var configTarget by remember { mutableStateOf(null) } + var adding by remember { mutableStateOf(false) } + // 正在连线:记"从哪条引脚拉出来的"(节点 + 引脚种类 + 分支)。 + // 判断节点有真/假两条 exec 出线,只记节点 id 分不清是从哪个口拉出来的。 + var linkingFrom by remember { mutableStateOf(null) } + // 点中的连线(要能删)。存的是 edges 里的下标。 + var selectedEdge by remember { mutableStateOf(null) } + // 画布底色。drawPath 里不能用 @Composable,所以在这里先取好。 + val boardBg = doubaoBg() + // ★ 画布尺寸**跟着节点长**:手势里算平移范围要用、Box 的 .size() 也要用, + // 所以提到这一层算一次(放在手势闭包里的话,外面那个 .size() 就取不到了)。 + val (cw, ch) = canvasSize(meeting.nodes) + // 导出要用:复制到剪贴板 + 弹个提示 + val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current + val context = androidx.compose.ui.platform.LocalContext.current + // 变量管理面板 + var showVars by remember { mutableStateOf(false) } + // 编辑器菜单(拖动灵敏度 / 导出) + var showMenu by remember { mutableStateOf(false) } + // 导入会议(粘 JSON) + var showImport by remember { mutableStateOf(false) } + // ★ **导入节点文件**:用系统的文件选择器挑一个 .py,读出来交给内核落盘。 + // + // 为什么必须走"读出来 -> 交给内核写"这条路: + // 应用沙箱里 App 能写自己的数据目录,但 nodes/ 是**内核在管**的地方, + // 而且内核还会先把文件试加载一遍 —— 写错了当场把 Python 的报错回给用户, + // 而不是让他导入一个坏节点、之后每次开会都看见它。 + var nodeImportMsg by remember { mutableStateOf("") } + /** + * 连线被拒时的说明。 + * + * ★ 为什么要这个:类型校验本身是对的,但**光拒绝不说话**会让用户 + * 反复试同一个操作("明明连着为啥不行")。接不上必须当场说清楚 + * 是什么类型对什么类型、该怎么办。 + */ + var linkHint by remember { mutableStateOf("") } + /** + * 变量登记表:名字 → 类型。 + * + * ★ 算一次给底下用(引脚、卡片、连线都要查)—— + * 读变量的出口类型必须按它来,不能写死 str, + * 否则数字变量接不到运算节点上。 + */ + val varTypeMap = remember(meeting.vars) { + meeting.vars.associate { it.name to it.type } + } + // 节点管理 / 现场编辑 + var showNodeMgr by remember { mutableStateOf(false) } + // 全屏积木编辑器:非 null 就是打开着 + var blockEdit by remember { mutableStateOf>?>(null) } + var nodeFiles by remember { mutableStateOf>(emptyList()) } + var editFile by remember { mutableStateOf(null) } + var editCode by remember { mutableStateOf("") } + var editName by remember { mutableStateOf("") } + var nodeMgrMsg by remember { mutableStateOf("") } + + // 拉一次节点文件列表(打开管理面板时、导入导出之后都要) + suspend fun refreshNodeFiles() { + val arr = runCatching { vm.nodeFiles() }.getOrElse { org.json.JSONArray() } + nodeFiles = (0 until arr.length()).mapNotNull { i -> + arr.optJSONObject(i)?.let { o -> + fun pins(k: String) = (o.optJSONArray(k) ?: org.json.JSONArray()).let { a -> + (0 until a.length()).mapNotNull { j -> + a.optJSONObject(j)?.let { p -> + p.optString("type") to p.optString("name") + } + } + } + NodeFile( + file = o.optString("file"), + ok = o.optBoolean("ok", true), + error = o.optString("error"), + label = o.optString("label"), + desc = o.optString("desc"), + inputs = pins("inputs"), + outputs = pins("outputs"), + ) + } + } + } + + // 导出节点:系统的保存对话框 + var pendingNodeExport by remember { mutableStateOf("") } + val nodeExporter = rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("text/x-python"), + ) { uri -> + if (uri != null) { + val ok = runCatching { + context.contentResolver.openOutputStream(uri)?.use { os -> + os.write(pendingNodeExport.toByteArray(Charsets.UTF_8)) + } + true + }.getOrElse { false } + nodeMgrMsg = if (ok) "已导出到文件" else "导出失败:路径不可写" + } + } + + val nodePicker = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + val picked = runCatching { + val name = uri.lastPathSegment.orEmpty().substringAfterLast('/') + val text = context.contentResolver.openInputStream(uri)?.use { ins -> + ins.readBytes().toString(Charsets.UTF_8) + }.orEmpty() + name to text + }.getOrElse { "" to "" } + val (name0, text) = picked + if (text.isBlank()) { + nodeImportMsg = "读不到文件内容(可能没给存储权限)" + } else { + vm.launch { + val r = runCatching { vm.importNodeFile(name0.ifBlank { "node.py" }, text) } + nodeImportMsg = r.fold( + onSuccess = { "已导入:$it" }, + onFailure = { "导入失败:${it.message.orEmpty().take(300)}" }, + ) + } + } + } + } + // ★ 拖动灵敏度:屏幕上移动 1px,节点实际移动 (1/缩放) × 这个系数。 + // 除缩放是必须的(不然放大后节点跑得比手指快);剩下的手感 —— + // 跟手一点还是稳一点 —— 跟屏幕尺寸、手指习惯都有关系, + // 与其我替你定死,不如做成可调的。 + var dragSensitivity by remember { mutableStateOf(1f) } + var running by remember { mutableStateOf(false) } + var runInput by remember { mutableStateOf("") } + var runError by remember { mutableStateOf("") } + var dirty by remember { mutableStateOf(false) } + var showResult by remember { mutableStateOf(false) } + val nodeOutputs = remember { mutableStateMapOf() } + + // 运行时的节点状态:正在跑 / 跑完 / 出错 + val liveStatus = remember { mutableStateMapOf() } + // 正在流动的那条 exec 线(下标);-1 = 没有。蓝图里执行流到哪,哪条线就动 + var litEdge by remember { mutableStateOf(-1) } + // 执行流的动画相位:0→1 循环。蓝图里 exec 线上的流动光点就是靠它。 + val flowPhase = rememberInfiniteTransition(label = "flow").animateFloat( + initialValue = 0f, + targetValue = 1f, + animationSpec = infiniteRepeatable( + animation = tween(850, easing = LinearEasing), + repeatMode = RepeatMode.Restart, + ), + label = "flowPhase", + ) + // 判断 / while 的结论(true/false/body/done),结果界面要写明 + val nodeVerdict = remember { mutableStateMapOf() } + // ★ 运行链:按**执行顺序**记下每一步。 + // 结果界面要的是"这条链上每一步的结果",不是一堆节点的最终状态 —— + // 循环转几轮就有几条记录,一眼能看出先后。 + val liveTrace = remember { mutableStateListOf() } + // 本次运行的最终输出(可能有多个、类型各不相同,结果界面按标签页展示) + val liveResults = remember { mutableStateListOf() } + // 当前正在跑哪个节点(界面顶部要显示"运行到哪了") + var nowRunning by remember { mutableStateOf("") } + // 每个节点的告警(比如"输入是空的,你漏了数据线")。 + // ★ 空输入如果不说出来,用户只会看到"明明有值却判断为真", + // 怎么查都查不出规则哪里错了 —— 规则本身没错。 + val nodeWarn = remember { mutableStateMapOf() } + + var panX by remember { mutableStateOf(0f) } + var panY by remember { mutableStateOf(0f) } + // 缩放。和看图片一样:双指捏合缩放、双指拖动平移,单指拖节点。 + var scale by remember { mutableStateOf(1f) } + + /** 统一的保存入口:拖动结束后、改完配置后都走它 */ + fun persist() { + vm.launch { + try { + meeting = vm.client.saveMeeting(meeting.id, meeting) + dirty = false + } catch (_: Exception) { + // 保存失败不打断编辑:本地改动还在,下次拖动会再试 + } + } + } + + /** 把当前这张图导成 JSON 文本(导出到剪贴板和导出到文件共用) */ + fun meetingJson(): String = JSONObject() + .put("name", meeting.name) + .put("nodes", JSONArray().apply { meeting.nodes.forEach { put(it.toJson()) } }) + .put("edges", JSONArray().apply { meeting.edges.forEach { put(it.toJson()) } }) + .put("vars", JSONArray().apply { meeting.vars.forEach { put(it.toJson()) } }) + .toString(2) + + /** 导入一份会议内容(只换图,不换名字和 id) */ + fun applyImported(m: Meeting) { + meeting = meeting.copy(nodes = m.nodes, edges = m.edges, vars = m.vars) + dirty = true + persist() + } + + // ★ 文件导入 / 导出走**系统文件选择器**。 + // + // 为什么必须加这条:剪贴板对**长文本**不可靠 —— 各大 ROM 都有自己的一套 + // 截断策略(有的按字节、有的按字符、有的只对"看起来像密码"的东西截), + // 而会议 JSON 动不动几 KB。用户反馈的"粘贴 JSON 被截断"就是这个。 + // 存成文件没有这个问题,也是能长期保存、能发给别人的那条路。 + var pendingExport by remember { mutableStateOf("") } + val exportLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("application/json"), + ) { uri -> + if (uri != null) { + val ok = runCatching { + context.contentResolver.openOutputStream(uri)?.use { os -> + os.write(pendingExport.toByteArray(Charsets.UTF_8)) + } + true + }.getOrElse { false } + android.widget.Toast.makeText( + context, + if (ok) "已导出到文件(${pendingExport.length} 字符)" else "导出失败:路径不可写", + android.widget.Toast.LENGTH_SHORT, + ).show() + } + } + val importLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + val text = runCatching { + context.contentResolver.openInputStream(uri)?.use { ins -> + ins.readBytes().toString(Charsets.UTF_8) + }.orEmpty() + }.getOrElse { "" } + val m = runCatching { JSONObject(text.trim()).toMeeting() }.getOrElse { null } + if (m != null && m.nodes.isNotEmpty()) { + applyImported(m) + android.widget.Toast.makeText( + context, + "已从文件导入 ${m.nodes.size} 个节点", + android.widget.Toast.LENGTH_SHORT, + ).show() + } else { + android.widget.Toast.makeText( + context, "这个文件不是合法的会议 JSON", android.widget.Toast.LENGTH_SHORT, + ).show() + } + } + } + + fun updateNode(node: MeetingNode) { + meeting = meeting.copy(nodes = meeting.nodes.map { if (it.id == node.id) node else it }) + dirty = true + } + + Column(Modifier.fillMaxSize().background(doubaoBg())) { + // 顶栏 + Row( + Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = { if (dirty) persist(); onBack() }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回") + } + Column(Modifier.weight(1f)) { + Text( + meeting.name, + fontSize = 16.sp, + color = doubaoText(), + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + when { + // ★ "运行到哪了"要一眼看得见:只有节点上的勾和线的流动, + // 循环转很多轮时还是不知道现在第几步。所以直接写出来。 + running && nowRunning.isNotBlank() -> + "正在跑:$nowRunning(第 ${liveTrace.size} 步)" + running -> "正在准备…" + linkingFrom != null -> "点目标节点的左侧圆点接线(点空白取消)" + dirty -> "未保存" + // 手势规则要写出来:两指平移不是所有人一上来就知道的 + else -> "${meeting.nodes.size} 节点 · ${meeting.edges.size} 连线 · 一指拖节点 / 两指移动缩放" + }, + fontSize = 11.sp, + color = if (linkingFrom != null) Doubao.Blue else doubaoTextSecondary(), + ) + + // ★ 连线被拒时**当场说明原因** —— 光拒绝不说话,用户会反复试同一个操作。 + if (linkHint.isNotBlank()) { + Spacer(Modifier.height(4.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "⚠ $linkHint", + fontSize = 11.sp, + color = Color(0xFFD93025), + lineHeight = 15.sp, + modifier = Modifier.weight(1f), + ) + Text( + "知道了", + fontSize = 11.sp, + color = Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { linkHint = "" } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + } + } + // ★ 变量管理:变量是**会议级**的(一张图里同名变量只有一个), + // 所以它不属于任何一个节点,得有个地方统一配名字/类型/初始值。 + // 类型是**必选**的 —— 它决定这个变量的读变量节点能接到哪去。 + Text( + if (meeting.vars.isEmpty()) "变量" else "变量 ${meeting.vars.size}", + fontSize = 13.sp, + color = if (meeting.vars.isEmpty()) doubaoTextSecondary() else Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { showVars = true } + .padding(horizontal = 8.dp, vertical = 8.dp), + ) + // ★ 编辑器菜单:拖动灵敏度 / 导出会议。 + // 工具栏已经放了变量 / 加节点 / 运行 / 结果,再塞个滑块只会更挤, + // 所以收进一个 ⋮ 里。 + Text( + "⋮", + fontSize = 18.sp, + color = doubaoTextSecondary(), + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { showMenu = true } + .padding(horizontal = 10.dp, vertical = 4.dp), + ) + IconButton(onClick = { adding = true }) { + Icon(Icons.Filled.Add, "加节点") + } + IconButton( + onClick = { + if (dirty) persist() + running = true + runError = "" + nodeOutputs.clear() + liveStatus.clear() + vm.runMeeting( + meetingId = meeting.id, + input = runInput, + onEvent = { ev -> + when (ev.type) { + "node_start" -> { + liveStatus[ev.nodeId] = "running" + liveTrace.add( + TraceStep( + nodeId = ev.nodeId, + title = ev.title.ifBlank { ev.nodeType }, + nodeType = ev.nodeType, + run = ev.run, + ) + ) + nowRunning = ev.title.ifBlank { ev.nodeType } + // ★ 执行流到这一步了:把这根 exec 线点亮,让它"流"起来。 + // 蓝图里就是靠这个看出"现在跑到哪了" —— + // 节点上的勾只说明"跑过了",看不出**正在跑哪条线**。 + val idx = meeting.edges.indexOfFirst { it.to == ev.nodeId } + if (idx >= 0) litEdge = idx + } + "node_delta" -> nodeOutputs[ev.nodeId] = + (nodeOutputs[ev.nodeId] ?: "") + ev.text + "node_done" -> { + liveStatus[ev.nodeId] = "done" + if (ev.output.isNotBlank()) nodeOutputs[ev.nodeId] = ev.output + // 判断 / while 的结论要留下来,结果界面里要写明 + if (ev.branch.isNotBlank()) { + nodeVerdict[ev.nodeId] = ev.branch + } + // ★ 把结论补进运行链里**这一步**。 + // + // 链是按 node_start 记的(这样能实时长出来), + // 而结论要到 node_done 才有。不补的话结果界面 + // 就只有节点名和输出,"judge 走了真还是假"完全看不到 —— + // 用户的原话是"判断结果呢?被你吃了?"。 + val at = liveTrace.indexOfLast { it.nodeId == ev.nodeId } + if (at >= 0) { + liveTrace[at] = liveTrace[at].copy( + verdict = ev.verdict, + branch = ev.branch, + note = ev.note, + ) + } + } + "node_warn" -> nodeWarn[ev.nodeId] = ev.warn + "node_error" -> { + liveStatus[ev.nodeId] = "error" + nodeOutputs[ev.nodeId] = "出错:${ev.error}" + } + "meeting_done" -> { + liveResults.clear() + liveResults.addAll(ev.results) + running = false + litEdge = -1 + nowRunning = "" + if (ev.error.isNotBlank()) runError = ev.error + } + } + }, + onError = { msg -> running = false; runError = msg }, + ) + }, + ) { + Icon( + Icons.Filled.PlayArrow, + "运行", + tint = if (running) doubaoTextSecondary() else Doubao.Blue, + ) + } + } + + if (runError.isNotBlank()) { + Text( + "运行出错:$runError", + color = MaterialTheme.colorScheme.error, + fontSize = 12.sp, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + ) + } + + // 画布 + // + // ★ 手势分工(用户定的,比"谁抢到算谁的"清楚得多): + // **一指** → 拖手指底下那个节点;点在端口上是连线;点在节点上开配置 + // **两指** → 平移画布(按在哪都行,包括按在节点上) + // + // 为什么这样分:一指拖节点是手机上的直觉;而"想挪画布"和"想挪节点" + // 是两种完全不同的意图,用**手指数**区分最干净 —— 不需要谁去抢, + // 也不会再出现"想拖节点结果整张图跑了"(之前就是这么坏的)。 + // + // ★ 所有点击(端口连线、开配置)也收在这里统一命中判断, + // 不再让节点自己挂 clickable —— 多个手势识别器叠一起必然互相抢, + // 这个坑前面已经踩过两次了。 + val nodesSnapshot = rememberUpdatedState(meeting.nodes) + val linkingSnapshot = rememberUpdatedState(linkingFrom) + + Box( + Modifier + .weight(1f) + .fillMaxWidth() + .pointerInput(Unit) { + val nodeW = NODE_W.dp.toPx() + val portHit = PORT_HIT.dp.toPx() + // 画布的像素尺寸按**真实密度**算,不再拍一个 2.75。 + // 尺寸在 composable 那一层算好了(cw/ch),这里只管换算成像素。 + val contentW = cw.dp.toPx() + val contentH = ch.dp.toPx() + + /** + * 屏幕坐标 → 画布坐标。 + * + * graphicsLayer 的 transformOrigin 设成左上角,所以 + * 屏幕 = 画布 × 缩放 + 平移,反解就是这个式子。 + * 用默认的中心原点还得带上控件尺寸,容易算错。 + */ + fun toCanvas(pos: Offset): Offset = + Offset((pos.x - panX) / scale, (pos.y - panY) / scale) + + fun nodeAt(c: Offset): MeetingNode? = nodesSnapshot.value.lastOrNull { n -> + c.x >= n.x.dp.toPx() && c.x <= n.x.dp.toPx() + nodeW && + c.y >= n.y.dp.toPx() && c.y <= n.y.dp.toPx() + nodeHeight(n).dp.toPx() + } + + /** 命中哪个引脚。返回 (节点, 引脚, 是输出端) */ + fun portAt(c: Offset): Triple? { + for (n in nodesSnapshot.value.asReversed()) { + outputPins(n, vm.meetingMeta.customNodes, varTypeMap).forEachIndexed { i, pin -> + val p = pinPos(n, i, isOutput = true) + val pp = Offset(p.x.dp.toPx(), p.y.dp.toPx()) + if ((pp - c).getDistance() <= portHit) return Triple(n, pin, true) + } + inputPins(n, vm.meetingMeta.customNodes, varTypeMap).forEachIndexed { i, pin -> + val p = pinPos(n, i, isOutput = false) + val pp = Offset(p.x.dp.toPx(), p.y.dp.toPx()) + if ((pp - c).getDistance() <= portHit) return Triple(n, pin, false) + } + } + return null + } + + /** 命中哪条连线。返回 edges 里的下标;离得太远就返回 null。 */ + fun edgeAt(c: Offset): Int? { + val ns = nodesSnapshot.value + val wireHit = 14.dp.toPx() // 手指没那么准,给宽一点 + var best: Int? = null + var bestD = Float.MAX_VALUE + meeting.edges.forEachIndexed { index, edge -> + val a = ns.firstOrNull { it.id == edge.from } ?: return@forEachIndexed + val b = ns.firstOrNull { it.id == edge.to } ?: return@forEachIndexed + val start = Offset( + portOut(a, edge.kind, edge.branch).x.dp.toPx(), + portOut(a, edge.kind, edge.branch).y.dp.toPx(), + ) + val end = Offset( + portIn(b, edge.kind).x.dp.toPx(), + portIn(b, edge.kind).y.dp.toPx(), + ) + val dx = maxOf(36.dp.toPx(), kotlin.math.abs(end.x - start.x) * 0.5f) + val d = distanceToWire(start, end, dx, c) + if (d < bestD) { + bestD = d + best = index + } + } + return if (bestD <= wireHit) best else null + } + + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + var last = down.position + var moved = false + var accumulated = 0f + val c0 = toCanvas(down.position) + // 按在端口上就不算"拖节点",否则会一边连线一边把节点拖走 + val portHitAtDown = portAt(c0) + var hit = if (portHitAtDown == null) nodeAt(c0) else null + var dragX = hit?.x ?: 0f + var dragY = hit?.y ?: 0f + // 平移用:上一次的质心和手指数。手指数一变就重置, + // 不然第二根手指按下的瞬间质心会跳一大截,画面"唰"地飞走。 + var lastCentroid: Offset? = null + var lastSpan = 0f + var lastCount = 1 + + while (true) { + val event = awaitPointerEvent() + val pressed = event.changes.filter { it.pressed } + if (pressed.isEmpty()) break + + if (pressed.size >= 2) { + // 两层:平移画布。正在拖的节点立刻放手 —— + // 用户临时改主意想挪画布,不该继续拖着节点跑。 + hit = null + moved = true + val centroid = + pressed.fold(Offset.Zero) { acc, c -> acc + c.position } / + pressed.size.toFloat() + val span = (pressed[0].position - pressed[1].position).getDistance() + val prev = lastCentroid + if (lastCount == pressed.size && prev != null) { + // ① 缩放:两指间距的比例。**以两指中点为锚** —— + // 中点底下的东西保持不动,这才是"看图片"的手感。 + // 不做锚点修正的话,捏合时画面会往左上角跑。 + if (lastSpan > 1f && span > 1f) { + val nextScale = (scale * (span / lastSpan)).coerceIn(0.4f, 3f) + if (nextScale != scale) { + // 锚点 = (中点 - 平移) / 缩放 (缩放前) + // 平移' = 中点 - 锚点 × 缩放' (缩放后) + val ax = (centroid.x - panX) / scale + val ay = (centroid.y - panY) / scale + panX = centroid.x - ax * nextScale + panY = centroid.y - ay * nextScale + scale = nextScale + } + } + // ② 平移:质心位移 + panX += centroid.x - prev.x + panY += centroid.y - prev.y + // 缩放会改变内容在屏幕上的大小,钳制范围要跟着变 + val next = clampPan( + panX, panY, + size.width.toFloat(), size.height.toFloat(), + contentW * scale, contentH * scale, + ) + panX = next.first + panY = next.second + } + lastCentroid = centroid + lastSpan = span + lastCount = pressed.size + pressed.forEach { it.consume() } + continue + } + + // 一指 + lastCentroid = null + lastSpan = 0f + lastCount = 1 + val change = event.changes.firstOrNull { it.id == down.id } ?: break + if (!change.pressed) break + val delta = change.position - last + accumulated += delta.getDistance() + // 阈值 4px:手指按下时抖一下不该算拖动 + if (moved || accumulated > 4f) { + moved = true + change.consume() + if (hit != null) { + // 屏幕上移动 1px,画布坐标只移动 1/scale —— + // 不除的话放大后节点会"跑得比手指快"。 + // + // ★ 再乘一个**可调系数**(编辑器菜单里的滑块): + // 除缩放是必须的,但剩下的手感(跟手还是稳一点) + // 跟屏幕尺寸、手指习惯都有关,做成可调。 + // + // ★ 不再钳到固定画布:画布会跟着节点长, + // 所以只留一点负向余量(往左上也能拖出去)。 + dragX = (dragX + delta.x / scale * dragSensitivity) + .coerceAtLeast(-CANVAS_MARGIN) + dragY = (dragY + delta.y / scale * dragSensitivity) + .coerceAtLeast(-CANVAS_MARGIN) + updateNode(hit.copy(x = dragX, y = dragY)) + } + // 空白处单指拖动:什么都不做(平移要两指) + } + last = change.position + } + + if (!moved) { + // ------- 没怎么动 = 点击 ------- + val linking = linkingSnapshot.value + when { + // 点输出引脚:开始 / 取消连线 + portHitAtDown != null && portHitAtDown.third -> { + val (n, pin, _) = portHitAtDown + val key = LinkFrom(n.id, pin.kind, pin.key) + linkingFrom = if (linking == key) null else key + } + // 点输入引脚:完成连线(**只接同种引脚**) + portHitAtDown != null && linking != null -> { + val (n, pin, _) = portHitAtDown + val from = linking.nodeId + val fromKind = linking.kind + val branch = linking.branch + // ★ exec 只能接 exec、data 只能接 data。 + // 蓝图里接错类型会直接报"类型不兼容" —— + // 这里静默不接(引脚本来就没画在一起,点错很难)。 + // 把"执行顺序"和"传值"混在一根线上, + // 整套语义就垮了,所以这条必须守住。 + if (from != n.id && pin.accepts_(fromKind)) { + // ★ 判断节点的真假 exec 分支:一条分支只留一条线, + // 再连一次是"改接"(不然会有两条"真", + // 跑起来走哪条全看队列顺序,根本说不清)。 + // + // 其他引脚**不是**这样:智能体的 exec / data 输出 + // 都可以同时给好几个下游("多路"),所以那里是**追加**。 + // 之前把判断的"改接"逻辑套到了所有引脚上, + // 结果智能体只能连一个下游 —— + // 用户报的"输出节点也能拓展"就是这个。 + val isBranch = fromKind == "exec" + && (branch == "true" || branch == "false") + val dup = meeting.edges.any { + it.from == from && it.to == n.id && + it.branch == branch && it.kind == fromKind && + // ★ 引脚也要一起比:运算的两个入口都是 num, + // 光看 kind 的话"给 A 接了、再给 B 接"会被当成 + // 重复(其实是两个不同的入口,都得接上)。 + it.toPin == pin.key + } + if (!dup) { + val kept = if (isBranch) { + meeting.edges.filterNot { + it.from == from && it.branch == branch && + it.kind == "exec" + } + } else { + meeting.edges + } + // ★ 一个**数据入口**只接一根线(后接的替换先接的)。 + // 不然两条线并到一个入口,用户以为接上了 B、 + // 其实两根都进 A(这就是"B 连不上")。 + val kept2 = if (fromKind == "exec") { + kept + } else { + kept.filterNot { + it.to == n.id && it.toPin == pin.key && + it.kind != "exec" + } + } + meeting = meeting.copy( + edges = kept2 + MeetingEdge( + from = from, + to = n.id, + branch = branch, + kind = fromKind, + toPin = pin.key, + ), + ) + dirty = true + linkHint = "" // 接上了,把上次的提示清掉 + persist() + } + } else if (from != n.id) { + // 类型不匹配:**当场说清楚**,别让用户反复试 + // ("明明连着为啥不行"这种问题最难查,因为界面什么都不说) + val want = if (pin.accepts.isEmpty()) listOf(pin.kind) else pin.accepts + linkHint = "接不上:" + kindLabel(fromKind) + " → 这里要 " + + want.joinToString("/") { kindLabel(it) } + + "。中间加一个**转换节点**就行。" + } + linkingFrom = null + } + // 点空白:取消连线 / 取消选中;点节点:开配置 + portHitAtDown == null && hit != null -> { + configTarget = hit + selectedEdge = null + } + portHitAtDown == null && linking != null -> { + linkingFrom = null + selectedEdge = null + } + // ★ 什么都没点到 → 再看看是不是点在**连线上**。 + // 连线是曲线,不能像节点那样用矩形判, + // 所以沿曲线采样找最近的(见 distanceToWire)。 + else -> selectedEdge = edgeAt(c0) + } + } else if (hit != null) { + persist() + } + } + }, + ) { + Box( + Modifier + .size(cw.dp, ch.dp) + .graphicsLayer { + // ★ 原点固定在左上角:这样"屏幕 = 画布 × 缩放 + 平移" + // 才成立,命中判断的反解也就一行。用默认的中心原点 + // 还得带上控件尺寸,最容易算错。 + transformOrigin = TransformOrigin(0f, 0f) + scaleX = scale + scaleY = scale + translationX = panX + translationY = panY + }, + ) { + // 连线和引脚画在节点底下 + Canvas(Modifier.fillMaxSize()) { + val px = { o: Offset -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) } + + meeting.edges.forEach { edge -> + val a = meeting.nodes.firstOrNull { it.id == edge.from } ?: return@forEach + val b = meeting.nodes.firstOrNull { it.id == edge.to } ?: return@forEach + // ★ 从**引脚的准确位置**出发,不是从节点中心 —— + // 判断节点两条出线一行一个,都从中心出发就分不清谁是谁 + val start = px(portOut(a, edge.kind, edge.branch, edge.fromPin)) + val end = px(portIn(b, edge.kind, varTypeMap, edge.toPin)) + // ★ 执行线白色(蓝图里 exec 线就是白的), + // 数据线按**类型**上色(白/绿/蓝/红)—— + // 和引脚同一个颜色,用户顺着颜色就能看出这根线接得对不对。 + val color = if (edge.kind != "exec") { + when (edge.branch) { + "true" -> Color(0xFF34A853) + "false" -> Color(0xFFEA4335) + else -> pinColor(edge.kind) + } + } else { + when (edge.branch) { + "true" -> Color(0xFF34A853) + "false" -> Color(0xFFEA4335) + else -> EXEC_BORDER + } + } + + // ★ 目标引脚的颜色(渐变用):"这根线进的是什么槽" + // 源色 = 传的是什么,目标色 = 收的是什么。两端同色时看起来还是纯色。 + val colorTo = run { + val ps = inputPins(b, emptyList(), varTypeMap) + val idx = if (edge.toPin.isNotBlank()) { + ps.indexOfFirst { it.key == edge.toPin } + } else { + ps.indexOfFirst { it.accepts_(edge.kind) } + } + ps.getOrNull(if (idx >= 0) idx else 0)?.let { pinColorOf(it) } ?: color + } + // ★ 三次贝塞尔,像 UE 蓝图那样:控制点水平拉开, + // 线从引脚水平出发、水平接入。直线在节点错位时 + // 会斜着穿过别的节点,看着像连错了。 + val dx = maxOf(36.dp.toPx(), kotlin.math.abs(end.x - start.x) * 0.5f) + val path = Path().apply { + moveTo(start.x, start.y) + cubicTo(start.x + dx, start.y, end.x - dx, end.y, end.x, end.y) + } + // 点中的那条画粗 + 套一层光晕,一眼看出"选的是这条" + val isSel = selectedEdge == meeting.edges.indexOf(edge) + if (isSel) { + drawPath( + path = path, + color = Doubao.Blue.copy(alpha = 0.30f), + style = Stroke(width = 9.dp.toPx(), cap = androidx.compose.ui.graphics.StrokeCap.Round), + ) + } + drawPath( + path = path, - color = if (isSel) Doubao.Blue else color, + + brush = if (isSel) { + SolidColor(Doubao.Blue) + } else { + // ★ **渐变**:从源引脚的颜色过渡到目标引脚的颜色。 + // 一眼能看出"这根线传的是什么"(源)→"它进的是什么槽"(目标)。 + // 比如 文本(绿) → 最终输出(紫):线从绿渐变到紫。 + // 两端同色时(绿→绿)看起来还是纯色,不会花。 + Brush.linearGradient(listOf(color, colorTo), start = start, end = end) + }, + style = Stroke( + width = if (isSel) 3.5.dp.toPx() else 2.5.dp.toPx(), + cap = androidx.compose.ui.graphics.StrokeCap.Round, + pathEffect = if (edge.branch == "false") { + PathEffect.dashPathEffect(floatArrayOf(9f, 9f)) + } else { + null + }, + ), + ) + // 箭头:**只有数据线才画**。 + // + // ★ exec 线不画箭头:exec 引脚本身就是个三角(▶), + // 再在端点附近画一个箭头会和引脚叠成"蝴蝶结"(▷◁), + // 看着像连错了。蓝图里 exec 线也是靠引脚形状表示方向的。 + // + // 数据线画,而且**往回收几个像素**,别贴着引脚。 + if (edge.kind != "exec") { + val len = 7.dp.toPx() + val tipX = end.x - 4.dp.toPx() + val arrow = Path().apply { + moveTo(tipX, end.y) + lineTo(tipX - len, end.y - len * 0.55f) + lineTo(tipX - len, end.y + len * 0.55f) + close() + } + drawPath(arrow, color) + } + // ★ **exec 线上的方向箭头**(照 UE 蓝图)。 + // + // 线本身不告诉人"从哪往哪流",端点上的三角只说明"这是个执行口"。 + // UE 在**线中间**画一个箭头,一眼看出方向 —— 图一复杂,没这个基本靠猜。 + // + // 位置取曲线中点,角度取中点处的切线: + // 三次贝塞尔在 t=0.5 的切线方向是 (end-start-dx, end.y-start.y)。 + + if (edge.kind == "exec") { + + val mid = bezierAt( + + start, + + Offset(start.x + dx, start.y), + + Offset(end.x - dx, end.y), + + end, + + 0.5f, + + ) + + val ang = kotlin.math.atan2(end.y - start.y, end.x - start.x - dx) + + val al = 6.dp.toPx() + + val dirArrow = Path().apply { + + moveTo(mid.x + al * kotlin.math.cos(ang), mid.y + al * kotlin.math.sin(ang)) + + lineTo(mid.x + al * kotlin.math.cos(ang + 2.5f), mid.y + al * kotlin.math.sin(ang + 2.5f)) + + lineTo(mid.x + al * kotlin.math.cos(ang - 2.5f), mid.y + al * kotlin.math.sin(ang - 2.5f)) + + close() + + } + + // 先描一圈背景色:箭头压在线上的时候才看得清 + + drawPath(dirArrow, boardBg, style = Stroke(width = 3.dp.toPx())) + + drawPath(dirArrow, if (isSel) Doubao.Blue else EXEC_BORDER) + + } + // ★ **执行流的流动效果**(照 UE 蓝图)。 + // + // 节点上的勾只说明"这个节点跑过了",看不出**现在正跑哪一步**、 + // 也看不出循环转到第几轮了。让光点沿着 exec 线跑, + // 一眼就知道执行到哪了 —— 尤其是循环里来回转的时候。 + // + // 只给 exec 线画:数据线是"值在那躺着等人来取",没有先后可言。 + if (edge.kind == "exec" && litEdge == meeting.edges.indexOf(edge)) { + val dots = 3 + for (k in 0 until dots) { + // 三个点错开相位,看起来像一串在跑 + val t = (flowPhase.value + k / dots.toFloat()) % 1f + val p = bezierAt( + start, + Offset(start.x + dx, start.y), + Offset(end.x - dx, end.y), + end, + t, + ) + drawCircle(Color.White, radius = 4.5.dp.toPx(), center = p) + drawCircle(Doubao.Blue, radius = 3.dp.toPx(), center = p) + } + } + } + + // 引脚。画在最上层,用户看得见"从哪儿拉出去、往哪儿接进来"。 + meeting.nodes.forEach { node -> + val linkingKindNow = linkingFrom?.kind + inputPins(node, emptyList(), varTypeMap).forEachIndexed { i, pin -> + val p = px(pinPos(node, i, isOutput = false)) + // 接不上的引脚淡化:蓝图里会直接报"类型不兼容", + // 这里用变淡表示,比"点了没反应"清楚得多 + val usable = linkingKindNow == null || pin.accepts_(linkingKindNow) + val alpha = if (usable) 1f else 0.25f + if (pin.kind == "exec") { + drawExecPin(p, PORT_R.dp.toPx(), filled = true, + tint = EXEC_BORDER.copy(alpha = alpha)) + } else { + // 数据入口按**类型**上色(白 exec / 绿 str / 蓝 num / 红 bool) + drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = p) + drawCircle(pinColorOf(pin).copy(alpha = alpha), + radius = PORT_R.dp.toPx(), center = p) + } + } + outputPins(node, emptyList(), varTypeMap).forEachIndexed { i, pin -> + val p = px(pinPos(node, i, isOutput = true)) + // 分支 exec(真/假)保留绿/红:那表达的是"走哪条", + // 不是"什么类型",和按类型上色不冲突。 + // 其余一律按**类型**上色。 + val c = when { + pin.kind == "exec" && pin.key == "true" -> Color(0xFF34A853) + pin.kind == "exec" && pin.key == "false" -> Color(0xFFEA4335) + pin.kind == "exec" -> EXEC_BORDER + else -> pinColorOf(pin) + } + // linkingFrom 编码是 "节点id\u0000种类\u0000分支" + val active = linkingFrom?.let { + it.nodeId == node.id && it.kind == pin.kind && it.branch == pin.key + } == true + val usableOut = linkingKindNow == null || pin.accepts_(linkingKindNow) + if (pin.kind == "exec") { + drawExecPin(p, (if (active) PORT_R + 1.5f else PORT_R).dp.toPx(), + filled = true, + tint = if (usableOut) c else c.copy(alpha = 0.25f)) + } else { + drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = p) + drawCircle( + color = c, + radius = (if (active) PORT_R + 2f else PORT_R).dp.toPx(), + center = p, + ) + } + // 正在连线的那个引脚加一圈外环,"我点的是这个"要看得见 + if (active) { + drawCircle( + color = (if (pin.kind == "exec") c else c).copy(alpha = 0.35f), + radius = (PORT_R + 5f).dp.toPx(), + center = p, + style = Stroke(width = 2.dp.toPx()), + ) + } + } + } + } + + // 节点 + meeting.nodes.forEach { node -> + val status = liveStatus[node.id] ?: "" + NodeCard( + node = node, + status = status, + output = nodeOutputs[node.id] ?: "", + warn = nodeWarn[node.id] ?: "", + linking = linkingFrom?.nodeId == node.id, + inDegree = meeting.edges.count { it.to == node.id }, + outDegree = meeting.edges.count { it.from == node.id }, + linkingKind = linkingFrom?.kind, + customDefs = vm.meetingMeta.customNodes, + varTypes = varTypeMap, + modifier = Modifier.offset(node.x.dp, node.y.dp), + ) + } + } + } + + // 运行输入 + Row( + Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OutlinedTextField( + value = runInput, + onValueChange = { runInput = it }, + modifier = Modifier.weight(1f), + placeholder = { Text("初始输入节点的文本留空时,用这句", fontSize = 12.sp) }, + textStyle = TextStyle(fontSize = 13.sp), + maxLines = 2, + ) + Spacer(Modifier.width(8.dp)) + // 跑起来就变成「停止」;空着的时候给个「结果」看整场输出。 + // + // 为什么停止按钮要紧:一场会议可能跑好几分钟(每个智能体都是一次 + // 完整模型调用),发现配错了却停不下来是最让人抓狂的。 + if (running) { + PrimaryButton("停止", danger = true) { + vm.stopMeeting() + running = false + // 把还在"跑"的节点标成中断,别让界面上一直转圈 + liveStatus.keys.toList().forEach { key -> + if (liveStatus[key] == "running") liveStatus[key] = "stopped" + } + } + } else { + PrimaryButton("运行") { + if (dirty) persist() + running = true + runError = "" + nodeOutputs.clear() + liveStatus.clear() + vm.runMeeting( + meetingId = meeting.id, + input = runInput, + // ★ 走和顶栏 ▶ **同一个**事件处理函数(见 applyMeetingEvent 的注释: + // 抄两份的结果就是"底部按钮跑完,标签页是空的") + onEvent = { ev -> + applyMeetingEvent( + ev = ev, + liveStatus = liveStatus, + nodeOutputs = nodeOutputs, + liveResults = liveResults, + liveTrace = liveTrace, + nodeWarn = nodeWarn, + nodeVerdict = nodeVerdict, + meetingEdges = meeting.edges, + onRunning = { nowRunning = it }, + onLitEdge = { litEdge = it }, + onDone = { running = false; runError = it }, + ) + }, + onError = { msg -> running = false; runError = msg }, + ) + } + } + if (nodeOutputs.isNotEmpty()) { + Spacer(Modifier.width(8.dp)) + Text( + "结果", + color = Doubao.Blue, + fontSize = 14.sp, + modifier = Modifier + .clip(RoundedCornerShape(10.dp)) + .clickable { showResult = true } + .padding(horizontal = 8.dp, vertical = 8.dp), + ) + } + } + // ★ 点中一条连线后,这里出现「删除」。 + // 蓝图里是 Alt+点引脚 断开;手机上没键盘,改成"点线选中、再点删除"—— + // 比长按好发现,也不会误删。 + selectedEdge?.let { idx -> + val edge = meeting.edges.getOrNull(idx) + if (edge != null) { + Row( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp) + .clip(RoundedCornerShape(10.dp)) + .background(Doubao.Blue.copy(alpha = 0.08f)) + .padding(horizontal = 10.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "已选中一条连线(${kindLabel(edge.kind)})", + fontSize = 12.sp, + color = doubaoTextSecondary(), + modifier = Modifier.weight(1f), + ) + Text( + "删除", + color = MaterialTheme.colorScheme.error, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + meeting = meeting.copy( + edges = meeting.edges.filterIndexed { i, _ -> i != idx }, + ) + selectedEdge = null + dirty = true + persist() + } + .padding(horizontal = 10.dp, vertical = 4.dp), + ) + Spacer(Modifier.width(4.dp)) + Text( + "取消", + color = doubaoTextSecondary(), + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { selectedEdge = null } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + } + } + } + + // 结果单开一屏(不是弹窗):一次运行可能几十轮、每轮都有大段输出, + // 弹窗那点地方根本放不下,也没法滚动着对照着看。 + if (showResult) { + MeetingResultScreen( + vm = vm, + meeting = meeting, + liveOutputs = nodeOutputs, + liveTrace = liveTrace.toList(), + liveResults = liveResults.toList(), + onBack = { showResult = false }, + ) + return + } + + if (showMenu) { + EditorMenuDialog( + sensitivity = dragSensitivity, + onSensitivity = { dragSensitivity = it }, + meeting = meeting, + onImport = { showMenu = false; showImport = true }, + onExportFile = { pendingExport = meetingJson(); exportLauncher.launch("${meeting.name.ifBlank { "doubao" }}.json") }, + onImportFile = { importLauncher.launch(arrayOf("application/json", "text/plain", "*/*")) }, + onExport = { json -> + clipboard.setText(androidx.compose.ui.text.AnnotatedString(json)) + android.widget.Toast + .makeText( + context, + "会议 JSON 已复制到剪贴板(${meeting.nodes.size} 个节点)", + android.widget.Toast.LENGTH_SHORT, + ) + .show() + }, + onDismiss = { showMenu = false }, + ) + } + + // 全屏积木编辑器(独立界面,不是对话框 —— 见 AGENTS.md) + blockEdit?.let { (nm, decl, blocks) -> + NodeBlockEditorScreen( + title = "搭积木", + fileName = nm, + initialBlocks = blocks, + initialDecl = decl, + onFileName = { blockEdit = Triple(it, decl, blocks) }, + onDecl = { blockEdit = Triple(nm, it, blocks) }, + onSave = { code -> + vm.launch { + val r = runCatching { vm.importNodeFile(nm, code) } + nodeMgrMsg = r.fold( + onSuccess = { "已保存:$it" }, + onFailure = { "存不了:${it.message.orEmpty().take(300)}" }, + ) + if (r.isSuccess) { + blockEdit = null + refreshNodeFiles() + showNodeMgr = true + } + } + }, + onBack = { blockEdit = null; showNodeMgr = true }, + ) + return@MeetingEditorScreen + } + + // 节点管理(全屏,不是弹窗 —— 见 AGENTS.md) + if (showNodeMgr) { + if (nodeFiles.isEmpty() && nodeMgrMsg.isBlank()) { + LaunchedEffect(Unit) { refreshNodeFiles() } + } + NodeManagerScreen( + nodes = nodeFiles, + dir = vm.meetingMeta.customDir, + message = nodeMgrMsg, + onImport = { nodePicker.launch(arrayOf("text/x-python", "text/plain", "*/*")) }, + onNew = { + // 新建**直接进积木编辑器**(全屏)—— + // 新手不该一上来就面对一个空白代码框。 + // 想写代码的话,积木界面右上角有「代码」页。 + val (blocks0, decl0) = newBlocksStarter() + blockEdit = Triple("my_node.py", decl0, blocks0) + // ★ 必须关掉管理页:它在下面那个 if 里会先 return, + // 不关的话积木编辑器永远轮不到渲染 —— 表现就是"点了没反应"。 + showNodeMgr = false + }, + onEdit = { nf -> + // 从内核读**源码**(列表里只有摘要,没有正文) + vm.launch { + val o = runCatching { vm.readNode(nf.file) }.getOrElse { null } + if (o == null) { + nodeMgrMsg = "读不到这个文件的源码" + } else { + editFile = nf.file + editName = nf.file + editCode = o.optString("code") + // 同上:不关管理页的话编辑界面根本显示不出来 + showNodeMgr = false + } + } + }, + onExport = { nf -> + vm.launch { + val o = runCatching { vm.readNode(nf.file) }.getOrElse { null } + if (o == null) { + nodeMgrMsg = "读不到这个文件的源码" + } else { + pendingNodeExport = o.optString("code") + nodeExporter.launch(nf.file) + } + } + }, + onDelete = { nf -> + vm.launch { + val r = runCatching { vm.deleteNodeFile(nf.file) } + nodeMgrMsg = r.fold( + onSuccess = { "已删除:${nf.file}" }, + onFailure = { "删不掉:${it.message.orEmpty().take(200)}" }, + ) + refreshNodeFiles() + } + }, + onBack = { showNodeMgr = false }, + ) + return@MeetingEditorScreen + } + + // 现场编辑 / 新建 + if (editCode.isNotEmpty() || editFile == null && editName.isNotBlank()) { + // 现场编辑代码(全屏,不是弹窗 —— 见 AGENTS.md) + NodeCodeScreen( + fileName = editName, + initialCode = editCode, + onFileName = { editName = it }, + onBlocks = { + // 切到积木视图。 + // + // ★ 代码**解析不回**积木(那要写一个 Python 解析器,不值得), + // 所以给一块空白帽子起手。界面上说明白,别让用户以为代码被吞了。 + val (blocks0, decl0) = newBlocksStarter() + blockEdit = Triple(editName.ifBlank { "my_node.py" }, decl0, blocks0) + editCode = "" + editFile = null + }, + onSave = { code -> + val name = editName.ifBlank { "node.py" } + vm.launch { + val r = runCatching { vm.importNodeFile(name, code) } + nodeMgrMsg = r.fold( + onSuccess = { "已保存:$it" }, + onFailure = { "存不了:${it.message.orEmpty().take(300)}" }, + ) + if (r.isSuccess) { + editCode = "" + editFile = null + showNodeMgr = true + refreshNodeFiles() + } + } + }, + onBack = { + editCode = "" + editFile = null + editName = "" + showNodeMgr = true + }, + ) + return@MeetingEditorScreen + } + + if (showImport) { + ImportDialog( + current = meeting, + clipboardText = clipboard.getText()?.text.orEmpty(), + onImport = { m -> + // ★ 只换图,不换名字和 id —— 用户是在"编辑这一场会议", + // 导入的是内容不是身份。名字保留着,他还能认出这是哪个会议。 + meeting = meeting.copy(nodes = m.nodes, edges = m.edges, vars = m.vars) + dirty = true + persist() + showImport = false + android.widget.Toast + .makeText( + context, + "已导入 ${m.nodes.size} 个节点", + android.widget.Toast.LENGTH_SHORT, + ) + .show() + }, + onDismiss = { showImport = false }, + ) + } + + if (showVars) { + VarManagerDialog( + vars = meeting.vars, + onSave = { list -> + meeting = meeting.copy(vars = list) + dirty = true + persist() + showVars = false + }, + onDismiss = { showVars = false }, + ) + } + + configTarget?.let { target -> + NodeConfigDialog( + node = target, + meta = vm.meetingMeta, + // 变量名从**登记表**来:变量是会议级的,节点只是引用它。 + // 这样"写"和"读"用的是同一个类型,不会两处各写一个打架。 + knownVarNames = meeting.vars.map { it.name }.filter { it.isNotBlank() }, + meetingVars = meeting.vars, + onDismiss = { configTarget = null }, + onSave = { updated -> + updateNode(updated) + persist() + configTarget = null + }, + onDelete = { + meeting = meeting.copy( + nodes = meeting.nodes.filter { it.id != target.id }, + // 连带删掉挂在它身上的连线,别留悬空边 + edges = meeting.edges.filter { it.from != target.id && it.to != target.id }, + ) + dirty = true + persist() + configTarget = null + }, + ) + } + + if (adding) { + AlertDialog( + onDismissRequest = { adding = false }, + title = { Text("加节点", fontSize = 16.sp) }, + text = { + // ★ 要能滚:节点类型已经有 10 种,一屏放不下 —— + // 不能滚的话「转换」「运算」就永远在屏幕外面,等于没加。 + Column( + Modifier + .fillMaxWidth() + .heightIn(max = 440.dp) + .verticalScroll(rememberScrollState()), + ) { + // 📥 导入节点文件(放在自定义节点列表**上面**:先能导入,才谈得上用) + Column( + Modifier.fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .clickable { adding = false; nodeMgrMsg = ""; showNodeMgr = true } + .padding(horizontal = 10.dp, vertical = 10.dp), + ) { + Text("📥 导入 / 管理节点…", fontSize = 14.sp, color = Doubao.Blue) + Spacer(Modifier.height(2.dp)) + Text( + "导入 .py、新建、现场编辑、导出、删除都在这里。文件放在:\n${vm.meetingMeta.customDir}", + fontSize = 10.sp, + color = doubaoTextSecondary(), + lineHeight = 14.sp, + ) + if (nodeImportMsg.isNotBlank()) { + Spacer(Modifier.height(4.dp)) + Text( + nodeImportMsg, + fontSize = 11.sp, + color = if (nodeImportMsg.startsWith("已导入")) Color(0xFF34A853) + else MaterialTheme.colorScheme.error, + lineHeight = 15.sp, + ) + } + } + HorizontalDivider(Modifier.padding(vertical = 6.dp), thickness = 0.5.dp) + // ★ **用户用 Python 拓展出来的节点**,列在内置节点前面。 + // 引脚是从内核读的,用户往 nodes/ 丢一个 .py,这里就多一项。 + vm.meetingMeta.customNodes.forEach { cd -> + val bad = cd.error.isNotBlank() + Column( + Modifier.fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .clickable(enabled = !bad) { + val n = MeetingNode( + id = "n_${System.currentTimeMillis().toString(36)}", + type = "custom", + customKey = cd.key, + x = 120f + meeting.nodes.size * 26f, + y = 120f + meeting.nodes.size * 26f, + title = cd.label, + ) + meeting = meeting.copy(nodes = meeting.nodes + n) + dirty = true + persist() + adding = false + } + .padding(horizontal = 10.dp, vertical = 8.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "🐍 " + cd.label, + fontSize = 14.sp, + color = if (bad) MaterialTheme.colorScheme.error else doubaoText(), + ) + if (cd.file.isNotBlank()) { + Spacer(Modifier.width(6.dp)) + Text( + cd.file, + fontSize = 10.sp, + color = doubaoTextSecondary(), + ) + } + } + Text( + if (bad) { + cd.error + } else { + cd.desc.ifBlank { + "入 ${cd.dataInputs.size} · 出 ${cd.dataOutputs.size} · exec 分支 ${cd.execOutputs.size} 路" + } + }, + fontSize = 11.sp, + color = if (bad) MaterialTheme.colorScheme.error else doubaoTextSecondary(), + lineHeight = 15.sp, + ) + } + } + if (vm.meetingMeta.customNodes.isNotEmpty()) { + HorizontalDivider(Modifier.padding(vertical = 6.dp), thickness = 0.5.dp) + } + + vm.meetingMeta.nodeTypes.forEach { (key, label, desc) -> + Column( + Modifier.fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .clickable { + val n = MeetingNode( + id = "n_${System.currentTimeMillis().toString(36)}", + type = key, + // 新节点摆在偏右下,避免正好压住已有节点; + // 画布会跟着长,不用管边界 + x = 120f + meeting.nodes.size * 26f, + y = 120f + meeting.nodes.size * 26f, + title = label, + ) + meeting = meeting.copy(nodes = meeting.nodes + n) + dirty = true + persist() + adding = false + } + .padding(vertical = 8.dp, horizontal = 4.dp), + ) { + Text(label, fontSize = 15.sp, color = doubaoText()) + Text(desc, fontSize = 11.sp, color = doubaoTextSecondary()) + } + } + } + }, + confirmButton = { TextButton(onClick = { adding = false }) { Text("取消") } }, + ) + } + } + + /** + * 三次贝塞尔上的一点。 + * + * 连线命中判断要用:连线是曲线,不能像节点那样用矩形判。 + * 沿着曲线采一串点、找最近的,够简单也够准。 + */ + private fun bezierAt(p0: Offset, p1: Offset, p2: Offset, p3: Offset, t: Float): Offset { + val mt = 1f - t + val a = mt * mt * mt + val b = 3f * mt * mt * t + val c = 3f * mt * t * t + val d = t * t * t + return Offset( + a * p0.x + b * p1.x + c * p2.x + d * p3.x, + a * p0.y + b * p1.y + c * p2.y + d * p3.y, + ) + } + + /** 连线离某个点最近有多远(像素)。用来判断"这一下点的是不是这条线"。 */ + private fun distanceToWire( + start: Offset, end: Offset, dx: Float, target: Offset, + ): Float { + val c1 = Offset(start.x + dx, start.y) + val c2 = Offset(end.x - dx, end.y) + var best = Float.MAX_VALUE + // 24 段够细了:连线上最细的弯也就几个像素 + for (i in 0..24) { + val p = bezierAt(start, c1, c2, end, i / 24f) + val d = (p - target).getDistance() + if (d < best) best = d + } + return best + } + + /** + * 一个引脚。照 UE 蓝图分四类: + * + * exec 执行引脚(白色三角):**决定执行顺序**,不传数据。 + * str / bool / num 数据引脚(彩色圆点):传值,类型必须对得上。 + * + * key 是"这条引脚对应哪个分支"(判断/while 用),label 是画在节点上的字。 + * + * accepts 是"这个入口能接哪些类型",空表示只接自己的 kind。 + * ★ while 的条件要同时收 bool 和 str:条件是"真/假",bool 最自然, + * 但**变量永远是字符串** —— 而循环条件几乎总是来自变量(不然没法每轮变化)。 + * 只收 bool 的话 while 连不上任何动态条件,等于没法用。 + */ + private data class PinSpec( + val kind: String, + val key: String, + val label: String, + val accepts: List = emptyList(), + /** + * exec 引脚的分支名。自定义节点可以有**多个 exec 出口**(= N 路分支), + * 连线时要把它写进 edge.branch,引擎才知道该走哪条。 + * 内置节点(判断/while)的 true/false/done/body 是同一套机制。 + */ + val branch: String = "", + ) { + /** 能不能接下 fromKind 这条线 */ + fun accepts_(fromKind: String): Boolean = + (if (accepts.isEmpty()) listOf(kind) else accepts).contains(fromKind) + } + + /** + * 左边一列的引脚(从上到下)。 + * + * ★ **纯节点**(读变量 / 值)没有 exec 入:它们是蓝图里的 Get / 常量, + * 不在执行链上,值是被需要的节点运行时拉取的 —— 这就是"读变量只有输出"的真正原因。 + * ★ 开始事件也没有 exec 入:它是整张图的起点。 + */ + /** 任何数据类型都能接:除了 while 的条件,其他数据入口要的都是文本(见下面注释) */ + private val ANY_DATA = listOf("str", "bool", "num", "list") + + /** + * 运算表。必须和引擎里的 `OPS` **一致** —— + * 两边对不上就会出现"界面上选得到、保存时被丢掉"这种说不清的问题。 + */ + private val OPS_UI = listOf( + "add" to "加 +", "sub" to "减 −", "mul" to "乘 ×", "div" to "除 ÷", - "mod" to "取余 %", "concat" to "拼接", "eq" to "等于 =", "ne" to "不等于 ≠", - "gt" to "大于 >", "lt" to "小于 <", "neg" to "取反(负号)", "not" to "逻辑非 !", + + "mod" to "取余 %", "concat" to "拼接", + + "gt" to "大于 >", "lt" to "小于 <", "gte" to "大于等于 ≥", "lte" to "小于等于 ≤", + + "eq" to "等于 =(数字)", "ne" to "不等于 ≠(数字)", "streq" to "文本等于 ==", "strne" to "文本不等于 !=", + + // ★ 逻辑 / 位运算:和引擎的 OPS 一一对应,别只加一边 + + "and" to "与 and", "or" to "或 or", "xor" to "异或 xor", + + "shl" to "左移 <<", "shr" to "右移 >>", + "neg" to "取反(负号)", "not" to "逻辑非 !", + // ★ 单目运算:之前只在引擎里有,界面选不到 —— verify-ops.py 抓出来的 + // 列表只支持这两个(不做删除/排序:列表在会议里的用途是"攒东西") + "append" to "追加到列表", "clear" to "清空列表", + ) + + /** 运算的 (输入类型, 输出类型, 要几个输入)。和引擎的 OPS 一一对应。 */ + private fun opSpec(key: String): Triple = when (key) { + "concat" -> Triple("str", "str", 2) - "eq", "ne" -> Triple("str", "bool", 2) - "gt", "lt" -> Triple("num", "bool", 2) + + "eq", "ne", "gt", "lt", "gte", "lte" -> Triple("num", "bool", 2) + + "streq", "strne" -> Triple("str", "bool", 2) + + "and", "or", "xor" -> Triple("bool", "bool", 2) + + "shl", "shr" -> Triple("num", "num", 2) + "neg" -> Triple("num", "num", 1) + "not" -> Triple("bool", "bool", 1) + // 追加:A 是列表、B 是要加进去的东西(什么类型都行);清空:只有一个入口 + "append" -> Triple("list", "list", 2) + "clear" -> Triple("list", "list", 1) + else -> Triple("num", "num", 2) + } + + /** 运算的显示名 */ + private fun opLabel(key: String): String = + OPS_UI.firstOrNull { it.first == key }?.second ?: key -/** - * 节点的输入引脚。 - * - * ★ `custom` 的引脚来自**内核**(用户在 nodes/ 里写的声明),不在这里硬编码 —— - * 这样"加一种节点"就真的只是丢一个 .py,不用改 Kotlin。 - * meta 没加载到时给一个宽松的默认(不收 exec、一个文本入口), - * 免得卡片画不出引脚、用户以为节点坏了。 - */ -private fun inputPins( - node: MeetingNode, - custom: List = emptyList(), - /** 变量登记表:写变量的入口类型要按它查(和读变量的出口对称) */ - varTypes: Map = emptyMap(), -): List = when (node.type) { - "custom" -> { - val d = custom.firstOrNull { it.key == node.customKey } - if (d == null) { - listOf(PinSpec("exec", "", "▶"), PinSpec("str", "", "输入", accepts = ANY_DATA)) - } else { - buildList { - // 自己声明的 exec 入口(没有就不画 —— 纯数据节点) - d.inputs.filter { it.type == "exec" }.forEach { add(PinSpec("exec", "", "▶")) } - d.dataInputs.forEach { p -> - add(PinSpec(p.type, p.name, p.name, accepts = listOf(p.type))) - } - } - } - } - // 分支:收一个真假,走真/假两条 exec - "branch" -> listOf( - PinSpec("exec", "", "▶"), - // 条件收得宽一点:变量和上游多半给的是 "true"/"1" 这类文本 - PinSpec("bool", "", "条件", accepts = listOf("bool", "str", "num")), - ) - "start", "readvar", "value" -> emptyList() - // 转换:什么都收(出口类型在配置面板里选) - // Python 节点:执行节点 —— 上游什么都要能收(它就是拿来处理任意内容的) - "py" -> listOf( - PinSpec("exec", "", "▶"), - PinSpec("str", "", "输入", accepts = ANY_DATA), - ) - "cast" -> listOf(PinSpec("str", "", "值", accepts = ANY_DATA)) - // 运算:入口类型由算子决定(加法要数字、拼接要文本),单目只有一个入口 - "op" -> { - val key = node.op.ifBlank { "add" } - val (inType, _, arity) = opSpec(key) - if (arity == 1) { - listOf(PinSpec(inType, "a", if (inType == "num") "数" else "值")) - } else if (key == "append") { - // ★ 追加的第二个入口是"要加进去的东西",**什么类型都行** —— - // 往里塞一句话、一个数字、一个真假都对。 - listOf( - PinSpec("list", "a", "列表"), - PinSpec("str", "b", "加什么", accepts = ANY_DATA), - ) - } else { - listOf( - PinSpec(inType, "a", "A"), - PinSpec(inType, "b", "B"), - ) - } - } - "while" -> listOf( - PinSpec("exec", "", "▶"), - // 条件:bool 最自然,但变量是字符串,所以两种都收(见 PinSpec 注释) - PinSpec("bool", "", "条件", accepts = listOf("bool", "str", "num")), - ) - "judge" -> listOf( - PinSpec("exec", "", "▶"), - PinSpec("str", "", "值"), - ) - "var" -> { - // ★ 入口类型**按变量登记表**,而且**严格**(和读变量的出口对称)。 - // - // 之前写成"不卡类型"是治错了病:让用户难受的不是"卡得严", - // 是"接不上还不说为什么"。所以现在: - // · 类型跟着变量走(颜色也变,一眼知道这个入口要什么) - // · 不匹配就接不上,但**当场弹出说明**告诉他加转换节点 - val vt = varTypes[node.varName] ?: "str" - listOf( - PinSpec("exec", "", "▶"), - PinSpec(vt, "", pinTypeLabel(vt), accepts = listOf(vt)), - ) - } - // ★ end(最终输出)**什么类型都收** —— 引擎那边 NODE_DATA_IN['end'] - // 就是四种全要。这里写死 str 的话,数字/列表接到最终输出会被界面拒掉。 - "end" -> listOf( - PinSpec("exec", "", "▶"), - PinSpec("str", "", "值", accepts = ANY_DATA), - ) - else -> listOf( - PinSpec("exec", "", "▶"), - PinSpec("str", "", "输入"), - ) -} + /** - * 右边一列的引脚(从上到下)。 + + * 节点的输入引脚。 + * - * ★ 判断节点有**两条 exec 出线**(真/假)—— 相当于蓝图里的 Branch。 - * ★ while 有**两条 exec 出线**(循环体/结束)—— 相当于蓝图里的 While Loop。 - * ★ 写变量**没有数据出线**(存进去的值不从它往下传),但有 exec 出线。 - * ★ 纯节点(读变量 / 值)**只有数据出线**,没有任何 exec 引脚。 + + * ★ `custom` 的引脚来自**内核**(用户在 nodes/ 里写的声明),不在这里硬编码 —— + + * 这样"加一种节点"就真的只是丢一个 .py,不用改 Kotlin。 + + * meta 没加载到时给一个宽松的默认(不收 exec、一个文本入口), + + * 免得卡片画不出引脚、用户以为节点坏了。 + */ -/** 节点的输出引脚(custom 同样来自内核的定义) */ -private fun outputPins( + +private fun inputPins( + node: MeetingNode, + custom: List = emptyList(), - /** - * 变量登记表:名字 → 类型。 - * - * ★ 读变量的出口类型**必须**从这里查 —— 写死 str 的话, - * 数字变量接不到运算节点上去("运算为啥不给数字类型连"就是这么来的)。 - */ + + /** 变量登记表:写变量的入口类型要按它查(和读变量的出口对称) */ + varTypes: Map = emptyMap(), + ): List = when (node.type) { + "custom" -> { + val d = custom.firstOrNull { it.key == node.customKey } + if (d == null) { - listOf(PinSpec("exec", "", "▶"), PinSpec("str", "", "输出")) + + listOf(PinSpec("exec", "", "▶"), PinSpec("str", "", "输入", accepts = ANY_DATA)) + } else { + buildList { - // 多个 exec 出口 = N 路分支,每条一个引脚(名字就是分支名) - d.execOutputs.forEach { add(PinSpec("exec", it.name, it.name, branch = it.name)) } - d.dataOutputs.forEachIndexed { i, p -> - add( - PinSpec( - p.type, - p.name, - p.name + if (i > 0) "(接不了线)" else "", - ), - ) + + // 自己声明的 exec 入口(没有就不画 —— 纯数据节点) + + d.inputs.filter { it.type == "exec" }.forEach { add(PinSpec("exec", "", "▶")) } + + d.dataInputs.forEach { p -> + + add(PinSpec(p.type, p.name, p.name, accepts = listOf(p.type))) + } + } + } + } - // 分支:真 / 假两条 exec 出口 + + // 分支:收一个真假,走真/假两条 exec + "branch" -> listOf( - PinSpec("exec", "true", "真 ▶"), - PinSpec("exec", "false", "假 ▶"), + + PinSpec("exec", "", "▶"), + + // 条件收得宽一点:变量和上游多半给的是 "true"/"1" 这类文本 + + PinSpec("bool", "", "条件", accepts = listOf("bool", "str", "num")), + ) - "end" -> emptyList() - // ★ 读变量的出口类型**必须按变量登记表**,不能写死 str。 - // - // 写死 str 的后果:一个 num 变量 → 读变量 → 运算 的线**接不上** - // (运算的 num 入口只收 num,而读变量声称自己给 str)。 - // 引擎那边 _data_out_type 本来就是对的做法,界面这份是漏了 - // —— 用户报的"运算为啥不给数字类型连"就是这个。 - "readvar" -> listOf( - PinSpec(varTypes[node.varName] ?: "str", "", "值"), - ) - // 转换:出口类型就是它要转成的那个类型 - // Python 节点:执行节点,交出文本 + + "start", "readvar", "value" -> emptyList() + + // 转换:什么都收(出口类型在配置面板里选) + + // Python 节点:执行节点 —— 上游什么都要能收(它就是拿来处理任意内容的) + "py" -> listOf( + PinSpec("exec", "", "▶"), - PinSpec("str", "", "输出"), - ) - "cast" -> listOf(PinSpec(node.castTo.ifBlank { "str" }, "", "值")) - // 运算:出口类型由算子决定(加法出数字、比较出真假) - "op" -> listOf(PinSpec(opSpec(node.op.ifBlank { "add" }).second, "", "结果")) - // 值节点的类型由它自己选(str / bool / num)—— 这决定了它能接到哪去 - "value" -> listOf(PinSpec(node.valueType.ifBlank { "str" }, "", "值")) - "judge" -> listOf( - PinSpec("exec", "true", "真 ▶"), - PinSpec("exec", "false", "假 ▶"), + + PinSpec("str", "", "输入", accepts = ANY_DATA), + ) + + "cast" -> listOf(PinSpec("str", "", "值", accepts = ANY_DATA)) + + // 运算:入口类型由算子决定(加法要数字、拼接要文本),单目只有一个入口 + + "op" -> { + + val key = node.op.ifBlank { "add" } + + val (inType, _, arity) = opSpec(key) + + if (arity == 1) { + + listOf(PinSpec(inType, "a", if (inType == "num") "数" else "值")) + + } else if (key == "append") { + + // ★ 追加的第二个入口是"要加进去的东西",**什么类型都行** —— + + // 往里塞一句话、一个数字、一个真假都对。 + + listOf( + + PinSpec("list", "a", "列表"), + + PinSpec("str", "b", "加什么", accepts = ANY_DATA), + + ) + + } else { + + listOf( + + PinSpec(inType, "a", "A"), + + PinSpec(inType, "b", "B"), + + ) + + } + + } + "while" -> listOf( - PinSpec("exec", "body", "循环体 ▶"), - PinSpec("exec", "done", "结束 ▶"), - ) - "var" -> listOf(PinSpec("exec", "", "▶")) - "start" -> listOf( + PinSpec("exec", "", "▶"), - PinSpec("str", "", "输出"), + + // 条件:bool 最自然,但变量是字符串,所以两种都收(见 PinSpec 注释) + + PinSpec("bool", "", "条件", accepts = listOf("bool", "str", "num")), + ) + + "judge" -> listOf( + + PinSpec("exec", "", "▶"), + + PinSpec("str", "", "值"), + + ) + + "var" -> { + + // ★ 入口类型**按变量登记表**,而且**严格**(和读变量的出口对称)。 + + // + + // 之前写成"不卡类型"是治错了病:让用户难受的不是"卡得严", + + // 是"接不上还不说为什么"。所以现在: + + // · 类型跟着变量走(颜色也变,一眼知道这个入口要什么) + + // · 不匹配就接不上,但**当场弹出说明**告诉他加转换节点 + + val declType = varTypes[node.varName] ?: "str" + // ★ 列表变量:入口是 **str**(追加的是"一项内容",不是整个列表)。 + // 入口写成 list 的话,用户得先拼一个 JSON 数组才能往里加一项 —— 太别扭了。 + // 往列表里塞数字/真假怎么办?先过个转换节点转成文本(列表存的就是文本)。 + val vt = if (declType == "list") "str" else declType + val vtLabel = if (declType == "list") "追加的文本" else pinTypeLabel(vt) + listOf( + + PinSpec("exec", "", "▶"), + + PinSpec(vt, "", vtLabel, accepts = listOf(vt)), + + ) + + } + + // ★ end(最终输出)**什么类型都收** —— 引擎那边 NODE_DATA_IN['end'] + + // 就是四种全要。这里写死 str 的话,数字/列表接到最终输出会被界面拒掉。 + + "end" -> listOf( + + PinSpec("exec", "", "▶"), + + PinSpec("str", "", "值", accepts = ANY_DATA), + + ) + else -> listOf( + PinSpec("exec", "", "▶"), - PinSpec("str", "", "输出"), + + PinSpec("str", "", "输入"), + ) + } + + +/** + + * 右边一列的引脚(从上到下)。 + + * + + * ★ 判断节点有**两条 exec 出线**(真/假)—— 相当于蓝图里的 Branch。 + + * ★ while 有**两条 exec 出线**(循环体/结束)—— 相当于蓝图里的 While Loop。 + + * ★ 写变量**没有数据出线**(存进去的值不从它往下传),但有 exec 出线。 + + * ★ 纯节点(读变量 / 值)**只有数据出线**,没有任何 exec 引脚。 + + */ + +/** 节点的输出引脚(custom 同样来自内核的定义) */ + +private fun outputPins( + + node: MeetingNode, + + custom: List = emptyList(), + + /** + + * 变量登记表:名字 → 类型。 + + * + + * ★ 读变量的出口类型**必须**从这里查 —— 写死 str 的话, + + * 数字变量接不到运算节点上去("运算为啥不给数字类型连"就是这么来的)。 + + */ + + varTypes: Map = emptyMap(), + +): List = when (node.type) { + + "custom" -> { + + val d = custom.firstOrNull { it.key == node.customKey } + + if (d == null) { + + listOf(PinSpec("exec", "", "▶"), PinSpec("str", "", "输出")) + + } else { + + buildList { + + // 多个 exec 出口 = N 路分支,每条一个引脚(名字就是分支名) + + d.execOutputs.forEach { add(PinSpec("exec", it.name, it.name, branch = it.name)) } + + d.dataOutputs.forEachIndexed { i, p -> + + add( + + PinSpec( + + p.type, + + p.name, + + p.name + if (i > 0) "(接不了线)" else "", + + ), + + ) + + } + + } + + } + + } + + // 分支:真 / 假两条 exec 出口 + + "branch" -> listOf( + + PinSpec("exec", "true", "真 ▶"), + + PinSpec("exec", "false", "假 ▶"), + + ) + + "end" -> emptyList() + + // ★ 读变量的出口类型**必须按变量登记表**,不能写死 str。 + + // + + // 写死 str 的后果:一个 num 变量 → 读变量 → 运算 的线**接不上** + + // (运算的 num 入口只收 num,而读变量声称自己给 str)。 + + // 引擎那边 _data_out_type 本来就是对的做法,界面这份是漏了 + + // —— 用户报的"运算为啥不给数字类型连"就是这个。 + + "readvar" -> listOf( + + PinSpec(varTypes[node.varName] ?: "str", "", "值"), + + ) + + // 转换:出口类型就是它要转成的那个类型 + + // Python 节点:执行节点,交出文本 + + "py" -> listOf( + + PinSpec("exec", "", "▶"), + + PinSpec("str", "", "输出"), + + ) + + "cast" -> listOf(PinSpec(node.castTo.ifBlank { "str" }, "", "值")) + + // 运算:出口类型由算子决定(加法出数字、比较出真假) + + "op" -> listOf(PinSpec(opSpec(node.op.ifBlank { "add" }).second, "", "结果")) + + // 值节点的类型由它自己选(str / bool / num)—— 这决定了它能接到哪去 + + "value" -> listOf(PinSpec(node.valueType.ifBlank { "str" }, "", "值")) + + "judge" -> listOf( + + PinSpec("exec", "true", "真 ▶"), + + PinSpec("exec", "false", "假 ▶"), + + ) + + "while" -> listOf( + + PinSpec("exec", "body", "循环体 ▶"), + + PinSpec("exec", "done", "结束 ▶"), + + ) + + "var" -> listOf(PinSpec("exec", "", "▶")) + + "start" -> listOf( + + PinSpec("exec", "", "▶"), + + PinSpec("str", "", "输出"), + + ) + + else -> listOf( + + PinSpec("exec", "", "▶"), + + PinSpec("str", "", "输出"), + + ) + +} + + + /* ---- UE 蓝图式的节点尺寸:标题栏 + 引脚行 + 内容区 ---- */ + + /** 顶部彩色标题栏的高度 */ + private const val HEADER_H = 24f + /** 一行引脚占的高度 */ + private const val PIN_ROW_H = 21f + /** 引脚下面的内容区(预览文字 + 路数) */ + private const val BODY_H = 34f + + /** 引脚画多大 / 点多准。命中范围要大一圈,手指没那么准。 */ + private const val PORT_R = 5.5f + private const val PORT_HIT = 19f + + /** 节点高矮跟着引脚数走:判断节点两行出线、智能体进出各有两种,就高一些 */ + private fun nodeHeight( + node: MeetingNode, + customDefs: List = emptyList(), + varTypes: Map = emptyMap(), + ) : Float { + // 高度只看**引脚个数**,类型不影响(读变量的出口类型查不到也只是名字不对, + // 行数还是 1)—— 所以这里不给 varTypes 也画得对 + val rows = maxOf(inputPins(node, customDefs, varTypes).size, outputPins(node, customDefs, varTypes).size, 1) + return HEADER_H + rows * PIN_ROW_H + BODY_H + } + + /** + * 引脚的几何位置(dp,和节点坐标同一套)。 + * + * 第 index 个引脚在标题栏下面第 index 行、垂直居中。 + * 输入贴左边、输出贴右边 —— 和蓝图一致,连线从节点边缘出发 / 接入。 + */ + private fun pinPos(node: MeetingNode, index: Int, isOutput: Boolean): Offset { + val y = node.y + HEADER_H + PIN_ROW_H * index + PIN_ROW_H / 2f + val x = if (isOutput) node.x + NODE_W else node.x + return Offset(x, y) + } + + /** 按 (种类, 分支) 找输出引脚的序号;找不到就退回第一条(老数据容错) */ + private fun outPinIndex(node: MeetingNode, kind: String, branch: String): Int { + val pins = outputPins(node) + val exact = pins.indexOfFirst { it.kind == kind && (it.kind != "exec" || it.key == branch) } + if (exact >= 0) return exact + val byBranch = pins.indexOfFirst { it.kind == "exec" && it.key == branch } + return if (byBranch >= 0) byBranch else 0 + } + + /** + * 输入端口的位置。 + * + * data 线接"值/输入"那条;exec 线接"▶"那条。 + * 找不到对应种类时退回第一条 —— 老会议里没有 kind 字段,边一律当 exec, + * 而老图的节点只有一条入线,退回第一条正好对上。 + */ + private fun portIn( + node: MeetingNode, + kind: String, + /** 变量登记表(写变量的入口类型按它查,才能定位到对的行) */ + varTypes: Map = emptyMap(), + /** + * 边上记的引脚 key。有就**按 key 精确定位** —— + * 运算的 A/B 都是 num,不靠它分不开(表现就是两条线都落在 A 上、B 收不到)。 + */ + pinKey: String = "", + ) : Offset { + val pins = inputPins(node, emptyList(), varTypes) + // ① 边上有引脚 key:精确匹配(新会议都走这条) + if (pinKey.isNotBlank()) { + val byKey = pins.indexOfFirst { it.key == pinKey } + if (byKey >= 0) return pinPos(node, byKey, isOutput = false) + } + // ② 没记引脚(老会议):退回按类型找 + // ★ 按"这个入口能不能接 kind"来找,不是 kind 相等 —— + // while 的条件入口能接 bool 和 str,两种情况都得能定位到同一条引脚。 + val index = pins.indexOfFirst { it.accepts_(kind) } + return pinPos(node, if (index >= 0) index else 0, isOutput = false) + } + + /** 输出端口的位置 */ + private fun portOut( + node: MeetingNode, + kind: String, + branch: String, + /** 边上记的引脚 key(同 portIn;只有自定义节点有多个同名类型的数据出口时才用得上) */ + pinKey: String = "", + ): Offset { + val pins = outputPins(node) + if (pinKey.isNotBlank()) { + val byKey = pins.indexOfFirst { it.key == pinKey } + if (byKey >= 0) return pinPos(node, byKey, isOutput = true) + } + return pinPos(node, outPinIndex(node, kind, branch), isOutput = true) + } + + /** + * 正在连线时记住"从哪条引脚拉出来的"。 + * + * ★ 用数据类而不是拼字符串:一开始拼了 `"$id\u0000$kind\u0000$branch"`, + * 结果转义在几道工具链里被搞乱,编译报了一堆 Char/String 不匹配。 + * 三个字段就该用三个字段,别为了省事把结构化数据拍成字符串。 + */ + /** + * 运行链上的一步。 + * + * ★ 为什么要带上 verdict / branch:结果界面要写明"判断走了真还是假"、 + * "while 这一轮是继续还是结束"。只存节点名 + 输出的话,回看时 + * 只看到一段文本,完全不知道当时判成了什么。 + */ + private data class TraceStep( + val nodeId: String, + val title: String, + val nodeType: String, + val run: Int, + val verdict: Boolean? = null, + val branch: String = "", + val note: String = "", + ) + + private data class LinkFrom(val nodeId: String, val kind: String, val branch: String) + + /** 执行引脚画成白色三角、数据引脚画成彩色圆点 —— 蓝图就靠这个一眼分辨 */ + /** + * 变量管理:会议级的一张登记表。 + * + * ★ 为什么要单独一个界面:变量不属于任何节点 —— 一张图里同名变量只有一个, + * 「写变量」节点写它、「读变量」节点读它,靠名字关联。所以名字、**类型**、 + * 初始值这些得有个统一的地方配。 + * + * ★ 类型是**必选**的:数据引脚强类型,变量的类型决定了读它的那根线能接到哪去 + * (比如 while 的条件要 bool,那这个变量就得声明成 bool)。 + * 做成可选的话,用户不选时类型就是"猜"的,接不上时根本不知道为什么。 + * + * ★ 初始值:会议一开始就写进去,这样读变量第一轮就能读到东西, + * 不用非得先有个写变量节点跑过一遍。 + */ + @Composable + private fun VarManagerDialog( + vars: List, + onSave: (List) -> Unit, + onDismiss: () -> Unit, + ) { + // 编辑中的副本:点保存才生效,中途关掉不影响 + var draft by remember { mutableStateOf(vars) } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("变量", fontSize = 16.sp) }, + text = { + Column( + Modifier + .fillMaxWidth() + .heightIn(max = 440.dp) + .verticalScroll(rememberScrollState()), + ) { + Text( + "一张图里同名变量只有一个:「写变量」写它、「读变量」读它," + + "不用连线。类型是必选的,它决定读变量那根线能接到哪去。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + Spacer(Modifier.height(10.dp)) + + draft.forEachIndexed { i, v -> + Card( + Modifier.fillMaxWidth().padding(bottom = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(10.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = v.name, + onValueChange = { name -> + draft = draft.toMutableList().also { + it[i] = v.copy(name = name) + } + }, + modifier = Modifier.weight(1f), + label = { Text("变量名", fontSize = 11.sp) }, + singleLine = true, + textStyle = TextStyle(fontSize = 13.sp), + ) + Spacer(Modifier.width(6.dp)) + Text( + "删除", + color = MaterialTheme.colorScheme.error, + fontSize = 12.sp, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { + draft = draft.filterIndexed { j, _ -> j != i } + } + .padding(horizontal = 8.dp, vertical = 6.dp), + ) + } + Spacer(Modifier.height(6.dp)) + // ★ 类型必选:三个选项直接摆出来,默认 str + FlowChips( + options = listOf( + "str" to "文本 str", + "bool" to "真假 bool", + "num" to "数字 num", + "list" to "列表 list", + ), + active = v.type.ifBlank { "str" }, + onPick = { t -> + draft = draft.toMutableList().also { it[i] = v.copy(type = t) } + }, + ) + Spacer(Modifier.height(6.dp)) + OutlinedTextField( + value = v.initial, + onValueChange = { ini -> + draft = draft.toMutableList().also { + it[i] = v.copy(initial = ini) + } + }, + modifier = Modifier.fillMaxWidth(), + label = { Text("初始值(会议一开始就写进去)", fontSize = 11.sp) }, + singleLine = true, + textStyle = TextStyle(fontSize = 13.sp), + ) + Spacer(Modifier.height(6.dp)) + // ★ 描述位:**这段文字会一起给智能体看**。 + // 光有变量名,模型只能猜"这个 isRun 是次数还是个开关"; + // 写一句它就知道这是什么、该怎么用。 + OutlinedTextField( + value = v.note, + onValueChange = { note -> + draft = draft.toMutableList().also { + it[i] = v.copy(note = note) + } + }, + modifier = Modifier.fillMaxWidth(), + label = { Text("描述(会一起给智能体看)", fontSize = 11.sp) }, + placeholder = { + Text("例如:已经循环了几轮", fontSize = 12.sp) + }, + textStyle = TextStyle(fontSize = 13.sp), + maxLines = 3, + ) + if (v.type == "list") { + Spacer(Modifier.height(4.dp)) + Text( + "列表只能追加和清空(运算节点里),不做删除/排序。" + + "给智能体看的时候是 JSON。初始值写 [] 或 [\"第一项\"]。", + fontSize = 10.sp, + color = doubaoTextSecondary(), + lineHeight = 14.sp, + ) + } + if (v.type == "bool") { + Spacer(Modifier.height(4.dp)) + Text( + "bool:0 / 空 / false / no 是假,其他非空都是真", + fontSize = 10.sp, + color = doubaoTextSecondary(), + ) + } + } + } + } + + Text( + "+ 加一个变量", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + draft = draft + com.doubao.lynxclone.data.MeetingVar( + name = "变量${draft.size + 1}", + type = "str", + initial = "", + ) + } + .padding(horizontal = 8.dp, vertical = 6.dp), + ) + } + }, + confirmButton = { + TextButton(onClick = { + // 空名字和重名的丢掉(引擎那边也会再筛一遍) + onSave( + draft.filter { it.name.isNotBlank() } + .distinctBy { it.name.trim() } + .map { it.copy(name = it.name.trim(), type = it.type.ifBlank { "str" }) }, + ) + }) { Text("保存") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }, + ) + } + + /** + * 从**变量登记表**里选一个变量。 + * + * ★ 为什么不让用户手打名字:变量是会议级的,类型定义在变量上。 + * 手打很容易打成 "isrun" 和 "isRun" 两个变量,或者写/读两边各声明一个类型, + * 然后线接不上还找不到原因。 + * + * ★ 选完把类型和初始值也显示出来,让人马上知道这根线是什么类型。 + */ + @Composable + private fun VarPicker( + vars: List, + selected: String, + onPick: (String) -> Unit, + ) { + FormLabel("用哪个变量") + Spacer(Modifier.height(4.dp)) + if (vars.isEmpty()) { + Text( + "还没有变量。先点标题栏的「变量」加一个 —— 变量要先声明名字和类型。", + fontSize = 11.sp, + color = MaterialTheme.colorScheme.error, + lineHeight = 16.sp, + ) + return + } + FlowChips( + options = vars.map { it.name to "${it.name}(${typeLabel(it.type)})" }, + active = selected, + onPick = onPick, + ) + val hit = vars.firstOrNull { it.name == selected } + if (hit == null) { + Spacer(Modifier.height(4.dp)) + Text("还没选变量。", fontSize = 11.sp, color = MaterialTheme.colorScheme.error) + } else if (hit.initial.isNotEmpty()) { + Spacer(Modifier.height(4.dp)) + Text( + "初始值「${hit.initial}」—— 会议一开始就写进去,读变量第一轮就能读到。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 15.sp, + ) + } + } + + /** 变量类型的中文名 */ + private fun typeLabel(type: String): String = when (type) { + "list" -> "列表" + "bool" -> "真假" + "num" -> "数字" + else -> "文本" + } + + /** + * 编辑器菜单:拖动灵敏度 + 导出会议。 + * + * ★ 拖动灵敏度可调:节点移动量是「屏幕位移 ÷ 缩放 × 系数」。 + * 除缩放是必须的(不然放大后节点跑得比手指快);剩下的手感 —— + * 跟手一点还是稳一点 —— 跟屏幕尺寸、手指习惯都有关, + * 与其我替你定死一个,不如给个滑块。 + * + * ★ 导出成 JSON:会议就是一张图(节点 + 连线 + 变量), + * 导出成文本就能备份、发给别人、粘到别处去。 + */ + @Composable + private fun EditorMenuDialog( + sensitivity: Float, + onSensitivity: (Float) -> Unit, + meeting: Meeting, + onExport: (String) -> Unit, + onImport: () -> Unit, + /** 导出到文件(系统保存对话框) */ + onExportFile: () -> Unit, + /** 从文件导入(系统打开对话框) */ + onImportFile: () -> Unit, + onDismiss: () -> Unit, + ) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("编辑器", fontSize = 16.sp) }, + text = { + Column(Modifier.fillMaxWidth()) { + FormLabel("拖动灵敏度") + Spacer(Modifier.height(2.dp)) + Text( + "屏幕上划一格,节点实际移动多少。" + when { + sensitivity < 0.95f -> "现在偏慢,图更稳。" + sensitivity > 1.05f -> "现在偏快,节点跟手更紧。" + else -> "现在是跟手(1.0×)。" + }, + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, - ) - Spacer(Modifier.height(6.dp)) - Row(verticalAlignment = Alignment.CenterVertically) { - Text("慢", fontSize = 11.sp, color = doubaoTextSecondary()) - Slider( - value = sensitivity, - onValueChange = onSensitivity, - valueRange = 0.3f..2f, - modifier = Modifier.weight(1f).padding(horizontal = 8.dp), - ) - Text("快", fontSize = 11.sp, color = doubaoTextSecondary()) - } - Text( - "%.2f×".format(sensitivity), - fontSize = 11.sp, - color = Doubao.Blue, - modifier = Modifier.align(Alignment.CenterHorizontally), + ) - Spacer(Modifier.height(14.dp)) - FormLabel("导出") - Spacer(Modifier.height(4.dp)) - Text( - "把这场会议导成 JSON(节点 / 连线 / 变量全在里面),可以备份、也可以发给别人。", - fontSize = 11.sp, - color = doubaoTextSecondary(), - lineHeight = 16.sp, - ) Spacer(Modifier.height(6.dp)) + + Row(verticalAlignment = Alignment.CenterVertically) { + + Text("慢", fontSize = 11.sp, color = doubaoTextSecondary()) + + Slider( + + value = sensitivity, + + onValueChange = onSensitivity, + + valueRange = 0.3f..2f, + + modifier = Modifier.weight(1f).padding(horizontal = 8.dp), + + ) + + Text("快", fontSize = 11.sp, color = doubaoTextSecondary()) + + } + Text( + + "%.2f×".format(sensitivity), + + fontSize = 11.sp, + + color = Doubao.Blue, + + modifier = Modifier.align(Alignment.CenterHorizontally), + + ) + + + + Spacer(Modifier.height(14.dp)) + + FormLabel("导出") + + Spacer(Modifier.height(4.dp)) + + Text( + + "把这场会议导成 JSON(节点 / 连线 / 变量全在里面),可以备份、也可以发给别人。", + + fontSize = 11.sp, + + color = doubaoTextSecondary(), + + lineHeight = 16.sp, + + ) + + Spacer(Modifier.height(6.dp)) + + Text( + "导出到文件…(推荐:剪贴板对长文本不可靠,几 KB 会截断)", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onExportFile() } + .padding(horizontal = 8.dp, vertical = 6.dp), + ) + Text( + "复制会议 JSON(${meeting.nodes.size} 节点 · ${meeting.edges.size} 连线 · ${meeting.vars.size} 变量)", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + onExport( + JSONObject() + .put("name", meeting.name) + .put("nodes", JSONArray().apply { + meeting.nodes.forEach { put(it.toJson()) } + }) + .put("edges", JSONArray().apply { + meeting.edges.forEach { put(it.toJson()) } + }) + .put("vars", JSONArray().apply { + meeting.vars.forEach { put(it.toJson()) } + }) + .toString(2), + ) + } + .padding(horizontal = 8.dp, vertical = 6.dp), + ) + + Spacer(Modifier.height(14.dp)) + FormLabel("导入") + Spacer(Modifier.height(4.dp)) + Text( + "把别处的会议 JSON 粘进来,替换当前这张图(节点 / 连线 / 变量都换掉)。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + Spacer(Modifier.height(6.dp)) + // ★ 文件导入放在粘贴**前面**,并且标"推荐": + // 剪贴板对长文本不可靠(各大 ROM 有自己的截断策略), + // 会议 JSON 动不动几 KB,走文件才稳。 + Text( + "从文件导入…(推荐)", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onImportFile() } + .padding(horizontal = 8.dp, vertical = 6.dp), + ) + Text( + "粘贴会议 JSON…", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onImport() } + .padding(horizontal = 8.dp, vertical = 6.dp), + ) + } + }, + confirmButton = { TextButton(onClick = onDismiss) { Text("好") } }, + ) + } + + /** + * 一个最终输出的展示。 + * + * ★ **不同类型的展示方式不一样**(用户明确要求): + * 文本 原样段落 + * 数字 大字,一眼看到 + * 真假 一枚醒目的绿/红标记 + * 列表 按 JSON 展开成一项一项(空列表也明确写"(空)") + * 全都当成一段文字显示的话,数字混在长文里看不见、列表挤成一坨没法读。 + */ + @Composable + private fun ResultValueView(r: MeetingResult) { + when (r.type) { + "num" -> Text( + r.value.ifBlank { "—" }, + fontSize = 26.sp, + fontWeight = FontWeight.Medium, + color = Doubao.Blue, + ) + "bool" -> { + val yes = r.value.trim().lowercase() in listOf("true", "1", "yes", "真") + Surface( + shape = RoundedCornerShape(8.dp), + color = (if (yes) Color(0xFF34A853) else Color(0xFFEA4335)).copy(alpha = 0.14f), + ) { + Text( + if (yes) "真" else "假", + fontSize = 20.sp, + fontWeight = FontWeight.Medium, + color = if (yes) Color(0xFF34A853) else Color(0xFFEA4335), + modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp), + ) + } + } + "list" -> { + val items = runCatching { + val arr = JSONArray(r.value.ifBlank { "[]" }) + (0 until arr.length()).map { arr.optString(it) } + }.getOrElse { emptyList() } + if (items.isEmpty()) { + Text("(空列表)", fontSize = 13.sp, color = doubaoTextSecondary()) + } else { + // ★ **横向卡片**:一项一张卡,左右滑。 + // + // 原来竖着一行一项("1. xxx / 2. xxx"),项目一多就得往下滚, + // 而且和下面"运行链"的竖排条目长得一模一样,一眼分不清哪是哪。 + // 横向卡片把"这是列表的一项"和普通文字行在**形状上**区分开了: + // 一屏能看到三四张,滑动方向也和页面滚动垂直,不会串。 + Row( + Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + ) { + items.forEachIndexed { i, item -> + Card( + Modifier + .width(260.dp) + .padding(end = 8.dp), + colors = CardDefaults.cardColors( + containerColor = doubaoBg(), + ), + border = BorderStroke(1.dp, Doubao.Blue.copy(alpha = 0.25f)), + ) { + Column(Modifier.padding(10.dp)) { + // 序号做成小徽章,扫一眼就知道是第几项 + Surface( + shape = RoundedCornerShape(6.dp), + color = Doubao.Blue.copy(alpha = 0.12f), + ) { + Text( + "第 ${i + 1} 项", + fontSize = 10.sp, + color = Doubao.Blue, + modifier = Modifier.padding( + horizontal = 6.dp, + vertical = 1.dp, + ), + ) + } + Spacer(Modifier.height(6.dp)) + Text( + item.ifBlank { "(空)" }, + fontSize = 13.sp, + color = doubaoText(), + lineHeight = 19.sp, + ) + } + } + } + } + Spacer(Modifier.height(6.dp)) + Text( + "共 ${items.size} 项" + + if (items.size > 3) " · 左右滑动看更多" else "", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } + } + else -> { + // ★ 长文本默认**收起来**。 + // 辩论这种场景一段输出能有好几千字,全铺开的话下面的内容 + // 得翻半天才看得到,结果界面就"一塌糊涂"了(用户的原话)。 + // 默认只显示开头几行,想看全文点"展开"。 + var open by remember(r.value) { mutableStateOf(false) } + val long = r.value.length > 240 + // ★ 结果也要**按 Markdown 渲染**:智能体的输出本来就是 Markdown + // (标题、加粗、列表、代码块),当纯文本显示的话 `**加粗**` 会原样露出来 —— + // 辩论场景里满屏星号,正是用户说的"结果也要 md 解析"。 + // + // 长文本默认收起来(限高 150dp),点"展开全文"放开。 + Box( + Modifier + .fillMaxWidth() + .heightIn(max = if (open || !long) 6000.dp else 150.dp) + .clip(RoundedCornerShape(6.dp)), + ) { + MarkdownText( + markdown = r.value.ifBlank { "(没有输出)" }, + color = doubaoText(), + fontSize = 13, + lineHeight = 19, + ) + } + if (long) { + Spacer(Modifier.height(4.dp)) + Text( + if (open) "收起" else "展开全文(共 ${r.value.length} 字)", + fontSize = 11.sp, + color = Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { open = !open } + .padding(horizontal = 6.dp, vertical = 3.dp), + ) + } + } + } + } + + /** + * 最终输出面板:多个输出用**标签页**切换。 + * + * ★ 用户要求:"结果界面做个最终输出的标签页,最终结果可以是多个(用标签页形式 + * 展现),可以是任意类型,不同类型的最终结果展现方式不同。" + */ + @Composable + private fun ResultsPanel(results: List) { + if (results.isEmpty()) return + var tab by remember(results) { mutableStateOf(0) } + val idx = tab.coerceIn(0, results.size - 1) + + // ★ 标签页**重名要区分开**。 + // 图上多个 end 节点的标题都叫"最终输出"是常态(默认名), + // 原样展示就是一排一模一样的标签,点哪个都不知道。 + // 重名的补上序号,至少能分辨"这是第几个最终输出"。 + val dupTitles = results.groupingBy { it.title.ifBlank { "最终输出" } }.eachCount() + fun tabLabel(i: Int): String { + val base = results[i].title.ifBlank { "最终输出" } + return if ((dupTitles[base] ?: 0) > 1) "$base ${i + 1}" else base + } + + Column(Modifier.fillMaxWidth()) { + if (results.size > 1) { + // 多个输出才需要标签页;只有一个就直接展示,省一行 + Row( + Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + ) { + results.forEachIndexed { i, _ -> + val on = i == idx + Text( + tabLabel(i), + fontSize = 13.sp, + color = if (on) Color.White else doubaoTextSecondary(), + fontWeight = if (on) FontWeight.Medium else FontWeight.Normal, + modifier = Modifier + .padding(end = 8.dp) + .clip(RoundedCornerShape(8.dp)) + .background(if (on) Doubao.Blue else Doubao.Blue.copy(alpha = 0.08f)) + .clickable { tab = i } + .padding(horizontal = 12.dp, vertical = 6.dp), + ) + } + } + Spacer(Modifier.height(10.dp)) + } + val cur = results[idx] + Surface( + shape = RoundedCornerShape(10.dp), + color = Doubao.Blue.copy(alpha = 0.05f), + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(12.dp)) { + Text( + tabLabel(idx) + "(${typeLabel(cur.type)})", + fontSize = 11.sp, + color = Doubao.Blue, + ) + Spacer(Modifier.height(6.dp)) + ResultValueView(cur) + } + } + } + } + + /** + * 导入会议:粘贴一段 JSON,替换当前这张图。 + * + * ★ 导出/导入是一对:导出的 JSON 粘回来必须能用。所以这里**不挑格式** —— + * 直接走 toMeeting() 那套解析(和从内核读会议走同一条路),导出的字段它全都认。 + * + * ★ 导入前先说清楚会替换掉什么:图是不可逆的(除非用户自己留着旧的), + * 所以显示"当前几节点几连线""即将导入几节点几连线",让人点之前就知道在做什么。 + */ + @Composable + private fun ImportDialog( + current: Meeting, + clipboardText: String, + onImport: (Meeting) -> Unit, + onDismiss: () -> Unit, + ) { + var text by remember { mutableStateOf("") } + var error by remember { mutableStateOf("") } + // 解析成功就先预览要导入什么,不立刻套用 + val parsed = remember(text) { + if (text.isBlank()) { + null + } else { + runCatching { JSONObject(text.trim()).toMeeting() }.getOrElse { null } + } + } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("导入会议", fontSize = 16.sp) }, + text = { + Column(Modifier.fillMaxWidth()) { + Text( + "把导出的会议 JSON 粘在下面。导入会替换当前这张图" + + "(现在是 ${current.nodes.size} 节点 · ${current.edges.size} 连线)。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = text, + onValueChange = { text = it; error = "" }, + modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 300.dp), + placeholder = { Text("{\"nodes\": [...], \"edges\": [...]}", fontSize = 11.sp) }, + textStyle = TextStyle(fontSize = 11.sp), + label = { Text("会议 JSON", fontSize = 11.sp) }, + ) + Spacer(Modifier.height(6.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "从剪贴板粘贴", + color = Doubao.Blue, + fontSize = 12.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { text = clipboardText; error = "" } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + Spacer(Modifier.width(4.dp)) + Text( + "清空", + color = doubaoTextSecondary(), + fontSize = 12.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { text = ""; error = "" } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + Spacer(Modifier.height(4.dp)) + when { + error.isNotBlank() -> Text( + error, + fontSize = 11.sp, + color = MaterialTheme.colorScheme.error, + lineHeight = 15.sp, + ) + text.isBlank() -> Text( + "还没粘内容。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + parsed == null -> Text( + "这段内容不是合法的会议 JSON —— 检查一下是不是复制全了。", + fontSize = 11.sp, + color = MaterialTheme.colorScheme.error, + lineHeight = 15.sp, + ) + parsed.nodes.isEmpty() -> Text( + "解析出来了,但里面没有节点。", + fontSize = 11.sp, + color = MaterialTheme.colorScheme.error, + ) + else -> Text( + "可以导入:${parsed.nodes.size} 节点 · ${parsed.edges.size} 连线 · " + + "${parsed.vars.size} 变量。点「导入」后当前这张图会被替换。", + fontSize = 11.sp, + color = Color(0xFF34A853), + lineHeight = 15.sp, + ) + } + } + }, + confirmButton = { + TextButton( + enabled = parsed != null && parsed.nodes.isNotEmpty(), + onClick = { parsed?.let { onImport(it) } }, + ) { Text("导入") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }, + ) + } + + /** 连线种类的中文名(选中提示里用) */ + /** + * 引脚和连线的颜色**按类型定**。 + * + * ★ 为什么按类型上色(而不是"数据线都一个颜色"): + * 连错类型是这套图里最常见的错,而颜色是**扫一眼**就能判断的东西 —— + * 用户不用去读引脚旁边那两三个小字。 + * 他自己要求的配色:白 exec、绿 str、蓝 num、红 bool。 + * + * 列表给橙色:它是后加的类型,得和前面三个**一眼区分开**, + * 用紫色或青色都在深色背景上不够跳。 + */ + /** + * 「什么都能收」的引脚用它自己的颜色:**紫**。 + * + * ★ 为什么不能沿用 kind 的颜色:`end`(最终输出)的入口声明是 `str` 只是为了 + * 给个默认色,它实际 `accepts` 四种全要。画成绿色的话用户会以为 + * "只能接文本",数字和列表就不敢往上接 —— 颜色在这里是**语义**, + * 说错了比不说还糟。 + * + * 紫 = "这里什么都行"。写变量 / Python / 转换的入口也是这个色。 + */ + private val ANY_COLOR = Color(0xFF9C27B0) + + /** 按**引脚**算颜色(而不是只看 kind):收全部类型的引脚是紫的 */ + private fun pinColorOf(pin: PinSpec): Color = + if (pin.kind != "exec" && pin.accepts.containsAll(ANY_DATA)) ANY_COLOR + else pinColor(pin.kind) + + private fun pinColor(kind: String): Color = when (kind) { + // 执行引脚:白。它不传值,所以是"无色"的 —— 和彩色数据引脚形成对比 + "exec" -> Color(0xFFECEFF1) + "str" -> Color(0xFF34A853) + "num" -> Color(0xFF1A73E8) + "bool" -> Color(0xFFE53935) + "list" -> Color(0xFFF9A825) + "data" -> Color(0xFF34A853) // 老会议里的 'data' 当 str + else -> Color(0xFF9AA0A6) + } + + /** 引脚的边框色(描在白引脚外面,浅色背景下才看得见) */ + private fun pinBorder(kind: String): Color = + if (kind == "exec") Color(0xFF5F6368) else pinColor(kind).copy(alpha = 0.85f) + + private fun kindLabel(kind: String): String = when (kind) { + "exec" -> "执行线" + "bool" -> "bool 数据线" + "num" -> "num 数据线" + "data" -> "str 数据线" // 老会议里的 'data' + else -> "str 数据线" + } + + /** + * 类型选择器:str / bool / num。 + * + * ★ 为什么需要它:数据引脚是强类型的,**类型决定了这根线能接到哪去**。 + * 比如 while 的条件要 bool,那变量就得声明成 bool。 + * + * ★ bool 的转换规则(引擎和这里一致): + * 0 / 空 / 'false' / 'no' / 'off' → 假 + * 其他任何非空的东西 → 真 + * 也就是 `var == 0` 是假、`var != 0` 是真。 + */ + @Composable + private fun ValueTypePicker(draft: MeetingNode, onPick: (String) -> Unit) { + FormLabel("类型") + Spacer(Modifier.height(4.dp)) + FlowChips( + options = listOf( + "str" to "文本 str", + "bool" to "真假 bool", + "num" to "数字 num", + "list" to "列表 list", + ), + active = draft.valueType.ifBlank { "str" }, + onPick = onPick, + ) + if (draft.valueType == "bool") { + Spacer(Modifier.height(4.dp)) + Text( + "bool 怎么算:0 / 空 / false / no 是假,其他非空都是真(和 C 一样)。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + } + } + + private val EXEC_COLOR = Color(0xFFE8EAED) + private val EXEC_BORDER = Color(0xFF5F6368) + + /** + * 画一个执行引脚(蓝图里那种白色小三角)。 + * + * ★ 为什么非得是三角而不是圆点:蓝图里"执行"和"数据"是两种完全不同的东西 —— + * 一个**决定执行顺序**、一个只传值。形状不同才能在缩小之后也分得开; + * 只靠颜色的话,色弱用户、或者图缩小了就完全分不清了, + * 而这两种线接错等于整套语义都垮了。 + */ + private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawExecPin( + center: Offset, + radius: Float, + filled: Boolean, + tint: Color = EXEC_BORDER, + ) { + val h = radius * 1.5f + val path = Path().apply { + moveTo(center.x - h * 0.55f, center.y - h) + lineTo(center.x + h * 0.75f, center.y) + lineTo(center.x - h * 0.55f, center.y + h) + close() + } + if (filled) drawPath(path, Color.White) + drawPath(path, tint, style = Stroke(width = 1.6.dp.toPx())) + } + + + /** + * 平移范围的钳制。 + * + * 不让用户把整张图拖到屏幕外找不回来 —— 这比"能无限拖"重要得多: + * 手机上误拖一下整张图没了,用户只会以为程序坏了。 + * + * ★ 画布的实际像素尺寸必须按**真实密度**算。之前写死 2.75 是拍的, + * 密度 2.0 的机器上纵向只能挪一点点,用户体感就是"视图挪不动"。 + */ + /** + * 画布能铺多远(dp)。 + * + * ★ 以前画布是写死的 900×800,**拖到头就拖不动了**,想在图右边再接一段 + * 只能先把节点挪开腾地方。现在按"所有节点的包围盒 + 一圈余量"算: + * 节点拖到哪,画布就跟着长到哪,永远还有地方继续接。 + */ + private const val CANVAS_MARGIN = 900f + + /** 按节点包围盒算出画布尺寸 */ + private fun canvasSize(nodes: List): Pair { + var maxX = 0f + var maxY = 0f + for (n in nodes) { + if (n.x + NODE_W > maxX) maxX = n.x + NODE_W + if (n.y + nodeHeight(n) > maxY) maxY = n.y + nodeHeight(n) + } + return Pair(maxX + CANVAS_MARGIN, maxY + CANVAS_MARGIN) + } + + private fun clampPan( + x: Float, y: Float, + viewW: Float, viewH: Float, + contentW: Float, contentH: Float, + ): Pair = Pair( + x.coerceIn(minOf(0f, viewW - contentW), 0f), + y.coerceIn(minOf(0f, viewH - contentH), 0f), + ) -/** - * 把一条会议事件应用到界面状态上。 - * - * 抽出来是因为运行按钮有两处(顶栏 ▶ 和底部「运行」),原来各抄了一份 when —— - * 加停止、加结果界面时就得改两遍,漏一处就是"某个按钮跑起来不显示输出"。 - */ -/** - * 把一条会议事件应用到界面状态上。 - * - * ★ **两个运行入口共用这一份**(顶栏 ▶ 和底部「运行」)。 - * - * 之前是各写一份 when,结果加"多个最终输出"时只改了其中一个 —— - * 用底部按钮跑完,结果界面的标签页是空的(用户报的"本次的为啥在历史里": - * 历史里有标签页,本次只有一坨文本)。 - * 这类"同一段逻辑抄两份"的坑在这个文件里踩过不止一次, - * 所以现在只有这一处实现。 - */ -private fun applyMeetingEvent( - ev: com.doubao.lynxclone.data.MeetingEvent, - liveStatus: MutableMap, - nodeOutputs: MutableMap, - liveResults: MutableList, - liveTrace: MutableList? = null, - nodeWarn: MutableMap? = null, - nodeVerdict: MutableMap? = null, - meetingEdges: List = emptyList(), - onRunning: (String) -> Unit = {}, - onLitEdge: (Int) -> Unit = {}, - onDone: (String) -> Unit, -) { - when (ev.type) { - "node_start" -> { - liveStatus[ev.nodeId] = "running" - // 运行链:按**执行顺序**记下每一步(结果界面要的是"这条链怎么走下来的") - liveTrace?.add( - TraceStep( - nodeId = ev.nodeId, - title = ev.title.ifBlank { ev.nodeType }, - nodeType = ev.nodeType, - run = ev.run, - ), - ) - onRunning(ev.title.ifBlank { ev.nodeType }) - // 执行流到这一步了:把这根 exec 线点亮,让它"流"起来 - val idx = meetingEdges.indexOfFirst { it.to == ev.nodeId } - if (idx >= 0) onLitEdge(idx) - } - "node_delta" -> nodeOutputs[ev.nodeId] = (nodeOutputs[ev.nodeId] ?: "") + ev.text - "node_done" -> { - liveStatus[ev.nodeId] = "done" - if (ev.output.isNotBlank()) nodeOutputs[ev.nodeId] = ev.output - if (ev.branch.isNotBlank()) { - nodeVerdict?.put(ev.nodeId, ev.branch) - // 判断 / while 的结论在 node_done 才拿到,而链是按 node_start 记的, - // 所以把结论**补进链里那一步** - val tr = liveTrace - val at = tr?.indexOfLast { it.nodeId == ev.nodeId } ?: -1 - if (tr != null && at >= 0) { - tr[at] = tr[at].copy(verdict = ev.verdict, branch = ev.branch, note = ev.note) - } - } - } - "node_warn" -> { - if (nodeWarn != null) nodeWarn[ev.nodeId] = ev.warn - else nodeOutputs[ev.nodeId] = "⚠ ${ev.warn}" - } - "node_error" -> { - liveStatus[ev.nodeId] = "error" - nodeOutputs[ev.nodeId] = "出错:${ev.error}" - } - "meeting_done" -> { - // ★ 最终输出要收下来,结果界面的标签页靠它 - liveResults.clear() - liveResults.addAll(ev.results) - onRunning("") - onLitEdge(-1) - onDone(ev.error) - } - } -} + /** - * 运行结果单独一屏。 + + * 把一条会议事件应用到界面状态上。 + * - * 为什么要有:节点卡片就那么点大,长回答在卡片上只能看到两行 —— - * 想完整读一遍结果就得靠这个。**按节点在文中的顺序(节点的 x 坐标)排**, - * 而不是按事件到达顺序:用户脑子里的顺序是图上从左到右,不是事件流。 + + * 抽出来是因为运行按钮有两处(顶栏 ▶ 和底部「运行」),原来各抄了一份 when —— + + * 加停止、加结果界面时就得改两遍,漏一处就是"某个按钮跑起来不显示输出"。 + */ -@Composable -private fun MeetingResultScreen( - vm: AppViewModel, - meeting: Meeting, - liveOutputs: Map, - /** 本次运行的**运行链**:按执行顺序记的 (节点id, 标题, 第几轮) */ - liveTrace: List, - /** 本次的最终输出(多个 / 任意类型) */ - liveResults: List, - onBack: () -> Unit, + +/** + + * 把一条会议事件应用到界面状态上。 + + * + + * ★ **两个运行入口共用这一份**(顶栏 ▶ 和底部「运行」)。 + + * + + * 之前是各写一份 when,结果加"多个最终输出"时只改了其中一个 —— + + * 用底部按钮跑完,结果界面的标签页是空的(用户报的"本次的为啥在历史里": + + * 历史里有标签页,本次只有一坨文本)。 + + * 这类"同一段逻辑抄两份"的坑在这个文件里踩过不止一次, + + * 所以现在只有这一处实现。 + + */ + +private fun applyMeetingEvent( + + ev: com.doubao.lynxclone.data.MeetingEvent, + + liveStatus: MutableMap, + + nodeOutputs: MutableMap, + + liveResults: MutableList, + + liveTrace: MutableList? = null, + + nodeWarn: MutableMap? = null, + + nodeVerdict: MutableMap? = null, + + meetingEdges: List = emptyList(), + + onRunning: (String) -> Unit = {}, + + onLitEdge: (Int) -> Unit = {}, + + onDone: (String) -> Unit, + ) { + + when (ev.type) { + + "node_start" -> { + + liveStatus[ev.nodeId] = "running" + + // 运行链:按**执行顺序**记下每一步(结果界面要的是"这条链怎么走下来的") + + liveTrace?.add( + + TraceStep( + + nodeId = ev.nodeId, + + title = ev.title.ifBlank { ev.nodeType }, + + nodeType = ev.nodeType, + + run = ev.run, + + ), + + ) + + onRunning(ev.title.ifBlank { ev.nodeType }) + + // 执行流到这一步了:把这根 exec 线点亮,让它"流"起来 + + val idx = meetingEdges.indexOfFirst { it.to == ev.nodeId } + + if (idx >= 0) onLitEdge(idx) + + } + + "node_delta" -> nodeOutputs[ev.nodeId] = (nodeOutputs[ev.nodeId] ?: "") + ev.text + + "node_done" -> { + + liveStatus[ev.nodeId] = "done" + + if (ev.output.isNotBlank()) nodeOutputs[ev.nodeId] = ev.output + + if (ev.branch.isNotBlank()) { + + nodeVerdict?.put(ev.nodeId, ev.branch) + + // 判断 / while 的结论在 node_done 才拿到,而链是按 node_start 记的, + + // 所以把结论**补进链里那一步** + + val tr = liveTrace + + val at = tr?.indexOfLast { it.nodeId == ev.nodeId } ?: -1 + + if (tr != null && at >= 0) { + + tr[at] = tr[at].copy(verdict = ev.verdict, branch = ev.branch, note = ev.note) + + } + + } + + } + + "node_warn" -> { + + if (nodeWarn != null) nodeWarn[ev.nodeId] = ev.warn + + else nodeOutputs[ev.nodeId] = "⚠ ${ev.warn}" + + } + + "node_error" -> { + + liveStatus[ev.nodeId] = "error" + + nodeOutputs[ev.nodeId] = "出错:${ev.error}" + + } + + "meeting_done" -> { + + // ★ 最终输出要收下来,结果界面的标签页靠它 + + liveResults.clear() + + liveResults.addAll(ev.results) + + onRunning("") + + onLitEdge(-1) + + onDone(ev.error) + + } + + } + +} + + + +/** + + * 运行结果单独一屏。 + + * + + * 为什么要有:节点卡片就那么点大,长回答在卡片上只能看到两行 —— + + * 想完整读一遍结果就得靠这个。**按节点在文中的顺序(节点的 x 坐标)排**, + + * 而不是按事件到达顺序:用户脑子里的顺序是图上从左到右,不是事件流。 + + */ + +@Composable + +private fun MeetingResultScreen( + + vm: AppViewModel, + + meeting: Meeting, + + liveOutputs: Map, + + /** 本次运行的**运行链**:按执行顺序记的 (节点id, 标题, 第几轮) */ + + liveTrace: List, + + /** 本次的最终输出(多个 / 任意类型) */ + + liveResults: List, + + onBack: () -> Unit, + +) { + var runs by remember { mutableStateOf>(emptyList()) } + var loading by remember { mutableStateOf(true) } + // 展开的是第几条历史(-1 = 只看当前这次) + var expanded by remember { mutableStateOf(-1) } + val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current + val context = androidx.compose.ui.platform.LocalContext.current + + LaunchedEffect(meeting.id) { + try { + runs = vm.client.meetingRuns(meeting.id) + // ★ 没有"本次"可看时(比如重新进这一屏),把**最新那次**历史默认展开。 + // 不展开的话用户只看到一堆时间戳,还得自己点一下才知道这次跑了什么 —— + // 用户的原话是"这次的呢?"。 + + if (liveTrace.isEmpty() && runs.isNotEmpty()) expanded = 0 + } catch (_: Exception) { + // 读不到历史不算错:至少还能看当前这次 + } + loading = false + } + + // ★ 当前这次 = **运行链**(按执行顺序),不是"按图里的位置排序的节点"。 + // 用户要的是"这条链是怎么一步步走下来的":循环转几轮就有几条, + // 先后顺序就是执行顺序。按坐标排的话,循环里的节点会被排到一起, + // 完全看不出第几轮先跑了谁。 + val current = liveTrace + val currentFinal = meeting.nodes.firstOrNull { it.type == "end" } + ?.let { liveOutputs[it.id] }.orEmpty() + + /** + * 这一步的**具体参数**:判断用的什么条件、写哪个变量、值是什么。 + * + * ★ 用户明确要求"节点标题要把运行状态、具体参数写出来"。 + * 只写"判断"两个字的话,图上有五个判断节点就完全分不清是哪个、 + * 更不知道它当时在判什么 —— 回看运行记录等于白看。 + * + * ★ 类型优先看记录里的 nodeType;老记录里没存就从图里按 id 找。 + */ + fun stepParams(nodeId: String, fallbackType: String): String { + val node = meeting.nodes.firstOrNull { it.id == nodeId } + val type = fallbackType.ifBlank { node?.type.orEmpty() } + return when (type) { + "judge" -> { + val cond = when (node?.judgeKind) { + "contains" -> "包含「${node.judgeValue}」" + "not_contains" -> "不含「${node.judgeValue}」" + "longer_than" -> "字数 > ${node.judgeValue}" + "shorter_than" -> "字数 < ${node.judgeValue}" + "empty" -> "为空" + "not_empty" -> "不为空" + "ai" -> "让模型判断" + else -> node?.judgeKind.orEmpty() + } + cond + } + "var" -> node?.varName?.takeIf { it.isNotBlank() } + ?.let { name -> if (node.varValue.isNotBlank()) "$name = ${node.varValue}" else "$name ← 上游" } + .orEmpty() + "readvar" -> node?.varName.orEmpty() + "value" -> node?.text.orEmpty() + "agent" -> node?.agentId?.takeIf { it.isNotBlank() }?.let { "已指定智能体" }.orEmpty() + else -> "" + } + } + + /** + * 运行状态:判断走了真还是假、while 是继续还是结束。 + * + * ★ 这正是用户抱怨"判断结果呢?被你吃了?"的那件事。 + */ + fun stepStatus(fallbackType: String, verdict: Boolean?, branch: String): String { + return when { + fallbackType == "judge" && verdict == true -> "判断:真" + fallbackType == "judge" && verdict == false -> "判断:假" + fallbackType == "while" && branch == "body" -> "条件为真 → 继续循环" + fallbackType == "while" && branch == "done" -> "条件为假 → 结束循环" + fallbackType == "while" -> "条件判断" + else -> "" + } + } + + fun nodeLabel(step: MeetingStep): String = step.title.ifBlank { + when (step.nodeType) { + "start" -> "开始事件" + "judge" -> "判断" + "end" -> "最终输出" + "var" -> "写变量" + "readvar" -> "读变量" + "value" -> "值" + "while" -> "while 循环" + else -> "智能体" + } + } + + /** + * 判断 / while 的结论,画成一枚小标签。 + * + * ★ 用户明确要求:"结果界面要有节点的状态,比如判断节点你要写明是真是假"。 + * 回看时只看到一段文本的话,根本不知道当时判成了什么 —— + * 尤其是循环跑很多轮、每次判的结果还不一样的时候。 + * + * ★ 参数是 (节点类型, 结论, 分支) 而不是 MeetingStep: + * 历史记录用的是 MeetingStep、本次运行用的是 TraceStep, + * 两边都要显示同一枚标签,所以按字段取而不是按类型取。 + */ + @Composable + fun VerdictBadge(nodeType: String, verdict: Boolean?, branch: String) { + val (text, tint) = when { + nodeType == "judge" && verdict == true -> "判断:真" to Color(0xFF34A853) + nodeType == "judge" && verdict == false -> "判断:假" to Color(0xFFEA4335) + nodeType == "while" && branch == "body" -> "条件为真 · 继续循环" to Color(0xFF34A853) + nodeType == "while" && branch == "done" -> "条件为假 · 结束循环" to Color(0xFFEA4335) + nodeType == "while" -> "条件判断" to doubaoTextSecondary() + else -> return + } + Surface( + shape = RoundedCornerShape(6.dp), + color = tint.copy(alpha = 0.12f), + ) { + Text( + text, + fontSize = 11.sp, + color = tint, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + } + + /** 把一次运行拼成能复制的纯文本 */ + fun runToText(run: MeetingRun): String = buildString { + if (run.output.isNotBlank()) { + append(run.output) + append("\n\n————\n") + } + run.steps.forEach { s -> + append("【${nodeLabel(s)}") + if (s.run > 1 || run.steps.count { it.nodeId == s.nodeId } > 1) { + append(" 第${s.run}轮") + } + append("】\n") + append(if (s.error.isNotBlank()) "出错:${s.error}" else s.output) + append("\n\n") + } + } + + Column(Modifier.fillMaxSize().background(doubaoBg())) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回") } + Column(Modifier.weight(1f)) { + Text("运行结果", fontSize = 17.sp, color = doubaoText(), fontWeight = FontWeight.Medium) + Text( + "${meeting.name} · 共 ${runs.size} 次历史", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } + TextButton(onClick = { + vm.launch { + try { + vm.client.clearMeetingRuns(meeting.id) + runs = emptyList() + } catch (_: Exception) { /* 清不掉就算了 */ } + } + }) { Text("清空历史", fontSize = 13.sp) } + } + + Column( + Modifier.weight(1f).verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp), + ) { + // ---------------- 当前这次 ---------------- + if (current.isNotEmpty() || currentFinal.isNotBlank() || liveResults.isNotEmpty()) { + Text("本次", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue) + Spacer(Modifier.height(6.dp)) + // ★ **最终输出(可能有多个,标签页切换,按类型不同渲染)** + if (liveResults.isNotEmpty()) { + ResultsPanel(liveResults) + Spacer(Modifier.height(10.dp)) + } else if (currentFinal.isNotBlank()) { + // 老记录里没有 results(那时还没这个字段),退回显示单个文本输出 + Surface( + shape = RoundedCornerShape(10.dp), + color = Doubao.Blue.copy(alpha = 0.06f), + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(10.dp)) { + Text("最终输出", fontSize = 11.sp, color = Doubao.Blue) + Spacer(Modifier.height(3.dp)) + Text(currentFinal, fontSize = 13.sp, color = doubaoText(), lineHeight = 19.sp) + } + } + Spacer(Modifier.height(10.dp)) + } + // ★ **运行链**:按执行顺序一步步列出每一步的结果。 + // 序号就是"整条链上的第几步",循环转几轮就有几条 —— + // 这才是用户要的"运行链的每次结果"。 + current.forEachIndexed { i, step -> + Row { + Text( + "${i + 1}", + fontSize = 11.sp, + color = Doubao.Blue, + fontWeight = FontWeight.Medium, + modifier = Modifier.width(20.dp).padding(top = 1.dp), + ) + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + buildString { + append(step.title) + if (liveTrace.count { it.nodeId == step.nodeId } > 1) { + append(" · 第 ${step.run} 轮") + } + // 具体参数也写进标题 + val ps = stepParams(step.nodeId, step.nodeType) + if (ps.isNotBlank()) append(" · $ps") + }, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + ) + // ★ 判断 / while 走了哪条路,就写在标题旁边。 + // 少了它,回看时只有一段文本,根本不知道判成了什么。 + // (轮次已经在上面拼进标题里了,这里不要再写一遍 —— + // 之前就是这样,界面上出现"第 3 轮 第 3 轮"。) + Spacer(Modifier.width(6.dp)) + VerdictBadge(step.nodeType, step.verdict, step.branch) + } + val body = liveOutputs[step.nodeId].orEmpty() + if (body.isNotBlank()) { + Text( + body, + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 17.sp, + ) + } + } + } + Spacer(Modifier.height(10.dp)) + } + if (currentFinal.isNotBlank()) { + Text( + "复制本次结果", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + val text = buildString { + append(currentFinal) + append("\n\n————\n") + current.forEachIndexed { i, step -> + append("${i + 1}. ${step.title}") + if (current.count { it.nodeId == step.nodeId } > 1) { + append("(第 ${step.run} 轮)") + } + val mark = when { + step.nodeType == "judge" && step.verdict == true -> "判断:真" + step.nodeType == "judge" && step.verdict == false -> "判断:假" + step.nodeType == "while" && step.branch == "body" -> "条件为真 · 继续循环" + step.nodeType == "while" && step.branch == "done" -> "条件为假 · 结束循环" + else -> "" + } + if (mark.isNotEmpty()) append(" [$mark]") + append("\n") + append(liveOutputs[step.nodeId].orEmpty()) + append("\n\n") + } + } + clipboard.setText(androidx.compose.ui.text.AnnotatedString(text)) + android.widget.Toast + .makeText(context, "已复制", android.widget.Toast.LENGTH_SHORT).show() + } + .padding(vertical = 6.dp), + ) + } + Spacer(Modifier.height(14.dp)) + } + + // ---------------- 历史 ---------------- + Text("历史", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue) + Spacer(Modifier.height(6.dp)) + if (loading) { + Text("读取中…", fontSize = 12.sp, color = doubaoTextSecondary()) + } else if (runs.isEmpty()) { + Text( + "还没有历史。跑一次会议之后这里会留一条记录(最多 20 条)。", + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 17.sp, + ) + } else { + runs.forEachIndexed { index, run -> + val open = expanded == index + Surface( + shape = RoundedCornerShape(12.dp), + color = doubaoSurface(), + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp) + .clickable { expanded = if (open) -1 else index }, + ) { + Column(Modifier.padding(12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + run.shortTime, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + ) + Spacer(Modifier.width(8.dp)) + Text( + "${run.steps.size} 步" + + if (run.aborted) " · 已停止" else "", + fontSize = 11.sp, + color = if (run.aborted) Color(0xFFF29900) else doubaoTextSecondary(), + ) + Spacer(Modifier.weight(1f)) + Text(if (open) "收起" else "展开", fontSize = 11.sp, color = Doubao.Blue) + } + // 摘要:最终输出前面一小段,不展开也能知道这次跑出啥 + Text( + run.output.ifBlank { "(没有最终输出)" }, + fontSize = 12.sp, + color = doubaoTextSecondary(), + maxLines = if (open) 100 else 2, + overflow = TextOverflow.Ellipsis, + lineHeight = 17.sp, + modifier = Modifier.padding(top = 4.dp), + ) + if (open) { + Spacer(Modifier.height(8.dp)) + // ★ 这一次的最终输出(可能有多个、类型各不相同) + if (run.results.isNotEmpty()) { + ResultsPanel(run.results) + Spacer(Modifier.height(12.dp)) + } + // ★ **运行链**:按执行顺序把每一步的结果列出来。 + // + // 不是"节点状态一览",而是"这条链是怎么一步步走下来的"—— + // 循环转几轮就有几条记录,先后顺序一目了然。 + // 序号也是执行顺序,不是节点在图里的位置。 + val countByNode = run.steps.groupingBy { it.nodeId }.eachCount() + run.steps.forEachIndexed { i, s -> + Row(Modifier.padding(top = 8.dp)) { + // 序号:这一步是整条链上的第几步 + Text( + "${i + 1}", + fontSize = 11.sp, + color = Doubao.Blue, + fontWeight = FontWeight.Medium, + modifier = Modifier + .width(20.dp) + .padding(top = 1.dp), + ) + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + buildString { + append(nodeLabel(s)) + if ((countByNode[s.nodeId] ?: 0) > 1) { + append(" · 第 ${s.run} 轮") + } + }, + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + color = if (s.error.isNotBlank()) { + MaterialTheme.colorScheme.error + } else { + doubaoText() + }, + ) + // 判断 / while 走的是哪条路,写在标题旁边 + Spacer(Modifier.width(6.dp)) + VerdictBadge(s.nodeType, s.verdict, s.branch) + } + val body = if (s.error.isNotBlank()) { + "出错:${s.error}" + } else { + s.output.ifBlank { s.note } + } + if (body.isNotBlank()) { + Text( + body, + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 17.sp, + ) + } + } + } + } + Text( + "复制这次", + color = Doubao.Blue, + fontSize = 12.sp, + modifier = Modifier + .padding(top = 8.dp) + .clip(RoundedCornerShape(8.dp)) + .clickable { + clipboard.setText( + androidx.compose.ui.text.AnnotatedString(runToText(run)), + ) + android.widget.Toast + .makeText(context, "已复制", android.widget.Toast.LENGTH_SHORT) + .show() + } + .padding(vertical = 4.dp), + ) + } + } + } + } + } + Spacer(Modifier.height(24.dp)) + } + } + } + + /* ====================================================================== */ + /* 节点卡片 */ + /* ====================================================================== */ + + private fun nodeColor(type: String): Color = when (type) { + "start" -> Color(0xFF34A853) // 开始事件:绿,和蓝图的事件节点一个颜色 + "judge" -> Color(0xFFF29900) // 判断:橙 + "end" -> Color(0xFF7B61FF) // 最终输出:紫 + "var", "readvar" -> Color(0xFF00A0A0) // 变量:青,和普通逻辑区分开 + "value" -> Color(0xFF9C6ADE) // 值/常量:淡紫 + "cast" -> Color(0xFF7E57C2) // 转换:深一点的紫(和"值"同族) + "op" -> Color(0xFF00897B) // 运算:深青(和变量同族,都是"算东西") + "py" -> Color(0xFF37474F) // Python:深灰蓝("这是代码") + // 自定义节点:洋红("这是你自己加的",一眼能从内置节点里认出来) + "custom" -> Color(0xFFAD1457) + // 分支:橙(和判断的蓝紫区分开 —— 判断是"按规则算",分支是"直接收真假") + "branch" -> Color(0xFFE8710A) + "while" -> Color(0xFFD93025) // 循环:红,醒目 + else -> Doubao.Blue + } + + @Composable + private fun NodeCard( + node: MeetingNode, + status: String, + output: String, + linking: Boolean, + /** 接到这个节点的连线数(多路输入要显示出来) */ + inDegree: Int, + /** 从这个节点出去的连线数(多路输出也要显示) */ + outDegree: Int, + /** 正在连线的引脚种类(exec / data);null = 没在连线。用来灰掉接不上的引脚 */ + linkingKind: String?, + /** 这个节点的告警(比如"输入是空的,漏了数据线") */ + warn: String = "", + /** 自定义节点的定义(引脚从内核来,卡片照着画) */ + customDefs: List = emptyList(), + /** 变量登记表:读变量的出口类型要按它查 */ + varTypes: Map = emptyMap(), + modifier: Modifier, + ) { + val accent = nodeColor(node.type) + val ins = inputPins(node) + val outs = outputPins(node) + val rows = maxOf(ins.size, outs.size, 1) + + Column( + modifier + .width(NODE_W.dp) + .height(nodeHeight(node).dp) + .clip(RoundedCornerShape(8.dp)) + .background(doubaoSurface()) + .border( + width = if (linking) 2.dp else 1.dp, + color = when { + linking -> Doubao.Blue + status == "running" -> accent + status == "error" -> MaterialTheme.colorScheme.error + else -> accent.copy(alpha = 0.55f) + }, + shape = RoundedCornerShape(8.dp), + ) + // 拖动节点 / 平移画布 / 点击(开配置、点引脚连线)**全部**由父级 + // 统一处理(见上面画布那段的长注释)。这里一个手势识别器都不挂 —— + // 多个叠一起必然互相抢,这个坑前面踩过两次了。 + , + ) { + // ★ 彩色标题栏 —— 蓝图节点的招牌长相。 + // 一眼就能按颜色分出"这是个判断节点还是智能体", + // 不用去读小字(图一大,字根本看不清)。 + Row( + Modifier + .fillMaxWidth() + .height(HEADER_H.dp) + .background(accent) + .padding(horizontal = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + node.title.ifBlank { + when (node.type) { + "start" -> "初始输入" + "judge" -> "判断" + "end" -> "最终输出" + "var" -> "写变量" + "readvar" -> "读变量" + "value" -> "值" + "cast" -> "转换" + "op" -> "运算" + "py" -> "Python" + "branch" -> "分支" + "custom" -> "自定义" + "while" -> "while 循环" + else -> "智能体" + } + }, + fontSize = 10.sp, + fontWeight = FontWeight.Medium, + color = Color.White, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + // 状态标记放标题栏里:不占正文空间 + when (status) { + "running" -> Text("…", fontSize = 11.sp, color = Color.White) + "done" -> Text("✓", fontSize = 10.sp, color = Color.White) + "error" -> Text("!", fontSize = 11.sp, color = Color.White) + "stopped" -> Text("■", fontSize = 9.sp, color = Color.White) + } + if (node.maxRuns != 1) { + Spacer(Modifier.width(4.dp)) + Text( + if (node.maxRuns == 0) "∞" else "×${node.maxRuns}", + fontSize = 9.sp, + color = Color.White.copy(alpha = 0.85f), + ) + } + } + + // ★ 引脚行:左输入、右输出,各自带标签。 + // 标签紧贴引脚那一侧 —— 蓝图的习惯,视线从引脚扫进去就能读到。 + Box( + Modifier + .fillMaxWidth() + .height((rows * PIN_ROW_H).dp), + ) { + ins.forEachIndexed { i, pin -> + Text( + pin.label, + fontSize = 9.sp, + color = doubaoTextSecondary(), + modifier = Modifier + .align(Alignment.TopStart) + .offset(x = 7.dp, y = (PIN_ROW_H * i + 4f).dp), + ) + } + outs.forEachIndexed { i, pin -> + Text( + pin.label, + fontSize = 9.sp, + color = when (pin.key) { + "true" -> Color(0xFF34A853) + "false" -> Color(0xFFEA4335) + else -> doubaoTextSecondary() + }, + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = (-7).dp, y = (PIN_ROW_H * i + 4f).dp), + ) + } + } + + // 内容区:节点配置摘要 + 运行时的输出 + Text( + when { + output.isNotBlank() -> output + node.type == "agent" -> buildString { + append(if (node.agentId.isBlank()) "未选智能体" else "已选智能体") + if (node.saveToVar.isNotBlank()) append(" · 存→${node.saveToVar}") + } + node.type == "judge" -> node.judgeKind + node.type == "var" -> node.varName.ifBlank { "没填变量名" } + node.type == "readvar" -> node.varName.ifBlank { "没填变量名" } + node.type == "value" -> node.text.ifBlank { "(空值)" } + node.type == "cast" -> "转成" + typeLabel(node.castTo.ifBlank { "str" }) + node.type == "op" -> opLabel(node.op.ifBlank { "add" }) + node.type == "py" -> node.code.lineSequence() + .firstOrNull { it.isNotBlank() }?.trim()?.take(40) ?: "(还没写代码)" + node.type == "while" -> "条件为真就跑循环体" + node.text.isNotBlank() -> node.text + else -> "点一下配置" + }, + fontSize = 9.sp, + color = doubaoTextSecondary(), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + lineHeight = 12.sp, + modifier = Modifier.padding(horizontal = 6.dp), + ) + Spacer(Modifier.weight(1f)) + // ★ 告警:最典型的那个是"输入是空的,你漏了数据线"。 + // 不说出来的话,用户只会看到"明明有值却判断为真", + // 怎么查都查不出规则哪里错了 —— 规则本身没错,是没喂给它值。 + if (warn.isNotBlank()) { + Text( + "⚠ $warn", + fontSize = 8.sp, + color = Color(0xFFD93025), + maxLines = 4, + overflow = TextOverflow.Ellipsis, + lineHeight = 11.sp, + modifier = Modifier.padding(horizontal = 6.dp), + ) + } + // 进出路数写在最底下:多路是智能体的常态,不显示用户不知道自己接全没有 + Text( + buildString { + if (inDegree > 0) append("← $inDegree") + if (inDegree > 0 && outDegree > 0) append(" ") + if (outDegree > 0) append("$outDegree →") + }, + fontSize = 8.sp, + color = doubaoTextSecondary(), + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + } + + /* ====================================================================== */ + /* 小零件 */ + /* ====================================================================== */ + + /** + * 变量名的多选胶囊。 + * + * 和 FlowChips 的区别只有一个:**可以同时选中多个**。 + * 单独写一个而不是给 FlowChips 加参数 —— 单选和多选的视觉反馈不一样 + * (多选要明确标出"勾上了"),混在一起容易让人以为没生效。 + */ + @OptIn(ExperimentalLayoutApi::class) + @Composable + private fun VarChips( + names: List, + selected: List, + onToggle: (String) -> Unit, + ) { + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + names.forEach { name -> + val on = name in selected + Box( + Modifier + .clip(RoundedCornerShape(14.dp)) + .background(if (on) Doubao.Blue else MaterialTheme.colorScheme.surfaceVariant) + .clickable { onToggle(name) } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) { + Text( + if (on) "✓ $name" else name, + fontSize = 12.sp, + color = if (on) Color.White else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + + /** 主按钮(和智能体页那个「新建智能体」同款) */ + @Composable + private fun PrimaryButton(label: String, danger: Boolean = false, onClick: () -> Unit) { + androidx.compose.material3.Button( + onClick = onClick, + shape = RoundedCornerShape(24.dp), + colors = if (danger) { + androidx.compose.material3.ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error, + ) + } else { + androidx.compose.material3.ButtonDefaults.buttonColors() + }, + contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 22.dp, vertical = 12.dp), + ) { + Text(label, fontSize = 15.sp) + } + } + + /** + * 可换行的选择胶囊。 + * + * 直接复用智能体页那个 WrapChips(它内部用 FlowRow 按实际宽度折行)—— + * 之前在手写等分换行上栽过:标签长短差很多时,每行第三个会被挤成竖排一个字一行。 + * 同一份实现,不会再犯第二次。 + */ + @Composable + private fun FlowChips( + options: List>, + active: String, + onPick: (String) -> Unit, + ) { + WrapChips(options = options, active = active, onPick = onPick) + } -/* ====================================================================== */ -/* 节点配置 */ + + /* ====================================================================== */ +/* 节点配置 */ + +/* ====================================================================== */ + + + @Composable + private fun NodeConfigDialog( + node: MeetingNode, + meta: com.doubao.lynxclone.data.MeetingMeta, + /** 变量登记表里的变量名,供选择用 */ + knownVarNames: List, + /** 变量登记表:名字 / 类型(必选)/ 初始值 */ + meetingVars: List, + onDismiss: () -> Unit, + onSave: (MeetingNode) -> Unit, + onDelete: () -> Unit, + ) { + var draft by remember { mutableStateOf(node) } + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( - when (draft.type) { - "start" -> "初始输入" - "agent" -> "智能体节点" - "judge" -> "判断节点" - else -> "最终输出" - }, - fontSize = 16.sp, - ) - }, - text = { - Column(Modifier.verticalScroll(rememberScrollState())) { - OutlinedTextField( - value = draft.title, - onValueChange = { draft = draft.copy(title = it) }, - modifier = Modifier.fillMaxWidth(), - label = { Text("节点标题", fontSize = 12.sp) }, - singleLine = true, - textStyle = TextStyle(fontSize = 14.sp), - ) when (draft.type) { + + "start" -> "初始输入" + + "agent" -> "智能体节点" + + "judge" -> "判断节点" + + else -> "最终输出" + + }, + + fontSize = 16.sp, + + ) + + }, + + text = { + + Column(Modifier.verticalScroll(rememberScrollState())) { + + OutlinedTextField( + + value = draft.title, + + onValueChange = { draft = draft.copy(title = it) }, + + modifier = Modifier.fillMaxWidth(), + + label = { Text("节点标题", fontSize = 12.sp) }, + + singleLine = true, + + textStyle = TextStyle(fontSize = 14.sp), + + ) + + + + when (draft.type) { + "value" -> { + // ★ 值节点以前**没有配置面板** —— 打开是空的, + // 用户根本没法设它的值("值节点如何设置值"就是这么来的)。 + Spacer(Modifier.height(10.dp)) + Text( + "值节点是**纯节点**:它不执行,只是被别的节点「拉取」时" + + "现给一个值。类型决定它的出口能接到哪去。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + Spacer(Modifier.height(8.dp)) + FormLabel("类型") + Spacer(Modifier.height(4.dp)) + ValueTypePicker(draft) { draft = draft.copy(valueType = it) } + Spacer(Modifier.height(10.dp)) + FormLabel("值") + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = draft.text, + onValueChange = { draft = draft.copy(text = it) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 80.dp), + placeholder = { + Text( + when (draft.valueType) { + "num" -> "例如 42" + "bool" -> "true / false" + "list" -> "[\"第一条\", \"第二条\"]" + else -> "例如 一段文字" + }, + fontSize = 12.sp, + ) + }, + textStyle = TextStyle(fontSize = 13.sp), + label = { Text("值", fontSize = 11.sp) }, + ) + Spacer(Modifier.height(6.dp)) + Text( + when (draft.valueType) { + "num" -> "数字:能接运算节点的加法/比较那些入口" + "bool" -> "真假:能接分支节点、运算的与或非。写 0/1 或 true/false" + "list" -> "列表:写成 JSON 数组。只能追加和清空" + else -> "文本:能接智能体、判断、拼接" + }, + fontSize = 11.sp, + color = Doubao.Blue, + lineHeight = 15.sp, + ) + } + + "start", "end" -> { + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = draft.text, + onValueChange = { draft = draft.copy(text = it) }, + modifier = Modifier.fillMaxWidth().height(110.dp), + label = { Text("写死的文本(留空则用上游 / 运行输入)", fontSize = 12.sp) }, + textStyle = TextStyle(fontSize = 13.sp), + ) + } + "agent" -> { + Spacer(Modifier.height(10.dp)) + FormLabel("智能体") + Spacer(Modifier.height(4.dp)) + FlowChips( + options = meta.agents.map { it.id to it.name }, + active = draft.agentId, + onPick = { draft = draft.copy(agentId = it) }, + ) + + Spacer(Modifier.height(10.dp)) + OutlinedTextField( + value = draft.extraPrompt, + onValueChange = { draft = draft.copy(extraPrompt = it) }, + modifier = Modifier.fillMaxWidth().height(100.dp), + label = { Text("附加系统提示词(本节点专属)", fontSize = 12.sp) }, + placeholder = { Text("例如:你只负责挑毛病,不要给建议", fontSize = 12.sp) }, + textStyle = TextStyle(fontSize = 13.sp), - ) - Text( - // ★ 这里不能写 Markdown 的 ** ——这是个普通 Text,不渲染 Markdown, - // 用户看到的就是字面的两个星号(真犯过)。 - "拼在智能体原有人设的后面,不会顶掉它。", - fontSize = 11.sp, - color = doubaoTextSecondary(), + ) - Spacer(Modifier.height(10.dp)) - OutlinedTextField( - value = draft.outputControl, - onValueChange = { draft = draft.copy(outputControl = it) }, - modifier = Modifier.fillMaxWidth().height(90.dp), - label = { Text("输出控制", fontSize = 12.sp) }, - placeholder = { Text("例如:不超过 100 字;用 JSON 输出;必须给出结论", fontSize = 12.sp) }, - textStyle = TextStyle(fontSize = 13.sp), + Text( + + // ★ 这里不能写 Markdown 的 ** ——这是个普通 Text,不渲染 Markdown, + + // 用户看到的就是字面的两个星号(真犯过)。 + + "拼在智能体原有人设的后面,不会顶掉它。", + + fontSize = 11.sp, + + color = doubaoTextSecondary(), + ) + + + Spacer(Modifier.height(10.dp)) + + OutlinedTextField( + + value = draft.outputControl, + + onValueChange = { draft = draft.copy(outputControl = it) }, + + modifier = Modifier.fillMaxWidth().height(90.dp), + + label = { Text("输出控制", fontSize = 12.sp) }, + + placeholder = { Text("例如:不超过 100 字;用 JSON 输出;必须给出结论", fontSize = 12.sp) }, + + textStyle = TextStyle(fontSize = 13.sp), + + ) + + + /* -------- 变量权限 -------- */ + val knownVars = knownVarNames + Spacer(Modifier.height(12.dp)) + FormLabel("可读变量") + Spacer(Modifier.height(4.dp)) + if (knownVars.isEmpty()) { + Text( + "图里还没有「写变量」节点。加一个之后这里就能勾了。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } else { + VarChips( + names = knownVars, + selected = draft.readVars, + onToggle = { name -> + draft = draft.copy( + readVars = if (name in draft.readVars) { + draft.readVars - name + } else { + draft.readVars + name + }, + ) + }, + ) + } + Spacer(Modifier.height(4.dp)) + Text( + "勾了的变量,当前值会拼进这个智能体的提示词。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + + Spacer(Modifier.height(10.dp)) + FormLabel("可写变量") + Spacer(Modifier.height(4.dp)) + if (knownVars.isEmpty()) { + Text("(同上,先加「写变量」节点)", fontSize = 11.sp, color = doubaoTextSecondary()) + } else { + VarChips( + names = knownVars, + selected = draft.writeVars, + onToggle = { name -> + draft = draft.copy( + writeVars = if (name in draft.writeVars) { + draft.writeVars - name + } else { + draft.writeVars + name + }, + ) + }, + ) + } + Spacer(Modifier.height(4.dp)) + Text( + "勾了之后,智能体会被要求用 [[SET 名字=值]] 写回来;" + + "这一行不会出现在正文里,会被系统取走。没勾的变量它写不动。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + } + + "judge" -> { + Spacer(Modifier.height(10.dp)) + FormLabel("判断条件") + Spacer(Modifier.height(4.dp)) + FlowChips( + options = meta.judgeKinds, + active = draft.judgeKind, + onPick = { draft = draft.copy(judgeKind = it) }, + ) + if (draft.judgeKind !in listOf("empty", "not_empty")) { + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = draft.judgeValue, + onValueChange = { draft = draft.copy(judgeValue = it) }, + modifier = Modifier.fillMaxWidth(), + label = { + Text( + if (draft.judgeKind == "ai") "判断标准(交给模型判断)" + else if (draft.judgeKind.startsWith("longer") || draft.judgeKind.startsWith("shorter")) "字数" + else "关键词", + fontSize = 12.sp, + ) + }, + singleLine = true, + textStyle = TextStyle(fontSize = 14.sp), + ) + } + Spacer(Modifier.height(6.dp)) + Text( + "出边分 true / false 两条,界面上绿色实线是真、红色虚线是假。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + } + + "var" -> { + Spacer(Modifier.height(10.dp)) + VarPicker( + vars = meetingVars, + selected = draft.varName, + onPick = { draft = draft.copy(varName = it) }, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = draft.varValue, + onValueChange = { draft = draft.copy(varValue = it) }, + modifier = Modifier.fillMaxWidth().height(90.dp), + label = { Text("写死的值(留空则把上游内容存进去)", fontSize = 12.sp) }, + textStyle = TextStyle(fontSize = 13.sp), + ) + Spacer(Modifier.height(10.dp)) + // ★ **按变量类型自动决定动作**,这里要让用户看得见。 + // 列表默认追加、其他类型覆盖 —— 不写出来用户不知道会发生什么。 + val hitVar = meetingVars.firstOrNull { it.name == draft.varName } + Spacer(Modifier.height(8.dp)) + when { + hitVar == null -> Text( + "还没选变量。选一个之后这里会显示它会怎么存。", + fontSize = 11.sp, + color = MaterialTheme.colorScheme.error, + ) + hitVar.type == "list" -> { + Text( + "这个变量是**列表** —— 存的时候默认**追加一项**" + + "(循环里攒东西靠的就是这个,不用再连运算节点)。", + fontSize = 11.sp, + color = Doubao.Blue, + lineHeight = 16.sp, + ) + Spacer(Modifier.height(6.dp)) + FlowChips( + options = listOf( + "append" to "追加一项", + "replace" to "整体覆盖", + ), + active = draft.listMode.ifBlank { "append" }, + onPick = { draft = draft.copy(listMode = it) }, + ) + } + else -> Text( + "这个变量是「${typeLabel(hitVar.type)}」—— 存的时候**覆盖**旧值。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } + Spacer(Modifier.height(6.dp)) + Text( + "类型在「变量」面板里配,这里不用再选。变量整场会议共享,任何节点都能读。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + } + + "py" -> { + Spacer(Modifier.height(10.dp)) + Text( + "写一段 Python,入口约定是 def run(ctx)。\n" + + " ctx.input 上游内容 · ctx.vars 变量快照\n" + + " ctx.set_var(名, 值) 写变量 · ctx.log(...) 记一条说明\n" + + "跑挂了会在节点上报错,不会让整场会议停;死循环 10 秒会被掐掉。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + Spacer(Modifier.height(8.dp)) + FormLabel("代码") + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = draft.code, + onValueChange = { draft = draft.copy(code = it) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 150.dp), + placeholder = { Text("def run(ctx):\n return ctx.input.upper()", fontSize = 12.sp) }, + textStyle = TextStyle(fontSize = 12.sp), + label = { Text("run(ctx)", fontSize = 11.sp) }, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = draft.desc, + onValueChange = { draft = draft.copy(desc = it) }, + modifier = Modifier.fillMaxWidth(), + label = { Text("给智能体看的说明(当工具时用)", fontSize = 11.sp) }, + placeholder = { Text("例如:把一段文字变成大写", fontSize = 12.sp) }, + textStyle = TextStyle(fontSize = 13.sp), + maxLines = 2, + ) + Spacer(Modifier.height(6.dp)) + Text( + "想让智能体调用它:去**智能体节点**上勾「可用工具」。", + fontSize = 11.sp, + color = Doubao.Blue, + lineHeight = 16.sp, + ) + } + + "cast" -> { + Spacer(Modifier.height(10.dp)) + FormLabel("转成什么类型") + Spacer(Modifier.height(4.dp)) + Text( + "类型校验是认真的,连错类型接不上 —— 所以要有这么一步显式转换。" + + "转真假用的是和 while 判断同一套规则:0 / 空 / false / no 是假," + + "其他非空都是真。转数字时解析不了就当 0。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + Spacer(Modifier.height(6.dp)) + FlowChips( + options = listOf( + "str" to "文本 str", + "bool" to "真假 bool", + "num" to "数字 num", + "list" to "列表 list", + ), + active = draft.castTo.ifBlank { "str" }, + onPick = { draft = draft.copy(castTo = it) }, + ) + } + + "op" -> { + Spacer(Modifier.height(10.dp)) + FormLabel("算什么") + Spacer(Modifier.height(4.dp)) + FlowChips( + options = OPS_UI, + active = draft.op.ifBlank { "add" }, + onPick = { draft = draft.copy(op = it) }, + ) + Spacer(Modifier.height(6.dp)) + val (inType, outType, arity) = opSpec(draft.op.ifBlank { "add" }) + Text( + "入口要「${typeLabel(inType)}」,出口是「${typeLabel(outType)}」" + + if (arity == 1) "(单目运算,只有一个入口)" else "(两个入口 A / B)", + fontSize = 11.sp, + color = Doubao.Blue, + lineHeight = 16.sp, + ) + Spacer(Modifier.height(4.dp)) + Text( + "除零、把文字当数字算都不会让会议停下,会照常往下跑并把问题记在结果里。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 16.sp, + ) + } + + "readvar" -> { + Spacer(Modifier.height(10.dp)) + VarPicker( + vars = meetingVars, + selected = draft.varName, + onPick = { draft = draft.copy(varName = it) }, + ) + Spacer(Modifier.height(6.dp)) + Text( + "读出变量的当前值,当成这个节点的输出往下传。" + + "**类型跟着变量走**(在「变量」面板里配),它决定了这根线能接到哪去。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } + } + + /* -------- 执行次数:所有节点类型都适用 -------- */ + Spacer(Modifier.height(14.dp)) + FormLabel("最多执行次数") + Spacer(Modifier.height(4.dp)) + FlowChips( + options = listOf( + "1" to "1 次", + "2" to "2 次", + "3" to "3 次", + "5" to "5 次", + "10" to "10 次", + "0" to "无限循环", + ), + active = draft.maxRuns.toString(), + onPick = { draft = draft.copy(maxRuns = it.toIntOrNull() ?: 1) }, + ) + Spacer(Modifier.height(6.dp)) + Text( + when (draft.maxRuns) { + 0 -> "一直跑下去,觉得够了点「停止」。适合两个智能体互相点评这种。" + 1 -> "只跑一次。有环(比如甲→乙→甲)也只转一圈。" + else -> "有环时会来回跑最多 ${draft.maxRuns} 轮;不在环上的节点照样只跑一次。" + }, + fontSize = 11.sp, + color = if (draft.maxRuns == 0) Doubao.Blue else doubaoTextSecondary(), + lineHeight = 16.sp, + ) + } + }, + confirmButton = { TextButton(onClick = { onSave(draft) }) { Text("保存") } }, + dismissButton = { + Row { + TextButton(onClick = onDelete) { + Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp) + } + TextButton(onClick = onDismiss) { Text("取消") } + } + }, + ) + } + + diff --git a/android/kernel/meeting.py b/android/kernel/meeting.py index f75252c..658bc53 100644 --- a/android/kernel/meeting.py +++ b/android/kernel/meeting.py @@ -211,8 +211,12 @@ OPS = ( ('div', '除 ÷', 'num', 'num', 2), ('mod', '取余 %', 'num', 'num', 2), ('concat', '拼接', 'str', 'str', 2), - ('eq', '等于 =', 'str', 'bool', 2), - ('ne', '不等于 ≠', 'str', 'bool', 2), + ('eq', '等于 =(数字)', 'num', 'bool', 2), + ('ne', '不等于 ≠(数字)', 'num', 'bool', 2), + # ★ 文本相等单独一份:数字相等和文本相等**不是一回事** —— + # "01" 和 "1" 作为文本不等,作为数字相等;拼写比较也不能先转成数字。 + ('streq', '文本等于 ==', 'str', 'bool', 2), + ('strne', '文本不等于 !=', 'str', 'bool', 2), ('gt', '大于 >', 'num', 'bool', 2), ('lt', '小于 <', 'num', 'bool', 2), ('gte', '大于等于 ≥', 'num', 'bool', 2), @@ -343,8 +347,17 @@ def apply_op(op_key: str, a, b=None): if op_key == 'concat': return str(a) + str(b), '' - if op_key in ('eq', 'ne'): + # 文本相等:直接比字符串,不经过 as_num。 + # 两者不能混:01 和 1 作为文本不等、作为数字相等。 + if op_key in ('streq', 'strne'): same = str(a) == str(b) + return cast_value(same if op_key == 'streq' else not same, 'bool'), '' + if op_key in ('eq', 'ne'): + x1, e3 = as_num(a) + y1, e4 = as_num(b) + if e3 or e4: + return 'false', (e3 or e4) + same = (x1 == y1) return cast_value(same if op_key == 'eq' else not same, 'bool'), '' x, e1 = as_num(a) diff --git a/scripts/verify-ops.py b/scripts/verify-ops.py new file mode 100644 index 0000000..1a99b2d --- /dev/null +++ b/scripts/verify-ops.py @@ -0,0 +1,34 @@ +"""核对引擎和界面的算子表是否一致。 + +加算子时"只加一边"已经犯过好几次: + · 引擎加了 gte/lte/and/or/xor/shl/shr,界面 OPS_UI 没加(用户"没看到大于等于") + · 引擎有 neg/not,界面也选不到 +加完算子先跑它,别等用户发现。 +""" +import os, re, sys +WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(WS, 'android', 'kernel')) +import meeting as M +KT = os.path.join(WS, 'android', 'app', 'src', 'main', 'java', + 'com', 'doubao', 'lynxclone', 'ui', 'MeetingsScreen.kt') +src = open(KT, encoding='utf-8').read() +m = re.search(r'OPS_UI = listOf\((.*?)\n\s*\)', src, re.S) +ui = set(re.findall(r'"(\w+)"\s+to\s+"', m.group(1))) if m else set() +eng = {o[0] for o in M.OPS} +sb = re.search(r'private fun opSpec\(key: String\)(.*?)private fun opLabel', src, re.S) +ss = sb.group(1) if sb else '' +spec = set(re.findall(r'"(\w+)"', ss)) +has_else = 'else ->' in ss +miss_ui = sorted(eng - ui) +miss_spec = [] if has_else else sorted(ui - spec) +covered = sorted(ui - spec) if has_else else [] +extra = sorted(ui - eng) +print(' 引擎 OPS %d 个' % len(eng)) +print(' 界面 OPS_UI %d 个' % len(ui)) +print(' 界面 opSpec %d 个%s' % (len(spec), '(有 else 兜底)' if has_else else '')) +print(' %s 引擎有、界面选项里没有: %s' % ('X' if miss_ui else 'v', miss_ui or '无')) +print(' %s 界面有选项、opSpec 没定义类型: %s' % ('X' if miss_spec else 'v', miss_spec or '无')) +if covered: + print(' (%s 由 else 兜底,正常)' % covered) +print(' %s 界面有、引擎不认: %s' % ('X' if extra else 'v', extra or '无')) +sys.exit(1 if (miss_ui or miss_spec or extra) else 0) \ No newline at end of file