Commit inicial - upload de todos os arquivos da pasta

This commit is contained in:
2026-01-04 16:14:31 -03:00
commit e3ed1a734b
310 changed files with 62749 additions and 0 deletions

View File

@@ -0,0 +1,689 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/Canva.tsx │
│ Developed by: Davidson Gomes │
│ Delay node integration developed by: Victor Calazans │
│ Creation date: May 13, 2025 |
│ Delay implementation date: May 17, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import {
useState,
useEffect,
useRef,
useCallback,
forwardRef,
useImperativeHandle,
} from "react";
import {
Controls,
ReactFlow,
addEdge,
useNodesState,
useEdgesState,
type OnConnect,
ConnectionMode,
ConnectionLineType,
useReactFlow,
ProOptions,
applyNodeChanges,
NodeChange,
OnNodesChange,
MiniMap,
Panel,
Background,
} from "@xyflow/react";
import { useDnD } from "@/contexts/DnDContext";
import { Edit, X, ChevronLeft, ChevronRight } from "lucide-react";
import "@xyflow/react/dist/style.css";
import "./canva.css";
import { getHelperLines } from "./utils";
import { NodePanel } from "./NodePanel";
import ContextMenu from "./ContextMenu";
import { initialEdges, edgeTypes } from "./edges";
import HelperLines from "./HelperLines";
import { initialNodes, nodeTypes } from "./nodes";
import { AgentForm } from "./nodes/components/agent/AgentForm";
import { ConditionForm } from "./nodes/components/condition/ConditionForm";
import { Agent, WorkflowData } from "@/types/agent";
import { updateAgent } from "@/services/agentService";
import { useToast } from "@/hooks/use-toast";
import { MessageForm } from "./nodes/components/message/MessageForm";
import { DelayForm } from "./nodes/components/delay/DelayForm";
import { Button } from "@/components/ui/button";
const proOptions: ProOptions = { account: "paid-pro", hideAttribution: true };
const NodeFormWrapper = ({
selectedNode,
editingLabel,
setEditingLabel,
handleUpdateNode,
setSelectedNode,
children,
}: {
selectedNode: any;
editingLabel: boolean;
setEditingLabel: (value: boolean) => void;
handleUpdateNode: (node: any) => void;
setSelectedNode: (node: any) => void;
children: React.ReactNode;
}) => {
// Handle ESC key to close the panel
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape" && !editingLabel) {
setSelectedNode(null);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [setSelectedNode, editingLabel]);
return (
<div className="flex flex-col h-full">
<div className="flex-shrink-0 sticky top-0 z-20 bg-neutral-800 shadow-md border-b border-neutral-700">
<div className="p-4 text-center relative">
<button
className="absolute right-2 top-2 text-neutral-200 hover:text-white p-1 rounded-full hover:bg-neutral-700"
onClick={() => setSelectedNode(null)}
aria-label="Close panel"
>
<X size={18} />
</button>
{!editingLabel ? (
<div className="flex items-center justify-center text-xl font-bold text-neutral-200">
<span>{selectedNode.data.label}</span>
{selectedNode.type !== "start-node" && (
<Edit
size={16}
className="ml-2 cursor-pointer hover:text-indigo-300"
onClick={() => setEditingLabel(true)}
/>
)}
</div>
) : (
<input
type="text"
value={selectedNode.data.label}
className="w-full p-2 text-center text-xl font-bold bg-neutral-800 text-neutral-200 border border-neutral-600 rounded"
onChange={(e) => {
handleUpdateNode({
...selectedNode,
data: {
...selectedNode.data,
label: e.target.value,
},
});
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
setEditingLabel(false);
}
}}
onBlur={() => setEditingLabel(false)}
autoFocus
/>
)}
</div>
</div>
<div className="flex-1 min-h-0 overflow-hidden">{children}</div>
</div>
);
};
const Canva = forwardRef(({ agent }: { agent: Agent | null }, ref) => {
const { toast } = useToast();
const [nodes, setNodes] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const { screenToFlowPosition } = useReactFlow();
const { type, setPointerEvents } = useDnD();
const [menu, setMenu] = useState<any>(null);
const localRef = useRef<any>(null);
const [selectedNode, setSelectedNode] = useState<any>(null);
const [activeExecutionNodeId, setActiveExecutionNodeId] = useState<
string | null
>(null);
const [editingLabel, setEditingLabel] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const [nodePanelOpen, setNodePanelOpen] = useState(false);
useImperativeHandle(ref, () => ({
getFlowData: () => ({
nodes,
edges,
}),
setHasChanges,
setActiveExecutionNodeId,
}));
// Effect to clear the active node after a timeout
useEffect(() => {
if (activeExecutionNodeId) {
const timer = setTimeout(() => {
setActiveExecutionNodeId(null);
}, 5000); // Increase to 5 seconds to give more time to visualize
return () => clearTimeout(timer);
}
}, [activeExecutionNodeId]);
useEffect(() => {
if (
agent?.config?.workflow &&
agent.config.workflow.nodes.length > 0 &&
agent.config.workflow.edges.length > 0
) {
setNodes(
(agent.config.workflow.nodes as typeof initialNodes) || initialNodes
);
setEdges(
(agent.config.workflow.edges as typeof initialEdges) || initialEdges
);
} else {
setNodes(initialNodes);
setEdges(initialEdges);
}
}, [agent, setNodes, setEdges]);
// Update nodes when the active node changes to add visual class
useEffect(() => {
if (nodes.length > 0) {
setNodes((nds: any) =>
nds.map((node: any) => {
if (node.id === activeExecutionNodeId) {
// Add a class to highlight the active node
return {
...node,
className: "active-execution-node",
data: {
...node.data,
isExecuting: true,
},
};
} else {
// Remove the highlight class
const { isExecuting, ...restData } = node.data || {};
return {
...node,
className: "",
data: restData,
};
}
})
);
}
}, [activeExecutionNodeId, setNodes]);
useEffect(() => {
if (agent?.config?.workflow) {
const initialNodes = agent.config.workflow.nodes || [];
const initialEdges = agent.config.workflow.edges || [];
if (
JSON.stringify(nodes) !== JSON.stringify(initialNodes) ||
JSON.stringify(edges) !== JSON.stringify(initialEdges)
) {
setHasChanges(true);
} else {
setHasChanges(false);
}
}
}, [nodes, edges, agent]);
const [helperLineHorizontal, setHelperLineHorizontal] = useState<
number | undefined
>(undefined);
const [helperLineVertical, setHelperLineVertical] = useState<
number | undefined
>(undefined);
const onConnect: OnConnect = useCallback(
(connection) => {
setEdges((currentEdges) => {
if (connection.source === connection.target) {
return currentEdges;
}
return addEdge(connection, currentEdges);
});
},
[setEdges]
);
const onConnectEnd = useCallback(
(_event: any, connectionState: any) => {
setPointerEvents("none");
if (connectionState.fromHandle?.type === "target") {
return;
}
if (!connectionState.isValid) {
// Since we're using NodePanel now, we don't need to do anything here
// The panel will handle node creation through drag and drop
}
},
[setPointerEvents]
);
const onConnectStart = useCallback(() => {
setPointerEvents("auto");
}, [setPointerEvents]);
const customApplyNodeChanges = useCallback(
(changes: NodeChange[], nodes: any): any => {
// reset the helper lines (clear existing lines, if any)
setHelperLineHorizontal(undefined);
setHelperLineVertical(undefined);
// this will be true if it's a single node being dragged
// inside we calculate the helper lines and snap position for the position where the node is being moved to
if (
changes.length === 1 &&
changes[0].type === "position" &&
changes[0].dragging &&
changes[0].position
) {
const helperLines = getHelperLines(changes[0], nodes);
// if we have a helper line, we snap the node to the helper line position
// this is being done by manipulating the node position inside the change object
changes[0].position.x =
helperLines.snapPosition.x ?? changes[0].position.x;
changes[0].position.y =
helperLines.snapPosition.y ?? changes[0].position.y;
// if helper lines are returned, we set them so that they can be displayed
setHelperLineHorizontal(helperLines.horizontal);
setHelperLineVertical(helperLines.vertical);
}
return applyNodeChanges(changes, nodes);
},
[]
);
const onNodesChange: OnNodesChange = useCallback(
(changes) => {
setNodes((nodes) => customApplyNodeChanges(changes, nodes));
},
[setNodes, customApplyNodeChanges]
);
const getLabelFromNode = (type: string) => {
const order = nodes.length;
switch (type) {
case "start-node":
return "Start";
case "agent-node":
return `Agent #${order}`;
case "condition-node":
return `Condition #${order}`;
case "message-node":
return `Message #${order}`;
case "delay-node":
return `Delay #${order}`;
default:
return "Node";
}
};
const handleAddNode = useCallback(
(type: any, node: any) => {
const newNode: any = {
id: String(Date.now()),
type,
position: node.position,
data: {
label: getLabelFromNode(type),
},
};
setNodes((nodes) => [...nodes, newNode]);
if (node.targetId) {
const newEdge: any = {
source: node.targetId,
sourceHandle: node.handleId,
target: newNode.id,
type: "default",
};
const newsEdges: any = [...edges, newEdge];
setEdges(newsEdges);
}
},
[nodes, setNodes, edges, setEdges]
);
const handleUpdateNode = useCallback(
(node: any) => {
setNodes((nodes) => {
const index = nodes.findIndex((n) => n.id === node.id);
if (index !== -1) {
nodes[index] = node;
}
return [...nodes];
});
if (selectedNode && selectedNode.id === node.id) {
setSelectedNode(node);
}
},
[setNodes, selectedNode]
);
const handleDeleteEdge = useCallback(
(id: any) => {
setEdges((edges) => {
const left = edges.filter((edge: any) => edge.id !== id);
return left;
});
},
[setEdges]
);
const onDragOver = useCallback((event: any) => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
}, []);
const onDrop = useCallback(
(event: any) => {
event.preventDefault();
if (!type) {
return;
}
const position = screenToFlowPosition({
x: event.clientX,
y: event.clientY,
});
const newNode: any = {
id: String(Date.now()),
type,
position,
data: {
label: getLabelFromNode(type),
},
};
setNodes((nodes) => [...nodes, newNode]);
},
[screenToFlowPosition, setNodes, type, getLabelFromNode]
);
const onNodeContextMenu = useCallback(
(event: any, node: any) => {
event.preventDefault();
if (node.id === "start-node") {
return;
}
if (!localRef.current) {
return;
}
const paneBounds = localRef.current.getBoundingClientRect();
const x = event.clientX - paneBounds.left;
const y = event.clientY - paneBounds.top;
const menuWidth = 200;
const menuHeight = 200;
const left = x + menuWidth > paneBounds.width ? undefined : x;
const top = y + menuHeight > paneBounds.height ? undefined : y;
const right =
x + menuWidth > paneBounds.width ? paneBounds.width - x : undefined;
const bottom =
y + menuHeight > paneBounds.height ? paneBounds.height - y : undefined;
setMenu({
id: node.id,
left,
top,
right,
bottom,
});
},
[setMenu]
);
const onNodeClick = useCallback((event: any, node: any) => {
event.preventDefault();
if (node.type === "start-node") {
return;
}
setSelectedNode(node);
}, []);
const onPaneClick = useCallback(() => {
setMenu(null);
setSelectedNode(null);
setNodePanelOpen(false);
}, [setMenu, setSelectedNode]);
return (
<div className="h-full w-full bg-[#121212]">
<div
style={{ position: "relative", height: "100%", width: "100%" }}
ref={localRef}
className="overflow-hidden"
>
<ReactFlow
nodes={nodes}
nodeTypes={nodeTypes}
onNodesChange={onNodesChange}
edges={edges}
edgeTypes={edgeTypes}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onConnectStart={onConnectStart}
onConnectEnd={onConnectEnd}
connectionMode={ConnectionMode.Strict}
connectionLineType={ConnectionLineType.Bezier}
onDrop={onDrop}
onDragOver={onDragOver}
onPaneClick={onPaneClick}
onNodeClick={onNodeClick}
onNodeContextMenu={onNodeContextMenu}
colorMode="dark"
minZoom={0.1}
maxZoom={10}
fitView={false}
defaultViewport={{
x: 0,
y: 0,
zoom: 1,
}}
elevateEdgesOnSelect
elevateNodesOnSelect
proOptions={proOptions}
connectionLineStyle={{
stroke: "gray",
strokeWidth: 2,
strokeDashoffset: 5,
strokeDasharray: 5,
}}
defaultEdgeOptions={{
type: "default",
style: {
strokeWidth: 3,
},
data: {
handleDeleteEdge,
},
}}
>
<Background color="#334155" gap={24} size={1.5} />
<MiniMap
className="bg-neutral-800/80 border border-neutral-700 rounded-lg shadow-lg"
nodeColor={(node) => {
switch (node.type) {
case "start-node":
return "#10b981";
case "agent-node":
return "#3b82f6";
case "message-node":
return "#f97316";
case "condition-node":
return "#3b82f6";
case "delay-node":
return "#eab308";
default:
return "#64748b";
}
}}
maskColor="rgba(15, 23, 42, 0.6)"
/>
<Controls
showInteractive={true}
showFitView={true}
orientation="vertical"
position="bottom-left"
/>
<HelperLines
horizontal={helperLineHorizontal}
vertical={helperLineVertical}
/>
{menu && <ContextMenu onClick={onPaneClick} {...menu} />}
{nodePanelOpen ? (
<Panel position="top-right">
<div className="flex items-start">
<Button
variant="outline"
size="icon"
onClick={() => setNodePanelOpen(false)}
className="mr-2 h-8 w-8 rounded-full bg-slate-800 border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700"
>
<ChevronRight className="h-4 w-4" />
</Button>
<NodePanel />
</div>
</Panel>
) : (
<Panel position="top-right">
<Button
variant="outline"
size="icon"
onClick={() => setNodePanelOpen(true)}
className="h-8 w-8 rounded-full bg-slate-800 border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700"
>
<ChevronLeft className="h-4 w-4" />
</Button>
</Panel>
)}
</ReactFlow>
{/* Overlay when form is open on smaller screens */}
{selectedNode && (
<div
className="md:hidden fixed inset-0 bg-black bg-opacity-50 z-[5] transition-opacity duration-300"
onClick={() => setSelectedNode(null)}
/>
)}
<div
className="absolute left-0 top-0 z-10 h-full w-[350px] bg-neutral-900 shadow-lg transition-all duration-300 ease-in-out border-r border-neutral-700 flex flex-col"
style={{
transform: selectedNode ? "translateX(0)" : "translateX(-100%)",
opacity: selectedNode ? 1 : 0,
}}
>
{selectedNode ? (
<NodeFormWrapper
selectedNode={selectedNode}
editingLabel={editingLabel}
setEditingLabel={setEditingLabel}
handleUpdateNode={handleUpdateNode}
setSelectedNode={setSelectedNode}
>
{selectedNode.type === "agent-node" && (
<AgentForm
selectedNode={selectedNode}
handleUpdateNode={handleUpdateNode}
setEdges={setEdges}
setIsOpen={() => {}}
setSelectedNode={setSelectedNode}
/>
)}
{selectedNode.type === "condition-node" && (
<ConditionForm
selectedNode={selectedNode}
handleUpdateNode={handleUpdateNode}
setEdges={setEdges}
setIsOpen={() => {}}
setSelectedNode={setSelectedNode}
/>
)}
{selectedNode.type === "message-node" && (
<MessageForm
selectedNode={selectedNode}
handleUpdateNode={handleUpdateNode}
setEdges={setEdges}
setIsOpen={() => {}}
setSelectedNode={setSelectedNode}
/>
)}
{selectedNode.type === "delay-node" && (
<DelayForm
selectedNode={selectedNode}
handleUpdateNode={handleUpdateNode}
setEdges={setEdges}
setIsOpen={() => {}}
setSelectedNode={setSelectedNode}
/>
)}
</NodeFormWrapper>
) : null}
</div>
</div>
</div>
);
});
Canva.displayName = "Canva";
export default Canva;

View File

@@ -0,0 +1,118 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/ContextMenu.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import { useReactFlow, Node, Edge } from "@xyflow/react";
import { Copy, Trash2 } from "lucide-react";
import React, { useCallback } from "react";
interface ContextMenuProps extends React.HTMLAttributes<HTMLDivElement> {
id: string;
top?: number | string;
left?: number | string;
right?: number | string;
bottom?: number | string;
}
export default function ContextMenu({
id,
top,
left,
right,
bottom,
...props
}: ContextMenuProps) {
const { getNode, setNodes, addNodes, setEdges } = useReactFlow();
const duplicateNode = useCallback(() => {
const node = getNode(id);
if (!node) {
console.error(`Node with id ${id} not found.`);
return;
}
const position = {
x: node.position.x + 50,
y: node.position.y + 50,
};
addNodes({
...node,
id: `${node.id}-copy`,
position,
selected: false,
dragging: false,
});
}, [id, getNode, addNodes]);
const deleteNode = useCallback(() => {
setNodes((nodes: Node[]) => nodes.filter((node) => node.id !== id));
setEdges((edges: Edge[]) =>
edges.filter((edge) => edge.source !== id && edge.target !== id),
);
}, [id, setNodes, setEdges]);
return (
<div
style={{
position: "absolute",
top: top !== undefined ? `${top}px` : undefined,
left: left !== undefined ? `${left}px` : undefined,
right: right !== undefined ? `${right}px` : undefined,
bottom: bottom !== undefined ? `${bottom}px` : undefined,
zIndex: 10,
}}
className="context-menu rounded-md border p-3 shadow-lg border-neutral-700 bg-neutral-800"
{...props}
>
<p className="mb-2 text-sm font-semibold text-neutral-200">
Actions
</p>
<button
onClick={duplicateNode}
className="mb-1 flex w-full flex-row items-center rounded-md px-2 py-1 text-sm hover:bg-neutral-700"
>
<Copy
size={16}
className="mr-2 flex-shrink-0 text-blue-300"
/>
<span className="text-neutral-300">Duplicate</span>
</button>
<button
onClick={deleteNode}
className="flex w-full flex-row items-center rounded-md px-2 py-1 text-sm hover:bg-neutral-700"
>
<Trash2
size={16}
className="mr-2 flex-shrink-0 text-red-300"
/>
<span className="text-neutral-300">Delete</span>
</button>
</div>
);
}

View File

@@ -0,0 +1,98 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/HelperLines.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import { ReactFlowState, useStore } from "@xyflow/react";
import { CSSProperties, useEffect, useRef } from "react";
const canvasStyle: CSSProperties = {
width: "100%",
height: "100%",
position: "absolute",
zIndex: 10,
pointerEvents: "none",
};
const storeSelector = (state: ReactFlowState) => ({
width: state.width,
height: state.height,
transform: state.transform,
});
export type HelperLinesProps = {
horizontal?: number;
vertical?: number;
};
// a simple component to display the helper lines
// it puts a canvas on top of the React Flow pane and draws the lines using the canvas API
function HelperLinesRenderer({ horizontal, vertical }: HelperLinesProps) {
const { width, height, transform } = useStore(storeSelector);
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!ctx || !canvas) {
return;
}
const dpi = window.devicePixelRatio;
canvas.width = width * dpi;
canvas.height = height * dpi;
ctx.scale(dpi, dpi);
ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = "#1d5ade";
ctx.lineWidth = 1;
ctx.setLineDash([5, 5]);
if (typeof vertical === "number") {
ctx.moveTo(vertical * transform[2] + transform[0], 0);
ctx.lineTo(vertical * transform[2] + transform[0], height);
ctx.stroke();
}
if (typeof horizontal === "number") {
ctx.moveTo(0, horizontal * transform[2] + transform[1]);
ctx.lineTo(width, horizontal * transform[2] + transform[1]);
ctx.stroke();
}
}, [width, height, transform, horizontal, vertical]);
return (
<canvas
ref={canvasRef}
className="react-flow__canvas"
style={canvasStyle}
/>
);
}
export default HelperLinesRenderer;

View File

@@ -0,0 +1,273 @@
"use client";
import type React from "react";
import { useState } from "react";
import {
User,
MessageSquare,
Filter,
Clock,
Plus,
MenuSquare,
Layers,
MoveRight,
} from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useDnD } from "@/contexts/DnDContext";
export function NodePanel() {
const [activeTab, setActiveTab] = useState("content");
const { setType } = useDnD();
const nodeTypes = {
content: [
{
id: "agent-node",
name: "Agent",
icon: User,
color: "text-blue-400",
bgColor: "bg-blue-950/40",
borderColor: "border-blue-500/30",
hoverColor: "group-hover:bg-blue-900/50",
glowColor: "group-hover:shadow-blue-500/20",
description: "Add an AI agent to process messages and execute tasks",
},
{
id: "message-node",
name: "Message",
icon: MessageSquare,
color: "text-orange-400",
bgColor: "bg-orange-950/40",
borderColor: "border-orange-500/30",
hoverColor: "group-hover:bg-orange-900/50",
glowColor: "group-hover:shadow-orange-500/20",
description: "Send a message to users or other nodes in the workflow",
},
],
logic: [
{
id: "condition-node",
name: "Condition",
icon: Filter,
color: "text-purple-400",
bgColor: "bg-purple-950/40",
borderColor: "border-purple-500/30",
hoverColor: "group-hover:bg-purple-900/50",
glowColor: "group-hover:shadow-purple-500/20",
description:
"Create a decision point with multiple outcomes based on conditions",
},
{
id: "delay-node",
name: "Delay",
icon: Clock,
color: "text-yellow-400",
bgColor: "bg-yellow-950/40",
borderColor: "border-yellow-500/30",
hoverColor: "group-hover:bg-yellow-900/50",
glowColor: "group-hover:shadow-yellow-500/20",
description: "Add a time delay between workflow operations",
},
],
};
const onDragStart = (event: React.DragEvent, nodeType: string) => {
event.dataTransfer.setData("application/reactflow", nodeType);
event.dataTransfer.effectAllowed = "move";
setType(nodeType);
};
const handleNodeAdd = (nodeType: string) => {
setType(nodeType);
};
return (
<div className="bg-slate-900/70 backdrop-blur-md border border-slate-700/50 rounded-xl shadow-xl w-[320px] transition-all duration-300 ease-in-out overflow-hidden">
<div className="px-4 pt-4 pb-2 border-b border-slate-700/50">
<div className="flex items-center gap-2 text-slate-200">
<Layers className="h-5 w-5 text-indigo-400" />
<h3 className="font-medium">Workflow Nodes</h3>
</div>
<p className="text-xs text-slate-400 mt-1">
Drag nodes to the canvas or click to add
</p>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<div className="px-4 pt-3">
<TabsList className="w-full bg-slate-800/50 grid grid-cols-2 p-1 rounded-lg">
<TabsTrigger
value="content"
className={cn(
"rounded-md text-xs font-medium transition-all",
"data-[state=active]:bg-gradient-to-br data-[state=active]:from-blue-900/30 data-[state=active]:to-indigo-900/30",
"data-[state=active]:text-blue-300 data-[state=active]:shadow-sm",
"data-[state=inactive]:text-slate-400"
)}
>
<MenuSquare className="h-3.5 w-3.5 mr-1.5" />
Content
</TabsTrigger>
<TabsTrigger
value="logic"
className={cn(
"rounded-md text-xs font-medium transition-all",
"data-[state=active]:bg-gradient-to-br data-[state=active]:from-yellow-900/30 data-[state=active]:to-orange-900/30",
"data-[state=active]:text-yellow-300 data-[state=active]:shadow-sm",
"data-[state=inactive]:text-slate-400"
)}
>
<Filter className="h-3.5 w-3.5 mr-1.5" />
Logic
</TabsTrigger>
</TabsList>
</div>
<TabsContent value="content" className="p-3 space-y-2 mt-0">
{nodeTypes.content.map((node) => (
<TooltipProvider key={node.id} delayDuration={300}>
<Tooltip>
<TooltipTrigger asChild>
<div
draggable
onDragStart={(event) => onDragStart(event, node.id)}
className={cn(
"group flex items-center gap-3 p-3.5 border rounded-lg cursor-grab transition-all duration-300",
"backdrop-blur-sm hover:shadow-lg",
node.borderColor,
node.bgColor,
node.glowColor
)}
>
<div
className={cn(
"flex items-center justify-center w-9 h-9 rounded-lg transition-all duration-300",
"bg-slate-800/80 group-hover:scale-105",
node.hoverColor
)}
>
<node.icon className={cn("h-5 w-5", node.color)} />
</div>
<div className="flex-1 min-w-0">
<span
className={cn("font-medium block text-sm", node.color)}
>
{node.name}
</span>
<span className="text-xs text-slate-400 truncate block">
{node.description}
</span>
</div>
<div
onClick={() => handleNodeAdd(node.id)}
className={cn(
"flex items-center justify-center h-7 w-7 rounded-md bg-slate-800/60 text-slate-400",
"hover:bg-gradient-to-r hover:text-white transition-all",
node.id === "agent-node"
? "hover:from-blue-800 hover:to-blue-600"
: "hover:from-orange-800 hover:to-orange-600"
)}
>
<Plus size={16} />
</div>
</div>
</TooltipTrigger>
<TooltipContent
side="right"
className="bg-slate-900 border-slate-700 text-slate-200"
>
<div className="p-1 max-w-[200px]">
<p className="font-medium text-sm">{node.name} Node</p>
<p className="text-xs text-slate-400 mt-1">
{node.description}
</p>
<div className="flex items-center mt-2 pt-2 border-t border-slate-700/50 text-xs text-slate-400">
<MoveRight className="h-3 w-3 mr-1.5" />
<span>Drag to canvas or click + to add</span>
</div>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
))}
</TabsContent>
<TabsContent value="logic" className="p-3 space-y-2 mt-0">
{nodeTypes.logic.map((node) => (
<TooltipProvider key={node.id} delayDuration={300}>
<Tooltip>
<TooltipTrigger asChild>
<div
draggable
onDragStart={(event) => onDragStart(event, node.id)}
className={cn(
"group flex items-center gap-3 p-3.5 border rounded-lg cursor-grab transition-all duration-300",
"backdrop-blur-sm hover:shadow-lg",
node.borderColor,
node.bgColor,
node.glowColor
)}
>
<div
className={cn(
"flex items-center justify-center w-9 h-9 rounded-lg transition-all duration-300",
"bg-slate-800/80 group-hover:scale-105",
node.hoverColor
)}
>
<node.icon className={cn("h-5 w-5", node.color)} />
</div>
<div className="flex-1 min-w-0">
<span
className={cn("font-medium block text-sm", node.color)}
>
{node.name}
</span>
<span className="text-xs text-slate-400 truncate block">
{node.description}
</span>
</div>
<div
onClick={() => handleNodeAdd(node.id)}
className={cn(
"flex items-center justify-center h-7 w-7 rounded-md bg-slate-800/60 text-slate-400",
"hover:bg-gradient-to-r hover:text-white transition-all",
node.id === "condition-node"
? "hover:from-purple-800 hover:to-purple-600"
: "hover:from-yellow-800 hover:to-yellow-600"
)}
>
<Plus size={16} />
</div>
</div>
</TooltipTrigger>
<TooltipContent
side="right"
className="bg-slate-900 border-slate-700 text-slate-200"
>
<div className="p-1 max-w-[200px]">
<p className="font-medium text-sm">{node.name} Node</p>
<p className="text-xs text-slate-400 mt-1">
{node.description}
</p>
<div className="flex items-center mt-2 pt-2 border-t border-slate-700/50 text-xs text-slate-400">
<MoveRight className="h-3 w-3 mr-1.5" />
<span>Drag to canvas or click + to add</span>
</div>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
))}
</TabsContent>
</Tabs>
</div>
);
}

View File

@@ -0,0 +1,188 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/canva.css │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
.react-flow.dark {
--xy-background-color-default: transparent;
}
.react-flow__panel {
box-shadow: none;
padding: 5px;
}
.react-flow__controls {
background-color: rgba(30, 30, 30, 0.8);
backdrop-filter: blur(4px);
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
border: 1px solid rgba(70, 70, 70, 0.5);
padding: 4px;
}
.react-flow__controls-button {
padding: 6px;
width: 32px;
height: 32px;
margin: 4px 0;
border: none !important;
background-color: rgba(40, 40, 40, 0.8) !important;
color: #a0a0a0 !important;
border-radius: 6px !important;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
}
.react-flow__controls-button:hover {
background-color: rgba(60, 60, 60, 0.9) !important;
color: #ffffff !important;
transform: translateY(-1px);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
.react-flow__controls-button svg {
fill: currentColor;
width: 16px;
height: 16px;
}
.react-flow__controls-button[data-action="zoom-in"] {
border-bottom: 1px solid rgba(70, 70, 70, 0.5) !important;
}
.react-flow__controls-button[data-action="zoom-out"] {
border-bottom: 1px solid rgba(70, 70, 70, 0.5) !important;
}
/* Hide scrollbar for all browsers while maintaining scroll functionality */
.scrollbar-hide {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE and Edge */
}
.scrollbar-hide::-webkit-scrollbar {
display: none; /* Chrome, Safari and Opera */
width: 0;
height: 0;
background: transparent;
}
/* Animated dashed edge for flow edges */
.edge-dashed-animated {
stroke-dasharray: 6;
stroke-dashoffset: 0;
animation: dash 0.5s linear infinite;
}
@keyframes dash {
to {
stroke-dashoffset: -12;
}
}
/* Edges styling */
.react-flow__edge-path {
stroke: #10b981; /* Emerald color for edges */
stroke-width: 2;
}
.react-flow__edge.selected .react-flow__edge-path {
stroke: #3b82f6; /* Blue color for selected edges */
stroke-width: 3;
}
/* Node handle styling */
.react-flow__handle {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #10b981;
border: 2px solid #0d9488;
}
.react-flow__handle:hover {
background-color: #3b82f6;
border-color: #2563eb;
}
/* Nó em execução */
.active-execution-node {
animation: pulse-execution 1.5s infinite;
filter: drop-shadow(0 0 15px rgba(5, 212, 114, 0.9));
z-index: 10;
transform: scale(1.03);
transition: transform 0.3s ease-in-out;
}
@keyframes pulse-execution {
0% {
box-shadow: 0 0 0 0 rgba(5, 212, 114, 0.9);
}
70% {
box-shadow: 0 0 0 15px rgba(5, 212, 114, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(5, 212, 114, 0);
}
}
.react-flow__node[data-is-executing="true"] {
filter: drop-shadow(0 0 15px rgba(5, 212, 114, 0.9));
transform: scale(1.03);
transition: transform 0.3s ease-in-out;
}
.react-flow__node[data-is-executing="true"]::before {
content: '';
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
border: 2px solid #05d472;
border-radius: 8px;
animation: pulse-border 1.5s infinite;
z-index: -1;
}
@keyframes pulse-border {
0% {
opacity: 1;
transform: scale(1);
}
70% {
opacity: 0.3;
transform: scale(1.03);
}
100% {
opacity: 1;
transform: scale(1);
}
}

View File

@@ -0,0 +1,119 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/edges/DefaultEdge.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import {
BaseEdge,
EdgeLabelRenderer,
EdgeProps,
getSmoothStepPath,
useReactFlow,
} from "@xyflow/react";
import { Trash2 } from "lucide-react";
export default function DefaultEdge({
id,
sourceX,
sourceY,
targetX,
targetY,
sourcePosition,
targetPosition,
style = {},
selected,
}: EdgeProps) {
const { setEdges } = useReactFlow();
const [edgePath, labelX, labelY] = getSmoothStepPath({
sourceX,
sourceY,
sourcePosition,
targetX,
targetY,
targetPosition,
borderRadius: 15,
});
const onEdgeClick = () => {
console.log("onEdgeClick", id);
setEdges((edges) => edges.filter((edge) => edge.id !== id));
};
return (
<>
<svg>
<defs>
<marker
id="arrowhead"
viewBox="0 0 10 16"
refX="12"
refY="8"
markerWidth="4"
markerHeight="5"
orient="auto"
>
<path d="M 0 0 L 10 8 L 0 16 z" fill="gray" />
</marker>
</defs>
</svg>
<BaseEdge
id={id}
path={edgePath}
className="edge-dashed-animated"
style={{
...style,
stroke: '#10B981',
strokeWidth: 3,
}}
markerEnd="url(#arrowhead)"
/>
{selected && (
<EdgeLabelRenderer>
<div
style={{
position: "absolute",
transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
fontSize: 12,
pointerEvents: "all",
zIndex: 1000,
}}
className="nodrag nopan"
>
<button
className="rounded-full bg-white p-1 shadow-md"
onClick={onEdgeClick}
>
<Trash2 className="text-red-500" size={16} />
</button>
</div>
</EdgeLabelRenderer>
)}
</>
);
}

View File

@@ -0,0 +1,41 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/edges/index.ts │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import type { Edge, EdgeTypes } from "@xyflow/react";
import DefaultEdge from "./DefaultEdge";
export const initialEdges = [
// { id: "a->c", source: "a", target: "c", animated: true },
// { id: "b->d", source: "b", target: "d" },
// { id: "c->d", source: "c", target: "d", animated: true },
] satisfies Edge[];
export const edgeTypes = {
default: DefaultEdge,
} satisfies EdgeTypes;

View File

@@ -0,0 +1,166 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/BaseNode.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import { Handle, Position } from "@xyflow/react";
import React from "react";
import { cn } from "@/lib/utils";
import { useDnD } from "@/contexts/DnDContext";
export function BaseNode({
selected,
hasTarget,
children,
borderColor,
isExecuting
}: {
selected: boolean;
hasTarget: boolean;
children: React.ReactNode;
borderColor: string;
isExecuting?: boolean;
}) {
const { pointerEvents } = useDnD();
// Border and background color mapping
const colorStyles = {
blue: {
border: "border-blue-700/70 hover:border-blue-500",
gradient: "bg-gradient-to-br from-blue-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(59,130,246,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(59,130,246,0.3)]"
},
orange: {
border: "border-orange-700/70 hover:border-orange-500",
gradient: "bg-gradient-to-br from-orange-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(249,115,22,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(249,115,22,0.3)]"
},
green: {
border: "border-green-700/70 hover:border-green-500",
gradient: "bg-gradient-to-br from-green-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(34,197,94,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(34,197,94,0.3)]"
},
red: {
border: "border-red-700/70 hover:border-red-500",
gradient: "bg-gradient-to-br from-red-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(239,68,68,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(239,68,68,0.3)]"
},
yellow: {
border: "border-yellow-700/70 hover:border-yellow-500",
gradient: "bg-gradient-to-br from-yellow-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(234,179,8,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(234,179,8,0.3)]"
},
purple: {
border: "border-purple-700/70 hover:border-purple-500",
gradient: "bg-gradient-to-br from-purple-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(168,85,247,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(168,85,247,0.3)]"
},
indigo: {
border: "border-indigo-700/70 hover:border-indigo-500",
gradient: "bg-gradient-to-br from-indigo-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(99,102,241,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(99,102,241,0.3)]"
},
pink: {
border: "border-pink-700/70 hover:border-pink-500",
gradient: "bg-gradient-to-br from-pink-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(236,72,153,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(236,72,153,0.3)]"
},
emerald: {
border: "border-emerald-700/70 hover:border-emerald-500",
gradient: "bg-gradient-to-br from-emerald-950/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(16,185,129,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(16,185,129,0.3)]"
},
slate: {
border: "border-slate-700/70 hover:border-slate-500",
gradient: "bg-gradient-to-br from-slate-800/40 to-neutral-900/90",
glow: "shadow-[0_0_15px_rgba(100,116,139,0.15)]",
selectedGlow: "shadow-[0_0_25px_rgba(100,116,139,0.3)]"
},
};
// Default to blue if color not in mapping
const colorStyle = colorStyles[borderColor as keyof typeof colorStyles] || colorStyles.blue;
// Selected styles
const selectedStyle = {
border: "border-green-500/90",
glow: colorStyle.selectedGlow
};
// Executing styles
const executingStyle = {
border: "border-emerald-500",
glow: "shadow-[0_0_25px_rgba(5,212,114,0.5)]"
};
return (
<>
<div
className={cn(
"relative z-0 w-[350px] rounded-2xl p-4 border-2 backdrop-blur-sm transition-all duration-300",
"shadow-lg hover:shadow-xl",
isExecuting ? executingStyle.glow : selected ? selectedStyle.glow : colorStyle.glow,
isExecuting ? executingStyle.border : selected ? selectedStyle.border : colorStyle.border,
colorStyle.gradient,
isExecuting && "active-execution-node"
)}
style={{
backdropFilter: "blur(12px)",
}}
data-is-executing={isExecuting ? "true" : "false"}
>
{hasTarget && (
<Handle
style={{
position: "absolute",
left: "50%",
top: "50%",
width: "100%",
borderRadius: "15px",
height: "100%",
backgroundColor: "transparent",
border: "none",
pointerEvents: pointerEvents === "none" ? "none" : "auto",
}}
type="target"
position={Position.Left}
/>
)}
{children}
</div>
</>
);
}

View File

@@ -0,0 +1,347 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/agent/AgentChatMessageList.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 14, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import React, { useEffect, useRef } from "react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { ChevronDown, ChevronRight, Copy, Check } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { useState } from "react";
import { Agent } from "@/types/agent";
import { InlineDataAttachments } from "@/app/chat/components/InlineDataAttachments";
interface FunctionMessageContent {
title: string;
content: string;
author?: string;
}
interface ChatMessage {
id: string;
content: {
parts: any[];
role: string;
};
author: string;
timestamp: number;
}
interface AgentChatMessageListProps {
messages: ChatMessage[];
agent: Agent;
expandedFunctions: Record<string, boolean>;
toggleFunctionExpansion: (messageId: string) => void;
getMessageText: (message: ChatMessage) => string | FunctionMessageContent;
containsMarkdown: (text: string) => boolean;
}
export function AgentChatMessageList({
messages,
agent,
expandedFunctions,
toggleFunctionExpansion,
getMessageText,
containsMarkdown,
}: AgentChatMessageListProps) {
const messagesEndRef = useRef<HTMLDivElement>(null);
// Scroll to bottom whenever messages change
useEffect(() => {
if (messagesEndRef.current) {
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [messages]);
return (
<div className="space-y-6">
{messages.map((message) => {
const messageContent = getMessageText(message);
const isExpanded = expandedFunctions[message.id] || false;
const isUser = message.author === "user";
const agentColor = "bg-emerald-400";
const hasFunctionCall = message.content.parts.some(
(part) => part.functionCall || part.function_call
);
const hasFunctionResponse = message.content.parts.some(
(part) => part.functionResponse || part.function_response
);
const isFunctionMessage = hasFunctionCall || hasFunctionResponse;
const isTaskExecutor = typeof messageContent === "object" &&
"author" in messageContent &&
typeof messageContent.author === "string" &&
messageContent.author.endsWith("- Task executor");
const inlineDataParts = message.content.parts.filter(part => part.inline_data);
const hasInlineData = inlineDataParts.length > 0;
const isWorkflowNode = message.author && message.author.startsWith('workflow-node:');
const nodeId = isWorkflowNode ? message.author.split(':')[1] : null;
return (
<div
key={message.id}
className="flex w-full"
style={{
justifyContent: isUser ? "flex-end" : "flex-start"
}}
>
<div
className="flex gap-3 max-w-[90%]"
style={{
flexDirection: isUser ? "row-reverse" : "row"
}}
>
<Avatar className={isUser ? "bg-[#333]" : agentColor}>
<AvatarFallback>
{isUser ? "U" : agent.name[0] || "A"}
</AvatarFallback>
</Avatar>
<div
className={`rounded-lg p-3 ${isFunctionMessage || isTaskExecutor
? "bg-[#333] text-emerald-400 font-mono text-sm"
: isUser
? "bg-emerald-400 text-black"
: "bg-[#222] text-white"
} overflow-hidden relative group`}
style={{
wordBreak: "break-word",
maxWidth: "calc(100% - 3rem)",
width: "100%",
...(isWorkflowNode ? {
borderLeft: '3px solid #05d472',
boxShadow: '0 0 10px rgba(5, 212, 114, 0.2)'
} : {})
}}
>
{isWorkflowNode && (
<div className="text-xs text-emerald-500 mb-1 flex items-center space-x-1 bg-emerald-950/30 p-1 rounded">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-3 w-3 mr-1">
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
</svg>
<span>Node {nodeId} is running</span>
</div>
)}
{isFunctionMessage || isTaskExecutor ? (
<div className="w-full">
<div
className="flex items-center gap-2 cursor-pointer hover:bg-[#444] rounded px-1 py-0.5 transition-colors"
onClick={() => toggleFunctionExpansion(message.id)}
>
{typeof messageContent === "object" &&
"title" in messageContent && (
<>
<div className="flex-1 font-semibold">
{(messageContent as FunctionMessageContent).title}
</div>
<div className="flex items-center justify-center w-5 h-5 text-emerald-400">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</div>
</>
)}
{isTaskExecutor && (
<>
<div className="flex-1 font-semibold">
Task Execution
</div>
<div className="flex items-center justify-center w-5 h-5 text-emerald-400">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</div>
</>
)}
</div>
{isExpanded && (
<div className="mt-2 pt-2 border-t border-[#555]">
{typeof messageContent === "object" &&
"content" in messageContent && (
<div className="max-w-full overflow-x-auto">
<pre className="whitespace-pre-wrap text-xs max-w-full" style={{
wordWrap: "break-word",
maxWidth: "100%",
wordBreak: "break-all"
}}>
{(messageContent as FunctionMessageContent).content}
</pre>
</div>
)}
</div>
)}
</div>
) : (
<div className="markdown-content break-words max-w-full overflow-x-auto">
{typeof messageContent === "object" &&
"author" in messageContent &&
messageContent.author !== "user" &&
!isTaskExecutor && (
<div className="text-xs text-neutral-400 mb-1">
{messageContent.author}
</div>
)}
{((typeof messageContent === "string" &&
containsMarkdown(messageContent)) ||
(typeof messageContent === "object" &&
"content" in messageContent &&
typeof messageContent.content === "string" &&
containsMarkdown(messageContent.content))) &&
!isTaskExecutor ? (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
h1: ({ ...props }) => (
<h1 className="text-xl font-bold my-4" {...props} />
),
h2: ({ ...props }) => (
<h2 className="text-lg font-bold my-3" {...props} />
),
h3: ({ ...props }) => (
<h3 className="text-base font-bold my-2" {...props} />
),
h4: ({ ...props }) => (
<h4 className="font-semibold my-2" {...props} />
),
p: ({ ...props }) => <p className="mb-3" {...props} />,
ul: ({ ...props }) => (
<ul
className="list-disc pl-6 mb-3 space-y-1"
{...props}
/>
),
ol: ({ ...props }) => (
<ol
className="list-decimal pl-6 mb-3 space-y-1"
{...props}
/>
),
li: ({ ...props }) => <li className="mb-1" {...props} />,
a: ({ ...props }) => (
<a
className="text-emerald-400 underline hover:opacity-80 transition-opacity"
target="_blank"
rel="noopener noreferrer"
{...props}
/>
),
blockquote: ({ ...props }) => (
<blockquote
className="border-l-4 border-[#444] pl-4 py-1 italic my-3 text-neutral-300"
{...props}
/>
),
code: ({ className, children, ...props }: any) => {
const match = /language-(\w+)/.exec(className || "");
const isInline = !match && typeof children === "string" && !children.includes("\n");
if (isInline) {
return (
<code
className="bg-[#333] px-1.5 py-0.5 rounded text-emerald-400 text-sm font-mono"
{...props}
>
{children}
</code>
);
}
return (
<div className="my-3 relative">
<div className="bg-[#1a1a1a] rounded-t-md border-b border-[#333] p-2 text-xs text-neutral-400">
<span>{match?.[1] || "Code"}</span>
</div>
<pre className="bg-[#1a1a1a] p-3 rounded-b-md overflow-x-auto whitespace-pre text-sm">
<code {...props}>{children}</code>
</pre>
</div>
);
},
table: ({ ...props }) => (
<div className="overflow-x-auto my-3">
<table
className="min-w-full border border-[#333] rounded"
{...props}
/>
</div>
),
thead: ({ ...props }) => (
<thead className="bg-[#1a1a1a]" {...props} />
),
tbody: ({ ...props }) => <tbody {...props} />,
tr: ({ ...props }) => (
<tr
className="border-b border-[#333] last:border-0"
{...props}
/>
),
th: ({ ...props }) => (
<th
className="px-4 py-2 text-left text-xs font-semibold text-neutral-300"
{...props}
/>
),
td: ({ ...props }) => (
<td className="px-4 py-2 text-sm" {...props} />
),
}}
>
{typeof messageContent === "string"
? messageContent
: messageContent.content}
</ReactMarkdown>
) : (
<div className="whitespace-pre-wrap">
{typeof messageContent === "string"
? messageContent
: messageContent.content}
</div>
)}
{hasInlineData && (
<InlineDataAttachments parts={inlineDataParts} />
)}
</div>
)}
</div>
</div>
</div>
);
})}
{/* Empty div at the end for auto-scrolling */}
<div ref={messagesEndRef} />
</div>
);
}

View File

@@ -0,0 +1,631 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/agent/AgentForm.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable jsx-a11y/alt-text */
import { useEdges, useNodes } from "@xyflow/react";
import { useCallback, useEffect, useMemo, useState, useRef } from "react";
import { Agent } from "@/types/agent";
import { listAgents, listFolders, Folder, getAgent } from "@/services/agentService";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { User, Loader2, Search, FolderIcon, Trash2, Play, MessageSquare, PlayIcon, Plus, X } from "lucide-react";
import { Input } from "@/components/ui/input";
import { AgentForm as GlobalAgentForm } from "@/app/agents/forms/AgentForm";
import { ApiKey, listApiKeys } from "@/services/agentService";
import { listMCPServers } from "@/services/mcpServerService";
import { availableModels } from "@/types/aiModels";
import { MCPServer } from "@/types/mcpServer";
import { AgentTestChatModal } from "./AgentTestChatModal";
import { sanitizeAgentName, escapePromptBraces } from "@/lib/utils";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
/* eslint-disable @typescript-eslint/no-explicit-any */
const user = typeof window !== "undefined" ? JSON.parse(localStorage.getItem("user") || '{}') : {};
const clientId: string = user?.client_id ? String(user.client_id) : "";
const agentListStyles = {
scrollbarWidth: 'none', /* Firefox */
msOverflowStyle: 'none', /* IE and Edge */
'::-webkit-scrollbar': {
display: 'none' /* Chrome, Safari and Opera */
}
};
export function AgentForm({ selectedNode, handleUpdateNode, setEdges, setIsOpen, setSelectedNode }: {
selectedNode: any;
handleUpdateNode: any;
setEdges: any;
setIsOpen: any;
setSelectedNode: any;
}) {
const [node, setNode] = useState(selectedNode);
const [loading, setLoading] = useState(true);
const [loadingFolders, setLoadingFolders] = useState(true);
const [loadingCurrentAgent, setLoadingCurrentAgent] = useState(false);
const [agents, setAgents] = useState<Agent[]>([]);
const [allAgents, setAllAgents] = useState<Agent[]>([]);
const [searchQuery, setSearchQuery] = useState("");
const [folders, setFolders] = useState<Folder[]>([]);
const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
const [selectedAgentType, setSelectedAgentType] = useState<string | null>(null);
const [agentTypes, setAgentTypes] = useState<string[]>([]);
const [agentFolderId, setAgentFolderId] = useState<string | null>(null);
const edges = useEdges();
const nodes = useNodes();
const [isAgentDialogOpen, setIsAgentDialogOpen] = useState(false);
const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
const [availableMCPs, setAvailableMCPs] = useState<MCPServer[]>([]);
const [newAgent, setNewAgent] = useState<Partial<Agent>>({
client_id: clientId || "",
name: "",
description: "",
type: "llm",
model: "openai/gpt-4.1-nano",
instruction: "",
api_key_id: "",
config: {
tools: [],
mcp_servers: [],
custom_mcp_servers: [],
custom_tools: { http_tools: [] },
sub_agents: [],
agent_tools: [],
},
});
const [isLoading, setIsLoading] = useState(false);
const [isTestModalOpen, setIsTestModalOpen] = useState(false);
const [isEditMode, setIsEditMode] = useState(false);
// Access the canvas reference from localStorage
const canvasRef = useRef<any>(null);
useEffect(() => {
// When the component is mounted, check if there is a canvas reference in the global context
if (typeof window !== "undefined") {
const workflowsPage = document.querySelector('[data-workflow-page="true"]');
if (workflowsPage) {
// If we are on the workflows page, try to access the canvas ref
const canvasElement = workflowsPage.querySelector('[data-canvas-ref="true"]');
if (canvasElement && (canvasElement as any).__reactRef) {
canvasRef.current = (canvasElement as any).__reactRef.current;
}
}
}
}, []);
const connectedNode = useMemo(() => {
const edge = edges.find((edge: any) => edge.source === selectedNode.id);
if (!edge) return null;
const node = nodes.find((node: any) => node.id === edge.target);
return node || null;
}, [edges, nodes, selectedNode.id]);
const currentAgent = typeof window !== "undefined" ?
JSON.parse(localStorage.getItem("current_workflow_agent") || '{}') : {};
const currentAgentId = currentAgent?.id;
useEffect(() => {
if (selectedNode) {
setNode(selectedNode);
}
}, [selectedNode]);
useEffect(() => {
if (!clientId) return;
setLoadingFolders(true);
listFolders(clientId)
.then((res) => {
setFolders(res.data);
})
.catch((error) => console.error("Error loading folders:", error))
.finally(() => setLoadingFolders(false));
}, [clientId]);
useEffect(() => {
if (!currentAgentId || !clientId) {
return;
}
setLoadingCurrentAgent(true);
getAgent(currentAgentId, clientId)
.then((res) => {
const agent = res.data;
if (agent.folder_id) {
setAgentFolderId(agent.folder_id);
setSelectedFolderId(agent.folder_id);
}
})
.catch((error) => console.error("Error loading current agent:", error))
.finally(() => setLoadingCurrentAgent(false));
}, [currentAgentId, clientId]);
useEffect(() => {
if (!clientId) return;
if (loadingFolders || loadingCurrentAgent) return;
setLoading(true);
listAgents(clientId, 0, 100, selectedFolderId || undefined)
.then((res) => {
const filteredAgents = res.data.filter((agent: Agent) => agent.id !== currentAgentId);
setAllAgents(filteredAgents);
setAgents(filteredAgents);
// Extract unique agent types
const types = [...new Set(filteredAgents.map(agent => agent.type))].filter(Boolean);
setAgentTypes(types);
})
.catch((error) => console.error("Error loading agents:", error))
.finally(() => setLoading(false));
}, [clientId, currentAgentId, selectedFolderId, loadingFolders, loadingCurrentAgent]);
useEffect(() => {
// Apply all filters: search, folder, and type
let filtered = allAgents;
// Search filter is applied in a separate effect
if (searchQuery.trim() !== "") {
filtered = filtered.filter((agent) =>
agent.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
agent.description?.toLowerCase().includes(searchQuery.toLowerCase())
);
}
// Apply agent type filter
if (selectedAgentType) {
filtered = filtered.filter(agent => agent.type === selectedAgentType);
}
setAgents(filtered);
}, [searchQuery, selectedAgentType, allAgents]);
useEffect(() => {
if (!clientId) return;
listApiKeys(clientId).then((res) => setApiKeys(res.data));
listMCPServers().then((res) => setAvailableMCPs(res.data));
}, [clientId]);
const handleDeleteEdge = useCallback(() => {
const id = edges.find((edge: any) => edge.source === selectedNode.id)?.id;
setEdges((edges: any) => {
const left = edges.filter((edge: any) => edge.id !== id);
return left;
});
}, [nodes, edges, selectedNode, setEdges]);
const handleSelectAgent = (agent: Agent) => {
const updatedNode = {
...node,
data: {
...node.data,
agent,
},
};
setNode(updatedNode);
handleUpdateNode(updatedNode);
};
const getAgentTypeName = (type: string) => {
const agentTypes: Record<string, string> = {
llm: "LLM Agent",
a2a: "A2A Agent",
sequential: "Sequential Agent",
parallel: "Parallel Agent",
loop: "Loop Agent",
workflow: "Workflow Agent",
task: "Task Agent",
};
return agentTypes[type] || type;
};
const handleOpenAgentDialog = () => {
setNewAgent({
client_id: clientId || "",
name: "",
description: "",
type: "llm",
model: "openai/gpt-4.1-nano",
instruction: "",
api_key_id: "",
config: {
tools: [],
mcp_servers: [],
custom_mcp_servers: [],
custom_tools: { http_tools: [] },
sub_agents: [],
agent_tools: [],
},
folder_id: selectedFolderId || undefined,
});
setIsAgentDialogOpen(true);
};
const handleSaveAgent = async (agentData: Partial<Agent>) => {
setIsLoading(true);
try {
const sanitizedData = {
...agentData,
client_id: clientId,
name: agentData.name ? sanitizeAgentName(agentData.name) : agentData.name,
instruction: agentData.instruction ? escapePromptBraces(agentData.instruction) : agentData.instruction
};
if (isEditMode && node.data.agent?.id) {
// Update existing agent
const { updateAgent } = await import("@/services/agentService");
const updated = await updateAgent(node.data.agent.id, sanitizedData as any);
// Refresh the agent list
const res = await listAgents(clientId, 0, 100, selectedFolderId || undefined);
const filteredAgents = res.data.filter((agent: Agent) => agent.id !== currentAgentId);
setAllAgents(filteredAgents);
setAgents(filteredAgents);
if (updated.data) {
handleSelectAgent(updated.data);
}
} else {
// Create new agent
const { createAgent } = await import("@/services/agentService");
const created = await createAgent(sanitizedData as any);
const res = await listAgents(clientId, 0, 100, selectedFolderId || undefined);
const filteredAgents = res.data.filter((agent: Agent) => agent.id !== currentAgentId);
setAllAgents(filteredAgents);
setAgents(filteredAgents);
if (created.data) {
handleSelectAgent(created.data);
}
}
setIsAgentDialogOpen(false);
setIsEditMode(false);
} catch (e) {
console.error("Error saving agent:", e);
setIsAgentDialogOpen(false);
setIsEditMode(false);
} finally {
setIsLoading(false);
}
};
const handleFolderChange = (value: string) => {
setSelectedFolderId(value === "all" ? null : value);
};
const handleAgentTypeChange = (value: string) => {
setSelectedAgentType(value === "all" ? null : value);
};
const getFolderNameById = (id: string) => {
const folder = folders.find((f) => f.id === id);
return folder?.name || id;
};
const handleEditAgent = () => {
if (!node.data.agent) return;
setNewAgent({
...node.data.agent,
client_id: clientId || "",
});
setIsEditMode(true);
setIsAgentDialogOpen(true);
};
return (
<>
{isAgentDialogOpen && (
<GlobalAgentForm
open={isAgentDialogOpen}
onOpenChange={(open) => {
setIsAgentDialogOpen(open);
if (!open) setIsEditMode(false);
}}
initialValues={newAgent}
apiKeys={apiKeys}
availableModels={availableModels}
availableMCPs={availableMCPs}
agents={allAgents}
onOpenApiKeysDialog={() => {}}
onOpenMCPDialog={() => {}}
onOpenCustomMCPDialog={() => {}}
onSave={handleSaveAgent}
isLoading={isLoading}
getAgentNameById={(id) => allAgents.find((a) => a.id === id)?.name || id}
clientId={clientId}
/>
)}
{/* Agent Test Chat Modal - moved outside of nested divs to render properly */}
{isTestModalOpen && node.data.agent && (
<AgentTestChatModal
open={isTestModalOpen}
onOpenChange={setIsTestModalOpen}
agent={node.data.agent}
/>
)}
<div className="flex flex-col h-full">
<div className="p-4 border-b border-neutral-700 flex-shrink-0">
<div className="mb-3">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-neutral-500" />
<Input
placeholder="Search agents..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 bg-neutral-800 border-neutral-700 text-neutral-200 focus-visible:ring-emerald-500"
/>
</div>
</div>
<div className="flex gap-2">
<div className="flex-1">
<Select
value={selectedFolderId ? selectedFolderId : "all"}
onValueChange={handleFolderChange}
>
<SelectTrigger className="w-full h-9 bg-neutral-800 border-neutral-700 text-neutral-200 focus:ring-emerald-500 focus:ring-offset-0">
<SelectValue placeholder="All folders" />
</SelectTrigger>
<SelectContent className="bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectItem value="all">All folders</SelectItem>
{folders.map((folder) => (
<SelectItem key={folder.id} value={folder.id}>
{folder.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex-1">
<Select
value={selectedAgentType ? selectedAgentType : "all"}
onValueChange={handleAgentTypeChange}
>
<SelectTrigger className="w-full h-9 bg-neutral-800 border-neutral-700 text-neutral-200 focus:ring-emerald-500 focus:ring-offset-0">
<SelectValue placeholder="All types" />
</SelectTrigger>
<SelectContent className="bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectItem value="all">All types</SelectItem>
{agentTypes.map((type) => (
<SelectItem key={type} value={type}>
{getAgentTypeName(type)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex flex-col flex-1 min-h-0">
<div className="px-4 pt-4 pb-2 flex items-center justify-between flex-shrink-0">
<h3 className="text-md font-medium text-neutral-200">
{searchQuery ? "Search Results" : "Select an Agent"}
</h3>
<Button
variant="outline"
size="icon"
className="h-8 w-8 bg-emerald-800 hover:bg-emerald-700 border-emerald-700 text-emerald-100"
onClick={() => {
setNewAgent({
id: "",
name: "",
client_id: clientId || "",
type: "llm",
model: "",
config: {},
description: "",
});
setIsEditMode(false);
setIsAgentDialogOpen(true);
}}
aria-label="New Agent"
>
<Plus size={14} />
</Button>
</div>
<div className="flex-1 overflow-y-auto px-4 scrollbar-hide">
<div className="space-y-2 pr-2">
{agents.length > 0 ? (
agents.map((agent) => (
<div
key={agent.id}
className={`p-3 rounded-md cursor-pointer transition-colors group relative ${
node.data.agent?.id === agent.id
? "bg-emerald-800/20 border border-emerald-600/40"
: "bg-neutral-800 hover:bg-neutral-700 border border-transparent"
}`}
onClick={() => handleSelectAgent(agent)}
>
<div className="flex items-start gap-2">
<div className="bg-neutral-700 rounded-full p-1.5 flex-shrink-0">
<User size={18} className="text-neutral-300" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<h3 className="font-medium text-neutral-200 truncate">{agent.name}</h3>
<div
className="ml-auto text-neutral-400 opacity-0 group-hover:opacity-100 hover:text-yellow-500 transition-colors p-1 rounded hover:bg-yellow-900/20"
onClick={(e) => {
e.stopPropagation();
setNewAgent({
...agent,
client_id: clientId || "",
});
setIsEditMode(true);
setIsAgentDialogOpen(true);
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
<path d="m15 5 4 4" />
</svg>
</div>
</div>
<div className="flex items-center gap-2 mt-1">
<Badge
variant="outline"
className="text-xs bg-neutral-700 text-emerald-400 border-neutral-600"
>
{getAgentTypeName(agent.type)}
</Badge>
{agent.model && (
<span className="text-xs text-neutral-400">{agent.model}</span>
)}
</div>
{agent.description && (
<p className="text-sm text-neutral-400 mt-1.5 line-clamp-2">
{agent.description.slice(0, 30)} {agent.description.length > 30 ? "..." : ""}
</p>
)}
</div>
</div>
</div>
))
) : (
<div className="text-center py-4 text-neutral-400">
No agents found
</div>
)}
</div>
</div>
</div>
{node.data.agent && (
<div className="p-4 border-t border-neutral-700 flex-shrink-0">
<div className="flex items-center justify-between mb-2">
<h3 className="text-md font-medium text-neutral-200">Selected Agent</h3>
<div className="flex gap-2">
<Button
variant="outline"
size="icon"
className="h-8 w-8 bg-neutral-700 hover:bg-neutral-600 border-neutral-600 text-neutral-200"
onClick={() => {
handleUpdateNode({
...node,
data: {
...node.data,
agent: null,
},
});
}}
aria-label="Clear agent"
>
<X size={14} />
</Button>
<Button
variant="outline"
size="icon"
className="h-8 w-8 bg-neutral-700 hover:bg-neutral-600 border-neutral-600 text-neutral-200"
onClick={handleEditAgent}
aria-label="Edit agent"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
<path d="m15 5 4 4" />
</svg>
</Button>
<Button
variant="outline"
size="icon"
className="h-8 w-8 bg-emerald-800 hover:bg-emerald-700 border-emerald-700 text-emerald-100"
onClick={() => setIsTestModalOpen(true)}
aria-label="Test agent"
>
<PlayIcon size={14} />
</Button>
</div>
</div>
<div className="p-3 rounded-md bg-emerald-800/20 border border-emerald-600/40">
<div className="flex items-start gap-2">
<div className="bg-emerald-900/50 rounded-full p-1.5 flex-shrink-0">
<User size={18} className="text-emerald-300" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-neutral-200 truncate">{node.data.agent.name}</h3>
<div className="flex items-center gap-2 mt-1">
<Badge
variant="outline"
className="text-xs bg-emerald-900/50 text-emerald-400 border-emerald-700/50"
>
{getAgentTypeName(node.data.agent.type)}
</Badge>
{node.data.agent.model && (
<span className="text-xs text-neutral-400">{node.data.agent.model}</span>
)}
</div>
{node.data.agent.description && (
<p className="text-sm text-neutral-400 mt-1.5 line-clamp-2">
{node.data.agent.description.slice(0, 30)} {node.data.agent.description.length > 30 ? "..." : ""}
</p>
)}
</div>
</div>
</div>
</div>
)}
</div>
</>
);
}

View File

@@ -0,0 +1,176 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/agent/AgentNode.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Handle, NodeProps, Position, useEdges } from "@xyflow/react";
import { MessageCircle, User, Code, ExternalLink, Workflow, GitBranch, RefreshCw, BookOpenCheck, ArrowRight } from "lucide-react";
import { Agent } from "@/types/agent";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { BaseNode } from "../../BaseNode";
export function AgentNode(props: NodeProps) {
const { selected, data } = props;
const edges = useEdges();
const isHandleConnected = (handleId: string) => {
return edges.some(
(edge) => edge.source === props.id && edge.sourceHandle === handleId
);
};
const isBottomHandleConnected = isHandleConnected("bottom-handle");
const agent = data.agent as Agent | undefined;
const isExecuting = data.isExecuting as boolean | undefined;
const getAgentTypeName = (type: string) => {
const agentTypes: Record<string, string> = {
llm: "LLM Agent",
a2a: "A2A Agent",
sequential: "Sequential Agent",
parallel: "Parallel Agent",
loop: "Loop Agent",
workflow: "Workflow Agent",
task: "Task Agent",
};
return agentTypes[type] || type;
};
const getAgentTypeIcon = (type: string) => {
switch (type) {
case "llm":
return <Code className="h-4 w-4 text-green-400" />;
case "a2a":
return <ExternalLink className="h-4 w-4 text-indigo-400" />;
case "sequential":
return <Workflow className="h-4 w-4 text-yellow-400" />;
case "parallel":
return <GitBranch className="h-4 w-4 text-purple-400" />;
case "loop":
return <RefreshCw className="h-4 w-4 text-orange-400" />;
case "workflow":
return <Workflow className="h-4 w-4 text-blue-400" />;
case "task":
return <BookOpenCheck className="h-4 w-4 text-red-400" />;
default:
return <User className="h-4 w-4 text-neutral-400" />;
}
};
const getModelBadgeColor = (model: string) => {
if (model?.includes('gpt-4')) return 'bg-green-900/30 text-green-400 border-green-600/30';
if (model?.includes('gpt-3')) return 'bg-yellow-900/30 text-yellow-400 border-yellow-600/30';
if (model?.includes('claude')) return 'bg-orange-900/30 text-orange-400 border-orange-600/30';
if (model?.includes('gemini')) return 'bg-blue-900/30 text-blue-400 border-blue-600/30';
return 'bg-neutral-800 text-neutral-400 border-neutral-600/50';
};
return (
<BaseNode hasTarget={true} selected={selected || false} borderColor="blue" isExecuting={isExecuting}>
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-900/40 shadow-sm">
<User className="h-5 w-5 text-blue-400" />
</div>
<div>
<p className="text-lg font-medium text-blue-400">
{data.label as string}
</p>
</div>
</div>
</div>
{agent ? (
<div className="mb-3 rounded-lg border border-blue-700/40 bg-blue-950/10 p-3 transition-all duration-200 hover:border-blue-600/50 hover:bg-blue-900/10">
<div className="flex flex-col">
<div className="flex items-start justify-between gap-2">
<div className="flex items-center">
{getAgentTypeIcon(agent.type)}
<span className="ml-1.5 font-medium text-white">{agent.name}</span>
</div>
<Badge
variant="outline"
className="px-1.5 py-0 text-xs bg-blue-900/30 text-blue-400 border-blue-700/40"
>
{getAgentTypeName(agent.type)}
</Badge>
</div>
{agent.model && (
<div className="mt-2 flex items-center">
<Badge
variant="outline"
className={cn("px-1.5 py-0 text-xs", getModelBadgeColor(agent.model))}
>
{agent.model}
</Badge>
</div>
)}
{agent.description && (
<p className="mt-2 text-xs text-neutral-400 line-clamp-2">
{agent.description.slice(0, 30)} {agent.description.length > 30 && '...'}
</p>
)}
</div>
</div>
) : (
<div className="mb-3 flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-blue-700/40 bg-blue-950/10 p-5 text-center transition-all duration-200 hover:border-blue-600/50 hover:bg-blue-900/20">
<User className="h-8 w-8 text-blue-700/50 mb-2" />
<p className="text-blue-400">Select an agent</p>
<p className="mt-1 text-xs text-neutral-500">Click to configure</p>
</div>
)}
<div className="mt-2 flex items-center justify-end text-sm text-neutral-400 transition-colors">
<div className="flex items-center space-x-1 rounded-md py-1 px-2">
<span>Next step</span>
<ArrowRight className="h-3.5 w-3.5" />
</div>
<Handle
className={cn(
"!w-3 !h-3 !rounded-full transition-all duration-300",
isBottomHandleConnected ? "!bg-blue-500 !border-blue-400" : "!bg-neutral-400 !border-neutral-500",
selected && isBottomHandleConnected && "!bg-blue-400 !border-blue-300"
)}
style={{
right: "-8px",
top: "calc(100% - 25px)",
}}
type="source"
position={Position.Right}
id="bottom-handle"
/>
</div>
</BaseNode>
);
}

View File

@@ -0,0 +1,470 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/agent/AgentTestChatModal.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import { useState, useCallback, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useAgentWebSocket } from "@/hooks/use-agent-webSocket";
import { getAccessTokenFromCookie, cn } from "@/lib/utils";
import { Agent } from "@/types/agent";
import { ChatInput } from "@/app/chat/components/ChatInput";
import { ChatMessage as ChatMessageComponent } from "@/app/chat/components/ChatMessage";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { ChatPart } from "@/services/sessionService";
import { FileData } from "@/lib/file-utils";
import { X, User, Bot, Zap, MessageSquare, Loader2, Code, ExternalLink, Workflow, RefreshCw } from "lucide-react";
interface FunctionMessageContent {
title: string;
content: string;
author?: string;
}
interface ChatMessage {
id: string;
content: any;
author: string;
timestamp: number;
}
interface AgentTestChatModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
agent: Agent;
canvasRef?: React.RefObject<any>;
}
export function AgentTestChatModal({ open, onOpenChange, agent, canvasRef }: AgentTestChatModalProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isSending, setIsSending] = useState(false);
const [expandedFunctions, setExpandedFunctions] = useState<Record<string, boolean>>({});
const [isInitializing, setIsInitializing] = useState(true);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const user = typeof window !== "undefined" ? JSON.parse(localStorage.getItem("user") || "{}") : {};
const clientId = user?.client_id || "test";
const generateExternalId = () => {
const now = new Date();
return (
now.getFullYear().toString() +
(now.getMonth() + 1).toString().padStart(2, "0") +
now.getDate().toString().padStart(2, "0") +
now.getHours().toString().padStart(2, "0") +
now.getMinutes().toString().padStart(2, "0") +
now.getSeconds().toString().padStart(2, "0") +
now.getMilliseconds().toString().padStart(3, "0")
);
};
const [externalId, setExternalId] = useState(generateExternalId());
const jwt = getAccessTokenFromCookie();
const onEvent = useCallback((event: any) => {
setMessages((prev) => [...prev, event]);
// Check if the message comes from a workflow node and highlight the node
// only if the canvasRef is available (called from Test Workflow on the main page)
if (event.author && event.author.startsWith('workflow-node:') && canvasRef?.current) {
const nodeId = event.author.split(':')[1];
canvasRef.current.setActiveExecutionNodeId(nodeId);
}
}, [canvasRef]);
const onTurnComplete = useCallback(() => {
setIsSending(false);
}, []);
const { sendMessage: wsSendMessage, disconnect } = useAgentWebSocket({
agentId: agent.id,
externalId,
jwt,
onEvent,
onTurnComplete,
});
// Handle ESC key to close the panel
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape" && open) {
onOpenChange(false);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [onOpenChange, open]);
// Show initialization state for better UX
useEffect(() => {
if (open) {
setIsInitializing(true);
const timer = setTimeout(() => {
setIsInitializing(false);
}, 1200);
return () => clearTimeout(timer);
}
}, [open, externalId]);
const handleRestartChat = () => {
if (disconnect) disconnect();
setMessages([]);
setExpandedFunctions({});
setExternalId(generateExternalId());
setIsInitializing(true);
// Short delay to show the initialization status
const timer = setTimeout(() => {
setIsInitializing(false);
}, 1200);
};
const handleSendMessageWithFiles = (message: string, files?: FileData[]) => {
if ((!message.trim() && (!files || files.length === 0))) return;
setIsSending(true);
const messageParts: ChatPart[] = [];
if (message.trim()) {
messageParts.push({ text: message });
}
if (files && files.length > 0) {
files.forEach(file => {
messageParts.push({
inline_data: {
data: file.data,
mime_type: file.content_type,
metadata: {
filename: file.filename
}
}
});
});
}
setMessages((prev) => [
...prev,
{
id: `temp-${Date.now()}`,
content: {
parts: messageParts,
role: "user"
},
author: "user",
timestamp: Date.now() / 1000,
},
]);
wsSendMessage(message, files);
};
const containsMarkdown = (text: string): boolean => {
if (!text || text.length < 3) return false;
const markdownPatterns = [
/[*_]{1,2}[^*_]+[*_]{1,2}/, // bold/italic
/\[[^\]]+\]\([^)]+\)/, // links
/^#{1,6}\s/m, // headers
/^[-*+]\s/m, // unordered lists
/^[0-9]+\.\s/m, // ordered lists
/^>\s/m, // block quotes
/`[^`]+`/, // inline code
/```[\s\S]*?```/, // code blocks
/^\|(.+\|)+$/m, // tables
/!\[[^\]]*\]\([^)]+\)/, // images
];
return markdownPatterns.some((pattern) => pattern.test(text));
};
const getMessageText = (message: ChatMessage): string | FunctionMessageContent => {
const author = message.author;
const parts = message.content.parts;
if (!parts || parts.length === 0) return "Empty content";
const functionCallPart = parts.find((part: any) => part.functionCall || part.function_call);
const functionResponsePart = parts.find((part: any) => part.functionResponse || part.function_response);
const inlineDataParts = parts.filter((part: any) => part.inline_data);
if (functionCallPart) {
const funcCall = functionCallPart.functionCall || functionCallPart.function_call || {};
const args = funcCall.args || {};
const name = funcCall.name || "unknown";
const id = funcCall.id || "no-id";
return {
author,
title: `📞 Function call: ${name}`,
content: `ID: ${id}\nArgs: ${Object.keys(args).length > 0 ? `\n${JSON.stringify(args, null, 2)}` : "{}"}`,
} as FunctionMessageContent;
}
if (functionResponsePart) {
const funcResponse = functionResponsePart.functionResponse || functionResponsePart.function_response || {};
const response = funcResponse.response || {};
const name = funcResponse.name || "unknown";
const id = funcResponse.id || "no-id";
const status = response.status || "unknown";
const statusEmoji = status === "error" ? "❌" : "✅";
let resultText = "";
if (status === "error") {
resultText = `Error: ${response.error_message || "Unknown error"}`;
} else if (response.report) {
resultText = `Result: ${response.report}`;
} else if (response.result && response.result.content) {
const content = response.result.content;
if (Array.isArray(content) && content.length > 0 && content[0].text) {
try {
const textContent = content[0].text;
const parsedJson = JSON.parse(textContent);
resultText = `Result: \n${JSON.stringify(parsedJson, null, 2)}`;
} catch (e) {
resultText = `Result: ${content[0].text}`;
}
} else {
resultText = `Result:\n${JSON.stringify(response, null, 2)}`;
}
} else {
resultText = `Result:\n${JSON.stringify(response, null, 2)}`;
}
return {
author,
title: `${statusEmoji} Function response: ${name}`,
content: `ID: ${id}\n${resultText}`,
} as FunctionMessageContent;
}
if (parts.length === 1 && parts[0].text) {
return {
author,
content: parts[0].text,
title: "Message",
} as FunctionMessageContent;
}
const textParts = parts.filter((part: any) => part.text).map((part: any) => part.text).filter((text: string) => text);
if (textParts.length > 0) {
return {
author,
content: textParts.join("\n\n"),
title: "Message",
} as FunctionMessageContent;
}
try {
return JSON.stringify(parts, null, 2).replace(/\\n/g, "\n");
} catch (error) {
return "Unable to interpret message content";
}
};
const toggleFunctionExpansion = (messageId: string) => {
setExpandedFunctions((prev) => ({ ...prev, [messageId]: !prev[messageId] }));
};
const getAgentTypeIcon = (type: string) => {
switch (type) {
case "llm":
return <Code className="h-4 w-4 text-green-400" />;
case "a2a":
return <ExternalLink className="h-4 w-4 text-indigo-400" />;
case "sequential":
case "workflow":
return <Workflow className="h-4 w-4 text-blue-400" />;
default:
return <Bot className="h-4 w-4 text-emerald-400" />;
}
};
// Scroll to bottom whenever messages change
useEffect(() => {
if (messagesContainerRef.current) {
messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
}
}, [messages]);
if (!open) return null;
// Use React Portal to render directly to document body, bypassing all parent containers
const modalContent = (
<>
{/* Overlay for mobile */}
<div
className="md:hidden fixed inset-0 bg-black bg-opacity-50 z-[15] transition-opacity duration-300"
onClick={() => onOpenChange(false)}
/>
{/* Side panel */}
<div
className="fixed right-0 top-0 z-[1000] h-full w-[450px] bg-gradient-to-b from-neutral-900 to-neutral-950 border-l border-neutral-800 shadow-2xl flex flex-col transition-all duration-300 ease-in-out transform"
style={{
transform: open ? 'translateX(0)' : 'translateX(100%)',
boxShadow: '0 0 25px rgba(0, 0, 0, 0.3)',
}}
>
{/* Header */}
<div className="flex-shrink-0 p-5 bg-gradient-to-r from-neutral-900 to-neutral-800 border-b border-neutral-800">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center mb-1">
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-emerald-600 to-emerald-900 flex items-center justify-center shadow-lg mr-3">
{getAgentTypeIcon(agent.type)}
</div>
<div>
<h2 className="text-lg font-semibold text-white">{agent.name}</h2>
<div className="flex items-center gap-2 mt-1">
<Badge
className="bg-emerald-900/40 text-emerald-400 border border-emerald-700/50 px-2"
>
{agent.type.toUpperCase()} Agent
</Badge>
{agent.model && (
<span className="text-xs text-neutral-400 bg-neutral-800/60 px-2 py-0.5 rounded-md">
{agent.model}
</span>
)}
</div>
</div>
</div>
</div>
<div className="flex items-center space-x-2">
<button
onClick={handleRestartChat}
className="p-1.5 rounded-full hover:bg-neutral-700/50 text-neutral-400 hover:text-white transition-colors group relative"
title="Restart chat"
disabled={isInitializing}
>
<RefreshCw size={18} className={isInitializing ? "animate-spin text-emerald-400" : ""} />
<span className="absolute -bottom-8 right-0 bg-neutral-800 text-neutral-200 text-xs rounded py-1 px-2 opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity whitespace-nowrap">
Restart chat
</span>
</button>
<button
onClick={() => onOpenChange(false)}
className="p-1.5 rounded-full hover:bg-neutral-700/50 text-neutral-400 hover:text-white transition-colors group relative"
>
<X size={18} />
<span className="absolute -bottom-8 right-0 bg-neutral-800 text-neutral-200 text-xs rounded py-1 px-2 opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity whitespace-nowrap">
Close
</span>
</button>
</div>
</div>
{agent.description && (
<div className="mt-3 text-sm text-neutral-400 bg-neutral-800/30 p-3 rounded-md border border-neutral-800">
{agent.description}
</div>
)}
</div>
{/* Chat content */}
<div className="flex-1 overflow-y-auto overflow-x-hidden p-3 bg-gradient-to-b from-neutral-900/50 to-neutral-950" ref={messagesContainerRef}>
{isInitializing ? (
<div className="flex flex-col items-center justify-center h-full">
<div className="w-12 h-12 rounded-full bg-gradient-to-br from-emerald-500 to-emerald-700 flex items-center justify-center shadow-lg mb-4 animate-pulse">
<Zap className="h-5 w-5 text-white" />
</div>
<p className="text-neutral-400 mb-2">Initializing connection...</p>
<div className="flex items-center space-x-2">
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-bounce"
style={{ animationDelay: '0ms' }}></span>
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-bounce"
style={{ animationDelay: '150ms' }}></span>
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-bounce"
style={{ animationDelay: '300ms' }}></span>
</div>
</div>
) : messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-center px-6">
<div className="w-14 h-14 rounded-full bg-gradient-to-br from-blue-500/20 to-emerald-500/20 flex items-center justify-center shadow-lg mb-5 border border-emerald-500/30">
<MessageSquare className="h-6 w-6 text-emerald-400" />
</div>
<h3 className="text-lg font-medium text-neutral-300 mb-2">Start the conversation</h3>
<p className="text-neutral-500 text-sm max-w-xs">
Type a message below to begin chatting with {agent.name}
</p>
</div>
) : (
<div className="space-y-4 w-full max-w-full">
{messages.map((message) => {
const messageContent = getMessageText(message);
const agentColor = message.author === "user" ? "bg-emerald-500" : "bg-gradient-to-br from-neutral-800 to-neutral-900";
const isExpanded = expandedFunctions[message.id] || false;
return (
<ChatMessageComponent
key={message.id}
message={message}
agentColor={agentColor}
isExpanded={isExpanded}
toggleExpansion={toggleFunctionExpansion}
containsMarkdown={containsMarkdown}
messageContent={messageContent}
/>
);
})}
{isSending && (
<div className="flex justify-start">
<div className="flex gap-3 max-w-[80%]">
<Avatar
className="bg-gradient-to-br from-purple-600 to-purple-800 shadow-md border-0"
>
<AvatarFallback className="bg-transparent">
<Bot className="h-4 w-4 text-white" />
</AvatarFallback>
</Avatar>
<div className="rounded-lg p-3 bg-gradient-to-br from-neutral-800 to-neutral-900 border border-neutral-700/50">
<div className="flex space-x-2">
<div className="h-2 w-2 rounded-full bg-emerald-400 animate-bounce"></div>
<div className="h-2 w-2 rounded-full bg-emerald-400 animate-bounce [animation-delay:0.2s]"></div>
<div className="h-2 w-2 rounded-full bg-emerald-400 animate-bounce [animation-delay:0.4s]"></div>
</div>
</div>
</div>
</div>
)}
</div>
)}
</div>
{/* Message input */}
<div className="p-3 border-t border-neutral-800 bg-neutral-900">
<ChatInput
onSendMessage={handleSendMessageWithFiles}
isLoading={isSending}
placeholder="Type your message..."
autoFocus={true}
/>
</div>
</div>
</>
);
// Use createPortal to render the modal directly to the document body
return typeof document !== 'undefined'
? createPortal(modalContent, document.body)
: null;
}

View File

@@ -0,0 +1,68 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/agent/styles.css │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
.markdown-content {
max-width: 100%;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
hyphens: auto;
}
.markdown-content pre {
white-space: pre-wrap;
overflow-x: auto;
max-width: 100%;
}
.markdown-content code {
white-space: pre-wrap;
word-break: break-all;
}
.markdown-content p {
max-width: 100%;
overflow-wrap: break-word;
}
.markdown-content table {
display: block;
overflow-x: auto;
max-width: 100%;
border-collapse: collapse;
}
.markdown-content img {
max-width: 100%;
height: auto;
}
.overflow-wrap-anywhere {
overflow-wrap: anywhere;
}

View File

@@ -0,0 +1,283 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/condition/ConditionDialog.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter
} from "@/components/ui/dialog";
import { ConditionType, ConditionTypeEnum } from "../../nodeFunctions";
import { Button } from "@/components/ui/button";
import { Filter, ArrowRight } from "lucide-react";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
const conditionTypes = [
{
id: "previous-output",
name: "Previous output",
description: "Validate the result returned by the previous node",
icon: <Filter className="h-5 w-5 text-blue-400" />,
color: "bg-blue-900/30 border-blue-700/50",
},
];
const operators = [
{ value: "is_defined", label: "is defined" },
{ value: "is_not_defined", label: "is not defined" },
{ value: "equals", label: "is equal to" },
{ value: "not_equals", label: "is not equal to" },
{ value: "contains", label: "contains" },
{ value: "not_contains", label: "does not contain" },
{ value: "starts_with", label: "starts with" },
{ value: "ends_with", label: "ends with" },
{ value: "greater_than", label: "is greater than" },
{ value: "greater_than_or_equal", label: "is greater than or equal to" },
{ value: "less_than", label: "is less than" },
{ value: "less_than_or_equal", label: "is less than or equal to" },
{ value: "matches", label: "matches the regex" },
{ value: "not_matches", label: "does not match the regex" },
];
const outputFields = [
{ value: "content", label: "Content" },
{ value: "status", label: "Status" },
];
function ConditionDialog({
open,
onOpenChange,
selectedNode,
handleUpdateNode,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
selectedNode: any;
handleUpdateNode: any;
}) {
const [selectedType, setSelectedType] = useState("previous-output");
const [selectedField, setSelectedField] = useState(outputFields[0].value);
const [selectedOperator, setSelectedOperator] = useState(operators[0].value);
const [comparisonValue, setComparisonValue] = useState("");
const handleConditionSave = (condition: ConditionType) => {
const newConditions = selectedNode.data.conditions
? [...selectedNode.data.conditions]
: [];
newConditions.push(condition);
const updatedNode = {
...selectedNode,
data: {
...selectedNode.data,
conditions: newConditions,
},
};
handleUpdateNode(updatedNode);
onOpenChange(false);
};
const getOperatorLabel = (value: string) => {
return operators.find(op => op.value === value)?.label || value;
};
const getFieldLabel = (value: string) => {
return outputFields.find(field => field.value === value)?.label || value;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="bg-neutral-800 border-neutral-700 text-neutral-200 sm:max-w-[650px]">
<DialogHeader>
<DialogTitle>Add New Condition</DialogTitle>
</DialogHeader>
<div className="grid gap-6 py-4">
<div className="grid gap-4">
<Label className="text-sm font-medium">Condition Type</Label>
<div className="grid grid-cols-1 gap-2">
{conditionTypes.map((type) => (
<div
key={type.id}
className={`flex items-center space-x-3 rounded-md border p-3 cursor-pointer transition-all ${
selectedType === type.id
? "bg-blue-900/30 border-blue-600"
: "border-neutral-700 hover:border-blue-700/50 hover:bg-neutral-700/50"
}`}
onClick={() => setSelectedType(type.id)}
>
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-900/40">
{type.icon}
</div>
<div className="flex-1">
<h4 className="font-medium">{type.name}</h4>
<p className="text-xs text-neutral-400">{type.description}</p>
</div>
{selectedType === type.id && (
<Badge className="bg-blue-600 text-neutral-100">Selected</Badge>
)}
</div>
))}
</div>
</div>
<div className="grid gap-4">
<div className="flex items-center justify-between">
<Label className="text-sm font-medium">Configuration</Label>
{selectedType === "previous-output" && (
<div className="flex items-center gap-2 text-sm text-neutral-400">
<span>Output field</span>
<ArrowRight className="h-3 w-3" />
<span>Operator</span>
{!["is_defined", "is_not_defined"].includes(selectedOperator) && (
<>
<ArrowRight className="h-3 w-3" />
<span>Value</span>
</>
)}
</div>
)}
</div>
{selectedType === "previous-output" && (
<div className="space-y-4">
<div className="grid gap-2">
<Label htmlFor="field">Output Field</Label>
<Select
value={selectedField}
onValueChange={setSelectedField}
>
<SelectTrigger id="field" className="bg-neutral-700 border-neutral-600">
<SelectValue placeholder="Select field" />
</SelectTrigger>
<SelectContent className="bg-neutral-700 border-neutral-600">
{outputFields.map((field) => (
<SelectItem key={field.value} value={field.value}>
{field.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="operator">Operator</Label>
<Select
value={selectedOperator}
onValueChange={setSelectedOperator}
>
<SelectTrigger id="operator" className="bg-neutral-700 border-neutral-600">
<SelectValue placeholder="Select operator" />
</SelectTrigger>
<SelectContent className="bg-neutral-700 border-neutral-600">
{operators.map((op) => (
<SelectItem key={op.value} value={op.value}>
{op.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{!["is_defined", "is_not_defined"].includes(selectedOperator) && (
<div className="grid gap-2">
<Label htmlFor="value">Comparison Value</Label>
<Input
id="value"
value={comparisonValue}
onChange={(e) => setComparisonValue(e.target.value)}
className="bg-neutral-700 border-neutral-600"
/>
</div>
)}
<div className="rounded-md bg-neutral-700/50 border border-neutral-600 p-3 mt-4">
<div className="text-sm font-medium text-neutral-400 mb-1">Preview</div>
<div className="text-sm">
<span className="text-blue-400 font-medium">{getFieldLabel(selectedField)}</span>
{" "}
<span className="text-neutral-300">{getOperatorLabel(selectedOperator)}</span>
{" "}
{!["is_defined", "is_not_defined"].includes(selectedOperator) && (
<span className="text-emerald-400 font-medium">"{comparisonValue || "(empty)"}"</span>
)}
</div>
</div>
</div>
)}
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
className="border-neutral-600 text-neutral-200 hover:bg-neutral-700"
>
Cancel
</Button>
<Button
onClick={() => {
handleConditionSave({
id: uuidv4(),
type: ConditionTypeEnum.PREVIOUS_OUTPUT,
data: {
field: selectedField,
operator: selectedOperator,
value: comparisonValue,
},
});
}}
className="bg-blue-700 hover:bg-blue-600 text-white"
>
Add Condition
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export { ConditionDialog };

View File

@@ -0,0 +1,290 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/condition/ConditionForm.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import { useEffect, useState } from "react";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ConditionType, ConditionTypeEnum } from "../../nodeFunctions";
import { ConditionDialog } from "./ConditionDialog";
import { Button } from "@/components/ui/button";
import { Filter, Trash2, Plus } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
/* eslint-disable @typescript-eslint/no-explicit-any */
function ConditionForm({
selectedNode,
handleUpdateNode,
}: {
selectedNode: any;
handleUpdateNode: any;
setEdges: any;
setIsOpen: any;
setSelectedNode: any;
}) {
const [node, setNode] = useState(selectedNode);
const [conditions, setConditions] = useState<ConditionType[]>(
selectedNode.data.conditions || []
);
const [open, setOpen] = useState(false);
const [deleteDialog, setDeleteDialog] = useState(false);
const [conditionToDelete, setConditionToDelete] =
useState<ConditionType | null>(null);
useEffect(() => {
if (selectedNode) {
setNode(selectedNode);
setConditions(selectedNode.data.conditions || []);
}
}, [selectedNode]);
const handleDelete = (condition: ConditionType) => {
setConditionToDelete(condition);
setDeleteDialog(true);
};
const confirmDelete = () => {
if (!conditionToDelete) return;
const newConditions = conditions.filter(
(c) => c.id !== conditionToDelete.id
);
setConditions(newConditions);
handleUpdateNode({
...node,
data: { ...node.data, conditions: newConditions },
});
setDeleteDialog(false);
setConditionToDelete(null);
};
const renderCondition = (condition: ConditionType) => {
if (condition.type === ConditionTypeEnum.PREVIOUS_OUTPUT) {
type OperatorType =
| "is_defined"
| "is_not_defined"
| "equals"
| "not_equals"
| "contains"
| "not_contains"
| "starts_with"
| "ends_with"
| "greater_than"
| "greater_than_or_equal"
| "less_than"
| "less_than_or_equal"
| "matches"
| "not_matches";
const operatorText: Record<OperatorType, string> = {
is_defined: "is defined",
is_not_defined: "is not defined",
equals: "is equal to",
not_equals: "is not equal to",
contains: "contains",
not_contains: "does not contain",
starts_with: "starts with",
ends_with: "ends with",
greater_than: "is greater than",
greater_than_or_equal: "is greater than or equal to",
less_than: "is less than",
less_than_or_equal: "is less than or equal to",
matches: "matches the regex",
not_matches: "does not match the regex",
};
return (
<div
key={condition.id}
className="p-3 rounded-md cursor-pointer transition-colors bg-neutral-800 hover:bg-neutral-700 border border-neutral-700 mb-2 group"
>
<div className="flex items-start gap-2">
<div className="bg-blue-900/50 rounded-full p-1.5 flex-shrink-0">
<Filter size={18} className="text-blue-300" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<h3 className="font-medium text-neutral-200">Condition</h3>
<Button
variant="ghost"
size="icon"
onClick={() => handleDelete(condition)}
className="h-7 w-7 text-neutral-400 opacity-0 group-hover:opacity-100 hover:text-red-500 hover:bg-red-900/20"
>
<Trash2 size={14} />
</Button>
</div>
<div className="flex items-center gap-2 mt-1">
<Badge
variant="outline"
className="text-xs bg-blue-900/20 text-blue-400 border-blue-700/50"
>
Field
</Badge>
<span className="text-sm text-neutral-300 font-medium">{condition.data.field}</span>
</div>
<div className="flex flex-wrap items-center gap-1 mt-1.5">
<span className="text-sm text-neutral-400">{operatorText[condition.data.operator as OperatorType]}</span>
{!["is_defined", "is_not_defined"].includes(condition.data.operator) && (
<span className="text-sm font-medium text-emerald-400">
"{condition.data.value}"
</span>
)}
</div>
</div>
</div>
</div>
);
}
return null;
};
return (
<div className="flex flex-col h-full">
<div className="p-4 border-b border-neutral-700 flex-shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<h3 className="text-md font-medium text-neutral-200">Logic Type</h3>
<Badge
variant="outline"
className="text-xs bg-blue-900/20 text-blue-400 border-blue-700/50"
>
{node.data.type === "or" ? "ANY" : "ALL"}
</Badge>
</div>
<Select
value={node.data.type || "and"}
onValueChange={(value) => {
const updatedNode = {
...node,
data: {
...node.data,
type: value,
},
};
setNode(updatedNode);
handleUpdateNode(updatedNode);
}}
>
<SelectTrigger className="w-[120px] h-8 bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent className="bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectItem value="and">ALL (AND)</SelectItem>
<SelectItem value="or">ANY (OR)</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-sm text-neutral-400 mt-2">
{node.data.type === "or"
? "Any of the following conditions must be true to proceed."
: "All of the following conditions must be true to proceed."}
</p>
</div>
<div className="flex-1 overflow-y-auto px-4 py-4 min-h-0">
<div className="mb-4">
<div className="flex items-center justify-between mb-3">
<h3 className="text-md font-medium text-neutral-200">Conditions</h3>
<Button
variant="outline"
size="sm"
className="h-8 bg-blue-800/20 hover:bg-blue-700/30 border-blue-700/50 text-blue-300"
onClick={() => setOpen(true)}
>
<Plus size={14} className="mr-1" />
Add Condition
</Button>
</div>
{conditions.length > 0 ? (
<div className="space-y-2">
{conditions.map((condition) => renderCondition(condition))}
</div>
) : (
<div
onClick={() => setOpen(true)}
className="flex flex-col items-center justify-center p-6 rounded-lg border-2 border-dashed border-neutral-700 hover:border-blue-600/50 hover:bg-neutral-800/50 transition-colors cursor-pointer text-center"
>
<Filter className="h-10 w-10 text-neutral-500 mb-2" />
<p className="text-neutral-400">No conditions yet</p>
<p className="text-sm text-neutral-500 mt-1">Click to add a condition</p>
</div>
)}
</div>
</div>
<ConditionDialog
open={open}
onOpenChange={setOpen}
selectedNode={selectedNode}
handleUpdateNode={handleUpdateNode}
/>
<Dialog open={deleteDialog} onOpenChange={setDeleteDialog}>
<DialogContent className="bg-neutral-800 border-neutral-700 text-neutral-200">
<DialogHeader>
<DialogTitle>Confirm Delete</DialogTitle>
</DialogHeader>
<div className="py-4">
<p>Are you sure you want to delete this condition?</p>
</div>
<DialogFooter>
<Button
variant="outline"
className="border-neutral-600 text-neutral-300 hover:bg-neutral-700"
onClick={() => {
setDeleteDialog(false);
setConditionToDelete(null);
}}
>
Cancel
</Button>
<Button
variant="destructive"
className="bg-red-900 hover:bg-red-800 text-white"
onClick={confirmDelete}
>
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
export { ConditionForm };

View File

@@ -0,0 +1,204 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/condition/ConditionNode.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Handle, Node, NodeProps, Position, useEdges } from "@xyflow/react";
import { FilterIcon, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { BaseNode } from "../../BaseNode";
import { ConditionType, ConditionTypeEnum } from "../../nodeFunctions";
export type ConditionNodeType = Node<
{
label?: string;
type?: "and" | "or";
conditions?: ConditionType[];
},
"condition-node"
>;
export type OperatorType =
| "is_defined"
| "is_not_defined"
| "equals"
| "not_equals"
| "contains"
| "not_contains"
| "starts_with"
| "ends_with"
| "greater_than"
| "greater_than_or_equal"
| "less_than"
| "less_than_or_equal"
| "matches"
| "not_matches";
const operatorText: Record<OperatorType, string> = {
equals: "is equal to",
not_equals: "is not equal to",
contains: "contains",
not_contains: "does not contain",
starts_with: "starts with",
ends_with: "ends with",
greater_than: "is greater than",
greater_than_or_equal: "is greater than or equal to",
less_than: "is less than",
less_than_or_equal: "is less than or equal to",
matches: "matches the pattern",
not_matches: "does not match the pattern",
is_defined: "is defined",
is_not_defined: "is not defined",
};
export function ConditionNode(props: NodeProps) {
const { selected, data } = props;
const edges = useEdges();
const isExecuting = data.isExecuting as boolean | undefined;
const typeText = {
and: "all of the following conditions",
or: "any of the following conditions",
};
const isHandleConnected = (handleId: string) => {
return edges.some(
(edge) => edge.source === props.id && edge.sourceHandle === handleId,
);
};
const isBottomHandleConnected = isHandleConnected("bottom-handle");
const conditions: ConditionType[] = data.conditions as ConditionType[];
// const statistics: StatisticType = data.statistics as StatisticType;
const renderCondition = (condition: ConditionType) => {
const isConnected = isHandleConnected(condition.id);
if (condition.type === ConditionTypeEnum.PREVIOUS_OUTPUT) {
return (
<div
className="mb-3 cursor-pointer rounded-lg border border-purple-700/40 bg-purple-950/10 p-3 text-left transition-all duration-200 hover:border-purple-600/50 hover:bg-purple-900/10"
>
<div className="flex items-center justify-between">
<div className="flex-1">
<p className="font-medium text-neutral-300">
O campo{" "}
<span className="font-semibold text-purple-400">
{condition.data.field}
</span>{" "}
<span className="text-neutral-400">
{operatorText[condition.data.operator as OperatorType]}
</span>{" "}
{!["is_defined", "is_not_defined"].includes(
condition.data.operator,
) && (
<span className="font-semibold text-green-400">
&quot;{condition.data.value}&quot;
</span>
)}
</p>
</div>
<Handle
className={cn(
"!rounded-full transition-all duration-300",
isConnected ? "!bg-purple-500 !border-purple-400" : "!bg-neutral-400 !border-neutral-500"
)}
style={{
top: "50%",
right: "-5px",
transform: "translateY(-50%)",
height: "14px",
position: "relative",
width: "14px",
}}
type="source"
position={Position.Right}
id={condition.id}
/>
</div>
</div>
);
}
return null;
};
return (
<BaseNode hasTarget={true} selected={selected || false} borderColor="purple" isExecuting={isExecuting}>
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-purple-900/40 shadow-sm">
<FilterIcon className="h-5 w-5 text-purple-400" />
</div>
<div>
<p className="text-lg font-medium text-purple-400">
{data.label as string}
</p>
<p className="text-xs text-neutral-400">
Matches {typeText[(data.type as "and" | "or") || "and"]}
</p>
</div>
</div>
</div>
{conditions && conditions.length > 0 && Array.isArray(conditions) ? (
conditions.map((condition) => (
<div key={condition.id}>{renderCondition(condition)}</div>
))
) : (
<div className="mb-3 flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-purple-700/40 bg-purple-950/10 p-5 text-center transition-all duration-200 hover:border-purple-600/50 hover:bg-purple-900/20">
<FilterIcon className="h-8 w-8 text-purple-700/50 mb-2" />
<p className="text-purple-400">No conditions configured</p>
<p className="mt-1 text-xs text-neutral-500">Click to add a condition</p>
</div>
)}
<div className="mt-2 flex items-center justify-end text-sm text-neutral-400 transition-colors">
<div className="flex items-center space-x-1 rounded-md py-1 px-2">
<span>Next step</span>
<ArrowRight className="h-3.5 w-3.5" />
</div>
<Handle
className={cn(
"!w-3 !h-3 !rounded-full transition-all duration-300",
isBottomHandleConnected ? "!bg-purple-500 !border-purple-400" : "!bg-neutral-400 !border-neutral-500",
selected && isBottomHandleConnected && "!bg-purple-400 !border-purple-300"
)}
style={{
right: "0px",
top: "calc(100% - 25px)",
}}
type="source"
position={Position.Right}
id="bottom-handle"
/>
</div>
</BaseNode>
);
}

View File

@@ -0,0 +1,256 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @author: Victor Calazans - Implementation of Delay node form │
│ @file: /app/agents/workflows/nodes/components/delay/DelayForm.tsx │
│ Developed by: Davidson Gomes │
│ Delay form developed by: Victor Calazans │
│ Creation date: May 13, 2025 │
│ Delay form implementation date: May 17, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useEffect } from "react";
import { Dispatch, SetStateAction } from "react";
import { Clock, Trash2, Save, AlertCircle, HourglassIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { DelayType, DelayUnitEnum } from "../../nodeFunctions";
import { cn } from "@/lib/utils";
export function DelayForm({
selectedNode,
handleUpdateNode,
setEdges,
setIsOpen,
setSelectedNode,
}: {
selectedNode: any;
handleUpdateNode: (node: any) => void;
setEdges: any;
setIsOpen: Dispatch<SetStateAction<boolean>>;
setSelectedNode: Dispatch<SetStateAction<any>>;
}) {
const [delay, setDelay] = useState<DelayType>({
value: 1,
unit: DelayUnitEnum.SECONDS,
description: "",
});
useEffect(() => {
if (selectedNode?.data?.delay) {
setDelay(selectedNode.data.delay);
}
}, [selectedNode]);
const handleSave = () => {
handleUpdateNode({
...selectedNode,
data: {
...selectedNode.data,
delay,
},
});
};
const handleDelete = () => {
setEdges((edges: any) => {
return edges.filter(
(edge: any) => edge.source !== selectedNode.id && edge.target !== selectedNode.id
);
});
setIsOpen(false);
setSelectedNode(null);
};
const getUnitLabel = (unit: DelayUnitEnum) => {
const units = {
[DelayUnitEnum.SECONDS]: "Seconds",
[DelayUnitEnum.MINUTES]: "Minutes",
[DelayUnitEnum.HOURS]: "Hours",
[DelayUnitEnum.DAYS]: "Days",
};
return units[unit] || unit;
};
const getTimeDescription = () => {
const value = delay.value || 0;
if (value <= 0) return "Invalid time";
if (value === 1) {
return `1 ${getUnitLabel(delay.unit).slice(0, -1)}`;
}
return `${value} ${getUnitLabel(delay.unit)}`;
};
return (
<div className="flex flex-col h-full">
<div className="p-4 border-b border-neutral-700 flex-shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<h3 className="text-md font-medium text-neutral-200">Delay Duration</h3>
<Badge
variant="outline"
className="text-xs bg-yellow-900/20 text-yellow-400 border-yellow-700/50"
>
{getTimeDescription().toUpperCase()}
</Badge>
</div>
<Select
value={delay.unit}
onValueChange={(value) =>
setDelay({
...delay,
unit: value as DelayUnitEnum,
})
}
>
<SelectTrigger className="w-[120px] h-8 bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectValue placeholder="Unit" />
</SelectTrigger>
<SelectContent className="bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectItem value={DelayUnitEnum.SECONDS}>Seconds</SelectItem>
<SelectItem value={DelayUnitEnum.MINUTES}>Minutes</SelectItem>
<SelectItem value={DelayUnitEnum.HOURS}>Hours</SelectItem>
<SelectItem value={DelayUnitEnum.DAYS}>Days</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="flex-1 overflow-y-auto p-4 min-h-0">
<div className="grid gap-4">
<div className="p-3 rounded-md bg-yellow-900/10 border border-yellow-700/30 mb-2">
<div className="flex items-start gap-2">
<div className="bg-yellow-900/50 rounded-full p-1.5 flex-shrink-0">
<Clock size={18} className="text-yellow-300" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-neutral-200">Time Delay</h3>
<p className="text-sm text-neutral-400 mt-1">
Pause workflow execution for a specified amount of time
</p>
</div>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="delay-value">Delay Value</Label>
<Input
id="delay-value"
type="number"
min="1"
className="bg-neutral-700 border-neutral-600"
value={delay.value}
onChange={(e) =>
setDelay({
...delay,
value: parseInt(e.target.value) || 1,
})
}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="delay-description">Description (optional)</Label>
<Textarea
id="delay-description"
className="bg-neutral-700 border-neutral-600 min-h-[100px] resize-none"
value={delay.description}
onChange={(e) =>
setDelay({
...delay,
description: e.target.value,
})
}
placeholder="Add a description for this delay"
/>
</div>
{delay.value > 0 ? (
<div className="rounded-md bg-neutral-700/50 border border-neutral-600 p-3 mt-2">
<div className="text-sm font-medium text-neutral-400 mb-1">Preview</div>
<div className="flex items-start gap-2 p-2 rounded-md bg-neutral-800/70">
<div className="rounded-full bg-yellow-900/30 p-1.5 mt-0.5">
<HourglassIcon size={15} className="text-yellow-400" />
</div>
<div className="flex-1">
<div className="flex flex-col">
<span className="text-sm text-yellow-400 font-medium">
{getTimeDescription()} delay
</span>
{delay.description && (
<span className="text-xs text-neutral-400 mt-1">
{delay.description}
</span>
)}
</div>
</div>
</div>
</div>
) : (
<div className="rounded-md bg-neutral-700/30 border border-neutral-600/50 p-4 flex flex-col items-center justify-center text-center">
<AlertCircle className="h-6 w-6 text-neutral-500 mb-2" />
<p className="text-neutral-400 text-sm">Please set a valid delay time</p>
</div>
)}
</div>
</div>
<div className="p-4 border-t border-neutral-700 flex-shrink-0">
<div className="flex gap-2 justify-between">
<Button
variant="outline"
className="border-red-700/50 bg-red-900/20 text-red-400 hover:bg-red-900/30 hover:text-red-300"
onClick={handleDelete}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete Node
</Button>
<Button
className="bg-yellow-700 hover:bg-yellow-600 text-white flex items-center gap-2"
onClick={handleSave}
>
<Save size={16} />
Save Delay
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,146 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @author: Victor Calazans - Implementation of Delay node functionality │
│ @file: /app/agents/workflows/nodes/components/delay/DelayNode.tsx │
│ Developed by: Davidson Gomes │
│ Delay node developed by: Victor Calazans │
│ Creation date: May 13, 2025 │
│ Delay node implementation date: May 17, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Handle, NodeProps, Position, useEdges } from "@xyflow/react";
import { Clock, ArrowRight, Timer } from "lucide-react";
import { DelayType } from "../../nodeFunctions";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { BaseNode } from "../../BaseNode";
export function DelayNode(props: NodeProps) {
const { selected, data } = props;
const edges = useEdges();
const isExecuting = data.isExecuting as boolean | undefined;
const isHandleConnected = (handleId: string) => {
return edges.some(
(edge) => edge.source === props.id && edge.sourceHandle === handleId
);
};
const isBottomHandleConnected = isHandleConnected("bottom-handle");
const delay = data.delay as DelayType | undefined;
const getUnitLabel = (unit: string) => {
switch (unit) {
case 'seconds':
return 'Seconds';
case 'minutes':
return 'Minutes';
case 'hours':
return 'Hours';
case 'days':
return 'Days';
default:
return unit;
}
};
return (
<BaseNode hasTarget={true} selected={selected || false} borderColor="yellow" isExecuting={isExecuting}>
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-yellow-900/40 shadow-sm">
<Clock className="h-5 w-5 text-yellow-400" />
</div>
<div>
<p className="text-lg font-medium text-yellow-400">
{data.label as string}
</p>
</div>
</div>
</div>
{delay ? (
<div className="mb-3 rounded-lg border border-yellow-700/40 bg-yellow-950/10 p-3 transition-all duration-200 hover:border-yellow-600/50 hover:bg-yellow-900/10">
<div className="flex flex-col">
<div className="flex items-start justify-between gap-2">
<div className="flex items-center">
<Timer className="h-4 w-4 text-yellow-400" />
<span className="ml-1.5 font-medium text-white">Delay</span>
</div>
<Badge
variant="outline"
className="px-1.5 py-0 text-xs bg-yellow-900/30 text-yellow-400 border-yellow-700/40"
>
{getUnitLabel(delay.unit)}
</Badge>
</div>
<div className="mt-2 flex items-center">
<span className="text-lg font-semibold text-yellow-300">{delay.value}</span>
<span className="ml-1 text-sm text-neutral-400">{delay.unit}</span>
</div>
{delay.description && (
<p className="mt-2 text-xs text-neutral-400 line-clamp-2">
{delay.description.slice(0, 80)} {delay.description.length > 80 && '...'}
</p>
)}
</div>
</div>
) : (
<div className="mb-3 flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-yellow-700/40 bg-yellow-950/10 p-5 text-center transition-all duration-200 hover:border-yellow-600/50 hover:bg-yellow-900/20">
<Clock className="h-8 w-8 text-yellow-700/50 mb-2" />
<p className="text-yellow-400">No delay configured</p>
<p className="mt-1 text-xs text-neutral-500">Click to configure</p>
</div>
)}
<div className="mt-2 flex items-center justify-end text-sm text-neutral-400 transition-colors">
<div className="flex items-center space-x-1 rounded-md py-1 px-2">
<span>Next step</span>
<ArrowRight className="h-3.5 w-3.5" />
</div>
<Handle
className={cn(
"!w-3 !h-3 !rounded-full transition-all duration-300",
isBottomHandleConnected ? "!bg-yellow-500 !border-yellow-400" : "!bg-neutral-400 !border-neutral-500",
selected && isBottomHandleConnected && "!bg-yellow-400 !border-yellow-300"
)}
style={{
right: "-8px",
top: "calc(100% - 25px)",
}}
type="source"
position={Position.Right}
id="bottom-handle"
/>
</div>
</BaseNode>
);
}

View File

@@ -0,0 +1,292 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/message/MessageForm.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable jsx-a11y/alt-text */
import { useEdges, useNodes } from "@xyflow/react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Agent } from "@/types/agent";
import { listAgents } from "@/services/agentService";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import {
MessageSquare,
Save,
Text,
Image,
File,
Video,
AlertCircle
} from "lucide-react";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
/* eslint-disable @typescript-eslint/no-explicit-any */
function MessageForm({
selectedNode,
handleUpdateNode,
setEdges,
setIsOpen,
setSelectedNode,
}: {
selectedNode: any;
handleUpdateNode: any;
setEdges: any;
setIsOpen: any;
setSelectedNode: any;
}) {
const [node, setNode] = useState(selectedNode);
const [messageType, setMessageType] = useState("text");
const [content, setContent] = useState("");
const [loading, setLoading] = useState(false);
const [agents, setAgents] = useState<Agent[]>([]);
const [allAgents, setAllAgents] = useState<Agent[]>([]);
const [searchTerm, setSearchTerm] = useState("");
const edges = useEdges();
const nodes = useNodes();
const connectedNode = useMemo(() => {
const edge = edges.find((edge) => edge.source === selectedNode.id);
if (!edge) return null;
const node = nodes.find((node) => node.id === edge.target);
return node || null;
}, [edges, nodes, selectedNode.id]);
const user = typeof window !== "undefined" ? JSON.parse(localStorage.getItem("user") || '{}') : {};
const clientId = user?.client_id || "";
const currentAgent = typeof window !== "undefined" ?
JSON.parse(localStorage.getItem("current_workflow_agent") || '{}') : {};
const currentAgentId = currentAgent?.id;
useEffect(() => {
if (selectedNode) {
setNode(selectedNode);
setMessageType(selectedNode.data.message?.type || "text");
setContent(selectedNode.data.message?.content || "");
}
}, [selectedNode]);
useEffect(() => {
if (!clientId) return;
setLoading(true);
listAgents(clientId)
.then((res) => {
const filteredAgents = res.data.filter((agent: Agent) => agent.id !== currentAgentId);
setAllAgents(filteredAgents);
setAgents(filteredAgents);
})
.catch((error) => console.error("Error loading agents:", error))
.finally(() => setLoading(false));
}, [clientId, currentAgentId]);
useEffect(() => {
if (searchTerm.trim() === "") {
setAgents(allAgents);
} else {
const filtered = allAgents.filter((agent) =>
agent.name.toLowerCase().includes(searchTerm.toLowerCase())
);
setAgents(filtered);
}
}, [searchTerm, allAgents]);
const handleDeleteEdge = useCallback(() => {
const id = edges.find((edge: any) => edge.source === selectedNode.id)?.id;
setEdges((edges: any) => {
const left = edges.filter((edge: any) => edge.id !== id);
return left;
});
}, [nodes, edges, selectedNode, setEdges]);
const handleSelectAgent = (agent: Agent) => {
const updatedNode = {
...node,
data: {
...node.data,
agent,
},
};
setNode(updatedNode);
handleUpdateNode(updatedNode);
};
const getAgentTypeName = (type: string) => {
const agentTypes: Record<string, string> = {
llm: "LLM Agent",
a2a: "A2A Agent",
sequential: "Sequential Agent",
parallel: "Parallel Agent",
loop: "Loop Agent",
workflow: "Workflow Agent",
task: "Task Agent",
};
return agentTypes[type] || type;
};
const handleSave = () => {
const updatedNode = {
...node,
data: {
...node.data,
message: {
type: messageType,
content,
},
},
};
setNode(updatedNode);
handleUpdateNode(updatedNode);
};
const messageTypeInfo = {
text: {
icon: <Text className="h-5 w-5 text-orange-400" />,
name: "Text Message",
description: "Simple text message",
color: "bg-orange-900/30 border-orange-700/50",
},
image: {
icon: <Image className="h-5 w-5 text-blue-400" />,
name: "Image",
description: "Image URL or base64",
color: "bg-blue-900/30 border-blue-700/50",
},
file: {
icon: <File className="h-5 w-5 text-emerald-400" />,
name: "File",
description: "File URL or base64",
color: "bg-emerald-900/30 border-emerald-700/50",
},
video: {
icon: <Video className="h-5 w-5 text-purple-400" />,
name: "Video",
description: "Video URL or base64",
color: "bg-purple-900/30 border-purple-700/50",
},
};
return (
<div className="flex flex-col h-full">
<div className="p-4 border-b border-neutral-700 flex-shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<h3 className="text-md font-medium text-neutral-200">Message Type</h3>
<Badge
variant="outline"
className="text-xs bg-orange-900/20 text-orange-400 border-orange-700/50"
>
{messageType === "text" ? "TEXT" : messageType.toUpperCase()}
</Badge>
</div>
<Select
value={messageType}
onValueChange={setMessageType}
>
<SelectTrigger className="w-[120px] h-8 bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent className="bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectItem value="text">Text</SelectItem>
{/* Other options can be enabled in the future */}
{/* <SelectItem value="image">Image</SelectItem>
<SelectItem value="file">File</SelectItem>
<SelectItem value="video">Video</SelectItem> */}
</SelectContent>
</Select>
</div>
</div>
<div className="flex-1 overflow-y-auto p-4 min-h-0">
<div className="grid gap-4">
<div className="p-3 rounded-md bg-orange-900/10 border border-orange-700/30 mb-2">
<div className="flex items-start gap-2">
<div className="bg-orange-900/50 rounded-full p-1.5 flex-shrink-0">
<MessageSquare size={18} className="text-orange-300" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-medium text-neutral-200">{messageTypeInfo.text.name}</h3>
<p className="text-sm text-neutral-400 mt-1">{messageTypeInfo.text.description}</p>
</div>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="content">Message Content</Label>
<Textarea
id="content"
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type your message here..."
className="min-h-[150px] bg-neutral-700 border-neutral-600 resize-none"
/>
</div>
{content.trim() !== "" ? (
<div className="rounded-md bg-neutral-700/50 border border-neutral-600 p-3 mt-2">
<div className="text-sm font-medium text-neutral-400 mb-1">Preview</div>
<div className="flex items-start gap-2 p-2 rounded-md bg-neutral-800/70">
<div className="rounded-full bg-orange-900/30 p-1.5 mt-0.5">
<MessageSquare size={15} className="text-orange-400" />
</div>
<div className="text-sm text-neutral-300 whitespace-pre-wrap">{content}</div>
</div>
</div>
) : (
<div className="rounded-md bg-neutral-700/30 border border-neutral-600/50 p-4 flex flex-col items-center justify-center text-center">
<AlertCircle className="h-6 w-6 text-neutral-500 mb-2" />
<p className="text-neutral-400 text-sm">Your message will appear here</p>
</div>
)}
</div>
</div>
<div className="p-4 border-t border-neutral-700 flex-shrink-0">
<Button
className="w-full bg-orange-700 hover:bg-orange-600 text-white flex items-center gap-2 justify-center"
onClick={handleSave}
>
<Save size={16} />
Save Message
</Button>
</div>
</div>
);
}
export { MessageForm };

View File

@@ -0,0 +1,162 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/message/MessageNode.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Handle, NodeProps, Position, useEdges } from "@xyflow/react";
import { MessageCircle, Text, Image, File, Video, ArrowRight } from "lucide-react";
import { MessageType, MessageTypeEnum } from "../../nodeFunctions";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { BaseNode } from "../../BaseNode";
export function MessageNode(props: NodeProps) {
const { selected, data } = props;
const edges = useEdges();
const isExecuting = data.isExecuting as boolean | undefined;
const isHandleConnected = (handleId: string) => {
return edges.some(
(edge) => edge.source === props.id && edge.sourceHandle === handleId
);
};
const isBottomHandleConnected = isHandleConnected("bottom-handle");
const message = data.message as MessageType | undefined;
const getMessageTypeIcon = (type: string) => {
switch (type) {
case MessageTypeEnum.TEXT:
return <Text className="h-4 w-4 text-orange-400" />;
case "image":
return <Image className="h-4 w-4 text-blue-400" />;
case "file":
return <File className="h-4 w-4 text-emerald-400" />;
case "video":
return <Video className="h-4 w-4 text-purple-400" />;
default:
return <MessageCircle className="h-4 w-4 text-orange-400" />;
}
};
const getMessageTypeColor = (type: string) => {
switch (type) {
case MessageTypeEnum.TEXT:
return 'bg-orange-900/30 text-orange-400 border-orange-700/40';
case "image":
return 'bg-blue-900/30 text-blue-400 border-blue-700/40';
case "file":
return 'bg-emerald-900/30 text-emerald-400 border-emerald-700/40';
case "video":
return 'bg-purple-900/30 text-purple-400 border-purple-700/40';
default:
return 'bg-orange-900/30 text-orange-400 border-orange-700/40';
}
};
const getMessageTypeName = (type: string) => {
const messageTypes: Record<string, string> = {
text: "Text Message",
image: "Image",
file: "File",
video: "Video",
};
return messageTypes[type] || type;
};
return (
<BaseNode hasTarget={true} selected={selected || false} borderColor="orange" isExecuting={isExecuting}>
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-orange-900/40 shadow-sm">
<MessageCircle className="h-5 w-5 text-orange-400" />
</div>
<div>
<p className="text-lg font-medium text-orange-400">
{data.label as string}
</p>
</div>
</div>
</div>
{message ? (
<div className="mb-3 rounded-lg border border-orange-700/40 bg-orange-950/10 p-3 transition-all duration-200 hover:border-orange-600/50 hover:bg-orange-900/10">
<div className="flex flex-col">
<div className="flex items-start justify-between gap-2">
<div className="flex items-center">
{getMessageTypeIcon(message.type)}
<span className="ml-1.5 font-medium text-white">{getMessageTypeName(message.type)}</span>
</div>
<Badge
variant="outline"
className={cn("px-1.5 py-0 text-xs", getMessageTypeColor(message.type))}
>
{message.type}
</Badge>
</div>
{message.content && (
<p className="mt-2 text-xs text-neutral-400 line-clamp-2">
{message.content.slice(0, 80)} {message.content.length > 80 && '...'}
</p>
)}
</div>
</div>
) : (
<div className="mb-3 flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-orange-700/40 bg-orange-950/10 p-5 text-center transition-all duration-200 hover:border-orange-600/50 hover:bg-orange-900/20">
<MessageCircle className="h-8 w-8 text-orange-700/50 mb-2" />
<p className="text-orange-400">No message configured</p>
<p className="mt-1 text-xs text-neutral-500">Click to configure</p>
</div>
)}
<div className="mt-2 flex items-center justify-end text-sm text-neutral-400 transition-colors">
<div className="flex items-center space-x-1 rounded-md py-1 px-2">
<span>Next step</span>
<ArrowRight className="h-3.5 w-3.5" />
</div>
<Handle
className={cn(
"!w-3 !h-3 !rounded-full transition-all duration-300",
isBottomHandleConnected ? "!bg-orange-500 !border-orange-400" : "!bg-neutral-400 !border-neutral-500",
selected && isBottomHandleConnected && "!bg-orange-400 !border-orange-300"
)}
style={{
right: "-8px",
top: "calc(100% - 25px)",
}}
type="source"
position={Position.Right}
id="bottom-handle"
/>
</div>
</BaseNode>
);
}

View File

@@ -0,0 +1,100 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/components/start/StartNode.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Handle, Node, NodeProps, Position, useEdges } from "@xyflow/react";
import { Zap, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { BaseNode } from "../../BaseNode";
export type StartNodeType = Node<
{
label?: string;
},
"start-node"
>;
export function StartNode(props: NodeProps) {
const { selected, data } = props;
const edges = useEdges();
const isExecuting = data.isExecuting as boolean | undefined;
const isSourceHandleConnected = edges.some(
(edge) => edge.source === props.id
);
return (
<BaseNode hasTarget={true} selected={selected || false} borderColor="emerald" isExecuting={isExecuting}>
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-emerald-900/40 shadow-sm">
<Zap className="h-5 w-5 text-emerald-400" />
</div>
<div>
<p className="text-lg font-medium text-emerald-400">Start</p>
</div>
</div>
</div>
<div className="mb-3 rounded-lg border border-emerald-700/40 bg-emerald-950/10 p-3 transition-all duration-200 hover:border-emerald-600/50 hover:bg-emerald-900/10">
<div className="flex flex-col">
<div className="flex items-start justify-between gap-2">
<div className="flex items-center">
<span className="font-medium text-white">Input: User content</span>
</div>
</div>
<p className="mt-2 text-xs text-neutral-400">
The workflow begins when a user sends a message to the agent
</p>
</div>
</div>
<div className="mt-2 flex items-center justify-end text-sm text-neutral-400 transition-colors">
<div className="flex items-center space-x-1 rounded-md py-1 px-2">
<span>Next step</span>
<ArrowRight className="h-3.5 w-3.5" />
</div>
<Handle
className={cn(
"!w-3 !h-3 !rounded-full transition-all duration-300",
isSourceHandleConnected ? "!bg-emerald-500 !border-emerald-400" : "!bg-neutral-400 !border-neutral-500",
selected && isSourceHandleConnected && "!bg-emerald-400 !border-emerald-300"
)}
style={{
right: "-8px",
top: "calc(100% - 25px)",
}}
type="source"
position={Position.Right}
/>
</div>
</BaseNode>
);
}

View File

@@ -0,0 +1,109 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @author: Victor Calazans - Implementation of Delay node type │
│ @file: /app/agents/workflows/nodes/index.ts │
│ Developed by: Davidson Gomes │
│ Delay node functionality developed by: Victor Calazans │
│ Creation date: May 13, 2025 │
│ Delay implementation date: May 17, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import type { NodeTypes, BuiltInNode, Node } from "@xyflow/react";
import { ConditionNode } from "./components/condition/ConditionNode";
import { AgentNode } from "./components/agent/AgentNode";
import { StartNode, StartNodeType } from "./components/start/StartNode";
import { MessageNode } from "./components/message/MessageNode";
import { DelayNode } from "./components/delay/DelayNode";
import "./style.css";
import {
ConditionType,
MessageType,
DelayType,
} from "./nodeFunctions";
import { Agent } from "@/types/agent";
type AgentNodeType = Node<
{
label?: string;
agent?: Agent;
},
"agent-node"
>;
type MessageNodeType = Node<
{
label?: string;
message?: MessageType;
},
"message-node"
>;
type DelayNodeType = Node<
{
label?: string;
delay?: DelayType;
},
"delay-node"
>;
type ConditionNodeType = Node<
{
label?: string;
integration?: string;
icon?: string;
conditions?: ConditionType[];
},
"condition-node"
>;
export type AppNode =
| BuiltInNode
| StartNodeType
| AgentNodeType
| ConditionNodeType
| MessageNodeType
| DelayNodeType;
export type NodeType = AppNode["type"];
export const initialNodes: AppNode[] = [
{
id: "start-node",
type: "start-node",
position: { x: -100, y: 100 },
data: {
label: "Start",
},
},
];
export const nodeTypes = {
"start-node": StartNode,
"agent-node": AgentNode,
"message-node": MessageNode,
"condition-node": ConditionNode,
"delay-node": DelayNode,
} satisfies NodeTypes;

View File

@@ -0,0 +1,65 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @author: Victor Calazans - Implementation of Delay types │
│ @file: /app/agents/workflows/nodes/nodeFunctions.ts │
│ Developed by: Davidson Gomes │
│ Delay node functionality developed by: Victor Calazans │
│ Creation date: May 13, 2025 │
│ Delay implementation date: May 17, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-unused-vars */
export enum ConditionTypeEnum {
PREVIOUS_OUTPUT = "previous-output",
}
export enum MessageTypeEnum {
TEXT = "text",
}
export enum DelayUnitEnum {
SECONDS = "seconds",
MINUTES = "minutes",
HOURS = "hours",
DAYS = "days",
}
export type MessageType = {
type: MessageTypeEnum;
content: string;
};
export type DelayType = {
value: number;
unit: DelayUnitEnum;
description?: string;
};
export type ConditionType = {
id: string;
type: ConditionTypeEnum;
data?: any;
};

View File

@@ -0,0 +1,54 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/nodes/style.css │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
/* .react-flow__handle {
background-color: #8492A6;
border-radius: 50%;
height: 16px;
position: absolute;
width: 16px;
} */
/* .react-flow__handle-right {
right: -6px;
top: 88%;
transform: translateY(-75%);
background-color: #f5f5f5 !important;
border: 3px solid #8492A6 !important;
} */
/* .react-flow__handle-left {
left: 0px;
top: 40%;
width: 60px;
border-radius: 0;
height: 50%;
transform: translateY(-75%);
background-color: transparent;
border: none;
} */

View File

@@ -0,0 +1,218 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/page.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import { useEffect, useState, useRef, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import Canva from "./Canva";
import { Agent } from "@/types/agent";
import { getAgent, updateAgent } from "@/services/agentService";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Save, Download, PlayIcon } from "lucide-react";
import Link from "next/link";
import { ReactFlowProvider } from "@xyflow/react";
import { DnDProvider } from "@/contexts/DnDContext";
import { NodeDataProvider } from "@/contexts/NodeDataContext";
import { SourceClickProvider } from "@/contexts/SourceClickContext";
import { useToast } from "@/hooks/use-toast";
import { AgentTestChatModal } from "./nodes/components/agent/AgentTestChatModal";
function WorkflowsContent() {
const searchParams = useSearchParams();
const agentId = searchParams.get("agentId");
const [agent, setAgent] = useState<Agent | null>(null);
const [loading, setLoading] = useState(false);
const canvaRef = useRef<any>(null);
const { toast } = useToast();
const [isTestModalOpen, setIsTestModalOpen] = useState(false);
const user =
typeof window !== "undefined"
? JSON.parse(localStorage.getItem("user") || "{}")
: {};
const clientId = user?.client_id || "";
useEffect(() => {
if (agentId && clientId) {
setLoading(true);
getAgent(agentId, clientId)
.then((res) => {
setAgent(res.data);
if (typeof window !== "undefined") {
localStorage.setItem(
"current_workflow_agent",
JSON.stringify(res.data)
);
}
})
.catch((err) => {
console.error("Error loading agent:", err);
})
.finally(() => {
setLoading(false);
});
}
}, [agentId, clientId]);
useEffect(() => {
return () => {
if (typeof window !== "undefined") {
localStorage.removeItem("current_workflow_agent");
}
};
}, []);
const handleSaveWorkflow = async () => {
if (!agent || !canvaRef.current) return;
try {
const { nodes, edges } = canvaRef.current.getFlowData();
const workflow = {
nodes,
edges,
};
await updateAgent(agent.id, {
...agent,
config: {
...agent.config,
workflow,
},
});
toast({
title: "Workflow saved",
description: "The changes were saved successfully",
});
canvaRef.current.setHasChanges(false);
} catch (error) {
console.error("Error saving workflow:", error);
toast({
title: "Error saving workflow",
description: "Unable to save the changes",
variant: "destructive",
});
}
};
if (loading) {
return (
<div className="w-full h-screen bg-[#121212] flex items-center justify-center">
<div className="text-white text-xl">Loading...</div>
</div>
);
}
return (
<div className="relative w-full h-screen flex flex-col" data-workflow-page="true">
{/* Header with controls */}
<div className="w-full bg-[#121212] py-4 px-6 z-10 flex items-center justify-between border-b border-neutral-800">
<div className="flex items-center gap-2">
<Link href="/agents">
<Button
variant="outline"
className="bg-neutral-800 border-neutral-700 text-neutral-200 hover:bg-neutral-700"
>
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Agents
</Button>
</Link>
{agent && (
<div className="bg-neutral-800 px-4 py-2 rounded-md">
<h2 className="text-neutral-200 font-medium">
{agent.name} -{" "}
<span className="text-neutral-400 text-sm">{agent.type}</span>
</h2>
</div>
)}
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
className="bg-neutral-800 border-neutral-700 text-neutral-200 hover:bg-neutral-700"
onClick={handleSaveWorkflow}
>
<Save className="mr-2 h-4 w-4" />
Save
</Button>
{agent && (
<Button
variant="outline"
className="bg-green-800 border-green-700 text-green-200 hover:bg-green-700"
onClick={() => setIsTestModalOpen(true)}
>
<PlayIcon className="h-4 w-4 mr-2" />
Test Workflow
</Button>
)}
</div>
</div>
{/* Main content area */}
<div className="flex-1 relative overflow-hidden">
{agent && isTestModalOpen && (
<AgentTestChatModal
open={isTestModalOpen}
onOpenChange={setIsTestModalOpen}
agent={agent}
canvasRef={canvaRef} // Pass the canvas reference to allow visualization of running nodes
/>
)}
<NodeDataProvider>
<SourceClickProvider>
<DnDProvider>
<ReactFlowProvider>
<Canva agent={agent} ref={canvaRef} data-canvas-ref="true" />
</ReactFlowProvider>
</DnDProvider>
</SourceClickProvider>
</NodeDataProvider>
</div>
</div>
);
}
export default function WorkflowsPage() {
return (
<Suspense
fallback={
<div className="w-full h-screen bg-[#121212] flex items-center justify-center">
<div className="text-white text-xl">Loading...</div>
</div>
}
>
<WorkflowsContent />
</Suspense>
);
}

View File

@@ -0,0 +1,199 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/agents/workflows/utils.ts │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
import { Node, NodePositionChange, XYPosition } from "@xyflow/react";
type GetHelperLinesResult = {
horizontal?: number;
vertical?: number;
snapPosition: Partial<XYPosition>;
};
// this utility function can be called with a position change (inside onNodesChange)
// it checks all other nodes and calculated the helper line positions and the position where the current node should snap to
export function getHelperLines(
change: NodePositionChange,
nodes: Node[],
distance = 5,
): GetHelperLinesResult {
const defaultResult = {
horizontal: undefined,
vertical: undefined,
snapPosition: { x: undefined, y: undefined },
};
const nodeA = nodes.find((node) => node.id === change.id);
if (!nodeA || !change.position) {
return defaultResult;
}
const nodeABounds = {
left: change.position.x,
right: change.position.x + (nodeA.measured?.width ?? 0),
top: change.position.y,
bottom: change.position.y + (nodeA.measured?.height ?? 0),
width: nodeA.measured?.width ?? 0,
height: nodeA.measured?.height ?? 0,
};
let horizontalDistance = distance;
let verticalDistance = distance;
return nodes
.filter((node) => node.id !== nodeA.id)
.reduce<GetHelperLinesResult>((result, nodeB) => {
const nodeBBounds = {
left: nodeB.position.x,
right: nodeB.position.x + (nodeB.measured?.width ?? 0),
top: nodeB.position.y,
bottom: nodeB.position.y + (nodeB.measured?.height ?? 0),
width: nodeB.measured?.width ?? 0,
height: nodeB.measured?.height ?? 0,
};
// |‾‾‾‾‾‾‾‾‾‾‾|
// | A |
// |___________|
// |
// |
// |‾‾‾‾‾‾‾‾‾‾‾|
// | B |
// |___________|
const distanceLeftLeft = Math.abs(nodeABounds.left - nodeBBounds.left);
if (distanceLeftLeft < verticalDistance) {
result.snapPosition.x = nodeBBounds.left;
result.vertical = nodeBBounds.left;
verticalDistance = distanceLeftLeft;
}
// |‾‾‾‾‾‾‾‾‾‾‾|
// | A |
// |___________|
// |
// |
// |‾‾‾‾‾‾‾‾‾‾‾|
// | B |
// |___________|
const distanceRightRight = Math.abs(
nodeABounds.right - nodeBBounds.right,
);
if (distanceRightRight < verticalDistance) {
result.snapPosition.x = nodeBBounds.right - nodeABounds.width;
result.vertical = nodeBBounds.right;
verticalDistance = distanceRightRight;
}
// |‾‾‾‾‾‾‾‾‾‾‾|
// | A |
// |___________|
// |
// |
// |‾‾‾‾‾‾‾‾‾‾‾|
// | B |
// |___________|
const distanceLeftRight = Math.abs(nodeABounds.left - nodeBBounds.right);
if (distanceLeftRight < verticalDistance) {
result.snapPosition.x = nodeBBounds.right;
result.vertical = nodeBBounds.right;
verticalDistance = distanceLeftRight;
}
// |‾‾‾‾‾‾‾‾‾‾‾|
// | A |
// |___________|
// |
// |
// |‾‾‾‾‾‾‾‾‾‾‾|
// | B |
// |___________|
const distanceRightLeft = Math.abs(nodeABounds.right - nodeBBounds.left);
if (distanceRightLeft < verticalDistance) {
result.snapPosition.x = nodeBBounds.left - nodeABounds.width;
result.vertical = nodeBBounds.left;
verticalDistance = distanceRightLeft;
}
// |‾‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾‾|
// | A | | B |
// |___________| |___________|
const distanceTopTop = Math.abs(nodeABounds.top - nodeBBounds.top);
if (distanceTopTop < horizontalDistance) {
result.snapPosition.y = nodeBBounds.top;
result.horizontal = nodeBBounds.top;
horizontalDistance = distanceTopTop;
}
// |‾‾‾‾‾‾‾‾‾‾‾|
// | A |
// |___________|_________________
// | |
// | B |
// |___________|
const distanceBottomTop = Math.abs(nodeABounds.bottom - nodeBBounds.top);
if (distanceBottomTop < horizontalDistance) {
result.snapPosition.y = nodeBBounds.top - nodeABounds.height;
result.horizontal = nodeBBounds.top;
horizontalDistance = distanceBottomTop;
}
// |‾‾‾‾‾‾‾‾‾‾‾| |‾‾‾‾‾‾‾‾‾‾‾|
// | A | | B |
// |___________|_____|___________|
const distanceBottomBottom = Math.abs(
nodeABounds.bottom - nodeBBounds.bottom,
);
if (distanceBottomBottom < horizontalDistance) {
result.snapPosition.y = nodeBBounds.bottom - nodeABounds.height;
result.horizontal = nodeBBounds.bottom;
horizontalDistance = distanceBottomBottom;
}
// |‾‾‾‾‾‾‾‾‾‾‾|
// | B |
// | |
// |‾‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// | A |
// |___________|
const distanceTopBottom = Math.abs(nodeABounds.top - nodeBBounds.bottom);
if (distanceTopBottom < horizontalDistance) {
result.snapPosition.y = nodeBBounds.bottom;
result.horizontal = nodeBBounds.bottom;
horizontalDistance = distanceTopBottom;
}
return result;
}, defaultResult);
}