Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions frontend-v2/e2e/workflow-container-editor.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {}, 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()
})
65 changes: 58 additions & 7 deletions frontend-v2/src/features/workflows/editor/workflow-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -564,6 +568,12 @@ 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<WorkflowPublishFailure | null>(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<ResizablePanelHandle | null>(null);
const inspectorAnimationRef = useRef<number | null>(null);
/** Bumps on every persistable edit so in-flight writes can detect they are stale. */
Expand Down Expand Up @@ -1459,6 +1469,7 @@ function WorkflowEditorContent({
if (previewedVersionRef.current !== null) {
setPreviewedVersion(null);
setPublishVersionName("");
setPublishFailure(null);
setPublishDialogOpen(true);
return;
}
Expand All @@ -1467,29 +1478,41 @@ 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<void> {
if (workflow === null) {
if (workflow === null || publishingRef.current) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2-4(建议) 导入后自动发布也使用 publishWorkflowMutation,该路径没有设置 publishingRef。我让自动发布请求保持进行中,打开手动发布对话框,看到发布按钮已禁用,但在版本名输入框按 Enter 仍发出了第二个 POST /publish,可能生成额外版本。建议保留 isPending 检查,并用 ref 兜住手动提交同一拍的重复触发。

Suggested change
if (workflow === null || publishingRef.current) {
if (workflow === null || publishingRef.current || publishWorkflowMutation.isPending) {

可直接采纳,也可以不改。

return;
}
setPublishDialogOpen(false);
publishingRef.current = true;
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,
),
);
} finally {
publishingRef.current = false;
}
}

Expand Down Expand Up @@ -3117,7 +3140,16 @@ function WorkflowEditorContent({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={publishDialogOpen} onOpenChange={setPublishDialogOpen}>
<AlertDialog
open={publishDialogOpen}
onOpenChange={(open) => {
// The dialog is where a refusal is reported; closing it mid-publish would hide one.
if (!open && publishWorkflowMutation.isPending) {
return;
}
setPublishDialogOpen(open);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
Expand All @@ -3130,7 +3162,10 @@ function WorkflowEditorContent({
{publishDialogOpen && workflow && <PinnedSchedulesWarning workflowId={workflow.id} />}
<Input
value={publishVersionName}
onChange={(event) => setPublishVersionName(event.target.value)}
onChange={(event) => {
setPublishVersionName(event.target.value);
setPublishFailure(null);
}}
aria-label={t("settings.workflow.versionHistory")}
placeholder={t("settings.workflow.publishVersionPlaceholder")}
autoFocus
Expand All @@ -3141,9 +3176,25 @@ function WorkflowEditorContent({
}
}}
/>
{publishFailure !== null && (
<div role="alert" className="text-destructive space-y-1 text-sm">
<p>{publishFailure.message}</p>
{publishFailure.detail !== null && (
<p className="text-muted-foreground text-xs break-words">
{t("settings.workflow.publishRejectedDetail")}
<code>{publishFailure.detail}</code>
</p>
)}
</div>
)}
<AlertDialogFooter>
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => void confirmPublish()}>
<AlertDialogCancel disabled={publishWorkflowMutation.isPending}>
{t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
disabled={publishWorkflowMutation.isPending}
onClick={() => void confirmPublish()}
>
<IconVersions />
{t("settings.workflow.publish")}
</AlertDialogAction>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */}
<Handle
type="target"
position={Position.Left}
data-workflow-input={id}
aria-label={t("settings.workflow.connectTo", { name: data.title })}
className={cn(
"workflow-port workflow-port-input !size-2.5 !border-0 !bg-transparent",
"workflow-port workflow-port-input z-30 !size-2.5 !border-0 !bg-transparent",
isInputCandidate && "workflow-port-candidate",
)}
style={{ top: WORKFLOW_ITERATION_HEADER_HEIGHT / 2 }}
Expand All @@ -142,7 +145,7 @@ export function IterationNodeFrame({
data-workflow-output={id}
aria-label={t("settings.workflow.connectFrom", { name: data.title })}
className={cn(
"workflow-port workflow-port-output !size-2.5 !border-0 !bg-transparent",
"workflow-port workflow-port-output z-30 !size-2.5 !border-0 !bg-transparent",
isOutputCandidate && "workflow-port-candidate",
)}
style={{ top: WORKFLOW_ITERATION_HEADER_HEIGHT / 2 }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
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<string, string> = { 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(
"发布被拒绝:节点「汇总输出」的收集变量没有通过发布校验,草稿已保存。",
);
// 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", () => {
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(/^发布失败:/);
});
});
Loading
Loading