diff --git a/backend/app/engine/nodes/human.py b/backend/app/engine/nodes/human.py index 9a1f7a04..5f64cc64 100644 --- a/backend/app/engine/nodes/human.py +++ b/backend/app/engine/nodes/human.py @@ -44,12 +44,20 @@ async def run_human(state: GraphState, ctx: NodeContext) -> dict[str, Any]: } if not approved and ctx.cfg("stop_on_reject", False): raise NodeError(ctx.node.id, f"人工拒绝:{result['note'] or '未说明原因'}") - elif mode == "edit": + else: # edit / input + # 驳回在这两种模式下以前是个摆设:__decision__ 硬编码成 approved, + # approved 字段看都不看。界面上按钮在、toast 说"已驳回",运行却照常 + # 往下走——比没有这个按钮更糟。 + # + # 这两种模式在图上只有一个 out 出口(没有 rejected 那条边),所以驳回 + # 的正确语义是终止运行,而不是当作通过继续。缺省仍是通过:只传 value + # 不带 approved 的老调用方行为不变。 + rejected = isinstance(response, dict) and response.get("approved") is False + if rejected: + note = _note_of(response) + raise NodeError(ctx.node.id, f"人工驳回:{note or '未说明原因'}") value = response.get("value") if isinstance(response, dict) else response result = {"value": value, "note": _note_of(response), "__decision__": "approved"} - else: # input - value = response.get("value") if isinstance(response, dict) else response - result = {"value": value, "__decision__": "approved"} updates: dict[str, Any] = {"nodes": {ctx.node.id: result}} var_name = ctx.cfg("assign_to", "") diff --git a/backend/app/engine/runner.py b/backend/app/engine/runner.py index 5dba5e5c..106ebadd 100644 --- a/backend/app/engine/runner.py +++ b/backend/app/engine/runner.py @@ -17,7 +17,7 @@ from app.core.events import EventType, RunEventModel from app.db.base import SessionLocal from app.db.models import Approval, Run, RunEvent, Workflow from app.engine.compiler import compile_graph, initial_state -from app.engine.context import RunContext +from app.engine.context import NodeError, RunContext from app.engine.schema import GraphSpec, validate_graph logger = logging.getLogger(__name__) @@ -373,7 +373,9 @@ class RunManager: raise except Exception as e: # noqa: BLE001 status = "failed" - error = f"{type(e).__name__}: {e}" + # NodeError 的 message 本来就是写给人看的("人工驳回:…"), + # 再套一层类型名只会让界面上的错误更难读 + error = str(e) if isinstance(e, NodeError) else f"{type(e).__name__}: {e}" logger.exception("run %s 失败", run_id) await self._emit(run_id, EventType.RUN_FAILED, data={"error": error}) finally: diff --git a/frontend/src/pages/RunsPage.tsx b/frontend/src/pages/RunsPage.tsx index 98994875..efce30a2 100644 --- a/frontend/src/pages/RunsPage.tsx +++ b/frontend/src/pages/RunsPage.tsx @@ -4,6 +4,8 @@ import clsx from 'clsx' import { api } from '../api/client' import { formatMs } from '../canvas/NodeCard' import { Empty, Spinner, StatusDot, useToast } from '../components/ui' +import { ApprovalCard } from '../run/RunPanel' +import { useCatalog } from '../store/catalog' import type { Run, RunEvent } from '../types' /** 运行历史。每次运行的完整事件流都落了库,所以这里能完整回放。 */ @@ -14,6 +16,11 @@ export function RunsPage() { const [events, setEvents] = useState([]) const [loading, setLoading] = useState(true) const [filter, setFilter] = useState('') + // 导航上的待办徽标指向这一页,所以这页必须能处理待办 + const approvals = useCatalog((s) => s.approvals) + const pendingHere = approvals.filter( + (a) => a.run_id === selected?.id && a.status === 'pending', + ) const load = async () => { setLoading(true) @@ -120,6 +127,15 @@ export function RunsPage() { + {/* 等待人工的运行要能就地处理。导航上的待办徽标指向这一页, + 而这里以前只有只读的事件列表——刷新页面后那些卡在审批上的 + 运行在整个界面里没有任何入口可以推进。 */} + {pendingHere.length > 0 && ( +
+ {pendingHere.map((a) => )} +
+ )} + {selected.error && (
diff --git a/frontend/src/pages/StudioPage.tsx b/frontend/src/pages/StudioPage.tsx
index b46f64d5..75d9ddfa 100644
--- a/frontend/src/pages/StudioPage.tsx
+++ b/frontend/src/pages/StudioPage.tsx
@@ -68,6 +68,17 @@ export function StudioPage() {
     return () => window.removeEventListener('keydown', onKey)
   }, [doSave])
 
+  // 有未保存改动时拦一下关标签页/刷新。画布没有撤销栈,关掉就真没了。
+  useEffect(() => {
+    if (!dirty) return
+    const guard = (e: BeforeUnloadEvent) => {
+      e.preventDefault()
+      e.returnValue = ''
+    }
+    window.addEventListener('beforeunload', guard)
+    return () => window.removeEventListener('beforeunload', guard)
+  }, [dirty])
+
   const errorCount = issues.filter((i) => i.level === 'error').length
   const warnCount = issues.filter((i) => i.level === 'warning').length
 
@@ -236,7 +247,18 @@ function WorkflowPicker({ open, onClose }: { open: boolean; onClose: () => void
               'group flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2 hover:bg-hover',
               current?.id === w.id && 'border-[var(--accent)]',
             )}
-            onClick={() => { load(w); onClose() }}
+            onClick={() => {
+              // 切换会把当前画布整个换掉。没存过的改动就这么没了,
+              // 而且全局没有撤销——至少问一句
+              if (
+                useStudio.getState().dirty &&
+                !confirm('当前画布有未保存的改动,切换后会丢失。确定要切换吗?')
+              ) {
+                return
+              }
+              load(w)
+              onClose()
+            }}
           >
             
diff --git a/frontend/src/run/RunPanel.tsx b/frontend/src/run/RunPanel.tsx index b2f6cf91..3943d736 100644 --- a/frontend/src/run/RunPanel.tsx +++ b/frontend/src/run/RunPanel.tsx @@ -172,7 +172,7 @@ function RunLauncher() { // ------------------------------------------------------------------------- -function ApprovalCard({ approval }: { approval: any }) { +export function ApprovalCard({ approval }: { approval: any }) { const toast = useToast() const refreshApprovals = useCatalog((s) => s.refreshApprovals) const attachRun = useStudio((s) => s.attachRun) @@ -193,7 +193,16 @@ function ApprovalCard({ approval }: { approval: any }) { }) await refreshApprovals() await attachRun(approval.run_id) // 恢复后重新接上事件流 - toast(approved ? '已放行,运行继续' : '已驳回', 'ok') + // 驳回在"补充输入/编辑草稿"模式下会终止整个运行(图上没有 rejected 那条 + // 出口边),说清楚比笼统一句"已驳回"诚实 + toast( + approved + ? '已放行,运行继续' + : approval.mode === 'approve' + ? '已驳回' + : '已驳回,本次运行终止', + 'ok', + ) } catch (e: any) { toast(e.message ?? '操作失败', 'error') } finally { @@ -251,8 +260,13 @@ function ApprovalCard({ approval }: { approval: any }) { -
diff --git a/frontend/src/store/studio.ts b/frontend/src/store/studio.ts index 937b755e..7a042fa8 100644 --- a/frontend/src/store/studio.ts +++ b/frontend/src/store/studio.ts @@ -4,7 +4,7 @@ import { type Connection, type Edge, type EdgeChange, type Node, type NodeChange, } from '@xyflow/react' import { api, streamCopilot, streamRun } from '../api/client' -import { NODE_DEFS } from '../canvas/nodeDefs' +import { NODE_DEFS, sourceHandles } from '../canvas/nodeDefs' import type { GraphEdge, GraphSpec, NodeRuntime, NodeType, Run, RunEvent, ValidationIssue, Workflow, } from '../types' @@ -175,6 +175,37 @@ export const useStudio = create((set, get) => ({ }, updateNode: (id, patch) => { + const target = get().nodes.find((n) => n.id === id) + // 出口 handle 是从 config 算出来的(分支的 case key、human 的 mode), + // 改 config 就可能让已连好的边指向一个不存在的出口。React Flow 对这种边 + // 只在 console 打一条 008 警告然后不渲染——它看不见、点不到、删不掉, + // 却照样被 toGraph 序列化存盘。所以这里同步把边跟过去。 + const before = target ? sourceHandles(target.data.nodeType, target.data.config ?? {}) : [] + const after = + target && patch.config !== undefined + ? sourceHandles(target.data.nodeType, patch.config) + : before + + let edges = get().edges + if (target && before.length && after !== before) { + const alive = new Set(after.map((h) => h.id)) + // 改名场景(出口数量没变)按位置重映射,这样连好的线不会白连 + const byPosition = new Map() + if (before.length === after.length) { + before.forEach((h, i) => { + if (h.id !== after[i].id) byPosition.set(h.id, after[i].id) + }) + } + edges = edges.flatMap((e) => { + if (e.source !== id || !e.sourceHandle) return [e] + if (alive.has(e.sourceHandle)) return [e] + const moved = byPosition.get(e.sourceHandle) + // 出口真的没了(删了一个 case、换了 human 模式)就把边一起去掉, + // 留着只会变成一条谁也看不见的脏边 + return moved ? [{ ...e, sourceHandle: moved }] : [] + }) + } + set({ nodes: get().nodes.map((n) => n.id === id @@ -188,6 +219,7 @@ export const useStudio = create((set, get) => ({ } : n, ), + edges, dirty: true, }) void get().validate()