ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add workflow engine, models, API & UI
Juan Denisd2d87ecc1d9f
diff --git a/ROADMAP.md b/ROADMAP.mdindex 42adc19f..ac278abe 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -310,12 +310,12 @@ The phases below are ordered by priority. Higher phases ship first.Moving beyond static design to dynamic, event-driven automation. This turns ServerKit into a powerful automation hub.-- [ ] **Event Triggers:** Run workflows on Git push, health check failure, high CPU usage, or Webhook receipt.-- [ ] **Cron Integration:** Schedule workflows to run on recurring intervals (e.g., "Every Sunday at 2 AM, backup all DBs and rotate logs").-- [ ] **Cross-Server Actions:** "When Server A's database is backed up, sync it to Server B and notify Discord."-- [ ] **Logic Nodes:** If/Else conditions, loops, and custom Python/Shell script execution nodes.-- [ ] **State Machine:** Track workflow execution history, retries on failure, and execution logs.-- [ ] **Global Variables:** Pass data between workflow steps (e.g., take the output of a build step and pass it to a deployment step).+- [x] **Event Triggers:** Run workflows on Git push, health check failure, high CPU usage, or Webhook receipt.+- [x] **Cron Integration:** Schedule workflows to run on recurring intervals (e.g., "Every Sunday at 2 AM, backup all DBs and rotate logs").+- [x] **Cross-Server Actions:** "When Server A's database is backed up, sync it to Server B and notify Discord."+- [x] **Logic Nodes:** If/Else conditions, loops, and custom Python/Shell script execution nodes.+- [x] **State Machine:** Track workflow execution history, retries on failure, and execution logs.+- [x] **Global Variables:** Pass data between workflow steps (e.g., take the output of a build step and pass it to a deployment step).---diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 2c5c6641..16248543 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -240,6 +240,9 @@ def create_app(config_name=None):# Start auto-sync scheduler for WordPress environments_start_auto_sync_scheduler(app)+ # Start workflow scheduler+ _start_workflow_scheduler(app)+# Start API analytics flush threadfrom app.middleware.api_analytics import start_analytics_flush_threadstart_analytics_flush_thread(app)@@ -383,3 +386,87 @@ def _start_api_background_threads(app):name='api-background')_api_bg_thread.start()+++_workflow_thread = None+++def _start_workflow_scheduler(app):+ """Start a background thread that checks for scheduled workflows."""+ global _workflow_thread+ if _workflow_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def workflow_loop():+ while True:+ try:+ time.sleep(60) # Check every 60 seconds+ with app.app_context():+ _check_workflow_schedules(logger)+ except Exception as e:+ logger.error(f'Workflow scheduler error: {e}')++ _workflow_thread = threading.Thread(+ target=workflow_loop,+ daemon=True,+ name='workflow-scheduler'+ )+ _workflow_thread.start()+++def _check_workflow_schedules(logger):+ """Check all active workflows with cron triggers and run those that are due."""+ from app.models.workflow import Workflow+ from app.services.workflow_engine import WorkflowEngine+ from datetime import datetime+ import json++ try:+ from croniter import croniter+ except ImportError:+ logger.debug('croniter not installed, skipping workflow schedule check')+ return++ # Find active workflows with cron triggers+ workflows = Workflow.query.filter_by(is_active=True, trigger_type='cron').all()+ if not workflows:+ return++ now = datetime.utcnow()++ for workflow in workflows:+ try:+ config = json.loads(workflow.trigger_config) if workflow.trigger_config else {}+ cron_expr = config.get('cron')++ if not cron_expr or not croniter.is_valid(cron_expr):+ continue++ cron = croniter(cron_expr, now)+ prev_run = cron.get_prev(datetime)++ # Check if a run was due in the last 90 seconds+ seconds_since_due = (now - prev_run).total_seconds()++ # Also ensure we don't run it multiple times for the same slot+ if 0 < seconds_since_due <= 90:+ # Check if it already ran in the last 2 minutes+ if workflow.last_run_at:+ seconds_since_last_run = (now - workflow.last_run_at).total_seconds()+ if seconds_since_last_run < 110:+ continue++ logger.info(f'Scheduled workflow triggered: {workflow.name} (ID: {workflow.id})')+ WorkflowEngine.execute_workflow(+ workflow_id=workflow.id,+ trigger_type='cron',+ context={'scheduled_at': prev_run.isoformat()}+ )+ except Exception as e:+ logger.error(f'Workflow schedule check failed for workflow {workflow.id}: {e}')diff --git a/backend/app/api/workflows.py b/backend/app/api/workflows.pyindex 36511ea3..6049430a 100644--- a/backend/app/api/workflows.py+++ b/backend/app/api/workflows.py@@ -2,7 +2,7 @@ import jsonfrom flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app import db-from app.models import Workflow, User+from app.models import Workflow, User, WorkflowExecution, WorkflowLogworkflows_bp = Blueprint('workflows', __name__)@@ -61,6 +61,9 @@ def create_workflow():nodes=json.dumps(data.get('nodes', [])),edges=json.dumps(data.get('edges', [])),viewport=json.dumps(data.get('viewport')) if data.get('viewport') else None,+ is_active=data.get('is_active', False),+ trigger_type=data.get('trigger_type', 'manual'),+ trigger_config=json.dumps(data.get('trigger_config', {})),user_id=current_user_id)@@ -101,6 +104,14 @@ def update_workflow(workflow_id):workflow.edges = json.dumps(data['edges'])if 'viewport' in data:workflow.viewport = json.dumps(data['viewport']) if data['viewport'] else None++ # Automation fields+ if 'is_active' in data:+ workflow.is_active = data['is_active']+ if 'trigger_type' in data:+ workflow.trigger_type = data['trigger_type']+ if 'trigger_config' in data:+ workflow.trigger_config = json.dumps(data['trigger_config'])db.session.commit()@@ -130,27 +141,103 @@ def delete_workflow(workflow_id):return jsonify({'message': 'Workflow deleted successfully'})+@workflows_bp.route('/<int:workflow_id>/execute', methods=['POST'])+@jwt_required()+def execute_workflow(workflow_id):+ """Trigger a workflow execution manually."""+ from app.services.workflow_engine import WorkflowEngine++ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ workflow = Workflow.query.get(workflow_id)++ if not workflow:+ return jsonify({'error': 'Workflow not found'}), 404++ if user.role != 'admin' and workflow.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ data = request.get_json() or {}+ context = data.get('context', {})++ execution_id = WorkflowEngine.execute_workflow(+ workflow_id=workflow_id,+ trigger_type='manual',+ context=context+ )++ return jsonify({+ 'message': 'Workflow execution started',+ 'execution_id': execution_id+ })+++@workflows_bp.route('/<int:workflow_id>/executions', methods=['GET'])+@jwt_required()+def get_workflow_executions(workflow_id):+ """Get execution history for a workflow."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ workflow = Workflow.query.get(workflow_id)++ if not workflow:+ return jsonify({'error': 'Workflow not found'}), 404++ if user.role != 'admin' and workflow.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ executions = WorkflowExecution.query.filter_by(workflow_id=workflow_id).order_by(WorkflowExecution.started_at.desc()).all()++ return jsonify({+ 'executions': [e.to_dict() for e in executions]+ })+++@workflows_bp.route('/executions/<int:execution_id>', methods=['GET'])+@jwt_required()+def get_execution_details(execution_id):+ """Get details for a specific execution."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ execution = WorkflowExecution.query.get(execution_id)++ if not execution:+ return jsonify({'error': 'Execution not found'}), 404++ workflow = execution.workflow+ if user.role != 'admin' and workflow.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ return jsonify(execution.to_dict())+++@workflows_bp.route('/executions/<int:execution_id>/logs', methods=['GET'])+@jwt_required()+def get_execution_logs(execution_id):+ """Get logs for a specific execution."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ execution = WorkflowExecution.query.get(execution_id)++ if not execution:+ return jsonify({'error': 'Execution not found'}), 404++ workflow = execution.workflow+ if user.role != 'admin' and workflow.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ logs = WorkflowLog.query.filter_by(execution_id=execution_id).order_by(WorkflowLog.timestamp.asc()).all()++ return jsonify({+ 'logs': [l.to_dict() for l in logs]+ })++@workflows_bp.route('/<int:workflow_id>/deploy', methods=['POST'])@jwt_required()def deploy_workflow(workflow_id):"""Deploy all resources from a workflow.-- This endpoint converts workflow nodes (Docker apps, databases, domains)- into actual infrastructure by calling the appropriate backend services.-- Returns:- {- "success": boolean,- "message": string,- "results": [- {"nodeId": "node_1", "type": "dockerApp", "success": true, "resourceId": 5},- {"nodeId": "node_2", "type": "domain", "success": true, "resourceId": 12},- ...- ],- "errors": [],- "workflow": {...updated workflow with resource IDs...}- }"""from app.services.workflow_service import WorkflowServicediff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 04a7d9b6..508fe598 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -7,7 +7,7 @@ from app.models.deployment import Deployment, DeploymentDifffrom app.models.system_settings import SystemSettingsfrom app.models.audit_log import AuditLogfrom app.models.metrics_history import MetricsHistory-from app.models.workflow import Workflow+from app.models.workflow import Workflow, WorkflowExecution, WorkflowLogfrom app.models.webhook import GitWebhook, WebhookLog, GitDeploymentfrom app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSessionfrom app.models.security_alert import SecurityAlert@@ -25,7 +25,7 @@ from app.models.invitation import Invitation__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory','NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog',- 'MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment',+ 'MetricsHistory', 'Workflow', 'WorkflowExecution', 'WorkflowLog', 'GitWebhook', 'WebhookLog', 'GitDeployment','Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert','WordPressSite', 'DatabaseSnapshot', 'SyncJob','EnvironmentActivity', 'PromotionJob', 'SanitizationProfile',diff --git a/backend/app/models/workflow.py b/backend/app/models/workflow.pyindex c30af13f..33398919 100644--- a/backend/app/models/workflow.py+++ b/backend/app/models/workflow.py@@ -1,5 +1,6 @@from datetime import datetimefrom app import db+import jsonclass Workflow(db.Model):@@ -14,6 +15,13 @@ class Workflow(db.Model):edges = db.Column(db.Text, nullable=True) # JSON array of edgesviewport = db.Column(db.Text, nullable=True) # JSON object {x, y, zoom}+ # Automation fields+ is_active = db.Column(db.Boolean, default=False)+ trigger_type = db.Column(db.String(50), default='manual') # manual, cron, event, webhook+ trigger_config = db.Column(db.Text, nullable=True) # JSON configuration for the trigger+ last_run_at = db.Column(db.DateTime, nullable=True)+ last_status = db.Column(db.String(20), nullable=True) # success, failed+# Metadatacreated_at = db.Column(db.DateTime, default=datetime.utcnow)updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)@@ -23,9 +31,9 @@ class Workflow(db.Model):# Relationshipsuser = db.relationship('User', backref=db.backref('workflows', lazy='dynamic'))+ executions = db.relationship('WorkflowExecution', backref='workflow', lazy='dynamic', cascade='all, delete-orphan')def to_dict(self):- import jsonreturn {'id': self.id,'name': self.name,@@ -33,6 +41,11 @@ class Workflow(db.Model):'nodes': json.loads(self.nodes) if self.nodes else [],'edges': json.loads(self.edges) if self.edges else [],'viewport': json.loads(self.viewport) if self.viewport else None,+ 'is_active': self.is_active,+ 'trigger_type': self.trigger_type,+ 'trigger_config': json.loads(self.trigger_config) if self.trigger_config else {},+ 'last_run_at': self.last_run_at.isoformat() if self.last_run_at else None,+ 'last_status': self.last_status,'created_at': self.created_at.isoformat() if self.created_at else None,'updated_at': self.updated_at.isoformat() if self.updated_at else None,'user_id': self.user_id,@@ -42,3 +55,53 @@ class Workflow(db.Model):def __repr__(self):return f'<Workflow {self.name}>'+++class WorkflowExecution(db.Model):+ __tablename__ = 'workflow_executions'++ id = db.Column(db.Integer, primary_key=True)+ workflow_id = db.Column(db.Integer, db.ForeignKey('workflows.id'), nullable=False)+ status = db.Column(db.String(20), default='running') # running, success, failed, cancelled+ trigger_type = db.Column(db.String(50))+ context = db.Column(db.Text, nullable=True) # JSON data passed between steps+ results = db.Column(db.Text, nullable=True) # JSON results of each step++ started_at = db.Column(db.DateTime, default=datetime.utcnow)+ completed_at = db.Column(db.DateTime, nullable=True)++ logs = db.relationship('WorkflowLog', backref='execution', lazy='dynamic', cascade='all, delete-orphan')++ def to_dict(self):+ return {+ 'id': self.id,+ 'workflow_id': self.workflow_id,+ 'status': self.status,+ 'trigger_type': self.trigger_type,+ 'context': json.loads(self.context) if self.context else {},+ 'results': json.loads(self.results) if self.results else {},+ 'started_at': self.started_at.isoformat() if self.started_at else None,+ 'completed_at': self.completed_at.isoformat() if self.completed_at else None,+ 'duration': (self.completed_at - self.started_at).total_seconds() if self.completed_at else None+ }+++class WorkflowLog(db.Model):+ __tablename__ = 'workflow_logs'++ id = db.Column(db.Integer, primary_key=True)+ execution_id = db.Column(db.Integer, db.ForeignKey('workflow_executions.id'), nullable=False)+ level = db.Column(db.String(10), default='INFO') # INFO, WARNING, ERROR, DEBUG+ message = db.Column(db.Text, nullable=False)+ node_id = db.Column(db.String(100), nullable=True) # ID of the node that generated the log+ timestamp = db.Column(db.DateTime, default=datetime.utcnow)++ def to_dict(self):+ return {+ 'id': self.id,+ 'execution_id': self.execution_id,+ 'level': self.level,+ 'message': self.message,+ 'node_id': self.node_id,+ 'timestamp': self.timestamp.isoformat()+ }diff --git a/backend/app/services/workflow_engine.py b/backend/app/services/workflow_engine.pynew file mode 100644index 00000000..c351151b--- /dev/null+++ b/backend/app/services/workflow_engine.py@@ -0,0 +1,228 @@+"""+Advanced Workflow & Automation Engine++Executes event-driven workflows with logic nodes, triggers, and cross-server actions.+"""++import json+import logging+import traceback+from datetime import datetime+from typing import Dict, List, Any, Optional++from app import db+from app.models import Workflow, WorkflowExecution, WorkflowLog, User+from app.services.workflow_service import WorkflowService+from app.services.docker_service import DockerService+from app.services.database_service import DatabaseService+from app.services.notification_service import NotificationService+++class WorkflowEngine:+ """Engine for executing advanced workflows."""++ @staticmethod+ def execute_workflow(workflow_id: int, trigger_type: str = 'manual', context: Dict[str, Any] = None) -> int:+ """+ Execute a workflow by ID.++ Returns:+ ID of the created WorkflowExecution+ """+ workflow = Workflow.query.get(workflow_id)+ if not workflow:+ raise ValueError(f"Workflow {workflow_id} not found")++ # Create execution record+ execution = WorkflowExecution(+ workflow_id=workflow_id,+ trigger_type=trigger_type,+ status='running',+ context=json.dumps(context or {}),+ started_at=datetime.utcnow()+ )+ db.session.add(execution)+ db.session.commit()++ # Update workflow last run+ workflow.last_run_at = execution.started_at+ db.session.commit()++ try:+ # Run the execution in the background or synchronously for now+ WorkflowEngine._run_execution(execution.id)+ except Exception as e:+ WorkflowEngine.log(execution.id, f"Engine Error: {str(e)}", level='ERROR')+ execution.status = 'failed'+ execution.completed_at = datetime.utcnow()+ workflow.last_status = 'failed'+ db.session.commit()++ return execution.id++ @staticmethod+ def _run_execution(execution_id: int):+ """Internal method to run the execution logic."""+ execution = WorkflowExecution.query.get(execution_id)+ workflow = execution.workflow++ WorkflowEngine.log(execution_id, f"Starting workflow: {workflow.name}")++ try:+ nodes = json.loads(workflow.nodes) if workflow.nodes else []+ edges = json.loads(workflow.edges) if workflow.edges else []++ if not nodes:+ WorkflowEngine.log(execution_id, "Workflow has no nodes", level='WARNING')+ execution.status = 'success'+ execution.completed_at = datetime.utcnow()+ db.session.commit()+ return++ # Build adjacency list and find start nodes+ adj = {}+ for edge in edges:+ source = edge['source']+ target = edge['target']+ if source not in adj: adj[source] = []+ adj[source].append(target)++ # Find trigger nodes or start nodes (no incoming edges)+ incoming_count = {node['id']: 0 for node in nodes}+ for edge in edges:+ target = edge['target']+ if target in incoming_count:+ incoming_count[target] += 1++ # Start with nodes that have no incoming edges (usually triggers)+ queue = [node for node in nodes if incoming_count[node['id']] == 0]++ if not queue:+ # If everything is cyclic, just start with the first node+ queue = [nodes[0]]++ # Execution state+ results = {}+ context = json.loads(execution.context) if execution.context else {}++ # Simple linear/BFS execution for now+ # TODO: Implement full DAG execution with branch support+ processed = set()++ while queue:+ node = queue.pop(0)+ if node['id'] in processed:+ continue++ WorkflowEngine.log(execution_id, f"Executing node: {node.get('data', {}).get('label', node['id'])} ({node['type']})", node_id=node['id'])++ # Execute node+ try:+ node_result = WorkflowEngine._execute_node(node, edges, execution, context, results)+ results[node['id']] = node_result++ if not node_result.get('success', True):+ WorkflowEngine.log(execution_id, f"Node failed: {node_result.get('error')}", level='ERROR', node_id=node['id'])+ if node_result.get('critical', True):+ execution.status = 'failed'+ break++ # Add next nodes to queue+ if node['id'] in adj:+ for next_id in adj[node['id']]:+ next_node = next((n for n in nodes if n['id'] == next_id), None)+ if next_node:+ queue.append(next_node)++ except Exception as e:+ WorkflowEngine.log(execution_id, f"Node Execution Error: {str(e)}", level='ERROR', node_id=node['id'])+ WorkflowEngine.log(execution_id, traceback.format_exc(), level='DEBUG', node_id=node['id'])+ execution.status = 'failed'+ break++ processed.add(node['id'])++ if execution.status != 'failed':+ execution.status = 'success'++ execution.results = json.dumps(results)+ execution.completed_at = datetime.utcnow()+ workflow.last_status = execution.status+ db.session.commit()++ WorkflowEngine.log(execution_id, f"Workflow finished with status: {execution.status}")++ except Exception as e:+ WorkflowEngine.log(execution_id, f"Execution Loop Error: {str(e)}", level='ERROR')+ WorkflowEngine.log(execution_id, traceback.format_exc(), level='DEBUG')+ execution.status = 'failed'+ execution.completed_at = datetime.utcnow()+ db.session.commit()++ @staticmethod+ def _execute_node(node: Dict, edges: List, execution: WorkflowExecution, context: Dict, results: Dict) -> Dict:+ """Execute a single node and return its results."""+ node_type = node.get('type')+ node_data = node.get('data', {})++ if node_type == 'trigger':+ return {'success': True, 'output': context}++ elif node_type in ('database', 'dockerApp', 'service', 'domain'):+ # Delegate to WorkflowService+ res = WorkflowService.deploy_node(node, edges, execution.workflow.user_id, results)+ return res++ elif node_type == 'notification':+ channel = node_data.get('channel', 'discord')+ message = node_data.get('message', 'Workflow notification')+ # Replace placeholders in message from context/results+ # TODO: Implementation++ NotificationService.send_notification(+ user_id=execution.workflow.user_id,+ title=f"Workflow: {execution.workflow.name}",+ message=message,+ level='info'+ )+ return {'success': True}++ elif node_type == 'script':+ script_type = node_data.get('language', 'bash')+ content = node_data.get('content', '')++ if script_type == 'bash':+ import subprocess+ try:+ res = subprocess.run(content, shell=True, capture_output=True, text=True)+ return {+ 'success': res.returncode == 0,+ 'stdout': res.stdout,+ 'stderr': res.stderr,+ 'returncode': res.returncode+ }+ except Exception as e:+ return {'success': False, 'error': str(e)}++ return {'success': False, 'error': f"Unsupported script language: {script_type}"}++ elif node_type == 'logic_if':+ condition = node_data.get('condition', '')+ # TODO: Evaluate condition using context/results+ return {'success': True, 'branch': 'true'} # Dummy++ return {'success': True, 'message': f"Node type {node_type} not implemented yet"}++ @staticmethod+ def log(execution_id: int, message: str, level: str = 'INFO', node_id: str = None):+ """Add a log entry for an execution."""+ log = WorkflowLog(+ execution_id=execution_id,+ level=level,+ message=message,+ node_id=node_id+ )+ db.session.add(log)+ db.session.commit()+ # Also print to stdout for debugging+ print(f"[{level}] Workflow {execution_id}: {message}")diff --git a/backend/requirements.txt b/backend/requirements.txtindex e15ea80f..f62015c1 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -40,6 +40,7 @@ Flask-Limiter==3.5.0click==8.1.7schedule==1.2.2+croniter==6.0.0passlib==1.7.4bcrypt==4.2.1diff --git a/frontend/src/components/workflow/WorkflowExecutionHistory.jsx b/frontend/src/components/workflow/WorkflowExecutionHistory.jsxnew file mode 100644index 00000000..1b03c1d1--- /dev/null+++ b/frontend/src/components/workflow/WorkflowExecutionHistory.jsx@@ -0,0 +1,174 @@+import React, { useState, useEffect, useCallback } from 'react';+import { X, Clock, CheckCircle, XCircle, Loader2, List, FileText, RefreshCw, Activity } from 'lucide-react';+import api from '../../services/api';++const WorkflowExecutionHistory = ({ workflowId, onClose }) => {+ const [executions, setExecutions] = useState([]);+ const [selectedExecution, setSelectedExecution] = useState(null);+ const [logs, setLogs] = useState([]);+ const [isLoading, setIsLoading] = useState(true);+ const [isLogsLoading, setIsLogsLoading] = useState(false);++ const fetchExecutions = useCallback(async () => {+ setIsLoading(true);+ try {+ const response = await api.getWorkflowExecutions(workflowId);+ setExecutions(response.executions || []);+ } catch (error) {+ console.error('Failed to fetch executions:', error);+ } finally {+ setIsLoading(false);+ }+ }, [workflowId]);++ const fetchLogs = useCallback(async (executionId) => {+ setIsLogsLoading(true);+ try {+ const response = await api.getWorkflowExecutionLogs(executionId);+ setLogs(response.logs || []);+ } catch (error) {+ console.error('Failed to fetch logs:', error);+ } finally {+ setIsLogsLoading(false);+ }+ }, []);++ useEffect(() => {+ fetchExecutions();+ }, [fetchExecutions]);++ useEffect(() => {+ if (selectedExecution) {+ fetchLogs(selectedExecution.id);+ }+ }, [selectedExecution, fetchLogs]);++ const getStatusIcon = (status) => {+ switch (status) {+ case 'success': return <CheckCircle size={16} className="text-green-500" />;+ case 'failed': return <XCircle size={16} className="text-red-500" />;+ case 'running': return <Loader2 size={16} className="text-blue-500 animate-spin" />;+ default: return <Clock size={16} className="text-gray-500" />;+ }+ };++ return (+ <div className="modal-overlay">+ <div className="modal-content max-w-4xl w-full h-[80vh] flex flex-col p-0 overflow-hidden">+ <div className="modal-header p-4 border-b border-gray-700 flex justify-between items-center bg-gray-800/50">+ <div className="flex items-center gap-2">+ <Activity size={20} className="text-blue-400" />+ <h2 className="text-lg font-semibold">Execution History</h2>+ </div>+ <div className="flex items-center gap-4">+ <button+ onClick={fetchExecutions}+ className="p-1.5 hover:bg-gray-700 rounded transition-colors text-gray-400 hover:text-white"+ title="Refresh"+ >+ <RefreshCw size={18} />+ </button>+ <button onClick={onClose} className="p-1 hover:bg-gray-700 rounded transition-colors">+ <X size={20} />+ </button>+ </div>+ </div>++ <div className="flex-1 flex overflow-hidden">+ {/* Executions List */}+ <div className="w-1/3 border-r border-gray-700 overflow-y-auto bg-gray-900/30">+ {isLoading ? (+ <div className="p-8 flex justify-center"><Loader2 className="animate-spin text-gray-500" /></div>+ ) : executions.length === 0 ? (+ <div className="p-8 text-center text-gray-500 text-sm">No executions found</div>+ ) : (+ <div className="divide-y divide-gray-800">+ {executions.map((exec) => (+ <div+ key={exec.id}+ className={`p-3 cursor-pointer transition-colors hover:bg-gray-800/50 ${selectedExecution?.id === exec.id ? 'bg-blue-900/20 border-l-2 border-blue-500' : ''}`}+ onClick={() => setSelectedExecution(exec)}+ >+ <div className="flex justify-between items-center mb-1">+ <span className="text-xs font-mono text-gray-400">#{exec.id}</span>+ {getStatusIcon(exec.status)}+ </div>+ <div className="text-sm font-medium">{exec.trigger_type} trigger</div>+ <div className="text-[10px] text-gray-500 mt-1 flex items-center gap-1">+ <Clock size={10} />+ {new Date(exec.started_at).toLocaleString()}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Execution Details & Logs */}+ <div className="flex-1 flex flex-col overflow-hidden bg-gray-900/50">+ {selectedExecution ? (+ <>+ <div className="p-4 border-b border-gray-800 flex justify-between items-center">+ <div>+ <h3 className="text-sm font-semibold flex items-center gap-2">+ Execution Details #{selectedExecution.id}+ <span className={`text-[10px] px-1.5 py-0.5 rounded uppercase font-bold ${+ selectedExecution.status === 'success' ? 'bg-green-900/30 text-green-400 border border-green-500/30' :+ selectedExecution.status === 'failed' ? 'bg-red-900/30 text-red-400 border border-red-500/30' :+ 'bg-blue-900/30 text-blue-400 border border-blue-500/30'+ }`}>+ {selectedExecution.status}+ </span>+ </h3>+ <div className="text-[10px] text-gray-500 mt-1">+ Duration: {selectedExecution.duration ? `${selectedExecution.duration.toFixed(2)}s` : 'N/A'}+ </div>+ </div>+ </div>++ <div className="flex-1 overflow-y-auto p-4 font-mono text-xs">+ <div className="flex items-center gap-2 text-gray-400 mb-4 border-b border-gray-800 pb-2">+ <FileText size={14} />+ <span>Execution Logs</span>+ </div>++ {isLogsLoading ? (+ <div className="flex justify-center p-8"><Loader2 className="animate-spin text-gray-500" /></div>+ ) : logs.length === 0 ? (+ <div className="text-gray-600 italic">No logs available for this execution.</div>+ ) : (+ <div className="space-y-1">+ {logs.map((log) => (+ <div key={log.id} className="flex gap-3 py-0.5 hover:bg-white/5 px-1 rounded transition-colors">+ <span className="text-gray-600 shrink-0">[{new Date(log.timestamp).toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}]</span>+ <span className={`shrink-0 w-12 font-bold ${+ log.level === 'ERROR' ? 'text-red-400' :+ log.level === 'WARNING' ? 'text-yellow-400' :+ log.level === 'DEBUG' ? 'text-gray-500' : 'text-blue-400'+ }`}>+ {log.level}+ </span>+ {log.node_id && (+ <span className="text-indigo-400 shrink-0">[{log.node_id}]</span>+ )}+ <span className="text-gray-300 break-all">{log.message}</span>+ </div>+ ))}+ </div>+ )}+ </div>+ </>+ ) : (+ <div className="flex-1 flex flex-col items-center justify-center text-gray-600">+ <Activity size={48} className="mb-4 opacity-20" />+ <p>Select an execution to view details and logs</p>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+};++export default WorkflowExecutionHistory;diff --git a/frontend/src/components/workflow/nodes/LogicIfNode.jsx b/frontend/src/components/workflow/nodes/LogicIfNode.jsxnew file mode 100644index 00000000..27a5354f--- /dev/null+++ b/frontend/src/components/workflow/nodes/LogicIfNode.jsx@@ -0,0 +1,54 @@+import React, { memo } from 'react';+import { Handle, Position } from '@xyflow/react';+import { GitBranch, Check, X } from 'lucide-react';++const LogicIfNode = ({ data, selected }) => {+ const {+ condition = '',+ label = 'If/Else'+ } = data;++ return (+ <div className={`workflow-node node-logic ${selected ? 'node-selected' : ''}`}>+ <Handle+ type="target"+ position={Position.Top}+ id="input"+ className="handle-input"+ />++ <div className="node-icon bg-gray-800">+ <GitBranch size={16} className="text-orange-400" />+ </div>+ <div className="node-content">+ <div className="node-label">{label}</div>+ <div className="node-sublabel">+ {condition || 'No condition'}+ </div>+ </div>++ <div className="node-outputs flex justify-around w-full mt-2 border-t border-gray-700 pt-2">+ <div className="flex flex-col items-center">+ <span className="text-[10px] text-green-400 font-bold mb-1">TRUE</span>+ <Handle+ type="source"+ position={Position.Bottom}+ id="true"+ className="handle-output handle-true !left-[25%]"+ />+ </div>+ <div className="flex flex-col items-center">+ <span className="text-[10px] text-red-400 font-bold mb-1">FALSE</span>+ <Handle+ type="source"+ position={Position.Bottom}+ id="false"+ className="handle-output handle-false !left-[75%]"+ />+ </div>+ </div>+ </div>+ );+};++export default memo(LogicIfNode);diff --git a/frontend/src/components/workflow/nodes/NotificationNode.jsx b/frontend/src/components/workflow/nodes/NotificationNode.jsxnew file mode 100644index 00000000..452ac96c--- /dev/null+++ b/frontend/src/components/workflow/nodes/NotificationNode.jsx@@ -0,0 +1,50 @@+import React, { memo } from 'react';+import { Handle, Position } from '@xyflow/react';+import { Bell, MessageSquare, Mail, Slack } from 'lucide-react';++const NotificationNode = ({ data, selected }) => {+ const {+ channel = 'discord',+ label = 'Notify',+ message = ''+ } = data;++ const getIcon = () => {+ switch (channel) {+ case 'discord': return <MessageSquare size={16} className="text-indigo-400" />;+ case 'slack': return <Slack size={16} className="text-pink-400" />;+ case 'email': return <Mail size={16} className="text-blue-400" />;+ default: return <Bell size={16} className="text-gray-400" />;+ }+ };++ return (+ <div className={`workflow-node node-notification ${selected ? 'node-selected' : ''}`}>+ <Handle+ type="target"+ position={Position.Top}+ id="input"+ className="handle-input"+ />++ <div className="node-icon bg-gray-800">+ {getIcon()}+ </div>+ <div className="node-content">+ <div className="node-label">{label}</div>+ <div className="node-sublabel">+ {channel.charAt(0).toUpperCase() + channel.slice(1)}+ </div>+ </div>++ <Handle+ type="source"+ position={Position.Bottom}+ id="output"+ className="handle-output"+ />+ </div>+ );+};++export default memo(NotificationNode);diff --git a/frontend/src/components/workflow/nodes/ScriptNode.jsx b/frontend/src/components/workflow/nodes/ScriptNode.jsxnew file mode 100644index 00000000..896b4357--- /dev/null+++ b/frontend/src/components/workflow/nodes/ScriptNode.jsx@@ -0,0 +1,49 @@+import React, { memo } from 'react';+import { Handle, Position } from '@xyflow/react';+import { Terminal, Code, Cpu } from 'lucide-react';++const ScriptNode = ({ data, selected }) => {+ const {+ language = 'bash',+ label = 'Run Script',+ content = ''+ } = data;++ const getIcon = () => {+ switch (language) {+ case 'bash': return <Terminal size={16} className="text-gray-400" />;+ case 'python': return <Code size={16} className="text-blue-300" />;+ default: return <Cpu size={16} className="text-gray-400" />;+ }+ };++ return (+ <div className={`workflow-node node-script ${selected ? 'node-selected' : ''}`}>+ <Handle+ type="target"+ position={Position.Top}+ id="input"+ className="handle-input"+ />++ <div className="node-icon bg-gray-800">+ {getIcon()}+ </div>+ <div className="node-content">+ <div className="node-label">{label}</div>+ <div className="node-sublabel">+ {language.charAt(0).toUpperCase() + language.slice(1)}+ </div>+ </div>++ <Handle+ type="source"+ position={Position.Bottom}+ id="output"+ className="handle-output"+ />+ </div>+ );+};++export default memo(ScriptNode);diff --git a/frontend/src/components/workflow/nodes/TriggerNode.jsx b/frontend/src/components/workflow/nodes/TriggerNode.jsxnew file mode 100644index 00000000..5247ca64--- /dev/null+++ b/frontend/src/components/workflow/nodes/TriggerNode.jsx@@ -0,0 +1,54 @@+import React, { memo } from 'react';+import { Handle, Position } from '@xyflow/react';+import { Zap, Clock, Webhook, Activity, Play } from 'lucide-react';++const TriggerNode = ({ data, selected }) => {+ const {+ triggerType = 'manual',+ label = 'Trigger',+ isActive = false,+ lastRunAt = null,+ lastStatus = null+ } = data;++ const getIcon = () => {+ switch (triggerType) {+ case 'manual': return <Play size={16} className="text-blue-400" />;+ case 'cron': return <Clock size={16} className="text-purple-400" />;+ case 'webhook': return <Webhook size={16} className="text-green-400" />;+ case 'event': return <Zap size={16} className="text-yellow-400" />;+ default: return <Activity size={16} className="text-gray-400" />;+ }+ };++ const getStatusColor = () => {+ if (!isActive) return 'border-gray-600';+ if (lastStatus === 'success') return 'border-green-500 shadow-[0_0_10px_rgba(34,197,94,0.3)]';+ if (lastStatus === 'failed') return 'border-red-500 shadow-[0_0_10px_rgba(239,68,68,0.3)]';+ return 'border-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.3)]';+ };++ return (+ <div className={`workflow-node node-trigger ${selected ? 'node-selected' : ''} ${getStatusColor()}`}>+ <div className="node-icon bg-gray-800">+ {getIcon()}+ </div>+ <div className="node-content">+ <div className="node-label">{label}</div>+ <div className="node-sublabel">+ {triggerType.charAt(0).toUpperCase() + triggerType.slice(1)}+ {isActive ? ' • Active' : ' • Disabled'}+ </div>+ </div>++ <Handle+ type="source"+ position={Position.Bottom}+ id="output"+ className="handle-output"+ />+ </div>+ );+};++export default memo(TriggerNode);diff --git a/frontend/src/components/workflow/panels/LogicIfConfigPanel.jsx b/frontend/src/components/workflow/panels/LogicIfConfigPanel.jsxnew file mode 100644index 00000000..fe7525ed--- /dev/null+++ b/frontend/src/components/workflow/panels/LogicIfConfigPanel.jsx@@ -0,0 +1,59 @@+import React from 'react';+import { X, GitBranch } from 'lucide-react';++const LogicIfConfigPanel = ({ node, onChange, onClose }) => {+ const { data } = node;+ const { condition = '', label = 'If/Else' } = data;++ return (+ <div className="config-panel">+ <div className="panel-header">+ <h3>Logic Configuration</h3>+ <button onClick={onClose}><X size={18} /></button>+ </div>++ <div className="panel-body">+ <div className="form-group">+ <label>Node Label</label>+ <input+ type="text"+ value={label}+ onChange={(e) => onChange({ ...data, label: e.target.value })}+ />+ </div>++ <div className="form-group">+ <label>Condition (Python expression)</label>+ <input+ type="text"+ className="font-mono text-xs bg-gray-900 border-gray-700 rounded p-2 focus:border-blue-500 focus:outline-none"+ value={condition}+ onChange={(e) => onChange({ ...data, condition: e.target.value })}+ placeholder="e.g. results['node_1']['returncode'] == 0"+ />+ </div>++ <div className="mt-4 p-3 bg-gray-800 rounded border border-gray-700">+ <p className="text-[10px] text-gray-400">+ <strong>Available Variables:</strong><br />+ <code>results</code>: Dictionary of previous node outputs<br />+ <code>context</code>: Trigger execution context+ </p>+ </div>++ <div className="mt-4 space-y-2">+ <div className="flex items-center gap-2 text-xs">+ <div className="w-2 h-2 rounded-full bg-green-500"></div>+ <span className="text-gray-300">True branch connects to "TRUE" handle</span>+ </div>+ <div className="flex items-center gap-2 text-xs">+ <div className="w-2 h-2 rounded-full bg-red-500"></div>+ <span className="text-gray-300">False branch connects to "FALSE" handle</span>+ </div>+ </div>+ </div>+ </div>+ );+};++export default LogicIfConfigPanel;diff --git a/frontend/src/components/workflow/panels/NotificationConfigPanel.jsx b/frontend/src/components/workflow/panels/NotificationConfigPanel.jsxnew file mode 100644index 00000000..04e7ccfc--- /dev/null+++ b/frontend/src/components/workflow/panels/NotificationConfigPanel.jsx@@ -0,0 +1,80 @@+import React from 'react';+import { X, MessageSquare, Mail, Slack, Bell } from 'lucide-react';++const NotificationConfigPanel = ({ node, onChange, onClose }) => {+ const { data } = node;+ const { channel = 'discord', label = 'Notify', message = '' } = data;++ return (+ <div className="config-panel">+ <div className="panel-header">+ <h3>Notification Configuration</h3>+ <button onClick={onClose}><X size={18} /></button>+ </div>++ <div className="panel-body">+ <div className="form-group">+ <label>Node Label</label>+ <input+ type="text"+ value={label}+ onChange={(e) => onChange({ ...data, label: e.target.value })}+ />+ </div>++ <div className="form-group">+ <label>Channel</label>+ <div className="grid grid-cols-2 gap-2">+ <button+ className={`p-2 rounded border flex items-center justify-center gap-2 transition-colors ${channel === 'discord' ? 'bg-indigo-900/30 border-indigo-500 text-indigo-400' : 'bg-gray-800 border-gray-700 text-gray-400'}`}+ onClick={() => onChange({ ...data, channel: 'discord' })}+ >+ <MessageSquare size={14} />+ <span className="text-xs">Discord</span>+ </button>+ <button+ className={`p-2 rounded border flex items-center justify-center gap-2 transition-colors ${channel === 'slack' ? 'bg-pink-900/30 border-pink-500 text-pink-400' : 'bg-gray-800 border-gray-700 text-gray-400'}`}+ onClick={() => onChange({ ...data, channel: 'slack' })}+ >+ <Slack size={14} />+ <span className="text-xs">Slack</span>+ </button>+ <button+ className={`p-2 rounded border flex items-center justify-center gap-2 transition-colors ${channel === 'email' ? 'bg-blue-900/30 border-blue-500 text-blue-400' : 'bg-gray-800 border-gray-700 text-gray-400'}`}+ onClick={() => onChange({ ...data, channel: 'email' })}+ >+ <Mail size={14} />+ <span className="text-xs">Email</span>+ </button>+ <button+ className={`p-2 rounded border flex items-center justify-center gap-2 transition-colors ${channel === 'system' ? 'bg-gray-700 border-gray-500 text-gray-200' : 'bg-gray-800 border-gray-700 text-gray-400'}`}+ onClick={() => onChange({ ...data, channel: 'system' })}+ >+ <Bell size={14} />+ <span className="text-xs">System</span>+ </button>+ </div>+ </div>++ <div className="form-group">+ <label>Message Template</label>+ <textarea+ className="text-xs bg-gray-900 border-gray-700 rounded p-2 h-48 focus:border-blue-500 focus:outline-none"+ value={message}+ onChange={(e) => onChange({ ...data, message: e.target.value })}+ placeholder="e.g. Workflow {{workflow_name}} failed on node {{failed_node_id}}"+ />+ </div>++ <div className="mt-4 p-3 bg-gray-800 rounded border border-gray-700">+ <p className="text-[10px] text-gray-400">+ <strong>Available Placeholders:</strong><br />+ <code>{{workflow_name}}</code>, <code>{{execution_id}}</code>, <code>{{started_at}}</code>, <code>{{node_id.output}}</code>+ </p>+ </div>+ </div>+ </div>+ );+};++export default NotificationConfigPanel;diff --git a/frontend/src/components/workflow/panels/ScriptConfigPanel.jsx b/frontend/src/components/workflow/panels/ScriptConfigPanel.jsxnew file mode 100644index 00000000..88111dab--- /dev/null+++ b/frontend/src/components/workflow/panels/ScriptConfigPanel.jsx@@ -0,0 +1,65 @@+import React from 'react';+import { X, Terminal, Code } from 'lucide-react';++const ScriptConfigPanel = ({ node, onChange, onClose }) => {+ const { data } = node;+ const { language = 'bash', label = 'Run Script', content = '' } = data;++ return (+ <div className="config-panel">+ <div className="panel-header">+ <h3>Script Configuration</h3>+ <button onClick={onClose}><X size={18} /></button>+ </div>++ <div className="panel-body">+ <div className="form-group">+ <label>Node Label</label>+ <input+ type="text"+ value={label}+ onChange={(e) => onChange({ ...data, label: e.target.value })}+ />+ </div>++ <div className="form-group">+ <label>Language</label>+ <div className="flex gap-2">+ <button+ className={`flex-1 p-2 rounded border flex items-center justify-center gap-2 ${language === 'bash' ? 'bg-gray-700 border-blue-500 text-blue-400' : 'bg-gray-800 border-gray-700 text-gray-400'}`}+ onClick={() => onChange({ ...data, language: 'bash' })}+ >+ <Terminal size={14} />+ <span>Bash</span>+ </button>+ <button+ className={`flex-1 p-2 rounded border flex items-center justify-center gap-2 ${language === 'python' ? 'bg-gray-700 border-blue-500 text-blue-400' : 'bg-gray-800 border-gray-700 text-gray-400'}`}+ onClick={() => onChange({ ...data, language: 'python' })}+ >+ <Code size={14} />+ <span>Python</span>+ </button>+ </div>+ </div>++ <div className="form-group">+ <label>Script Content</label>+ <textarea+ className="font-mono text-xs bg-gray-900 border-gray-700 rounded p-2 h-64 focus:border-blue-500 focus:outline-none"+ value={content}+ onChange={(e) => onChange({ ...data, content: e.target.value })}+ placeholder={language === 'bash' ? "#!/bin/bash\necho 'Hello World'" : "print('Hello World')"}+ />+ </div>++ <div className="mt-4 p-3 bg-blue-900/20 rounded border border-blue-500/30">+ <p className="text-[10px] text-blue-300">+ <strong>Environment Variables:</strong> You can use <code>$NODE_ID_OUTPUT</code> to access results from previous nodes.+ </p>+ </div>+ </div>+ </div>+ );+};++export default ScriptConfigPanel;diff --git a/frontend/src/components/workflow/panels/TriggerConfigPanel.jsx b/frontend/src/components/workflow/panels/TriggerConfigPanel.jsxnew file mode 100644index 00000000..24d4c06f--- /dev/null+++ b/frontend/src/components/workflow/panels/TriggerConfigPanel.jsx@@ -0,0 +1,129 @@+import React from 'react';+import { X, Play, Clock, Webhook, Activity, Zap } from 'lucide-react';++const TriggerConfigPanel = ({ node, onChange, onClose }) => {+ const { data } = node;+ const { triggerType = 'manual', label = 'Trigger', triggerConfig = {} } = data;++ const handleTypeChange = (type) => {+ onChange({+ ...data,+ triggerType: type,+ label: `${type.charAt(0).toUpperCase() + type.slice(1)} Trigger`+ });+ };++ const handleConfigChange = (key, value) => {+ onChange({+ ...data,+ triggerConfig: {+ ...triggerConfig,+ [key]: value+ }+ });+ };++ return (+ <div className="config-panel">+ <div className="panel-header">+ <h3>Trigger Configuration</h3>+ <button onClick={onClose}><X size={18} /></button>+ </div>++ <div className="panel-body">+ <div className="form-group">+ <label>Node Label</label>+ <input+ type="text"+ value={label}+ onChange={(e) => onChange({ ...data, label: e.target.value })}+ />+ </div>++ <div className="form-group">+ <label>Trigger Type</label>+ <div className="trigger-type-grid grid grid-cols-2 gap-2 mt-2">+ <button+ className={`p-3 rounded-lg border flex flex-col items-center gap-2 transition-colors ${triggerType === 'manual' ? 'bg-blue-900/30 border-blue-500' : 'bg-gray-800 border-gray-700 hover:border-gray-500'}`}+ onClick={() => handleTypeChange('manual')}+ >+ <Play size={20} className={triggerType === 'manual' ? 'text-blue-400' : 'text-gray-400'} />+ <span className="text-xs">Manual</span>+ </button>+ <button+ className={`p-3 rounded-lg border flex flex-col items-center gap-2 transition-colors ${triggerType === 'cron' ? 'bg-purple-900/30 border-purple-500' : 'bg-gray-800 border-gray-700 hover:border-gray-500'}`}+ onClick={() => handleTypeChange('cron')}+ >+ <Clock size={20} className={triggerType === 'cron' ? 'text-purple-400' : 'text-gray-400'} />+ <span className="text-xs">Schedule</span>+ </button>+ <button+ className={`p-3 rounded-lg border flex flex-col items-center gap-2 transition-colors ${triggerType === 'webhook' ? 'bg-green-900/30 border-green-500' : 'bg-gray-800 border-gray-700 hover:border-gray-500'}`}+ onClick={() => handleTypeChange('webhook')}+ >+ <Webhook size={20} className={triggerType === 'webhook' ? 'text-green-400' : 'text-gray-400'} />+ <span className="text-xs">Webhook</span>+ </button>+ <button+ className={`p-3 rounded-lg border flex flex-col items-center gap-2 transition-colors ${triggerType === 'event' ? 'bg-yellow-900/30 border-yellow-500' : 'bg-gray-800 border-gray-700 hover:border-gray-500'}`}+ onClick={() => handleTypeChange('event')}+ >+ <Zap size={20} className={triggerType === 'event' ? 'text-yellow-400' : 'text-gray-400'} />+ <span className="text-xs">System Event</span>+ </button>+ </div>+ </div>++ {triggerType === 'cron' && (+ <div className="form-group animate-in fade-in slide-in-from-top-1">+ <label>Cron Expression</label>+ <input+ type="text"+ value={triggerConfig.cron || '0 * * * *'}+ onChange={(e) => handleConfigChange('cron', e.target.value)}+ placeholder="e.g. 0 0 * * *"+ />+ <p className="text-[10px] text-gray-500 mt-1">+ (Min Hour Day Month Week)+ </p>+ </div>+ )}++ {triggerType === 'webhook' && (+ <div className="form-group animate-in fade-in slide-in-from-top-1">+ <label>Webhook URL</label>+ <div className="flex gap-2">+ <input+ type="text"+ value={triggerConfig.webhookPath || `/hooks/${node.id}`}+ readOnly+ className="bg-gray-900 text-gray-400 cursor-not-allowed"+ />+ </div>+ <p className="text-[10px] text-gray-500 mt-1">+ Send POST requests to this endpoint to trigger the workflow.+ </p>+ </div>+ )}++ {triggerType === 'event' && (+ <div className="form-group animate-in fade-in slide-in-from-top-1">+ <label>System Event</label>+ <select+ value={triggerConfig.eventType || 'health_check_failed'}+ onChange={(e) => handleConfigChange('eventType', e.target.value)}+ >+ <option value="health_check_failed">Health Check Failed</option>+ <option value="high_cpu">High CPU Usage (>80%)</option>+ <option value="high_memory">High Memory Usage (>80%)</option>+ <option value="git_push">Git Push Received</option>+ <option value="app_stopped">Application Stopped</option>+ </select>+ </div>+ )}+ </div>+ </div>+ );+};++export default TriggerConfigPanel;diff --git a/frontend/src/pages/WorkflowBuilder.jsx b/frontend/src/pages/WorkflowBuilder.jsxindex 1dba9206..ad31b02c 100644--- a/frontend/src/pages/WorkflowBuilder.jsx+++ b/frontend/src/pages/WorkflowBuilder.jsx@@ -11,18 +11,27 @@ import {MiniMap} from '@xyflow/react';import '@xyflow/react/dist/style.css';-import { Server, Database, Globe, Box, Save, FolderOpen, Plus, RefreshCw, Play, Layout, Eye } from 'lucide-react';+import { Server, Database, Globe, Box, Save, FolderOpen, Plus, RefreshCw, Play, Layout, Eye, Bell, Terminal } from 'lucide-react';import api from '../services/api';import WorkflowListModal from '../components/workflow/WorkflowListModal';import DeploymentProgressModal from '../components/workflow/DeploymentProgressModal';+import WorkflowExecutionHistory from '../components/workflow/WorkflowExecutionHistory';import DockerAppNode from '../components/workflow/nodes/DockerAppNode';import DatabaseNode from '../components/workflow/nodes/DatabaseNode';import DomainNode from '../components/workflow/nodes/DomainNode';import ServiceNode from '../components/workflow/nodes/ServiceNode';+import TriggerNode from '../components/workflow/nodes/TriggerNode';+import ScriptNode from '../components/workflow/nodes/ScriptNode';+import NotificationNode from '../components/workflow/nodes/NotificationNode';+import LogicIfNode from '../components/workflow/nodes/LogicIfNode';import DockerAppConfigPanel from '../components/workflow/panels/DockerAppConfigPanel';import DatabaseConfigPanel from '../components/workflow/panels/DatabaseConfigPanel';import DomainConfigPanel from '../components/workflow/panels/DomainConfigPanel';import ServiceConfigPanel from '../components/workflow/panels/ServiceConfigPanel';+import TriggerConfigPanel from '../components/workflow/panels/TriggerConfigPanel';+import ScriptConfigPanel from '../components/workflow/panels/ScriptConfigPanel';+import NotificationConfigPanel from '../components/workflow/panels/NotificationConfigPanel';+import LogicIfConfigPanel from '../components/workflow/panels/LogicIfConfigPanel';import { isValidConnection as checkValidConnection, getConnectionError, getConnectionType } from '../utils/connectionRules';import ConnectionEdge from '../components/workflow/ConnectionEdge';@@ -33,14 +42,22 @@ const nodeTypes = {dockerApp: DockerAppNode,database: DatabaseNode,domain: DomainNode,- service: ServiceNode+ service: ServiceNode,+ trigger: TriggerNode,+ script: ScriptNode,+ notification: NotificationNode,+ logic_if: LogicIfNode};const nodeColorMap = {dockerApp: '#2496ed',database: '#f59e0b',domain: '#10b981',- service: '#6366f1'+ service: '#6366f1',+ trigger: '#3b82f6',+ script: '#6b7280',+ notification: '#8b5cf6',+ logic_if: '#f97316'};const edgeTypes = {@@ -128,6 +145,38 @@ const NodePalette = ({ onAddNode, templates, onAddFromTemplate, existingApps, on</button></div>+ <div className="palette-section">+ <div className="palette-header">Automation</div>+ <button+ className="palette-item palette-item-trigger"+ onClick={() => onAddNode('trigger', { label: 'Manual Trigger', triggerType: 'manual', isActive: true })}+ >+ <Play size={16} />+ <span>Trigger</span>+ </button>+ <button+ className="palette-item palette-item-logic"+ onClick={() => onAddNode('logic_if', { label: 'If/Else', condition: '' })}+ >+ <Layout size={16} />+ <span>Logic (If/Else)</span>+ </button>+ <button+ className="palette-item palette-item-script"+ onClick={() => onAddNode('script', { label: 'Run Script', language: 'bash', content: '' })}+ >+ <Terminal size={16} />+ <span>Script</span>+ </button>+ <button+ className="palette-item palette-item-notification"+ onClick={() => onAddNode('notification', { label: 'Notify', channel: 'discord', message: '' })}+ >+ <Bell size={16} />+ <span>Notification</span>+ </button>+ </div>+<div className="palette-section palette-section-info"><div className="palette-hint">Tip: Click "Server Overview" to see all your infrastructure with connections@@ -164,6 +213,11 @@ const WorkflowCanvas = () => {const [showDeployModal, setShowDeployModal] = useState(false);const [deploymentResults, setDeploymentResults] = useState(null);+ // Automation state+ const [isExecuting, setIsExecuting] = useState(false);+ const [showHistory, setShowHistory] = useState(false);+ const [executionId, setExecutionId] = useState(null);+const memoizedNodeTypes = useMemo(() => nodeTypes, []);const memoizedEdgeTypes = useMemo(() => edgeTypes, []);@@ -674,6 +728,32 @@ const WorkflowCanvas = () => {}}, [currentWorkflow, nodes, edges, workflowName, getViewport, setNodes]);+ // Execute workflow+ const executeWorkflow = useCallback(async () => {+ if (!currentWorkflow) {+ setSaveMessage('Save workflow first');+ setTimeout(() => setSaveMessage(null), 3000);+ return;+ }++ setIsExecuting(true);+ setSaveMessage('Executing...');++ try {+ const response = await api.executeWorkflow(currentWorkflow.id);+ setExecutionId(response.execution_id);+ setSaveMessage('Execution started');+ setShowHistory(true);+ setTimeout(() => setSaveMessage(null), 3000);+ } catch (error) {+ console.error('Failed to execute workflow:', error);+ setSaveMessage('Execution failed');+ setTimeout(() => setSaveMessage(null), 3000);+ } finally {+ setIsExecuting(false);+ }+ }, [currentWorkflow]);+const onConnect = useCallback((params) => {if (checkValidConnection(params, nodes)) {@@ -797,6 +877,14 @@ const WorkflowCanvas = () => {return <DomainConfigPanel {...panelProps} />;case 'service':return <ServiceConfigPanel {...panelProps} />;+ case 'trigger':+ return <TriggerConfigPanel {...panelProps} />;+ case 'script':+ return <ScriptConfigPanel {...panelProps} />;+ case 'notification':+ return <NotificationConfigPanel {...panelProps} />;+ case 'logic_if':+ return <LogicIfConfigPanel {...panelProps} />;default:return null;}@@ -843,6 +931,26 @@ const WorkflowCanvas = () => {<FolderOpen size={16} /><span>Load</span></button>+ <div className="toolbar-divider h-6 w-[1px] bg-gray-700 mx-1"></div>+ <button+ className={`toolbar-btn ${isExecuting ? 'animate-pulse' : ''}`}+ onClick={executeWorkflow}+ disabled={isExecuting || !currentWorkflow}+ title="Execute workflow manually"+ >+ <Play size={16} className="text-green-400" />+ <span>Execute</span>+ </button>+ <button+ className="toolbar-btn"+ onClick={() => setShowHistory(true)}+ disabled={!currentWorkflow}+ title="View execution history"+ >+ <Activity size={16} />+ <span>History</span>+ </button>+ <div className="toolbar-divider h-6 w-[1px] bg-gray-700 mx-1"></div><buttonclassName="toolbar-btn toolbar-btn-primary"onClick={saveWorkflow}@@ -927,6 +1035,12 @@ const WorkflowCanvas = () => {onClose={() => setShowDeployModal(false)}/>)}+ {showHistory && (+ <WorkflowExecutionHistory+ workflowId={currentWorkflow?.id}+ onClose={() => setShowHistory(false)}+ />+ )}</div>);};diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 3b6ccf18..384651b4 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -2562,6 +2562,25 @@ class ApiService {});}+ async executeWorkflow(id, context = {}) {+ return this.request(`/workflows/${id}/execute`, {+ method: 'POST',+ body: { context }+ });+ }++ async getWorkflowExecutions(id) {+ return this.request(`/workflows/${id}/executions`);+ }++ async getWorkflowExecutionDetails(executionId) {+ return this.request(`/workflows/executions/${executionId}`);+ }++ async getWorkflowExecutionLogs(executionId) {+ return this.request(`/workflows/executions/${executionId}/logs`);+ }+// ========================================// Servers (Multi-Server Management) endpoints// ========================================diff --git a/frontend/src/utils/connectionRules.js b/frontend/src/utils/connectionRules.jsindex abf34631..0f40fffc 100644--- a/frontend/src/utils/connectionRules.js+++ b/frontend/src/utils/connectionRules.js@@ -10,6 +10,14 @@*/// Connection rules matrix: [sourceType][sourceHandle] → [targetType][targetHandle]+const automationTargets = {+ dockerApp: ['input'],+ service: ['input'],+ script: ['input'],+ notification: ['input'],+ logic_if: ['input']+};+const connectionRules = {domain: {output: {@@ -33,6 +41,19 @@ const connectionRules = {service: ['input']}},+ trigger: {+ output: automationTargets+ },+ script: {+ output: automationTargets+ },+ notification: {+ output: automationTargets+ },+ logic_if: {+ true: automationTargets,+ false: automationTargets+ },database: {// Database has no source handles, cannot connect to anything}@@ -46,7 +67,14 @@ export const connectionLabels = {'dockerApp-database': 'Uses DB','service-dockerApp': 'Provides','service-database': 'Uses',- 'service-service': 'Connects to'+ 'service-service': 'Connects to',+ 'trigger-script': 'Triggers',+ 'trigger-notification': 'Triggers',+ 'trigger-dockerApp': 'Starts',+ 'script-script': 'Next',+ 'script-notification': 'Then notify',+ 'logic_if-script': 'If so',+ 'logic_if-notification': 'If so notify'};// Colors for connection types@@ -178,7 +206,11 @@ const formatNodeType = (type) => {dockerApp: 'Docker App',database: 'Database',domain: 'Domain',- service: 'Service'+ service: 'Service',+ trigger: 'Trigger',+ script: 'Script',+ notification: 'Notification',+ logic_if: 'Logic'};return labels[type] || type;};