会议模式:端口化连线、真假分支、变量节点、结果历史独立界面
用户反馈的四条。
【1. 连线改成端口】
以前是"节点上一个「连线」按钮,真假由程序猜"(第一条连 true、第二条连 false)——
用户根本不知道自己在连哪条,也没法只连一条。
现在:
- 每个节点左侧一个**输入端口**、右侧一个**输出端口**
- **判断节点右侧两个输出端口:上真(绿实线)下假(红虚线)**
- 点输出端口 → 点输入端口,所见即所得
- 输入端口的连线数写在卡片上("← 2 路")—— 智能体的输入本来就能接多路,
多路按顺序拼成一段文本,但以前界面上看不出来接了几路
- 真/假除了颜色还写了字:只靠红绿对色弱用户不友好
★ 所有点击(端口连线、开配置)都收进画布的**同一个**手势处理器统一命中判断,
节点上一个 clickable 都不挂 —— 多个手势识别器叠一起必然互相抢,
这个坑前面已经踩过两次("节点拖不动"就是其中一次)。
【2. 结果单开一屏 + 历史】
原来是弹窗:一次运行可能几十轮、每轮都有大段输出,弹窗那点地方根本放不下。
现在:
- 独立一屏,可以滚动着对照着看
- **历史**:内核在每次跑完时自动落一条记录(含每个节点的产出和轮次),
最多留 20 条,最新的在前。展开能看**哪个节点、第几轮**输出了什么
- 最终输出放最上面(那才是用户要的),其余按**节点在图上从左到右的顺序**排
- 每条都能单独复制
- 删会议时连带清掉它的历史(不然就是永远读不到的垃圾)
【3. 变量节点】
新增两种节点:
- **写变量**:把上游内容(或写死的值)存进一个变量
- **读变量**:把变量的当前值取出来往下传
变量是**整场会议共享的**:任何节点都能读,不用连线传。
需要它是因为会议是多轮多节点的,只靠连线传的话,到分叉再汇合就乱了
(一个节点只能拿到直接上游)。
【4. 智能体可以读/写变量】
智能体节点上勾"可读变量"和"可写变量":
- 可读的:当前值拼进它的提示词
- 可写的:告诉它用 `[[SET 名字=值]]` 写回来;引擎收到后**剥掉那一行**、
写进变量表,并发一个 node_vars 事件让界面显示"它改了哪些"
- **没授权的写不动**:那一行会原样留在正文里 ——
让用户看见"它想写但没权限",比默默失败好查得多
权限要显式勾选,不然模型会去猜"我能不能改这个",行为不可预测。
【一个真正的设计问题,被测试逼出来的】
`[[SET]]` 的解析我一开始放在 HTTP 层(app.py / index.mjs 的 runAgentFn 里),
结果**引擎测试全绿、一上 HTTP 就漏出 [[SET]] 那行** —— 因为引擎测试用的是
自己提供的假 runAgentFn,压根走不到那段代码。
这是节点语义("这个智能体能写哪些变量"是节点配置),应该归引擎。
挪进 run_meeting 之后,引擎测试立刻覆盖到了,而且换个调用方也不会忘。
【验证】
- verify-meeting.mjs:新增 5 个变量用例(写→读、留空用上游、读没设过的变量、
[[SET]] 被收走且不漏进正文、没授权的写不动),
**Node 与 Python 16/16 逐用例一致**,总 40/40
- verify-meeting-http.mjs:13/13 ×2(新增"节点类型里有写变量/读变量"断言)
- 模拟器实测:端口、判断节点的真假两色连线、输入端口的"← N 路"、×2 轮次标记、
写/读变量节点,全部正常显示
- 全部回归:Markdown 19/19、语音 41/41 ×2、会议引擎 40/40、会议 HTTP 13/13 ×2
This commit is contained in:
@@ -10,6 +10,8 @@ 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
|
||||
@@ -63,6 +65,8 @@ 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
|
||||
|
||||
/**
|
||||
@@ -254,7 +258,9 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
var configTarget by remember { mutableStateOf<MeetingNode?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
// 正在连线的源节点(两步点选的第一个"点")
|
||||
var linkingFrom by remember { mutableStateOf<String?>(null) }
|
||||
// 正在连线:记 (源节点id, 出边分支)。
|
||||
// 判断节点有真/假两个输出端口,只记节点 id 分不清是从哪个口拉出来的。
|
||||
var linkingFrom by remember { mutableStateOf<Pair<String, String>?>(null) }
|
||||
var running by remember { mutableStateOf(false) }
|
||||
var runInput by remember { mutableStateOf("") }
|
||||
var runError by remember { mutableStateOf("") }
|
||||
@@ -305,7 +311,7 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
)
|
||||
Text(
|
||||
when {
|
||||
linkingFrom != null -> "点目标节点完成连线(点空白取消)"
|
||||
linkingFrom != null -> "点目标节点的左侧圆点接线(点空白取消)"
|
||||
dirty -> "未保存"
|
||||
// 手势规则要写出来:两指平移不是所有人一上来就知道的
|
||||
else -> "${meeting.nodes.size} 节点 · ${meeting.edges.size} 连线 · 一指拖节点 / 两指移画布"
|
||||
@@ -370,17 +376,18 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
// 画布
|
||||
//
|
||||
// ★ 手势分工(用户定的,比"谁抢到算谁的"清楚得多):
|
||||
// **一指** → 拖手指底下那个节点;落在空白处则什么都不做
|
||||
// **一指** → 拖手指底下那个节点;点在端口上是连线;点在节点上开配置
|
||||
// **两指** → 平移画布(按在哪都行,包括按在节点上)
|
||||
//
|
||||
// 为什么这样分:一指拖节点是手机上的直觉;而"想挪画布"和"想挪节点"
|
||||
// 是两种完全不同的意图,用**手指数**区分最干净 —— 不需要谁去抢,
|
||||
// 也不会再出现"想拖节点结果整张图跑了"(之前就是这么坏的)。
|
||||
// 两指平移也是各家地图/画布应用的通用做法,用户不用学。
|
||||
//
|
||||
// 点击(开配置、点「连线」)仍由节点自己的 clickable 处理:
|
||||
// 那个只在"没怎么移动"时触发,和这里的拖动不冲突。
|
||||
// ★ 所有点击(端口连线、开配置)也收在这里统一命中判断,
|
||||
// 不再让节点自己挂 clickable —— 多个手势识别器叠一起必然互相抢,
|
||||
// 这个坑前面已经踩过两次了。
|
||||
val nodesSnapshot = rememberUpdatedState(meeting.nodes)
|
||||
val linkingSnapshot = rememberUpdatedState(linkingFrom)
|
||||
|
||||
Box(
|
||||
Modifier
|
||||
@@ -389,15 +396,32 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
.pointerInput(Unit) {
|
||||
val nodeW = NODE_W.dp.toPx()
|
||||
val nodeH = NODE_H.dp.toPx()
|
||||
val portHit = PORT_HIT.dp.toPx()
|
||||
// 画布的像素尺寸按**真实密度**算,不再拍一个 2.75
|
||||
val contentW = CANVAS_W.dp.toPx()
|
||||
val contentH = CANVAS_H.dp.toPx()
|
||||
|
||||
fun hitTest(pos: Offset, pan: Offset): MeetingNode? {
|
||||
// 屏幕坐标 → 画布坐标(减掉平移量)
|
||||
val cx = pos.x - pan.x
|
||||
val cy = pos.y - pan.y
|
||||
return nodesSnapshot.value.lastOrNull { n ->
|
||||
cx >= n.x.dp.toPx() && cx <= n.x.dp.toPx() + nodeW &&
|
||||
cy >= n.y.dp.toPx() && cy <= n.y.dp.toPx() + nodeH
|
||||
fun toCanvas(pos: Offset, pan: Offset) = Offset(pos.x - pan.x, pos.y - pan.y)
|
||||
|
||||
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() + nodeH
|
||||
}
|
||||
|
||||
/** 命中哪个端口。返回 (节点, 分支, 是输出端);输入端的 branch 恒为空串 */
|
||||
fun portAt(c: Offset): Triple<MeetingNode, String, Boolean>? {
|
||||
for (n in nodesSnapshot.value.asReversed()) {
|
||||
// 先看输出端口(判断节点有两个)
|
||||
for (b in outBranches(n)) {
|
||||
if ((portOut(n, b).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) } - c).getDistance() <= portHit) {
|
||||
return Triple(n, b, true)
|
||||
}
|
||||
}
|
||||
if ((portIn(n).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) } - c).getDistance() <= portHit) {
|
||||
return Triple(n, "", false)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
awaitEachGesture {
|
||||
@@ -405,10 +429,10 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
var last = down.position
|
||||
var moved = false
|
||||
var accumulated = 0f
|
||||
// 被拖节点的当前位置。必须自己累加 ——
|
||||
// 直接用 hit.x + delta 的话每一帧都在拿"按下那一刻的坐标"
|
||||
// 加一个小增量,节点会原地不动或者瞬移回起点。
|
||||
var hit = hitTest(down.position, Offset(panX, panY))
|
||||
val c0 = toCanvas(down.position, Offset(panX, panY))
|
||||
// 按在端口上就不算"拖节点",否则会一边连线一边把节点拖走
|
||||
val portHitAtDown = portAt(c0)
|
||||
var hit = if (portHitAtDown == null) nodeAt(c0) else null
|
||||
var dragX = hit?.x ?: 0f
|
||||
var dragY = hit?.y ?: 0f
|
||||
// 平移用:上一次的质心和手指数。手指数一变就重置,
|
||||
@@ -422,7 +446,7 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
if (pressed.isEmpty()) break
|
||||
|
||||
if (pressed.size >= 2) {
|
||||
// 两指:平移画布。正在拖的节点立刻放手 ——
|
||||
// 两层:平移画布。正在拖的节点立刻放手 ——
|
||||
// 用户临时改主意想挪画布,不该继续拖着节点跑。
|
||||
hit = null
|
||||
moved = true
|
||||
@@ -435,6 +459,7 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
panX + (centroid.x - prev.x),
|
||||
panY + (centroid.y - prev.y),
|
||||
size.width.toFloat(), size.height.toFloat(),
|
||||
contentW, contentH,
|
||||
)
|
||||
panX = next.first
|
||||
panY = next.second
|
||||
@@ -465,7 +490,44 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
}
|
||||
last = change.position
|
||||
}
|
||||
if (moved && hit != null) persist()
|
||||
|
||||
if (!moved) {
|
||||
// ------- 没怎么动 = 点击 -------
|
||||
val linking = linkingSnapshot.value
|
||||
when {
|
||||
// 点输出端口:开始/取消连线
|
||||
portHitAtDown != null && portHitAtDown.third -> {
|
||||
val (n, b, _) = portHitAtDown
|
||||
linkingFrom = if (linking?.first == n.id && linking.second == b) {
|
||||
null
|
||||
} else {
|
||||
n.id to b
|
||||
}
|
||||
}
|
||||
// 点输入端:完成连线
|
||||
portHitAtDown != null && linking != null -> {
|
||||
val (n, _, _) = portHitAtDown
|
||||
val from = linking.first
|
||||
if (from != n.id) {
|
||||
// 同一条出边只留一条:再连一次是"改接",不是"多连一条"
|
||||
val kept = meeting.edges.filterNot {
|
||||
it.from == from && it.branch == linking.second
|
||||
}
|
||||
meeting = meeting.copy(
|
||||
edges = kept + MeetingEdge(from, n.id, linking.second),
|
||||
)
|
||||
dirty = true
|
||||
persist()
|
||||
}
|
||||
linkingFrom = null
|
||||
}
|
||||
// 点空白:取消连线;点节点:开配置
|
||||
portHitAtDown == null && hit != null -> configTarget = hit
|
||||
portHitAtDown == null && linking != null -> linkingFrom = null
|
||||
}
|
||||
} else if (hit != null) {
|
||||
persist()
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
@@ -477,30 +539,36 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
translationY = panY
|
||||
},
|
||||
) {
|
||||
// 连线画在节点底下
|
||||
// 连线和端口画在节点底下
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val w = NODE_W.dp.toPx()
|
||||
val h = NODE_H.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 = Offset(a.x.dp.toPx() + w, a.y.dp.toPx() + h / 2)
|
||||
val end = Offset(b.x.dp.toPx(), b.y.dp.toPx() + h / 2)
|
||||
// 判断节点的两条出边用虚线区分,并在中间标 true / false
|
||||
val dashed = edge.branch == "false"
|
||||
// ★ 从**端口的实际位置**画起,不是从节点中心 ——
|
||||
// 判断节点两条出边一个在上一个在下,都从中心出发就分不清了
|
||||
val start = portOut(a, edge.branch).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
val end = portIn(b).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
val color = when (edge.branch) {
|
||||
"true" -> Color(0xFF34A853)
|
||||
"false" -> Color(0xFFEA4335)
|
||||
else -> Color(0xFFBFC4CC)
|
||||
}
|
||||
drawLine(
|
||||
color = if (edge.branch == "true") Doubao.Blue
|
||||
else if (dashed) Color(0xFF9AA0A6) else Color(0xFFBFC4CC),
|
||||
color = color,
|
||||
start = start,
|
||||
end = end,
|
||||
strokeWidth = 2.dp.toPx(),
|
||||
pathEffect = if (dashed) PathEffect.dashPathEffect(floatArrayOf(10f, 10f)) else null,
|
||||
pathEffect = if (edge.branch == "false") {
|
||||
PathEffect.dashPathEffect(floatArrayOf(10f, 10f))
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
// 箭头
|
||||
val angle = kotlin.math.atan2((end.y - start.y), (end.x - start.x))
|
||||
val len = 12.dp.toPx()
|
||||
drawLine(
|
||||
color = if (edge.branch == "true") Doubao.Blue else Color(0xFFBFC4CC),
|
||||
color = color,
|
||||
start = end,
|
||||
end = Offset(
|
||||
end.x - len * kotlin.math.cos(angle - 0.4f),
|
||||
@@ -509,15 +577,26 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
strokeWidth = 2.dp.toPx(),
|
||||
)
|
||||
}
|
||||
// 正在连线:从源节点画一条虚线跟着(这里只画到画布中心做个提示)
|
||||
linkingFrom?.let { from ->
|
||||
val a = meeting.nodes.firstOrNull { it.id == from }
|
||||
if (a != null) {
|
||||
|
||||
// 端口圆点。画在最上层,用户看得见"从哪儿拉出去、往哪儿接进来"。
|
||||
meeting.nodes.forEach { node ->
|
||||
val inP = portIn(node).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = inP)
|
||||
drawCircle(Color(0xFFBFC4CC), radius = PORT_R.dp.toPx(), center = inP)
|
||||
|
||||
outBranches(node).forEach { branch ->
|
||||
val p = portOut(node, branch).let { o -> Offset(o.x.dp.toPx(), o.y.dp.toPx()) }
|
||||
val c = when (branch) {
|
||||
"true" -> Color(0xFF34A853)
|
||||
"false" -> Color(0xFFEA4335)
|
||||
else -> nodeColor(node.type)
|
||||
}
|
||||
val active = linkingFrom?.let { it.first == node.id && it.second == branch } == true
|
||||
drawCircle(Color.White, radius = (PORT_R + 1.5f).dp.toPx(), center = p)
|
||||
drawCircle(
|
||||
color = Doubao.Blue,
|
||||
radius = 6.dp.toPx(),
|
||||
center = Offset(a.x.dp.toPx() + w, a.y.dp.toPx() + h / 2),
|
||||
style = Stroke(width = 3.dp.toPx()),
|
||||
color = c,
|
||||
radius = (if (active) PORT_R + 2f else PORT_R).dp.toPx(),
|
||||
center = p,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -530,46 +609,9 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
node = node,
|
||||
status = status,
|
||||
output = nodeOutputs[node.id] ?: "",
|
||||
linking = linkingFrom == node.id,
|
||||
linking = linkingFrom?.first == node.id,
|
||||
inDegree = meeting.edges.count { it.to == node.id },
|
||||
modifier = Modifier.offset(node.x.dp, node.y.dp),
|
||||
onDrag = { dx, dy ->
|
||||
updateNode(
|
||||
node.copy(
|
||||
// 夹在画布内,别让节点被拖到看不见的地方找不回来
|
||||
x = (node.x + dx).coerceIn(0f, CANVAS_W - NODE_W),
|
||||
y = (node.y + dy).coerceIn(0f, CANVAS_H - NODE_H),
|
||||
),
|
||||
)
|
||||
},
|
||||
onDragEnd = { if (dirty) persist() },
|
||||
onClick = {
|
||||
val from = linkingFrom
|
||||
when {
|
||||
// 第二步:点目标节点,连上
|
||||
from != null && from != node.id -> {
|
||||
val exists = meeting.edges.any { it.from == from && it.to == node.id }
|
||||
if (!exists) {
|
||||
// 判断节点的出边要分 true / false:
|
||||
// 还没有 true 边就先连 true,否则连 false
|
||||
val fromNode = meeting.nodes.firstOrNull { it.id == from }
|
||||
val branch = if (fromNode?.type == "judge") {
|
||||
val used = meeting.edges.filter { it.from == from }
|
||||
.map { it.branch }
|
||||
if (!used.contains("true")) "true" else "false"
|
||||
} else ""
|
||||
meeting = meeting.copy(
|
||||
edges = meeting.edges + MeetingEdge(from, node.id, branch),
|
||||
)
|
||||
dirty = true
|
||||
persist()
|
||||
}
|
||||
linkingFrom = null
|
||||
}
|
||||
from == node.id -> linkingFrom = null
|
||||
else -> configTarget = node
|
||||
}
|
||||
},
|
||||
onLink = { linkingFrom = if (linkingFrom == node.id) null else node.id },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -632,18 +674,26 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
}
|
||||
}
|
||||
|
||||
// 结果单开一屏(不是弹窗):一次运行可能几十轮、每轮都有大段输出,
|
||||
// 弹窗那点地方根本放不下,也没法滚动着对照着看。
|
||||
if (showResult) {
|
||||
MeetingResultDialog(
|
||||
MeetingResultScreen(
|
||||
vm = vm,
|
||||
meeting = meeting,
|
||||
outputs = nodeOutputs,
|
||||
onDismiss = { showResult = false },
|
||||
liveOutputs = nodeOutputs,
|
||||
onBack = { showResult = false },
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
configTarget?.let { target ->
|
||||
NodeConfigDialog(
|
||||
node = target,
|
||||
meta = vm.meetingMeta,
|
||||
knownVarNames = meeting.nodes
|
||||
.filter { it.type == "var" && it.varName.isNotBlank() }
|
||||
.map { it.varName }
|
||||
.distinct(),
|
||||
onDismiss = { configTarget = null },
|
||||
onSave = { updated ->
|
||||
updateNode(updated)
|
||||
@@ -700,20 +750,50 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () -
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 端口的几何位置(单位 dp,和节点坐标同一套)。
|
||||
*
|
||||
* ★ 判断节点有**两个输出端口**:真在上、假在下。
|
||||
* 以前是"一个节点一个连线按钮,真假由程序猜"(第一条连 true、第二条连 false)——
|
||||
* 用户根本不知道自己在连哪条,也没法只连一条。改成真端口之后所见即所得。
|
||||
*/
|
||||
private fun portIn(node: MeetingNode): Offset =
|
||||
Offset(node.x, node.y + NODE_H / 2f)
|
||||
|
||||
private fun portOut(node: MeetingNode, branch: String): Offset {
|
||||
val y = when (branch) {
|
||||
"true" -> node.y + NODE_H * 0.30f
|
||||
"false" -> node.y + NODE_H * 0.70f
|
||||
else -> node.y + NODE_H / 2f
|
||||
}
|
||||
return Offset(node.x + NODE_W, y)
|
||||
}
|
||||
|
||||
/** 端口圆点的半径(画多大)与命中半径(点多准)。命中范围要大一圈,手指没那么准。 */
|
||||
private const val PORT_R = 6f
|
||||
private const val PORT_HIT = 22f
|
||||
|
||||
/** 输入端口永远只有一个;输出端口按分支给(普通节点一个,判断节点真假两个) */
|
||||
private fun outBranches(node: MeetingNode): List<String> =
|
||||
if (node.type == "judge") listOf("true", "false") else listOf("")
|
||||
|
||||
/**
|
||||
* 平移范围的钳制。
|
||||
*
|
||||
* 不让用户把整张图拖到屏幕外找不回来 —— 这比"能无限拖"重要得多:
|
||||
* 手机上误拖一下整张图没了,用户只会以为程序坏了。
|
||||
*
|
||||
* ★ 画布的实际像素尺寸必须按**真实密度**算。之前写死 2.75 是拍的,
|
||||
* 密度 2.0 的机器上纵向只能挪一点点,用户体感就是"视图挪不动"。
|
||||
*/
|
||||
private fun clampPan(x: Float, y: Float, viewW: Float, viewH: Float): Pair<Float, Float> {
|
||||
val contentW = CANVAS_W * 2.75f // dp → px(按 2.75 的常见密度估)
|
||||
val contentH = CANVAS_H * 2.75f
|
||||
return Pair(
|
||||
x.coerceIn(minOf(0f, viewW - contentW), 0f),
|
||||
y.coerceIn(minOf(0f, viewH - contentH), 0f),
|
||||
)
|
||||
}
|
||||
private fun clampPan(
|
||||
x: Float, y: Float,
|
||||
viewW: Float, viewH: Float,
|
||||
contentW: Float, contentH: Float,
|
||||
): Pair<Float, Float> = Pair(
|
||||
x.coerceIn(minOf(0f, viewW - contentW), 0f),
|
||||
y.coerceIn(minOf(0f, viewH - contentH), 0f),
|
||||
)
|
||||
|
||||
/**
|
||||
* 把一条会议事件应用到界面状态上。
|
||||
@@ -750,51 +830,110 @@ private fun applyMeetingEvent(
|
||||
* 而不是按事件到达顺序:用户脑子里的顺序是图上从左到右,不是事件流。
|
||||
*/
|
||||
@Composable
|
||||
private fun MeetingResultDialog(
|
||||
private fun MeetingResultScreen(
|
||||
vm: AppViewModel,
|
||||
meeting: Meeting,
|
||||
outputs: Map<String, String>,
|
||||
onDismiss: () -> Unit,
|
||||
liveOutputs: Map<String, String>,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// 最终输出单独拎出来放最上面:那是用户真正要的东西
|
||||
val endNode = meeting.nodes.firstOrNull { it.type == "end" }
|
||||
val finalText = endNode?.let { outputs[it.id] }.orEmpty()
|
||||
val ordered = remember(meeting.id, outputs.size) {
|
||||
meeting.nodes
|
||||
.filter { it.type != "end" && outputs[it.id].orEmpty().isNotBlank() }
|
||||
.sortedWith(compareBy({ it.y }, { it.x }))
|
||||
}
|
||||
var runs by remember { mutableStateOf<List<MeetingRun>>(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
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("运行结果", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (finalText.isBlank() && ordered.isEmpty()) {
|
||||
Text("还没有结果,先点运行。", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
LaunchedEffect(meeting.id) {
|
||||
try {
|
||||
runs = vm.client.meetingRuns(meeting.id)
|
||||
} catch (_: Exception) {
|
||||
// 读不到历史不算错:至少还能看当前这次
|
||||
}
|
||||
loading = false
|
||||
}
|
||||
|
||||
if (finalText.isNotBlank()) {
|
||||
Text("最终输出", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// 当前这次(刚跑完、还没落盘成历史的那份)
|
||||
val current = remember(meeting.id, liveOutputs.size) {
|
||||
meeting.nodes
|
||||
.filter { it.type != "end" && liveOutputs[it.id].orEmpty().isNotBlank() }
|
||||
.sortedWith(compareBy({ it.y }, { it.x }))
|
||||
}
|
||||
val currentFinal = meeting.nodes.firstOrNull { it.type == "end" }
|
||||
?.let { liveOutputs[it.id] }.orEmpty()
|
||||
|
||||
fun nodeLabel(step: MeetingStep): String = step.title.ifBlank {
|
||||
when (step.nodeType) {
|
||||
"start" -> "初始输入"
|
||||
"judge" -> "判断"
|
||||
"end" -> "最终输出"
|
||||
else -> "智能体"
|
||||
}
|
||||
}
|
||||
|
||||
/** 把一次运行拼成能复制的纯文本 */
|
||||
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()) {
|
||||
Text("本次", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
if (currentFinal.isNotBlank()) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
color = Doubao.Blue.copy(alpha = 0.06f),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
finalText,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
lineHeight = 19.sp,
|
||||
modifier = Modifier.padding(10.dp),
|
||||
)
|
||||
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))
|
||||
}
|
||||
|
||||
ordered.forEach { node ->
|
||||
current.forEach { node ->
|
||||
Text(
|
||||
node.title.ifBlank {
|
||||
when (node.type) {
|
||||
@@ -809,36 +948,142 @@ private fun MeetingResultDialog(
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
outputs[node.id].orEmpty(),
|
||||
liveOutputs[node.id].orEmpty(),
|
||||
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.forEach { n ->
|
||||
append("【${n.title.ifBlank { n.type }}】\n")
|
||||
append(liveOutputs[n.id].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))
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Row {
|
||||
TextButton(onClick = {
|
||||
// 结果要能拿走:用户多半是要粘到别处用
|
||||
val all = buildString {
|
||||
if (finalText.isNotBlank()) append(finalText)
|
||||
else {
|
||||
ordered.forEach { n ->
|
||||
append("【${n.title.ifBlank { n.type }}】\n")
|
||||
append(outputs[n.id].orEmpty())
|
||||
append("\n\n")
|
||||
|
||||
// ---------------- 历史 ----------------
|
||||
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))
|
||||
// 同一个节点跑过几轮?用来决定要不要标"第N轮"
|
||||
val countByNode = run.steps.groupingBy { it.nodeId }.eachCount()
|
||||
run.steps.forEach { s ->
|
||||
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()
|
||||
},
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
Text(
|
||||
if (s.error.isNotBlank()) "出错:${s.error}" else s.output,
|
||||
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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
clipboard.setText(androidx.compose.ui.text.AnnotatedString(all))
|
||||
android.widget.Toast.makeText(context, "已复制", android.widget.Toast.LENGTH_SHORT).show()
|
||||
}) { Text("复制") }
|
||||
TextButton(onClick = onDismiss) { Text("关闭") }
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ====================================================================== */
|
||||
@@ -858,11 +1103,9 @@ private fun NodeCard(
|
||||
status: String,
|
||||
output: String,
|
||||
linking: Boolean,
|
||||
/** 接到这个节点的连线数(多路输入要显示出来) */
|
||||
inDegree: Int,
|
||||
modifier: Modifier,
|
||||
onDrag: (Float, Float) -> Unit,
|
||||
onDragEnd: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
onLink: () -> Unit,
|
||||
) {
|
||||
val accent = nodeColor(node.type)
|
||||
Column(
|
||||
@@ -880,10 +1123,9 @@ private fun NodeCard(
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
// 拖动节点/平移画布由**父级**统一处理(见上面画布那段的长注释)。
|
||||
// 这里只留点击:开配置、点「连线」按钮。clickable 只在几乎没移动时
|
||||
// 才触发,和父级的拖动不冲突。
|
||||
.clickable(onClick = onClick)
|
||||
// 拖动节点 / 平移画布 / 点击(开配置、点端口连线)**全部**由父级
|
||||
// 统一处理(见上面画布那段的长注释)。这里一个手势识别器都不挂 ——
|
||||
// 多个叠一起必然互相抢,这个坑前面踩过两次了。
|
||||
.padding(8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -928,20 +1170,13 @@ private fun NodeCard(
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// 连线按钮:两步点选的第一步
|
||||
if (node.type != "end") {
|
||||
Text(
|
||||
if (linking) "选目标…" else "连线",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.clickable(onClick = onLink)
|
||||
.padding(horizontal = 4.dp, vertical = 1.dp),
|
||||
)
|
||||
// 接到这个节点的连线数。智能体的输入是**可以接多路**的(多路按顺序
|
||||
// 拼成一段文本),把条数写出来,用户才知道自己接了几路、有没有漏。
|
||||
if (inDegree > 0) {
|
||||
Text("← $inDegree 路", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (node.maxRuns != 1) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 会重复的节点标出来:不然图上看着和普通节点一样,
|
||||
// 跑起来发现它转了三轮会很意外
|
||||
Text(
|
||||
@@ -958,6 +1193,44 @@ private fun NodeCard(
|
||||
/* 小零件 */
|
||||
/* ====================================================================== */
|
||||
|
||||
/**
|
||||
* 变量名的多选胶囊。
|
||||
*
|
||||
* 和 FlowChips 的区别只有一个:**可以同时选中多个**。
|
||||
* 单独写一个而不是给 FlowChips 加参数 —— 单选和多选的视觉反馈不一样
|
||||
* (多选要明确标出"勾上了"),混在一起容易让人以为没生效。
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun VarChips(
|
||||
names: List<String>,
|
||||
selected: List<String>,
|
||||
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) {
|
||||
@@ -1001,6 +1274,8 @@ private fun FlowChips(
|
||||
private fun NodeConfigDialog(
|
||||
node: MeetingNode,
|
||||
meta: com.doubao.lynxclone.data.MeetingMeta,
|
||||
/** 图里所有「写变量」节点声明的变量名,供勾选权限用 */
|
||||
knownVarNames: List<String>,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (MeetingNode) -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
@@ -1078,6 +1353,68 @@ private fun NodeConfigDialog(
|
||||
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" -> {
|
||||
@@ -1109,12 +1446,59 @@ private fun NodeConfigDialog(
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"出边分 true / false 两条,界面上蓝色实线是 true、灰色虚线是 false。",
|
||||
"出边分 true / false 两条,界面上绿色实线是真、红色虚线是假。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 16.sp,
|
||||
)
|
||||
}
|
||||
|
||||
"var" -> {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = draft.varName,
|
||||
onValueChange = { draft = draft.copy(varName = it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text("变量名", fontSize = 12.sp) },
|
||||
placeholder = { Text("例如:主题", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
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(6.dp))
|
||||
Text(
|
||||
"变量是整场会议共享的:任何节点都能读,不用连线传。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 16.sp,
|
||||
)
|
||||
}
|
||||
|
||||
"readvar" -> {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = draft.varName,
|
||||
onValueChange = { draft = draft.copy(varName = it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text("变量名", fontSize = 12.sp) },
|
||||
placeholder = { Text("要和「写变量」节点的名字一致", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"读出变量的当前值,当成这个节点的输出往下传。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* -------- 执行次数:所有节点类型都适用 -------- */
|
||||
|
||||
@@ -27,6 +27,7 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
@@ -687,6 +688,8 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
{'key': 'agent', 'label': '智能体', 'desc': '一个智能体处理一轮'},
|
||||
{'key': 'judge', 'label': '判断', 'desc': '按条件分 true / false 两条路'},
|
||||
{'key': 'end', 'label': '最终输出', 'desc': '汇总结果'},
|
||||
{'key': 'var', 'label': '写变量', 'desc': '把内容存进一个变量,后面任何节点都能读'},
|
||||
{'key': 'readvar', 'label': '读变量', 'desc': '把变量的当前值取出来往下传'},
|
||||
],
|
||||
'judgeKinds': [{'key': k, 'label': v} for k, v in meeting.JUDGE_KINDS],
|
||||
'agents': [
|
||||
@@ -696,6 +699,16 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
})
|
||||
return True
|
||||
|
||||
# 运行历史:结果界面要能回看前几次跑了什么
|
||||
if pathname.startswith('/api/meetings/') and pathname.endswith('/runs'):
|
||||
mid = pathname[len('/api/meetings/'):-len('/runs')]
|
||||
if method == 'GET':
|
||||
self.send_json(200, {'runs': meeting.list_runs(mid)})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
self.send_json(200, {'ok': meeting.clear_runs(mid)})
|
||||
return True
|
||||
|
||||
# /api/meetings/<id>/run —— 走 SSE 跑整张图。
|
||||
# ★ 必须在 _match_id 之前处理:那个函数明确拒绝带斜杠的 id,
|
||||
# 而这里路径里就有一个 /run,交给它会永远匹配不上。
|
||||
@@ -930,13 +943,17 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
sse = SseChannel(self)
|
||||
sse.start()
|
||||
|
||||
def run_agent_fn(node: dict, incoming: str, cfg: dict, emit, node_id: str) -> str:
|
||||
def run_agent_fn(node: dict, incoming: str, cfg: dict, emit, node_id: str,
|
||||
variables: dict) -> str:
|
||||
"""
|
||||
跑一个 agent 节点 / AI 判断节点。
|
||||
|
||||
★ 节点的附加提示词和输出控制都是**拼在系统提示词后面**,而不是替换它 ——
|
||||
智能体本身的人设("你是毒舌评论员")不能被节点的输出要求顶掉,
|
||||
两者是"人设 + 这一轮的额外要求"的关系。
|
||||
|
||||
variables 是整场会议共享的变量表。节点上勾了可读/可写变量时,
|
||||
可读的把当前值拼进提示词,可写的告诉它怎么用 [[SET 名字=值]] 写回来。
|
||||
"""
|
||||
agent = store.agent_or_empty(node.get('agentId') or '') or None
|
||||
extra = (node.get('extraPrompt') or '').strip()
|
||||
@@ -956,6 +973,12 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
parts.append('【本次任务的额外要求】\n' + extra)
|
||||
if control:
|
||||
parts.append('【输出要求】\n' + control)
|
||||
# 变量说明拼在最后:它和"输出要求"一样是这一轮的约束,
|
||||
# 但放在更后面,模型对"最后看到的东西"注意力更高
|
||||
var_text = meeting.variables_prompt(
|
||||
variables, node.get('readVars'), node.get('writeVars'))
|
||||
if var_text:
|
||||
parts.append(var_text)
|
||||
merged_agent = {**(agent or {}), 'systemPrompt': '\n\n'.join(parts)}
|
||||
|
||||
# 上游内容作为这一轮的用户消息;没有上游就给个占位,免得空消息报错
|
||||
@@ -988,17 +1011,67 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
emit=relay,
|
||||
should_stop=sse.should_stop,
|
||||
)
|
||||
return (result or {}).get('content') or ''
|
||||
raw = (result or {}).get('content') or ''
|
||||
# ★ 这里**不**处理 [[SET]]:那是节点语义,归引擎管(见 meeting.run_meeting)。
|
||||
# 放在这一层的话,引擎自己的测试压根覆盖不到,换个调用方也会忘 ——
|
||||
# 真发生过:引擎测试全绿,一上 HTTP 就漏出 [[SET]] 那行。
|
||||
return raw
|
||||
|
||||
try:
|
||||
# ★ 一边转发一边攒一份运行记录:结果界面要能按"哪个节点、第几轮"
|
||||
# 回看,而不是只有一个最终答案。循环跑很多轮时这份记录尤其有用。
|
||||
steps = []
|
||||
final = {'output': '', 'aborted': False, 'error': ''}
|
||||
|
||||
def record(event):
|
||||
sse.send(event)
|
||||
kind = event.get('type')
|
||||
if kind == 'node_done':
|
||||
steps.append({
|
||||
'nodeId': event.get('nodeId'),
|
||||
'nodeType': event.get('nodeType'),
|
||||
'title': event.get('title'),
|
||||
'run': event.get('run') or 1,
|
||||
'output': event.get('output') or '',
|
||||
'note': event.get('note') or '',
|
||||
})
|
||||
elif kind == 'node_error':
|
||||
steps.append({
|
||||
'nodeId': event.get('nodeId'),
|
||||
'nodeType': event.get('nodeType'),
|
||||
'title': event.get('title'),
|
||||
'run': event.get('run') or 1,
|
||||
'output': '',
|
||||
'error': event.get('error') or '',
|
||||
})
|
||||
elif kind == 'meeting_done':
|
||||
final['output'] = event.get('output') or ''
|
||||
final['aborted'] = bool(event.get('aborted'))
|
||||
final['error'] = event.get('error') or ''
|
||||
|
||||
meeting.run_meeting(
|
||||
meeting=item,
|
||||
settings=settings,
|
||||
user_input=user_input,
|
||||
emit=sse.send,
|
||||
emit=record,
|
||||
run_agent_fn=run_agent_fn,
|
||||
should_stop=sse.should_stop,
|
||||
)
|
||||
|
||||
# 存历史。节点标题在事件里可能没有(引擎只在 node_start 里给),
|
||||
# 这里从会议定义里补齐,免得历史界面上全是"未命名"。
|
||||
titles = {n['id']: n.get('title') for n in (item.get('nodes') or [])}
|
||||
for step in steps:
|
||||
if not step.get('title'):
|
||||
step['title'] = titles.get(step.get('nodeId')) or ''
|
||||
meeting.append_run(meeting_id, {
|
||||
'at': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
|
||||
'input': user_input,
|
||||
'steps': steps,
|
||||
'output': final['output'],
|
||||
'aborted': final['aborted'],
|
||||
'error': final['error'],
|
||||
})
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# 引擎自己炸了也要让界面知道,不能一声不响地断掉
|
||||
sse.send({'type': 'meeting_done', 'output': '', 'error': f'{type(exc).__name__}: {exc}'})
|
||||
|
||||
@@ -32,6 +32,7 @@ end 最终输出:汇总上游内容作为结果。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
@@ -41,7 +42,7 @@ import paths
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
NODE_TYPES = ('start', 'agent', 'judge', 'end')
|
||||
NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar')
|
||||
|
||||
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
|
||||
JUDGE_KINDS = (
|
||||
@@ -54,6 +55,73 @@ JUDGE_KINDS = (
|
||||
('ai', '让模型判断'),
|
||||
)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 变量
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 为什么需要:会议是"多轮、多节点"的,前面的结论要带到后面去。
|
||||
# 只靠连线传的话,到分叉再汇合就乱了(一个节点只能拿到直接上游)。
|
||||
# 变量是**全局的**,任何节点都能读,所以要"记住一件事供后面用"时用它。
|
||||
#
|
||||
# 用 [[SET 名字=值]] 这种显式标记让智能体写变量,而不是让它自由发挥:
|
||||
# 自由发挥没法可靠解析,最后就是"有时能改有时改不了"这种最难查的问题。
|
||||
|
||||
# 整行匹配。^...$ 保证不会误伤正文里出现的方括号。
|
||||
SET_RE = re.compile(r'^[ \t]*\[\[SET[ \t]+([^\]=\r\n]+?)[ \t]*=[ \t]*(.*?)\]\][ \t]*$', re.MULTILINE)
|
||||
|
||||
|
||||
def apply_sets(text: str, variables: dict, allowed) -> tuple:
|
||||
"""
|
||||
从模型输出里抽出 [[SET 名字=值]],写进变量表,并把这些行从正文里去掉。
|
||||
|
||||
返回 (剥干净的正文, {改动的变量})。
|
||||
|
||||
allowed 是"这个节点有权限写哪些变量"。没授权的**原样留在正文里**,
|
||||
而不是悄悄丢掉 —— 用户能看见"它想写但没权限",比默默失败好查得多。
|
||||
"""
|
||||
changed = {}
|
||||
allow = set(allowed or [])
|
||||
|
||||
def repl(match):
|
||||
name = match.group(1).strip()
|
||||
value = match.group(2).strip()
|
||||
if allow and name not in allow:
|
||||
return match.group(0)
|
||||
variables[name] = value
|
||||
changed[name] = value
|
||||
return ''
|
||||
|
||||
cleaned = SET_RE.sub(repl, text or '')
|
||||
# 去掉被 SET 行留出来的多余空行
|
||||
cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip()
|
||||
return cleaned, changed
|
||||
|
||||
|
||||
def variables_prompt(variables: dict, read_names, write_names) -> str:
|
||||
"""
|
||||
给智能体拼一段"你能看到哪些变量、能改哪些"的说明。
|
||||
|
||||
只读的不列写法说明,只写的不列当前值 —— 权限边界写清楚,
|
||||
模型才不会去猜"我能不能改这个"。
|
||||
"""
|
||||
reads = [n for n in (read_names or []) if n]
|
||||
writes = [n for n in (write_names or []) if n]
|
||||
if not reads and not writes:
|
||||
return ''
|
||||
parts = []
|
||||
if reads:
|
||||
lines = [f'- {n} = {variables.get(n, "(还没设过)")}' for n in reads]
|
||||
parts.append('【你可以看到的变量】\n' + '\n'.join(lines))
|
||||
if writes:
|
||||
parts.append(
|
||||
'【你可以修改的变量】' + '、'.join(writes) + '\n'
|
||||
'要修改变量时,在回答的**最后**单独起一行写:\n'
|
||||
'[[SET 变量名=新值]]\n'
|
||||
'这一行不会显示给用户,会被系统取走并写入变量。'
|
||||
'不需要修改就不要写这一行。'
|
||||
)
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
|
||||
def _ts36() -> str:
|
||||
num = int(datetime.now(timezone.utc).timestamp() * 1000)
|
||||
@@ -189,6 +257,69 @@ def delete_meeting(meeting_id: str) -> bool:
|
||||
if len(left) == len(items):
|
||||
return False
|
||||
_write(left)
|
||||
# 会议删了,它的运行历史也一并清掉 —— 留着就是永远读不到的垃圾
|
||||
runs = _read_runs()
|
||||
runs.pop(meeting_id, None)
|
||||
_write_runs(runs)
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 运行历史
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 每场会议最多留多少条历史。会议可能是无限循环、一次跑几十轮,
|
||||
# 不设上限的话这个文件会一直涨。
|
||||
RUN_HISTORY_LIMIT = 20
|
||||
|
||||
|
||||
def _runs_file() -> str:
|
||||
return os.path.join(paths.get().data_dir, 'meeting-runs.json')
|
||||
|
||||
|
||||
def _read_runs() -> dict:
|
||||
file_path = _runs_file()
|
||||
if not os.path.isfile(file_path):
|
||||
return {}
|
||||
try:
|
||||
with open(file_path, encoding='utf-8') as fh:
|
||||
data = json.load(fh)
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f'[meeting] meeting-runs.json 读不了:{exc}', file=sys.stderr)
|
||||
return {}
|
||||
items = data.get('runs') if isinstance(data, dict) else None
|
||||
return items if isinstance(items, dict) else {}
|
||||
|
||||
|
||||
def _write_runs(runs: dict) -> None:
|
||||
os.makedirs(paths.get().data_dir, exist_ok=True)
|
||||
with open(_runs_file(), 'w', encoding='utf-8') as fh:
|
||||
json.dump({'runs': runs}, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
def list_runs(meeting_id: str) -> list:
|
||||
"""某场会议的历史运行记录,**最新的在前**"""
|
||||
return list(reversed(_read_runs().get(meeting_id) or []))
|
||||
|
||||
|
||||
def append_run(meeting_id: str, record: dict) -> dict:
|
||||
with _lock:
|
||||
runs = _read_runs()
|
||||
items = runs.get(meeting_id) or []
|
||||
items.append(record)
|
||||
# 只留最近 RUN_HISTORY_LIMIT 条
|
||||
runs[meeting_id] = items[-RUN_HISTORY_LIMIT:]
|
||||
_write_runs(runs)
|
||||
return record
|
||||
|
||||
|
||||
def clear_runs(meeting_id: str) -> bool:
|
||||
with _lock:
|
||||
runs = _read_runs()
|
||||
if meeting_id not in runs:
|
||||
return False
|
||||
runs.pop(meeting_id, None)
|
||||
_write_runs(runs)
|
||||
return True
|
||||
|
||||
|
||||
@@ -336,6 +467,9 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
runs = {}
|
||||
steps = 0
|
||||
|
||||
# 变量表:整场会议共享。var / readvar 节点和授权过的智能体都能读写它。
|
||||
variables = {}
|
||||
|
||||
def limit_of(node: dict) -> int:
|
||||
"""
|
||||
节点的执行次数上限。**0 表示无限**。
|
||||
@@ -388,8 +522,9 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
run_index = runs.get(node_id, 0) + 1
|
||||
runs[node_id] = run_index
|
||||
node_type = node['type']
|
||||
title = node.get('title') or {'start': '初始输入', 'agent': '智能体',
|
||||
'judge': '判断', 'end': '最终输出'}.get(node_type, node_type)
|
||||
title = node.get('title') or {'start': '初始输入', 'agent': '智能体', 'judge': '判断',
|
||||
'end': '最终输出', 'var': '写变量',
|
||||
'readvar': '读变量'}.get(node_type, node_type)
|
||||
emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type,
|
||||
'title': title, 'run': run_index, 'maxRuns': limit_of(node)})
|
||||
|
||||
@@ -406,15 +541,49 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str,
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
|
||||
elif node_type == 'agent':
|
||||
out = run_agent_fn(node, incoming, settings, emit, node_id)
|
||||
outputs[node_id] = out
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': out, 'run': run_index})
|
||||
raw = run_agent_fn(node, incoming, settings, emit, node_id, variables)
|
||||
# ★ 把 [[SET 名字=值]] 抽出来写进变量,正文里不留那些行。
|
||||
#
|
||||
# 这件事放在**引擎**里而不是"调用引擎的那一层":
|
||||
# 它是节点语义的一部分("这个智能体能写哪些变量"是节点配置),
|
||||
# 放在外面的话 —— 换个调用方就忘了做,而且引擎自己的测试
|
||||
# 压根覆盖不到(真发生过:引擎测试全绿,一上 HTTP 就漏出 [[SET]])。
|
||||
cleaned, changed = apply_sets(raw, variables, node.get('writeVars'))
|
||||
outputs[node_id] = cleaned
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': cleaned, 'run': run_index})
|
||||
if changed:
|
||||
# 改了哪些变量要让用户看见,不然就是"背地里改了我的东西"
|
||||
emit({'type': 'node_vars', 'nodeId': node_id, 'vars': changed,
|
||||
'note': '、'.join(f'{k} = {str(v)[:30]}' for k, v in changed.items())})
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
|
||||
elif node_type == 'var':
|
||||
# 写变量节点:有上游就用上游内容当值,否则用节点里写死的
|
||||
name = str(node.get('varName') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('变量节点没填变量名')
|
||||
value = (node.get('varValue') or '').strip() or incoming
|
||||
variables[name] = value
|
||||
outputs[node_id] = value
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': value, 'run': run_index,
|
||||
'note': f'变量 {name} = {value[:40]}'})
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
|
||||
elif node_type == 'readvar':
|
||||
# 读变量节点:把变量的当前值当成输出往下传
|
||||
name = str(node.get('varName') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('读变量节点没填变量名')
|
||||
value = variables.get(name, '')
|
||||
outputs[node_id] = value
|
||||
emit({'type': 'node_done', 'nodeId': node_id, 'output': value, 'run': run_index,
|
||||
'note': f'读到 {name}' + ('' if value else '(还没设过,是空的)')})
|
||||
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
|
||||
|
||||
elif node_type == 'judge':
|
||||
kind = str(node.get('judgeKind') or 'not_empty')
|
||||
if kind == 'ai':
|
||||
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id)
|
||||
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id, variables)
|
||||
passed = 'YES' in verdict.upper()[:40] or '是' in verdict[:20]
|
||||
else:
|
||||
passed = _judge_rule(node, incoming)
|
||||
|
||||
Reference in New Issue
Block a user