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 8fba5fc..36c6e2b 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 @@ -4,6 +4,8 @@ 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 @@ -41,6 +43,7 @@ import androidx.compose.runtime.getValue 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 @@ -256,6 +259,7 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - 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() } // 运行时的节点状态:正在跑 / 跑完 / 出错 @@ -300,8 +304,12 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - overflow = TextOverflow.Ellipsis, ) Text( - if (linkingFrom != null) "点目标节点完成连线(点空白取消)" - else if (dirty) "未保存" else "${meeting.nodes.size} 节点 · ${meeting.edges.size} 连线", + when { + linkingFrom != null -> "点目标节点完成连线(点空白取消)" + dirty -> "未保存" + // 手势规则要写出来:两指平移不是所有人一上来就知道的 + else -> "${meeting.nodes.size} 节点 · ${meeting.edges.size} 连线 · 一指拖节点 / 两指移画布" + }, fontSize = 11.sp, color = if (linkingFrom != null) Doubao.Blue else doubaoTextSecondary(), ) @@ -361,21 +369,103 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - // 画布 // - // ★ 用手势平移(panX/panY + graphicsLayer),**不用 horizontalScroll + - // verticalScroll** —— 那两个滚动修饰符叠在同一个 Modifier 链上测量会互相 - // 打架,实测画布根本滚不动(节点被推到屏幕外就再也看不到,最终输出节点 - // 直接找不着)。平移只有一个状态、行为完全可控,也不和节点的拖拽抢手势: - // 手指落在节点上时子节点的拖拽先消费事件,落在空白处才是平移。 + // ★ 手势分工(用户定的,比"谁抢到算谁的"清楚得多): + // **一指** → 拖手指底下那个节点;落在空白处则什么都不做 + // **两指** → 平移画布(按在哪都行,包括按在节点上) + // + // 为什么这样分:一指拖节点是手机上的直觉;而"想挪画布"和"想挪节点" + // 是两种完全不同的意图,用**手指数**区分最干净 —— 不需要谁去抢, + // 也不会再出现"想拖节点结果整张图跑了"(之前就是这么坏的)。 + // 两指平移也是各家地图/画布应用的通用做法,用户不用学。 + // + // 点击(开配置、点「连线」)仍由节点自己的 clickable 处理: + // 那个只在"没怎么移动"时触发,和这里的拖动不冲突。 + val nodesSnapshot = rememberUpdatedState(meeting.nodes) + Box( Modifier .weight(1f) .fillMaxWidth() .pointerInput(Unit) { - detectDragGestures { change, drag -> - change.consume() - val next = clampPan(panX + drag.x, panY + drag.y, size.width.toFloat(), size.height.toFloat()) - panX = next.first - panY = next.second + val nodeW = NODE_W.dp.toPx() + val nodeH = NODE_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 + } + } + + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + var last = down.position + var moved = false + var accumulated = 0f + // 被拖节点的当前位置。必须自己累加 —— + // 直接用 hit.x + delta 的话每一帧都在拿"按下那一刻的坐标" + // 加一个小增量,节点会原地不动或者瞬移回起点。 + var hit = hitTest(down.position, Offset(panX, panY)) + var dragX = hit?.x ?: 0f + var dragY = hit?.y ?: 0f + // 平移用:上一次的质心和手指数。手指数一变就重置, + // 不然第二根手指按下的瞬间质心会跳一大截,画面"唰"地飞走。 + var lastCentroid: Offset? = null + 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 prev = lastCentroid + if (lastCount == pressed.size && prev != null) { + val next = clampPan( + panX + (centroid.x - prev.x), + panY + (centroid.y - prev.y), + size.width.toFloat(), size.height.toFloat(), + ) + panX = next.first + panY = next.second + } + lastCentroid = centroid + lastCount = pressed.size + pressed.forEach { it.consume() } + continue + } + + // 一指 + lastCentroid = null + 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) { + dragX = (dragX + delta.x).coerceIn(0f, CANVAS_W - NODE_W) + dragY = (dragY + delta.y).coerceIn(0f, CANVAS_H - NODE_H) + updateNode(hit.copy(x = dragX, y = dragY)) + } + // 空白处单指拖动:什么都不做(平移要两指) + } + last = change.position + } + if (moved && hit != null) persist() } }, ) { @@ -499,8 +589,21 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - maxLines = 2, ) Spacer(Modifier.width(8.dp)) - PrimaryButton(if (running) "运行中…" else "运行") { - if (!running) { + // 跑起来就变成「停止」;空着的时候给个「结果」看整场输出。 + // + // 为什么停止按钮要紧:一场会议可能跑好几分钟(每个智能体都是一次 + // 完整模型调用),发现配错了却停不下来是最让人抓狂的。 + 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 = "" @@ -509,32 +612,34 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - vm.runMeeting( meetingId = meeting.id, input = runInput, - onEvent = { ev -> - when (ev.type) { - "node_start" -> liveStatus[ev.nodeId] = "running" - "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 - } - "node_error" -> { - liveStatus[ev.nodeId] = "error" - nodeOutputs[ev.nodeId] = "出错:${ev.error}" - } - "meeting_done" -> { - running = false - if (ev.error.isNotBlank()) runError = ev.error - } - } - }, + onEvent = { ev -> applyMeetingEvent(ev, liveStatus, nodeOutputs) { 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), + ) + } } } + if (showResult) { + MeetingResultDialog( + meeting = meeting, + outputs = nodeOutputs, + onDismiss = { showResult = false }, + ) + } + configTarget?.let { target -> NodeConfigDialog( node = target, @@ -610,6 +715,132 @@ private fun clampPan(x: Float, y: Float, viewW: Float, viewH: Float): Pair, + nodeOutputs: MutableMap, + onDone: (String) -> Unit, +) { + when (ev.type) { + "node_start" -> liveStatus[ev.nodeId] = "running" + "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 + } + "node_error" -> { + liveStatus[ev.nodeId] = "error" + nodeOutputs[ev.nodeId] = "出错:${ev.error}" + } + "meeting_done" -> onDone(ev.error) + } +} + +/** + * 运行结果单独一屏。 + * + * 为什么要有:节点卡片就那么点大,长回答在卡片上只能看到两行 —— + * 想完整读一遍结果就得靠这个。**按节点在文中的顺序(节点的 x 坐标)排**, + * 而不是按事件到达顺序:用户脑子里的顺序是图上从左到右,不是事件流。 + */ +@Composable +private fun MeetingResultDialog( + meeting: Meeting, + outputs: Map, + onDismiss: () -> 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 })) + } + 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()) + } + + if (finalText.isNotBlank()) { + Text("最终输出", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue) + Spacer(Modifier.height(4.dp)) + 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), + ) + } + Spacer(Modifier.height(10.dp)) + } + + ordered.forEach { node -> + Text( + node.title.ifBlank { + when (node.type) { + "start" -> "初始输入" + "judge" -> "判断" + else -> "智能体" + } + }, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + ) + Spacer(Modifier.height(3.dp)) + Text( + outputs[node.id].orEmpty(), + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 17.sp, + ) + Spacer(Modifier.height(10.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") + } + } + } + clipboard.setText(androidx.compose.ui.text.AnnotatedString(all)) + android.widget.Toast.makeText(context, "已复制", android.widget.Toast.LENGTH_SHORT).show() + }) { Text("复制") } + TextButton(onClick = onDismiss) { Text("关闭") } + } + }, + ) +} + /* ====================================================================== */ /* 节点卡片 */ /* ====================================================================== */ @@ -649,15 +880,9 @@ private fun NodeCard( }, shape = RoundedCornerShape(12.dp), ) - // 拖动:节点位置就是内核里的 x/y,拖完直接存 - .pointerInput(node.id) { - detectDragGestures( - onDragEnd = { onDragEnd() }, - ) { change, drag -> - change.consume() - onDrag(drag.x, drag.y) - } - } + // 拖动节点/平移画布由**父级**统一处理(见上面画布那段的长注释)。 + // 这里只留点击:开配置、点「连线」按钮。clickable 只在几乎没移动时 + // 才触发,和父级的拖动不冲突。 .clickable(onClick = onClick) .padding(8.dp), ) { @@ -702,17 +927,29 @@ private fun NodeCard( lineHeight = 13.sp, ) Spacer(Modifier.weight(1f)) - // 连线按钮:两步点选的第一步 - 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), - ) + 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 (node.maxRuns != 1) { + Spacer(Modifier.weight(1f)) + // 会重复的节点标出来:不然图上看着和普通节点一样, + // 跑起来发现它转了三轮会很意外 + Text( + if (node.maxRuns == 0) "∞" else "×${node.maxRuns}", + fontSize = 10.sp, + color = if (node.maxRuns == 0) Color(0xFFF29900) else doubaoTextSecondary(), + ) + } } } } @@ -723,10 +960,17 @@ private fun NodeCard( /** 主按钮(和智能体页那个「新建智能体」同款) */ @Composable -private fun PrimaryButton(label: String, onClick: () -> Unit) { +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) @@ -798,7 +1042,6 @@ private fun NodeConfigDialog( textStyle = TextStyle(fontSize = 13.sp), ) } - "agent" -> { Spacer(Modifier.height(10.dp)) FormLabel("智能体") @@ -873,6 +1116,34 @@ private fun NodeConfigDialog( ) } } + + /* -------- 执行次数:所有节点类型都适用 -------- */ + 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("保存") } }, diff --git a/android/kernel/meeting.py b/android/kernel/meeting.py index d496548..814b92f 100644 --- a/android/kernel/meeting.py +++ b/android/kernel/meeting.py @@ -204,12 +204,20 @@ def _sanitize_nodes(nodes: list) -> list: if not nid or nid in seen or ntype not in NODE_TYPES: continue seen.add(nid) + try: + max_runs = int(n.get('maxRuns')) if n.get('maxRuns') is not None else 1 + except (TypeError, ValueError): + max_runs = 1 out.append({ **n, 'id': nid, 'type': ntype, 'x': float(n.get('x') or 0), 'y': float(n.get('y') or 0), + # 夹在 0~20:**0 = 无限循环**(两个智能体互相点评那种用法), + # 1~20 是有限次。负数或大于 20 的值都不认,退回 1 —— + # 不然用户手改文件写成 99999 会一直烧额度。 + 'maxRuns': 0 if max_runs <= 0 else min(max_runs, 20), }) return out @@ -317,12 +325,52 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str, return {'output': '', 'error': '这张图没有入口节点'} queue = [n['id'] for n in starts] - # 每个节点最多处理一次;总步数再兜一个上限,防止用户画出很长的环 - visited = set() + + # ★ 每个节点跑了几次(不是"跑没跑过")。 + # + # 用户要的是"n1 → n2 → n1 只有一轮,但**能重复**": + # 默认每节点 1 次(= 不重复,和以前一样),把节点上的「最多执行次数」 + # 调大就能来回跑 —— 比如两个节点都设 3,就是 n1/n2 各跑三轮。 + # + # 以前用的是 visited 集合(跑过就不再跑),环永远只转一圈,没法重复。 + runs = {} steps = 0 - max_steps = max(20, len(nodes) * 4) + + def limit_of(node: dict) -> int: + """ + 节点的执行次数上限。**0 表示无限**。 + + 为什么要支持无限:两个智能体互相点评(甲评乙、乙再评甲)是常见用法, + 用户希望一直怼下去,自己觉得够了再按停止。 + + 为什么敢开无限:引擎每一轮都会检查 should_stop(客户端断开或用户点了停止), + 所以"无限"实际是"跑到你喊停为止",不是真的停不下来。 + 另外还兜了一个很大的硬上限 MAX_STEPS_HARD,防止用户忘了停、 + 或者客户端异常断开时把额度烧光。 + """ + raw = node.get('maxRuns') + try: + value = int(raw) if raw is not None else 1 + except (TypeError, ValueError): + value = 1 + return 0 if value <= 0 else min(value, 20) + + budget = sum((limit_of(n) or 200) for n in nodes) + # 硬上限:无限循环时预算按每节点 200 次估,再乘 2 留余量。 + # 这不是"限制用户",是**防止客户端异常断开时把额度烧光** —— + # 正常用停止按钮就能收尾,根本碰不到这个数。 + max_steps = max(20, budget * 2 + len(nodes)) + final_output = '' + def can_run(node_id: str) -> bool: + node = by_id.get(node_id) + if not node: + return False + limit = limit_of(node) + # 0 = 无限:永远还能再跑一次 + return limit == 0 or runs.get(node_id, 0) < limit + while queue and steps < max_steps: if should_stop and should_stop(): emit({'type': 'meeting_done', 'output': final_output, 'aborted': True}) @@ -330,33 +378,37 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str, node_id = queue.pop(0) steps += 1 - if node_id in visited: + if not can_run(node_id): continue - visited.add(node_id) node = by_id.get(node_id) if not node: continue + 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) - emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type, 'title': title}) + emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type, + 'title': title, 'run': run_index, 'maxRuns': limit_of(node)}) incoming = _collect_input(node_id, edges, outputs) try: if node_type == 'start': - text = (node.get('text') or '').strip() or (user_input or '') + # 第二轮开始,"初始输入"要把**自己上一轮的输出**当输入, + # 否则循环回来的内容会被起点覆盖掉,重复就没意义了 + text = incoming or (node.get('text') or '').strip() or (user_input or '') outputs[node_id] = text emit({'type': 'node_done', 'nodeId': node_id, 'output': text, - 'note': '用的初始输入'}) + 'run': run_index, 'note': '用的初始输入'}) 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}) + emit({'type': 'node_done', 'nodeId': node_id, 'output': out, 'run': run_index}) next_ids = [e['to'] for e in _outgoing(edges, node_id)] elif node_type == 'judge': @@ -373,6 +425,7 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str, outputs[node_id] = incoming emit({'type': 'node_done', 'nodeId': node_id, 'output': incoming, + 'run': run_index, 'verdict': passed, 'branch': 'true' if passed else 'false', 'note': f'判断结果:{passed}'}) @@ -389,7 +442,7 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str, elif node_type == 'end': outputs[node_id] = (node.get('text') or '').strip() or incoming final_output = outputs[node_id] - emit({'type': 'node_done', 'nodeId': node_id, 'output': final_output}) + emit({'type': 'node_done', 'nodeId': node_id, 'output': final_output, 'run': run_index}) next_ids = [] else: @@ -398,12 +451,15 @@ def run_meeting(*, meeting: dict, settings: dict, user_input: str, except Exception as exc: # noqa: BLE001 # 单个节点出错不该让整场会议停摆:记下来,继续跑下游 - emit({'type': 'node_error', 'nodeId': node_id, 'error': str(exc)}) + emit({'type': 'node_error', 'nodeId': node_id, 'error': str(exc), 'run': run_index}) outputs[node_id] = '' next_ids = [e['to'] for e in _outgoing(edges, node_id)] + # ★ 只有"还能再跑"的节点才重新入队。 + # 这就是"重复"的开关:maxRuns=1(默认)时,跑过的节点不会再进来, + # 环也只转一圈;把它调大,环就会来回转到次数用完为止。 for nid in next_ids: - if nid not in visited: + if can_run(nid): queue.append(nid) emit({'type': 'meeting_done', 'output': final_output}) diff --git a/scripts/device-meeting-drag.mjs b/scripts/device-meeting-drag.mjs new file mode 100644 index 0000000..0376291 --- /dev/null +++ b/scripts/device-meeting-drag.mjs @@ -0,0 +1,84 @@ +/** + * 验证"一指拖节点 / 两指平移画布"。 + * + * ★ 每次跑之前先**删掉所有旧会议、新建一个**。 + * 原因:旧会议的节点坐标是历史遗留(可能被拖到画布角落、跑出屏幕), + * 测试点就会落在空白处 —— 上一轮我就是这么得出"节点拖不动"的错误结论的。 + * 新建的会议用的是当前默认坐标,位置可预测。 + * + * adb 模拟不了真两指,所以两指那项只做说明性检查(代码里已按手指数分支)。 + * + * 用法: node scripts/device-meeting-drag.mjs + */ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const SERIAL = process.argv[2] || 'emulator-5556'; +const ADB = process.env.ADB || 'C:\\Android\\Sdk\\platform-tools\\adb.exe'; +const OUT = path.join(os.tmpdir(), 'meeting-shots'); +fs.mkdirSync(OUT, { recursive: true }); + +const sh = (...a) => spawnSync(ADB, ['-s', SERIAL, ...a], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +async function shot(n) { + sh('shell', 'screencap', '-p', '/sdcard/_s.png'); + const dst = path.join(OUT, `${n}.png`); + sh('pull', '/sdcard/_s.png', dst); + return dst; +} +/** 去掉状态栏(时钟会变),只比较下面的内容区,避免"时钟变了"被误判成"画面变了" */ +const bodyHash = (p) => { + const b = fs.readFileSync(p); + // PNG 没法简单裁,就按字节采样并跳过前 8KB(状态栏在图像顶部, + // PNG 是逐行压缩的,跳过开头基本能避开它) + let h = 0; + for (let i = 8192; i < b.length; i += 53) h = (h * 31 + b[i]) >>> 0; + return h.toString(16); +}; +async function tap(x, y, w = 1400) { sh('shell', 'input', 'tap', String(x), String(y)); await sleep(w); } +const api = (p, opt) => sh('shell', `curl -s --max-time 10 ${opt || ''} http://127.0.0.1:5199${p}`).stdout || ''; + +console.log('清掉旧会议,建一个新的(坐标可预测)…'); +const list = api('/api/meetings'); +try { + for (const m of JSON.parse(list).meetings || []) { + api(`/api/meetings/${m.id}`, `-X DELETE`); + } +} catch { /* 没有就没有 */ } +api('/api/meetings', `-X POST -H 'Content-Type: application/json' -d '{"name":"DragTest"}'`); +await sleep(800); + +console.log('导航到会议编辑器…'); +sh('shell', 'input', 'keyevent', 'KEYCODE_WAKEUP'); +sh('shell', 'svc', 'power', 'stayon', 'true'); +sh('shell', 'am', 'start', '-n', 'com.doubao.lynxclone/.MainActivity'); +await sleep(6000); +await tap(45, 105); // 抽屉 +await tap(250, 561, 2500); // 会议模式 +await tap(300, 300, 3500); // 打开会议 + +const before = await shot('40-before'); +console.log(' 拖动前已截图'); + +// 新默认:n_start 在 (12,120)dp。密度 2.0、画布区从屏幕 y≈150px 开始。 +// 所以节点大致在屏幕 (24..256, 390..566),取中心 (140, 470)。 +console.log('① 一指拖「初始输入」节点'); +sh('shell', 'input', 'swipe', '140', '470', '420', '700', '900'); +await sleep(2500); +const afterDrag = await shot('41-after-node-drag'); + +console.log('② 一指拖空白处(应什么都不发生)'); +sh('shell', 'input', 'swipe', '600', '250', '380', '420', '900'); +await sleep(2000); +const afterEmpty = await shot('42-after-empty-drag'); + +const h0 = bodyHash(before); +const h1 = bodyHash(afterDrag); +const h2 = bodyHash(afterEmpty); +console.log(''); +console.log(` 拖动前 : ${h0}`); +console.log(` 拖节点后 : ${h1} ${h0 === h1 ? '❌ 没变 → 节点没拖动' : '✅ 变了 → 节点动了'}`); +console.log(` 拖空白后 : ${h2} ${h1 === h2 ? '✅ 没变 → 空白处不动作(正确)' : '❌ 变了 → 空白处也动了'}`); +console.log('截图在', OUT); diff --git a/scripts/verify-meeting.mjs b/scripts/verify-meeting.mjs index 34c8caa..de55f0a 100644 --- a/scripts/verify-meeting.mjs +++ b/scripts/verify-meeting.mjs @@ -104,7 +104,7 @@ const cases = [ wantHas: ['甲 收到[起点]', '乙 收到[起点]'], }, { - name: '环不会把引擎转死(每个节点最多跑一次)', + name: '环不会把引擎转死(默认每节点只跑一次)', meeting: { nodes: [ { id: 's', type: 'start', text: 'x' }, @@ -119,6 +119,76 @@ const cases = [ }, wantRunCount: 2, // 甲、乙各一次,不会无限循环 }, + { + name: 'n1 ↔ n2 环:maxRuns=1 只走一轮', + meeting: { + nodes: [ + { id: 's', type: 'start', text: '起点' }, + { id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 1 }, + { id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 1 }, + ], + edges: [ + { from: 's', to: 'n1' }, + { from: 'n1', to: 'n2' }, + { from: 'n2', to: 'n1' }, + ], + }, + wantEachRuns: { n1: 1, n2: 1 }, + }, + { + name: 'n1 ↔ n2 环:maxRuns=3 能来回跑三轮', + meeting: { + nodes: [ + { id: 's', type: 'start', text: '起点' }, + { id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 3 }, + { id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 3 }, + ], + edges: [ + { from: 's', to: 'n1' }, + { from: 'n1', to: 'n2' }, + { from: 'n2', to: 'n1' }, + ], + }, + wantEachRuns: { n1: 3, n2: 3 }, + }, + { + name: 'n1 ↔ n2 环:maxRuns=0 无限循环(靠 shouldStop 收尾)', + meeting: { + nodes: [ + { id: 's', type: 'start', text: '起点' }, + { id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 0 }, + { id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 0 }, + ], + edges: [ + { from: 's', to: 'n1' }, + { from: 'n1', to: 'n2' }, + { from: 'n2', to: 'n1' }, + ], + }, + // 提示跑 6 次之后停下来,模拟用户按停止 + stopAfter: 6, + wantEachRuns: { n1: 3, n2: 3 }, + wantAborted: true, + }, + { + name: '重复时后一轮能拿到前一轮的输出', + meeting: { + nodes: [ + { id: 's', type: 'start', text: '起点' }, + { id: 'n1', type: 'agent', title: '甲', agentId: '', maxRuns: 2 }, + { id: 'n2', type: 'agent', title: '乙', agentId: '', maxRuns: 2 }, + ], + edges: [ + { from: 's', to: 'n1' }, + { from: 'n1', to: 'n2' }, + { from: 'n2', to: 'n1' }, + ], + }, + // 第二轮甲收到的必须**包含乙第一轮的产出**,不能是空的 —— + // 否则"重复"就只是把同一件事做两遍,没有意义。 + // 注意 n1 现在有两条入边(s 和 n2),按设计会拼接,所以还带着起点那句。 + wantSecondRoundHas: '乙 收到[甲 收到[起点]]', + }, { name: '单个节点出错不影响下游继续跑', meeting: { @@ -153,8 +223,13 @@ async function runOne(impl, cs) { const order = []; const events = []; let runCount = 0; + // 每个节点跑了几次 / 每次收到的输入(验"重复"用) + const perNode = {}; + const inputsByNode = {}; const agentFn = async (node, input, settings, emit, nodeId) => { runCount += 1; + perNode[nodeId] = (perNode[nodeId] || 0) + 1; + (inputsByNode[nodeId] = inputsByNode[nodeId] || []).push(input); if (node.title === '会炸的') throw new Error('故意炸一下'); return impl === 'node' ? echoAgent(node, input) @@ -169,8 +244,13 @@ async function runOne(impl, cs) { if (e.type === 'node_start') order.push(e.nodeId); }, runAgentFn: agentFn, + // 无限循环的用例靠这个模拟"用户按了停止" + shouldStop: cs.stopAfter ? () => runCount >= cs.stopAfter : undefined, }); - return { order, events, runCount, output: out.output || '', error: out.error || '' }; + return { + order, events, runCount, perNode, inputsByNode, + output: out.output || '', error: out.error || '', aborted: !!out.aborted, + }; } /* --------------------------------------------- Python 侧:起内核跑同一组 */ @@ -187,30 +267,41 @@ for cs in cases: order = [] events = [] state = {'runs': 0} + per_node = {} + inputs_by_node = {} def emit(e): events.append(e) if e.get('type') == 'node_start': order.append(e.get('nodeId')) def agent_fn(node, incoming, settings, emit_fn, node_id): state['runs'] += 1 + per_node[node_id] = per_node.get(node_id, 0) + 1 + inputs_by_node.setdefault(node_id, []).append(incoming) if node.get('title') == '会炸的': raise RuntimeError('故意炸一下') title = node.get('title') or node.get('id') return f"{title} 收到[{incoming}]" + stop_after = cs.get('stopAfter') + should_stop = (lambda: state['runs'] >= stop_after) if stop_after else None r = M.run_meeting(meeting=cs['meeting'], settings={}, user_input='', - emit=emit, run_agent_fn=agent_fn) + emit=emit, run_agent_fn=agent_fn, should_stop=should_stop) out.append({'order': order, 'events': events, 'runCount': state['runs'], - 'output': r.get('output') or '', 'error': r.get('error') or ''}) + 'perNode': per_node, 'inputsByNode': inputs_by_node, + 'output': r.get('output') or '', 'error': r.get('error') or '', + 'aborted': bool(r.get('aborted'))}) print(json.dumps(out, ensure_ascii=False)) `; const res = spawnSync(PY, ['-c', script], { - input: JSON.stringify(cases.map((c) => ({ meeting: c.meeting }))), + input: JSON.stringify(cases.map((c) => ({ + meeting: c.meeting, + stopAfter: c.stopAfter || null, + }))), encoding: 'utf8', - maxBuffer: 16 * 1024 * 1024, + maxBuffer: 32 * 1024 * 1024, env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, }); if (res.status !== 0) { - console.log(' Python 侧执行失败:', (res.stderr || '').slice(0, 500)); + console.log(' Python 侧执行失败:', (res.stderr || '').slice(0, 600)); return null; } try { @@ -251,6 +342,21 @@ for (const cs of cases) { if (cs.wantRunCount !== undefined) { check(' 环没有把引擎转死', nodeRes.runCount === cs.wantRunCount, `跑了 ${nodeRes.runCount} 次`); } + if (cs.wantEachRuns) { + const got = JSON.stringify(nodeRes.perNode); + const want = JSON.stringify(cs.wantEachRuns); + check(' 每个节点的执行次数正确', got === want, got); + } + if (cs.wantSecondRoundHas !== undefined) { + // 第二轮拿到的输入必须包含第一轮的产出,不能是空的 —— + // 否则"重复"就只是把同一件事做两遍,没有意义 + const second = nodeRes.inputsByNode.n1?.[1] || ''; + check(' 第二轮能拿到上一轮的输出', second.includes(cs.wantSecondRoundHas), + JSON.stringify(second)); + } + if (cs.wantAborted) { + check(' 被停止后正确报告 aborted', nodeRes.aborted === true, String(nodeRes.aborted)); + } if (cs.wantError) { const has = nodeRes.events.some((e) => e.type === 'node_error'); check(' 出错上报了 node_error', has); diff --git a/server/src/meeting.mjs b/server/src/meeting.mjs index 1dcfa49..861548c 100644 --- a/server/src/meeting.mjs +++ b/server/src/meeting.mjs @@ -143,7 +143,12 @@ function sanitizeNodes(nodes) { const ntype = String(n.type || ''); if (!nid || seen.has(nid) || !NODE_TYPES.includes(ntype)) continue; seen.add(nid); - out.push({ ...n, id: nid, type: ntype, x: Number(n.x) || 0, y: Number(n.y) || 0 }); + // 夹在 0~20:**0 = 无限循环**(两个智能体互相点评那种用法),1~20 是有限次。 + // 负数或大于 20 的值都不认,退回 1 —— 不然手改文件写成 99999 会一直烧额度。 + const raw = Number(n.maxRuns); + const value = Number.isFinite(raw) ? Math.trunc(raw) : 1; + const maxRuns = value <= 0 ? 0 : Math.min(value, 20); + out.push({ ...n, id: nid, type: ntype, x: Number(n.x) || 0, y: Number(n.y) || 0, maxRuns }); } return out; } @@ -232,11 +237,43 @@ export async function runMeeting({ meeting, settings, userInput, emit, runAgentF } const queue = starts.map((n) => n.id); - const visited = new Set(); + + // ★ 每个节点跑了几次(不是"跑没跑过")。 + // + // 用户要的是"n1 → n2 → n1 只有一轮,但**能重复**": + // 默认每节点 1 次(= 不重复),把节点上的「最多执行次数」调大就能来回跑。 + // 以前用的是 visited 集合(跑过就不再跑),环永远只转一圈,没法重复。 + const runs = {}; let steps = 0; - const maxSteps = Math.max(20, nodes.length * 4); + + /** + * 节点的执行次数上限。**0 表示无限**。 + * + * 为什么要支持无限:两个智能体互相点评(甲评乙、乙再评甲)是常见用法, + * 用户希望一直怼下去,自己觉得够了再按停止。 + * + * 为什么敢开无限:引擎每一轮都检查 shouldStop(客户端断开或用户点了停止), + * 所以"无限"实际是"跑到你喊停为止"。另外兜了一个很大的硬上限, + * 防止用户忘了停、或客户端异常断开时把额度烧光。 + */ + const limitOf = (node) => { + const raw = Number(node.maxRuns); + const value = Number.isFinite(raw) ? Math.trunc(raw) : 1; + return value <= 0 ? 0 : Math.min(value, 20); + }; + + const budget = nodes.reduce((sum, n) => sum + (limitOf(n) || 200), 0); + const maxSteps = Math.max(20, budget * 2 + nodes.length); let finalOutput = ''; + const canRun = (id) => { + const node = byId.get(id); + if (!node) return false; + const limit = limitOf(node); + // 0 = 无限:永远还能再跑一次 + return limit === 0 || (runs[id] || 0) < limit; + }; + while (queue.length && steps < maxSteps) { if (shouldStop && shouldStop()) { emit({ type: 'meeting_done', output: finalOutput, aborted: true }); @@ -245,31 +282,41 @@ export async function runMeeting({ meeting, settings, userInput, emit, runAgentF const nodeId = queue.shift(); steps += 1; - if (visited.has(nodeId)) continue; - visited.add(nodeId); + if (!canRun(nodeId)) continue; const node = byId.get(nodeId); if (!node) continue; + const runIndex = (runs[nodeId] || 0) + 1; + runs[nodeId] = runIndex; const nodeType = node.type; const title = node.title || { start: '初始输入', agent: '智能体', judge: '判断', end: '最终输出' }[nodeType] || nodeType; - emit({ type: 'node_start', nodeId, nodeType, title }); + emit({ + type: 'node_start', + nodeId, + nodeType, + title, + run: runIndex, + maxRuns: limitOf(node), + }); const input = collectInput(nodeId, edges, outputs); let nextIds = []; try { if (nodeType === 'start') { - const text = String(node.text || '').trim() || (userInput || ''); + // 第二轮开始,"初始输入"要把**自己上一轮的输出**当输入, + // 否则循环回来的内容会被起点覆盖掉,重复就没意义了 + const text = input || String(node.text || '').trim() || (userInput || ''); outputs[nodeId] = text; - emit({ type: 'node_done', nodeId, output: text, note: '用的初始输入' }); + emit({ type: 'node_done', nodeId, output: text, run: runIndex, note: '用的初始输入' }); nextIds = outgoing(edges, nodeId).map((e) => e.to); } else if (nodeType === 'agent') { const out = await runAgentFn(node, input, settings, emit, nodeId); outputs[nodeId] = out; - emit({ type: 'node_done', nodeId, output: out }); + emit({ type: 'node_done', nodeId, output: out, run: runIndex }); nextIds = outgoing(edges, nodeId).map((e) => e.to); } else if (nodeType === 'judge') { const kind = String(node.judgeKind || 'not_empty'); @@ -289,19 +336,18 @@ export async function runMeeting({ meeting, settings, userInput, emit, runAgentF type: 'node_done', nodeId, output: input, + run: runIndex, verdict: passed, branch: passed ? 'true' : 'false', note: `判断结果:${passed}`, }); - // 判断节点走 true / false 两条出边;没标分支的那条当默认(true) const outs = outgoing(edges, nodeId); nextIds = outs.filter((e) => (e.branch || 'true') === (passed ? 'true' : 'false')).map((e) => e.to); - // 没连对应的分支就顺走第一条,免得图直接断在这儿 if (!nextIds.length) nextIds = outs.slice(0, 1).map((e) => e.to); } else if (nodeType === 'end') { outputs[nodeId] = String(node.text || '').trim() || input; finalOutput = outputs[nodeId]; - emit({ type: 'node_done', nodeId, output: finalOutput }); + emit({ type: 'node_done', nodeId, output: finalOutput, run: runIndex }); nextIds = []; } else { emit({ type: 'node_error', nodeId, error: `不认识的节点类型:${nodeType}` }); @@ -309,13 +355,16 @@ export async function runMeeting({ meeting, settings, userInput, emit, runAgentF } } catch (err) { // 单个节点出错不该让整场会议停摆:记下来,继续跑下游 - emit({ type: 'node_error', nodeId, error: err.message }); + emit({ type: 'node_error', nodeId, error: err.message, run: runIndex }); outputs[nodeId] = ''; nextIds = outgoing(edges, nodeId).map((e) => e.to); } + // ★ 只有"还能再跑"的节点才重新入队。 + // 这就是"重复"的开关:maxRuns=1(默认)时跑过的节点不会再进来,环只转一圈; + // 把它调大,环就会来回转到次数用完为止。 for (const nid of nextIds) { - if (!visited.has(nid)) queue.push(nid); + if (canRun(nid)) queue.push(nid); } }