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 928f2a1..c9fb77d 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 @@ -293,6 +293,39 @@ class AppViewModel(val client: KernelClient) : ViewModel() { } } + /** + * 强制重新拉一次 meta。 + * + * ★ 导入/删掉节点文件之后必须调它 —— 自定义节点是**运行期从磁盘读**的, + * 不重拉的话界面上还是旧的那一套引脚,用户会以为导入没生效。 + * (ensureMeetingMeta 有 loaded 缓存,所以这里要单独一个不走缓存的入口。) + */ + fun reloadMeetingMeta() { + launch { + meetingMeta = client.meetingMeta() + meetingMetaLoaded = true + } + } + + /** 列出 nodes/ 里的自定义节点文件 */ + suspend fun nodeFiles(): org.json.JSONArray = client.nodeFiles() + + /** 读一个自定义节点的源码 */ + suspend fun readNode(file: String): org.json.JSONObject = client.readNode(file) + + /** 导入一个自定义节点文件;成功返回节点名,失败抛异常(错误信息给用户看) */ + suspend fun importNodeFile(file: String, code: String): String { + val res = client.importNode(file, code) + reloadMeetingMeta() + return res.optString("label").ifBlank { file } + } + + /** 删掉一个自定义节点文件 */ + suspend fun deleteNodeFile(file: String) { + client.deleteNode(file) + reloadMeetingMeta() + } + private var meetingJob: Job? = null /** diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt new file mode 100644 index 0000000..95d43cd --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt @@ -0,0 +1,373 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.doubao.lynxclone.data.CustomNodeDef + +/* + * 自定义节点的管理 / 编辑界面。 + * + * ★ 为什么单独一个文件: + * MeetingsScreen.kt 已经 3800 行了,往里塞东西的每一次都要重新理解上下文, + * 而且改错了很难看出来(这一轮已经因为漏一个花括号排查了很久)。 + * "节点"本身是一个独立的东西,界面也单独放。 + */ + +/** 一个节点文件的列表项(来自 GET /api/meeting/nodes) */ +data class NodeFile( + val file: String = "", + val ok: Boolean = true, + val error: String = "", + val label: String = "", + val desc: String = "", + val inputs: List> = emptyList(), + val outputs: List> = emptyList(), +) + +/** + * 节点管理:列出 nodes/ 里的全部文件,能导入 / 编辑 / 导出 / 删除。 + * + * ★ 为什么要有这个界面: + * 原来只能 adb push 一个文件进去 —— 那不叫能用。 + * 用户要的是"我在手机上就能加一种节点、改它、把它发给别人"。 + */ +@Composable +fun NodeManagerDialog( + nodes: List, + dir: String, + message: String, + onImport: () -> Unit, + onEdit: (NodeFile) -> Unit, + onExport: (NodeFile) -> Unit, + onDelete: (NodeFile) -> Unit, + onNew: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("自定义节点", fontSize = 16.sp) }, + text = { + Column( + Modifier + .fillMaxWidth() + .heightIn(max = 460.dp) + .verticalScroll(rememberScrollState()), + ) { + Text( + "往这个目录放 .py 就多一种节点,界面上的引脚是从文件里读的:\n$dir", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 15.sp, + ) + Spacer(Modifier.height(10.dp)) + Row { + Text( + "+ 新建", + color = Doubao.Blue, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onNew() } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) + Spacer(Modifier.width(4.dp)) + Text( + "📥 导入文件", + color = Doubao.Blue, + fontSize = 13.sp, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onImport() } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) + } + if (message.isNotBlank()) { + Spacer(Modifier.height(4.dp)) + Text( + message, + fontSize = 11.sp, + color = if (message.startsWith("已导入")) Color(0xFF34A853) + else MaterialTheme.colorScheme.error, + lineHeight = 15.sp, + ) + } + Spacer(Modifier.height(8.dp)) + HorizontalDivider(thickness = 0.5.dp) + Spacer(Modifier.height(8.dp)) + + if (nodes.isEmpty()) { + Text( + "还没有自定义节点。点「新建」写一个,或者导入别人给你的 .py。", + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 17.sp, + ) + } + nodes.forEach { n -> + Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + (if (n.ok) "🐍 " else "⚠ ") + n.label.ifBlank { n.file }, + fontSize = 14.sp, + color = if (n.ok) doubaoText() else MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.width(6.dp)) + Text(n.file, fontSize = 10.sp, color = doubaoTextSecondary()) + } + Spacer(Modifier.height(2.dp)) + Text( + if (!n.ok) n.error + else n.desc.ifBlank { + "入 ${n.inputs.size} · 出 ${n.outputs.size}" + }, + fontSize = 11.sp, + color = if (n.ok) doubaoTextSecondary() + else MaterialTheme.colorScheme.error, + lineHeight = 15.sp, + ) + Spacer(Modifier.height(4.dp)) + Row { + NodeAction("编辑") { onEdit(n) } + NodeAction("导出") { onExport(n) } + NodeAction("删除", danger = true) { onDelete(n) } + } + } + HorizontalDivider(thickness = 0.4.dp) + } + } + }, + confirmButton = { TextButton(onClick = onDismiss) { Text("好") } }, + ) +} + +@Composable +private fun NodeAction(label: String, danger: Boolean = false, onClick: () -> Unit) { + Text( + label, + fontSize = 12.sp, + color = if (danger) MaterialTheme.colorScheme.error else Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { onClick() } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) +} + +/** + * 搭积木用的"积木块"。 + * + * ★ 这块的设计:**每一块都是一段能独立成立的 Python**,点一下就插进编辑器。 + * 不是 Scratch 那种拖拽画布 —— 那种要自己实现一套积木布局和吸附, + * 而这里的产物最终是**代码**,代码编辑器本来就在旁边。 + * 所以做成"点积木 -> 生成代码 -> 你能接着改",比拖拽更实用: + * 生成出来的东西是可读、可改、可以继续学的 Python,不是一个封闭的图形。 + * + * 对新手:从零写不出来,但知道要"记一条日志""设置输出"。 + * 对老手:这些块就是快捷键,省得敲样板代码。 + */ +private data class Block(val label: String, val hint: String, val code: String) + +private val BLOCKS = listOf( + Block("📝 记一条日志", "把内容写进这一步的说明里", " ctx.log(\"\", )\n"), + Block("📤 设置文本输出", "这个节点的文本出口给什么", " node[\"output\"][\"\"] = \"\"\n"), + Block("💾 写变量", "存进会议变量(要先在变量面板登记)", " ctx.set_var(\"\", )\n"), + Block("📖 读输入", "读某个入口的值", " value = node[\"input\"][\"\"]\n"), + Block("🔤 转大写", "把文本变成大写", " text = str(node[\"input\"][\"\"]).upper()\n"), + Block("✂️ 取前几个字", "截取开头 N 个字符", " head = text[:3]\n"), + Block("📏 文本长度", "有多少个字", " n = len(text)\n"), + Block("➕ 拼两段文本", "把两段接起来", " joined = a + b\n"), + Block("🔀 如果…否则…", "按条件走不同的路(把分支名换成你声明的)", + " if n >= 3:\n node[\"output\"][\"高分\"] = True\n else:\n node[\"output\"][\"低分\"] = True\n"), + Block("🔁 重复 N 次", "循环", " for i in range(3):\n pass\n"), + Block("🧩 遍历列表", "逐个处理列表里的东西", + " for item in node[\"input\"][\"列表\"]:\n ctx.log(item)\n"), + Block("🛡 试试看(出错不崩)", "包一层异常保护", + " try:\n pass\n except Exception as e:\n ctx.log(\"出错:\", e)\n"), +) + +private val TEMPLATE = """ +ToolName = { + "name": "我的节点", + "desc": "说明它干什么(当工具时给模型看,写清楚)", + "input": [ + {"type": "str", "name": "文本", "value": ""}, + ], + "output": [ + {"type": "exec", "name": "好了"}, + {"type": "str", "name": "结果"}, + ], +} + + +def run(ctx, node): + text = str(node["input"]["文本"]) + ctx.log("收到:", text) + node["output"]["结果"] = text.upper() + node["output"]["好了"] = True + return node +""".trimIndent() + +/** 新建时的空白模板 */ +fun newNodeTemplate(): String = TEMPLATE + +/** + * 现场编辑一个节点:代码框 + 搭积木面板。 + * + * 改完保存会走内核的导入接口 —— 内核**先试加载一遍**,写错了当场把 + * Python 的报错显示出来,而不是存进去变成一个坏节点。 + */ +@Composable +fun NodeEditDialog( + title: String, + fileName: String, + initialCode: String, + onFileName: (String) -> Unit, + onSave: (String) -> Unit, + onDismiss: () -> Unit, +) { + var code by remember { mutableStateOf(initialCode) } + var tab by remember { mutableStateOf(0) } // 0 = 代码,1 = 积木 + var focusLine by remember { mutableStateOf(code.lines().size) } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title, fontSize = 16.sp) }, + text = { + Column( + Modifier + .fillMaxWidth() + .heightIn(max = 500.dp), + ) { + OutlinedTextField( + value = fileName, + onValueChange = onFileName, + modifier = Modifier.fillMaxWidth(), + label = { Text("文件名", fontSize = 11.sp) }, + singleLine = true, + textStyle = TextStyle(fontSize = 12.sp), + ) + Spacer(Modifier.height(8.dp)) + + // 两个页签:写代码 / 搭积木 + Row { + TabChip("代码", tab == 0) { tab = 0 } + Spacer(Modifier.width(6.dp)) + TabChip("搭积木", tab == 1) { tab = 1 } + } + Spacer(Modifier.height(8.dp)) + + if (tab == 0) { + OutlinedTextField( + value = code, + onValueChange = { code = it }, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 260.dp, max = 320.dp) + .verticalScroll(rememberScrollState()), + textStyle = TextStyle(fontSize = 11.sp), + label = { Text("run(ctx, node)", fontSize = 11.sp) }, + ) + } else { + Text( + "点一块,代码就加到编辑器末尾。生成的是**普通 Python**," + + "你随时能切回「代码」接着改 —— 不是把你锁在积木里。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 15.sp, + ) + Spacer(Modifier.height(6.dp)) + Column( + Modifier + .fillMaxWidth() + .heightIn(max = 240.dp) + .verticalScroll(rememberScrollState()), + ) { + BLOCKS.forEach { b -> + Column( + Modifier + .fillMaxWidth() + .padding(vertical = 3.dp) + .clip(RoundedCornerShape(8.dp)) + .background(Doubao.Blue.copy(alpha = 0.07f)) + .clickable { + code = code.trimEnd('\n') + "\n" + b.code + focusLine = code.lines().size + } + .padding(horizontal = 10.dp, vertical = 7.dp), + ) { + Text(b.label, fontSize = 13.sp, color = Doubao.Blue) + Text( + b.hint, + fontSize = 10.sp, + color = doubaoTextSecondary(), + ) + } + } + } + Spacer(Modifier.height(8.dp)) + Text("当前代码:", fontSize = 11.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(3.dp)) + Text( + code.lines().takeLast(12).joinToString("\n"), + fontSize = 10.sp, + color = doubaoText(), + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 130.dp) + .verticalScroll(rememberScrollState()), + ) + } + } + }, + confirmButton = { TextButton(onClick = { onSave(code) }) { Text("保存") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }, + ) +} + +@Composable +private fun TabChip(label: String, on: Boolean, onClick: () -> Unit) { + Text( + label, + fontSize = 13.sp, + color = if (on) Color.White else doubaoTextSecondary(), + fontWeight = if (on) FontWeight.Medium else FontWeight.Normal, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .background(if (on) Doubao.Blue else Doubao.Blue.copy(alpha = 0.08f)) + .clickable { onClick() } + .padding(horizontal = 14.dp, vertical = 6.dp), + ) +} 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 2bf77cb..2f77f1b 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 @@ -300,6 +300,87 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - var showMenu by remember { mutableStateOf(false) } // 导入会议(粘 JSON) var showImport by remember { mutableStateOf(false) } + // ★ **导入节点文件**:用系统的文件选择器挑一个 .py,读出来交给内核落盘。 + // + // 为什么必须走"读出来 -> 交给内核写"这条路: + // 应用沙箱里 App 能写自己的数据目录,但 nodes/ 是**内核在管**的地方, + // 而且内核还会先把文件试加载一遍 —— 写错了当场把 Python 的报错回给用户, + // 而不是让他导入一个坏节点、之后每次开会都看见它。 + var nodeImportMsg by remember { mutableStateOf("") } + // 节点管理 / 现场编辑 + var showNodeMgr by remember { mutableStateOf(false) } + var nodeFiles by remember { mutableStateOf>(emptyList()) } + var editFile by remember { mutableStateOf(null) } + var editCode by remember { mutableStateOf("") } + var editName by remember { mutableStateOf("") } + var nodeMgrMsg by remember { mutableStateOf("") } + + // 拉一次节点文件列表(打开管理面板时、导入导出之后都要) + suspend fun refreshNodeFiles() { + val arr = runCatching { vm.nodeFiles() }.getOrElse { org.json.JSONArray() } + nodeFiles = (0 until arr.length()).mapNotNull { i -> + arr.optJSONObject(i)?.let { o -> + fun pins(k: String) = (o.optJSONArray(k) ?: org.json.JSONArray()).let { a -> + (0 until a.length()).mapNotNull { j -> + a.optJSONObject(j)?.let { p -> + p.optString("type") to p.optString("name") + } + } + } + NodeFile( + file = o.optString("file"), + ok = o.optBoolean("ok", true), + error = o.optString("error"), + label = o.optString("label"), + desc = o.optString("desc"), + inputs = pins("inputs"), + outputs = pins("outputs"), + ) + } + } + } + + // 导出节点:系统的保存对话框 + var pendingNodeExport by remember { mutableStateOf("") } + val nodeExporter = rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("text/x-python"), + ) { uri -> + if (uri != null) { + val ok = runCatching { + context.contentResolver.openOutputStream(uri)?.use { os -> + os.write(pendingNodeExport.toByteArray(Charsets.UTF_8)) + } + true + }.getOrElse { false } + nodeMgrMsg = if (ok) "已导出到文件" else "导出失败:路径不可写" + } + } + + val nodePicker = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + val picked = runCatching { + val name = uri.lastPathSegment.orEmpty().substringAfterLast('/') + val text = context.contentResolver.openInputStream(uri)?.use { ins -> + ins.readBytes().toString(Charsets.UTF_8) + }.orEmpty() + name to text + }.getOrElse { "" to "" } + val (name0, text) = picked + if (text.isBlank()) { + nodeImportMsg = "读不到文件内容(可能没给存储权限)" + } else { + vm.launch { + val r = runCatching { vm.importNodeFile(name0.ifBlank { "node.py" }, text) } + nodeImportMsg = r.fold( + onSuccess = { "已导入:$it" }, + onFailure = { "导入失败:${it.message.orEmpty().take(300)}" }, + ) + } + } + } + } // ★ 拖动灵敏度:屏幕上移动 1px,节点实际移动 (1/缩放) × 这个系数。 // 除缩放是必须的(不然放大后节点跑得比手指快);剩下的手感 —— // 跟手一点还是稳一点 —— 跟屏幕尺寸、手指习惯都有关系, @@ -1234,6 +1315,89 @@ if (edge.kind == "exec") { ) } + // 节点管理面板 + if (showNodeMgr) { + if (nodeFiles.isEmpty() && nodeMgrMsg.isBlank()) { + LaunchedEffect(Unit) { refreshNodeFiles() } + } + NodeManagerDialog( + nodes = nodeFiles, + dir = vm.meetingMeta.customDir, + message = nodeMgrMsg, + onImport = { nodePicker.launch(arrayOf("text/x-python", "text/plain", "*/*")) }, + onNew = { + editFile = null + editName = "my_node.py" + editCode = newNodeTemplate() + }, + onEdit = { nf -> + // 从内核读**源码**(列表里只有摘要,没有正文) + vm.launch { + val o = runCatching { vm.readNode(nf.file) }.getOrElse { null } + if (o == null) { + nodeMgrMsg = "读不到这个文件的源码" + } else { + editFile = nf.file + editName = nf.file + editCode = o.optString("code") + } + } + }, + onExport = { nf -> + vm.launch { + val o = runCatching { vm.readNode(nf.file) }.getOrElse { null } + if (o == null) { + nodeMgrMsg = "读不到这个文件的源码" + } else { + pendingNodeExport = o.optString("code") + nodeExporter.launch(nf.file) + } + } + }, + onDelete = { nf -> + vm.launch { + val r = runCatching { vm.deleteNodeFile(nf.file) } + nodeMgrMsg = r.fold( + onSuccess = { "已删除:${nf.file}" }, + onFailure = { "删不掉:${it.message.orEmpty().take(200)}" }, + ) + refreshNodeFiles() + } + }, + onDismiss = { showNodeMgr = false }, + ) + } + + // 现场编辑 / 新建 + if (editCode.isNotEmpty() || editFile == null && editName.isNotBlank()) { + NodeEditDialog( + title = if (editFile == null) "新建节点" else "编辑 ${editFile}", + fileName = editName, + initialCode = editCode, + onFileName = { editName = it }, + onSave = { code -> + val name = editName.ifBlank { "node.py" } + vm.launch { + val r = runCatching { vm.importNodeFile(name, code) } + nodeMgrMsg = r.fold( + onSuccess = { "已保存:$it" }, + onFailure = { "存不了:${it.message.orEmpty().take(300)}" }, + ) + if (r.isSuccess) { + editCode = "" + editFile = null + refreshNodeFiles() + } + } + }, + onDismiss = { + editCode = "" + editFile = null + editName = "" + }, + ) + } + if (showImport) { ImportDialog( current = meeting, @@ -1310,6 +1474,33 @@ if (edge.kind == "exec") { .heightIn(max = 440.dp) .verticalScroll(rememberScrollState()), ) { + // 📥 导入节点文件(放在自定义节点列表**上面**:先能导入,才谈得上用) + Column( + Modifier.fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .clickable { adding = false; nodeMgrMsg = ""; showNodeMgr = true } + .padding(horizontal = 10.dp, vertical = 10.dp), + ) { + Text("📥 导入 / 管理节点…", fontSize = 14.sp, color = Doubao.Blue) + Spacer(Modifier.height(2.dp)) + Text( + "导入 .py、新建、现场编辑、导出、删除都在这里。文件放在:\n${vm.meetingMeta.customDir}", + fontSize = 10.sp, + color = doubaoTextSecondary(), + lineHeight = 14.sp, + ) + if (nodeImportMsg.isNotBlank()) { + Spacer(Modifier.height(4.dp)) + Text( + nodeImportMsg, + fontSize = 11.sp, + color = if (nodeImportMsg.startsWith("已导入")) Color(0xFF34A853) + else MaterialTheme.colorScheme.error, + lineHeight = 15.sp, + ) + } + } + HorizontalDivider(Modifier.padding(vertical = 6.dp), thickness = 0.5.dp) // ★ **用户用 Python 拓展出来的节点**,列在内置节点前面。 // 引脚是从内核读的,用户往 nodes/ 丢一个 .py,这里就多一项。 vm.meetingMeta.customNodes.forEach { cd -> @@ -3060,6 +3251,8 @@ private fun nodeColor(type: String): Color = when (type) { "cast" -> Color(0xFF7E57C2) // 转换:深一点的紫(和"值"同族) "op" -> Color(0xFF00897B) // 运算:深青(和变量同族,都是"算东西") "py" -> Color(0xFF37474F) // Python:深灰蓝("这是代码") + // 自定义节点:洋红("这是你自己加的",一眼能从内置节点里认出来) + "custom" -> Color(0xFFAD1457) "while" -> Color(0xFFD93025) // 循环:红,醒目 else -> Doubao.Blue } @@ -3131,6 +3324,7 @@ private fun NodeCard( "cast" -> "转换" "op" -> "运算" "py" -> "Python" + "custom" -> "自定义" "while" -> "while 循环" else -> "智能体" } diff --git a/android/kernel/app.py b/android/kernel/app.py index 575d7eb..9dea3d2 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -704,6 +704,133 @@ class KernelHandler(BaseHTTPRequestHandler): self.send_json(200, {'meeting': meeting.create_meeting(body)}) return True + # ---------------- 自定义节点(用户用 Python 拓展的) ---------------- # + if pathname == '/api/meeting/nodes' and method == 'GET': + import custom_nodes as _cn + folder = _cn.nodes_dir() + items = [] + if os.path.isdir(folder): + for fn in sorted(os.listdir(folder)): + if not fn.endswith('.py'): + continue + d = _cn.load_file(os.path.join(folder, fn)) + items.append({ + 'file': fn, + 'ok': not d.get('error'), + 'error': d.get('error') or '', + 'label': d.get('label') or '', + 'desc': d.get('desc') or '', + 'inputs': d.get('inputs') or [], + 'outputs': d.get('outputs') or [], + }) + self.send_json(200, {'dir': folder, 'nodes': items}) + return True + + if pathname.startswith('/api/meeting/nodes/') and method == 'GET': + # 读一个节点文件的**源码** —— 现场编辑要用 + import custom_nodes as _cn + import urllib.parse as _up + fname = os.path.basename( + _up.unquote(pathname[len('/api/meeting/nodes/'):]).replace('\\', '/')) + target = os.path.join(_cn.nodes_dir(), fname) + if not fname.endswith('.py') or not os.path.isfile(target): + self.send_json(404, {'error': '没有这个节点文件'}) + return True + try: + with open(target, 'r', encoding='utf-8') as fh: + code = fh.read() + except OSError as exc: + self.send_json(400, {'error': f'读不了:{exc}'}) + return True + d = _cn.load_file(target) + self.send_json(200, { + 'file': fname, + 'code': code, + 'ok': not d.get('error'), + 'error': d.get('error') or '', + 'label': d.get('label') or '', + 'inputs': d.get('inputs') or [], + 'outputs': d.get('outputs') or [], + }) + return True + + if pathname == '/api/meeting/nodes' and method == 'POST': + # 导入一个节点文件。 + # + # 为什么要有这个接口:应用沙箱里**没有别的办法**把文件放进数据目录 —— + # 界面用系统的文件选择器读进来,再 POST 到这里落盘。 + # 不给的话用户只能用 adb push,那不叫能用。 + import custom_nodes as _cn + body = self.read_json_body() + fname = str(body.get('file') or '').strip() + code = str(body.get('code') or '') + if not fname.lower().endswith('.py'): + fname += '.py' + # 只留文件名:用户选的路径里可能带 / 或 ..,不能让它写到别处 + fname = os.path.basename(fname.replace('\\', '/')) + if not fname or fname == '.py': + self.send_json(400, {'error': '文件名不对'}) + return True + if not code.strip(): + self.send_json(400, {'error': '这个文件是空的'}) + return True + + # ★ 先**试加载一遍**再落盘。 + # 直接写进去的话,用户导入一个写错的文件,节点列表里就多一个坏节点, + # 每次打开会议都看到它。先跑一遍能把错误**当场**告诉他, + # 而且原始报错不吞 —— 用户要照着那句报错去改代码。 + folder = _cn.nodes_dir() + try: + os.makedirs(folder, exist_ok=True) + except OSError as exc: + self.send_json(400, {'error': f'节点目录建不出来:{exc}'}) + return True + tmp = os.path.join(folder, '_import_check_.py') + try: + with open(tmp, 'w', encoding='utf-8') as fh: + fh.write(code) + chk = _cn.load_file(tmp) + finally: + try: + os.remove(tmp) + except OSError: + pass + if chk.get('error'): + self.send_json(400, {'error': chk['error']}) + return True + + target = os.path.join(folder, fname) + try: + with open(target, 'w', encoding='utf-8') as fh: + fh.write(code) + except OSError as exc: + self.send_json(400, {'error': f'写不进去:{exc}'}) + return True + self.send_json(200, { + 'ok': True, + 'file': fname, + 'label': chk.get('label') or fname, + 'key': chk.get('key') or '', + }) + return True + + if pathname.startswith('/api/meeting/nodes/') and method == 'DELETE': + import custom_nodes as _cn + import urllib.parse as _up + fname = os.path.basename( + _up.unquote(pathname[len('/api/meeting/nodes/'):]).replace('\\', '/')) + target = os.path.join(_cn.nodes_dir(), fname) + if not fname.endswith('.py') or not os.path.isfile(target): + self.send_json(404, {'error': '没有这个节点文件'}) + return True + try: + os.remove(target) + except OSError as exc: + self.send_json(400, {'error': f'删不掉:{exc}'}) + return True + self.send_json(200, {'ok': True}) + return True + if pathname == '/api/meeting/meta' and method == 'GET': # 编辑器要用:节点类型、判断条件、可用智能体 self.send_json(200, { diff --git a/tmp-msg-cn2.txt b/tmp-msg-cn2.txt deleted file mode 100644 index aa1f1fd..0000000 --- a/tmp-msg-cn2.txt +++ /dev/null @@ -1,69 +0,0 @@ -会议模式:自定义节点做完(用户的 node.txt 方案,全链路测通) - -用户:"直接做完并测试" - -【做了什么】 -把用户给的声明式方案落地成一种真正的节点类型: - - ToolName = { - "name": "打分", - "desc": "文字越长分越高", - "input": [{"type": "str", "name": "文本", "value": ""}], - "output": [{"type": "exec", "name": "高分"}, - {"type": "exec", "name": "低分"}, - {"type": "str", "name": "分数"}], - } - def run(ctx, node): - node["output"]["分数"] = "分数:" + str(len(node["input"]["文本"])) - node["output"]["高分"] = len(...) >= 3 - node["output"]["低分"] = len(...) < 3 - return node - -往 <数据目录>/nodes/ 丢一个 .py,会议里就多出一种节点。**不用改 Kotlin**。 - -【链路】 -1. custom_nodes.py:加载 / 校验 / 规整引脚 / 子线程跑(10 秒超时) -2. meeting.py:新增 `custom` 节点类型 - - 类型上下文里加载定义(_LAST_CUSTOM),连线时查声明决定收什么类型 - - 执行分支:按引脚收输入 -> run_custom -> 取第一个数据出口往下传 -3. app.py:/api/meeting/meta 带 customNodes(含 inputs/outputs)+ customDir -4. Kotlin:MeetingMeta.customNodes、CustomNodeDef/CustomPin、 - inputPins/outputPins 对 `custom` **从内核读引脚**、NodeCard 传 customDefs、 - 加节点面板顶部列出自定义节点(带 🐍 和文件名,坏的显示原因) -5. nodes-示例/:score.py(活文档)+ README.md(格式和三条规则) - -【三条语义(已在 README 和节点注释里写清楚,并实测)】 -1. node["input"][名] 是**引擎填的实际值**,声明里的 value 只是"没接线时的默认" -2. 多个 exec 出口 = **多路分支**,最多一个 True: - 恰好一个 → 走那条 - 都不 True → **停在原地** + 报警告(不猜、不顺走第一条) - 多个 True → 报错 -3. return 什么无所谓,引擎读 node["output"] - -【发现并修的坑(用户原版写不通的两处)】 -① 键必须加引号:`name:"..."` 是 JS 写法,Python 报 - "SyntaxError: invalid syntax. Perhaps you forgot a comma?" —— - 这句话完全看不出问题在哪。内核专门认出来并给出正确写法。 -② 声明是列表、访问是字典,对不上:声明 `input: [{...}]` 是列表, - 但 run 里写 `node["input"]["A1"]`(按名字取)。 - 解法:**引擎在跑之前把 input/output 换成按名字取的字典**, - 声明的列表原样留给引擎和界面读类型。 - -【实测(HTTP 全链路)】 - meta: 打分 key=custom_score exec 分支=['高分','低分'] - 保存后边数: 5/5(类型校验认识自定义节点的引脚) - 起点='好' → 执行 ev,sc,lo → 低分出口(分数:1) - 起点='这段文字比较长' → 执行 ev,sc,hi → 高分出口(分数:7) - 历史里也存了 results ✓ - -【限制(如实写在 README 里)】 -数据出口只有**第一个能接线** —— 边(edge)上没有"从哪个引脚出来"的信息。 -其余数据出口的值仍会显示在节点卡片上,只是接不了线。 -要修得给边加 fromPin/toPin,属于数据模型层面的改动。 - -【验证】 -- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致 -- 会议 HTTP 13/13 ×2、语音 41/41、Markdown 19/19 -- 自定义节点:加载 / 运行 / 写变量 / 记日志 / N 路分支 / 报错兜底 / 超时, - Python 侧和 HTTP 侧各测一遍 -- APK 构建通过 diff --git a/tmp-msg-mgr.txt b/tmp-msg-mgr.txt new file mode 100644 index 0000000..32f8c2b --- /dev/null +++ b/tmp-msg-mgr.txt @@ -0,0 +1,68 @@ +会议模式:自定义节点的导入 / 导出 / 现场编辑 / 搭积木 + +用户:"自定义节点可以导入导出也可以。也可以现场编辑,支持 py 或搭积木生成代码(像编程猫那样)" + +【原来只有一个"导入"】 +节点文件只能 adb push 进去 —— 那不叫能用。现在是一整套: + + 自定义节点(加节点面板 -> 「导入 / 管理节点…」) + 往这个目录放 .py 就多一种节点,界面上的引脚是从文件里读的: + /data/user/0/com.doubao.lynxclone/files/kernel-data/nodes + + + 新建 📥 导入文件 + ──────────────────────────────── + 🐍 打分 score.py + 文字越长分越高:够 3 分走「高分」,否则走「低分」 + 编辑 导出 删除 + +【内核新增三个接口】 + GET /api/meeting/nodes 列出全部(含加载失败的原因,坏的也列出来) + GET /api/meeting/nodes/ 读**源码**(现场编辑用) + POST /api/meeting/nodes 导入 / 保存 + DELETE /api/meeting/nodes/ 删除 + +★ POST 会**先试加载一遍再落盘**:直接写进去的话,用户导入一个写错的文件, + 节点列表里就多一个坏节点,每次开会都看见它。先跑一遍能把 Python 的报错 + **当场**回给界面,而且原始报错不吞 —— 用户要照着那句话去改代码。 +★ 文件名只留 basename:用户选的路径里可能带 / 或 ..,不能让它写到别处。 + +【现场编辑】 +代码框(可滚动)+ 文件名可改。保存走同一个 POST,所以同样有"先试加载"的保护。 + +【搭积木】 +「代码 / 搭积木」两个页签。积木面板有 12 块: + 📝 记一条日志 / 📤 设置文本输出 / 💾 写变量 / 📖 读输入 / 🔤 转大写 / + ✂️ 取前几个字 / 📏 文本长度 / ➕ 拼两段文本 / 🔀 如果…否则… / + 🔁 重复 N 次 / 🧩 遍历列表 / 🛡 试试看(出错不崩) +点一块就把对应的 Python 追加到代码末尾,下面实时显示"当前代码"。 + +★ 为什么不做 Scratch 那种拖拽画布: + 这里的产物最终是**代码**,代码编辑器本来就在旁边(同一个对话框里另一个页签)。 + 做成"点积木 -> 生成代码 -> 你接着改",生成的是**可读可改、能继续学**的普通 + Python,而不是一个封闭的图形。对新手:从零写不出来但知道要"记一条日志"; + 对老手:这些块就是快捷键,省得敲样板代码。 + 拖拽画布要自己实现吸附、嵌套、布局,收益主要是好看 —— 那是下一步的事。 + +【界面放在新文件里】 +MeetingsCustomNodes.kt(NodeManagerDialog / NodeEditDialog / 积木表)。 +MeetingsScreen.kt 已经 3800 行,往里塞东西每一次都要重新理解上下文, +而且改错了很难看出来 —— 这一轮就因为漏一个花括号排查了很久。 + +【顺带修的一个真 bug】 +加节点面板里导入那块 Column 少了一个 `}`(我写漏的), +导致 MeetingEditorScreen 不闭合、后面所有顶层声明全部"未解析" +(报的是 PrimaryButton / LinkFrom / canvasSize 找不到,看着完全不像是括号问题)。 +用括号计数脚本定位到的。这个排查手段以后可以常用。 + +【设备实测(emulator-5556)】 + 加节点面板:🐍 打分 score.py + 说明 ✓ + 节点管理:目录显示、新建/导入、编辑/导出/删除 ✓ + 编辑对话框:读到真实源码、代码/搭积木两个页签 ✓ + 搭积木:12 块积木、点击生成、当前代码实时预览 ✓ + 引擎:CUSTOMDIR / CUSTOMNODES / SAVED 5/5 / STEPS ['ev','sc','hi'] / + RESULTS [('高分出口','分数:7')] ✓ + +【验证】 +- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致 +- 会议 HTTP 13/13 +- APK 构建通过、装机通过、界面截图确认