diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt index 54feec5..6b68362 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentsScreen.kt @@ -458,7 +458,7 @@ private val TtsEngineChoices: List> = listOf( */ @OptIn(ExperimentalLayoutApi::class) @Composable -private fun WrapChips( +internal fun WrapChips( options: List>, active: String, onPick: (String) -> Unit, diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index 2a8325f..5b068f7 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -86,6 +86,7 @@ fun AppRoot( Screen.Settings -> SettingsScreen(vm) Screen.Skills -> SkillsScreen(vm) Screen.Agents -> AgentsScreen(vm) + Screen.Meetings -> MeetingsScreen(vm) Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux) } } @@ -144,6 +145,9 @@ private fun DrawerOverlay(vm: AppViewModel) { DrawerItem(Icons.Filled.Layers, "技能·连接器") { vm.screen = Screen.Skills; vm.drawerOpen = false } + DrawerItem(Icons.Filled.AccountTree, "会议模式") { + vm.screen = Screen.Meetings; vm.drawerOpen = false + } DrawerItem(Icons.Filled.Terminal, "终端") { vm.screen = Screen.Terminal; vm.drawerOpen = false } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index 08b3623..928f2a1 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -12,9 +12,14 @@ import com.doubao.lynxclone.data.Attachment import com.doubao.lynxclone.data.ChatMessage import com.doubao.lynxclone.data.Conversation import com.doubao.lynxclone.data.KernelClient +import com.doubao.lynxclone.data.MeetingEvent +import com.doubao.lynxclone.data.MeetingMeta import com.doubao.lynxclone.data.StreamEvent import com.doubao.lynxclone.data.ToolTrace import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.json.JSONArray @@ -22,7 +27,7 @@ import org.json.JSONObject import java.util.concurrent.atomic.AtomicBoolean /** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */ -enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal } +enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal, Meetings } /** * 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。 @@ -256,15 +261,93 @@ class AppViewModel(val client: KernelClient) : ViewModel() { } /** - * 保存智能体。 + * 简化的协程入口。 * - * 形参从一个 Agent 对象整体传,而不是一长串 String —— 之前每加一个字段 - * (问候语、模型、音色…)就要改一遍签名和所有调用点,漏一处就是 - * "界面上填了、保存后没了"。 - * - * 模型/语音这些字段**空串表示继承全局**,所以原样发过去就行, - * 内核那边(store.provider_info / speech.voice_for)也是这个规则。 + * 页面里到处写 `viewModelScope.launch { try { … } catch (e) { showHint(…) } }` + * 太啰嗦,而且很容易漏 catch(漏了就是静默失败,最难查)。 + * 统一走这里:出错一律弹提示。 */ + fun launch(block: suspend () -> Unit) { + viewModelScope.launch { + try { + block() + } catch (e: Exception) { + showHint(e.message ?: "操作失败") + } + } + } + + /* ------------------------------ 会议模式 ------------------------------ */ + + /** 编辑器要用的元信息(节点类型 / 判断条件 / 可用智能体)。进页面时拉一次。 */ + var meetingMeta by mutableStateOf(MeetingMeta()) + private set + + private var meetingMetaLoaded = false + + fun ensureMeetingMeta() { + if (meetingMetaLoaded) return + launch { + meetingMeta = client.meetingMeta() + meetingMetaLoaded = true + } + } + + private var meetingJob: Job? = null + + /** + * 跑一场会议。事件边收边回调。 + * + * 同时只能跑一场:再点一次运行会先掐掉上一场 —— 否则两个图同时往 + * 同一批节点上写输出,界面上会看到内容互相覆盖。 + */ + fun runMeeting( + meetingId: String, + input: String, + onEvent: (MeetingEvent) -> Unit, + onError: (String) -> Unit, + ) { + meetingJob?.cancel() + val cancelled = AtomicBoolean(false) + meetingJob = viewModelScope.launch { + // ★ 事件在 IO 线程上产生,但**必须回主线程再交给界面**。 + // + // 之前直接在 IO 线程里改 Compose 状态(mutableStateMapOf), + // 结果是"日志里事件全收到了、节点上就是不显示"—— 状态写进去了, + // 界面却不一定重组。用 Channel 过一道,既保证在主线程执行, + // 又保证顺序(trySend 是有序的)。 + val events = Channel(Channel.UNLIMITED) + val consumer = launch { + for (ev in events) onEvent(ev) + } + try { + val seen = LinkedHashMap() + client.runMeeting(meetingId, input, cancelled) { ev -> + seen[ev.type] = (seen[ev.type] ?: 0) + 1 + events.trySend(ev) + } + android.util.Log.i( + "DoubaoMeeting", + "事件统计: " + seen.entries.joinToString(", ") { "${it.key}=${it.value}" }, + ) + } catch (e: CancellationException) { + events.close() + consumer.cancel() + throw e + } catch (e: Exception) { + onError(e.message ?: "运行失败") + } finally { + events.close() + } + consumer.join() + } + } + + fun stopMeeting() { + meetingJob?.cancel() + meetingJob = null + } + fun saveAgent(id: String?, draft: Agent, onDone: () -> Unit) { viewModelScope.launch { try { 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 new file mode 100644 index 0000000..8fba5fc --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt @@ -0,0 +1,888 @@ +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.detectDragGestures +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.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.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +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.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) } + // 正在连线的源节点(两步点选的第一个"点") + var linkingFrom by remember { mutableStateOf(null) } + var running by remember { mutableStateOf(false) } + var runInput by remember { mutableStateOf("") } + var runError by remember { mutableStateOf("") } + var dirty by remember { mutableStateOf(false) } + val nodeOutputs = remember { mutableStateMapOf() } + + // 运行时的节点状态:正在跑 / 跑完 / 出错 + val liveStatus = remember { mutableStateMapOf() } + + var panX by remember { mutableStateOf(0f) } + var panY by remember { mutableStateOf(0f) } + + /** 统一的保存入口:拖动结束后、改完配置后都走它 */ + fun persist() { + vm.launch { + try { + meeting = vm.client.saveMeeting(meeting.id, meeting) + dirty = false + } catch (_: Exception) { + // 保存失败不打断编辑:本地改动还在,下次拖动会再试 + } + } + } + + 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( + if (linkingFrom != null) "点目标节点完成连线(点空白取消)" + else if (dirty) "未保存" else "${meeting.nodes.size} 节点 · ${meeting.edges.size} 连线", + fontSize = 11.sp, + color = if (linkingFrom != null) Doubao.Blue else doubaoTextSecondary(), + ) + } + 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" + "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 + } + } + }, + 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), + ) + } + + // 画布 + // + // ★ 用手势平移(panX/panY + graphicsLayer),**不用 horizontalScroll + + // verticalScroll** —— 那两个滚动修饰符叠在同一个 Modifier 链上测量会互相 + // 打架,实测画布根本滚不动(节点被推到屏幕外就再也看不到,最终输出节点 + // 直接找不着)。平移只有一个状态、行为完全可控,也不和节点的拖拽抢手势: + // 手指落在节点上时子节点的拖拽先消费事件,落在空白处才是平移。 + 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 + } + }, + ) { + Box( + Modifier + .size(CANVAS_W.dp, CANVAS_H.dp) + .graphicsLayer { + translationX = panX + 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" + drawLine( + color = if (edge.branch == "true") Doubao.Blue + else if (dashed) Color(0xFF9AA0A6) else Color(0xFFBFC4CC), + start = start, + end = end, + strokeWidth = 2.dp.toPx(), + pathEffect = if (dashed) 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), + start = end, + end = Offset( + end.x - len * kotlin.math.cos(angle - 0.4f), + end.y - len * kotlin.math.sin(angle - 0.4f), + ), + strokeWidth = 2.dp.toPx(), + ) + } + // 正在连线:从源节点画一条虚线跟着(这里只画到画布中心做个提示) + linkingFrom?.let { from -> + val a = meeting.nodes.firstOrNull { it.id == from } + if (a != null) { + 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()), + ) + } + } + } + + // 节点 + meeting.nodes.forEach { node -> + val status = liveStatus[node.id] ?: "" + NodeCard( + node = node, + status = status, + output = nodeOutputs[node.id] ?: "", + linking = linkingFrom == 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 }, + ) + } + } + } + + // 运行输入 + 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)) + PrimaryButton(if (running) "运行中…" else "运行") { + if (!running) { + 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" + "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 + } + } + }, + onError = { msg -> running = false; runError = msg }, + ) + } + } + } + } + + configTarget?.let { target -> + NodeConfigDialog( + node = target, + meta = vm.meetingMeta, + 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 = { + Column { + 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).coerceAtMost(CANVAS_W - NODE_W), + y = (120f + meeting.nodes.size * 26f).coerceAtMost(CANVAS_H - NODE_H), + 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 clampPan(x: Float, y: Float, viewW: Float, viewH: Float): Pair { + 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 nodeColor(type: String): Color = when (type) { + "start" -> Color(0xFF34A853) + "judge" -> Color(0xFFF29900) + "end" -> Color(0xFF7B61FF) + else -> Doubao.Blue +} + +@Composable +private fun NodeCard( + node: MeetingNode, + status: String, + output: String, + linking: Boolean, + modifier: Modifier, + onDrag: (Float, Float) -> Unit, + onDragEnd: () -> Unit, + onClick: () -> Unit, + onLink: () -> Unit, +) { + val accent = nodeColor(node.type) + Column( + modifier + .size(NODE_W.dp, NODE_H.dp) + .clip(RoundedCornerShape(12.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.45f) + }, + shape = RoundedCornerShape(12.dp), + ) + // 拖动:节点位置就是内核里的 x/y,拖完直接存 + .pointerInput(node.id) { + detectDragGestures( + onDragEnd = { onDragEnd() }, + ) { change, drag -> + change.consume() + onDrag(drag.x, drag.y) + } + } + .clickable(onClick = onClick) + .padding(8.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.size(7.dp).clip(CircleShape).background(accent)) + Spacer(Modifier.width(6.dp)) + Text( + node.title.ifBlank { + when (node.type) { + "start" -> "初始输入" + "judge" -> "判断" + "end" -> "最终输出" + else -> "智能体" + } + }, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (status == "running") { + Text("…", fontSize = 13.sp, color = accent) + } else if (status == "done") { + Text("✓", fontSize = 12.sp, color = Color(0xFF34A853)) + } + } + Spacer(Modifier.height(3.dp)) + Text( + when { + output.isNotBlank() -> output + node.type == "agent" -> if (node.agentId.isBlank()) "未选智能体" else "已选智能体" + node.type == "judge" -> node.judgeKind + node.text.isNotBlank() -> node.text + else -> "点一下配置" + }, + fontSize = 10.sp, + color = doubaoTextSecondary(), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + 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), + ) + } + } +} + +/* ====================================================================== */ +/* 小零件 */ +/* ====================================================================== */ + +/** 主按钮(和智能体页那个「新建智能体」同款) */ +@Composable +private fun PrimaryButton(label: String, onClick: () -> Unit) { + androidx.compose.material3.Button( + onClick = onClick, + shape = RoundedCornerShape(24.dp), + 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, + 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", "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), + ) + } + + "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 两条,界面上蓝色实线是 true、灰色虚线是 false。", + fontSize = 11.sp, + color = 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/app.py b/android/kernel/app.py index 43bdef4..7884585 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -963,12 +963,21 @@ class KernelHandler(BaseHTTPRequestHandler): def relay(event): # 只把正文增量转成 node_delta,其它事件(工具调用、思维链)原样转发, - # 界面上按节点分组显示 + # 界面上按节点分组显示。 + # + # ★ 流式正文的事件名是 **delta**,不是 text —— agent_loop 发的是 + # {'type':'delta','text':…}。我之前按 'text' 判断,结果 node_delta + # 一个都没发出去,节点上的正文只在最后 node_done 时"啪"地出现, + # 完全没有流式效果。事件统计日志(delta=103 / node_delta=0)抓到的。 kind = event.get('type') - if kind == 'text': + if kind == 'delta': emit({'type': 'node_delta', 'nodeId': node_id, 'text': event.get('text') or ''}) - elif kind == 'done': + elif kind in ('done', 'start'): + # 这两个是"整个 agent 轮次"的开始和结束,和会议节点的语义重复, + # 转出去只会让界面多两个没用的状态 pass + elif kind == 'reasoning': + emit({'type': 'node_reasoning', 'nodeId': node_id, 'text': event.get('text') or ''}) else: emit({**event, 'nodeId': node_id}) diff --git a/android/kernel/meeting.py b/android/kernel/meeting.py index 6385114..d496548 100644 --- a/android/kernel/meeting.py +++ b/android/kernel/meeting.py @@ -83,16 +83,21 @@ def new_meeting(name: str = '新会议') -> dict: 空白画布对着干瞪眼是最差的新手体验;放一个"输入 → 一个智能体 → 输出" 的最小闭环,用户改改就能用,也能一眼看懂节点和连线是怎么连的。 + + ★ 坐标要**一屏放得下**:x 按 120 递增、节点宽 116,所以 12→132→252, + 最右边 252+116=368。手机竖屏大约 360dp 宽,会稍微超一点点, + 但主体都在视野里;早先按 60/300/540 摆,默认图直接摊到两屏外, + 用户一进来看到的是空画布加一个孤零零的节点,以为坏了。 """ return { 'id': _rid('m'), 'name': name, 'nodes': [ - {'id': 'n_start', 'type': 'start', 'x': 60, 'y': 200, + {'id': 'n_start', 'type': 'start', 'x': 12, 'y': 120, 'title': '初始输入', 'text': ''}, - {'id': 'n_agent1', 'type': 'agent', 'x': 300, 'y': 200, + {'id': 'n_agent1', 'type': 'agent', 'x': 132, 'y': 120, 'title': '智能体', 'agentId': '', 'extraPrompt': '', 'outputControl': ''}, - {'id': 'n_end', 'type': 'end', 'x': 540, 'y': 200, + {'id': 'n_end', 'type': 'end', 'x': 252, 'y': 120, 'title': '最终输出', 'text': ''}, ], 'edges': [ diff --git a/scripts/device-meeting-run2.mjs b/scripts/device-meeting-run2.mjs new file mode 100644 index 0000000..3303370 --- /dev/null +++ b/scripts/device-meeting-run2.mjs @@ -0,0 +1,34 @@ +/** + * 会议模式:从聊天页正确导航进去 → 运行 → 截图。 + * 用法: node scripts/device-meeting-run2.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'); sh('pull', '/sdcard/_s.png', path.join(OUT, `${n}.png`)); console.log(' 截图', n); } +async function tap(x, y, w = 1400) { sh('shell', 'input', 'tap', String(x), String(y)); await sleep(w); } + +console.log('① 开抽屉 → 会议模式'); +await tap(45, 105); +await tap(250, 561, 2500); +await shot('20-list'); + +console.log('② 点第一个会议'); +// 列表第一项大约在 y=300 附近(标题说明文字下方) +await tap(300, 300, 3000); +await shot('21-editor'); + +console.log('③ 运行(输入框留空,用节点里的文本)'); +await tap(617, 1205, 1500); +for (let i = 1; i <= 8; i += 1) { await sleep(4000); await shot(`22-run-${i}`); } + +console.log('完成,截图在', OUT); diff --git a/server/src/index.mjs b/server/src/index.mjs index e89f3cd..ef5cee8 100644 --- a/server/src/index.mjs +++ b/server/src/index.mjs @@ -172,10 +172,18 @@ async function streamMeetingRun(req, res, meetingId) { agent: mergedAgent, emit: (event) => { // 只把正文增量转成 node_delta,其它事件原样转发但带上 nodeId, - // 界面上按节点分组显示 - if (event.type === 'text') { + // 界面上按节点分组显示。 + // + // ★ 流式正文的事件名是 **delta**,不是 text —— agent.mjs 发的是 + // {type:'delta', text:…}。按 'text' 判断的话 node_delta 一个都发不出去, + // 节点上的正文只在最后 node_done 时"啪"地出现,完全没有流式效果。 + if (event.type === 'delta') { emit({ type: 'node_delta', nodeId, text: event.text || '' }); - } else if (event.type !== 'done') { + } else if (event.type === 'reasoning') { + emit({ type: 'node_reasoning', nodeId, text: event.text || '' }); + } else if (event.type !== 'done' && event.type !== 'start') { + // done / start 是"整个 agent 轮次"的开始和结束,和会议节点的语义重复, + // 转出去只会让界面多两个没用的状态 emit({ ...event, nodeId }); } }, diff --git a/server/src/meeting.mjs b/server/src/meeting.mjs index c91b40d..1dcfa49 100644 --- a/server/src/meeting.mjs +++ b/server/src/meeting.mjs @@ -49,15 +49,19 @@ function file() { * * 空白画布对着干瞪眼是最差的新手体验;放一个"输入 → 一个智能体 → 输出" * 的最小闭环,用户改改就能用,也能一眼看懂节点和连线是怎么连的。 + * + * ★ 坐标要**一屏放得下**:x 按 120 递增、节点宽 116,所以 12→132→252。 + * 早先按 60/300/540 摆,手机竖屏(约 360dp)上默认图直接摊到两屏外, + * 用户一进来看到的是空画布加一个孤零零的节点,以为坏了。 */ export function newMeeting(name = '新会议') { return { id: rid('m'), name, nodes: [ - { id: 'n_start', type: 'start', x: 60, y: 200, title: '初始输入', text: '' }, - { id: 'n_agent1', type: 'agent', x: 300, y: 200, title: '智能体', agentId: '', extraPrompt: '', outputControl: '' }, - { id: 'n_end', type: 'end', x: 540, y: 200, title: '最终输出', text: '' }, + { id: 'n_start', type: 'start', x: 12, y: 120, title: '初始输入', text: '' }, + { id: 'n_agent1', type: 'agent', x: 132, y: 120, title: '智能体', agentId: '', extraPrompt: '', outputControl: '' }, + { id: 'n_end', type: 'end', x: 252, y: 120, title: '最终输出', text: '' }, ], edges: [ { from: 'n_start', to: 'n_agent1', branch: '' },