From 3a9d49ddc3d93aeae4ac2265277de38b822721d4 Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 11:46:00 +0800 Subject: [PATCH 1/8] fix(v2): refuse Loop references the engine never assigns at publish The engine publishes only a Loop's named outputs to the outer scope (as desktop loop_round.rs exit_outputs does), resolves its loop variables only inside the body, and never assigns a body's round Start. Publication still declared `{loop}.output` and checked only that a producer was visible, so a graph saved with `loop-1.output` or `loop-1-start.input` published fine and failed at runtime as "unassigned". Publication now rejects such selector, template and aggregator references as invalid_loop_reference on the consuming node, and the static catalog no longer declares `{loop}.output`. This is stricter than desktop, recorded in the README. Refs ora-space/circus#1388 --- v2-server/README.md | 2 +- v2-server/internal/workflow/README.md | 3 + v2-server/internal/workflow/declarations.go | 3 +- .../internal/workflow/loop_references.go | 111 ++++++++++++++++++ .../internal/workflow/loop_references_test.go | 60 ++++++++++ v2-server/internal/workflow/validate.go | 23 ++-- 6 files changed, 185 insertions(+), 17 deletions(-) create mode 100644 v2-server/internal/workflow/loop_references.go create mode 100644 v2-server/internal/workflow/loop_references_test.go diff --git a/v2-server/README.md b/v2-server/README.md index baa62c0ca..6d67cbccb 100644 --- a/v2-server/README.md +++ b/v2-server/README.md @@ -622,7 +622,7 @@ not execute these kinds: `crates/application/src/workflow_run/engine/node_type.r 图规则不属于 HTTP 层:`server.Options.AnalyzeWorkflow` 提供草稿分析,`Options.ValidateWorkflow` 提供发布前的可执行性校验,两者由工作流领域注入;未注入时定义读写照常,分析和发布返回 `503 workflow_domain_unavailable`,不会把未校验的文档伪装成可运行版本。 -与 desktop 的明确差异:v2 以租户代替 desktop 的单一 `local` 命名空间,`namespace` 恒为 `local`;重名改为由数据库唯一索引拒绝并映射为 409(desktop 并发重名可能返回 500);发布校验放在事务内(desktop 存在校验与冻结之间的 TOCTOU);软删记录 `deleted_at`(desktop 丢弃快照删除时间);版本列表在同一毫秒内用 id 兜底排序;名称唯一性用 PostgreSQL `lower()`,比 desktop 的 ASCII `NOCASE` 范围更宽。 +与 desktop 的明确差异:v2 以租户代替 desktop 的单一 `local` 命名空间,`namespace` 恒为 `local`;重名改为由数据库唯一索引拒绝并映射为 409(desktop 并发重名可能返回 500);发布校验放在事务内(desktop 存在校验与冻结之间的 TOCTOU);软删记录 `deleted_at`(desktop 丢弃快照删除时间);版本列表在同一毫秒内用 id 兜底排序;名称唯一性用 PostgreSQL `lower()`,比 desktop 的 ASCII `NOCASE` 范围更宽;发布另外拒绝引擎永远不会赋值的 Loop 引用(`invalid_loop_reference`):Loop 外引用它的命名输出以外的变量(如旧图里的 `{loop}.output`),循环体内引用 Loop 的循环变量以外的变量,或引用轮次 Start 的变量。desktop 接受这类图,运行到该节点才以变量未赋值失败。 ### 工作流运行历史 diff --git a/v2-server/internal/workflow/README.md b/v2-server/internal/workflow/README.md index e6c94999b..a09ff9e7c 100644 --- a/v2-server/internal/workflow/README.md +++ b/v2-server/internal/workflow/README.md @@ -19,6 +19,8 @@ err = workflow.ValidateWorkflow(graph) `ValidateWorkflow` 继续检查可达图的节点配置、DAG、Start 和全局声明、Aggregator / Iteration 派生类型、 Loop 配置及作用域,以及对被排除节点的变量引用。备用节点配置不参与检查,但无效身份、边和归属不能被过滤隐藏。 已知的历史 `prompt` / `tool` 类型沿用 desktop 的可解析行为;解析通过不代表运行时支持这些节点。 +另外,`ValidateWorkflow` 比 desktop 多拒绝一类引擎永远不会赋值的 Loop 引用(`invalid_loop_reference`,指向引用它的节点): +Loop 外只能读命名输出(没有 `{loop}.output`),循环体内只能读 Loop 的循环变量,轮次 Start 不提供变量。 发布边界对应 `WorkflowGraph::parse`,启动边界另外调用 `validate_executable_graph`。 例如缺少 Start 的平面图、未指定本机可用执行器的 Agent 仍可能通过发布校验。 @@ -41,6 +43,7 @@ HTTP 错误码由适配层映射;诊断措辞不承诺逐字匹配 desktop。 | `document_test.go` | 编排投影、无效结构、未知类型、备用节点重新接入、无效引用、发布与启动校验边界 | | `config_test.go` | Start / 全局声明、Agent 策略和 schema、Condition / Output 历史格式、Aggregator 拓扑及类型 | | `container_test.go` | Loop 轮次上限、携带值与可见性;Iteration 归属、输入 / 收集类型及边界 | +| `loop_references_test.go` | Loop 外只读命名输出、循环体内只读循环变量、轮次 Start 无变量;选择器、模板与聚合候选都指向引用节点 | | `testdata/spare-chain.json`、`testdata/iteration.json` | 改编自 desktop `execution_document/tests.rs` | | `testdata/loop.json` | 改编自 desktop `loop_graph/tests.rs` | | `condition_test.go` | Condition 的 case 顺序、空 case、and/or、各运算符、比较值模板与失败(改编自 desktop `condition.rs`) | diff --git a/v2-server/internal/workflow/declarations.go b/v2-server/internal/workflow/declarations.go index dd932fbd0..49bb574b0 100644 --- a/v2-server/internal/workflow/declarations.go +++ b/v2-server/internal/workflow/declarations.go @@ -24,7 +24,8 @@ func (s *scope) validateDeclarations(globals map[string]string) error { for name, typ := range n.inputs { declare(n, name, typ) } - case "condition", "iteration", "aggregator": + // A Loop publishes only its named outputs (below), never an `output`. + case "condition", "iteration", "aggregator", "loop": default: declare(n, "output", "string") } diff --git a/v2-server/internal/workflow/loop_references.go b/v2-server/internal/workflow/loop_references.go new file mode 100644 index 000000000..62002cb1c --- /dev/null +++ b/v2-server/internal/workflow/loop_references.go @@ -0,0 +1,111 @@ +package workflow + +import ( + "sort" + "strings" +) + +// validateLoopReferences rejects references the engine can never assign, so authors learn at +// publication, with the consumer named, what would otherwise fail at runtime as "unassigned". +// The engine publishes only a Loop's named outputs to the outer scope (desktop loop_round.rs +// exit_outputs), resolves its carried variables only inside its body, and never assigns +// anything to a body's round Start. A Loop's own configuration is validated by +// validateLoopBindings and is skipped here. +func validateLoopReferences(d *document) error { + type loopNames struct{ outputs, variables map[string]bool } + loops := map[string]loopNames{} + for _, n := range d.nodes { + if !d.active[n.id] || n.kind != "loop" { + continue + } + cfg, _ := (Node{data: n.data}).loopConfig() // validateNode already checked the shape. + names := loopNames{outputs: map[string]bool{}, variables: map[string]bool{}} + for _, output := range cfg.Outputs { + names.outputs[output.Name] = true + } + for _, variable := range cfg.Variables { + names.variables[variable.Name] = true + } + loops[n.id] = names + } + if len(loops) == 0 { + return nil + } + check := func(n *node, field string, parts []string) error { + producer := d.byID[parts[0]] + if producer == nil || producer == n || len(parts) < 2 { + return nil + } + selected := strings.Join(parts, ".") + if producer.kind == "start" && producer.container { + return invalid("invalid_loop_reference", n.id, field, + "round Start "+producer.id+" assigns no variables; "+selected+" is never set, read the Loop's variables instead") + } + names, isLoop := loops[producer.id] + if !isLoop { + return nil + } + if n.container && n.owner == producer.id { + if !names.variables[parts[1]] { + return invalid("invalid_loop_reference", n.id, field, + "inside Loop "+producer.id+" only its loop variables ("+listNames(names.variables)+") are readable; "+selected+" is not one") + } + return nil + } + if !names.outputs[parts[1]] { + return invalid("invalid_loop_reference", n.id, field, + "Loop "+producer.id+" publishes only its named outputs ("+listNames(names.outputs)+"); "+selected+" is not one") + } + return nil + } + for _, n := range d.nodes { + if !d.active[n.id] || n.kind == "loop" { + continue + } + for _, parts := range n.selectors { + if err := check(n, "selector", parts); err != nil { + return err + } + } + for _, text := range n.templates { + for _, parts := range templateSelectors(text) { + if err := check(n, "template", parts); err != nil { + return err + } + } + } + } + return nil +} + +// templateSelectors lists the qualified `{{#node.variable#}}` references in one template. +// Malformed templates are diagnosed at execution, as on desktop. +func templateSelectors(text string) [][]string { + var result [][]string + for { + _, after, found := strings.Cut(text, "{{#") + if !found { + return result + } + selected, rest, closed := strings.Cut(after, "#}}") + if !closed { + return result + } + if strings.Contains(selected, ".") { + result = append(result, strings.Split(selected, ".")) + } + text = rest + } +} + +func listNames(names map[string]bool) string { + if len(names) == 0 { + return "none" + } + sorted := make([]string, 0, len(names)) + for name := range names { + sorted = append(sorted, name) + } + sort.Strings(sorted) + return strings.Join(sorted, ", ") +} diff --git a/v2-server/internal/workflow/loop_references_test.go b/v2-server/internal/workflow/loop_references_test.go new file mode 100644 index 000000000..65000d50c --- /dev/null +++ b/v2-server/internal/workflow/loop_references_test.go @@ -0,0 +1,60 @@ +package workflow_test + +import ( + "errors" + "strings" + "testing" + + "github.com/wanglongan587/cloud/v2-server/internal/workflow" +) + +// The engine publishes only a Loop's named outputs and never assigns its round Start, so +// references the editor used to offer must be refused at publication, naming the consumer. +func TestLoopReferences(t *testing.T) { + outer := func(selector ...string) func(obj) { + return func(g obj) { + addNode(g, "out", "output", obj{"outputs": []any{obj{"name": "r", "variableSelector": selector}}}) + connect(g, "loop", "out") + } + } + body := func(prompt string) func(obj) { + return func(g obj) { dataOf(g, "writer")["agentConfig"].(obj)["prompt"] = prompt } + } + for _, test := range []struct { + name string + edit func(obj) + nodeID string // empty when the graph is valid + reason string + }{ + {"outer named output", outer("loop", "result"), "", ""}, + {"outer loop.output", outer("loop", "output"), "out", "publishes only its named outputs (result); loop.output"}, + {"outer loop variable", outer("loop", "draft"), "out", "loop.draft is not one"}, + {"outer template loop.output", func(g obj) { + addNode(g, "after", "agent", obj{"agentConfig": obj{"executor": obj{"agentCli": "claude", "modelId": "model"}, "prompt": "Use {{#loop.output#}}"}}) + connect(g, "loop", "after") + }, "after", "publishes only its named outputs"}, + {"outer aggregator loop.output", func(g obj) { + addNode(g, "agg", "aggregator", obj{"aggregatorConfig": obj{"variables": []any{[]string{"loop", "output"}}}}) + connect(g, "loop", "agg") + }, "agg", "publishes only its named outputs"}, + {"body loop variable", body("Improve {{#loop.draft#}} for {{#start.input#}}"), "", ""}, + {"body loop output", body("Improve {{#loop.result#}}"), "writer", "only its loop variables (draft) are readable; loop.result"}, + {"body round start input", body("Improve {{#entry.input#}}"), "writer", "round Start entry assigns no variables"}, + } { + t.Run(test.name, func(t *testing.T) { + g := fixture(t, "loop") + test.edit(g) + err := workflow.ValidateWorkflow(encode(t, g)) + if test.nodeID == "" { + if err != nil { + t.Fatalf("expected a publishable graph, got %v", err) + } + return + } + var domain *workflow.ValidationError + if !errors.As(err, &domain) || domain.Code != "invalid_loop_reference" || domain.NodeID != test.nodeID || !strings.Contains(domain.Reason, test.reason) { + t.Fatalf("expected invalid_loop_reference on %s mentioning %q, got %v", test.nodeID, test.reason, err) + } + }) + } +} diff --git a/v2-server/internal/workflow/validate.go b/v2-server/internal/workflow/validate.go index 17703213f..f9c1cf3de 100644 --- a/v2-server/internal/workflow/validate.go +++ b/v2-server/internal/workflow/validate.go @@ -1,7 +1,5 @@ package workflow -import "strings" - type scope struct { id string nodes []*node @@ -54,6 +52,11 @@ func buildScopes(d *document) (map[string]*scope, error) { if err != nil { return nil, err } + // Before scope typing, so a stale Loop reference names its consumer instead of surfacing + // as an undeclared aggregator candidate. + if err := validateLoopReferences(d); err != nil { + return nil, err + } for _, e := range d.edges { if !d.active[e.source] || !d.active[e.target] { continue @@ -112,20 +115,10 @@ func buildScopes(d *document) (map[string]*scope, error) { } } for _, text := range n.templates { - for { - _, after, found := strings.Cut(text, "{{#") - if !found { - break - } - selected, rest, closed := strings.Cut(after, "#}}") - if !closed { - break - } // Malformed templates are diagnosed at execution, as on desktop. - producer, _, qualified := strings.Cut(selected, ".") - if qualified && d.unused[producer] { - return nil, invalid("unused_reference", n.id, "template", "template references unused node "+producer) + for _, parts := range templateSelectors(text) { + if d.unused[parts[0]] { + return nil, invalid("unused_reference", n.id, "template", "template references unused node "+parts[0]) } - text = rest } } } From 957a3674a3bff9a35f50628732f79249affb17bb Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 11:46:19 +0800 Subject: [PATCH 2/8] fix(v2): offer a Loop's named outputs and loop variables in the variable catalog The editor catalog offered `{loop}.output` to consumers after a Loop and only the round Start's `input` inside it; the engine assigns neither, so every workflow configured from the picker failed at runtime. Following the owner's decision (fix the catalog, not the engine), Loops now work the way Iteration already does: outer consumers see the Loop's named `loopConfig.outputs` (typed `any`, as the backend declares them, so aggregator typing agrees); body members see the loop variables, their in-body upstream, and what the Loop itself sees (e.g. `start.input`); the round Start contributes nothing. Desktop shares this catalog (packages/workflow-mock/src/variable-catalog.ts) and the same bug; it is left for the desktop comparison. Refs ora-space/circus#1388 --- .../workflows/mock/variable-catalog.test.ts | 96 ++++++++++++++++ .../lib/workflows/mock/variable-catalog.ts | 106 ++++++++++++++---- 2 files changed, 181 insertions(+), 21 deletions(-) diff --git a/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts b/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts index 8f23674de..a0458ffae 100644 --- a/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts +++ b/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import type { Edge, Node } from "@xyflow/react"; import { deriveWorkflowVariableCatalog } from "./variable-catalog"; +import { createMockWorkflowLoopGroup } from "./node-factory"; import type { WorkflowNodeData } from "./node-data"; function node( @@ -285,3 +286,98 @@ describe("deriveWorkflowVariableCatalog aggregator typing", () => { ).toBe("string"); }); }); + +describe("deriveWorkflowVariableCatalog loop scope rules", () => { + // The editor's own Loop group: a round Start and an Agent fed back as `value`, + // exported as the named output `result`. + const group = createMockWorkflowLoopGroup({ + sequence: 1, + position: { x: 0, y: 0 }, + locale: "zh-CN", + }); + const [loop, roundStart, loopAgent] = group.nodes as [ + Node, + Node, + Node, + ]; + const loopStart = node("start", { + kind: "start", + title: "Start", + description: "", + inputVariables: [{ name: "topic", valueType: "string" }], + }); + const after = node("after", { kind: "output", title: "After", description: "" }); + const nodes = [loopStart, loop, roundStart, loopAgent, after]; + const edges: Edge[] = [ + { id: "s-l", source: "start", target: loop.id }, + ...group.edges, + { id: "l-a", source: loop.id, target: "after" }, + ]; + const selectors = (consumer: string): string[] => + deriveWorkflowVariableCatalog(nodes, edges, consumer, []).map((entry) => + entry.selector.join("."), + ); + + it("offers outer consumers the named outputs, never loop.output", () => { + const visible = selectors("after"); + expect(visible).toContain(`${loop.id}.result`); + expect(visible).not.toContain(`${loop.id}.output`); + // Neither loop variables nor body products leak out of the Loop. + expect(visible).not.toContain(`${loop.id}.value`); + expect(visible).not.toContain(`${loopAgent.id}.output`); + expect(visible).not.toContain(`${roundStart.id}.input`); + expect(visible).toEqual( + expect.arrayContaining(["start.input", "start.topic"]), + ); + }); + + it("types named outputs as any, as the backend declares them", () => { + const result = deriveWorkflowVariableCatalog(nodes, edges, "after", []).find( + (entry) => entry.selector.join(".") === `${loop.id}.result`, + ); + expect(result?.valueType).toBe("any"); + }); + + it("offers body members the loop variables and the Loop's upstream", () => { + const visible = selectors(loopAgent.id); + expect(visible).toEqual( + expect.arrayContaining([`${loop.id}.value`, "start.input", "start.topic"]), + ); + // The round Start assigns nothing; the Loop's exposed outputs are not yet produced. + expect(visible).not.toContain(`${roundStart.id}.input`); + expect(visible).not.toContain(`${loop.id}.result`); + expect(visible).not.toContain(`${loop.id}.output`); + const value = deriveWorkflowVariableCatalog(nodes, edges, loopAgent.id, []).find( + (entry) => entry.selector.join(".") === `${loop.id}.value`, + ); + expect(value?.valueType).toBe("string"); + }); + + it("shares in-body products between body members only", () => { + const reviewer = node( + "reviewer", + { + kind: "agent", + title: "Review", + description: "", + containerId: loop.id, + }, + loop.id, + ); + const visible = deriveWorkflowVariableCatalog( + [...nodes, reviewer], + [...edges, { id: "a-r", source: loopAgent.id, target: "reviewer" }], + "reviewer", + [], + ).map((entry) => entry.selector.join(".")); + expect(visible).toContain(`${loopAgent.id}.output`); + expect(visible).toContain(`${loop.id}.value`); + }); + + it("lists no round Start variables when the Loop panel derives body candidates", () => { + const body = deriveWorkflowVariableCatalog([roundStart, loopAgent], [], undefined, []); + expect(body.map((entry) => entry.selector.join("."))).toEqual([ + `${loopAgent.id}.output`, + ]); + }); +}); diff --git a/frontend-v2/src/lib/workflows/mock/variable-catalog.ts b/frontend-v2/src/lib/workflows/mock/variable-catalog.ts index ccbcd412f..4de2e5f5e 100644 --- a/frontend-v2/src/lib/workflows/mock/variable-catalog.ts +++ b/frontend-v2/src/lib/workflows/mock/variable-catalog.ts @@ -52,6 +52,12 @@ function arrayElementType(valueType: string): string { * `item`/`index` round bindings plus their in-region upstream products, but never the * iteration's own exposed results; outer consumers see the three exposed variables * (`output`, `entries`, `failed_count`) whose types stay fixed across error strategies. + * + * Loops follow the same shape, matching the engine, which publishes only a Loop's named + * `loopConfig.outputs` and never a `{loop}.output`: outer consumers see those named outputs; + * body members see the carried loop variables, their in-body upstream products, and every + * variable visible to the Loop itself (its upstream, e.g. `start.input`). A body's round + * Start assigns nothing, so it contributes no variables. */ export function deriveWorkflowVariableCatalog( nodes: Array>, @@ -59,10 +65,34 @@ export function deriveWorkflowVariableCatalog( consumerNodeId?: string, globalVariables: WorkflowGlobalVariable[] = DEFAULT_WORKFLOW_GLOBAL_VARIABLES, ): WorkflowVariableCatalogEntry[] { - const visibleProducerIds = - consumerNodeId === undefined - ? new Set(nodes.map((node) => node.id)) - : collectVisibleProducerIds(nodes, edges, consumerNodeId); + // Container membership: Iteration members by `parentId` (as the frozen graph persists it), + // Loop members by `data.containerId` with `parentId` as the legacy fallback. + const kindById = new Map(nodes.map((node) => [node.id, node.data.kind])); + const owningContainerOf = (nodeId: string): string | null => { + const member = nodes.find((node) => node.id === nodeId); + const owner = member?.data.containerId ?? member?.parentId; + const kind = owner === undefined ? undefined : kindById.get(owner); + return kind === "iteration" || kind === "loop" ? owner! : null; + }; + const consumerOwner = + consumerNodeId === undefined ? null : owningContainerOf(consumerNodeId); + const consumerLoopId = + consumerOwner !== null && kindById.get(consumerOwner) === "loop" + ? consumerOwner + : null; + + let visibleProducerIds: Set; + if (consumerNodeId === undefined) { + visibleProducerIds = new Set(nodes.map((node) => node.id)); + } else { + visibleProducerIds = collectVisibleProducerIds(nodes, edges, consumerNodeId); + // A Loop body has no edge from outside: its round pool inherits what the Loop sees. + if (consumerLoopId !== null) { + for (const id of collectVisibleProducerIds(nodes, edges, consumerLoopId)) { + visibleProducerIds.add(id); + } + } + } const entries = globalVariables.flatMap(globalVariableCatalogEntry); // Aggregator outputs are typed by their candidate selectors (backend parse rule: all @@ -72,22 +102,16 @@ export function deriveWorkflowVariableCatalog( globalVariables, ); - // Iteration membership: `parentId` containment, as the frozen graph persists it. - const iterationIds = new Set( - nodes - .filter((node) => node.data.kind === "iteration") - .map((node) => node.id), - ); - const owningIterationOf = (nodeId: string): string | null => { - const parent = nodes.find((node) => node.id === nodeId)?.parentId; - return parent !== undefined && iterationIds.has(parent) ? parent : null; - }; - for (const node of nodes) { if (node.data.kind === "start") { if (!visibleProducerIds.has(node.id) || node.id === consumerNodeId) { continue; } + // A Loop's round Start only marks the body entry; the engine never assigns its + // `input` or declared fields, so offering them would fail every run. + if (node.data.containerId !== undefined) { + continue; + } // `start.input` is the initial prompt value. It is always declared, even before a run // supplies text, so downstream configuration can reference the stable selector. entries.push(nodeVariable(node, "input", "string")); @@ -112,14 +136,22 @@ export function deriveWorkflowVariableCatalog( ); continue; } + if (node.data.kind === "loop") { + appendLoopVariables( + entries, + node, + consumerNodeId, + consumerLoopId, + visibleProducerIds, + ); + continue; + } if (!visibleProducerIds.has(node.id) || node.id === consumerNodeId) { continue; } - // A region member's products stay region-visible only: the consumer sees them when it - // shares the same region, never from outside. - const consumerOwner = - consumerNodeId === undefined ? null : owningIterationOf(consumerNodeId); - const producerOwner = owningIterationOf(node.id); + // A container member's products stay container-visible only: the consumer sees them + // when it shares the same container, never from outside. + const producerOwner = owningContainerOf(node.id); if ( producerOwner !== null && consumerOwner !== producerOwner && @@ -167,7 +199,6 @@ export function deriveWorkflowVariableCatalog( case "tool": case "junction": case "human": - case "loop": case "subflow": break; } @@ -175,6 +206,35 @@ export function deriveWorkflowVariableCatalog( return entries; } +/** + * Adds one Loop's variables by consumer scope: carried loop variables for its body members, + * named outputs for visible outer consumers. Named outputs are typed `any`, as the backend + * declares them, so aggregator candidate typing agrees with publication. + */ +function appendLoopVariables( + entries: WorkflowVariableCatalogEntry[], + node: Node, + consumerNodeId: string | undefined, + consumerLoopId: string | null, + visibleProducerIds: Set, +): void { + const config = node.data.loopConfig; + if (consumerLoopId === node.id) { + for (const variable of config?.variables ?? []) { + entries.push(nodeVariable(node, variable.name, variable.valueType)); + } + return; + } + if (!visibleProducerIds.has(node.id) || node.id === consumerNodeId) { + return; + } + for (const output of config?.outputs ?? []) { + if (output.name.trim() !== "") { + entries.push(nodeVariable(node, output.name, "any")); + } + } +} + /** Adds one iteration node's round bindings and exposed results by consumer scope. */ function appendIterationVariables( entries: WorkflowVariableCatalogEntry[], @@ -369,6 +429,10 @@ function selectorDeclaredType( if (owner.data.kind === "aggregator") { return aggregatorOutputTypes.get(nodeId) ?? "any"; } + if (owner.data.kind === "loop") { + // The backend declares named Loop outputs as `any`; `{loop}.output` does not exist. + return "any"; + } if (owner.data.kind === "iteration") { const config = owner.data.iterationConfig; if (variableName === "output" && config !== undefined) { From 3d806e42e69f4a6c9748634df1cb30fe3b7d7a41 Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 11:46:19 +0800 Subject: [PATCH 3/8] fix(v2): keep a refused publish in its dialog and name the refused node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A refused publish closed the dialog and left only the list-level "工作流图无法 解析,请检查后再保存。", which spoke of saving and named nothing. v2-server now returns the domain's node, field and reason as the params of 400 workflow_run_graph_parse (read through a FaultParams method so the HTTP layer still does not import the domain). The publish dialog stays open while publishing and, on failure, says the publish was rejected, names the node by its title and the field in the author's terms, and shows the server's reason; other refusals keep their own message under a 发布失败 prefix. Refs ora-space/circus#1388 --- .../workflows/editor/workflow-editor.tsx | 44 ++++++++-- .../editor/workflow-publish-error.test.ts | 75 +++++++++++++++++ .../editor/workflow-publish-error.ts | 83 +++++++++++++++++++ .../src/features/workflows/page.test.tsx | 36 +++++++- .../src/lib/workflows/editor/translations.ts | 46 ++++++++++ v2-server/README.md | 2 + v2-server/internal/server/workflows.go | 9 +- v2-server/internal/server/workflows_test.go | 21 ++++- v2-server/internal/workflow/README.md | 1 + v2-server/internal/workflow/workflow.go | 14 ++++ 10 files changed, 323 insertions(+), 8 deletions(-) create mode 100644 frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts create mode 100644 frontend-v2/src/features/workflows/editor/workflow-publish-error.ts diff --git a/frontend-v2/src/features/workflows/editor/workflow-editor.tsx b/frontend-v2/src/features/workflows/editor/workflow-editor.tsx index 97ff91717..357085b22 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-editor.tsx +++ b/frontend-v2/src/features/workflows/editor/workflow-editor.tsx @@ -94,6 +94,10 @@ import { useAgents } from "@/lib/workflows/data/catalog-hooks"; import { availableSkills, useSkills } from "@/lib/workflows/data/catalog-hooks"; import { useWorkflowAgentModels } from "@/lib/workflows/data/catalog-hooks"; import { localizeContractError } from "@/lib/workflows/host/contract-error"; +import { + describePublishFailure, + type WorkflowPublishFailure, +} from "./workflow-publish-error"; import { WorkflowCanvas } from "./workflow-canvas"; import { authoredWorkflowNodesEqual, @@ -564,6 +568,9 @@ function WorkflowEditorContent({ const [globalVariablesDialogOpen, setGlobalVariablesDialogOpen] = useState(false); const [publishVersionName, setPublishVersionName] = useState(""); + // A refused publish stays in its dialog, so the author sees it was the publish, not a save. + const [publishFailure, setPublishFailure] = + useState(null); const inspectorPanelRef = useRef(null); const inspectorAnimationRef = useRef(null); /** Bumps on every persistable edit so in-flight writes can detect they are stale. */ @@ -1459,6 +1466,7 @@ function WorkflowEditorContent({ if (previewedVersionRef.current !== null) { setPreviewedVersion(null); setPublishVersionName(""); + setPublishFailure(null); setPublishDialogOpen(true); return; } @@ -1467,29 +1475,38 @@ function WorkflowEditorContent({ return; } setPublishVersionName(""); + setPublishFailure(null); setPublishDialogOpen(true); } /** Publishes the current draft as an immutable snapshot with an optional version name. */ async function confirmPublish(): Promise { - if (workflow === null) { + if (workflow === null || publishWorkflowMutation.isPending) { return; } - setPublishDialogOpen(false); + setPublishFailure(null); setManagerError(null); const version = publishVersionName.trim(); + const nodes = workflow.nodes; try { const result = await publishWorkflowMutation.mutateAsync({ workflowId: workflow.id, version: version === "" ? null : version, }); + setPublishDialogOpen(false); toast.success( t("settings.workflow.publishSuccess", { version: result.snapshot.version, }), ); } catch (cause) { - setManagerError(localizeContractError(cause, t)); + setPublishFailure( + describePublishFailure( + cause, + (nodeId) => nodes.find((node) => node.id === nodeId)?.data.title, + t, + ), + ); } } @@ -3130,7 +3147,10 @@ function WorkflowEditorContent({ {publishDialogOpen && workflow && } setPublishVersionName(event.target.value)} + onChange={(event) => { + setPublishVersionName(event.target.value); + setPublishFailure(null); + }} aria-label={t("settings.workflow.versionHistory")} placeholder={t("settings.workflow.publishVersionPlaceholder")} autoFocus @@ -3141,9 +3161,23 @@ function WorkflowEditorContent({ } }} /> + {publishFailure !== null && ( +
+

{publishFailure.message}

+ {publishFailure.detail !== null && ( +

+ {t("settings.workflow.publishRejectedDetail")} + {publishFailure.detail} +

+ )} +
+ )} {t("common.cancel")} - void confirmPublish()}> + void confirmPublish()} + > {t("settings.workflow.publish")} diff --git a/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts b/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts new file mode 100644 index 000000000..b5c265847 --- /dev/null +++ b/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { ContractError } from "@/lib/workflows/contracts"; +import { workflowI18n } from "@/lib/workflows/host/i18n"; +import { describePublishFailure } from "./workflow-publish-error"; + +const t = workflowI18n.t; +const titles: Record = { out: "汇总输出" }; +const title = (id: string) => titles[id]; + +describe("describePublishFailure", () => { + it("names the refused node by title, the field, and the server's reason", () => { + const failure = describePublishFailure( + new ContractError("workflow_run_graph_parse", { + nodeId: "out", + field: "selector", + reason: "Loop loop-1 publishes only its named outputs (result); loop-1.output is not one", + }), + title, + t, + ); + expect(failure).toEqual({ + message: "发布被拒绝:节点「汇总输出」的变量引用没有通过发布校验,草稿已保存。", + detail: "Loop loop-1 publishes only its named outputs (result); loop-1.output is not one", + }); + }); + + it("reads the server's data paths, indices included, as the field the author edits", () => { + const message = (field: string) => + describePublishFailure( + new ContractError("workflow_run_graph_parse", { nodeId: "out", field, reason: "x" }), + title, + t, + ).message; + expect(message("data.aggregatorConfig")).toBe( + "发布被拒绝:节点「汇总输出」的聚合变量没有通过发布校验,草稿已保存。", + ); + expect(message("data.outputs[1].variableSelector")).toBe( + "发布被拒绝:节点「汇总输出」的输出结果没有通过发布校验,草稿已保存。", + ); + expect(message("iterationConfig.collectSelector")).toBe( + "发布被拒绝:节点「汇总输出」的收集变量没有通过发布校验,草稿已保存。", + ); + }); + + it("falls back to the node id and the raw field the editor has no words for", () => { + const failure = describePublishFailure( + new ContractError("workflow_run_graph_parse", { nodeId: "gone", field: "data.kind", reason: "x" }), + title, + t, + ); + expect(failure.message).toBe("发布被拒绝:节点「gone」没有通过发布校验(data.kind),草稿已保存。"); + }); + + it("names the node without a field when the server gives none", () => { + const failure = describePublishFailure( + new ContractError("workflow_run_graph_parse", { nodeId: "out", reason: "x" }), + title, + t, + ); + expect(failure.message).toBe("发布被拒绝:节点「汇总输出」没有通过发布校验,草稿已保存。"); + }); + + it("says the graph was rejected when no node is known", () => { + expect( + describePublishFailure(new ContractError("workflow_run_graph_parse", {}), title, t), + ).toEqual({ message: "发布被拒绝:工作流图没有通过发布校验,草稿已保存。", detail: null }); + }); + + it("keeps other refusals' own message under a publish prefix", () => { + expect( + describePublishFailure(new ContractError("workflow_version_already_exists"), title, t), + ).toEqual({ message: "发布失败:该工作流版本已存在。", detail: null }); + expect(describePublishFailure(new Error("network"), title, t).message).toMatch(/^发布失败:/); + }); +}); diff --git a/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts b/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts new file mode 100644 index 000000000..5ce32756a --- /dev/null +++ b/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts @@ -0,0 +1,83 @@ +import type { TFunction } from "i18next"; +import { ContractError } from "@/lib/workflows/contracts"; +import { localizeContractError } from "@/lib/workflows/host/contract-error"; + +/** What the publish dialog says about a failed publish. */ +export interface WorkflowPublishFailure { + /** States that publishing (not saving) failed and, when known, which node was refused. */ + message: string; + /** The server's diagnostic reason, shown verbatim beneath the message. */ + detail: string | null; +} + +/** + * Publish-validation field paths the editor can name in the author's terms, most specific + * first. Paths are matched after dropping the `data.` prefix and array indices, so + * `data.outputs[0].variableSelector` reads as the Output's results. + */ +const FIELD_LABELS: ReadonlyArray = [ + ["iterationConfig.iteratorSelector", "settings.workflow.publishField.iterator"], + ["iterationConfig.collectSelector", "settings.workflow.publishField.collect"], + ["iterationConfig", "settings.workflow.publishField.iteration"], + ["aggregatorConfig", "settings.workflow.publishField.aggregator"], + ["loopConfig", "settings.workflow.publishField.loop"], + ["agentConfig", "settings.workflow.publishField.agent"], + ["outputs", "settings.workflow.publishField.outputs"], + ["inputVariables", "settings.workflow.publishField.inputs"], + ["cases", "settings.workflow.publishField.cases"], + ["selector", "settings.workflow.publishField.selector"], + ["template", "settings.workflow.publishField.template"], + ["edges", "settings.workflow.publishField.edges"], + ["edge", "settings.workflow.publishField.edges"], + ["parentId", "settings.workflow.publishField.container"], + ["containerId", "settings.workflow.publishField.container"], +]; + +/** Names a refused field, or `null` when the editor has no words for it. */ +function fieldLabel(field: string, t: TFunction): string | null { + const path = field.replace(/^data\./, "").replace(/\[\d+\]/g, ""); + const match = FIELD_LABELS.find( + ([prefix]) => path === prefix || path.startsWith(`${prefix}.`), + ); + return match === undefined ? null : t(match[1]); +} + +/** + * Explains a refused publish. `workflow_run_graph_parse` carries the refused node, field and + * reason in its params when the server knows them; the node is named by its title so the + * author can find it on the canvas. Other refusals keep their own localized message. + */ +export function describePublishFailure( + cause: unknown, + nodeTitle: (nodeId: string) => string | undefined, + t: TFunction, +): WorkflowPublishFailure { + if ( + !(cause instanceof ContractError) || + cause.code !== "workflow_run_graph_parse" + ) { + return { + message: t("settings.workflow.publishFailed", { + message: localizeContractError(cause, t), + }), + detail: null, + }; + } + const { nodeId, field, reason } = cause.params; + const detail = typeof reason === "string" && reason !== "" ? reason : null; + if (typeof nodeId !== "string" || nodeId === "") { + return { message: t("settings.workflow.publishRejectedGraph"), detail }; + } + const node = nodeTitle(nodeId) ?? nodeId; + if (typeof field !== "string" || field === "") { + return { message: t("settings.workflow.publishRejectedNode", { node }), detail }; + } + const label = fieldLabel(field, t); + return { + message: + label === null + ? t("settings.workflow.publishRejectedNodePath", { node, field }) + : t("settings.workflow.publishRejectedNodeField", { node, field: label }), + detail, + }; +} diff --git a/frontend-v2/src/features/workflows/page.test.tsx b/frontend-v2/src/features/workflows/page.test.tsx index 0076d1e94..5c8979b09 100644 --- a/frontend-v2/src/features/workflows/page.test.tsx +++ b/frontend-v2/src/features/workflows/page.test.tsx @@ -122,11 +122,45 @@ describe("workflow page", () => { await user.click(within(dialog).getByRole("button", { name: "发布" })); expect( - await screen.findByText("服务端暂时不能检查和发布工作流,草稿已保存。"), + await within(dialog).findByText("发布失败:服务端暂时不能检查和发布工作流,草稿已保存。"), ).toBeInTheDocument(); expect(screen.getByText("暂未发布")).toBeInTheDocument(); }); + it("keeps the publish dialog open on a graph refusal and names the refused node", async () => { + const user = userEvent.setup(); + await renderPage(); + await createWorkflow(user, "旧引用"); + await screen.findByDisplayValue("旧引用"); + const workflowId = server.backend.list().workflows.find((w) => w.name === "旧引用")!.id; + const graph = JSON.parse(server.backend.get({ workflowId }).draft.graph) as { + nodes: { id: string; data: { title: string } }[]; + }; + const [first] = graph.nodes; + server.refuse = { + match: /POST .*\/publish$/, + status: 400, + data: { + code: "workflow_run_graph_parse", + params: { nodeId: first!.id, field: "selector", reason: "Loop loop-1 publishes only its named outputs (result)" }, + requestId: "r", + }, + }; + + await user.click(await screen.findByRole("button", { name: "发布" })); + const dialog = await screen.findByRole("alertdialog", { name: "发布工作流" }); + await user.click(within(dialog).getByRole("button", { name: "发布" })); + + expect( + await within(dialog).findByText( + `发布被拒绝:节点「${first!.data.title}」的变量引用没有通过发布校验,草稿已保存。`, + ), + ).toBeInTheDocument(); + expect(within(dialog).getByText("Loop loop-1 publishes only its named outputs (result)")).toBeInTheDocument(); + expect(screen.getByRole("alertdialog", { name: "发布工作流" })).toBeInTheDocument(); + expect(screen.getByText("暂未发布")).toBeInTheDocument(); + }); + it("offers once to import the workflows this browser kept", async () => { const user = userEvent.setup(); new LocalWorkflowBackend({ storage: browserWorkflowStorage }).create({ name: "本机旧流程", graph: null }); diff --git a/frontend-v2/src/lib/workflows/editor/translations.ts b/frontend-v2/src/lib/workflows/editor/translations.ts index c83bae501..c5d16f5b2 100644 --- a/frontend-v2/src/lib/workflows/editor/translations.ts +++ b/frontend-v2/src/lib/workflows/editor/translations.ts @@ -410,6 +410,29 @@ export const workflowEditorTranslations = { "settings.workflow.publishVersionPlaceholder": "版本名(可选,留空自动生成)", "settings.workflow.publishError": "发布工作流失败。", + "settings.workflow.publishFailed": "发布失败:{{message}}", + "settings.workflow.publishRejectedGraph": + "发布被拒绝:工作流图没有通过发布校验,草稿已保存。", + "settings.workflow.publishRejectedNode": + "发布被拒绝:节点「{{node}}」没有通过发布校验,草稿已保存。", + "settings.workflow.publishRejectedNodeField": + "发布被拒绝:节点「{{node}}」的{{field}}没有通过发布校验,草稿已保存。", + "settings.workflow.publishRejectedNodePath": + "发布被拒绝:节点「{{node}}」没有通过发布校验({{field}}),草稿已保存。", + "settings.workflow.publishRejectedDetail": "服务端说明:", + "settings.workflow.publishField.selector": "变量引用", + "settings.workflow.publishField.template": "提示词变量", + "settings.workflow.publishField.aggregator": "聚合变量", + "settings.workflow.publishField.iterator": "迭代源", + "settings.workflow.publishField.collect": "收集变量", + "settings.workflow.publishField.edges": "连线", + "settings.workflow.publishField.container": "所属容器", + "settings.workflow.publishField.iteration": "迭代配置", + "settings.workflow.publishField.loop": "循环配置", + "settings.workflow.publishField.agent": "Agent 配置", + "settings.workflow.publishField.outputs": "输出结果", + "settings.workflow.publishField.inputs": "开始变量", + "settings.workflow.publishField.cases": "分支条件", "settings.workflow.publishSuccess": "已发布版本 {{version}}", "settings.workflow.deleteSuccess": "已删除“{{name}}”", "settings.workflow.versionLoadError": "无法加载该版本。", @@ -1066,6 +1089,29 @@ export const workflowEditorTranslations = { "settings.workflow.publishVersionPlaceholder": "Version name (optional; auto-generated when empty)", "settings.workflow.publishError": "Failed to publish the workflow.", + "settings.workflow.publishFailed": "Publishing failed: {{message}}", + "settings.workflow.publishRejectedGraph": + "Publishing was rejected: the workflow graph failed publish validation. The draft is saved.", + "settings.workflow.publishRejectedNode": + "Publishing was rejected: node “{{node}}” failed publish validation. The draft is saved.", + "settings.workflow.publishRejectedNodeField": + "Publishing was rejected: the {{field}} of node “{{node}}” failed publish validation. The draft is saved.", + "settings.workflow.publishRejectedNodePath": + "Publishing was rejected: node “{{node}}” failed publish validation ({{field}}). The draft is saved.", + "settings.workflow.publishRejectedDetail": "Server says: ", + "settings.workflow.publishField.selector": "variable reference", + "settings.workflow.publishField.template": "prompt variable", + "settings.workflow.publishField.aggregator": "aggregated variables", + "settings.workflow.publishField.iterator": "iteration source", + "settings.workflow.publishField.collect": "collected variable", + "settings.workflow.publishField.edges": "edges", + "settings.workflow.publishField.container": "container", + "settings.workflow.publishField.iteration": "iteration settings", + "settings.workflow.publishField.loop": "loop settings", + "settings.workflow.publishField.agent": "Agent settings", + "settings.workflow.publishField.outputs": "results", + "settings.workflow.publishField.inputs": "start variables", + "settings.workflow.publishField.cases": "branch conditions", "settings.workflow.publishSuccess": "Published version {{version}}", "settings.workflow.deleteSuccess": "Deleted “{{name}}”", "settings.workflow.versionLoadError": "Failed to load that version.", diff --git a/v2-server/README.md b/v2-server/README.md index 6d67cbccb..e2bb4f701 100644 --- a/v2-server/README.md +++ b/v2-server/README.md @@ -620,6 +620,8 @@ not execute these kinds: `crates/application/src/workflow_run/engine/node_type.r 写操作按定义行加锁串行:发布在同一事务里读草稿、校验并冻结,避免校验过的图和冻结的图不是同一份。请求体限制 6 MiB、拒绝未知字段;响应错误沿用 Cloud 的 `{code, params, requestId}`,领域错误码与 desktop 一致(如 `workflow_name_conflict`、`workflow_version_already_exists`、`workflow_cannot_delete_active_version`、`workflow_run_graph_parse`)。`workflow_name_conflict` 只用于手动创建或重命名工作流;工作流插件导入遇到同名定义会自动改名,不返回该错误。 +发布被图校验拒绝时,`400 workflow_run_graph_parse` 的 `params` 带上领域给出的 `nodeId`、`field` 和 `reason`(领域能定位时才有前两项;`reason` 是关于提交文档的英文诊断,不含主机或数据库细节),编辑器据此在发布对话框里点名被拒的节点。 + 图规则不属于 HTTP 层:`server.Options.AnalyzeWorkflow` 提供草稿分析,`Options.ValidateWorkflow` 提供发布前的可执行性校验,两者由工作流领域注入;未注入时定义读写照常,分析和发布返回 `503 workflow_domain_unavailable`,不会把未校验的文档伪装成可运行版本。 与 desktop 的明确差异:v2 以租户代替 desktop 的单一 `local` 命名空间,`namespace` 恒为 `local`;重名改为由数据库唯一索引拒绝并映射为 409(desktop 并发重名可能返回 500);发布校验放在事务内(desktop 存在校验与冻结之间的 TOCTOU);软删记录 `deleted_at`(desktop 丢弃快照删除时间);版本列表在同一毫秒内用 id 兜底排序;名称唯一性用 PostgreSQL `lower()`,比 desktop 的 ASCII `NOCASE` 范围更宽;发布另外拒绝引擎永远不会赋值的 Loop 引用(`invalid_loop_reference`):Loop 外引用它的命名输出以外的变量(如旧图里的 `{loop}.output`),循环体内引用 Loop 的循环变量以外的变量,或引用轮次 Start 的变量。desktop 接受这类图,运行到该节点才以变量未赋值失败。 diff --git a/v2-server/internal/server/workflows.go b/v2-server/internal/server/workflows.go index 29506e2d7..5d7c429c4 100644 --- a/v2-server/internal/server/workflows.go +++ b/v2-server/internal/server/workflows.go @@ -213,7 +213,14 @@ func workflowFault(w http.ResponseWriter, err error, op, draftSource string) { case errors.Is(err, store.ErrWorkflowActiveRuns): fault(w, http.StatusBadRequest, "workflow_active_runs") case errors.Is(err, store.ErrWorkflowDocumentInvalid): - fault(w, http.StatusBadRequest, "workflow_run_graph_parse") + // The domain's refusal names the node and field when it knows them; the HTTP layer + // reads them through this method instead of importing the domain package. + var refusal interface{ FaultParams() map[string]any } + if errors.As(err, &refusal) { + faultWithParams(w, http.StatusBadRequest, "workflow_run_graph_parse", refusal.FaultParams()) + } else { + fault(w, http.StatusBadRequest, "workflow_run_graph_parse") + } case errors.Is(err, errWorkflowDomainUnavailable): fault(w, http.StatusServiceUnavailable, "workflow_domain_unavailable") default: diff --git a/v2-server/internal/server/workflows_test.go b/v2-server/internal/server/workflows_test.go index 7bacb6527..bc4d6f086 100644 --- a/v2-server/internal/server/workflows_test.go +++ b/v2-server/internal/server/workflows_test.go @@ -23,6 +23,7 @@ import ( "github.com/wanglongan587/cloud/v2-server/internal/server" "github.com/wanglongan587/cloud/v2-server/internal/store" "github.com/wanglongan587/cloud/v2-server/internal/store/storetest" + wf "github.com/wanglongan587/cloud/v2-server/internal/workflow" ) // workflowCall drives the definition routes while validating every response against the candidate @@ -327,11 +328,29 @@ func TestWorkflowAnalysisAndPublishValidation(t *testing.T) { _, created := call("POST", base, map[string]any{"name": "不可执行", "graph": "unrunnable"}) id := created["workflow"].(map[string]any)["id"].(string) status, failure := call("POST", base+"/"+id+"/publish", map[string]any{"version": "v1"}) - if status != 400 || failure["code"] != "workflow_run_graph_parse" { + if status != 400 || failure["code"] != "workflow_run_graph_parse" || !reflect.DeepEqual(failure["params"], map[string]any{}) { t.Fatalf("publish invalid graph = %d %v", status, failure) } } +// A domain refusal names the node and field so the editor can say what to fix. +func TestWorkflowPublishRefusalNamesTheNode(t *testing.T) { + call := workflowServer(t, func(o *server.Options) { + o.ValidateWorkflow = func(string) error { + return &wf.ValidationError{Code: "invalid_loop_reference", NodeID: "out", Field: "selector", Reason: "Loop loop publishes only its named outputs (result); loop.output is not one"} + } + }) + tid := workflowTenant(t, call) + base := "/api/v2/tenants/" + tid + "/workflows" + _, created := call("POST", base, map[string]any{"name": "旧引用", "graph": "{}"}) + id := created["workflow"].(map[string]any)["id"].(string) + status, failure := call("POST", base+"/"+id+"/publish", map[string]any{"version": "v1"}) + want := map[string]any{"nodeId": "out", "field": "selector", "reason": "Loop loop publishes only its named outputs (result); loop.output is not one"} + if status != 400 || failure["code"] != "workflow_run_graph_parse" || !reflect.DeepEqual(failure["params"], want) { + t.Fatalf("publish refusal = %d %v, want params %v", status, failure, want) + } +} + func TestWorkflowWithoutDomainStillReadsAssets(t *testing.T) { call := workflowServer(t, func(o *server.Options) { o.AnalyzeWorkflow = nil diff --git a/v2-server/internal/workflow/README.md b/v2-server/internal/workflow/README.md index a09ff9e7c..2db135f86 100644 --- a/v2-server/internal/workflow/README.md +++ b/v2-server/internal/workflow/README.md @@ -28,6 +28,7 @@ Loop 外只能读命名输出(没有 `{loop}.output`),循环体内只能 装配层将 `Analysis` 映射成 HTTP 传输类型,`ValidateWorkflow` 可直接作为回调传入。 失败返回 `*ValidationError`,包含领域分类 `Code`、可选的 `NodeID`、`Field` 和 `Reason`。 +`FaultParams` 把后三项交给 HTTP 层作为 `workflow_run_graph_parse` 的 `params`,HTTP 层不必导入本包。 HTTP 错误码由适配层映射;诊断措辞不承诺逐字匹配 desktop。 ## 行为依据与测试 diff --git a/v2-server/internal/workflow/workflow.go b/v2-server/internal/workflow/workflow.go index ee7dd0dad..2835208c1 100644 --- a/v2-server/internal/workflow/workflow.go +++ b/v2-server/internal/workflow/workflow.go @@ -54,6 +54,20 @@ func (e *ValidationError) Error() string { return fmt.Sprintf("workflow %s (%s): %s", e.Code, where, e.Reason) } +// FaultParams names the refused node, field and reason for the public +// workflow_run_graph_parse fault, so an author can find what to fix. The reason is a bounded +// diagnostic about the submitted document; it carries no host or database detail. +func (e *ValidationError) FaultParams() map[string]any { + params := map[string]any{"reason": e.Reason} + if e.NodeID != "" { + params["nodeId"] = e.NodeID + } + if e.Field != "" { + params["field"] = e.Field + } + return params +} + func invalid(code, nodeID, field, reason string) error { return &ValidationError{Code: code, NodeID: nodeID, Field: field, Reason: reason} } From 61429bd2659711d754db7cd5024c7be670db7b2d Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 11:46:19 +0800 Subject: [PATCH 4/8] fix(v2): let an iteration frame's ports take a drag across their whole dot The iteration header is raised (z-20) above its region, and the frame's input and output ports sat beneath it, so the inner half of each port's hit area belonged to the header: pressing there dragged the frame instead of starting a connection. The ports now stack above the header. The Loop container renders its ports after an unraised header and was not affected. The new e2e spec hit-tests both containers' ports across the dot, drags a connection from the inner half, and publishes a stale `loop.output` graph to check the refusal names the node in the dialog. Refs ora-space/circus#1388 --- .../e2e/workflow-container-editor.spec.ts | 79 +++++++++++++++++++ .../editor/workflow-flow/iteration-node.tsx | 7 +- 2 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 frontend-v2/e2e/workflow-container-editor.spec.ts diff --git a/frontend-v2/e2e/workflow-container-editor.spec.ts b/frontend-v2/e2e/workflow-container-editor.spec.ts new file mode 100644 index 000000000..f2ab6fdc9 --- /dev/null +++ b/frontend-v2/e2e/workflow-container-editor.spec.ts @@ -0,0 +1,79 @@ +import { expect, test, type Page } from '@playwright/test' +import { signIn } from './login.ts' + +const agent = (prompt: string) => ({ executor: { agentCli: 'official/ora-space.opencode', modelId: 'fixture' }, prompt }) +const node = (id: string, kind: string, title: string, x: number, y: number, data: Record = {}, parentId?: string) => ({ id, type: 'workflow', position: { x, y }, parentId, data: { kind, title, description: '', ...data } }) +const edge = (source: string, target: string, sourceHandle?: string) => ({ id: `${source}-${target}`, source, target, sourceHandle, type: 'workflow' }) +const loop = (x: number, y: number) => [ + node('loop', 'loop', '反馈循环', x, y, { loopConfig: { + maxIterations: 2, maxIterationsBehavior: 'fail', + variables: [{ name: 'value', valueType: 'string', initial: { kind: 'constant', value: '' }, feedback: ['writer', 'output'] }], + until: { logic: 'and', conditions: [{ variableSelector: ['writer', 'output'], operator: 'not_empty' }] }, + outputs: [{ name: 'result', variableSelector: ['writer', 'output'] }], + } }), + node('entry', 'start', '轮次开始', 40, 145, { containerId: 'loop' }, 'loop'), + node('writer', 'agent', '改进', 350, 145, { containerId: 'loop', agentConfig: agent('改进:{{#loop.value#}}') }, 'loop'), +] + +/** Creates a workflow from a graph through the API and opens it in the editor. */ +async function openGraph(page: Page, title: string, graph: unknown) { + await page.goto('/workflows') + await signIn(page) + const tenant = (await (await page.request.get('/api/v1/me/tenants')).json()).items[0].id as string + // The e2e database outlives a run, so each run makes its own workflow. + const name = `${title} ${Date.now().toString(36)}` + const created = await page.request.post(`/api/v2/tenants/${tenant}/workflows`, { data: { name, graph: JSON.stringify(graph) } }) + expect(created.status()).toBe(201) + await page.reload() + await page.getByRole('complementary', { name: '工作流列表' }).getByRole('button', { name, exact: true }).click() + await expect(page.getByRole('textbox', { name: '工作流名称' })).toHaveValue(name) +} + +test('workflow container editor: a frame port connects from anywhere on its dot, not only its outer half', async ({ page }) => { + await page.setViewportSize({ width: 1920, height: 1080 }) + await openGraph(page, '容器端口', { schemaVersion: 2, nodes: [ + node('start', 'start', '开始', 0, 40, { inputVariables: [{ name: 'items', valueType: 'array[string]', value: ['a'] }] }), + node('iter', 'iteration', '逐段处理', 320, 0, { iterationConfig: { iteratorSelector: ['start', 'items'], collectSelector: ['worker', 'output'], errorStrategy: 'continue', maxIterations: 50 } }), + node('worker', 'agent', '处理段落', 120, 90, { agentConfig: agent('处理:{{#iter.item#}}') }, 'iter'), + node('out', 'output', '迭代输出', 1000, 40, { outputs: [{ name: 'paragraphs', variableSelector: ['iter', 'output'] }] }), + ...loop(320, 420), + node('out2', 'output', '循环输出', 1100, 470, { outputs: [{ name: 'result', variableSelector: ['loop', 'result'] }] }), + ], edges: [edge('start', 'iter'), edge('iter', 'worker', 'iteration-entry'), edge('entry', 'writer'), edge('start', 'loop')] }) + + const edges = page.locator('.react-flow__edge') + await expect(edges).toHaveCount(4) + for (const [source, target] of [['iter', 'out'], ['loop', 'out2']]) { + const port = (await page.locator(`[data-workflow-output="${source}"]`).boundingBox())! + const x = port.x + port.width / 2 + const y = port.y + port.height / 2 + // The 22px target around the dot belongs to the port on both sides of the frame edge; the + // iteration header used to cover its inner half. + for (const dx of [-8, -4, 0, 4, 8]) { + const owner = await page.evaluate(([px, py]) => document.elementFromPoint(px, py)?.closest('[data-workflow-output]')?.getAttribute('data-workflow-output'), [x + dx, y]) + expect(owner, `${source} output port at dx=${dx}`).toBe(source) + } + const input = (await page.locator(`[data-workflow-input="${target}"]`).boundingBox())! + const before = await edges.count() + await page.mouse.move(x - 4, y) + await page.mouse.down() + await page.mouse.move(input.x + input.width / 2, input.y + input.height / 2, { steps: 12 }) + await page.mouse.up() + await expect(edges).toHaveCount(before + 1) + } +}) + +test('workflow container editor: publishing a stale loop.output reference is refused in the dialog, naming the node', async ({ page }) => { + await openGraph(page, '旧引用', { schemaVersion: 2, nodes: [ + node('start', 'start', '开始', 0, 60), + ...loop(320, 0), + node('out', 'output', '汇总输出', 1120, 60, { outputs: [{ name: 'result', variableSelector: ['loop', 'output'] }] }), + ], edges: [edge('start', 'loop'), edge('entry', 'writer'), edge('loop', 'out')] }) + + await page.getByRole('button', { name: '发布', exact: true }).click() + const publish = page.getByRole('alertdialog', { name: '发布工作流' }) + await publish.getByRole('textbox').fill('v1') + await publish.getByRole('button', { name: '发布' }).click() + await expect(publish.getByText('发布被拒绝:节点「汇总输出」的变量引用没有通过发布校验,草稿已保存。', { exact: true })).toBeVisible() + await expect(publish.getByText(/Loop loop publishes only its named outputs \(result\); loop\.output is not one/)).toBeVisible() + await expect(page.getByText('暂未发布')).toBeVisible() +}) diff --git a/frontend-v2/src/features/workflows/editor/workflow-flow/iteration-node.tsx b/frontend-v2/src/features/workflows/editor/workflow-flow/iteration-node.tsx index 4b5199832..8509136cf 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-flow/iteration-node.tsx +++ b/frontend-v2/src/features/workflows/editor/workflow-flow/iteration-node.tsx @@ -125,13 +125,16 @@ export function IterationNodeFrame({ : expandedHeight, }} > + {/* The frame ports sit on the header's edges, and the header is raised (z-20) above + the region and its members; the ports must stack above it, or the header swallows + the pointer and a drag from the port never starts a connection. */} Date: Mon, 23 Nov 2026 14:29:30 +0800 Subject: [PATCH 5/8] test(v2): check publication no longer declares `{loop}.output` The reference check refuses `{loop}.output` before scope typing runs, so reverting the declarations.go change went unnoticed. declarations() now returns the static catalog it builds, and an internal test reads it directly: a Loop declares its named outputs (typed any) and no `output`. Refs ora-space/circus#1388 --- v2-server/internal/workflow/README.md | 1 + v2-server/internal/workflow/declarations.go | 20 ++++++---- .../loop_declarations_internal_test.go | 37 +++++++++++++++++++ 3 files changed, 51 insertions(+), 7 deletions(-) create mode 100644 v2-server/internal/workflow/loop_declarations_internal_test.go diff --git a/v2-server/internal/workflow/README.md b/v2-server/internal/workflow/README.md index 2db135f86..672e7ab7a 100644 --- a/v2-server/internal/workflow/README.md +++ b/v2-server/internal/workflow/README.md @@ -45,6 +45,7 @@ HTTP 错误码由适配层映射;诊断措辞不承诺逐字匹配 desktop。 | `config_test.go` | Start / 全局声明、Agent 策略和 schema、Condition / Output 历史格式、Aggregator 拓扑及类型 | | `container_test.go` | Loop 轮次上限、携带值与可见性;Iteration 归属、输入 / 收集类型及边界 | | `loop_references_test.go` | Loop 外只读命名输出、循环体内只读循环变量、轮次 Start 无变量;选择器、模板与聚合候选都指向引用节点 | +| `loop_declarations_internal_test.go` | 发布期静态类型表不声明 `{loop}.output`,只声明命名输出 | | `testdata/spare-chain.json`、`testdata/iteration.json` | 改编自 desktop `execution_document/tests.rs` | | `testdata/loop.json` | 改编自 desktop `loop_graph/tests.rs` | | `condition_test.go` | Condition 的 case 顺序、空 case、and/or、各运算符、比较值模板与失败(改编自 desktop `condition.rs`) | diff --git a/v2-server/internal/workflow/declarations.go b/v2-server/internal/workflow/declarations.go index 49bb574b0..0399ec3fb 100644 --- a/v2-server/internal/workflow/declarations.go +++ b/v2-server/internal/workflow/declarations.go @@ -7,6 +7,12 @@ type declaration struct{ typ, writer string } // validateDeclarations mirrors desktop's base-then-topological derived catalog. // This is static publication typing; no variable values or execution state live here. func (s *scope) validateDeclarations(globals map[string]string) error { + _, err := s.declarations(globals) + return err +} + +// declarations returns the scope's static catalog, keyed by qualified selector. +func (s *scope) declarations(globals map[string]string) (map[string]declaration, error) { catalog := map[string]declaration{} for key, typ := range globals { catalog[key] = declaration{typ: typ, writer: strings.SplitN(key, ".", 2)[0]} @@ -48,14 +54,14 @@ func (s *scope) validateDeclarations(globals map[string]string) error { ancestors := s.ancestors(n.id) for _, parts := range n.aggregator { if s.byID[parts[0]] != nil && !ancestors[parts[0]] { - return invalid("invalid_aggregator", n.id, "aggregatorConfig.variables", "producer must be a static predecessor") + return nil, invalid("invalid_aggregator", n.id, "aggregatorConfig.variables", "producer must be a static predecessor") } def, exists := catalog[qualified(parts)] if !exists { - return invalid("invalid_aggregator", n.id, "aggregatorConfig.variables", "selector is not declared") + return nil, invalid("invalid_aggregator", n.id, "aggregatorConfig.variables", "selector is not declared") } if typ != "" && typ != def.typ { - return invalid("invalid_aggregator", n.id, "aggregatorConfig.variables", "selectors must have the same declared type") + return nil, invalid("invalid_aggregator", n.id, "aggregatorConfig.variables", "selectors must have the same declared type") } typ = def.typ } @@ -64,15 +70,15 @@ func (s *scope) validateDeclarations(globals map[string]string) error { if n.kind == "iteration" { source, exists := catalog[qualified(n.iterator)] if !exists || !strings.HasPrefix(source.typ, "array") { - return invalid("invalid_iteration", n.id, "iterationConfig.iteratorSelector", "iterator must be a declared array") + return nil, invalid("invalid_iteration", n.id, "iterationConfig.iteratorSelector", "iterator must be a declared array") } if writer := s.byID[source.writer]; writer != nil && writer.owner == n.id { - return invalid("invalid_iteration", n.id, "iterationConfig.iteratorSelector", "iterator must be outside its own region") + return nil, invalid("invalid_iteration", n.id, "iterationConfig.iteratorSelector", "iterator must be outside its own region") } member := s.byID[n.collect[0]] collected, exists := catalog[qualified(n.collect)] if member == nil || member.owner != n.id || !exists { - return invalid("invalid_iteration", n.id, "iterationConfig.collectSelector", "collect must be a declared root variable of a region member") + return nil, invalid("invalid_iteration", n.id, "iterationConfig.collectSelector", "collect must be a declared root variable of a region member") } item := "any" switch source.typ { @@ -86,5 +92,5 @@ func (s *scope) validateDeclarations(globals map[string]string) error { declare(n, "failed_count", "number") } } - return nil + return catalog, nil } diff --git a/v2-server/internal/workflow/loop_declarations_internal_test.go b/v2-server/internal/workflow/loop_declarations_internal_test.go new file mode 100644 index 000000000..f8c7ad3f8 --- /dev/null +++ b/v2-server/internal/workflow/loop_declarations_internal_test.go @@ -0,0 +1,37 @@ +package workflow + +import ( + "os" + "testing" +) + +// Publication must not declare `{loop}.output`: the engine never assigns it. The reference +// check refuses such selectors first, so this reads the static catalog directly. +func TestLoopDeclaresOnlyNamedOutputs(t *testing.T) { + source, err := os.ReadFile("testdata/loop.json") + if err != nil { + t.Fatal(err) + } + doc, err := project(string(source)) + if err != nil { + t.Fatal(err) + } + scopes, err := buildScopes(doc) + if err != nil { + t.Fatal(err) + } + globals, err := validateGlobals(doc.raw, true) + if err != nil { + t.Fatal(err) + } + catalog, err := scopes[""].declarations(globals) + if err != nil { + t.Fatal(err) + } + if _, declared := catalog["loop.output"]; declared { + t.Error("loop.output is declared, but the engine publishes only named outputs") + } + if got := catalog["loop.result"]; got != (declaration{typ: "any", writer: "loop"}) { + t.Errorf("loop.result = %+v, want the named output typed any", got) + } +} From 1d06497c1ce039cad98ce6a77901fc54ccc602b2 Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 14:29:30 +0800 Subject: [PATCH 6/8] fix(v2): check a Loop's own config and in-body aggregators at publish invalid_loop_reference skipped Loop nodes, so `until` or `outputs` reading the round Start, or a second Loop whose `initial` read `loopA.output`, still published and failed at run time. A Loop's `initial` is now checked as an outer reference (named outputs only, never the Loop itself), and its `feedback`, `until` and `outputs` as round-pool references (its loop variables, never its named outputs); the round Start is always refused. An aggregator inside a Loop body is typed against the body's own declarations, so its candidates must come from the body or be globals; it is refused with that reason rather than "selector is not declared". A global whose name starts with a Loop or round Start ID resolves as the global and is no longer refused. Templates now carry the field they came from (agentConfig.prompt, cases, loopConfig.until) instead of a generic "template", so the editor can name a Condition's comparison value correctly. Refs ora-space/circus#1388 --- v2-server/README.md | 2 +- v2-server/internal/workflow/README.md | 5 +- v2-server/internal/workflow/agent.go | 2 +- v2-server/internal/workflow/document.go | 7 +- .../internal/workflow/loop_references.go | 137 +++++++++++++++--- .../internal/workflow/loop_references_test.go | 94 ++++++++++-- v2-server/internal/workflow/nodes.go | 6 +- v2-server/internal/workflow/validate.go | 8 +- 8 files changed, 215 insertions(+), 46 deletions(-) diff --git a/v2-server/README.md b/v2-server/README.md index f94425465..ad2ed4d35 100644 --- a/v2-server/README.md +++ b/v2-server/README.md @@ -624,7 +624,7 @@ not execute these kinds: `crates/application/src/workflow_run/engine/node_type.r 图规则不属于 HTTP 层:`server.Options.AnalyzeWorkflow` 提供草稿分析,`Options.ValidateWorkflow` 提供发布前的可执行性校验,两者由工作流领域注入;未注入时定义读写照常,分析和发布返回 `503 workflow_domain_unavailable`,不会把未校验的文档伪装成可运行版本。 -与 desktop 的明确差异:v2 以租户代替 desktop 的单一 `local` 命名空间,`namespace` 恒为 `local`;重名改为由数据库唯一索引拒绝并映射为 409(desktop 并发重名可能返回 500);发布校验放在事务内(desktop 存在校验与冻结之间的 TOCTOU);软删记录 `deleted_at`(desktop 丢弃快照删除时间);版本列表在同一毫秒内用 id 兜底排序;名称唯一性用 PostgreSQL `lower()`,比 desktop 的 ASCII `NOCASE` 范围更宽;发布另外拒绝引擎永远不会赋值的 Loop 引用(`invalid_loop_reference`):Loop 外引用它的命名输出以外的变量(如旧图里的 `{loop}.output`),循环体内引用 Loop 的循环变量以外的变量,或引用轮次 Start 的变量。desktop 接受这类图,运行到该节点才以变量未赋值失败。 +与 desktop 的明确差异:v2 以租户代替 desktop 的单一 `local` 命名空间,`namespace` 恒为 `local`;重名改为由数据库唯一索引拒绝并映射为 409(desktop 并发重名可能返回 500);发布校验放在事务内(desktop 存在校验与冻结之间的 TOCTOU);软删记录 `deleted_at`(desktop 丢弃快照删除时间);版本列表在同一毫秒内用 id 兜底排序;名称唯一性用 PostgreSQL `lower()`,比 desktop 的 ASCII `NOCASE` 范围更宽;发布另外拒绝引擎永远不会赋值的 Loop 引用(`invalid_loop_reference`):Loop 外引用它的命名输出以外的变量(如旧图里的 `{loop}.output`),循环体内引用 Loop 的循环变量以外的变量,或引用轮次 Start 的变量;Loop 自己的配置同样检查(`initial` 读 Loop 开始前的变量池,`feedback`、`until`、`outputs` 读本轮变量池),循环体内的变量聚合器只能选循环体内产生的变量或全局变量。名字恰好以 Loop 或轮次 Start 的 ID 开头的全局变量按全局变量解析,不受影响。desktop 接受这类图,运行到该节点才以变量未赋值失败。 ### 工作流运行历史 diff --git a/v2-server/internal/workflow/README.md b/v2-server/internal/workflow/README.md index 672e7ab7a..f9ded83c6 100644 --- a/v2-server/internal/workflow/README.md +++ b/v2-server/internal/workflow/README.md @@ -20,7 +20,8 @@ err = workflow.ValidateWorkflow(graph) Loop 配置及作用域,以及对被排除节点的变量引用。备用节点配置不参与检查,但无效身份、边和归属不能被过滤隐藏。 已知的历史 `prompt` / `tool` 类型沿用 desktop 的可解析行为;解析通过不代表运行时支持这些节点。 另外,`ValidateWorkflow` 比 desktop 多拒绝一类引擎永远不会赋值的 Loop 引用(`invalid_loop_reference`,指向引用它的节点): -Loop 外只能读命名输出(没有 `{loop}.output`),循环体内只能读 Loop 的循环变量,轮次 Start 不提供变量。 +Loop 外(含 Loop 自己的 `initial`)只能读命名输出(没有 `{loop}.output`),循环体内和 Loop 的 `feedback`、`until`、`outputs` 只能读本 Loop 的循环变量, +轮次 Start 不提供变量,循环体内的 Aggregator 只能选循环体内产生的变量(与 `validateDeclarations` 的循环体类型表一致)。错误的 `field` 指出引用所在的配置项,如 `agentConfig.prompt`、`cases`、`loopConfig.until`。 发布边界对应 `WorkflowGraph::parse`,启动边界另外调用 `validate_executable_graph`。 例如缺少 Start 的平面图、未指定本机可用执行器的 Agent 仍可能通过发布校验。 @@ -44,7 +45,7 @@ HTTP 错误码由适配层映射;诊断措辞不承诺逐字匹配 desktop。 | `document_test.go` | 编排投影、无效结构、未知类型、备用节点重新接入、无效引用、发布与启动校验边界 | | `config_test.go` | Start / 全局声明、Agent 策略和 schema、Condition / Output 历史格式、Aggregator 拓扑及类型 | | `container_test.go` | Loop 轮次上限、携带值与可见性;Iteration 归属、输入 / 收集类型及边界 | -| `loop_references_test.go` | Loop 外只读命名输出、循环体内只读循环变量、轮次 Start 无变量;选择器、模板与聚合候选都指向引用节点 | +| `loop_references_test.go` | Loop 外只读命名输出、循环体内只读循环变量、轮次 Start 无变量;Loop 自身的 `initial` / `feedback` / `until` / `outputs`、循环体内聚合器、同名全局变量;错误指向引用节点和字段 | | `loop_declarations_internal_test.go` | 发布期静态类型表不声明 `{loop}.output`,只声明命名输出 | | `testdata/spare-chain.json`、`testdata/iteration.json` | 改编自 desktop `execution_document/tests.rs` | | `testdata/loop.json` | 改编自 desktop `loop_graph/tests.rs` | diff --git a/v2-server/internal/workflow/agent.go b/v2-server/internal/workflow/agent.go index fac07a936..e7496a397 100644 --- a/v2-server/internal/workflow/agent.go +++ b/v2-server/internal/workflow/agent.go @@ -13,7 +13,7 @@ func validateAgent(c reader, n *node) { n.interactive = c.boolean("interactive") } validateCompletion(c) - n.templates = append(n.templates, c.str("prompt")) + n.templates = append(n.templates, templateRef{text: c.str("prompt"), field: "agentConfig.prompt"}) for _, skill := range c.elements("skills") { skill.str("skillId") if skill.value["enabled"] != nil { diff --git a/v2-server/internal/workflow/document.go b/v2-server/internal/workflow/document.go index 68c52a45c..6384c8fa9 100644 --- a/v2-server/internal/workflow/document.go +++ b/v2-server/internal/workflow/document.go @@ -16,7 +16,7 @@ type node struct { container bool raw, data object selectors [][]string - templates []string + templates []templateRef bindings [][]string // Condition/Output bindings, subject to Loop visibility. aggregator [][]string iterator []string @@ -28,6 +28,11 @@ type node struct { interactive bool } +// templateRef is one authored `{{#node.variable#}}` template and the data field it came from, +// so a refusal can point the author at the prompt, the branch condition or the Loop's end +// condition rather than at a generic "template". +type templateRef struct{ text, field string } + type edge struct { source, target string raw object diff --git a/v2-server/internal/workflow/loop_references.go b/v2-server/internal/workflow/loop_references.go index 62002cb1c..b57e1f352 100644 --- a/v2-server/internal/workflow/loop_references.go +++ b/v2-server/internal/workflow/loop_references.go @@ -1,19 +1,33 @@ package workflow import ( + "fmt" "sort" "strings" ) // validateLoopReferences rejects references the engine can never assign, so authors learn at -// publication, with the consumer named, what would otherwise fail at runtime as "unassigned". -// The engine publishes only a Loop's named outputs to the outer scope (desktop loop_round.rs -// exit_outputs), resolves its carried variables only inside its body, and never assigns -// anything to a body's round Start. A Loop's own configuration is validated by -// validateLoopBindings and is skipped here. -func validateLoopReferences(d *document) error { +// publication, with the consumer named, what would otherwise fail at runtime as "unassigned" +// or "has no value in this round". It checks variable names; validateLoopBindings separately +// checks that the producing node is visible at all. +// +// What the engine assigns, by where a reference is resolved: +// - Outside a Loop (root and Iteration nodes, and a Loop's `initial` selectors, which read the +// pool the Loop starts in): only the Loop's named outputs (desktop loop_round.rs +// exit_outputs); there is no `{loop}.output`, and a Loop's initial values cannot read that +// Loop at all. +// - In a Loop's round pool (its body members, and its own `feedback`, `until` and `outputs`): +// its loop variables, not its named outputs, which exist only once the Loop finishes. +// - A body's round Start assigns nothing, wherever it is read. +// - An Aggregator inside a body is typed against the body's own declarations only +// (validateDeclarations), so its candidates must be produced in that body. +// +// A global whose name happens to start with a Loop or round Start ID is resolved as the global, +// so it is never refused here. +func validateLoopReferences(d *document, globals map[string]string) error { type loopNames struct{ outputs, variables map[string]bool } loops := map[string]loopNames{} + configs := map[string]loopConfig{} for _, n := range d.nodes { if !d.active[n.id] || n.kind != "loop" { continue @@ -27,57 +41,132 @@ func validateLoopReferences(d *document) error { names.variables[variable.Name] = true } loops[n.id] = names + configs[n.id] = cfg } if len(loops) == 0 { return nil } - check := func(n *node, field string, parts []string) error { + // check resolves parts as read by consumer in the round pool of Loop `round`, or outside + // every Loop when round is "". + check := func(consumer *node, round, field string, parts []string) error { + if len(parts) < 2 || globals[qualified(parts)] != "" { + return nil + } producer := d.byID[parts[0]] - if producer == nil || producer == n || len(parts) < 2 { + if producer == nil { return nil } selected := strings.Join(parts, ".") if producer.kind == "start" && producer.container { - return invalid("invalid_loop_reference", n.id, field, - "round Start "+producer.id+" assigns no variables; "+selected+" is never set, read the Loop's variables instead") + hint := "" + if round != "" { + hint = ", read the Loop's variables instead" + } + return invalid("invalid_loop_reference", consumer.id, field, + "round Start "+producer.id+" assigns no variables; "+selected+" is never set"+hint) } names, isLoop := loops[producer.id] - if !isLoop { + switch { + case !isLoop: return nil - } - if n.container && n.owner == producer.id { + case producer == consumer && round == "": + return invalid("invalid_loop_reference", consumer.id, field, + "Loop "+producer.id+"'s initial values are read before its first round; "+selected+" cannot read the Loop itself") + case round == producer.id: if !names.variables[parts[1]] { - return invalid("invalid_loop_reference", n.id, field, + return invalid("invalid_loop_reference", consumer.id, field, "inside Loop "+producer.id+" only its loop variables ("+listNames(names.variables)+") are readable; "+selected+" is not one") } - return nil - } - if !names.outputs[parts[1]] { - return invalid("invalid_loop_reference", n.id, field, + case !names.outputs[parts[1]]: + return invalid("invalid_loop_reference", consumer.id, field, "Loop "+producer.id+" publishes only its named outputs ("+listNames(names.outputs)+"); "+selected+" is not one") } return nil } + checkTemplate := func(consumer *node, round string, template templateRef) error { + for _, parts := range templateSelectors(template.text) { + if err := check(consumer, round, template.field, parts); err != nil { + return err + } + } + return nil + } for _, n := range d.nodes { - if !d.active[n.id] || n.kind == "loop" { + if !d.active[n.id] { continue } + if n.kind == "loop" { + if err := checkLoopConfig(n, configs[n.id], check, checkTemplate); err != nil { + return err + } + continue + } + round := "" + if n.container { + round = n.owner + } for _, parts := range n.selectors { - if err := check(n, "selector", parts); err != nil { + if err := check(n, round, "selector", parts); err != nil { return err } } - for _, text := range n.templates { - for _, parts := range templateSelectors(text) { - if err := check(n, "template", parts); err != nil { - return err + for _, template := range n.templates { + if err := checkTemplate(n, round, template); err != nil { + return err + } + } + if n.kind == "aggregator" && round != "" { + for _, parts := range n.aggregator { + producer := d.byID[parts[0]] + if globals[qualified(parts)] != "" || (producer != nil && producer.container && producer.owner == round) { + continue } + return invalid("invalid_loop_reference", n.id, "aggregatorConfig.variables", + "inside Loop "+round+" an aggregator reads only variables produced in the Loop body or globals; "+strings.Join(parts, ".")+" is not one") } } } return nil } +// checkLoopConfig applies check to a Loop's own selectors: `initial` reads the pool the Loop +// starts in, while `feedback`, `until` and `outputs` read the Loop's round pool. +func checkLoopConfig( + loop *node, + cfg loopConfig, + check func(consumer *node, round, field string, parts []string) error, + checkTemplate func(consumer *node, round string, template templateRef) error, +) error { + for i, variable := range cfg.Variables { + if variable.Initial.Kind == "variable" { + if err := check(loop, "", fmt.Sprintf("loopConfig.variables[%d].initial", i), variable.Initial.Selector); err != nil { + return err + } + } + if err := check(loop, loop.id, fmt.Sprintf("loopConfig.variables[%d].feedback", i), variable.Feedback); err != nil { + return err + } + } + for _, clause := range cfg.until { + for _, rule := range clause.rules { + if err := check(loop, loop.id, "loopConfig.until", rule.selector); err != nil { + return err + } + } + } + for _, template := range loop.templates { + if err := checkTemplate(loop, loop.id, template); err != nil { + return err + } + } + for i, output := range cfg.Outputs { + if err := check(loop, loop.id, fmt.Sprintf("loopConfig.outputs[%d].variableSelector", i), output.Selector); err != nil { + return err + } + } + return nil +} + // templateSelectors lists the qualified `{{#node.variable#}}` references in one template. // Malformed templates are diagnosed at execution, as on desktop. func templateSelectors(text string) [][]string { diff --git a/v2-server/internal/workflow/loop_references_test.go b/v2-server/internal/workflow/loop_references_test.go index 65000d50c..da9074748 100644 --- a/v2-server/internal/workflow/loop_references_test.go +++ b/v2-server/internal/workflow/loop_references_test.go @@ -8,8 +8,9 @@ import ( "github.com/wanglongan587/cloud/v2-server/internal/workflow" ) -// The engine publishes only a Loop's named outputs and never assigns its round Start, so -// references the editor used to offer must be refused at publication, naming the consumer. +// The engine publishes only a Loop's named outputs, resolves its loop variables only in its +// round pool and never assigns its round Start, so references the editor used to offer must be +// refused at publication, naming the consumer and the field it came from. func TestLoopReferences(t *testing.T) { outer := func(selector ...string) func(obj) { return func(g obj) { @@ -20,26 +21,95 @@ func TestLoopReferences(t *testing.T) { body := func(prompt string) func(obj) { return func(g obj) { dataOf(g, "writer")["agentConfig"].(obj)["prompt"] = prompt } } + until := func(selector ...string) func(obj) { + return func(g obj) { + loopConfig(g)["until"] = obj{"logic": "and", "conditions": []any{obj{"variableSelector": selector, "operator": "not_empty"}}} + } + } + // A second Loop after the fixture's, whose initial value reads selector. + second := func(selector ...string) func(obj) { + return func(g obj) { + addNode(g, "loop2", "loop", obj{"loopConfig": obj{ + "maxIterations": 2, + "variables": []any{obj{"name": "draft", "valueType": "any", "initial": obj{"kind": "variable", "selector": selector}, "feedback": []string{"loop2", "draft"}}}, + "until": obj{"logic": "and", "conditions": []any{}}, + "outputs": []any{obj{"name": "final", "variableSelector": []string{"loop2", "draft"}}}, + }}) + addNode(g, "entry2", "start", obj{"containerId": "loop2"}) + connect(g, "loop", "loop2") + } + } + aggregate := func(selector ...string) func(obj) { + return func(g obj) { + addNode(g, "agg", "aggregator", obj{"containerId": "loop", "aggregatorConfig": obj{"variables": []any{selector}}}) + connect(g, "writer", "agg") + } + } + global := func(name string, edit func(obj)) func(obj) { + return func(g obj) { + g["globalVariables"] = []any{obj{"name": name, "valueType": "string", "value": "g"}} + edit(g) + } + } for _, test := range []struct { name string edit func(obj) nodeID string // empty when the graph is valid + field string reason string }{ - {"outer named output", outer("loop", "result"), "", ""}, - {"outer loop.output", outer("loop", "output"), "out", "publishes only its named outputs (result); loop.output"}, - {"outer loop variable", outer("loop", "draft"), "out", "loop.draft is not one"}, + {"outer named output", outer("loop", "result"), "", "", ""}, + {"outer loop.output", outer("loop", "output"), "out", "selector", "publishes only its named outputs (result); loop.output"}, + {"outer loop variable", outer("loop", "draft"), "out", "selector", "loop.draft is not one"}, {"outer template loop.output", func(g obj) { addNode(g, "after", "agent", obj{"agentConfig": obj{"executor": obj{"agentCli": "claude", "modelId": "model"}, "prompt": "Use {{#loop.output#}}"}}) connect(g, "loop", "after") - }, "after", "publishes only its named outputs"}, + }, "after", "agentConfig.prompt", "publishes only its named outputs"}, + {"outer condition value loop.output", func(g obj) { + addNode(g, "branch", "condition", obj{"cases": []any{obj{"id": "c1", "logic": "and", "conditions": []any{ + obj{"variableSelector": []string{"start", "input"}, "operator": "equals", "value": "{{#loop.output#}}"}, + }}}}) + connect(g, "loop", "branch") + }, "branch", "cases", "publishes only its named outputs"}, {"outer aggregator loop.output", func(g obj) { addNode(g, "agg", "aggregator", obj{"aggregatorConfig": obj{"variables": []any{[]string{"loop", "output"}}}}) connect(g, "loop", "agg") - }, "agg", "publishes only its named outputs"}, - {"body loop variable", body("Improve {{#loop.draft#}} for {{#start.input#}}"), "", ""}, - {"body loop output", body("Improve {{#loop.result#}}"), "writer", "only its loop variables (draft) are readable; loop.result"}, - {"body round start input", body("Improve {{#entry.input#}}"), "writer", "round Start entry assigns no variables"}, + }, "agg", "selector", "publishes only its named outputs"}, + {"body loop variable", body("Improve {{#loop.draft#}} for {{#start.input#}}"), "", "", ""}, + {"body loop output", body("Improve {{#loop.result#}}"), "writer", "agentConfig.prompt", "only its loop variables (draft) are readable; loop.result"}, + {"body round start input", body("Improve {{#entry.input#}}"), "writer", "agentConfig.prompt", "round Start entry assigns no variables"}, + + // The Loop's own configuration: until, feedback and outputs read the round pool. + {"until reads a loop variable", until("loop", "draft"), "", "", ""}, + {"until reads the round Start", until("entry", "input"), "loop", "loopConfig.until", "round Start entry assigns no variables"}, + {"until reads a named output", until("loop", "result"), "loop", "loopConfig.until", "only its loop variables (draft) are readable; loop.result"}, + {"until value template reads the round Start", func(g obj) { + loopConfig(g)["until"] = obj{"logic": "and", "conditions": []any{obj{"variableSelector": []string{"writer", "output"}, "operator": "equals", "value": "{{#entry.input#}}"}}} + }, "loop", "loopConfig.until", "round Start entry"}, + {"feedback reads the round Start", func(g obj) { carried(g)["feedback"] = []string{"entry", "input"} }, "loop", "loopConfig.variables[0].feedback", "round Start entry"}, + {"output binds a loop variable", func(g obj) { + loopConfig(g)["outputs"] = []any{obj{"name": "result", "variableSelector": []string{"loop", "draft"}}} + }, "", "", ""}, + {"output binds the round Start", func(g obj) { + loopConfig(g)["outputs"] = []any{obj{"name": "result", "variableSelector": []string{"entry", "input"}}} + }, "loop", "loopConfig.outputs[0].variableSelector", "round Start entry"}, + + // initial reads the pool the Loop starts in. + {"initial reads the upstream named output", second("loop", "result"), "", "", ""}, + {"initial reads the upstream loop.output", second("loop", "output"), "loop2", "loopConfig.variables[0].initial", "publishes only its named outputs (result); loop.output"}, + {"initial reads its own Loop", func(g obj) { + carried(g)["initial"] = obj{"kind": "variable", "selector": []string{"loop", "draft"}} + }, "loop", "loopConfig.variables[0].initial", "cannot read the Loop itself"}, + {"initial reads a round Start", second("entry", "input"), "loop2", "loopConfig.variables[0].initial", "round Start entry assigns no variables; entry.input is never set"}, + + // A body aggregator is typed against the body's own declarations. + {"body aggregator reads a body product", aggregate("writer", "output"), "", "", ""}, + {"body aggregator reads a loop variable", aggregate("loop", "draft"), "agg", "aggregatorConfig.variables", "produced in the Loop body or globals; loop.draft"}, + {"body aggregator reads the Loop's upstream", aggregate("start", "input"), "agg", "aggregatorConfig.variables", "start.input is not one"}, + + // A global named like a Loop variable resolves as the global. + {"global shadowing loop.output", global("loop.output", outer("loop", "output")), "", "", ""}, + {"global shadowing the round Start", global("entry.input", body("Use {{#entry.input#}}")), "", "", ""}, } { t.Run(test.name, func(t *testing.T) { g := fixture(t, "loop") @@ -52,8 +122,8 @@ func TestLoopReferences(t *testing.T) { return } var domain *workflow.ValidationError - if !errors.As(err, &domain) || domain.Code != "invalid_loop_reference" || domain.NodeID != test.nodeID || !strings.Contains(domain.Reason, test.reason) { - t.Fatalf("expected invalid_loop_reference on %s mentioning %q, got %v", test.nodeID, test.reason, err) + if !errors.As(err, &domain) || domain.Code != "invalid_loop_reference" || domain.NodeID != test.nodeID || domain.Field != test.field || !strings.Contains(domain.Reason, test.reason) { + t.Fatalf("expected invalid_loop_reference on %s %s mentioning %q, got %v", test.nodeID, test.field, test.reason, err) } }) } diff --git a/v2-server/internal/workflow/nodes.go b/v2-server/internal/workflow/nodes.go index d40be247a..f31aab303 100644 --- a/v2-server/internal/workflow/nodes.go +++ b/v2-server/internal/workflow/nodes.go @@ -130,7 +130,11 @@ func validateCondition(c reader, n *node, loop bool) { n.bindings = append(n.bindings, parts) } if text, ok := rule.value["value"].(string); ok { - n.templates = append(n.templates, text) + field := "cases" + if loop { + field = "loopConfig.until" + } + n.templates = append(n.templates, templateRef{text: text, field: field}) } } } diff --git a/v2-server/internal/workflow/validate.go b/v2-server/internal/workflow/validate.go index f9c1cf3de..6486a3549 100644 --- a/v2-server/internal/workflow/validate.go +++ b/v2-server/internal/workflow/validate.go @@ -54,7 +54,7 @@ func buildScopes(d *document) (map[string]*scope, error) { } // Before scope typing, so a stale Loop reference names its consumer instead of surfacing // as an undeclared aggregator candidate. - if err := validateLoopReferences(d); err != nil { + if err := validateLoopReferences(d, globals); err != nil { return nil, err } for _, e := range d.edges { @@ -114,10 +114,10 @@ func buildScopes(d *document) (map[string]*scope, error) { return nil, invalid("unused_reference", n.id, "selector", "variable references unused node "+parts[0]) } } - for _, text := range n.templates { - for _, parts := range templateSelectors(text) { + for _, template := range n.templates { + for _, parts := range templateSelectors(template.text) { if d.unused[parts[0]] { - return nil, invalid("unused_reference", n.id, "template", "template references unused node "+parts[0]) + return nil, invalid("unused_reference", n.id, template.field, "template references unused node "+parts[0]) } } } From 99cec6fea89b639b0aee2a6b2f0462a554153b90 Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 14:29:31 +0800 Subject: [PATCH 7/8] fix(v2): offer in-body aggregators only body variables; Loop membership by containerId Publication types an aggregator inside a Loop body against the body's own declarations, but the catalog offered it the loop variables and the Loop's upstream, which publish then refused. Such an aggregator now sees only globals and its in-body upstream products. Loop membership is now `data.containerId` everywhere in the catalog and the Loop panel, matching the backend, which refuses a Loop member without it; Iteration membership stays `parentId`. Refs ora-space/circus#1388 --- .../editor/workflow-node-details.tsx | 3 +- .../workflows/mock/variable-catalog.test.ts | 57 +++++++++++++++++++ .../lib/workflows/mock/variable-catalog.ts | 35 +++++++++--- 3 files changed, 86 insertions(+), 9 deletions(-) diff --git a/frontend-v2/src/features/workflows/editor/workflow-node-details.tsx b/frontend-v2/src/features/workflows/editor/workflow-node-details.tsx index 04b73c7d1..0673fa93f 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-node-details.tsx +++ b/frontend-v2/src/features/workflows/editor/workflow-node-details.tsx @@ -1023,8 +1023,9 @@ function LoopNodeDetails({ }: WorkflowNodeDetailsLayoutProps) { const { t } = useTranslation(); const loopConfig = node.data.loopConfig; + // Loop membership is `data.containerId`, as in the variable catalog and the backend. const childNodes = graphNodes.filter( - (candidate) => candidate.parentId === node.id, + (candidate) => candidate.data.containerId === node.id, ); const conditionCatalog: WorkflowVariableCatalogEntry[] = [ ...variableCatalog.filter((entry) => entry.sourceNodeId !== node.id), diff --git a/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts b/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts index a0458ffae..f65f265cd 100644 --- a/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts +++ b/frontend-v2/src/lib/workflows/mock/variable-catalog.test.ts @@ -381,3 +381,60 @@ describe("deriveWorkflowVariableCatalog loop scope rules", () => { ]); }); }); + +describe("deriveWorkflowVariableCatalog loop body aggregators and membership", () => { + const group = createMockWorkflowLoopGroup({ + sequence: 1, + position: { x: 0, y: 0 }, + locale: "zh-CN", + }); + const [loop, roundStart, loopAgent] = group.nodes as [ + Node, + Node, + Node, + ]; + const start = node("start", { kind: "start", title: "Start", description: "" }); + const aggregator = node( + "agg", + { + kind: "aggregator", + title: "Agg", + description: "", + containerId: loop.id, + aggregatorConfig: { variables: [] }, + }, + loop.id, + ); + const edges: Edge[] = [ + { id: "s-l", source: "start", target: loop.id }, + ...group.edges, + { id: "a-g", source: loopAgent.id, target: "agg" }, + ]; + + it("offers a body aggregator only globals and in-body products, as publication types it", () => { + const visible = deriveWorkflowVariableCatalog( + [start, loop, roundStart, loopAgent, aggregator], + edges, + "agg", + [{ name: "sys.workflow_id", valueType: "string" }], + ).map((entry) => entry.selector.join(".")); + expect(visible).toEqual(["sys.workflow_id", `${loopAgent.id}.output`]); + }); + + it("treats a node as a Loop member by containerId, not by parentId alone", () => { + // A parentId-only child of a Loop is refused by the backend; the catalog does not treat + // it as a body member either, so it gets no loop variables. + const stray = node( + "stray", + { kind: "agent", title: "Stray", description: "" }, + loop.id, + ); + const visible = deriveWorkflowVariableCatalog( + [start, loop, roundStart, loopAgent, stray], + [...edges, { id: "a-s", source: loopAgent.id, target: "stray" }], + "stray", + [], + ).map((entry) => entry.selector.join(".")); + expect(visible).not.toContain(`${loop.id}.value`); + }); +}); diff --git a/frontend-v2/src/lib/workflows/mock/variable-catalog.ts b/frontend-v2/src/lib/workflows/mock/variable-catalog.ts index 4de2e5f5e..3c2e7e814 100644 --- a/frontend-v2/src/lib/workflows/mock/variable-catalog.ts +++ b/frontend-v2/src/lib/workflows/mock/variable-catalog.ts @@ -57,7 +57,12 @@ function arrayElementType(valueType: string): string { * `loopConfig.outputs` and never a `{loop}.output`: outer consumers see those named outputs; * body members see the carried loop variables, their in-body upstream products, and every * variable visible to the Loop itself (its upstream, e.g. `start.input`). A body's round - * Start assigns nothing, so it contributes no variables. + * Start assigns nothing, so it contributes no variables. An Aggregator inside a body is the + * exception: publication types it against the body's own declarations, so it sees only + * globals and its in-body upstream products. + * + * Loop membership is `data.containerId` (the backend refuses a Loop member without it); + * Iteration membership is `parentId`. */ export function deriveWorkflowVariableCatalog( nodes: Array>, @@ -65,19 +70,31 @@ export function deriveWorkflowVariableCatalog( consumerNodeId?: string, globalVariables: WorkflowGlobalVariable[] = DEFAULT_WORKFLOW_GLOBAL_VARIABLES, ): WorkflowVariableCatalogEntry[] { - // Container membership: Iteration members by `parentId` (as the frozen graph persists it), - // Loop members by `data.containerId` with `parentId` as the legacy fallback. const kindById = new Map(nodes.map((node) => [node.id, node.data.kind])); const owningContainerOf = (nodeId: string): string | null => { const member = nodes.find((node) => node.id === nodeId); - const owner = member?.data.containerId ?? member?.parentId; - const kind = owner === undefined ? undefined : kindById.get(owner); - return kind === "iteration" || kind === "loop" ? owner! : null; + if (member === undefined) { + return null; + } + const loopId = member.data.containerId; + if (loopId !== undefined) { + return kindById.get(loopId) === "loop" ? loopId : null; + } + const parent = member.parentId; + return parent !== undefined && kindById.get(parent) === "iteration" + ? parent + : null; }; const consumerOwner = consumerNodeId === undefined ? null : owningContainerOf(consumerNodeId); + const consumerIsAggregator = + consumerNodeId !== undefined && + kindById.get(consumerNodeId) === "aggregator"; + // The Loop whose round pool the consumer reads: loop variables and the Loop's upstream. const consumerLoopId = - consumerOwner !== null && kindById.get(consumerOwner) === "loop" + consumerOwner !== null && + kindById.get(consumerOwner) === "loop" && + !consumerIsAggregator ? consumerOwner : null; @@ -108,7 +125,9 @@ export function deriveWorkflowVariableCatalog( continue; } // A Loop's round Start only marks the body entry; the engine never assigns its - // `input` or declared fields, so offering them would fail every run. + // `input` or declared fields, so offering them would fail every run. Like the backend, + // any Start carrying `containerId` is a round Start, even when the caller passes only + // the body (the Loop panel does). if (node.data.containerId !== undefined) { continue; } From 0196e37758d98ed5393028567d2345350bcff7a7 Mon Sep 17 00:00:00 2001 From: Eric Wang Date: Mon, 23 Nov 2026 14:29:31 +0800 Subject: [PATCH 8/8] fix(v2): keep a pending publish in its dialog and name where a reference was written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cancel or Escape while a publish was pending closed the dialog, and a later refusal was then shown nowhere. The dialog now stays open until the publish settles; a ref guards against a second submit in the same tick, and tests cover both. Refusal fields follow the server's new template sources: an Agent prompt reads 提示词变量, a Condition value 分支条件, and a Loop's initial value, next-round value, end condition and outputs are named as such. Refs ora-space/circus#1388 --- .../workflows/editor/workflow-editor.tsx | 23 ++++++++++-- .../editor/workflow-publish-error.test.ts | 16 +++++++++ .../editor/workflow-publish-error.ts | 6 +++- .../src/features/workflows/page.test.tsx | 36 +++++++++++++++++++ .../src/lib/workflows/editor/translations.ts | 12 +++++-- 5 files changed, 87 insertions(+), 6 deletions(-) diff --git a/frontend-v2/src/features/workflows/editor/workflow-editor.tsx b/frontend-v2/src/features/workflows/editor/workflow-editor.tsx index 357085b22..fa7b25b75 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-editor.tsx +++ b/frontend-v2/src/features/workflows/editor/workflow-editor.tsx @@ -571,6 +571,9 @@ function WorkflowEditorContent({ // A refused publish stays in its dialog, so the author sees it was the publish, not a save. const [publishFailure, setPublishFailure] = useState(null); + // Set synchronously so a second Enter or click in the same tick cannot publish twice; the + // mutation's own `isPending` only updates on the next render. + const publishingRef = useRef(false); const inspectorPanelRef = useRef(null); const inspectorAnimationRef = useRef(null); /** Bumps on every persistable edit so in-flight writes can detect they are stale. */ @@ -1481,9 +1484,10 @@ function WorkflowEditorContent({ /** Publishes the current draft as an immutable snapshot with an optional version name. */ async function confirmPublish(): Promise { - if (workflow === null || publishWorkflowMutation.isPending) { + if (workflow === null || publishingRef.current) { return; } + publishingRef.current = true; setPublishFailure(null); setManagerError(null); const version = publishVersionName.trim(); @@ -1507,6 +1511,8 @@ function WorkflowEditorContent({ t, ), ); + } finally { + publishingRef.current = false; } } @@ -3134,7 +3140,16 @@ function WorkflowEditorContent({ - + { + // The dialog is where a refusal is reported; closing it mid-publish would hide one. + if (!open && publishWorkflowMutation.isPending) { + return; + } + setPublishDialogOpen(open); + }} + > @@ -3173,7 +3188,9 @@ function WorkflowEditorContent({ )} - {t("common.cancel")} + + {t("common.cancel")} + void confirmPublish()} diff --git a/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts b/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts index b5c265847..ba47ba5e7 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts +++ b/frontend-v2/src/features/workflows/editor/workflow-publish-error.test.ts @@ -40,6 +40,22 @@ describe("describePublishFailure", () => { expect(message("iterationConfig.collectSelector")).toBe( "发布被拒绝:节点「汇总输出」的收集变量没有通过发布校验,草稿已保存。", ); + // Templates are named by where they were written, not as a generic "template". + expect(message("agentConfig.prompt")).toBe( + "发布被拒绝:节点「汇总输出」的提示词变量没有通过发布校验,草稿已保存。", + ); + expect(message("cases")).toBe( + "发布被拒绝:节点「汇总输出」的分支条件没有通过发布校验,草稿已保存。", + ); + expect(message("loopConfig.until")).toBe( + "发布被拒绝:节点「汇总输出」的结束条件没有通过发布校验,草稿已保存。", + ); + expect(message("loopConfig.variables[0].initial")).toBe( + "发布被拒绝:节点「汇总输出」的循环变量初始值没有通过发布校验,草稿已保存。", + ); + expect(message("loopConfig.outputs[0].variableSelector")).toBe( + "发布被拒绝:节点「汇总输出」的循环输出没有通过发布校验,草稿已保存。", + ); }); it("falls back to the node id and the raw field the editor has no words for", () => { diff --git a/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts b/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts index 5ce32756a..fecbcc21e 100644 --- a/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts +++ b/frontend-v2/src/features/workflows/editor/workflow-publish-error.ts @@ -20,13 +20,17 @@ const FIELD_LABELS: ReadonlyArray = [ ["iterationConfig.collectSelector", "settings.workflow.publishField.collect"], ["iterationConfig", "settings.workflow.publishField.iteration"], ["aggregatorConfig", "settings.workflow.publishField.aggregator"], + ["loopConfig.variables.initial", "settings.workflow.publishField.loopInitial"], + ["loopConfig.variables.feedback", "settings.workflow.publishField.loopFeedback"], + ["loopConfig.until", "settings.workflow.publishField.loopUntil"], + ["loopConfig.outputs", "settings.workflow.publishField.loopOutputs"], ["loopConfig", "settings.workflow.publishField.loop"], + ["agentConfig.prompt", "settings.workflow.publishField.prompt"], ["agentConfig", "settings.workflow.publishField.agent"], ["outputs", "settings.workflow.publishField.outputs"], ["inputVariables", "settings.workflow.publishField.inputs"], ["cases", "settings.workflow.publishField.cases"], ["selector", "settings.workflow.publishField.selector"], - ["template", "settings.workflow.publishField.template"], ["edges", "settings.workflow.publishField.edges"], ["edge", "settings.workflow.publishField.edges"], ["parentId", "settings.workflow.publishField.container"], diff --git a/frontend-v2/src/features/workflows/page.test.tsx b/frontend-v2/src/features/workflows/page.test.tsx index 5c8979b09..f155ecf63 100644 --- a/frontend-v2/src/features/workflows/page.test.tsx +++ b/frontend-v2/src/features/workflows/page.test.tsx @@ -161,6 +161,42 @@ describe("workflow page", () => { expect(screen.getByText("暂未发布")).toBeInTheDocument(); }); + it("publishes once and keeps the dialog until a pending publish settles", async () => { + const user = userEvent.setup(); + await renderPage(); + await createWorkflow(user, "慢发布"); + await screen.findByDisplayValue("慢发布"); + let release!: () => void; + server.hold = { match: /POST .*\/publish$/, until: new Promise((resolve) => (release = resolve)) }; + server.refuse = { + match: /POST .*\/publish$/, + status: 409, + data: { code: "workflow_version_already_exists", params: {}, requestId: "r" }, + }; + + await user.click(await screen.findByRole("button", { name: "发布" })); + const dialog = await screen.findByRole("alertdialog", { name: "发布工作流" }); + const version = within(dialog).getByRole("textbox"); + await user.type(version, "v1"); + await user.click(within(dialog).getByRole("button", { name: "发布" })); + // A second submit while the first is in flight, by Enter so a disabled button cannot hide it. + fireEvent.keyDown(version, { key: "Enter" }); + await waitFor(() => expect(within(dialog).getByRole("button", { name: "取消" })).toBeDisabled()); + expect(within(dialog).getByRole("button", { name: "发布" })).toBeDisabled(); + // Escape from inside the dialog, where it would otherwise dismiss it. + await user.click(version); + await user.keyboard("{Escape}"); + // Base UI keeps a closing popup mounted for its exit, marking it `data-closed`. + expect(dialog).toHaveAttribute("data-open"); + expect(dialog).not.toHaveAttribute("data-closed"); + + release(); + expect(await within(dialog).findByText("发布失败:该工作流版本已存在。")).toBeInTheDocument(); + expect(dialog).toHaveAttribute("data-open"); + expect(server.seen.filter((request) => /POST .*\/publish$/.test(request))).toHaveLength(1); + expect(within(dialog).getByRole("button", { name: "取消" })).toBeEnabled(); + }); + it("offers once to import the workflows this browser kept", async () => { const user = userEvent.setup(); new LocalWorkflowBackend({ storage: browserWorkflowStorage }).create({ name: "本机旧流程", graph: null }); diff --git a/frontend-v2/src/lib/workflows/editor/translations.ts b/frontend-v2/src/lib/workflows/editor/translations.ts index c5d16f5b2..09ac43a10 100644 --- a/frontend-v2/src/lib/workflows/editor/translations.ts +++ b/frontend-v2/src/lib/workflows/editor/translations.ts @@ -421,7 +421,11 @@ export const workflowEditorTranslations = { "发布被拒绝:节点「{{node}}」没有通过发布校验({{field}}),草稿已保存。", "settings.workflow.publishRejectedDetail": "服务端说明:", "settings.workflow.publishField.selector": "变量引用", - "settings.workflow.publishField.template": "提示词变量", + "settings.workflow.publishField.prompt": "提示词变量", + "settings.workflow.publishField.loopInitial": "循环变量初始值", + "settings.workflow.publishField.loopFeedback": "循环变量的下一轮取值", + "settings.workflow.publishField.loopUntil": "结束条件", + "settings.workflow.publishField.loopOutputs": "循环输出", "settings.workflow.publishField.aggregator": "聚合变量", "settings.workflow.publishField.iterator": "迭代源", "settings.workflow.publishField.collect": "收集变量", @@ -1100,7 +1104,11 @@ export const workflowEditorTranslations = { "Publishing was rejected: node “{{node}}” failed publish validation ({{field}}). The draft is saved.", "settings.workflow.publishRejectedDetail": "Server says: ", "settings.workflow.publishField.selector": "variable reference", - "settings.workflow.publishField.template": "prompt variable", + "settings.workflow.publishField.prompt": "prompt variable", + "settings.workflow.publishField.loopInitial": "loop variable's initial value", + "settings.workflow.publishField.loopFeedback": "loop variable's next-round value", + "settings.workflow.publishField.loopUntil": "end conditions", + "settings.workflow.publishField.loopOutputs": "loop outputs", "settings.workflow.publishField.aggregator": "aggregated variables", "settings.workflow.publishField.iterator": "iteration source", "settings.workflow.publishField.collect": "collected variable",